FastLED 3.9.15
Loading...
Searching...
No Matches
noise_woryley.cpp
Go to the documentation of this file.
1#include "noise_woryley.h"
2
3namespace fl {
4namespace {
5
6constexpr i32 Q15_ONE = 32768; // 1.0 in Q15
7// constexpr i32 Q15_HALF = Q15_ONE / 2;
8
9// Helper: multiply two Q15 numbers (result in Q15)
10// i32 q15_mul(i32 a, i32 b) {
11// return (i32)(((int64_t)a * b) >> 15);
12// }
13
14// Helper: absolute difference
15i32 q15_abs(i32 a) { return a < 0 ? -a : a; }
16
17// Pseudo-random hash based on grid coordinates
18u16 hash(i32 x, i32 y) {
19 u32 n = (u32)(x * 374761393 + y * 668265263);
20 n = (n ^ (n >> 13)) * 1274126177;
21 return (u16)((n ^ (n >> 16)) & 0xFFFF);
22}
23
24// Get fractional feature point inside a grid cell
25void feature_point(i32 gx, i32 gy, i32 &fx, i32 &fy) {
26 u16 h = hash(gx, gy);
27 fx = (h & 0xFF) * 128; // scale to Q15 (0–32767)
28 fy = ((h >> 8) & 0xFF) * 128;
29}
30} // namespace
31
32// Compute 2D Worley noise at (x, y) in Q15
33i32 worley_noise_2d_q15(i32 x, i32 y) {
34 i32 cell_x = x >> 15;
35 i32 cell_y = y >> 15;
36
37 i32 min_dist = INT32_MAX;
38
39 // Check surrounding 9 cells
40 for (int dy = -1; dy <= 1; ++dy) {
41 for (int dx = -1; dx <= 1; ++dx) {
42 i32 gx = cell_x + dx;
43 i32 gy = cell_y + dy;
44
45 i32 fx, fy;
46 feature_point(gx, gy, fx, fy);
47
48 i32 feature_x = (gx << 15) + fx;
49 i32 feature_y = (gy << 15) + fy;
50
51 i32 dx_q15 = x - feature_x;
52 i32 dy_q15 = y - feature_y;
53
54 // Approximate distance using Manhattan (faster) or Euclidean
55 // (costlier)
56 i32 dist =
57 q15_abs(dx_q15) + q15_abs(dy_q15); // Manhattan distance
58
59 if (dist < min_dist)
60 min_dist = dist;
61 }
62 }
63
64 // Normalize: maximum possible distance is roughly 2*Q15_ONE
65 return (min_dist << 15) / (2 * Q15_ONE);
66}
67
68} // namespace fl
int y
Definition simple.h:93
int x
Definition simple.h:92
void feature_point(i32 gx, i32 gy, i32 &fx, i32 &fy)
i32 worley_noise_2d_q15(i32 x, i32 y)
IMPORTANT!
Definition crgb.h:20
#define INT32_MAX