From e7c5c4fff64998d394f318a7e20b3f667fbe0089 Mon Sep 17 00:00:00 2001 From: whoswhip Date: Sun, 12 Apr 2026 16:06:59 -0400 Subject: [PATCH] refactor: optimize permutation generation and replace static array with dynamic allocation --- Spectrum/Input/MovementPaths.cs | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/Spectrum/Input/MovementPaths.cs b/Spectrum/Input/MovementPaths.cs index 22afe2f..b5ad771 100644 --- a/Spectrum/Input/MovementPaths.cs +++ b/Spectrum/Input/MovementPaths.cs @@ -1,10 +1,11 @@ -namespace Spectrum.Input +using System.Security.Cryptography; + +namespace Spectrum.Input { public class MovementPaths { private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t); private static readonly int[] _permutation = GeneratePermutation(); - private static readonly int[] _p; private static double _perlinTime = 0.0; private static Point _lastMove = new(0, 0); @@ -13,15 +14,6 @@ private static double _velocityX = 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 Lerp(double a, double b, double t) => a + t * (b - a); private static double Grad(int hash, double x) @@ -36,8 +28,8 @@ int X = (int)Math.Floor(x) & 255; x -= Math.Floor(x); double u = Fade(x); - int a = _p[X]; - int b = _p[X + 1]; + int a = _permutation[X]; + int b = _permutation[X + 1]; double res = Lerp(Grad(a, x), Grad(b, x - 1), u); return res * 0.188; } @@ -282,13 +274,20 @@ private static int[] GeneratePermutation() { - int[] perm = new int[256]; - for (int i = 0; i < 256; i++) perm[i] = i; + int[] perm = new int[512]; + + for (int i = 0; i < 256; i++) + perm[i] = 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]); } + + for (int i = 0; i < 256; i++) + perm[i + 256] = perm[i]; + return perm; } }