refactor: optimize permutation generation and replace static array with dynamic allocation

This commit is contained in:
2026-04-12 16:06:59 -04:00
parent 4225aeda33
commit e7c5c4fff6
+15 -16
View File
@@ -1,10 +1,11 @@
namespace Spectrum.Input using System.Security.Cryptography;
namespace Spectrum.Input
{ {
public class MovementPaths public class MovementPaths
{ {
private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t); private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t);
private static readonly int[] _permutation = GeneratePermutation(); private static readonly int[] _permutation = GeneratePermutation();
private static readonly int[] _p;
private static double _perlinTime = 0.0; private static double _perlinTime = 0.0;
private static Point _lastMove = new(0, 0); private static Point _lastMove = new(0, 0);
@@ -13,15 +14,6 @@
private static double _velocityX = 0.0; private static double _velocityX = 0.0;
private static double _velocityY = 0.0; private static double _velocityY = 0.0;
static MovementPaths()
{
_p = new int[512];
for (int i = 0; i < 256; i++)
{
_p[256 + i] = _p[i] = _permutation[i];
}
}
private static double Fade(double t) => t * t * t * (t * (t * 6 - 15) + 10); private static double Fade(double t) => t * t * t * (t * (t * 6 - 15) + 10);
private static double Lerp(double a, double b, double t) => a + t * (b - a); private static double Lerp(double a, double b, double t) => a + t * (b - a);
private static double Grad(int hash, double x) private static double Grad(int hash, double x)
@@ -36,8 +28,8 @@
int X = (int)Math.Floor(x) & 255; int X = (int)Math.Floor(x) & 255;
x -= Math.Floor(x); x -= Math.Floor(x);
double u = Fade(x); double u = Fade(x);
int a = _p[X]; int a = _permutation[X];
int b = _p[X + 1]; int b = _permutation[X + 1];
double res = Lerp(Grad(a, x), Grad(b, x - 1), u); double res = Lerp(Grad(a, x), Grad(b, x - 1), u);
return res * 0.188; return res * 0.188;
} }
@@ -282,13 +274,20 @@
private static int[] GeneratePermutation() private static int[] GeneratePermutation()
{ {
int[] perm = new int[256]; int[] perm = new int[512];
for (int i = 0; i < 256; i++) perm[i] = i;
for (int i = 0; i < 256; i++)
perm[i] = i;
for (int i = 255; i > 0; i--) for (int i = 255; i > 0; i--)
{ {
int j = Random.Shared.Next(i + 1); int j = RandomNumberGenerator.GetInt32(i + 1);
(perm[i], perm[j]) = (perm[j], perm[i]); (perm[i], perm[j]) = (perm[j], perm[i]);
} }
for (int i = 0; i < 256; i++)
perm[i + 256] = perm[i];
return perm; return perm;
} }
} }