12constexpr u32 WAVES = 96;
13constexpr f32 TAU = 6.28318530718f;
15constexpr f32 SLOPE_RMS = 0.22f;
17struct Wave {
f32 kx, kz, slope, phase; };
26f32 unit(
u32& state) {
return static_cast<f32>(next(state) >> 8) / 16777216.0f; }
30std::vector<Wave> spectrum(
u32 seed) {
31 std::vector<Wave> waves;
34 while (waves.size() < WAVES) {
35 const i32 kx =
static_cast<i32>(next(state) % 41) - 20;
36 const i32 kz =
static_cast<i32>(next(state) % 41) - 20;
37 const f32 k = std::sqrt(
static_cast<f32>(kx * kx + kz * kz));
39 waves.push_back({
static_cast<f32>(kx),
static_cast<f32>(kz), std::pow(k, -0.55f), unit(state) * TAU});
44void field(
u32 seed, std::vector<f32>& sx, std::vector<f32>& sz) {
46 const std::vector<Wave> waves = spectrum(seed);
48 for (
u32 y = 0; y < n; ++y) {
49 for (
u32 x = 0; x < n; ++x) {
50 const f32 u =
static_cast<f32>(x) /
static_cast<f32>(n), v =
static_cast<f32>(y) /
static_cast<f32>(n);
51 f32 ax = 0.0f, az = 0.0f;
52 for (
const Wave& w : waves) {
53 const f32 c = std::cos(TAU * (w.kx * u + w.kz * v) + w.phase) * w.slope;
54 const f32 k = std::sqrt(w.kx * w.kx + w.kz * w.kz);
60 power +=
static_cast<f64>(ax) * ax +
static_cast<f64>(az) * az;
63 const f32 gain = SLOPE_RMS / std::sqrt(
static_cast<f32>(power / (2.0 * n * n)));
64 for (
f32& v : sx) v *= gain;
65 for (
f32& v : sz) v *= gain;
68u8 pack(
f32 v) {
return static_cast<u8>(std::clamp(v * 0.5f + 0.5f, 0.0f, 1.0f) * 255.0f + 0.5f); }
74 std::vector<f32> ax(n * n), az(n * n), bx(n * n), bz(n * n);
75 field(0x9E3779B9u, ax, az);
76 field(0x7F4A7C15u, bx, bz);
77 std::vector<u8> pixels(n * n * 4);
78 for (
u32 i = 0; i < n * n; ++i) {
79 const f32 la = 1.0f / std::sqrt(1.0f + ax[i] * ax[i] + az[i] * az[i]);
80 const f32 lb = 1.0f / std::sqrt(1.0f + bx[i] * bx[i] + bz[i] * bz[i]);
81 pixels[i * 4 + 0] = pack(ax[i] * la);
82 pixels[i * 4 + 1] = pack(az[i] * la);
83 pixels[i * 4 + 2] = pack(bx[i] * lb);
84 pixels[i * 4 + 3] = pack(bz[i] * lb);
std::int32_t i32
Signed 32-bit integer.
constexpr u32 RIPPLE_NORMALS_SIZE
constexpr u32 RIPPLE_NORMALS_LONGEST
The longest wave in a field runs this many times across the texture, the shortest twenty: a field rea...
std::uint32_t u32
Unsigned 32-bit integer.
std::uint8_t u8
Unsigned 8-bit integer.
double f64
64-bit floating point
std::vector< u8 > buildRippleNormals()
RGBA8, RIPPLE_NORMALS_SIZE square. A texel's rg (and ba) is the xy of a unit normal whose z is up: th...
float f32
32-bit floating point