c++帕林噪声算法实现
时间: 2023-11-18 21:52:32 浏览: 44
帕林噪声(Perlin noise)是一种流行的用于生成自然风景和纹理的算法。下面是一个简单的 C++ 实现:
```c++
#include <cmath>
#include <random>
class PerlinNoise {
public:
PerlinNoise() {
std::random_device rd;
m_engine.seed(rd());
for (int i = 0; i < 256; ++i) {
m_permutation[i] = i;
}
std::shuffle(m_permutation.begin(), m_permutation.begin() + 256, m_engine);
for (int i = 0; i < 256; ++i) {
m_permutation[256 + i] = m_permutation[i];
}
}
double noise(double x, double y, double z) const {
int X = static_cast<int>(std::floor(x)) & 255;
int Y = static_cast<int>(std::floor(y)) & 255;
int Z = static_cast<int>(std::floor(z)) & 255;
x -= std::floor(x);
y -= std::floor(y);
z -= std::floor(z);
double u = fade(x);
double v = fade(y);
double w = fade(z);
int A = m_permutation[X] + Y, AA = m_permutation[A] + Z, AB = m_permutation[A + 1] + Z;
int B = m_permutation[X + 1] + Y, BA = m_permutation[B] + Z, BB = m_permutation[B + 1] + Z;
return lerp(w, lerp(v, lerp(u, grad(m_permutation[AA], x, y, z),
grad(m_permutation[BA], x - 1, y, z)),
lerp(u, grad(m_permutation[AB], x, y - 1, z),
grad(m_permutation[BB], x - 1, y - 1, z))),
lerp(v, lerp(u, grad(m_permutation[AA + 1], x, y, z - 1),
grad(m_permutation[BA + 1], x - 1, y, z - 1)),
lerp(u, grad(m_permutation[AB + 1], x, y - 1, z - 1),
grad(m_permutation[BB + 1], x - 1, y - 1, z - 1))));
}
private:
double fade(double t) const {
return t * t * t * (t * (t * 6 - 15) + 10);
}
double lerp(double t, double a, double b) const {
return a + t * (b - a);
}
double grad(int hash, double x, double y, double z) const {
int h = hash & 15;
double u = h < 8 ? x : y;
double v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
std::array<int, 512> m_permutation;
std::default_random_engine m_engine;
};
```