Libftpp
A modern C++ library
perlin_noise_2D.cpp
Go to the documentation of this file.
1 #include "perlin_noise_2D.hpp"
2 
3 float PerlinNoise2D::linearInterpolation(float a, float b, float t)
4 {
5  return a + t * (b - a);
6 }
7 
8 IVector2<float> PerlinNoise2D::gradient(const int& i, const int& j)
9 {
10  // long long hashSeed = i ^ j ^ _seedGlobal;
11 
12  long long randVal = generator(i, j);
13  float angle = static_cast<float>(randVal % 360) * 3.14159f / 180.f;
14 
15  return IVector2<float>(cos(angle), sin(angle)); // vecteur unitaire
16 }
17 
18 float PerlinNoise2D::fade(const float& t)
19 {
20  return t * t * t * (t * (t * 6 - 15) + 10);
21 }
22 
23 float PerlinNoise2D::sample(const float& x, const float& y)
24 {
25  IVector2<float> cell(std::floor(x), std::floor(y));
26 
27  IVector2<float> localCoord(x, y);
28  localCoord -= cell; // vecteur point→coin bas-gauche
29 
30  float u = localCoord.x; // position locale dans la cellule
31  float v = localCoord.y;
32 
33  // Générer les gradients pour les 4 coins
34  IVector2<float> g00 = gradient(cell.x, cell.y);
35  IVector2<float> g10 = gradient(cell.x + 1, cell.y);
36  IVector2<float> g01 = gradient(cell.x, cell.y + 1);
37  IVector2<float> g11 = gradient(cell.x + 1, cell.y + 1);
38 
39  // Calcul des vecteurs point vers le coin et dot products
40  IVector2<float> d00(u, v);
41  IVector2<float> d10(u - 1, v);
42  IVector2<float> d01(u, v - 1);
43  IVector2<float> d11(u - 1, v - 1);
44 
45  float dot00 = d00.dot(g00);
46  float dot10 = d10.dot(g10);
47  float dot01 = d01.dot(g01);
48  float dot11 = d11.dot(g11);
49 
50  // Partie lissage du bruit pour eviter les blocs
51  float fu = fade(u);
52  float fv = fade(v);
53 
54  // Interpolation bilinéaire
55  float ix0 = linearInterpolation(dot00, dot10, fu); // bas
56  float ix1 = linearInterpolation(dot01, dot11, fu); // haut
57  float value = linearInterpolation(ix0, ix1, fv); // final
58 
59  return value;
60 }
float sample(const float &x, const float &y)
TType x
Definition: ivector2.hpp:10
TType y
Definition: ivector2.hpp:11
float dot()
Definition: ivector2.hpp:77