用于噪声生成的哈希函数

Hash function for noise generation

我正在制作值噪声发生器,我发现我当前的哈希值在图像中产生了一种模式:

所以我正在寻找更好的散列函数 less predictable/repeatable。

我使用散列而不是随机数,因为我希望它具有确定性。给定一个 (x, y) 坐标,它应该总是产生相同的结果。

如果可以扩展散列函数以轻松接受更多参数,如 (x, y, z) 或 (x, y, z, t),而不是就两个。

我当前的哈希值是:

public static class Hash
{
    public static float GetHash(int x)
    {
        x = x ^ 61 ^ (x >> 16);
        x += x << 3;
        x ^= x >> 4;
        x *= 0x27d4eb2d;
        x ^= x >> 15;
        return x / (float)int.MaxValue;
    }

    public static float GetHash(int x, int y) => GetHash((y << 8) + x);
}

我添加了行 x / (float)int.MaxValue 因为我想要一个从 0 到 1 的浮点数结果。

但我必须承认我只是从某个地方复制粘贴它。按位运算(和哈希)不是我的强项。

原回答: 我会使用像 https://github.com/Auburns/FastNoise_CSharp 这样的库 也许你可以从那个FastNoise.cs文件

中的源代码中学习

修改后的答案,包括来自参考来源的代码、散列函数 "Copyright(c) 2017 Jordan Peck"

private const int X_PRIME = 1619;
private const int Y_PRIME = 31337;
private const int Z_PRIME = 6971;
private const int W_PRIME = 1013;

private static int Hash2D(int seed, int x, int y)
{
    int hash = seed;
    hash ^= X_PRIME * x;
    hash ^= Y_PRIME * y;

    hash = hash * hash * hash * 60493;
    hash = (hash >> 13) ^ hash;

    return hash;
}

private static int Hash3D(int seed, int x, int y, int z)
{
    int hash = seed;
    hash ^= X_PRIME * x;
    hash ^= Y_PRIME * y;
    hash ^= Z_PRIME * z;

    hash = hash * hash * hash * 60493;
    hash = (hash >> 13) ^ hash;

    return hash;
}

private static int Hash4D(int seed, int x, int y, int z, int w)
{
    int hash = seed;
    hash ^= X_PRIME * x;
    hash ^= Y_PRIME * y;
    hash ^= Z_PRIME * z;
    hash ^= W_PRIME * w;

    hash = hash * hash * hash * 60493;
    hash = (hash >> 13) ^ hash;

    return hash;
}