This commit is contained in:
TinyHerm committed 2026-11-24 23:40:08 +03:00
commit 1c7a8cf25f
579 files changed
+83196

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace VibranceHud.Theming;
public sealed class AnimatedPicture : IDisposable
{
public const double MinFrameSeconds = 1.0 / 30.0;
public const double EarlyWakeSeconds = 0.002;
private const int PropertyTagFrameDelay = 20736;
private readonly MemoryStream _bytes;
private readonly Image _image;
private readonly double[] _delays;
private int _index;
private double _owed;
public int Count => _delays.Length;
public int Index => _index;
public double CurrentSeconds => _delays[_index];
public double SecondsUntilNext => Math.Max(0.0, _delays[_index] - _owed);
public Image Current
{
get
{
_image.SelectActiveFrame(FrameDimension.Time, _index);
return _image;
}
}
private AnimatedPicture(MemoryStream bytes, Image image, double[] delays)
{
_bytes = bytes;
_image = image;
_delays = delays;
}
public static AnimatedPicture? From(byte[] fileBytes)
{
MemoryStream memoryStream = null;
Image image = null;
try
{
memoryStream = new MemoryStream(fileBytes, writable: false);
image = Image.FromStream(memoryStream);
int num;
try
{
num = image.GetFrameCount(FrameDimension.Time);
}
catch
{
num = 1;
}
if (num <= 1)
{
image.Dispose();
memoryStream.Dispose();
return null;
}
return new AnimatedPicture(memoryStream, image, ReadDelays(image, num));
}
catch
{
image?.Dispose();
memoryStream?.Dispose();
return null;
}
}
private static double[] ReadDelays(Image image, int count)
{
double[] array = new double[count];
for (int i = 0; i < count; i++)
{
array[i] = 1.0 / 30.0;
}
try
{
byte[] array2 = image.GetPropertyItem(20736)?.Value;
if (array2 != null)
{
for (int j = 0; j < count && (j + 1) * 4 <= array2.Length; j++)
{
int num = BitConverter.ToInt32(array2, j * 4);
array[j] = Math.Max(1.0 / 30.0, (double)num / 100.0);
}
}
}
catch
{
}
return array;
}
public bool Advance(double seconds)
{
if (seconds <= 0.0)
{
return false;
}
_owed += seconds;
double num = _delays[_index];
if (_owed + 0.002 < num)
{
return false;
}
_owed -= num;
_index = (_index + 1) % _delays.Length;
_owed = Math.Clamp(_owed, -0.002, _delays[_index] / 2.0);
return true;
}
public void DropBankedTime()
{
_owed = 0.0;
}
public void Dispose()
{
_image.Dispose();
_bytes.Dispose();
}
}
File diff suppressed because it is too large. Load diff
+190
View File
@@ -0,0 +1,190 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace VibranceHud.Theming;
internal sealed class BackgroundFramePump : IDisposable
{
internal const int ParkedIntervalMs = 1000;
internal const int SlowestFrameMs = 2000;
internal static Func<Form, bool> InFront = DefaultInFront;
private readonly Form _host;
private readonly Action _onPictureChanged;
private readonly Timer _timer = new Timer();
private readonly Stopwatch _clock = Stopwatch.StartNew();
private double _lastSeconds;
private bool _disposed;
private bool _movingOrSizing;
internal bool Ticking
{
get
{
if (!_disposed)
{
return _timer.Enabled;
}
return false;
}
}
internal int IntervalMs => _timer.Interval;
internal BackgroundFramePump(Form host, Action onPictureChanged)
{
_host = host;
_onPictureChanged = onPictureChanged;
_timer.Interval = 1000;
_timer.Tick += (object? _, EventArgs _) =>
{
Tick();
};
_host.Activated += Wake;
_host.Deactivate += Wake;
_host.VisibleChanged += Wake;
_host.Resize += Wake;
_host.HandleDestroyed += Wake;
_host.ResizeBegin += OnMoveOrSizeBegin;
_host.ResizeEnd += OnMoveOrSizeEnd;
_host.Disposed += OnHostDisposed;
Reassess();
}
private void Wake(object? sender, EventArgs e)
{
Reassess();
}
private void OnMoveOrSizeBegin(object? sender, EventArgs e)
{
_movingOrSizing = true;
Reassess();
}
private void OnMoveOrSizeEnd(object? sender, EventArgs e)
{
_movingOrSizing = false;
Reassess();
}
private void OnHostDisposed(object? sender, EventArgs e)
{
Dispose();
}
internal void Reassess()
{
if (_disposed)
{
return;
}
bool hasMotion = AppBackground.HasMotion;
bool flag = _host.IsDisposed || _host.Disposing;
bool flag2 = _host.Visible && _host.WindowState != FormWindowState.Minimized && !flag && _host.IsHandleCreated;
bool flag3 = BackgroundMotionPolicy.ShouldPlay(hasMotion, _host.Visible, _host.WindowState == FormWindowState.Minimized, flag2 && InFront(_host), AppBackground.GameIsRunning(), flag, AppBackground.ReducedMotion, _movingOrSizing);
bool motionAllowed = AppBackground.MotionAllowed;
AppBackground.SetMotionGate(flag3);
if (!flag3 && !_movingOrSizing)
{
AppBackground.ForgetKeptFrames();
}
if (flag3)
{
if (!motionAllowed)
{
_lastSeconds = _clock.Elapsed.TotalSeconds;
}
_timer.Interval = NextIntervalMs();
_timer.Start();
}
else if ((hasMotion & flag2) && InFront(_host) && !_movingOrSizing)
{
_timer.Interval = 1000;
_timer.Start();
}
else
{
_timer.Stop();
}
}
private int NextIntervalMs()
{
return BackgroundFrameRate.IntervalMs(AppBackground.SecondsUntilNextFrame, AppBackground.CurrentFrameSeconds, AppBackground.ComposeMsPerFrame, 2000);
}
private void ArmForTheNextFrame()
{
_timer.Interval = NextIntervalMs();
}
internal void Tick()
{
if (_disposed)
{
return;
}
double totalSeconds = _clock.Elapsed.TotalSeconds;
double seconds = Math.Min(totalSeconds - _lastSeconds, 0.5);
_lastSeconds = totalSeconds;
bool motionAllowed = AppBackground.MotionAllowed;
Reassess();
if (!AppBackground.MotionAllowed)
{
if (motionAllowed)
{
_onPictureChanged();
}
return;
}
bool flag = AppBackground.Advance(seconds);
ArmForTheNextFrame();
if (flag)
{
_onPictureChanged();
}
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
_host.Activated -= Wake;
_host.Deactivate -= Wake;
_host.VisibleChanged -= Wake;
_host.Resize -= Wake;
_host.HandleDestroyed -= Wake;
_host.ResizeBegin -= OnMoveOrSizeBegin;
_host.ResizeEnd -= OnMoveOrSizeEnd;
_host.Disposed -= OnHostDisposed;
_timer.Stop();
_timer.Dispose();
AppBackground.SetMotionGate(mayPlay: false);
AppBackground.ForgetKeptFrames();
}
}
private static bool DefaultInFront(Form host)
{
if (!host.IsHandleCreated)
{
return false;
}
return GetForegroundWindow() == host.Handle;
}
[DllImport("user32.dll")]
private static extern nint GetForegroundWindow();
}
@@ -0,0 +1,21 @@
using System;
namespace VibranceHud.Theming;
public static class BackgroundFrameRate
{
public const int ComposeShare = 4;
public static int IntervalMs(double frameSeconds, double lastComposeMs, int slowestMs)
{
double num = Math.Max(frameSeconds, 1.0 / 30.0);
return IntervalMs(num, num, lastComposeMs, slowestMs);
}
public static int IntervalMs(double untilNextSeconds, double frameSeconds, double lastComposeMs, int slowestMs)
{
double num = Math.Max(frameSeconds, 1.0 / 30.0) * 1000.0;
double num2 = Math.Max(0.0, lastComposeMs) * 4.0;
return (int)Math.Clamp(Math.Round(Math.Max(0.0, untilNextSeconds) * 1000.0 + Math.Max(0.0, num2 - num)), 1.0, Math.Max(1, slowestMs));
}
}
+114
View File
@@ -0,0 +1,114 @@
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
namespace VibranceHud.Theming;
public static class BackgroundMatte
{
public static readonly Color Black = Color.FromArgb(255, 0, 0, 0);
public static readonly Color White = Color.FromArgb(255, 255, 255, 255);
public static Color Default => Black;
public static bool NeedsOne(Image? image)
{
if (image == null)
{
return false;
}
PixelFormat pixelFormat = image.PixelFormat;
if ((pixelFormat & PixelFormat.Indexed) != 0)
{
ColorPalette palette;
try
{
palette = image.Palette;
}
catch
{
return false;
}
Color[] entries = palette.Entries;
foreach (Color color in entries)
{
if (color.A < byte.MaxValue)
{
return true;
}
}
return false;
}
if (!Image.IsAlphaPixelFormat(pixelFormat))
{
return false;
}
return AnyPixelSeesThrough(image);
}
public static bool NeedsOne(string path)
{
try
{
using FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
using Image image = Image.FromStream(stream);
return NeedsOne(image);
}
catch
{
return false;
}
}
private static bool AnyPixelSeesThrough(Image image)
{
Bitmap bitmap = null;
try
{
Bitmap bitmap2 = image as Bitmap;
if (bitmap2 == null || bitmap2.PixelFormat != PixelFormat.Format32bppArgb)
{
bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);
using (Graphics graphics = Graphics.FromImage(bitmap))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.DrawImage(image, 0, 0, image.Width, image.Height);
}
bitmap2 = bitmap;
}
Rectangle rect = new Rectangle(0, 0, bitmap2.Width, bitmap2.Height);
BitmapData bitmapData = bitmap2.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
try
{
byte[] array = new byte[bitmapData.Stride];
for (int i = 0; i < bitmapData.Height; i++)
{
Marshal.Copy(bitmapData.Scan0 + i * bitmapData.Stride, array, 0, bitmapData.Stride);
for (int j = 3; j < bitmapData.Width * 4; j += 4)
{
if (array[j] < byte.MaxValue)
{
return true;
}
}
}
}
finally
{
bitmap2.UnlockBits(bitmapData);
}
return false;
}
catch
{
return false;
}
finally
{
bitmap?.Dispose();
}
}
}
@@ -0,0 +1,13 @@
namespace VibranceHud.Theming;
public static class BackgroundMotionPolicy
{
public static bool ShouldPlay(bool pictureMoves, bool windowVisible, bool minimized, bool inForeground, bool gameRunning, bool goingAway, bool reducedMotion, bool movingOrSizing = false)
{
if ((((pictureMoves & windowVisible) && !minimized) & inForeground) && !gameRunning && !goingAway && !reducedMotion)
{
return !movingOrSizing;
}
return false;
}
}
+26
View File
@@ -0,0 +1,26 @@
using VibranceHud.Design;
namespace VibranceHud.Theming;
public static class ColourModeLook
{
public const int Version = 1;
public static bool Settle(AppSettings settings)
{
if (settings.ColourModeLookVersion >= 1)
{
return false;
}
if (!SignatureLooks.TryGet(settings.ThemeName, out var look))
{
SignatureLooks.TryGet("Ash", out look);
}
settings.ThemeName = look.Theme;
settings.BackdropLookName = BackdropLooks.Name(look.Backdrop);
settings.SurfaceStyleName = SurfaceStyles.Name(look.Surface);
settings.ChromeName = Chromes.Name(look.Chrome);
settings.ColourModeLookVersion = 1;
return true;
}
}
+183
View File
@@ -0,0 +1,183 @@
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
namespace VibranceHud.Theming;
public sealed class CustomThemeService
{
private const string DefaultFileName = "background.png";
private static readonly string[] Keepable = new string[6] { ".png", ".gif", ".jpg", ".jpeg", ".bmp", ".webp" };
private readonly string _dataDir;
private readonly AppSettings _settings;
public string ImagePath => Path.Combine(_dataDir, StoredName);
private string StoredName
{
get
{
if (!string.IsNullOrWhiteSpace(_settings.CustomBackgroundFile))
{
return _settings.CustomBackgroundFile;
}
return "background.png";
}
}
public bool HasImage
{
get
{
if (!string.IsNullOrEmpty(_settings.CustomBackgroundFile))
{
return File.Exists(ImagePath);
}
return false;
}
}
public Color SavedMatte => BackgroundMatte.Default;
public bool NeedsMatte => AppBackground.NeedsMatte;
public CustomThemeService(string dataDir, AppSettings settings)
{
_dataDir = dataDir;
_settings = settings;
}
public bool SetImage(string sourcePath)
{
string text2;
string text3;
try
{
Directory.CreateDirectory(_dataDir);
using (FileStream stream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
{
using Image image = Image.FromStream(stream);
if (image.Width <= 0 || image.Height <= 0)
{
return false;
}
}
string text = Path.GetExtension(sourcePath).ToLowerInvariant();
if (!Enumerable.Contains(Keepable, text))
{
text = ".png";
}
text2 = "background" + text;
text3 = Path.Combine(_dataDir, text2);
if (!string.Equals(Path.GetFullPath(sourcePath), Path.GetFullPath(text3), StringComparison.OrdinalIgnoreCase))
{
if (Enumerable.Contains(Keepable, Path.GetExtension(sourcePath).ToLowerInvariant()))
{
File.Copy(sourcePath, text3, overwrite: true);
}
else
{
using FileStream stream2 = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
using Image original = Image.FromStream(stream2);
using Bitmap bitmap = new Bitmap(original);
bitmap.Save(text3, ImageFormat.Png);
}
}
}
catch
{
return false;
}
if (!AppBackground.Load(text3, _settings.CustomBackgroundDim, _settings.CustomBackgroundBlur))
{
return false;
}
ImageTheme imageTheme = ImagePalette.Extract(AppBackground.SamplePixels(), ThemeCatalog.ByName("Ash").Accent);
RemoveStoredFilesExcept(text2);
_settings.CustomBackgroundFile = text2;
_settings.CustomBackgroundDim = imageTheme.SuggestedDim;
_settings.CustomAccentArgb = imageTheme.Accent.ToArgb();
AppBackground.SetDim(imageTheme.SuggestedDim);
Install(imageTheme);
return true;
}
public bool Restore()
{
if (!HasImage)
{
return false;
}
if (!AppBackground.Load(ImagePath, _settings.CustomBackgroundDim, _settings.CustomBackgroundBlur))
{
return false;
}
AppBackground.SetMatte(SavedMatte);
Install(ImagePalette.Derive((_settings.CustomAccentArgb != 0) ? Color.FromArgb(_settings.CustomAccentArgb) : ImagePalette.Extract(AppBackground.SamplePixels(), ThemeCatalog.ByName("Ash").Accent).Accent, _settings.CustomBackgroundDim));
return true;
}
public void SetDim(int dim)
{
_settings.CustomBackgroundDim = dim;
AppBackground.SetDim(dim);
}
public void SetBlur(int blur)
{
_settings.CustomBackgroundBlur = blur;
AppBackground.SetBlur(blur);
}
public void SetMatte(Color colour)
{
AppBackground.SetMatte(colour);
}
public void Remove()
{
AppBackground.Clear();
ThemeCatalog.ClearCustom();
_settings.CustomBackgroundFile = "";
_settings.CustomAccentArgb = 0;
RemoveStoredFilesExcept(null);
}
private void RemoveStoredFilesExcept(string? keep)
{
try
{
if (!Directory.Exists(_dataDir))
{
return;
}
string[] files = Directory.GetFiles(_dataDir, "background.*");
foreach (string path in files)
{
if (keep == null || !string.Equals(Path.GetFileName(path), keep, StringComparison.OrdinalIgnoreCase))
{
try
{
File.Delete(path);
}
catch
{
}
}
}
}
catch
{
}
}
private static void Install(ImageTheme t)
{
ThemeCatalog.SetCustom(t);
}
}
+182
View File
@@ -0,0 +1,182 @@
using System;
using System.Drawing;
namespace VibranceHud.Theming;
public static class ImagePalette
{
public const float MinValue = 0.25f;
public const float MinSaturation = 0.2f;
public const float MinAccentBrightness = 0.45f;
public const int MinDim = 0;
public const int MaxDim = 80;
private const int HueBuckets = 24;
public static ImageTheme Extract(Color[] pixels, Color fallbackAccent)
{
int[] array = new int[24];
float[] array2 = new float[24];
float[] array3 = new float[24];
float num = 0f;
for (int i = 0; i < pixels.Length; i++)
{
Color c = pixels[i];
ToHsv(c, out var h, out var s, out var v);
num += (0.2126f * (float)(int)c.R + 0.7152f * (float)(int)c.G + 0.0722f * (float)(int)c.B) / 255f;
if (!(v < 0.25f) && !(s < 0.2f))
{
int num2 = Math.Min(23, (int)(h / 360f * 24f));
array[num2]++;
array2[num2] += s;
array3[num2] += v;
}
}
int num3 = -1;
for (int j = 0; j < 24; j++)
{
if (array[j] > 0 && (num3 < 0 || array[j] > array[num3]))
{
num3 = j;
}
}
int dim = SuggestedDim((pixels.Length == 0) ? 0f : (num / (float)pixels.Length));
if (pixels.Length == 0)
{
return Derive(fallbackAccent, dim);
}
Color accent = ((num3 >= 0) ? Lift(FromHsv(((float)num3 + 0.5f) * 15f, array2[num3] / (float)array[num3], array3[num3] / (float)array[num3])) : FromHsv(0f, 0f, 0.86f));
return Derive(accent, dim);
}
public static ImageTheme Derive(Color accent, int dim)
{
Color color = ShiftHue(accent, 40f);
ToHsv(accent, out var h, out var s, out var _);
float num = Math.Min(s, 0.65f);
return new ImageTheme(accent, Scale(accent, 0.6f), accent, color, Blend(accent, color, 0.5f), FromHsv(h, num * 0.34f, 0.055f), FromHsv(h, num * 0.3f, 0.13f), FromHsv(h, num * 0.3f, 0.19f), FromHsv(h, num * 0.28f, 0.265f), FromHsv(h, num * 0.45f, 0.05f), FromHsv(h, num * 0.16f, 0.6f), dim);
}
public static int SuggestedDim(float meanLuma)
{
return Math.Clamp((int)Math.Round(meanLuma * 85f), 0, 80);
}
private static Color Lift(Color c)
{
ToHsv(c, out var h, out var s, out var v);
for (int i = 0; i < 24; i++)
{
if (!(Luma(FromHsv(h, s, v)) < 0.45f))
{
break;
}
if (!(v < 1f))
{
break;
}
v = Math.Min(1f, v + 0.05f);
}
return FromHsv(h, s, v);
}
private static float Luma(Color c)
{
return (0.2126f * (float)(int)c.R + 0.7152f * (float)(int)c.G + 0.0722f * (float)(int)c.B) / 255f;
}
private static Color Scale(Color c, float factor)
{
return Color.FromArgb((int)Math.Clamp((float)(int)c.R * factor, 0f, 255f), (int)Math.Clamp((float)(int)c.G * factor, 0f, 255f), (int)Math.Clamp((float)(int)c.B * factor, 0f, 255f));
}
private static Color Blend(Color a, Color b, float t)
{
return Color.FromArgb((int)((float)(int)a.R + (float)(b.R - a.R) * t), (int)((float)(int)a.G + (float)(b.G - a.G) * t), (int)((float)(int)a.B + (float)(b.B - a.B) * t));
}
private static Color ShiftHue(Color c, float degrees)
{
ToHsv(c, out var h, out var s, out var v);
return FromHsv((h + degrees) % 360f, s, v);
}
private static void ToHsv(Color c, out float h, out float s, out float v)
{
float num = (float)(int)c.R / 255f;
float num2 = (float)(int)c.G / 255f;
float num3 = (float)(int)c.B / 255f;
float num4 = Math.Max(num, Math.Max(num2, num3));
float num5 = Math.Min(num, Math.Min(num2, num3));
float num6 = num4 - num5;
v = num4;
s = ((num4 <= 0f) ? 0f : (num6 / num4));
if (num6 <= 0f)
{
h = 0f;
}
else if (num4 == num)
{
h = 60f * (((num2 - num3) / num6 + 6f) % 6f);
}
else if (num4 == num2)
{
h = 60f * ((num3 - num) / num6 + 2f);
}
else
{
h = 60f * ((num - num2) / num6 + 4f);
}
}
private static Color FromHsv(float h, float s, float v)
{
float num = v * s;
float num2 = num * (1f - Math.Abs(h / 60f % 2f - 1f));
float num3 = v - num;
float num4;
float num5;
float num6;
if (h < 60f)
{
num4 = num;
num5 = num2;
num6 = 0f;
}
else if (h < 120f)
{
num4 = num2;
num5 = num;
num6 = 0f;
}
else if (h < 180f)
{
num4 = 0f;
num5 = num;
num6 = num2;
}
else if (h < 240f)
{
num4 = 0f;
num5 = num2;
num6 = num;
}
else if (h < 300f)
{
num4 = num2;
num5 = 0f;
num6 = num;
}
else
{
num4 = num;
num5 = 0f;
num6 = num2;
}
return Color.FromArgb((int)Math.Round((num4 + num3) * 255f), (int)Math.Round((num5 + num3) * 255f), (int)Math.Round((num6 + num3) * 255f));
}
}
+5
View File
@@ -0,0 +1,5 @@
using System.Drawing;
namespace VibranceHud.Theming;
public sealed record ImageTheme(Color Accent, Color AccentDim, Color NodeA, Color NodeB, Color Line, Color Background, Color Surface, Color SurfaceHover, Color Border, Color GlassFill, Color GlassEdge, int SuggestedDim);
+28
View File
@@ -0,0 +1,28 @@
using System;
using System.Drawing;
using VibranceHud.Design;
namespace VibranceHud.Theming;
public static class SlatePreferences
{
public readonly record struct Snapshot(int GuiOpacityPercent, bool MatteBlur, int MatteArgb);
public const int NeverChosen = 0;
public static int DefaultOpacityPercent => (int)Math.Round(66.0);
public static Snapshot Defaults => new Snapshot(DefaultOpacityPercent, MatteBlur: true, BackgroundMatte.Default.ToArgb());
public static void Apply(int guiOpacityPercent, bool matteBlur, int matteArgb)
{
SlateSurface.UserOpacity = ((guiOpacityPercent == 0) ? 0.66 : ((double)guiOpacityPercent / 100.0));
SlateSurface.MatteBlur = matteBlur;
AppBackground.SetMatte((matteArgb == 0) ? BackgroundMatte.Default : Color.FromArgb(matteArgb));
}
public static Snapshot Capture()
{
return new Snapshot((int)Math.Round(SlateSurface.UserOpacity * 100.0), SlateSurface.MatteBlur, AppBackground.Matte.ToArgb());
}
}
+334
View File
@@ -0,0 +1,334 @@
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace VibranceHud.Theming;
internal static class SoftUpscale
{
internal sealed class Small
{
public readonly int Width;
public readonly int Height;
public readonly int[] Pixels;
public long Bytes => (long)Pixels.Length * 4L;
public Small(int width, int height, int[] pixels)
{
Width = width;
Height = height;
Pixels = pixels;
}
public static Small From(Bitmap bmp)
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bitmapData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
try
{
int[] array = new int[bmp.Width * bmp.Height];
for (int i = 0; i < bmp.Height; i++)
{
Marshal.Copy(bitmapData.Scan0 + i * bitmapData.Stride, array, i * bmp.Width, bmp.Width);
}
return new Small(bmp.Width, bmp.Height, array);
}
finally
{
bmp.UnlockBits(bitmapData);
}
}
}
[ThreadStatic]
private static int[]? _rowA;
[ThreadStatic]
private static int[]? _rowB;
[ThreadStatic]
private static int[]? _rows;
[ThreadStatic]
private static int[]? _x0;
[ThreadStatic]
private static int[]? _x1;
[ThreadStatic]
private static int[]? _fx;
[ThreadStatic]
private static int[]? _fy;
private const uint LowPair = 16711935u;
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static void CoverInto(Small small, Rectangle cover, Bitmap target)
{
int width = target.Width;
int height = target.Height;
int width2 = small.Width;
int height2 = small.Height;
if (width <= 0 || height <= 0 || width2 <= 0 || height2 <= 0 || cover.Width <= 0 || cover.Height <= 0)
{
return;
}
int[] x = Grow(ref _x0, width);
int[] x2 = Grow(ref _x1, width);
int[] fx = Grow(ref _fx, width);
Weights(width, cover.X, cover.Width, width2, x, x2, fx);
int[] array = Grow(ref _rowA, width);
int[] array2 = Grow(ref _rowB, width);
int num = -1;
int num2 = -1;
int num3 = cover.Height / height2 + 2;
int[] array3 = Grow(ref _rows, num3 * width);
int[] array4 = Grow(ref _fy, num3);
BitmapData bitmapData = target.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
try
{
double ky = (double)height2 / (double)cover.Height;
int num4;
for (int i = 0; i < height; i += num4)
{
SourceRow(i, cover.Y, ky, height2, out var y, out var y2, out array4[0]);
num4 = 1;
while (i + num4 < height && num4 < num3)
{
SourceRow(i + num4, cover.Y, ky, height2, out var y3, out var y4, out var f);
if (y3 != y || y4 != y2)
{
break;
}
array4[num4++] = f;
}
if (num != y)
{
if (num2 == y)
{
int[] array5 = array2;
array2 = array;
array = array5;
int num5 = num2;
num2 = num;
num = num5;
}
else
{
Widen(small, y, x, x2, fx, array, width);
num = y;
}
}
if (y2 != y && num2 != y2)
{
Widen(small, y2, x, x2, fx, array2, width);
num2 = y2;
}
if (y2 == y)
{
for (int j = 0; j < num4; j++)
{
Marshal.Copy(array, 0, bitmapData.Scan0 + (i + j) * bitmapData.Stride, width);
}
continue;
}
BlendRun(array, array2, array4, num4, array3, width);
for (int k = 0; k < num4; k++)
{
Marshal.Copy(array3, k * width, bitmapData.Scan0 + (i + k) * bitmapData.Stride, width);
}
}
}
finally
{
target.UnlockBits(bitmapData);
}
}
private static int[] Grow(ref int[]? buffer, int n)
{
if (buffer == null || buffer.Length < n)
{
buffer = new int[n];
}
return buffer;
}
private static void SourceRow(int y, int coverY, double ky, int sh, out int y0, out int y1, out int f)
{
double num = ((double)(y - coverY) + 0.5) * ky - 0.5;
if (num <= 0.0)
{
y0 = (y1 = 0);
f = 0;
return;
}
y0 = (int)num;
f = (int)Math.Round((num - (double)y0) * 256.0);
if (f >= 256)
{
y0++;
f = 0;
}
if (y0 >= sh - 1)
{
y0 = (y1 = sh - 1);
f = 0;
}
else
{
y1 = ((f == 0) ? y0 : (y0 + 1));
}
}
private static void Weights(int w, int coverX, int coverW, int sw, int[] x0, int[] x1, int[] fx)
{
double num = (double)sw / (double)coverW;
for (int i = 0; i < w; i++)
{
double num2 = ((double)(i - coverX) + 0.5) * num - 0.5;
int num3 = (int)Math.Floor(num2);
int num4 = (int)Math.Round((num2 - (double)num3) * 256.0);
if (num4 >= 256)
{
num3++;
num4 = 0;
}
int num5 = Math.Clamp(num3 + 1, 0, sw - 1);
num3 = Math.Clamp(num3, 0, sw - 1);
if (num2 < 0.0)
{
num3 = (num5 = 0);
num4 = 0;
}
x0[i] = num3;
x1[i] = num5;
fx[i] = ((num3 != num5) ? num4 : 0);
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void Widen(Small small, int row, int[] x0, int[] x1, int[] fx, int[] into, int w)
{
int[] pixels = small.Pixels;
int num = row * small.Width;
for (int i = 0; i < w; i++)
{
uint num2 = (uint)pixels[num + x0[i]];
int num3 = fx[i];
if (num3 == 0)
{
into[i] = (int)num2;
continue;
}
uint num4 = (uint)pixels[num + x1[i]];
uint num5 = (uint)(256 - num3);
uint num6 = (uint)(((int)((num2 & 0xFF00FF) * num5) + (int)(num4 & 0xFF00FF) * num3 + 8388736 >>> 8) & 0xFF00FF);
uint num7 = (uint)(((int)(((num2 >> 8) & 0xFF00FF) * num5) + (int)((num4 >> 8) & 0xFF00FF) * num3 + 8388736 >>> 8) & 0xFF00FF);
into[i] = (int)(num6 | (num7 << 8));
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void BlendRun(int[] a, int[] b, int[] fy, int run, int[] into, int w)
{
if (Avx2.IsSupported)
{
BlendRunAvx2(a, b, fy, run, into, w);
return;
}
for (int i = 0; i < run; i++)
{
BlendRow(a, b, fy[i], into, i * w, 0, w);
}
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
private static void BlendRunAvx2(int[] a, int[] b, int[] fy, int run, int[] into, int w)
{
Span<ushort> span = stackalloc ushort[run];
for (int i = 0; i < run; i++)
{
int num = fy[i] + 1 >> 1;
span[i] = (ushort)((num > 0) ? ((num >= 128) ? ushort.MaxValue : ((ushort)((128 - num) | (num << 8)))) : 0);
}
ref byte source = ref Unsafe.As<int, byte>(ref MemoryMarshal.GetArrayDataReference(a));
ref byte source2 = ref Unsafe.As<int, byte>(ref MemoryMarshal.GetArrayDataReference(b));
ref byte source3 = ref Unsafe.As<int, byte>(ref MemoryMarshal.GetArrayDataReference(into));
Vector256<short> right = Vector256.Create((short)64);
int j;
for (j = 0; j <= w - 8; j += 8)
{
Vector256<byte> vector = Unsafe.ReadUnaligned<Vector256<byte>>(in Unsafe.Add(ref source, j * 4));
Vector256<byte> vector2 = Unsafe.ReadUnaligned<Vector256<byte>>(in Unsafe.Add(ref source2, j * 4));
Vector256<byte> left = Avx2.UnpackLow(vector, vector2);
Vector256<byte> left2 = Avx2.UnpackHigh(vector, vector2);
for (int k = 0; k < run; k++)
{
ref byte destination = ref Unsafe.Add(ref source3, (k * w + j) * 4);
ushort num2 = span[k];
switch (num2)
{
case 0:
Unsafe.WriteUnaligned(ref destination, vector);
continue;
case ushort.MaxValue:
Unsafe.WriteUnaligned(ref destination, vector2);
continue;
}
Vector256<sbyte> right2 = Vector256.Create(num2).AsSByte();
Vector256<short> left3 = Avx2.ShiftRightLogical(Avx2.Add(Avx2.MultiplyAddAdjacent(left, right2), right), 7);
Vector256<short> right3 = Avx2.ShiftRightLogical(Avx2.Add(Avx2.MultiplyAddAdjacent(left2, right2), right), 7);
Unsafe.WriteUnaligned(ref destination, Avx2.PackUnsignedSaturate(left3, right3));
}
}
if (j < w)
{
for (int l = 0; l < run; l++)
{
BlendRow(a, b, fy[l], into, l * w, j, w);
}
}
}
private static void BlendRow(int[] a, int[] b, int f, int[] into, int at, int from, int w)
{
uint num = (uint)(256 - f);
int i = from;
if (Vector.IsHardwareAccelerated && from == 0)
{
Span<uint> span = MemoryMarshal.Cast<int, uint>(a.AsSpan(0, w));
Span<uint> span2 = MemoryMarshal.Cast<int, uint>(b.AsSpan(0, w));
Span<uint> span3 = MemoryMarshal.Cast<int, uint>(into.AsSpan(at, w));
Vector<uint> vector = new Vector<uint>(16711935u);
Vector<uint> vector2 = new Vector<uint>(8388736u);
Vector<uint> vector3 = new Vector<uint>(num);
Vector<uint> vector4 = new Vector<uint>((uint)f);
for (int count = Vector<uint>.Count; i <= w - count; i += count)
{
Vector<uint> vector5 = new Vector<uint>(span.Slice(i, count));
Vector<uint> vector6 = new Vector<uint>(span2.Slice(i, count));
Vector<uint> vector7 = Vector.ShiftRightLogical((vector5 & vector) * vector3 + (vector6 & vector) * vector4 + vector2, 8) & vector;
Vector<uint> value = Vector.ShiftRightLogical((Vector.ShiftRightLogical(vector5, 8) & vector) * vector3 + (Vector.ShiftRightLogical(vector6, 8) & vector) * vector4 + vector2, 8) & vector;
(vector7 | Vector.ShiftLeft(value, 8)).CopyTo(span3.Slice(i, count));
}
}
for (; i < w; i++)
{
int num2 = a[i];
uint num3 = (uint)b[i];
uint num4 = (uint)(((num2 & 0xFF00FF) * (int)num + (int)(num3 & 0xFF00FF) * f + 8388736 >>> 8) & 0xFF00FF);
uint num5 = (uint)((((num2 >>> 8) & 0xFF00FF) * (int)num + (int)((num3 >> 8) & 0xFF00FF) * f + 8388736 >>> 8) & 0xFF00FF);
into[at + i] = (int)(num4 | (num5 << 8));
}
}
}