From 5c96a2c19ae3b16348f71e48af66710be112b742 Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Fri, 26 Dec 2025 22:01:23 +0000 Subject: [PATCH] Codechange: Improve performance of perlin noise function. (#14991) Avoid pow() and reduce computations. --- src/tgp.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/tgp.cpp b/src/tgp.cpp index ba7ed02a38..61de35564b 100644 --- a/src/tgp.cpp +++ b/src/tgp.cpp @@ -944,15 +944,17 @@ static double interpolated_noise(const double x, const double y, const int prime */ static double perlin_coast_noise_2D(const double x, const double y, const double p, const int prime) { + constexpr int OCTAVES = 6; + constexpr double INITIAL_FREQUENCY = 1 << OCTAVES; + double total = 0.0; - - for (int i = 0; i < 6; i++) { - const double frequency = (double)(1 << i); - const double amplitude = pow(p, (double)i); - - total += interpolated_noise((x * frequency) / 64.0, (y * frequency) / 64.0, prime) * amplitude; + double frequency = 1.0 / INITIAL_FREQUENCY; + double amplitude = 1.0; + for (int i = 0; i < OCTAVES; i++) { + total += interpolated_noise(x * frequency, y * frequency, prime) * amplitude; + frequency *= 2.0; + amplitude *= p; } - return total; }