mirror of
https://github.com/whoswhip/Spectrum.git
synced 2026-12-06 01:28:42 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c227396a3
|
||
|
|
5800221000 | ||
|
|
03596041d3 | ||
|
|
c4013a2adc | ||
|
|
181e234bb2
|
||
|
|
e2aaf54216
|
||
|
|
0fbc91fde4
|
||
|
|
d8a71f9d91
|
||
|
|
c4075c4894
|
||
|
|
07de8e3012
|
||
|
|
dce1f835f0
|
||
|
|
3ff7bee7c7 | ||
|
|
f89fd135b4
|
||
|
|
51744ca9c7
|
||
|
|
4b4cebd517
|
@@ -1,52 +1,15 @@
|
||||
# Spectrum
|
||||
Spectrum is a semi-universal colorbot that uses C# and OpenCV for image processing.
|
||||
|
||||
<img width="600" height="502" alt="Spectrum Menu" src="https://upld.zip/d9Z8Evjm.png" />
|
||||
## Features
|
||||
- Extensive configuration file
|
||||
- Dataset collection
|
||||
- Multiple mouse movement paths
|
||||
|
||||
## Configuration
|
||||
On first run, a default configuration file is created.
|
||||
### Parameters
|
||||
| Parameter | Range/Options | Default Value | Description |
|
||||
|---------------|-----------------------|---------------|---------------------------------|
|
||||
| `ImageWidth` | 1 - ScreenSize | 640 | Defines the width of the image |
|
||||
| `ImageHeight` | 1 - ScreenSize | 640 | Defines the height of the image|
|
||||
|
||||
| Parameter | Range/Options | Default Value | Description |
|
||||
|-------------------|---------------|---------------|---------------------------------|
|
||||
| `YOffsetPercent` | 0.0 - 1 | 0.8 | Sets the vertical offset |
|
||||
| `XOffsetPercent` | 0.0 - 1 | 0.5 | Sets the horizontal offset |
|
||||
|
||||
| Parameter | Range/Options | Default Value | Description |
|
||||
|--------------------|-------------------------------|---------------|---------------------------------------------------------|
|
||||
| `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 |
|
||||
|
||||
| Parameter | Range/Options | Default Value | Description |
|
||||
|-----------------------|---------------|---------------|---------------------------------|
|
||||
| `ShowDetectionWindow` | true or false | true | Displays the detection window |
|
||||
|
||||
| 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|
|
||||
|
||||
| Parameter | Sub-Parameter | Range/Options | Default Value | Description |
|
||||
|-------------|---------------|---------------|---------------|---------------------------------|
|
||||
| **UpperHSV**| `Val0` | 0 - 255 | 150 | Hue |
|
||||
| | `Val1` | 0 - 255 | 255 | Saturation |
|
||||
| | `Val2` | 0 - 255 | 229 | Value |
|
||||
| | `Val3` | 0 | 0 | |
|
||||
| **LowerHSV**| `Val0` | 0 - 255 | 150 | Hue |
|
||||
| | `Val1` | 0 - 255 | 255 | Saturation |
|
||||
| | `Val2` | 0 - 255 | 229 | Value |
|
||||
| | `Val3` | 0 | 0 | |
|
||||
- IMGui Menu
|
||||
- FOV Overlay
|
||||
- Detection Overlay
|
||||
- Triggerbot
|
||||
- Makcu Support
|
||||
|
||||
## Dataset Collection
|
||||
When `CollectData` and `AutoLabel` are enabled, Spectrum automatically generates:
|
||||
|
||||
+30
-1
@@ -96,12 +96,28 @@ namespace Spectrum
|
||||
QuadraticBezier,
|
||||
Adaptive
|
||||
}
|
||||
public enum MovementMethod
|
||||
{
|
||||
MouseEvent,
|
||||
Makcu
|
||||
}
|
||||
public enum FovType
|
||||
{
|
||||
Circle,
|
||||
Rectangle
|
||||
}
|
||||
public enum CaptureMethod
|
||||
{
|
||||
GDI,
|
||||
DirectX
|
||||
}
|
||||
public class ConfigData
|
||||
{
|
||||
|
||||
// Image settings
|
||||
public int ImageWidth { get; set; } = 640;
|
||||
public int ImageHeight { get; set; } = 640;
|
||||
public CaptureMethod CaptureMethod { get; set; } = CaptureMethod.DirectX;
|
||||
|
||||
// Offset settings
|
||||
public double YOffsetPercent { get; set; } = 0.8;
|
||||
@@ -116,12 +132,22 @@ namespace Spectrum
|
||||
public bool EmaSmoothening { get; set; } = true;
|
||||
public double EmaSmootheningFactor { get; set; } = 0.1;
|
||||
|
||||
public MovementMethod MovementMethod { get; set; } = MovementMethod.MouseEvent;
|
||||
|
||||
// Triggerbot settings
|
||||
public bool TriggerBot { get; set; } = false;
|
||||
public Keys TriggerKey { get; set; } = Keys.XButton2;
|
||||
public int TriggerDelay { get; set; } = 50; // milliseconds
|
||||
public int TriggerRadius { get; set; } = 15; // pixels
|
||||
public int TriggerDuration { get; set; } = 100; // milliseconds
|
||||
|
||||
// Display settings
|
||||
public bool 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 Keys MenuKey { get; set; } = Keys.Insert;
|
||||
public bool DrawFOV { get; set; } = false;
|
||||
public FovType FOVType { get; set; } = FovType.Rectangle;
|
||||
public Vector4 FOVColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
||||
|
||||
// Data collection settings
|
||||
@@ -133,6 +159,9 @@ namespace Spectrum
|
||||
public Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229);
|
||||
public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229);
|
||||
public string SelectedColor { get; set; } = "Arsenal [Magenta]";
|
||||
|
||||
// Misc
|
||||
public bool DebugMode { get; set; } = false;
|
||||
}
|
||||
public class ColorData
|
||||
{
|
||||
|
||||
@@ -3,7 +3,7 @@ using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||
|
||||
namespace Spectrum
|
||||
namespace Spectrum.Detection
|
||||
{
|
||||
public static class AutoLabeling
|
||||
{
|
||||
@@ -15,6 +15,7 @@ namespace Spectrum
|
||||
private static readonly ConcurrentQueue<LabelingData> labelingQueue = new ConcurrentQueue<LabelingData>();
|
||||
private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new ConcurrentQueue<BackgroundImageData>();
|
||||
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||
public static bool Started = false;
|
||||
|
||||
private static List<YoloBoundingBox> GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight)
|
||||
{
|
||||
@@ -49,6 +50,9 @@ namespace Spectrum
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
|
||||
var labelContent = new StringBuilder();
|
||||
foreach (var box in boundingBoxes)
|
||||
{
|
||||
@@ -56,15 +60,17 @@ namespace Spectrum
|
||||
}
|
||||
File.WriteAllText(path, labelContent.ToString());
|
||||
}
|
||||
catch
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log("[ERROR] Failed to save labels.", LogLevel.Error);
|
||||
LogManager.Log($"[ERROR] Failed to save labels. Error: {ex.Message}", LogLevel.Error);
|
||||
}
|
||||
}
|
||||
private static void SaveMatAsImage(Mat mat, string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(Path.GetDirectoryName(path)))
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||
Cv2.ImWrite(path, mat);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -108,6 +114,8 @@ namespace Spectrum
|
||||
|
||||
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
|
||||
{
|
||||
|
||||
LogManager.Log($"Adding {filteredContours.Length} contours to labeling queue.", LogLevel.Debug);
|
||||
if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0)
|
||||
return;
|
||||
|
||||
@@ -125,9 +133,6 @@ namespace Spectrum
|
||||
|
||||
public static void AddBackgroundImage(Mat mat, bool detected)
|
||||
{
|
||||
if (!mainConfig.Data.AutoLabel)
|
||||
return;
|
||||
|
||||
detectionAttemps++;
|
||||
|
||||
if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected)
|
||||
@@ -159,8 +164,8 @@ namespace Spectrum
|
||||
string imageFileName = $"image_{imageCount:D6}.jpg";
|
||||
string labelFileName = $"image_{imageCount:D6}.txt";
|
||||
|
||||
string imagePath = Path.Combine("dataset/images", imageFileName);
|
||||
string labelPath = Path.Combine("dataset/labels", labelFileName);
|
||||
string imagePath = Path.Combine("bin/dataset/images", imageFileName);
|
||||
string labelPath = Path.Combine("bin/dataset/labels", labelFileName);
|
||||
|
||||
SaveMatAsImage(data.Mat, imagePath);
|
||||
|
||||
@@ -184,7 +189,7 @@ namespace Spectrum
|
||||
lock (lockObject)
|
||||
{
|
||||
string imageFileName = $"image_{imageCount:D6}.jpg";
|
||||
string imagePath = Path.Combine("dataset/images", imageFileName);
|
||||
string imagePath = Path.Combine("bin/dataset/images", imageFileName);
|
||||
|
||||
SaveMatAsImage(data.Mat, imagePath);
|
||||
|
||||
@@ -202,6 +207,8 @@ namespace Spectrum
|
||||
{
|
||||
if (cancellationTokenSource != null)
|
||||
return;
|
||||
LogManager.Log("Starting auto labeling...", LogLevel.Info);
|
||||
Started = true;
|
||||
cancellationTokenSource = new CancellationTokenSource();
|
||||
backgroundTask = Task.Run(() => LabelingLoop(cancellationTokenSource.Token));
|
||||
}
|
||||
@@ -209,6 +216,9 @@ namespace Spectrum
|
||||
{
|
||||
if (cancellationTokenSource == null)
|
||||
return;
|
||||
|
||||
LogManager.Log("Stopping auto labeling...", LogLevel.Info);
|
||||
Started = false;
|
||||
cancellationTokenSource.Cancel();
|
||||
backgroundTask?.Wait();
|
||||
cancellationTokenSource.Dispose();
|
||||
@@ -0,0 +1,225 @@
|
||||
using System.Drawing.Imaging;
|
||||
using Vortice.Direct3D;
|
||||
using Vortice.Direct3D11;
|
||||
using Vortice.DXGI;
|
||||
using Size = System.Drawing.Size;
|
||||
using Rectangle = System.Drawing.Rectangle;
|
||||
using Point = System.Drawing.Point;
|
||||
|
||||
namespace Spectrum.Detection
|
||||
{
|
||||
public class CaptureManager : IDisposable
|
||||
{
|
||||
private readonly object _sync = new();
|
||||
private ID3D11Device? _device;
|
||||
private ID3D11DeviceContext? _context;
|
||||
private IDXGIOutputDuplication? _duplication;
|
||||
private ID3D11Texture2D? _stagingTex;
|
||||
private Size _desktopSize;
|
||||
public bool IsDirectXAvailable { get; private set; }
|
||||
public bool IsInitialized => _device != null && _duplication != null && _stagingTex != null;
|
||||
|
||||
public bool TryInitialize(int adapterIndex = 0, int outputIndex = 0)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
try
|
||||
{
|
||||
DisposeDxgiResources();
|
||||
|
||||
using var factory = DXGI.CreateDXGIFactory1<IDXGIFactory1>();
|
||||
if (factory.EnumAdapters1(adapterIndex, out var adapter).Failure)
|
||||
return false;
|
||||
if (adapter.EnumOutputs(outputIndex, out var output).Failure)
|
||||
{
|
||||
adapter.Dispose();
|
||||
return false;
|
||||
}
|
||||
|
||||
var hr = D3D11.D3D11CreateDevice(
|
||||
adapter,
|
||||
DriverType.Unknown,
|
||||
DeviceCreationFlags.BgraSupport,
|
||||
new[]
|
||||
{
|
||||
FeatureLevel.Level_12_1,
|
||||
FeatureLevel.Level_12_0,
|
||||
FeatureLevel.Level_11_1,
|
||||
FeatureLevel.Level_11_0
|
||||
},
|
||||
out _device);
|
||||
|
||||
if (hr.Failure || _device == null)
|
||||
{
|
||||
output.Dispose();
|
||||
adapter.Dispose();
|
||||
return false;
|
||||
}
|
||||
|
||||
_context = _device.ImmediateContext;
|
||||
|
||||
_duplication = output.QueryInterface<IDXGIOutput1>().DuplicateOutput(_device);
|
||||
var desc = output.Description;
|
||||
_desktopSize = new Size(desc.DesktopCoordinates.Right - desc.DesktopCoordinates.Left,
|
||||
desc.DesktopCoordinates.Bottom - desc.DesktopCoordinates.Top);
|
||||
|
||||
output.Dispose();
|
||||
adapter.Dispose();
|
||||
|
||||
EnsureStagingTexture(_desktopSize);
|
||||
|
||||
IsDirectXAvailable = true;
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
IsDirectXAvailable = false;
|
||||
DisposeDxgiResources();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Bitmap? CaptureScreenshotDirectX(Rectangle bounds)
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
if (!IsInitialized)
|
||||
{
|
||||
if (!TryInitialize())
|
||||
return null;
|
||||
}
|
||||
|
||||
bounds = Rectangle.Intersect(new Rectangle(Point.Empty, _desktopSize), bounds);
|
||||
if (bounds.Width <= 0 || bounds.Height <= 0) return null;
|
||||
|
||||
EnsureStagingTexture(_desktopSize);
|
||||
|
||||
IDXGIResource? desktopResource = null;
|
||||
bool frameAcquired = false;
|
||||
try
|
||||
{
|
||||
var result = _duplication!.AcquireNextFrame(16, out var frameInfo, out desktopResource);
|
||||
if (result.Failure)
|
||||
{
|
||||
if (result.Code == unchecked((int)Vortice.DXGI.ResultCode.AccessLost) ||
|
||||
result.Code == unchecked((int)Vortice.DXGI.ResultCode.DeviceRemoved))
|
||||
{
|
||||
TryInitialize();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
frameAcquired = true;
|
||||
|
||||
using var fullTex = desktopResource.QueryInterface<ID3D11Texture2D>();
|
||||
|
||||
_context!.CopySubresourceRegion(
|
||||
_stagingTex!,
|
||||
0,
|
||||
bounds.X,
|
||||
bounds.Y,
|
||||
0,
|
||||
fullTex,
|
||||
0,
|
||||
new Vortice.Mathematics.Box(bounds.X, bounds.Y, 0, bounds.Right, bounds.Bottom, 1)
|
||||
);
|
||||
|
||||
var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
||||
var map = _context.Map(_stagingTex!, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None);
|
||||
var bmpData = bmp.LockBits(new Rectangle(0, 0, bounds.Width, bounds.Height),
|
||||
ImageLockMode.WriteOnly,
|
||||
PixelFormat.Format32bppArgb);
|
||||
|
||||
try
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
byte* srcBase = (byte*)map.DataPointer + bounds.Y * map.RowPitch + bounds.X * 4;
|
||||
int srcStride = map.RowPitch;
|
||||
int dstStride = bmpData.Stride;
|
||||
int rowBytes = bounds.Width * 4;
|
||||
|
||||
byte* dst = (byte*)bmpData.Scan0;
|
||||
byte* src = srcBase;
|
||||
for (int y = 0; y < bounds.Height; y++)
|
||||
{
|
||||
Buffer.MemoryCopy(src, dst, rowBytes, rowBytes);
|
||||
src += srcStride;
|
||||
dst += dstStride;
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
bmp.UnlockBits(bmpData);
|
||||
_context.Unmap(_stagingTex!, 0);
|
||||
}
|
||||
|
||||
return bmp;
|
||||
}
|
||||
finally
|
||||
{
|
||||
desktopResource?.Dispose();
|
||||
if (frameAcquired)
|
||||
{
|
||||
try { _duplication?.ReleaseFrame(); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void EnsureStagingTexture(Size desktopSize)
|
||||
{
|
||||
if (_device == null) return;
|
||||
if (_stagingTex != null &&
|
||||
_stagingTex.Description.Width == desktopSize.Width &&
|
||||
_stagingTex.Description.Height == desktopSize.Height)
|
||||
return;
|
||||
|
||||
_stagingTex?.Dispose();
|
||||
_stagingTex = _device.CreateTexture2D(new Texture2DDescription
|
||||
{
|
||||
Width = desktopSize.Width,
|
||||
Height = desktopSize.Height,
|
||||
MipLevels = 1,
|
||||
ArraySize = 1,
|
||||
Format = Format.B8G8R8A8_UNorm,
|
||||
SampleDescription = new(1, 0),
|
||||
Usage = ResourceUsage.Staging,
|
||||
CPUAccessFlags = CpuAccessFlags.Read,
|
||||
BindFlags = BindFlags.None
|
||||
});
|
||||
}
|
||||
|
||||
public Bitmap? CaptureScreenshotGdi(Rectangle bounds)
|
||||
{
|
||||
var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
||||
using var g = Graphics.FromImage(bmp);
|
||||
g.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size, CopyPixelOperation.SourceCopy);
|
||||
return bmp;
|
||||
}
|
||||
public bool TryInitializeDirectX(int adapterIndex = 0, int outputIndex = 0) => TryInitialize(adapterIndex, outputIndex);
|
||||
|
||||
private void DisposeDxgiResources()
|
||||
{
|
||||
_duplication?.Dispose();
|
||||
_stagingTex?.Dispose();
|
||||
_context?.Dispose();
|
||||
_device?.Dispose();
|
||||
_duplication = null;
|
||||
_stagingTex = null;
|
||||
_context = null;
|
||||
_device = null;
|
||||
IsDirectXAvailable = false;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_sync)
|
||||
{
|
||||
DisposeDxgiResources();
|
||||
}
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
using OpenCvSharp;
|
||||
using Spectrum.Input;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace Spectrum.Detection
|
||||
{
|
||||
class DetectionManager
|
||||
{
|
||||
private long iterationCount = 0;
|
||||
private long totalTime = 0;
|
||||
private Stopwatch stopwatch = new Stopwatch();
|
||||
private Rectangle bounds = new Rectangle(0, 0, 0, 0);
|
||||
private (int Width, int Height) screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||
private ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||
private Renderer? renderer;
|
||||
private Thread? _detectionThread;
|
||||
private DateTime lastMenuToggle = DateTime.MinValue;
|
||||
private readonly CaptureManager _captureManager;
|
||||
|
||||
public DetectionManager(Renderer renderer)
|
||||
{
|
||||
this.renderer = renderer;
|
||||
_captureManager = Program.SharedCaptureManager;
|
||||
_detectionThread = new Thread(DetectionLoop)
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "Spectrum Detection Thread",
|
||||
Priority = ThreadPriority.AboveNormal
|
||||
};
|
||||
_detectionThread.Start();
|
||||
}
|
||||
|
||||
private void DetectionLoop()
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (InputManager.IsKeyOrMouseDown(mainConfig.Data.Keybind) || InputManager.IsKeyOrMouseDown(mainConfig.Data.TriggerKey))
|
||||
{
|
||||
stopwatch.Restart();
|
||||
bounds = new Rectangle(
|
||||
(screenSize.Width - mainConfig.Data.ImageWidth) / 2,
|
||||
(screenSize.Height - mainConfig.Data.ImageHeight) / 2,
|
||||
mainConfig.Data.ImageWidth,
|
||||
mainConfig.Data.ImageHeight
|
||||
);
|
||||
var screenshot = null as Bitmap;
|
||||
if (mainConfig.Data.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable)
|
||||
screenshot = _captureManager.CaptureScreenshotDirectX(bounds);
|
||||
else
|
||||
{
|
||||
if (_captureManager.IsInitialized)
|
||||
_captureManager.Dispose();
|
||||
screenshot = _captureManager.CaptureScreenshotGdi(bounds);
|
||||
}
|
||||
|
||||
if (screenshot == null)
|
||||
{
|
||||
LogManager.Log("Capture returned null screenshot. Skipping iteration.", LogManager.LogLevel.Debug);
|
||||
Thread.Sleep(2);
|
||||
continue;
|
||||
}
|
||||
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
|
||||
Mat drawing = mat.Clone();
|
||||
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV);
|
||||
Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat);
|
||||
Cv2.Dilate(mat, mat, null, iterations: 2);
|
||||
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary);
|
||||
|
||||
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
|
||||
|
||||
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 50).ToArray();
|
||||
|
||||
var processedContours = MergeOverlappingContours(filteredContours);
|
||||
|
||||
if (processedContours.Length > 0)
|
||||
{
|
||||
int refX = bounds.X + bounds.Width / 2;
|
||||
int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent);
|
||||
|
||||
double minDist = double.MaxValue;
|
||||
OpenCvSharp.Point[]? closestContour = null;
|
||||
int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0;
|
||||
|
||||
foreach (var contour in processedContours)
|
||||
{
|
||||
int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
|
||||
foreach (var point in contour)
|
||||
{
|
||||
if (point.X < minX) minX = point.X;
|
||||
if (point.Y < minY) minY = point.Y;
|
||||
if (point.X > maxX) maxX = point.X;
|
||||
if (point.Y > maxY) maxY = point.Y;
|
||||
}
|
||||
int centerX = (minX + maxX) / 2;
|
||||
int centerY = (minY + maxY) / 2;
|
||||
|
||||
int absCenterX = centerX + bounds.X;
|
||||
int absCenterY = centerY + bounds.Y;
|
||||
double dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2));
|
||||
|
||||
if (dist < minDist)
|
||||
{
|
||||
minDist = dist;
|
||||
closestContour = contour;
|
||||
bestMinX = minX;
|
||||
bestMinY = minY;
|
||||
bestMaxX = maxX;
|
||||
bestMaxY = maxY;
|
||||
}
|
||||
|
||||
if (renderer != null && mainConfig.Data.DrawDetections)
|
||||
{
|
||||
var _rect = new Rectangle(
|
||||
minX + bounds.X,
|
||||
minY + bounds.Y,
|
||||
(maxX - minX + 1),
|
||||
(maxY - minY + 1)
|
||||
);
|
||||
renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
if (closestContour != null)
|
||||
{
|
||||
int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent));
|
||||
int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent));
|
||||
int targetX = groupX + bounds.X;
|
||||
int targetY = groupY + bounds.Y;
|
||||
|
||||
if (mainConfig.Data.AutoLabel)
|
||||
{
|
||||
AutoLabeling.AddToQueue(drawing, bounds, processedContours);
|
||||
AutoLabeling.AddBackgroundImage(drawing, true);
|
||||
}
|
||||
if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData)
|
||||
{
|
||||
AutoLabeling.AddBackgroundImage(drawing, false);
|
||||
}
|
||||
|
||||
InputManager.SetLastDetection(new System.Drawing.Point(targetX, targetY));
|
||||
|
||||
if (mainConfig.Data.EnableAim)
|
||||
{
|
||||
InputManager.MoveMouse();
|
||||
}
|
||||
if (mainConfig.Data.TriggerBot)
|
||||
{
|
||||
var _ = InputManager.ClickMouse();
|
||||
}
|
||||
}
|
||||
if (mainConfig.Data.DebugMode)
|
||||
{
|
||||
iterationCount++;
|
||||
totalTime += stopwatch.ElapsedMilliseconds;
|
||||
}
|
||||
}
|
||||
else if (mainConfig.Data.CollectData)
|
||||
{
|
||||
if (mainConfig.Data.CollectData)
|
||||
AutoLabeling.AddBackgroundImage(drawing, false);
|
||||
}
|
||||
screenshot?.Dispose();
|
||||
mat.Dispose();
|
||||
drawing.Dispose();
|
||||
|
||||
if (!AutoLabeling.Started && (mainConfig.Data.CollectData || mainConfig.Data.AutoLabel))
|
||||
{
|
||||
AutoLabeling.StartLabeling();
|
||||
}
|
||||
else if (AutoLabeling.Started && !mainConfig.Data.CollectData && !mainConfig.Data.AutoLabel)
|
||||
{
|
||||
AutoLabeling.StopLabeling();
|
||||
}
|
||||
|
||||
if (iterationCount >= 1000 && mainConfig.Data.DebugMode)
|
||||
{
|
||||
LogManager.Log($"Processed {iterationCount} iterations in {totalTime} ms.", LogManager.LogLevel.Info);
|
||||
int fps = (int)(iterationCount * 1000 / totalTime);
|
||||
LogManager.Log($"Average FPS: {fps}", LogManager.LogLevel.Info);
|
||||
LogManager.Log($"Average time per iteration: {totalTime / iterationCount} ms", LogManager.LogLevel.Info);
|
||||
iterationCount = 0;
|
||||
totalTime = 0;
|
||||
}
|
||||
}
|
||||
else if (InputManager.IsKeyOrMouseDown(mainConfig.Data.MenuKey))
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
if ((now - lastMenuToggle).TotalMilliseconds > 175)
|
||||
{
|
||||
mainConfig.Data.ShowMenu = !mainConfig.Data.ShowMenu;
|
||||
lastMenuToggle = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.Log($"DetectionLoop error: {ex.GetType().Name}: {ex.Message}", LogManager.LogLevel.Error);
|
||||
Thread.Sleep(5);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours)
|
||||
{
|
||||
var contourRects = new List<(Rect rect, List<int> indices)>();
|
||||
for (int i = 0; i < contours.Length; i++)
|
||||
{
|
||||
var rect = Cv2.BoundingRect(contours[i]);
|
||||
contourRects.Add((rect, new List<int> { i }));
|
||||
}
|
||||
bool merged;
|
||||
do
|
||||
{
|
||||
merged = false;
|
||||
for (int i = 0; i < contourRects.Count; i++)
|
||||
{
|
||||
var (rectA, indicesA) = contourRects[i];
|
||||
for (int j = i + 1; j < contourRects.Count; j++)
|
||||
{
|
||||
var (rectB, indicesB) = contourRects[j];
|
||||
if (rectA.IntersectsWith(rectB))
|
||||
{
|
||||
var newRect = new Rect(
|
||||
Math.Min(rectA.X, rectB.X),
|
||||
Math.Min(rectA.Y, rectB.Y),
|
||||
Math.Max(rectA.X + rectA.Width, rectB.X + rectB.Width) - Math.Min(rectA.X, rectB.X),
|
||||
Math.Max(rectA.Y + rectA.Height, rectB.Y + rectB.Height) - Math.Min(rectA.Y, rectB.Y)
|
||||
);
|
||||
var newIndices = new List<int>();
|
||||
newIndices.AddRange(indicesA);
|
||||
newIndices.AddRange(indicesB);
|
||||
contourRects[i] = (newRect, newIndices);
|
||||
contourRects.RemoveAt(j);
|
||||
merged = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (merged) break;
|
||||
}
|
||||
} while (merged);
|
||||
|
||||
var mergedContours = new List<OpenCvSharp.Point[]>();
|
||||
foreach (var (rect, indices) in contourRects)
|
||||
{
|
||||
var points = new List<OpenCvSharp.Point>();
|
||||
foreach (var idx in indices)
|
||||
{
|
||||
points.AddRange(contours[idx]);
|
||||
}
|
||||
var hull = Cv2.ConvexHull(points);
|
||||
mergedContours.Add(hull);
|
||||
}
|
||||
return mergedContours.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.Makcu
|
||||
{
|
||||
internal class MakcuMain
|
||||
{
|
||||
public static MakcuMouse MakcuInstance { get; private set; }
|
||||
|
||||
private static bool _isMakcuLoaded = false;
|
||||
|
||||
private static bool _isSubscribedToButtonEvents = false;
|
||||
|
||||
private const bool DefaultDebugLoggingForInternalCreation = false;
|
||||
private const bool DefaultSendInitCommandsForInternalCreation = true;
|
||||
|
||||
public static void ConfigureMakcuInstance(bool debugEnabled, bool sendInitCmds)
|
||||
{
|
||||
|
||||
LogManager.Log($"MakcuMain: Configuring MakcuInstance. Debug: {debugEnabled}, SendInitCmds: {sendInitCmds}", LogLevel.Debug);
|
||||
UnsubscribeFromButtonEvents();
|
||||
MakcuInstance?.Dispose();
|
||||
|
||||
MakcuInstance = new MakcuMouse(debugEnabled, sendInitCmds);
|
||||
_isMakcuLoaded = false;
|
||||
}
|
||||
|
||||
private static async Task<bool> InitializeMakcuDevice()
|
||||
{
|
||||
if (_isMakcuLoaded && MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
|
||||
{
|
||||
LogManager.Log("MakcuMain: InitializeMakcuDevice called, but Makcu is already loaded and connected.", LogLevel.Debug);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (MakcuInstance == null)
|
||||
{
|
||||
ConfigureMakcuInstance(true, DefaultSendInitCommandsForInternalCreation);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (MakcuInstance == null || !MakcuInstance.Init())
|
||||
{
|
||||
_isMakcuLoaded = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
string version = MakcuInstance.GetKmVersion();
|
||||
|
||||
_isMakcuLoaded = true;
|
||||
|
||||
SubscribeToButtonEvents();
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_isMakcuLoaded = false;
|
||||
if (MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
|
||||
{
|
||||
MakcuInstance.Close();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<bool> Load() => await InitializeMakcuDevice();
|
||||
|
||||
public static void Unload()
|
||||
{
|
||||
UnsubscribeFromButtonEvents();
|
||||
if (MakcuInstance != null)
|
||||
{
|
||||
MakcuInstance.Close();
|
||||
}
|
||||
_isMakcuLoaded = false;
|
||||
LogManager.Log("MakcuMain: Makcu device unloaded/closed.", LogLevel.Debug);
|
||||
}
|
||||
|
||||
private static void SubscribeToButtonEvents()
|
||||
{
|
||||
if (MakcuInstance != null && !_isSubscribedToButtonEvents)
|
||||
{
|
||||
MakcuInstance.ButtonStateChanged += OnMakcuButtonStateChanged;
|
||||
_isSubscribedToButtonEvents = true;
|
||||
LogManager.Log("MakcuMain: Subscribed to MakcuInstance.ButtonStateChanged events.", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
|
||||
private static void UnsubscribeFromButtonEvents()
|
||||
{
|
||||
if (MakcuInstance != null && _isSubscribedToButtonEvents)
|
||||
{
|
||||
MakcuInstance.ButtonStateChanged -= OnMakcuButtonStateChanged;
|
||||
_isSubscribedToButtonEvents = false;
|
||||
LogManager.Log("MakcuMain: Unsubscribed from MakcuInstance.ButtonStateChanged events.", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
|
||||
private static void OnMakcuButtonStateChanged(MakcuMouseButton button, bool isPressed)
|
||||
{
|
||||
|
||||
string state = isPressed ? "Pressed" : "Released";
|
||||
LogManager.Log($"{button} physical {state}!", LogLevel.Debug);
|
||||
}
|
||||
public static void DisposeInstance()
|
||||
{
|
||||
Unload();
|
||||
MakcuInstance?.Dispose();
|
||||
MakcuInstance = null;
|
||||
_isMakcuLoaded = false;
|
||||
LogManager.Log("MakcuMain: MakcuMouse instance disposed (null).", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
using System.Diagnostics;
|
||||
using System.IO.Ports;
|
||||
using System.Text;
|
||||
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||
|
||||
/// https://github.com/sdfgasfgr/Aimmy-Makcu/blob/master/Aimmy2/MouseMovementLibraries/MakcuSupport/MakcuMouse.cs
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.Makcu
|
||||
{
|
||||
public enum MakcuMouseButton
|
||||
{
|
||||
Left = 0, Right = 1, Middle = 2, Mouse4 = 3, Mouse5 = 4
|
||||
}
|
||||
|
||||
public class MakcuMouse : IDisposable
|
||||
{
|
||||
private static readonly byte[] BaudChangeCommand = { 0xDE, 0xAD, 0x05, 0x00, 0xA5, 0x00, 0x09, 0x3D, 0x00 };
|
||||
|
||||
private SerialPort _serialPort;
|
||||
private readonly bool _debugLogging;
|
||||
private readonly bool _sendInitCommands;
|
||||
|
||||
private readonly object _serialLock = new object();
|
||||
private bool _isInitializedAndConnected = false;
|
||||
private Thread _listenerThread;
|
||||
private ManualResetEventSlim _stopListenerEvent = new ManualResetEventSlim(false);
|
||||
private volatile bool _pauseListener = false;
|
||||
|
||||
private readonly Dictionary<MakcuMouseButton, bool> _buttonStates = new Dictionary<MakcuMouseButton, bool>();
|
||||
|
||||
public event Action<MakcuMouseButton, bool> ButtonStateChanged;
|
||||
|
||||
public string PortName { get; private set; }
|
||||
public int BaudRate => _serialPort?.BaudRate ?? (_isInitializedAndConnected ? 4000000 : 115200);
|
||||
public bool IsInitializedAndConnected => _isInitializedAndConnected && _serialPort != null && _serialPort.IsOpen;
|
||||
|
||||
|
||||
public MakcuMouse(bool debugLogging = false, bool sendInitCommands = true)
|
||||
{
|
||||
_debugLogging = debugLogging;
|
||||
_sendInitCommands = sendInitCommands;
|
||||
foreach (MakcuMouseButton btn in Enum.GetValues(typeof(MakcuMouseButton)))
|
||||
{
|
||||
_buttonStates[btn] = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void Log(string message)
|
||||
{
|
||||
if (_debugLogging)
|
||||
{
|
||||
LogManager.Log($"[MakcuMouse {DateTime.Now:HH:mm:ss}] {message}", LogLevel.Debug);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private string FindComPortInternal()
|
||||
{
|
||||
Log("Searching for COM port for Makcu device using SerialPort.GetPortNames() and connection test...");
|
||||
string[] availablePorts;
|
||||
try
|
||||
{
|
||||
availablePorts = SerialPort.GetPortNames();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Error getting COM port list: {ex.Message}. Cannot continue search.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (availablePorts == null || !availablePorts.Any())
|
||||
{
|
||||
Log("No COM ports available according to SerialPort.GetPortNames().");
|
||||
return null;
|
||||
}
|
||||
|
||||
Log($"Available COM ports: {string.Join(", ", availablePorts)}. Testing each one...");
|
||||
|
||||
foreach (string portName in availablePorts)
|
||||
{
|
||||
Log($"Testing port: {portName}");
|
||||
SerialPort testPort = null;
|
||||
try
|
||||
{
|
||||
|
||||
testPort = new SerialPort(portName, 115200)
|
||||
{
|
||||
ReadTimeout = 250,
|
||||
WriteTimeout = 500,
|
||||
DtrEnable = true,
|
||||
RtsEnable = true
|
||||
};
|
||||
testPort.Open();
|
||||
Log($"Port {portName} opened at 115200 baud.");
|
||||
|
||||
Log($"Sending command to change baudrate to 4M on {portName}.");
|
||||
testPort.Write(BaudChangeCommand, 0, BaudChangeCommand.Length);
|
||||
testPort.BaseStream.Flush();
|
||||
Thread.Sleep(150);
|
||||
|
||||
testPort.Close();
|
||||
testPort.BaudRate = 4000000;
|
||||
testPort.Open();
|
||||
Log($"Port {portName} reopened at 4000000 baud.");
|
||||
|
||||
testPort.DiscardInBuffer();
|
||||
testPort.Write("km.version()\r\n");
|
||||
Log($"Command 'km.version()' sent to {portName}. Waiting for response...");
|
||||
|
||||
string response = "";
|
||||
try
|
||||
{
|
||||
response = testPort.ReadLine().Trim();
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
Log($"Timeout waiting for 'km.version()' response on {portName}. Probably not the Makcu device.");
|
||||
testPort.Close();
|
||||
continue;
|
||||
}
|
||||
|
||||
Log($"Response from 'km.version()' on {portName}: '{response}'");
|
||||
|
||||
if (!string.IsNullOrEmpty(response) && (response.Contains("KMBOX") || response.Contains("Makcu") || response.Contains("MAKCU") || response.StartsWith("v") || char.IsDigit(response.FirstOrDefault())))
|
||||
{
|
||||
Log($"Makcu device found on port: {portName}! Version response: '{response}'");
|
||||
testPort.Close();
|
||||
return portName;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log($"Response from 'km.version()' on {portName} does not seem to be from a Makcu device. Response: '{response}'");
|
||||
}
|
||||
|
||||
testPort.Close();
|
||||
}
|
||||
catch (UnauthorizedAccessException ex)
|
||||
{
|
||||
Log($"Unauthorized access error on {portName}: {ex.Message} (Port might be in use).");
|
||||
}
|
||||
catch (TimeoutException ex)
|
||||
{
|
||||
Log($"Timeout on {portName} (possibly during baud rate change or write): {ex.Message}");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Failed to test port {portName}: {ex.GetType().Name} - {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (testPort != null && testPort.IsOpen)
|
||||
{
|
||||
testPort.Close();
|
||||
}
|
||||
testPort?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Log("Makcu device not found on any available COM ports after connection test.");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
private bool OpenSerialPort(string portNameToOpen, int baudRate)
|
||||
{
|
||||
try
|
||||
{
|
||||
_serialPort?.Close();
|
||||
_serialPort?.Dispose();
|
||||
|
||||
Log($"Attempting to open {portNameToOpen} at {baudRate} baud.");
|
||||
_serialPort = new SerialPort(portNameToOpen, baudRate)
|
||||
{
|
||||
ReadTimeout = 100,
|
||||
WriteTimeout = 500,
|
||||
DtrEnable = true,
|
||||
RtsEnable = true
|
||||
};
|
||||
_serialPort.Open();
|
||||
PortName = portNameToOpen;
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Failed to open {portNameToOpen} at {baudRate} baud. Error: {ex.Message}");
|
||||
_serialPort?.Dispose(); _serialPort = null; return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool ChangeBaudRateTo4M()
|
||||
{
|
||||
if (_serialPort == null || !_serialPort.IsOpen)
|
||||
{
|
||||
Log("ChangeBaudRateTo4M: _serialPort is null or not open.");
|
||||
return false;
|
||||
}
|
||||
Log("Sending command to change baudrate to 4M.");
|
||||
try
|
||||
{
|
||||
_serialPort.Write(BaudChangeCommand, 0, BaudChangeCommand.Length);
|
||||
_serialPort.BaseStream.Flush();
|
||||
Thread.Sleep(150);
|
||||
|
||||
string currentPortName = _serialPort.PortName;
|
||||
_serialPort.Close();
|
||||
|
||||
_serialPort.BaudRate = 4000000;
|
||||
_serialPort.Open();
|
||||
|
||||
Log("Successfully changed to 4M baud."); return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Error changing baudrate to 4M: {ex.Message}");
|
||||
|
||||
_serialPort?.Close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Init()
|
||||
{
|
||||
lock (_serialLock)
|
||||
{
|
||||
if (_isInitializedAndConnected) { Log("MakcuMouse is already initialized."); return true; }
|
||||
|
||||
string portToUse = FindComPortInternal();
|
||||
if (string.IsNullOrEmpty(portToUse))
|
||||
{ Log("Init failed: Could not find a valid COM port for Makcu."); return false; }
|
||||
|
||||
|
||||
if (!OpenSerialPort(portToUse, 115200))
|
||||
{ Log($"Init failed: Could not open port {portToUse} at 115200 baud."); return false; }
|
||||
|
||||
if (!ChangeBaudRateTo4M())
|
||||
{ Log("Init failed: Could not change to 4M baud."); Close(); return false; }
|
||||
|
||||
_isInitializedAndConnected = true;
|
||||
PortName = portToUse;
|
||||
|
||||
if (_sendInitCommands)
|
||||
{
|
||||
if (!SendCommandInternal("km.buttons(1)", false, out _))
|
||||
{ Log("Init failed: Could not send 'km.buttons(1)'."); Close(); return false; }
|
||||
|
||||
_stopListenerEvent.Reset();
|
||||
_listenerThread = new Thread(() => ListenForButtonEvents(_debugLogging))
|
||||
{ IsBackground = true, Name = "MakcuButtonListener" };
|
||||
_listenerThread.Start();
|
||||
}
|
||||
Log($"MakcuMouse initialized successfully on port {PortName} at {BaudRate} baud."); return true;
|
||||
}
|
||||
}
|
||||
|
||||
private bool SendCommandInternal(string command, bool expectResponse, out string responseText, int responseTimeoutMs = 200)
|
||||
{
|
||||
responseText = null;
|
||||
if (!_isInitializedAndConnected || _serialPort == null || !_serialPort.IsOpen)
|
||||
{
|
||||
Log($"Error in SendCommand: Connection not open or initialized. Command: {command}");
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (_serialLock)
|
||||
{
|
||||
if (!_serialPort.IsOpen)
|
||||
{
|
||||
Log($"Error in SendCommand (lock): Port not open. Command: {command}");
|
||||
return false;
|
||||
}
|
||||
|
||||
_pauseListener = true;
|
||||
int originalReadTimeout = _serialPort.ReadTimeout;
|
||||
|
||||
try
|
||||
{
|
||||
if (expectResponse)
|
||||
{
|
||||
_serialPort.ReadTimeout = responseTimeoutMs;
|
||||
_serialPort.DiscardInBuffer();
|
||||
}
|
||||
|
||||
Log($"Sending: {command}");
|
||||
_serialPort.Write(command + "\r\n");
|
||||
|
||||
if (expectResponse)
|
||||
{
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
string commandTrimmed = command.Trim();
|
||||
bool firstLineIsEcho = true;
|
||||
|
||||
while (stopwatch.ElapsedMilliseconds < responseTimeoutMs)
|
||||
{
|
||||
try
|
||||
{
|
||||
string line = _serialPort.ReadLine().Trim();
|
||||
if (!string.IsNullOrEmpty(line))
|
||||
{
|
||||
Log($"Received (raw): {line}");
|
||||
if (line.Equals(commandTrimmed, StringComparison.OrdinalIgnoreCase) && firstLineIsEcho)
|
||||
{
|
||||
firstLineIsEcho = false;
|
||||
continue;
|
||||
}
|
||||
if (line.Equals("OK", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (sb.Length > 0) continue;
|
||||
}
|
||||
if (sb.Length > 0) sb.Append("\n");
|
||||
sb.Append(line);
|
||||
}
|
||||
if (_serialPort.BytesToRead == 0 && sb.Length > 0)
|
||||
{
|
||||
Thread.Sleep(15);
|
||||
if (_serialPort.BytesToRead == 0) break;
|
||||
}
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
Log($"ReadLine() timeout in SendCommandInternal for '{command}'.");
|
||||
break;
|
||||
}
|
||||
catch (InvalidOperationException ioe) { Log($"InvalidOperationException in ReadLine (SendCommandInternal): {ioe.Message}"); _isInitializedAndConnected = false; Close(); return false; }
|
||||
catch (Exception ex) { Log($"Exception in ReadLine (SendCommandInternal): {ex.Message}"); break; }
|
||||
}
|
||||
stopwatch.Stop();
|
||||
responseText = sb.ToString().Trim();
|
||||
Log($"Final response for '{command}': '{responseText}' (Time: {stopwatch.ElapsedMilliseconds}ms)");
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (TimeoutException tex)
|
||||
{
|
||||
Log($"General timeout in SendCommandInternal for '{command}': {tex.Message}");
|
||||
return false;
|
||||
}
|
||||
catch (InvalidOperationException ioe)
|
||||
{
|
||||
Log($"General InvalidOperationException in SendCommandInternal (possibly port closed): {ioe.Message}");
|
||||
_isInitializedAndConnected = false; Close();
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"General exception in SendCommandInternal for '{command}': {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pauseListener = false;
|
||||
if (expectResponse)
|
||||
{
|
||||
_serialPort.ReadTimeout = originalReadTimeout;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ListenForButtonEvents(bool debug)
|
||||
{
|
||||
Log("Listener thread started. (PACKET PARSING MODE)");
|
||||
byte lastMask = 0x00; // <<-- CAMBIO CLAVE: Inicializar como todos los botones liberados
|
||||
var buttonMap = new Dictionary<int, MakcuMouseButton> {
|
||||
{0, MakcuMouseButton.Left}, {1, MakcuMouseButton.Right}, {2, MakcuMouseButton.Middle},
|
||||
{3, MakcuMouseButton.Mouse4}, {4, MakcuMouseButton.Mouse5}
|
||||
};
|
||||
|
||||
byte[] packetHeader = { 0x6B, 0x6D, 0x2E };
|
||||
int currentHeaderIndex = 0;
|
||||
|
||||
while (!_stopListenerEvent.IsSet)
|
||||
{
|
||||
if (!IsInitializedAndConnected || _pauseListener || _serialPort == null || !_serialPort.IsOpen)
|
||||
{
|
||||
Thread.Sleep(20);
|
||||
currentHeaderIndex = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_serialPort.BytesToRead > 0)
|
||||
{
|
||||
byte byteRead = (byte)_serialPort.ReadByte();
|
||||
|
||||
if (byteRead == packetHeader[currentHeaderIndex])
|
||||
{
|
||||
currentHeaderIndex++;
|
||||
if (currentHeaderIndex == packetHeader.Length)
|
||||
{
|
||||
if (debug) Log($"Listener: Packet header {string.Join(",", packetHeader.Select(b => b.ToString("X2")))} detected!");
|
||||
|
||||
if (_serialPort.BytesToRead > 0)
|
||||
{
|
||||
byte currentMask = (byte)_serialPort.ReadByte();
|
||||
if (debug) Log($"Listener: Potential button mask byte: 0x{currentMask:X2}");
|
||||
|
||||
if (currentMask <= 0b00011111)
|
||||
{
|
||||
if (currentMask != lastMask)
|
||||
{
|
||||
if (debug) Log($"Listener: Processing button mask. New: 0x{currentMask:X2}, Prev: 0x{lastMask:X2}");
|
||||
byte changedBits = (byte)(currentMask ^ lastMask);
|
||||
|
||||
lock (_buttonStates)
|
||||
{
|
||||
foreach (var pair in buttonMap)
|
||||
{
|
||||
if ((changedBits & (1 << pair.Key)) != 0)
|
||||
{
|
||||
bool isPressed = (currentMask & (1 << pair.Key)) != 0;
|
||||
_buttonStates[pair.Value] = isPressed;
|
||||
if (debug) Log($"Listener: ---> EVENT: Button: {pair.Value}, IsPressed: {isPressed}");
|
||||
try
|
||||
{
|
||||
ButtonStateChanged?.Invoke(pair.Value, isPressed);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Exception in ButtonStateChanged handler: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
lastMask = currentMask;
|
||||
if (debug)
|
||||
{
|
||||
var pressedButtons = _buttonStates.Where(kvp => kvp.Value).Select(kvp => kvp.Key.ToString()).ToArray();
|
||||
Log($"Listener: Button states updated. Mask: 0x{currentMask:X2} -> {(pressedButtons.Any() ? string.Join(", ", pressedButtons) : "None")}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int expectedTailBytes = 2;
|
||||
for (int i = 0; i < expectedTailBytes; i++)
|
||||
{
|
||||
if (_serialPort.BytesToRead > 0)
|
||||
{
|
||||
byte consumedByte = (byte)_serialPort.ReadByte();
|
||||
if (debug) Log($"Listener: Consumed tail byte {i + 1}: 0x{consumedByte:X2}");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (debug) Log($"Listener: Expected tail byte {i + 1} but no data. Packet might be short.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (debug) Log("Listener: Header found, but no data for button mask byte. Packet might be short.");
|
||||
}
|
||||
currentHeaderIndex = 0;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (currentHeaderIndex > 0 && debug)
|
||||
{
|
||||
Log($"Listener: Byte 0x{byteRead:X2} broke header sequence at index {currentHeaderIndex}. Resetting search.");
|
||||
}
|
||||
currentHeaderIndex = 0;
|
||||
if (byteRead == packetHeader[0])
|
||||
{
|
||||
currentHeaderIndex = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
if (debug) Log("Listener: TimeoutException during serial read.");
|
||||
currentHeaderIndex = 0;
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
Log($"Listener: InvalidOperationException (port probably closed): {ex.Message}. Stopping listener.");
|
||||
_isInitializedAndConnected = false;
|
||||
currentHeaderIndex = 0;
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log($"Error in listener: {ex.GetType().Name} - {ex.Message}");
|
||||
currentHeaderIndex = 0;
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
}
|
||||
Log("Listener thread terminated.");
|
||||
}
|
||||
|
||||
public bool Press(MakcuMouseButton button) => SendCommandInternal($"km.{GetButtonString(button)}(1)", false, out _);
|
||||
public bool Release(MakcuMouseButton button) => SendCommandInternal($"km.{GetButtonString(button)}(0)", false, out _);
|
||||
public bool Move(int x, int y) => SendCommandInternal($"km.move({x},{y})", false, out _);
|
||||
public bool MoveSmooth(int x, int y, int segments) => SendCommandInternal($"km.move({x},{y},{segments})", false, out _);
|
||||
public bool MoveBezier(int x, int y, int segments, int ctrlX, int ctrlY) => SendCommandInternal($"km.move({x},{y},{segments},{ctrlX},{ctrlY})", false, out _);
|
||||
public bool Scroll(int delta) => SendCommandInternal($"km.wheel({delta})", false, out _);
|
||||
|
||||
public string GetKmVersion()
|
||||
{
|
||||
return SendCommandInternal("km.version()", true, out string response, 500) ? response : null;
|
||||
}
|
||||
private string GetButtonString(MakcuMouseButton button)
|
||||
{
|
||||
switch (button)
|
||||
{
|
||||
case MakcuMouseButton.Left: return "left";
|
||||
case MakcuMouseButton.Right: return "right";
|
||||
case MakcuMouseButton.Middle: return "middle";
|
||||
default: throw new ArgumentException($"Button {button} not supported for direct press/release actions (left/right/middle).");
|
||||
}
|
||||
}
|
||||
private string GetButtonLockString(MakcuMouseButton button)
|
||||
{
|
||||
switch (button)
|
||||
{
|
||||
case MakcuMouseButton.Left: return "ml";
|
||||
case MakcuMouseButton.Right: return "mr";
|
||||
case MakcuMouseButton.Middle: return "mm";
|
||||
case MakcuMouseButton.Mouse4: return "ms1";
|
||||
case MakcuMouseButton.Mouse5: return "ms2";
|
||||
default: throw new ArgumentException($"Button not supported for lock/catch: {button}");
|
||||
}
|
||||
}
|
||||
public Dictionary<MakcuMouseButton, bool> GetCurrentButtonStates()
|
||||
{ lock (_buttonStates) { return new Dictionary<MakcuMouseButton, bool>(_buttonStates); } }
|
||||
|
||||
public int GetCurrentButtonMask()
|
||||
{
|
||||
int mask = 0;
|
||||
lock (_buttonStates)
|
||||
{
|
||||
if (_buttonStates.TryGetValue(MakcuMouseButton.Left, out bool l) && l) mask |= (1 << (int)MakcuMouseButton.Left);
|
||||
if (_buttonStates.TryGetValue(MakcuMouseButton.Right, out bool r) && r) mask |= (1 << (int)MakcuMouseButton.Right);
|
||||
if (_buttonStates.TryGetValue(MakcuMouseButton.Middle, out bool m) && m) mask |= (1 << (int)MakcuMouseButton.Middle);
|
||||
if (_buttonStates.TryGetValue(MakcuMouseButton.Mouse4, out bool m4) && m4) mask |= (1 << (int)MakcuMouseButton.Mouse4);
|
||||
if (_buttonStates.TryGetValue(MakcuMouseButton.Mouse5, out bool m5) && m5) mask |= (1 << (int)MakcuMouseButton.Mouse5);
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
private bool _disposedValue;
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposedValue)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
Close();
|
||||
_stopListenerEvent?.Dispose();
|
||||
}
|
||||
_disposedValue = true;
|
||||
}
|
||||
}
|
||||
public void Dispose() { Dispose(true); GC.SuppressFinalize(this); }
|
||||
~MakcuMouse() { Dispose(false); }
|
||||
|
||||
public void Close()
|
||||
{
|
||||
Log("Closing MakcuMouse connection...");
|
||||
_isInitializedAndConnected = false;
|
||||
|
||||
if (_listenerThread != null)
|
||||
{
|
||||
_stopListenerEvent.Set();
|
||||
if (_listenerThread.IsAlive)
|
||||
{
|
||||
if (!_listenerThread.Join(TimeSpan.FromSeconds(1)))
|
||||
{
|
||||
Log("Listener thread did not terminate in time.");
|
||||
}
|
||||
}
|
||||
_listenerThread = null;
|
||||
}
|
||||
lock (_serialLock)
|
||||
{
|
||||
if (_serialPort != null)
|
||||
{
|
||||
if (_serialPort.IsOpen)
|
||||
{
|
||||
try { _serialPort.Close(); }
|
||||
catch (Exception ex) { Log($"Error closing port: {ex.Message}"); }
|
||||
}
|
||||
_serialPort.Dispose();
|
||||
_serialPort = null;
|
||||
}
|
||||
}
|
||||
PortName = null;
|
||||
Log("MakcuMouse connection closed.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Spectrum.Input.InputLibraries.MouseEvent
|
||||
{
|
||||
public class MouseMain
|
||||
{
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
||||
|
||||
public static void Move(int x, int y)
|
||||
{
|
||||
mouse_event(0x0001, (uint)x, (uint)y, 0, 0);
|
||||
}
|
||||
|
||||
public static void ClickDown()
|
||||
{
|
||||
mouse_event(0x0002, 0, 0, 0, 0);
|
||||
}
|
||||
public static void ClickUp()
|
||||
{
|
||||
mouse_event(0x0004, 0, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
using Spectrum.Input.InputLibraries.Makcu;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain;
|
||||
|
||||
namespace Spectrum.Input
|
||||
{
|
||||
public static class InputManager
|
||||
{
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool GetCursorPos(out Point lpPoint);
|
||||
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||
private static Point lastDetection = new Point();
|
||||
private static long _lastMoveTicks = 0;
|
||||
private static readonly double _dtRef = 1.0 / 120.0;
|
||||
|
||||
private static double GetDeltaSeconds()
|
||||
{
|
||||
long now = Stopwatch.GetTimestamp();
|
||||
if (_lastMoveTicks == 0)
|
||||
{
|
||||
_lastMoveTicks = now;
|
||||
return _dtRef;
|
||||
}
|
||||
long deltaTicks = now - _lastMoveTicks;
|
||||
_lastMoveTicks = now;
|
||||
double dt = (double)deltaTicks / Stopwatch.Frequency;
|
||||
|
||||
if (dt < 0.0001) dt = 0.0001; // 10k fps cap
|
||||
if (dt > 0.05) dt = 0.05; // 20 fps floor
|
||||
return dt;
|
||||
}
|
||||
|
||||
private static double TimeScaleFactor(double baseFactor, double deltaSeconds)
|
||||
{
|
||||
if (baseFactor <= 0) return 0;
|
||||
if (baseFactor >= 1) return 1;
|
||||
double k = deltaSeconds / _dtRef;
|
||||
return 1 - Math.Pow(1 - baseFactor, k);
|
||||
}
|
||||
|
||||
public static void MoveMouse()
|
||||
{
|
||||
Point reference = new Point();
|
||||
if (mainConfig.Data.ClosestToMouse)
|
||||
{
|
||||
GetCursorPos(out reference);
|
||||
}
|
||||
else
|
||||
{
|
||||
reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
|
||||
reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
||||
}
|
||||
|
||||
Point start = new Point(reference.X, reference.Y);
|
||||
Point end = new Point(lastDetection.X, lastDetection.Y);
|
||||
|
||||
double dt = GetDeltaSeconds();
|
||||
double effSensitivity = TimeScaleFactor(mainConfig.Data.Sensitivity, dt);
|
||||
|
||||
Point newPosition = mainConfig.Data.AimMovementType switch
|
||||
{
|
||||
MovementType.CubicBezier => MovementPaths.CubicBezierMovement(start, end, effSensitivity),
|
||||
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, effSensitivity),
|
||||
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, effSensitivity),
|
||||
MovementType.QuadraticBezier => MovementPaths.CurvedMovement(start, end, effSensitivity),
|
||||
_ => end
|
||||
};
|
||||
|
||||
if (mainConfig.Data.EmaSmoothening)
|
||||
{
|
||||
double emaAlpha = TimeScaleFactor(mainConfig.Data.EmaSmootheningFactor, dt);
|
||||
newPosition.X = (int)Math.Round(MovementPaths.EmaSmoothing(reference.X, newPosition.X, emaAlpha));
|
||||
newPosition.Y = (int)Math.Round(MovementPaths.EmaSmoothing(reference.Y, newPosition.Y, emaAlpha));
|
||||
}
|
||||
|
||||
int deltaX = newPosition.X - reference.X;
|
||||
int deltaY = newPosition.Y - reference.Y;
|
||||
|
||||
if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return;
|
||||
if (deltaX > mainConfig.Data.ImageWidth || deltaX < -mainConfig.Data.ImageWidth || deltaY > mainConfig.Data.ImageHeight || deltaY < -mainConfig.Data.ImageHeight)
|
||||
return;
|
||||
|
||||
switch (mainConfig.Data.MovementMethod)
|
||||
{
|
||||
case MovementMethod.MouseEvent:
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
break;
|
||||
case MovementMethod.Makcu:
|
||||
if (EnsureMakcuReady())
|
||||
MakcuMain.MakcuInstance.Move(deltaX, deltaY);
|
||||
else
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
break;
|
||||
default:
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task ClickMouse()
|
||||
{
|
||||
if (!mainConfig.Data.TriggerBot)
|
||||
return;
|
||||
if (!IsKeyOrMouseDown(mainConfig.Data.TriggerKey) || mainConfig.Data.TriggerKey == Keys.None)
|
||||
return;
|
||||
|
||||
var currentPosition = new Point();
|
||||
if (mainConfig.Data.ClosestToMouse)
|
||||
{
|
||||
GetCursorPos(out currentPosition);
|
||||
}
|
||||
else
|
||||
{
|
||||
currentPosition.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
|
||||
currentPosition.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
||||
}
|
||||
|
||||
if (mainConfig.Data.TriggerDelay > 0)
|
||||
await Task.Delay(mainConfig.Data.TriggerDelay);
|
||||
|
||||
int radius = mainConfig.Data.TriggerRadius;
|
||||
|
||||
if (Math.Abs(currentPosition.X - lastDetection.X) < radius && Math.Abs(currentPosition.Y - lastDetection.Y) < radius)
|
||||
{
|
||||
switch (mainConfig.Data.MovementMethod)
|
||||
{
|
||||
case MovementMethod.MouseEvent:
|
||||
MouseEvent.ClickDown();
|
||||
break;
|
||||
case MovementMethod.Makcu:
|
||||
if (EnsureMakcuReady())
|
||||
MakcuMain.MakcuInstance.Press(MakcuMouseButton.Left);
|
||||
else
|
||||
MouseEvent.ClickDown();
|
||||
break;
|
||||
default:
|
||||
MouseEvent.ClickDown();
|
||||
break;
|
||||
}
|
||||
await Task.Delay(mainConfig.Data.TriggerDuration);
|
||||
switch (mainConfig.Data.MovementMethod)
|
||||
{
|
||||
case MovementMethod.MouseEvent:
|
||||
MouseEvent.ClickUp();
|
||||
break;
|
||||
case MovementMethod.Makcu:
|
||||
if (EnsureMakcuReady())
|
||||
MakcuMain.MakcuInstance.Release(MakcuMouseButton.Left);
|
||||
else
|
||||
MouseEvent.ClickUp();
|
||||
break;
|
||||
default:
|
||||
MouseEvent.ClickUp();
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var dist = Math.Sqrt(Math.Pow(currentPosition.X - lastDetection.X, 2) + Math.Pow(currentPosition.Y - lastDetection.Y, 2));
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetLastDetection(Point point)
|
||||
{
|
||||
lastDetection = point;
|
||||
}
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern short GetAsyncKeyState(int vKey);
|
||||
|
||||
private static readonly Keys[] MouseKeys =
|
||||
{
|
||||
Keys.LButton, Keys.RButton, Keys.MButton, Keys.XButton1, Keys.XButton2
|
||||
};
|
||||
|
||||
public static Task<Keys> ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null)
|
||||
{
|
||||
var tcs = new TaskCompletionSource<Keys>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
Action<MakcuMouseButton, bool>? makcuHandler = null;
|
||||
bool subscribedToMakcu = false;
|
||||
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && EnsureMakcuReady())
|
||||
{
|
||||
makcuHandler = (btn, isPressed) =>
|
||||
{
|
||||
if (!isPressed) return;
|
||||
var key = MapMakcuButtonToKeys(btn);
|
||||
if (key.HasValue)
|
||||
{
|
||||
tcs.TrySetResult(key.Value);
|
||||
}
|
||||
};
|
||||
MakcuMain.MakcuInstance.ButtonStateChanged += makcuHandler;
|
||||
subscribedToMakcu = true;
|
||||
}
|
||||
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
if (tcs.Task.IsCompleted)
|
||||
{
|
||||
return;
|
||||
}
|
||||
for (int key = 0x08; key <= 0xFE; key++)
|
||||
{
|
||||
if ((GetAsyncKeyState(key) & 0x8000) != 0)
|
||||
{
|
||||
tcs.TrySetResult((Keys)key);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var mouseKey in MouseKeys)
|
||||
{
|
||||
if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0)
|
||||
{
|
||||
tcs.TrySetResult(mouseKey);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (cancellationToken?.IsCancellationRequested == true)
|
||||
{
|
||||
tcs.TrySetCanceled();
|
||||
return;
|
||||
}
|
||||
Thread.Sleep(10);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null)
|
||||
{
|
||||
try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { }
|
||||
}
|
||||
}
|
||||
})
|
||||
{ IsBackground = true };
|
||||
|
||||
tcs.Task.ContinueWith(_ =>
|
||||
{
|
||||
if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null)
|
||||
{
|
||||
try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { }
|
||||
}
|
||||
}, TaskScheduler.Default);
|
||||
|
||||
thread.Start();
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
private static bool EnsureMakcuReady()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) return true;
|
||||
var ok = MakcuMain.Load().GetAwaiter().GetResult();
|
||||
if (ok && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) return true;
|
||||
|
||||
LogManager.Log("Makcu not ready. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
|
||||
MakcuMain.Unload();
|
||||
mainConfig.Data.MovementMethod = MovementMethod.MouseEvent;
|
||||
return false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
LogManager.Log("Makcu initialization threw an exception. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
|
||||
MakcuMain.Unload();
|
||||
mainConfig.Data.MovementMethod = MovementMethod.MouseEvent;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static Keys? MapMakcuButtonToKeys(MakcuMouseButton btn)
|
||||
{
|
||||
return btn switch
|
||||
{
|
||||
MakcuMouseButton.Left => Keys.LButton,
|
||||
MakcuMouseButton.Right => Keys.RButton,
|
||||
MakcuMouseButton.Middle => Keys.MButton,
|
||||
MakcuMouseButton.Mouse4 => Keys.XButton1,
|
||||
MakcuMouseButton.Mouse5 => Keys.XButton2,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
public static bool IsKeyOrMouseDown(Keys key)
|
||||
{
|
||||
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true)
|
||||
{
|
||||
var makcuBtn = MapKeysToMakcuButton(key);
|
||||
if (makcuBtn.HasValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
var states = MakcuMain.MakcuInstance.GetCurrentButtonStates();
|
||||
|
||||
return states.TryGetValue(makcuBtn.Value, out var pressed) && pressed;
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
return (GetAsyncKeyState((int)key) & 0x8000) != 0; ;
|
||||
}
|
||||
|
||||
private static MakcuMouseButton? MapKeysToMakcuButton(Keys key)
|
||||
{
|
||||
return key switch
|
||||
{
|
||||
Keys.LButton => MakcuMouseButton.Left,
|
||||
Keys.RButton => MakcuMouseButton.Right,
|
||||
Keys.MButton => MakcuMouseButton.Middle,
|
||||
Keys.XButton1 => MakcuMouseButton.Mouse4,
|
||||
Keys.XButton2 => MakcuMouseButton.Mouse5,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
|
||||
namespace Spectrum.Input
|
||||
{
|
||||
public class MovementPaths
|
||||
{
|
||||
private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t);
|
||||
public static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
double u = 1 - t;
|
||||
double tt = t * t;
|
||||
double uu = u * u;
|
||||
|
||||
double x = uu * u * start.X + 3 * uu * t * control1.X + 3 * u * tt * control2.X + tt * t * end.X;
|
||||
double y = uu * u * start.Y + 3 * uu * t * control1.Y + 3 * u * tt * control2.Y + tt * t * end.Y;
|
||||
|
||||
return new Point((int)Math.Round(x), (int)Math.Round(y));
|
||||
}
|
||||
public static Point CubicBezierMovement(Point start, Point end, double t)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
Point control1 = new Point(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3);
|
||||
Point control2 = new Point(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3);
|
||||
return CubicBezier(start, end, control1, control2, t);
|
||||
}
|
||||
|
||||
public static Point CubicBezierCurvedMovement(Point start, Point end, double t, double curvature = 0.25)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
curvature = Math.Max(0, Math.Min(1, curvature));
|
||||
double dx = end.X - start.X;
|
||||
double dy = end.Y - start.Y;
|
||||
double dist = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (dist == 0) return start;
|
||||
double nx = -dy / dist;
|
||||
double ny = dx / dist;
|
||||
double offset = dist * curvature;
|
||||
var control1 = new Point((int)Math.Round(start.X + dx / 3 + nx * offset), (int)Math.Round(start.Y + dy / 3 + ny * offset));
|
||||
var control2 = new Point((int)Math.Round(start.X + 2 * dx / 3 + nx * offset), (int)Math.Round(start.Y + 2 * dy / 3 + ny * offset));
|
||||
return CubicBezier(start, end, control1, control2, t);
|
||||
}
|
||||
|
||||
public static Point LinearInterpolation(Point start, Point end, double t)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
int x = (int)Math.Round(start.X + t * (end.X - start.X));
|
||||
int y = (int)Math.Round(start.Y + t * (end.Y - start.Y));
|
||||
return new Point(x, y);
|
||||
}
|
||||
|
||||
public static Point CurvedMovement(Point start, Point end, double t)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
Point control = new Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 - 200);
|
||||
return QuadraticBezier(start, end, control, t);
|
||||
}
|
||||
public static Point QuadraticBezier(Point start, Point end, Point control, double t)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
double u = 1 - t;
|
||||
double tt = t * t;
|
||||
double uu = u * u;
|
||||
double x = uu * start.X + 2 * u * t * control.X + tt * end.X;
|
||||
double y = uu * start.Y + 2 * u * t * control.Y + tt * end.Y;
|
||||
return new Point((int)Math.Round(x), (int)Math.Round(y));
|
||||
}
|
||||
|
||||
public static Point AdaptiveMovement(Point start, Point end, double sensitivity)
|
||||
{
|
||||
double dx = end.X - start.X;
|
||||
double dy = end.Y - start.Y;
|
||||
double distance = Math.Sqrt(dx * dx + dy * dy);
|
||||
if (distance == 0) return start;
|
||||
double stepSize = Math.Max(0, sensitivity) * distance;
|
||||
stepSize = Math.Min(stepSize, distance);
|
||||
double directionX = dx / distance;
|
||||
double directionY = dy / distance;
|
||||
int newX = (int)Math.Round(start.X + directionX * stepSize);
|
||||
int newY = (int)Math.Round(start.Y + directionY * stepSize);
|
||||
return new Point(newX, newY);
|
||||
}
|
||||
public static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor)
|
||||
{
|
||||
smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor));
|
||||
return currentValue * smoothingFactor + previousValue * (1 - smoothingFactor);
|
||||
}
|
||||
|
||||
public static Point EmaSmoothing(Point previous, Point current, double smoothingFactor)
|
||||
{
|
||||
smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor));
|
||||
int x = (int)Math.Round(EmaSmoothing(previous.X, current.X, smoothingFactor));
|
||||
int y = (int)Math.Round(EmaSmoothing(previous.Y, current.Y, smoothingFactor));
|
||||
return new Point(x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,163 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Spectrum
|
||||
{
|
||||
public static class InputManager
|
||||
{
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool GetCursorPos(out POINT lpPoint);
|
||||
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||
|
||||
private struct POINT
|
||||
{
|
||||
public int X;
|
||||
public int Y;
|
||||
}
|
||||
// AIMMY V2 CODE - https://github.com/Babyhamsta/Aimmy/blob/2e906552673e359ded90383c5e97d79c8f38a2f2/Aimmy2/InputLogic/MouseManager.cs#L34-L50
|
||||
private static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t)
|
||||
{
|
||||
double u = 1 - t;
|
||||
double tt = t * t;
|
||||
double uu = u * u;
|
||||
|
||||
double x = uu * u * start.X + 3 * uu * t * control1.X + 3 * u * tt * control2.X + tt * t * end.X;
|
||||
double y = uu * u * start.Y + 3 * uu * t * control1.Y + 3 * u * tt * control2.Y + tt * t * end.Y;
|
||||
|
||||
return new Point((int)x, (int)y);
|
||||
}
|
||||
private static Point CubicBezierMovement(Point start, Point end, double t)
|
||||
{
|
||||
Point control1 = new Point(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3);
|
||||
Point control2 = new Point(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3);
|
||||
return CubicBezier(start, end, control1, control2, t);
|
||||
}
|
||||
|
||||
private static Point LinearInterpolation(Point start, Point end, double t)
|
||||
{
|
||||
int x = (int)(start.X + t * (end.X - start.X));
|
||||
int y = (int)(start.Y + t * (end.Y - start.Y));
|
||||
return new Point(x, y);
|
||||
}
|
||||
|
||||
private static Point CurvedMovement(Point start, Point end, double t)
|
||||
{
|
||||
Point control = new Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 - 200);
|
||||
return QuadraticBezier(start, end, control, t);
|
||||
}
|
||||
private static Point QuadraticBezier(Point start, Point end, Point control, double t)
|
||||
{
|
||||
double u = 1 - t;
|
||||
double tt = t * t;
|
||||
double uu = u * u;
|
||||
double x = uu * start.X + 2 * u * t * control.X + tt * end.X;
|
||||
double y = uu * start.Y + 2 * u * t * control.Y + tt * end.Y;
|
||||
return new Point((int)x, (int)y);
|
||||
}
|
||||
|
||||
private static Point AdaptiveMovement(Point start, Point end, double sensitivity)
|
||||
{
|
||||
double distance = Math.Sqrt(Math.Pow(end.X - start.X, 2) + Math.Pow(end.Y - start.Y, 2));
|
||||
double stepSize = distance * sensitivity;
|
||||
|
||||
double directionX = (end.X - start.X) / distance;
|
||||
double directionY = (end.Y - start.Y) / distance;
|
||||
|
||||
int newX = (int)(start.X + directionX * stepSize);
|
||||
int newY = (int)(start.Y + directionY * stepSize);
|
||||
return new Point(newX, newY);
|
||||
}
|
||||
private static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor) => (currentValue * smoothingFactor) + (previousValue * (1 - smoothingFactor));
|
||||
|
||||
public static void MoveMouse(Point target)
|
||||
{
|
||||
POINT reference = new POINT();
|
||||
if (mainConfig.Data.ClosestToMouse)
|
||||
{
|
||||
GetCursorPos(out reference);
|
||||
}
|
||||
else
|
||||
{
|
||||
// center of the screen
|
||||
reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
|
||||
reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
||||
}
|
||||
|
||||
|
||||
|
||||
Point start = new Point(reference.X, reference.Y);
|
||||
Point end = new Point(target.X, target.Y);
|
||||
Point newPosition = mainConfig.Data.AimMovementType switch
|
||||
{
|
||||
MovementType.CubicBezier => CubicBezierMovement(start, end, mainConfig.Data.Sensitivity),
|
||||
MovementType.Linear => LinearInterpolation(start, end, mainConfig.Data.Sensitivity),
|
||||
MovementType.Adaptive => AdaptiveMovement(start, end, mainConfig.Data.Sensitivity),
|
||||
MovementType.QuadraticBezier => CurvedMovement(start, end, mainConfig.Data.Sensitivity),
|
||||
_ => 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 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);
|
||||
}
|
||||
[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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
|
||||
namespace Spectrum
|
||||
{
|
||||
public class LogManager
|
||||
{
|
||||
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||
public enum LogLevel
|
||||
{
|
||||
Debug,
|
||||
@@ -33,6 +35,12 @@ namespace Spectrum
|
||||
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
|
||||
public static void Log(string message, LogLevel level = LogLevel.Info)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message)) return;
|
||||
if (mainConfig == null)
|
||||
mainConfig = Program.mainConfig;
|
||||
if (level == LogLevel.Debug && (!mainConfig.Data.DebugMode && !Debugger.IsAttached))
|
||||
return;
|
||||
|
||||
string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
|
||||
Debug.WriteLine(logMessage);
|
||||
_logEntries.Add(new LogEntry(level, message));
|
||||
|
||||
+31
-269
@@ -1,23 +1,33 @@
|
||||
using OpenCvSharp;
|
||||
using System.Drawing.Imaging;
|
||||
using Spectrum.Detection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Spectrum
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static Rectangle bounds = new Rectangle(0, 0, 0, 0);
|
||||
static Renderer? renderer = null;
|
||||
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");
|
||||
public static long iterationCount = 0;
|
||||
public static long totalTime = 0;
|
||||
private static DetectionManager? detectionManager;
|
||||
public static CaptureManager SharedCaptureManager { get; } = new CaptureManager();
|
||||
|
||||
|
||||
static void Main()
|
||||
{
|
||||
Thread renderThread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
renderer = new Renderer();
|
||||
renderer = new Renderer(SharedCaptureManager);
|
||||
bool dxok = SharedCaptureManager.TryInitializeDirectX();
|
||||
if (!dxok)
|
||||
{
|
||||
LogManager.Log("Failed to initialize DirectX. Falling back to gdi.", LogManager.LogLevel.Warning);
|
||||
mainConfig.Data.CaptureMethod = CaptureMethod.GDI;
|
||||
}
|
||||
renderer.Run();
|
||||
LogManager.Log("Renderer started successfully.", LogManager.LogLevel.Info);
|
||||
}
|
||||
@@ -28,28 +38,25 @@ namespace Spectrum
|
||||
});
|
||||
renderThread.Start();
|
||||
|
||||
string[] dirs = { "bin", "bin/dataset", "bin/dataset/images", "bin/dataset/labels", "bin/logs", "bin/configs" };
|
||||
foreach (var dir in dirs)
|
||||
{
|
||||
if (!Directory.Exists(dir))
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
LogManager.Log($"Created directory: {dir}", LogManager.LogLevel.Info);
|
||||
}
|
||||
}
|
||||
|
||||
var screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||
mainConfig.LoadConfig();
|
||||
mainConfig.StartFileWatcher();
|
||||
|
||||
var screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||
|
||||
if (mainConfig.Data.ShowDetectionWindow)
|
||||
{
|
||||
Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize);
|
||||
Cv2.WaitKey(1);
|
||||
}
|
||||
if (mainConfig.Data.AutoLabel)
|
||||
{
|
||||
AutoLabeling.StartLabeling();
|
||||
}
|
||||
|
||||
Directory.CreateDirectory("bin");
|
||||
Directory.CreateDirectory("bin/dataset");
|
||||
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)));
|
||||
@@ -59,260 +66,15 @@ namespace Spectrum
|
||||
mainConfig.LoadConfig(true);
|
||||
}
|
||||
|
||||
while (true)
|
||||
Thread.Sleep(1000);
|
||||
|
||||
if (renderer == null)
|
||||
{
|
||||
if (SystemHelper.GetAsyncKeyState((int)mainConfig.Data.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);
|
||||
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
|
||||
Mat drawing = mat.Clone();
|
||||
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV);
|
||||
Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat);
|
||||
Cv2.Dilate(mat, mat, null, iterations: 2);
|
||||
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary);
|
||||
|
||||
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
|
||||
|
||||
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 100).ToArray();
|
||||
|
||||
var mergedContours = MergeOverlappingContours(filteredContours);
|
||||
|
||||
var processedContours = mergedContours.Select(ShrinkWideContour).ToArray();
|
||||
|
||||
if (processedContours.Length > 0)
|
||||
{
|
||||
int refX = bounds.X + bounds.Width / 2;
|
||||
int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent);
|
||||
|
||||
double minDist = double.MaxValue;
|
||||
OpenCvSharp.Point[]? closestContour = null;
|
||||
int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0;
|
||||
|
||||
foreach (var contour in processedContours)
|
||||
{
|
||||
int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
|
||||
foreach (var point in contour)
|
||||
{
|
||||
if (point.X < minX) minX = point.X;
|
||||
if (point.Y < minY) minY = point.Y;
|
||||
if (point.X > maxX) maxX = point.X;
|
||||
if (point.Y > maxY) maxY = point.Y;
|
||||
}
|
||||
int centerX = (minX + maxX) / 2;
|
||||
int centerY = (minY + maxY) / 2;
|
||||
|
||||
int absCenterX = centerX + bounds.X;
|
||||
int absCenterY = centerY + bounds.Y;
|
||||
double dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2));
|
||||
|
||||
if (dist < minDist)
|
||||
{
|
||||
minDist = dist;
|
||||
closestContour = contour;
|
||||
bestMinX = minX;
|
||||
bestMinY = minY;
|
||||
bestMaxX = maxX;
|
||||
bestMaxY = maxY;
|
||||
LogManager.Log("Renderer failed to initialize. Exiting application.", LogManager.LogLevel.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (renderer != null && mainConfig.Data.DrawDetections)
|
||||
{
|
||||
var _rect = new Rectangle(
|
||||
minX + bounds.X,
|
||||
minY + bounds.Y,
|
||||
(maxX - minX + 1),
|
||||
(maxY - minY + 1)
|
||||
);
|
||||
renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
if (closestContour != null)
|
||||
{
|
||||
int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent));
|
||||
int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent));
|
||||
int targetX = groupX + bounds.X;
|
||||
int targetY = groupY + bounds.Y;
|
||||
|
||||
if (mainConfig.Data.AutoLabel)
|
||||
{
|
||||
AutoLabeling.AddToQueue(drawing, bounds, processedContours);
|
||||
AutoLabeling.AddBackgroundImage(drawing, true);
|
||||
}
|
||||
if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData)
|
||||
{
|
||||
AutoLabeling.AddBackgroundImage(drawing, false);
|
||||
}
|
||||
|
||||
if (mainConfig.Data.EnableAim)
|
||||
{
|
||||
InputManager.MoveMouse(new System.Drawing.Point(targetX, targetY));
|
||||
}
|
||||
|
||||
if (mainConfig.Data.ShowDetectionWindow)
|
||||
{
|
||||
Cv2.Rectangle(drawing, new OpenCvSharp.Point(bestMinX, bestMinY), new OpenCvSharp.Point(bestMaxX, bestMaxY), Scalar.Blue, 2);
|
||||
Cv2.ImShow("Spectrum Detection", drawing);
|
||||
Cv2.WaitKey(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (mainConfig.Data.ShowDetectionWindow || mainConfig.Data.CollectData)
|
||||
{
|
||||
Cv2.ImShow("Spectrum Detection", drawing);
|
||||
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
|
||||
{
|
||||
if (mainConfig.Data.ShowDetectionWindow)
|
||||
{
|
||||
Cv2.WaitKey(1);
|
||||
}
|
||||
else if (!mainConfig.Data.ShowDetectionWindow)
|
||||
{
|
||||
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)
|
||||
{
|
||||
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
|
||||
using (Graphics g = Graphics.FromImage(bitmap))
|
||||
{
|
||||
g.CopyFromScreen(bounds.Location, System.Drawing.Point.Empty, bounds.Size);
|
||||
}
|
||||
return bitmap;
|
||||
detectionManager = new DetectionManager(renderer);
|
||||
}
|
||||
}
|
||||
public static class SystemHelper
|
||||
|
||||
+611
-63
@@ -1,9 +1,13 @@
|
||||
using ClickableTransparentOverlay;
|
||||
using ImGuiNET;
|
||||
using OpenCvSharp;
|
||||
using Spectrum.Input;
|
||||
using Spectrum.Input.InputLibraries.Makcu;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using System.Globalization;
|
||||
using Spectrum.Detection;
|
||||
|
||||
namespace Spectrum
|
||||
{
|
||||
@@ -12,18 +16,22 @@ namespace Spectrum
|
||||
static (int width, int height) screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||
private List<Action<ImDrawListPtr>> drawCommands = new List<Action<ImDrawListPtr>>();
|
||||
private readonly object drawCommandsLock = new object();
|
||||
private readonly CaptureManager _captureManager;
|
||||
|
||||
private bool _vsync = true;
|
||||
private int _fpsLimit = 240;
|
||||
private Keys _pendingKeybind = Keys.None;
|
||||
private bool _waitingForKeybind = false;
|
||||
private Task? _keybindTask = null;
|
||||
private readonly Dictionary<string, bool> _waitingForKeybind = new();
|
||||
private readonly Dictionary<string, Keys> _pendingKeybind = new();
|
||||
private readonly Dictionary<string, Task?> _keybindTask = new();
|
||||
private readonly ConcurrentQueue<Keys> _keybindResults = new();
|
||||
private ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||
private ConfigManager<ColorData> colorConfig = Program.colorConfig;
|
||||
private string ColorName = "New Color";
|
||||
private static bool scrollToBottom = true;
|
||||
|
||||
public Renderer() : base("Spectrum", screenSize.width, screenSize.width)
|
||||
public Renderer(CaptureManager captureManager) : base("Spectrum", screenSize.width, screenSize.width)
|
||||
{
|
||||
_captureManager = captureManager;
|
||||
VSync = _vsync;
|
||||
FPSLimit = _fpsLimit;
|
||||
ImGui.CreateContext();
|
||||
@@ -40,9 +48,9 @@ namespace Spectrum
|
||||
|
||||
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.SetNextWindowSize(new Vector2(700, 500), ImGuiCond.FirstUseEver);
|
||||
ImGui.SetNextWindowPos(new Vector2(screenSize.width / 2 - 350, screenSize.height / 2 - 250), ImGuiCond.FirstUseEver);
|
||||
ImGui.SetNextWindowSizeConstraints(new Vector2(700, 500), new Vector2(float.MaxValue, float.MaxValue));
|
||||
|
||||
ImGui.Begin("Spectrum", ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoTitleBar);
|
||||
ImGui.Text("Spectrum");
|
||||
@@ -57,6 +65,10 @@ namespace Spectrum
|
||||
|
||||
ImGui.BeginTabBar("##tabs");
|
||||
if (ImGui.BeginTabItem("Aiming"))
|
||||
{
|
||||
ImGuiExtensions.BeginPaneGroup("Aiming Panes", 2, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f);
|
||||
|
||||
if (ImGuiExtensions.BeginPane("Aim Assist"))
|
||||
{
|
||||
bool enableAiming = mainConfig.Data.EnableAim;
|
||||
if (ImGui.Checkbox("##Enable Aiming", ref enableAiming))
|
||||
@@ -65,31 +77,32 @@ namespace Spectrum
|
||||
}
|
||||
|
||||
ImGui.SameLine();
|
||||
if (!_waitingForKeybind)
|
||||
ImGui.Text("Enable Aiming");
|
||||
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(mainConfig.Data.Keybind.ToString()).X);
|
||||
if (!_waitingForKeybind.GetValueOrDefault("Aiming", false))
|
||||
{
|
||||
if (ImGui.Button(mainConfig.Data.Keybind.ToString()))
|
||||
if (ImGui.Button($"{mainConfig.Data.Keybind.ToString()}###AimKeybind"))
|
||||
{
|
||||
_waitingForKeybind = true;
|
||||
_pendingKeybind = Keys.None;
|
||||
_keybindTask = Task.Run(async () =>
|
||||
_waitingForKeybind["Aiming"] = true;
|
||||
_pendingKeybind["Aiming"] = Keys.None;
|
||||
_keybindTask["Aiming"] = Task.Run(async () =>
|
||||
{
|
||||
var key = await InputManager.ListenForNextKeyOrMouseAsync();
|
||||
_pendingKeybind = key;
|
||||
_pendingKeybind["Aiming"] = key;
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ImGui.Button("Listening...");
|
||||
if (_pendingKeybind != Keys.None)
|
||||
ImGui.Button("Listening... ###AimListening");
|
||||
if (_pendingKeybind.GetValueOrDefault("Aiming", Keys.None) != Keys.None)
|
||||
{
|
||||
mainConfig.Data.Keybind = _pendingKeybind;
|
||||
_pendingKeybind = Keys.None;
|
||||
_waitingForKeybind = false;
|
||||
mainConfig.Data.Keybind = _pendingKeybind["Aiming"];
|
||||
_pendingKeybind["Aiming"] = Keys.None;
|
||||
_waitingForKeybind["Aiming"] = false;
|
||||
}
|
||||
}
|
||||
ImGui.SameLine();
|
||||
ImGui.Text("Enable Aiming");
|
||||
|
||||
bool closestToMouse = mainConfig.Data.ClosestToMouse;
|
||||
if (ImGui.Checkbox("Closest to Mouse", ref closestToMouse))
|
||||
@@ -98,7 +111,7 @@ namespace Spectrum
|
||||
}
|
||||
|
||||
float sensitivity = (float)mainConfig.Data.Sensitivity;
|
||||
if (ImGui.SliderFloat("Sensitivity", ref sensitivity, 0.1f, 2.0f, "%.1f"))
|
||||
if (ImGuiExtensions.SliderFill("Sensitivity", ref sensitivity, 0.1f, 2.0f, "%.1f"))
|
||||
{
|
||||
mainConfig.Data.Sensitivity = sensitivity;
|
||||
}
|
||||
@@ -110,13 +123,18 @@ namespace Spectrum
|
||||
mainConfig.Data.EmaSmoothening = EmaSmoothening;
|
||||
}
|
||||
|
||||
if (ImGui.SliderFloat("Ema Smoothening Factor", ref EmaSmootheningFactor, 0.01f, 1.0f, "%.2f"))
|
||||
if (EmaSmoothening)
|
||||
{
|
||||
if (ImGuiExtensions.SliderFill("Ema Smoothening Factor", ref EmaSmootheningFactor, 0.01f, 1.0f))
|
||||
{
|
||||
mainConfig.Data.EmaSmootheningFactor = EmaSmootheningFactor;
|
||||
}
|
||||
}
|
||||
|
||||
ImGui.TextUnformatted("Movement Type");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
MovementType AimPath = mainConfig.Data.AimMovementType;
|
||||
if (ImGui.BeginCombo("Movement Type", AimPath.ToString()))
|
||||
if (ImGui.BeginCombo("##Movement Type", AimPath.ToString()))
|
||||
{
|
||||
foreach (MovementType type in Enum.GetValues(typeof(MovementType)))
|
||||
{
|
||||
@@ -133,14 +151,14 @@ namespace Spectrum
|
||||
ImGui.EndCombo();
|
||||
}
|
||||
|
||||
int YOffset = (int)(mainConfig.Data.YOffsetPercent * 100);
|
||||
if (ImGui.SliderInt("Y Offset (%)", ref YOffset, 0, 100, "%d%%"))
|
||||
float YOffset = (int)(mainConfig.Data.YOffsetPercent * 100);
|
||||
if (ImGuiExtensions.SliderFill("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%%"))
|
||||
float XOffset = (int)(mainConfig.Data.XOffsetPercent * 100);
|
||||
if (ImGuiExtensions.SliderFill("X Offset (%)", ref XOffset, 0, 100, "%d%%"))
|
||||
{
|
||||
mainConfig.Data.XOffsetPercent = ((double)XOffset / 100);
|
||||
}
|
||||
@@ -152,19 +170,122 @@ namespace Spectrum
|
||||
{
|
||||
mainConfig.Data.DrawFOV = DrawFOV;
|
||||
}
|
||||
|
||||
ImGui.SameLine();
|
||||
ImGui.Text("Draw FOV");
|
||||
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12);
|
||||
Vector4 FOVColor = mainConfig.Data.FOVColor;
|
||||
if (ImGui.ColorEdit4("FOV Color", ref FOVColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
{
|
||||
mainConfig.Data.FOVColor = FOVColor;
|
||||
}
|
||||
|
||||
bool DrawDetections = mainConfig.Data.DrawDetections;
|
||||
if (ImGui.Checkbox("##Draw Detections", ref DrawDetections))
|
||||
{
|
||||
mainConfig.Data.DrawDetections = DrawDetections;
|
||||
}
|
||||
ImGui.SameLine();
|
||||
ImGui.Text("Draw FOV");
|
||||
ImGui.Text("Draw Detections");
|
||||
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12);
|
||||
Vector4 DetectionColor = mainConfig.Data.DetectionColor;
|
||||
if (ImGui.ColorEdit4("Draw Color", ref DetectionColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
{
|
||||
mainConfig.Data.DetectionColor = DetectionColor;
|
||||
}
|
||||
|
||||
if (DrawFOV)
|
||||
{
|
||||
ImGui.TextUnformatted("FOV Type");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
FovType fovType = mainConfig.Data.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;
|
||||
}
|
||||
if (isSelected)
|
||||
{
|
||||
ImGui.SetItemDefaultFocus();
|
||||
}
|
||||
}
|
||||
ImGui.EndCombo();
|
||||
}
|
||||
}
|
||||
ImGuiExtensions.EndPane();
|
||||
}
|
||||
|
||||
if (ImGuiExtensions.BeginPane("Triggerbot"))
|
||||
{
|
||||
bool triggerBot = mainConfig.Data.TriggerBot;
|
||||
if (ImGui.Checkbox("Enabled", ref triggerBot))
|
||||
{
|
||||
mainConfig.Data.TriggerBot = triggerBot;
|
||||
}
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(mainConfig.Data.TriggerKey.ToString()).X);
|
||||
if (!_waitingForKeybind.GetValueOrDefault("Trigger Key", false))
|
||||
{
|
||||
if (ImGui.Button($"{mainConfig.Data.TriggerKey.ToString()}###TriggerKeybind"))
|
||||
{
|
||||
_waitingForKeybind["Trigger Key"] = true;
|
||||
_pendingKeybind["Trigger Key"] = Keys.None;
|
||||
_keybindTask["Trigger Key"] = Task.Run(async () =>
|
||||
{
|
||||
var key = await InputManager.ListenForNextKeyOrMouseAsync();
|
||||
_pendingKeybind["Trigger Key"] = key;
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (triggerBot)
|
||||
{
|
||||
ImGui.Button("Listening... ###TriggerListening");
|
||||
if (_pendingKeybind.GetValueOrDefault("Trigger Key", Keys.None) != Keys.None)
|
||||
{
|
||||
mainConfig.Data.TriggerKey = _pendingKeybind["Trigger Key"];
|
||||
_pendingKeybind["Trigger Key"] = Keys.None;
|
||||
_waitingForKeybind["Trigger Key"] = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (triggerBot)
|
||||
{
|
||||
int triggerDelay = mainConfig.Data.TriggerDelay;
|
||||
if (ImGuiExtensions.SliderFill("Trigger Delay (ms)", ref triggerDelay, 1, 1000))
|
||||
{
|
||||
mainConfig.Data.TriggerDelay = triggerDelay;
|
||||
}
|
||||
|
||||
int triggerRadius = mainConfig.Data.TriggerRadius;
|
||||
if (ImGuiExtensions.SliderFill("Trigger Radius (px)", ref triggerRadius, 1, 100))
|
||||
{
|
||||
mainConfig.Data.TriggerRadius = triggerRadius;
|
||||
}
|
||||
|
||||
int triggerDuration = mainConfig.Data.TriggerDuration;
|
||||
if (ImGuiExtensions.SliderFill("Trigger Duration (ms)", ref triggerDuration, 1, 1000))
|
||||
{
|
||||
mainConfig.Data.TriggerDuration = triggerDuration;
|
||||
}
|
||||
}
|
||||
ImGuiExtensions.EndPane();
|
||||
}
|
||||
|
||||
ImGuiExtensions.EndPaneGroup();
|
||||
|
||||
ImGui.EndTabItem();
|
||||
}
|
||||
|
||||
if (ImGui.BeginTabItem("Detection"))
|
||||
{
|
||||
ImGuiExtensions.BeginPaneGroup("Detection Panes", 1, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f);
|
||||
|
||||
if (ImGuiExtensions.BeginPane("Detection Settings"))
|
||||
{
|
||||
int ImageWidth = mainConfig.Data.ImageWidth;
|
||||
if (ImGui.InputInt("Image Width", ref ImageWidth, 1, screenSize.width))
|
||||
@@ -214,6 +335,7 @@ namespace Spectrum
|
||||
mainConfig.Data.SelectedColor = color.Name;
|
||||
mainConfig.Data.UpperHSV = color.Upper;
|
||||
mainConfig.Data.LowerHSV = color.Lower;
|
||||
ColorName = color.Name;
|
||||
}
|
||||
if (isSelected)
|
||||
{
|
||||
@@ -224,29 +346,115 @@ namespace Spectrum
|
||||
}
|
||||
}
|
||||
|
||||
bool DrawDetections = mainConfig.Data.DrawDetections;
|
||||
if (ImGui.Checkbox("##Draw Detections", ref DrawDetections))
|
||||
ImGui.InputText("##ColorNameInput", ref ColorName, 32);
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Delete Color"))
|
||||
{
|
||||
mainConfig.Data.DrawDetections = DrawDetections;
|
||||
if (colors.Any(c => c.Name.Equals(mainConfig.Data.SelectedColor, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
colors.RemoveAll(c => c.Name.Equals(mainConfig.Data.SelectedColor, StringComparison.OrdinalIgnoreCase));
|
||||
colorConfig.SaveConfig();
|
||||
mainConfig.Data.SelectedColor = "Arsenal [Magenta]";
|
||||
mainConfig.Data.UpperHSV = new Scalar(150, 255, 229);
|
||||
mainConfig.Data.LowerHSV = new Scalar(150, 255, 229);
|
||||
}
|
||||
else
|
||||
{
|
||||
LogManager.Log($"Color '{mainConfig.Data.SelectedColor}' does not exist.", LogManager.LogLevel.Warning);
|
||||
}
|
||||
}
|
||||
ImGui.SameLine();
|
||||
Vector4 DetectionColor = mainConfig.Data.DetectionColor;
|
||||
if (ImGui.ColorEdit4("Draw Color", ref DetectionColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
if (ImGui.Button("Save Color"))
|
||||
{
|
||||
mainConfig.Data.DetectionColor = DetectionColor;
|
||||
var color = new ColorInfo(ColorName, mainConfig.Data.UpperHSV, mainConfig.Data.LowerHSV);
|
||||
if (!string.IsNullOrEmpty(ColorName))
|
||||
{
|
||||
colors.Add(color);
|
||||
colorConfig.SaveConfig();
|
||||
mainConfig.Data.SelectedColor = ColorName;
|
||||
}
|
||||
ImGui.SameLine();
|
||||
ImGui.Text("Draw Detections");
|
||||
else
|
||||
{
|
||||
LogManager.Log($"Colorname is empty.", LogManager.LogLevel.Warning);
|
||||
}
|
||||
}
|
||||
}
|
||||
ImGuiExtensions.EndPane();
|
||||
|
||||
ImGui.EndTabItem();
|
||||
}
|
||||
|
||||
if (ImGui.BeginTabItem("Misc."))
|
||||
if (ImGui.BeginTabItem("Settings"))
|
||||
{
|
||||
bool ShowDetectionWindow = mainConfig.Data.ShowDetectionWindow;
|
||||
if (ImGui.Checkbox("Show Detection Window", ref ShowDetectionWindow))
|
||||
ImGuiExtensions.BeginPaneGroup("Settings Panes", 2, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f);
|
||||
|
||||
if (ImGuiExtensions.BeginPane("Settings"))
|
||||
{
|
||||
mainConfig.Data.ShowDetectionWindow = ShowDetectionWindow;
|
||||
ImGui.TextUnformatted("Movement Method");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
MovementMethod movementMethod = mainConfig.Data.MovementMethod;
|
||||
if (ImGui.BeginCombo("##Movement Method", movementMethod.ToString()))
|
||||
{
|
||||
foreach (MovementMethod method in Enum.GetValues(typeof(MovementMethod)))
|
||||
{
|
||||
bool isSelected = (method == movementMethod);
|
||||
if (ImGui.Selectable(method.ToString(), isSelected))
|
||||
{
|
||||
mainConfig.Data.MovementMethod = method;
|
||||
switch (method)
|
||||
{
|
||||
case MovementMethod.Makcu:
|
||||
{
|
||||
var ok = MakcuMain.Load().GetAwaiter().GetResult();
|
||||
if (!ok)
|
||||
{
|
||||
LogManager.Log("Makcu failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
|
||||
mainConfig.Data.MovementMethod = MovementMethod.MouseEvent;
|
||||
MakcuMain.Unload();
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
MakcuMain.Unload();
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isSelected)
|
||||
{
|
||||
ImGui.SetItemDefaultFocus();
|
||||
}
|
||||
}
|
||||
ImGui.EndCombo();
|
||||
}
|
||||
|
||||
ImGui.TextUnformatted("Capture Method");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
CaptureMethod captureMethod = mainConfig.Data.CaptureMethod;
|
||||
if (ImGui.BeginCombo("##Capture Method", captureMethod.ToString()))
|
||||
{
|
||||
foreach (CaptureMethod method in Enum.GetValues(typeof(CaptureMethod)))
|
||||
{
|
||||
bool isSelected = (method == captureMethod);
|
||||
if (ImGui.Selectable(method.ToString(), isSelected))
|
||||
{
|
||||
CaptureMethod _method = method;
|
||||
if (method == CaptureMethod.DirectX)
|
||||
{
|
||||
bool dxOk = _captureManager.TryInitializeDirectX();
|
||||
if (!dxOk)
|
||||
{
|
||||
LogManager.Log("DirectX capture failed to initialize. Falling back to GDI.", LogManager.LogLevel.Warning);
|
||||
_method = CaptureMethod.GDI;
|
||||
}
|
||||
}
|
||||
mainConfig.Data.CaptureMethod = _method;
|
||||
}
|
||||
if (isSelected)
|
||||
{
|
||||
ImGui.SetItemDefaultFocus();
|
||||
}
|
||||
}
|
||||
ImGui.EndCombo();
|
||||
}
|
||||
|
||||
bool CollectData = mainConfig.Data.CollectData;
|
||||
@@ -264,27 +472,63 @@ namespace Spectrum
|
||||
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"))
|
||||
bool DebugMode = mainConfig.Data.DebugMode;
|
||||
if (ImGui.Checkbox("Debug Mode", ref DebugMode))
|
||||
{
|
||||
mainConfig.Data.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;
|
||||
if (ImGui.InputInt("##Background Image Interval", ref BackgroundImageInterval, 1, 1000))
|
||||
{
|
||||
if (BackgroundImageInterval < 1)
|
||||
BackgroundImageInterval = 1;
|
||||
else if (BackgroundImageInterval > 1000)
|
||||
BackgroundImageInterval = 1000;
|
||||
|
||||
mainConfig.Data.BackgroundImageInterval = BackgroundImageInterval;
|
||||
}
|
||||
|
||||
if (!_waitingForKeybind.GetValueOrDefault("Menu Key", false))
|
||||
{
|
||||
if (ImGui.Button(mainConfig.Data.MenuKey.ToString()))
|
||||
{
|
||||
_waitingForKeybind["Menu Key"] = true;
|
||||
_pendingKeybind["Menu Key"] = Keys.None;
|
||||
_keybindTask["Menu Key"] = Task.Run(async () =>
|
||||
{
|
||||
var key = await InputManager.ListenForNextKeyOrMouseAsync();
|
||||
_pendingKeybind["Menu Key"] = key;
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
ImGui.Button("Listening...");
|
||||
if (_pendingKeybind.GetValueOrDefault("Menu Key", Keys.None) != Keys.None)
|
||||
{
|
||||
mainConfig.Data.MenuKey = _pendingKeybind["Menu Key"];
|
||||
_pendingKeybind["Menu Key"] = Keys.None;
|
||||
_waitingForKeybind["Menu Key"] = false;
|
||||
}
|
||||
}
|
||||
ImGui.SameLine();
|
||||
ImGui.Text("Menu Keybind");
|
||||
|
||||
if (ImGui.Button("Save Configs"))
|
||||
{
|
||||
@@ -309,20 +553,29 @@ namespace Spectrum
|
||||
LogManager.Log($"Directory doesnt exist: {folderPath}", LogManager.LogLevel.Error);
|
||||
}
|
||||
}
|
||||
ImGui.SeparatorText("Logs");
|
||||
ImGuiExtensions.EndPane();
|
||||
}
|
||||
|
||||
ImGui.BeginChild("Logs", new Vector2(0, -34));
|
||||
ImGui.Dummy(new Vector2(0, 4));
|
||||
if (ImGuiExtensions.BeginPane("Logs"))
|
||||
{
|
||||
ImGui.BeginChild("Logs", new Vector2(0, -34), ImGuiChildFlags.None, ImGuiWindowFlags.HorizontalScrollbar);
|
||||
|
||||
float scrollY = ImGui.GetScrollY();
|
||||
float scrollMaxY = ImGui.GetScrollMaxY();
|
||||
bool isAtBottom = (scrollY >= scrollMaxY - 1.0f);
|
||||
|
||||
var _LogEntries = LogManager.LogEntries.ToList();
|
||||
var _LogEntries = LogManager.LogEntries.ToArray();
|
||||
foreach (var log in _LogEntries)
|
||||
{
|
||||
ImGui.Indent(8);
|
||||
ImGui.Text(log.ToString());
|
||||
ImGui.Unindent(8);
|
||||
}
|
||||
|
||||
if (scrollToBottom || isAtBottom)
|
||||
{
|
||||
ImGui.SetScrollHereY(1.0f);
|
||||
scrollToBottom = false;
|
||||
}
|
||||
|
||||
ImGui.Dummy(new Vector2(0, 4));
|
||||
ImGui.EndChild();
|
||||
ImGui.Dummy(new Vector2(0, 1));
|
||||
|
||||
@@ -344,6 +597,10 @@ namespace Spectrum
|
||||
{
|
||||
LogManager.OpenLogFolder();
|
||||
}
|
||||
ImGuiExtensions.EndPane();
|
||||
}
|
||||
|
||||
|
||||
|
||||
ImGui.EndTabItem();
|
||||
}
|
||||
@@ -361,6 +618,8 @@ namespace Spectrum
|
||||
var drawList = ImGui.GetWindowDrawList();
|
||||
|
||||
if (mainConfig.Data.DrawFOV)
|
||||
{
|
||||
if (mainConfig.Data.FOVType == FovType.Rectangle)
|
||||
{
|
||||
AddRect(new Rectangle(
|
||||
((screenSize.width - mainConfig.Data.ImageWidth) / 2) - 1,
|
||||
@@ -369,6 +628,11 @@ namespace Spectrum
|
||||
mainConfig.Data.ImageHeight + 2
|
||||
), mainConfig.Data.FOVColor);
|
||||
}
|
||||
else if (mainConfig.Data.FOVType == FovType.Circle)
|
||||
{
|
||||
AddCircle(new Vector2(screenSize.width / 2, screenSize.height / 2), mainConfig.Data.ImageWidth / 2, mainConfig.Data.FOVColor, 100, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
List<Action<ImDrawListPtr>> _drawCommands;
|
||||
lock (drawCommandsLock)
|
||||
@@ -403,6 +667,8 @@ namespace Spectrum
|
||||
style.WindowPadding = new Vector2(8, 8);
|
||||
style.FramePadding = new Vector2(6, 3);
|
||||
style.ItemSpacing = new Vector2(8, 4);
|
||||
style.ScrollbarRounding = 6.0f;
|
||||
style.ScrollbarSize = 12.0f;
|
||||
|
||||
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);
|
||||
@@ -459,7 +725,10 @@ namespace Spectrum
|
||||
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);
|
||||
|
||||
|
||||
colors[(int)ImGuiCol.ScrollbarBg] = new Vector4(0.15f, 0.15f, 0.18f, 1.0f);
|
||||
colors[(int)ImGuiCol.ScrollbarGrab] = new Vector4(0.31f, 0.31f, 0.34f, 1.0f);
|
||||
colors[(int)ImGuiCol.ScrollbarGrabHovered] = new Vector4(0.43f, 0.43f, 0.45f, 1.0f);
|
||||
colors[(int)ImGuiCol.ScrollbarGrabActive] = new Vector4(0.50f, 0.50f, 0.52f, 1.0f);
|
||||
}
|
||||
public void AddRect(Rectangle rect, Vector4 color, float thickness = 1.0f)
|
||||
{
|
||||
@@ -488,16 +757,23 @@ namespace Spectrum
|
||||
}
|
||||
}
|
||||
|
||||
public void AddText(Vector2 pos, Vector4 color, string text)
|
||||
public void AddText(Vector2 pos, Vector4 color, string text, int fontSize = 16)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
return;
|
||||
lock (drawCommandsLock)
|
||||
{
|
||||
drawCommands.Add(drawList => drawList.AddText(pos, ColorFromVector4(color), text));
|
||||
drawCommands.Add(drawList => drawList.AddText(ImGui.GetFont(), fontSize, pos, ColorFromVector4(color), text));
|
||||
}
|
||||
}
|
||||
|
||||
public Vector2 GetTextWidth(string text, int fontSize = 16)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
return new Vector2(0, 0);
|
||||
return ImGui.CalcTextSize(text, 0, text.Length, fontSize);
|
||||
}
|
||||
|
||||
private static uint ColorFromVector4(Vector4 color)
|
||||
{
|
||||
int r = (int)(Math.Clamp(color.X, 0f, 1f) * 255.0f);
|
||||
@@ -507,4 +783,276 @@ namespace Spectrum
|
||||
return (uint)((a << 24) | (b << 16) | (g << 8) | r);
|
||||
}
|
||||
}
|
||||
public static class ImGuiExtensions
|
||||
{
|
||||
private static readonly Dictionary<string, string> _sliderEditBuffers = new();
|
||||
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<PaneGroupState> _paneGroups = new();
|
||||
private static readonly Stack<bool> _paneInnerStack = new();
|
||||
|
||||
public static void BeginPaneGroup(string id, int count, float spacing = 12f,
|
||||
Vector2? padding = null,
|
||||
ImGuiChildFlags childFlags = ImGuiChildFlags.None,
|
||||
ImGuiWindowFlags windowFlags = ImGuiWindowFlags.None,
|
||||
float height = 0f)
|
||||
{
|
||||
if (count < 1) count = 1;
|
||||
var avail = ImGui.GetContentRegionAvail();
|
||||
float width = (avail.X - spacing * (count - 1)) / count;
|
||||
_paneGroups.Push(new PaneGroupState
|
||||
{
|
||||
Id = id,
|
||||
Count = count,
|
||||
Spacing = spacing,
|
||||
Index = 0,
|
||||
Width = width,
|
||||
Padding = padding,
|
||||
ChildFlags = childFlags,
|
||||
WindowFlags = windowFlags,
|
||||
Height = height <= 0 ? avail.Y : height
|
||||
});
|
||||
}
|
||||
|
||||
public static bool BeginPane(string localId, bool showHeader = true)
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,9 @@
|
||||
<PublishAot>False</PublishAot>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<UseWindowsForms>True</UseWindowsForms>
|
||||
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
|
||||
<TargetFrameworks></TargetFrameworks>
|
||||
<Platforms>AnyCPU;x64</Platforms>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -22,8 +25,9 @@
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.10" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="9.0.7" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
|
||||
<PackageReference Include="System.Drawing.Common" Version="9.0.8" />
|
||||
<PackageReference Include="System.IO.Ports" Version="9.0.8" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -7,13 +7,19 @@ EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|x64.Build.0 = Debug|x64
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|x64.ActiveCfg = Release|x64
|
||||
{C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
Reference in New Issue
Block a user