]> git.localhorst.tv Git - blank.git/blob - src/noise.hpp
update light levels from border on neighbor change
[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);
16
17         // get the next bit
18         bool operator ()();
19
20         template<class T>
21         void operator ()(T &out) {
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);
44
45         float operator ()(const glm::vec3 &) const;
46
47 private:
48         unsigned char Perm(size_t idx) const;
49         const glm::vec3 &Grad(size_t idx) const;
50
51 private:
52         unsigned char perm[512];
53         glm::vec3 grad[12];
54
55 };
56
57
58 /// implementation of Worley noise (aka Cell or Voroni noise)
59 class WorleyNoise {
60
61 public:
62         explicit WorleyNoise(unsigned int seed);
63
64         float operator ()(const glm::vec3 &) const;
65
66 private:
67         const unsigned int seed;
68         const int num_points;
69
70 };
71
72
73 template<class Noise>
74 float OctaveNoise(
75         const Noise &noise,
76         const glm::vec3 &in,
77         int num,
78         float persistence,
79         float frequency = 1.0f,
80         float amplitude = 1.0f,
81         float growth = 2.0f
82 ) {
83         float total = 0.0f;
84         float max = 0.0f;
85         for (int i = 0; i < num; ++i) {
86                 total += noise(in * frequency) * amplitude;
87                 max += amplitude;
88                 amplitude *= persistence;
89                 frequency *= growth;
90         }
91
92         return total / max;
93 }
94
95 }
96
97 #endif