]> git.localhorst.tv Git - blank.git/blob - src/noise.hpp
3c4609e566a041d838a626096ca0c849bad8fd53
[blank.git] / src / noise.hpp
1 #ifndef BLANK_NOISE_HPP_
2 #define BLANK_NOISE_HPP_
3
4 #include <cstdint>
5 #include <limits>
6 #include <glm/glm.hpp>
7
8
9 namespace blank {
10
11 class GaloisLFSR {
12
13 public:
14         // seed should be non-zero
15         explicit GaloisLFSR(std::uint64_t seed) noexcept;
16
17         // get the next bit
18         bool operator ()() noexcept;
19
20         template<class T>
21         void operator ()(T &out) noexcept {
22                 constexpr int num_bits =
23                         std::numeric_limits<T>::digits +
24                         std::numeric_limits<T>::is_signed;
25                 for (int i = 0; i < num_bits; ++i) {
26                         operator ()();
27                 }
28                 out = static_cast<T>(state);
29         }
30
31 private:
32         std::uint64_t state;
33         // bits 64, 63, 61, and 60 set to 1 (counting from 1 lo to hi)
34         static constexpr std::uint64_t mask = 0xD800000000000000;
35
36 };
37
38
39 /// (3D only) adaptation of Stefan Gustavson's SimplexNoise java class
40 class SimplexNoise {
41
42 public:
43         explicit SimplexNoise(unsigned int seed) noexcept;
44
45         float operator ()(const glm::vec3 &) const noexcept;
46
47 private:
48         unsigned char Perm(size_t idx) const noexcept;
49         unsigned char Perm12(size_t idx) const noexcept;
50         const glm::vec3 &Grad(unsigned char idx) const noexcept;
51
52 private:
53         unsigned char perm[512];
54         unsigned char perm12[512];
55         glm::vec3 grad[12];
56
57 };
58
59
60 /// implementation of Worley noise (aka Cell or Voroni noise)
61 class WorleyNoise {
62
63 public:
64         explicit WorleyNoise(unsigned int seed) noexcept;
65
66         float operator ()(const glm::vec3 &) const noexcept;
67
68 private:
69         const unsigned int seed;
70         const int num_points;
71
72 };
73
74
75 template<class Noise>
76 float OctaveNoise(
77         const Noise &noise,
78         const glm::vec3 &in,
79         int num,
80         float persistence,
81         float frequency = 1.0f,
82         float amplitude = 1.0f,
83         float growth = 2.0f
84 ) {
85         float total = 0.0f;
86         float max = 0.0f;
87         for (int i = 0; i < num; ++i) {
88                 total += noise(in * frequency) * amplitude;
89                 max += amplitude;
90                 amplitude *= persistence;
91                 frequency *= growth;
92         }
93
94         return total / max;
95 }
96
97 }
98
99 #endif