From eea38dc7bfb5a2bdbfe45b6deb0aa361b9509bdc Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 17:36:40 +0200 Subject: [PATCH 01/11] Make Fft a namespace instead of a static-only class. --- include/Nebulite/Math/FFT.hpp | 33 +++++++++++++++------------------ src/Nebulite/Math/FFT.cpp | 12 ++++++------ 2 files changed, 21 insertions(+), 24 deletions(-) diff --git a/include/Nebulite/Math/FFT.hpp b/include/Nebulite/Math/FFT.hpp index aa8bce5dd..28466eebe 100644 --- a/include/Nebulite/Math/FFT.hpp +++ b/include/Nebulite/Math/FFT.hpp @@ -9,45 +9,42 @@ #include //------------------------------------------ -namespace Nebulite::Math { /** - * @brief A class that provides static methods for performing Fast Fourier Transform (FFT) and related operations on audio data. + * @namespace Nebulite::Math::Fft + * @brief Functions for performing Fast Fourier Transform (FFT) and related operations on audio data. */ -class Fft { -public: +namespace Nebulite::Math::Fft { /** * @brief Computes the Fast Fourier Transform (FFT) of the given sound data. * @param data The sound data to transform. * @return A vector of complex numbers representing the FFT of the sound data. */ - static std::vector> fft(std::vector const& data); + std::vector> fft(std::vector const& data); /** * @brief Computes the Inverse Fast Fourier Transform (IFFT) of the given frequency-domain data. * @param xValues The frequency-domain data to transform back to the time domain. * @return A vector of complex numbers representing the IFFT of the input data, which can be converted back to audio samples. */ - static std::vector> fftInverse(std::vector> const& xValues); + std::vector> fftInverse(std::vector> const& xValues); /** - * @brief Applies a transfer function defined by the given numerator and denominator coefficients to the input sound data in the frequency domain. - * @param data The input sound data to which the transfer function will be applied. + * @brief Evaluates the transfer function defined by the given numerator and denominator coefficients at a specific angular frequency omega. + * @param omega The angular frequency (in radians per second) at which to evaluate the transfer function. * @param num The coefficients of the numerator of the transfer function, starting with the highest order. * @param den The coefficients of the denominator of the transfer function, starting with the highest order. - * @return A vector of doubles representing the sound data after applying the transfer function in the frequency domain. - * @throws std::domain_error if the leading coefficient of the denominator is zero, which is not supported. + * @return A complex number representing the value of the transfer function at the specified frequency. */ - static std::vector applyTransferFunctionFrequencyDomain(std::vector const& data, std::vector const& num, std::vector const& den); + std::complex evalTransfer(double omega,std::vector const& num,std::vector const& den); -private: /** - * @brief Evaluates the transfer function defined by the given numerator and denominator coefficients at a specific angular frequency omega. - * @param omega The angular frequency (in radians per second) at which to evaluate the transfer function. + * @brief Applies a transfer function defined by the given numerator and denominator coefficients to the input sound data in the frequency domain. + * @param data The input sound data to which the transfer function will be applied. * @param num The coefficients of the numerator of the transfer function, starting with the highest order. * @param den The coefficients of the denominator of the transfer function, starting with the highest order. - * @return A complex number representing the value of the transfer function at the specified frequency. + * @return A vector of doubles representing the sound data after applying the transfer function in the frequency domain. + * @throws std::domain_error if the leading coefficient of the denominator is zero, which is not supported. */ - static std::complex evalTransfer(double omega,std::vector const& num,std::vector const& den); -}; -} // namespace Nebulite::Math + std::vector applyTransferFunctionFrequencyDomain(std::vector const& data, std::vector const& num, std::vector const& den); +} // namespace Nebulite::Math::Fft #endif // NEBULITE_MATH_FFT_HPP diff --git a/src/Nebulite/Math/FFT.cpp b/src/Nebulite/Math/FFT.cpp index 9b5b97b7e..09bdd2626 100644 --- a/src/Nebulite/Math/FFT.cpp +++ b/src/Nebulite/Math/FFT.cpp @@ -22,7 +22,7 @@ #include "Nebulite/Utility/Ranges.hpp" //------------------------------------------ -namespace Nebulite::Math { +namespace Nebulite::Math::Fft { namespace { @@ -103,7 +103,7 @@ inline constexpr ApplyStages applyStagesInverse{ 2.0 * std::numbers::pi }; } // namespace -std::vector> Fft::fft(std::vector const& data) { +std::vector> fft(std::vector const& data) { if (data.empty()) return {}; auto const n = std::bit_ceil(data.size()); // next power of two std::vector> a(n); // Initialized to 0.0 @@ -114,7 +114,7 @@ std::vector> Fft::fft(std::vector const& data) { | std::ranges::to>>(); } -std::vector> Fft::fftInverse(std::vector> const& xValues) { +std::vector> fftInverse(std::vector> const& xValues) { auto const n = std::bit_ceil(xValues.size()); // next power of two if (n == 0) return {}; std::vector> a = xValues; @@ -139,14 +139,14 @@ std::complex evaluatePolynomial(std::vector const& coefficients, } } // namespace -std::complex Fft::evalTransfer(double const omega, std::vector const& num, std::vector const& den) { +std::complex evalTransfer(double const omega, std::vector const& num, std::vector const& den) { std::complex const z = std::exp(std::complex(0.0, -omega)); std::complex const numSum = evaluatePolynomial(num, z); std::complex const denSum = evaluatePolynomial(den, z); return numSum / denSum; } -std::vector Fft::applyTransferFunctionFrequencyDomain(std::vector const& data, std::vector const& num, std::vector const& den) { +std::vector applyTransferFunctionFrequencyDomain(std::vector const& data, std::vector const& num, std::vector const& den) { if (isZero(den.back())) { throw std::domain_error("Denominator has a zero leading coefficient, which is not yet supported."); } @@ -165,4 +165,4 @@ std::vector Fft::applyTransferFunctionFrequencyDomain(std::vector>(); } -} // namespace Nebulite::Math +} // namespace Nebulite::Math::Fft From 168508cb52327c89373926595113f63c11a5eaf4 Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 17:59:33 +0200 Subject: [PATCH 02/11] Add concepts for indexable and mutable ranges in FFT implementation --- src/Nebulite/Math/FFT.cpp | 44 +++++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/src/Nebulite/Math/FFT.cpp b/src/Nebulite/Math/FFT.cpp index 09bdd2626..6066371df 100644 --- a/src/Nebulite/Math/FFT.cpp +++ b/src/Nebulite/Math/FFT.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -21,6 +22,26 @@ #include "Nebulite/Utility/Generate.hpp" #include "Nebulite/Utility/Ranges.hpp" +//------------------------------------------ +// Concepts + +template +using index_reference_t = decltype(std::declval()[std::declval>()]); + +template +concept IndexableRange = std::ranges::range + && requires(R& r, std::ranges::range_size_t i){ + r[i]; + }; + +template +concept MutableRange = IndexableRange + && requires(R& r, std::ranges::range_size_t i) { + requires std::is_lvalue_reference_v>; + requires std::assignable_from, std::ranges::range_value_t>; + requires std::swappable>; + }; + //------------------------------------------ namespace Nebulite::Math::Fft { @@ -30,14 +51,16 @@ struct BitReversalPermutation { struct Closure : std::ranges::range_adaptor_closure { std::size_t n; - template + Closure(std::size_t rangeSize) : n(rangeSize) {} + + template auto operator()(R&& r) const { auto const bitCount = static_cast(std::bit_width(n - 1)); assert(r.size() == n); assert(std::has_single_bit(n)); // n must be a power of two for (auto const i : Utility::Generate::indices(n)) { if (auto const b = Utility::Convert::Bits::reverse(i, bitCount); i < b) { - std::swap(r[i], r[b]); + std::ranges::swap(r[i], r[b]); } } return std::forward(r); @@ -45,10 +68,7 @@ struct BitReversalPermutation { }; auto operator()(std::size_t const n) const { - return Closure{ - {}, // NOLINT - n, - }; + return Closure(n); } } constexpr bitReversalPermutation; @@ -57,7 +77,9 @@ struct ApplyStages { std::size_t const n; double const fullAngle; - template + Closure(std::size_t const rangeSize, double const a) : n(rangeSize), fullAngle(a) {} + + template static void applyStage(R& r, std::complex const stageTwiddle, std::size_t const stageSize, std::size_t const n) { auto const halfStageSize = stageSize / 2; @@ -76,7 +98,7 @@ struct ApplyStages { } } - template + template auto operator()(R&& r) const { for (auto const stageSize : Utility::Generate::powersOfTwo(n)) { double const ang = fullAngle / static_cast(stageSize); @@ -90,11 +112,7 @@ struct ApplyStages { double fullAngle; auto operator()(std::size_t const n) const { - return Closure{ - {}, // NOLINT - n, - fullAngle, - }; + return Closure(n, fullAngle); } }; From 95cc89dce5cd2dc0672ab78a9450c833fd523a10 Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 18:08:04 +0200 Subject: [PATCH 03/11] Refactor FFT Stages Application to support separate input and output ranges. --- src/Nebulite/Math/FFT.cpp | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/Nebulite/Math/FFT.cpp b/src/Nebulite/Math/FFT.cpp index 6066371df..84b8de6bb 100644 --- a/src/Nebulite/Math/FFT.cpp +++ b/src/Nebulite/Math/FFT.cpp @@ -54,7 +54,7 @@ struct BitReversalPermutation { Closure(std::size_t rangeSize) : n(rangeSize) {} template - auto operator()(R&& r) const { + static void apply(R& r, std::size_t const n) { auto const bitCount = static_cast(std::bit_width(n - 1)); assert(r.size() == n); assert(std::has_single_bit(n)); // n must be a power of two @@ -63,6 +63,11 @@ struct BitReversalPermutation { std::ranges::swap(r[i], r[b]); } } + } + + template + auto operator()(R&& r) const { + apply(r, n); return std::forward(r); } }; @@ -79,32 +84,37 @@ struct ApplyStages { Closure(std::size_t const rangeSize, double const a) : n(rangeSize), fullAngle(a) {} - template - static void applyStage(R& r, std::complex const stageTwiddle, std::size_t const stageSize, std::size_t const n) { + template + static void applySingleStage(I& input, O& output, std::complex const stageTwiddle, std::size_t const stageSize, std::size_t const n) { auto const halfStageSize = stageSize / 2; for (auto const i : Utility::Generate::indices(n) | std::views::stride(stageSize)) { std::complex w(1.0); for (auto const j : Utility::Generate::indices(halfStageSize)) { - auto const u = r[i + j]; - auto const v = r[i + j + halfStageSize] * w; + auto const u = input[i + j]; + auto const v = input[i + j + halfStageSize] * w; - r[i + j] = u + v; - r[i + j + halfStageSize] = u - v; + output[i + j] = u + v; + output[i + j + halfStageSize] = u - v; w *= stageTwiddle; } } } - template - auto operator()(R&& r) const { + template + static void apply(I& input, O& output, std::size_t const n, double const fullAngle) { for (auto const stageSize : Utility::Generate::powersOfTwo(n)) { double const ang = fullAngle / static_cast(stageSize); std::complex const stageTwiddle(std::cos(ang), std::sin(ang)); - applyStage(r, stageTwiddle, stageSize, n); + applySingleStage(input, output, stageTwiddle, stageSize, n); } + } + + template + auto operator()(R&& r) const { + apply(r, r, n, fullAngle); return std::forward(r); } }; From c62e5df753bb2ceaf2ae8a4fb573491da2ba42b5 Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 18:17:16 +0200 Subject: [PATCH 04/11] Separating ranges for applySingleStage into in and out wasn't possible, revert changes. --- src/Nebulite/Math/FFT.cpp | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/Nebulite/Math/FFT.cpp b/src/Nebulite/Math/FFT.cpp index 84b8de6bb..5f221555e 100644 --- a/src/Nebulite/Math/FFT.cpp +++ b/src/Nebulite/Math/FFT.cpp @@ -84,37 +84,39 @@ struct ApplyStages { Closure(std::size_t const rangeSize, double const a) : n(rangeSize), fullAngle(a) {} - template - static void applySingleStage(I& input, O& output, std::complex const stageTwiddle, std::size_t const stageSize, std::size_t const n) { + template + static void applySingleStage(R& r, std::complex const stageTwiddle, std::size_t const stageSize, std::size_t const n) { + assert(r.size() >= n); + auto const halfStageSize = stageSize / 2; for (auto const i : Utility::Generate::indices(n) | std::views::stride(stageSize)) { std::complex w(1.0); for (auto const j : Utility::Generate::indices(halfStageSize)) { - auto const u = input[i + j]; - auto const v = input[i + j + halfStageSize] * w; + auto const u = r[i + j]; + auto const v = r[i + j + halfStageSize] * w; - output[i + j] = u + v; - output[i + j + halfStageSize] = u - v; + r[i + j] = u + v; + r[i + j + halfStageSize] = u - v; w *= stageTwiddle; } } } - template - static void apply(I& input, O& output, std::size_t const n, double const fullAngle) { + template + static void apply(R& r, std::size_t const n, double const fullAngle) { for (auto const stageSize : Utility::Generate::powersOfTwo(n)) { double const ang = fullAngle / static_cast(stageSize); std::complex const stageTwiddle(std::cos(ang), std::sin(ang)); - applySingleStage(input, output, stageTwiddle, stageSize, n); + applySingleStage(r, stageTwiddle, stageSize, n); } } template auto operator()(R&& r) const { - apply(r, r, n, fullAngle); + apply(r, n, fullAngle); return std::forward(r); } }; From b30e10a7fb832b8da8dc553017c8c67b624689cd Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 18:35:19 +0200 Subject: [PATCH 05/11] Add range utilities and concepts for indexable and mutable ranges, improve normalize to allow for inplace-range-normalization. --- include/Nebulite/Utility/Ranges.hpp | 389 +++++++++++++++------------- 1 file changed, 212 insertions(+), 177 deletions(-) diff --git a/include/Nebulite/Utility/Ranges.hpp b/include/Nebulite/Utility/Ranges.hpp index c46bc8c3a..17200f3c4 100644 --- a/include/Nebulite/Utility/Ranges.hpp +++ b/include/Nebulite/Utility/Ranges.hpp @@ -15,6 +15,19 @@ #include #include + + + + + + +//------------------------------------------ +/** + * @namespace Nebulite::Utility::Ranges + * @brief Pipeable range utilities + */ +namespace Nebulite::Utility::Ranges { + //------------------------------------------ // Concepts @@ -26,227 +39,249 @@ concept OptionalLike = requires(T x) { *x; }; +template +using index_reference_t = decltype(std::declval()[std::declval>()]); + +template +concept IndexableRange = std::ranges::range + && requires(R& r, std::ranges::range_size_t i){ + r[i]; + }; + +template +concept MutableRange = IndexableRange + && requires(R& r, std::ranges::range_size_t i) { + requires std::is_lvalue_reference_v>; + requires std::assignable_from, std::ranges::range_value_t>; + requires std::swappable>; + }; + //------------------------------------------ -namespace Nebulite::Utility { +// Range Utilities + /** - * @brief Pipeable range utilities + * @brief Collects a range of optional values into an optional vector. If any value in the range is empty, the result will be an empty optional. */ -class Ranges { -public: +static struct CollectOptional : std::ranges::range_adaptor_closure { /** * @brief Collects a range of optional values into an optional vector. If any value in the range is empty, the result will be an empty optional. + * @tparam R The type of the input range. + * @param r The input range of optional values. + * @return An optional vector containing the collected values, or an empty optional if any value in the range is empty. */ - static struct CollectOptional : std::ranges::range_adaptor_closure { - /** - * @brief Collects a range of optional values into an optional vector. If any value in the range is empty, the result will be an empty optional. - * @tparam R The type of the input range. - * @param r The input range of optional values. - * @return An optional vector containing the collected values, or an empty optional if any value in the range is empty. - */ - template requires OptionalLike> - auto operator()(R&& r) const{ - using Optional = std::remove_cvref_t>; - using T = Optional::value_type; + template requires OptionalLike> + auto operator()(R&& r) const{ + using Optional = std::remove_cvref_t>; + using T = Optional::value_type; + + std::vector result; + if constexpr (std::ranges::sized_range) { + result.reserve(std::ranges::size(r)); + } - std::vector result; - if constexpr (std::ranges::sized_range) { - result.reserve(std::ranges::size(r)); + for (auto&& opt : std::forward(r)) { + if (!opt) { + return std::optional>{std::nullopt}; } - - for (auto&& opt : std::forward(r)) { - if (!opt) { - return std::optional>{std::nullopt}; - } - result.push_back(*std::forward(opt)); - } - return std::optional>{std::move(result)}; + result.push_back(*std::forward(opt)); } - } constexpr collectOptional{}; + return std::optional>{std::move(result)}; + } +} constexpr collectOptional{}; +/** + * @brief Collects a range of values into a vector with a transformation function. + * If the transformation function returns an empty optional for any value, the result will be an empty optional. + */ +static struct TryTransform { /** * @brief Collects a range of values into a vector with a transformation function. * If the transformation function returns an empty optional for any value, the result will be an empty optional. + * @tparam F The type of the transformation function. */ - static struct TryTransform { - /** - * @brief Collects a range of values into a vector with a transformation function. - * If the transformation function returns an empty optional for any value, the result will be an empty optional. - * @tparam F The type of the transformation function. - */ - template - struct Closure : std::ranges::range_adaptor_closure> { - F f; - - explicit constexpr Closure(F func) : f(std::move(func)){} - - template - auto operator()(R&& r) const { - using Optional = std::remove_cvref_t>>; - using T = Optional::value_type; - - std::vector result; - if constexpr (std::ranges::sized_range) { - result.reserve(std::ranges::size(r)); - } + template + struct Closure : std::ranges::range_adaptor_closure> { + F f; - for (auto&& elem : std::forward(r)) { - auto value = std::invoke(f, elem); - if (!value) { - return std::optional>{std::nullopt}; - } - result.push_back(std::move(*value)); - } + explicit constexpr Closure(F func) : f(std::move(func)){} + + template + auto operator()(R&& r) const { + using Optional = std::remove_cvref_t>>; + using T = Optional::value_type; + + std::vector result; + if constexpr (std::ranges::sized_range) { + result.reserve(std::ranges::size(r)); + } - return std::optional>{std::move(result)}; + for (auto&& elem : std::forward(r)) { + auto value = std::invoke(f, elem); + if (!value) { + return std::optional>{std::nullopt}; + } + result.push_back(std::move(*value)); } - }; - template - auto operator()(F f) const { - return Closure>{ - std::move(f), - }; + return std::optional>{std::move(result)}; } - } constexpr tryTransform{}; + }; - /** - * @brief An alternative implementation of std::views::enumerate, where the enumeration index is of type std::size_t - */ - static struct Enumerate : std::ranges::range_adaptor_closure { - template - struct EnumerateItem { - std::size_t index; - T value; + template + auto operator()(F f) const { + return Closure>{ + std::move(f), }; + } +} constexpr tryTransform{}; - // A simple enumerate view implementation that yields EnumerateItem{index, element} - template - requires std::ranges::input_range - struct EnumerateView : std::ranges::view_interface> { - V base = V(); - - EnumerateView() = default; - explicit EnumerateView(V b) : base(std::move(b)) {} - - using BaseIterator = std::ranges::iterator_t; - using BaseSentinel = std::ranges::sentinel_t; - - struct Iterator { - BaseIterator it{}; - std::size_t index = 0; - - using iterator_category = std::input_iterator_tag; // NOLINT - using value_type = EnumerateItem>; // NOLINT - using difference_type = std::ptrdiff_t; // NOLINT - - Iterator() = default; - Iterator(BaseIterator const& i, std::size_t const idx) : it(i), index(idx) {} - - value_type operator*() const { - return value_type{index, *it}; - } - - Iterator& operator++() { - ++it; - ++index; - return *this; - } - - void operator++(int) { ++*this; } +/** + * @brief An alternative implementation of std::views::enumerate, where the enumeration index is of type std::size_t + */ +static struct Enumerate : std::ranges::range_adaptor_closure { + template + struct EnumerateItem { + std::size_t index; + T value; + }; + + // A simple enumerate view implementation that yields EnumerateItem{index, element} + template + requires std::ranges::input_range + struct EnumerateView : std::ranges::view_interface> { + V base = V(); + + EnumerateView() = default; + explicit EnumerateView(V b) : base(std::move(b)) {} + + using BaseIterator = std::ranges::iterator_t; + using BaseSentinel = std::ranges::sentinel_t; + + struct Iterator { + BaseIterator it{}; + std::size_t index = 0; + + using iterator_category = std::input_iterator_tag; // NOLINT + using value_type = EnumerateItem>; // NOLINT + using difference_type = std::ptrdiff_t; // NOLINT + + Iterator() = default; + Iterator(BaseIterator const& i, std::size_t const idx) : it(i), index(idx) {} + + value_type operator*() const { + return value_type{index, *it}; + } - friend bool operator==(Iterator const& a, BaseIterator const& b) { return a.it == b; } - }; + Iterator& operator++() { + ++it; + ++index; + return *this; + } - struct Sentinel { - BaseSentinel end; - }; + void operator++(int) { ++*this; } - Iterator begin() { return Iterator{std::ranges::begin(base), 0}; } - Sentinel end() { return Sentinel{std::ranges::end(base)}; } + friend bool operator==(Iterator const& a, BaseIterator const& b) { return a.it == b; } + }; - // compare Iterator and sentinel - friend bool operator==(Iterator const& it, Sentinel const& s) { return it.it == s.end; } - friend bool operator==(Sentinel const& s, Iterator const& it) { return it == s; } + struct Sentinel { + BaseSentinel end; }; - template - auto operator()(R&& r) const { - using V = std::views::all_t; - return EnumerateView(std::views::all(std::forward(r))); - } - } constexpr enumerate{}; + Iterator begin() { return Iterator{std::ranges::begin(base), 0}; } + Sentinel end() { return Sentinel{std::ranges::end(base)}; } - /** - * @brief Checks if all elements in a range are equal and satisfy a given predicate. - */ - static struct AllEqualAnd : std::ranges::range_adaptor_closure{ - template - struct Closure : range_adaptor_closure>{ - Pred pred; + // compare Iterator and sentinel + friend bool operator==(Iterator const& it, Sentinel const& s) { return it.it == s.end; } + friend bool operator==(Sentinel const& s, Iterator const& it) { return it == s; } + }; - explicit Closure(Pred p) : pred(std::move(p)){} + template + auto operator()(R&& r) const { + using V = std::views::all_t; + return EnumerateView(std::views::all(std::forward(r))); + } +} constexpr enumerate{}; - template - bool operator()(R&& r) const { - if (std::ranges::empty(r)) { - return true; - } - auto const& first = *std::ranges::begin(r); - return std::ranges::all_of(std::forward(r), [this, first](auto const& elem) { - return std::invoke(pred, elem) && elem == first; - }); - } - }; +/** + * @brief Checks if all elements in a range are equal and satisfy a given predicate. + */ +static struct AllEqualAnd : std::ranges::range_adaptor_closure{ + template + struct Closure : range_adaptor_closure>{ + Pred pred; - template - auto operator()(Pred pred) const { - return Closure>{ - std::move(pred), - }; - } - } constexpr allEqualAnd{}; + explicit Closure(Pred p) : pred(std::move(p)){} - /** - * @brief Checks if all elements in a range are equal - */ - static struct AllEqual : std::ranges::range_adaptor_closure{ template bool operator()(R&& r) const { if (std::ranges::empty(r)) { return true; } auto const& first = *std::ranges::begin(r); - return std::ranges::all_of(std::forward(r), [first](auto const& elem) { - return elem == first; + return std::ranges::all_of(std::forward(r), [this, first](auto const& elem) { + return std::invoke(pred, elem) && elem == first; }); } - } constexpr allEqual{}; + }; - /** - * @brief Normalizes a given range by a value n, keeping the type the same. - */ - static struct Normalize { - struct Closure : std::ranges::range_adaptor_closure { - std::size_t const n; - - template - auto operator()(R&& r) const { - auto const dN = static_cast(n); - return std::forward(r) - | std::views::transform([dN] (auto const& v) { - return v / dN; - }); - } + template + auto operator()(Pred pred) const { + return Closure>{ + std::move(pred), }; + } +} constexpr allEqualAnd{}; - auto operator()(std::size_t const n) const { - return Closure{ - {}, // NOLINT - n, - }; +/** + * @brief Checks if all elements in a range are equal + */ +static struct AllEqual : std::ranges::range_adaptor_closure{ + template + bool operator()(R&& r) const { + if (std::ranges::empty(r)) { + return true; + } + auto const& first = *std::ranges::begin(r); + return std::ranges::all_of(std::forward(r), [first](auto const& elem) { + return elem == first; + }); + } +} constexpr allEqual{}; + +/** + * @brief Normalizes a given range by a value n, keeping the type the same. + */ +static struct Normalize { + struct Closure : std::ranges::range_adaptor_closure { + std::size_t const n; + + // Specialization for mutable ranges: modifies the range in place + template + auto operator()(R&& r) const { + auto const dN = static_cast(n); + for (auto& v : r) { + v /= dN; + } + return std::forward(r); } - } constexpr normalize{}; -}; -} // namespace Nebulite::Utility + // Specialization for input ranges: returns a transformed view + template requires (!MutableRange) + auto operator()(R&& r) const { + auto const dN = static_cast(n); + return std::forward(r) + | std::views::transform([dN] (auto const& v) { + return v / dN; + }); + } + }; + + auto operator()(std::size_t const n) const { + return Closure{ + {}, // NOLINT + n, + }; + } +} constexpr normalize{}; +} // namespace Nebulite::Utility::Ranges #endif // NEBULITE_UTILITY_RANGES_HPP From 7c4221dd7c56aa6035cb875768a139b25862c157 Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 18:38:19 +0200 Subject: [PATCH 06/11] Fix reallocation issues in Fft library, use new Utility::Ranges concepts. --- src/Nebulite/Math/FFT.cpp | 41 ++++++++++----------------------------- 1 file changed, 10 insertions(+), 31 deletions(-) diff --git a/src/Nebulite/Math/FFT.cpp b/src/Nebulite/Math/FFT.cpp index 5f221555e..80f372e1c 100644 --- a/src/Nebulite/Math/FFT.cpp +++ b/src/Nebulite/Math/FFT.cpp @@ -22,26 +22,6 @@ #include "Nebulite/Utility/Generate.hpp" #include "Nebulite/Utility/Ranges.hpp" -//------------------------------------------ -// Concepts - -template -using index_reference_t = decltype(std::declval()[std::declval>()]); - -template -concept IndexableRange = std::ranges::range - && requires(R& r, std::ranges::range_size_t i){ - r[i]; - }; - -template -concept MutableRange = IndexableRange - && requires(R& r, std::ranges::range_size_t i) { - requires std::is_lvalue_reference_v>; - requires std::assignable_from, std::ranges::range_value_t>; - requires std::swappable>; - }; - //------------------------------------------ namespace Nebulite::Math::Fft { @@ -53,7 +33,7 @@ struct BitReversalPermutation { Closure(std::size_t rangeSize) : n(rangeSize) {} - template + template static void apply(R& r, std::size_t const n) { auto const bitCount = static_cast(std::bit_width(n - 1)); assert(r.size() == n); @@ -65,7 +45,7 @@ struct BitReversalPermutation { } } - template + template auto operator()(R&& r) const { apply(r, n); return std::forward(r); @@ -84,7 +64,7 @@ struct ApplyStages { Closure(std::size_t const rangeSize, double const a) : n(rangeSize), fullAngle(a) {} - template + template static void applySingleStage(R& r, std::complex const stageTwiddle, std::size_t const stageSize, std::size_t const n) { assert(r.size() >= n); @@ -105,7 +85,7 @@ struct ApplyStages { } } - template + template static void apply(R& r, std::size_t const n, double const fullAngle) { for (auto const stageSize : Utility::Generate::powersOfTwo(n)) { double const ang = fullAngle / static_cast(stageSize); @@ -114,7 +94,7 @@ struct ApplyStages { } } - template + template auto operator()(R&& r) const { apply(r, n, fullAngle); return std::forward(r); @@ -140,8 +120,7 @@ std::vector> fft(std::vector const& data) { std::copy_n(data.begin(), data.size(), a.begin()); return a | bitReversalPermutation(n) - | applyStagesForward(n) - | std::ranges::to>>(); + | applyStagesForward(n); } std::vector> fftInverse(std::vector> const& xValues) { @@ -152,15 +131,15 @@ std::vector> fftInverse(std::vector> c return a | bitReversalPermutation(n) | applyStagesInverse(n) - | Utility::Ranges::normalize(n) - | std::ranges::to>>(); + | Utility::Ranges::normalize(n); } namespace { -std::complex evaluatePolynomial(std::vector const& coefficients, std::complex const z) { +template +std::complex evaluatePolynomial(R&& coefficients, std::complex const z) { std::complex zPow(1.0); std::complex result(0.0); - for (double const c : coefficients | std::views::reverse) { // coefficients hold highest order first + for (double const c : std::forward(coefficients) | std::views::reverse) { // coefficients hold highest order first assert(!std::isnan(c)); result += c * zPow; zPow *= z; From 6b970802086e4711b03750d4d229c4c05e865735 Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 18:42:38 +0200 Subject: [PATCH 07/11] Code cleanup --- include/Nebulite/Utility/Ranges.hpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/include/Nebulite/Utility/Ranges.hpp b/include/Nebulite/Utility/Ranges.hpp index 17200f3c4..2ff05776d 100644 --- a/include/Nebulite/Utility/Ranges.hpp +++ b/include/Nebulite/Utility/Ranges.hpp @@ -15,12 +15,6 @@ #include #include - - - - - - //------------------------------------------ /** * @namespace Nebulite::Utility::Ranges From 4180885a7ff162089fe9eab79efd08aaad126c9e Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 20:01:49 +0200 Subject: [PATCH 08/11] Use inplace-bitreversal-permutation to avoid unnecessary double-copying of input data. --- include/Nebulite/Utility/Ranges.hpp | 78 +++++++++++++++++++++++++++++ src/Nebulite/Math/FFT.cpp | 56 ++++----------------- 2 files changed, 88 insertions(+), 46 deletions(-) diff --git a/include/Nebulite/Utility/Ranges.hpp b/include/Nebulite/Utility/Ranges.hpp index 2ff05776d..5c06ba9c5 100644 --- a/include/Nebulite/Utility/Ranges.hpp +++ b/include/Nebulite/Utility/Ranges.hpp @@ -6,6 +6,8 @@ // Standard library #include +#include +#include #include #include #include @@ -15,6 +17,10 @@ #include #include +// Nebulite +#include "Nebulite/Utility/Convert/Bits.hpp" +#include "Nebulite/Utility/Generate.hpp" + //------------------------------------------ /** * @namespace Nebulite::Utility::Ranges @@ -277,5 +283,77 @@ static struct Normalize { }; } } constexpr normalize{}; + +struct InplaceBitReversalPermutation { + struct Closure : std::ranges::range_adaptor_closure { + std::size_t n; + + Closure(std::size_t rangeSize) : n(rangeSize) {} + + template + static void apply(R& r, std::size_t const n) { + auto const bitCount = static_cast(std::bit_width(n - 1)); + assert(r.size() == n); + assert(std::has_single_bit(n)); // n must be a power of two + for (auto const i : Generate::indices(n)) { + if (auto const b = Convert::Bits::reverse(i, bitCount); i < b) { + std::ranges::swap(r[i], r[b]); + } + } + } + + template + auto operator()(R&& r) const { + apply(r, n); + return std::forward(r); + } + }; + + auto operator()(std::size_t const n) const { + return Closure(n); + } +} constexpr inplaceBitReversalPermutation; // NOLINT + +/** + * @brief Creates a copy of a range with elements permuted according to the bit-reversal permutation. + */ +struct CopyBitReversalPermutation { + template + struct Closure : std::ranges::range_adaptor_closure> { + std::size_t n; + T t; + + Closure(std::size_t rangeSize, T const defaultValue) : n(rangeSize), t(defaultValue) {} + + template + static std::vector apply(R const& r, std::size_t const n, T const defaultValue) { + std::vector result(n); + auto const bitCount = static_cast(std::bit_width(n - 1)); + assert(std::has_single_bit(n)); // n must be a power of two + for (auto const source : Generate::indices(n)) { + auto const destination = Convert::Bits::reverse(source, bitCount); + + if (source >= r.size()) { + result[destination] = defaultValue; + } + else { + result[destination] = static_cast(r[source]); + } + } + return std::move(result); + } + + template + std::vector operator()(R const& r) const { + return apply(r, n, t); + } + }; + + template + auto operator()(std::size_t const n, T const defaultValue = T{}) const { + return Closure(n, std::move(defaultValue)); + } +} constexpr copyBitReversalPermutation; + } // namespace Nebulite::Utility::Ranges #endif // NEBULITE_UTILITY_RANGES_HPP diff --git a/src/Nebulite/Math/FFT.cpp b/src/Nebulite/Math/FFT.cpp index 80f372e1c..d4e7db8fb 100644 --- a/src/Nebulite/Math/FFT.cpp +++ b/src/Nebulite/Math/FFT.cpp @@ -2,12 +2,10 @@ // Includes // Standard library -#include #include #include #include #include -#include #include #include #include @@ -18,7 +16,6 @@ // Nebulite #include "Nebulite/Math/Equality.hpp" #include "Nebulite/Math/FFT.hpp" -#include "Nebulite/Utility/Convert/Bits.hpp" #include "Nebulite/Utility/Generate.hpp" #include "Nebulite/Utility/Ranges.hpp" @@ -27,37 +24,7 @@ namespace Nebulite::Math::Fft { namespace { -struct BitReversalPermutation { - struct Closure : std::ranges::range_adaptor_closure { - std::size_t n; - - Closure(std::size_t rangeSize) : n(rangeSize) {} - - template - static void apply(R& r, std::size_t const n) { - auto const bitCount = static_cast(std::bit_width(n - 1)); - assert(r.size() == n); - assert(std::has_single_bit(n)); // n must be a power of two - for (auto const i : Utility::Generate::indices(n)) { - if (auto const b = Utility::Convert::Bits::reverse(i, bitCount); i < b) { - std::ranges::swap(r[i], r[b]); - } - } - } - - template - auto operator()(R&& r) const { - apply(r, n); - return std::forward(r); - } - }; - - auto operator()(std::size_t const n) const { - return Closure(n); - } -} constexpr bitReversalPermutation; - -struct ApplyStages { +struct InplaceApplyStages { struct Closure : std::ranges::range_adaptor_closure { std::size_t const n; double const fullAngle; @@ -108,29 +75,26 @@ struct ApplyStages { } }; -inline constexpr ApplyStages applyStagesForward{ -2.0 * std::numbers::pi }; -inline constexpr ApplyStages applyStagesInverse{ 2.0 * std::numbers::pi }; +inline constexpr InplaceApplyStages inplaceApplyStagesForward{ -2.0 * std::numbers::pi }; +inline constexpr InplaceApplyStages inplaceApplyStagesInverse{ 2.0 * std::numbers::pi }; } // namespace std::vector> fft(std::vector const& data) { if (data.empty()) return {}; auto const n = std::bit_ceil(data.size()); // next power of two - std::vector> a(n); // Initialized to 0.0 - std::copy_n(data.begin(), data.size(), a.begin()); - return a - | bitReversalPermutation(n) - | applyStagesForward(n); + return data + | Utility::Ranges::copyBitReversalPermutation(n, std::complex{0.0}) + | inplaceApplyStagesForward(n); } std::vector> fftInverse(std::vector> const& xValues) { auto const n = std::bit_ceil(xValues.size()); // next power of two if (n == 0) return {}; - std::vector> a = xValues; - a.resize(n); - return a - | bitReversalPermutation(n) - | applyStagesInverse(n) + + return xValues + | Utility::Ranges::copyBitReversalPermutation(n, std::complex{0.0}) + | inplaceApplyStagesInverse(n) | Utility::Ranges::normalize(n); } From e205ab46cce5398416b17ab92bf9239d02c6a586 Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 20:02:31 +0200 Subject: [PATCH 09/11] Code cleanup --- include/Nebulite/Math/FFT.hpp | 58 +++++++++++++++++------------------ 1 file changed, 29 insertions(+), 29 deletions(-) diff --git a/include/Nebulite/Math/FFT.hpp b/include/Nebulite/Math/FFT.hpp index 28466eebe..0f2d41fce 100644 --- a/include/Nebulite/Math/FFT.hpp +++ b/include/Nebulite/Math/FFT.hpp @@ -14,37 +14,37 @@ * @brief Functions for performing Fast Fourier Transform (FFT) and related operations on audio data. */ namespace Nebulite::Math::Fft { - /** - * @brief Computes the Fast Fourier Transform (FFT) of the given sound data. - * @param data The sound data to transform. - * @return A vector of complex numbers representing the FFT of the sound data. - */ - std::vector> fft(std::vector const& data); +/** + * @brief Computes the Fast Fourier Transform (FFT) of the given sound data. + * @param data The sound data to transform. + * @return A vector of complex numbers representing the FFT of the sound data. + */ +std::vector> fft(std::vector const& data); - /** - * @brief Computes the Inverse Fast Fourier Transform (IFFT) of the given frequency-domain data. - * @param xValues The frequency-domain data to transform back to the time domain. - * @return A vector of complex numbers representing the IFFT of the input data, which can be converted back to audio samples. - */ - std::vector> fftInverse(std::vector> const& xValues); +/** + * @brief Computes the Inverse Fast Fourier Transform (IFFT) of the given frequency-domain data. + * @param xValues The frequency-domain data to transform back to the time domain. + * @return A vector of complex numbers representing the IFFT of the input data, which can be converted back to audio samples. + */ +std::vector> fftInverse(std::vector> const& xValues); - /** - * @brief Evaluates the transfer function defined by the given numerator and denominator coefficients at a specific angular frequency omega. - * @param omega The angular frequency (in radians per second) at which to evaluate the transfer function. - * @param num The coefficients of the numerator of the transfer function, starting with the highest order. - * @param den The coefficients of the denominator of the transfer function, starting with the highest order. - * @return A complex number representing the value of the transfer function at the specified frequency. - */ - std::complex evalTransfer(double omega,std::vector const& num,std::vector const& den); +/** + * @brief Evaluates the transfer function defined by the given numerator and denominator coefficients at a specific angular frequency omega. + * @param omega The angular frequency (in radians per second) at which to evaluate the transfer function. + * @param num The coefficients of the numerator of the transfer function, starting with the highest order. + * @param den The coefficients of the denominator of the transfer function, starting with the highest order. + * @return A complex number representing the value of the transfer function at the specified frequency. + */ +std::complex evalTransfer(double omega,std::vector const& num,std::vector const& den); - /** - * @brief Applies a transfer function defined by the given numerator and denominator coefficients to the input sound data in the frequency domain. - * @param data The input sound data to which the transfer function will be applied. - * @param num The coefficients of the numerator of the transfer function, starting with the highest order. - * @param den The coefficients of the denominator of the transfer function, starting with the highest order. - * @return A vector of doubles representing the sound data after applying the transfer function in the frequency domain. - * @throws std::domain_error if the leading coefficient of the denominator is zero, which is not supported. - */ - std::vector applyTransferFunctionFrequencyDomain(std::vector const& data, std::vector const& num, std::vector const& den); +/** + * @brief Applies a transfer function defined by the given numerator and denominator coefficients to the input sound data in the frequency domain. + * @param data The input sound data to which the transfer function will be applied. + * @param num The coefficients of the numerator of the transfer function, starting with the highest order. + * @param den The coefficients of the denominator of the transfer function, starting with the highest order. + * @return A vector of doubles representing the sound data after applying the transfer function in the frequency domain. + * @throws std::domain_error if the leading coefficient of the denominator is zero, which is not supported. + */ +std::vector applyTransferFunctionFrequencyDomain(std::vector const& data, std::vector const& num, std::vector const& den); } // namespace Nebulite::Math::Fft #endif // NEBULITE_MATH_FFT_HPP From 87d1c6636612d5bcd0cf0fa8f5a09096ad207479 Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 20:45:57 +0200 Subject: [PATCH 10/11] Add large FFT benchmark to FeatureTest and update profiling tasks --- TaskFiles/Benchmarks/fft.nebs | 5 +++ TaskFiles/Debugging/profiling.nebs | 7 +++- .../Module/Domain/GlobalSpace/FeatureTest.hpp | 10 +++++ .../Module/Domain/GlobalSpace/FeatureTest.cpp | 40 +++++++++++++++++++ 4 files changed, 61 insertions(+), 1 deletion(-) create mode 100644 TaskFiles/Benchmarks/fft.nebs diff --git a/TaskFiles/Benchmarks/fft.nebs b/TaskFiles/Benchmarks/fft.nebs new file mode 100644 index 000000000..4e6d46ee8 --- /dev/null +++ b/TaskFiles/Benchmarks/fft.nebs @@ -0,0 +1,5 @@ +# Testing benchmark for FFT (Fast Fourier Transform) implementation +# Using the featuretest module so we don' have to benchmark with the slower transformation fft. + +feature-test large-fft 10000000 +exit \ No newline at end of file diff --git a/TaskFiles/Debugging/profiling.nebs b/TaskFiles/Debugging/profiling.nebs index 7e3cf903e..34b1c3223 100644 --- a/TaskFiles/Debugging/profiling.nebs +++ b/TaskFiles/Debugging/profiling.nebs @@ -24,7 +24,8 @@ echo "Starting profiling.nebs" # - loading # - jsonRuleset # - parsing -set settings.profilingTask transformations +# - fft +set settings.profilingTask fft #################################################### ################### @@ -50,3 +51,7 @@ if $({global:settings.profilingTask|strCompare equals jsonRuleset}) then task Ta ################### # 6.) Parsing performance if $({global:settings.profilingTask|strCompare equals parsing}) then task TaskFiles/Benchmarks/parsing.nebs + +################### +# 7.) FFT performance +if $({global:settings.profilingTask|strCompare equals fft}) then task TaskFiles/Benchmarks/fft.nebs \ No newline at end of file diff --git a/include/Nebulite/Module/Domain/GlobalSpace/FeatureTest.hpp b/include/Nebulite/Module/Domain/GlobalSpace/FeatureTest.hpp index 659ea27e3..346d9622d 100644 --- a/include/Nebulite/Module/Domain/GlobalSpace/FeatureTest.hpp +++ b/include/Nebulite/Module/Domain/GlobalSpace/FeatureTest.hpp @@ -60,6 +60,13 @@ class FeatureTest final : public Base::DomainModule { "Usage: feature-test find-parent-key \n" "Using no argument will treated as an empty key.\n"; + // Benchmarks + + [[nodiscard]] Constants::Event largeFft(std::span args) const ; + static auto constexpr largeFftName = "feature-test large-fft"; + static auto constexpr largeFftDesc = "Tests the FFT implementation with a large dataset.\n" + "Usage: feature-test large-fft \n"; + //------------------------------------------ // Categories @@ -85,6 +92,9 @@ class FeatureTest final : public Base::DomainModule { // Keys bindFunction(&FeatureTest::keyCombination, keyCombinationName, keyCombinationDesc); bindFunction(&FeatureTest::findParentKey, findParentKeyName, findParentKeyDesc); + + // Benchmarks + bindFunction(&FeatureTest::largeFft, largeFftName, largeFftDesc); } struct Key : Data::KeyGroup<""> { diff --git a/src/Nebulite/Module/Domain/GlobalSpace/FeatureTest.cpp b/src/Nebulite/Module/Domain/GlobalSpace/FeatureTest.cpp index ae77a6b59..782322448 100644 --- a/src/Nebulite/Module/Domain/GlobalSpace/FeatureTest.cpp +++ b/src/Nebulite/Module/Domain/GlobalSpace/FeatureTest.cpp @@ -2,11 +2,15 @@ // Includes // Standard library +#include +#include +#include #include #include #include #include #include +#include // Nebulite #include "Nebulite/Constants/Event.hpp" @@ -15,9 +19,12 @@ #include "Nebulite/Data/Document/Json.hpp" #include "Nebulite/Data/Document/ScopedKey.hpp" #include "Nebulite/Interaction/Logic/Expression.hpp" +#include "Nebulite/Math/FFT.hpp" #include "Nebulite/Module/Domain/GlobalSpace/FeatureTest.hpp" #include "Nebulite/Utility/Args/FuncTree.hpp" +#include "Nebulite/Utility/Convert/Cast.hpp" #include "Nebulite/Utility/StringHandler.hpp" +#include "Nebulite/Utility/Time.hpp" //------------------------------------------ namespace Nebulite::Module::Domain::GlobalSpace { @@ -114,4 +121,37 @@ Constants::Event FeatureTest::findParentKey(std::span co return Constants::Event::success; } +Constants::Event FeatureTest::largeFft(std::span const args) const { + if (args.size() < 2) { + return Constants::StandardCapture::Warning::Functional::tooFewArgs(domain.capture); + } + if (args.size() > 2) { + return Constants::StandardCapture::Warning::Functional::tooManyArgs(domain.capture); + } + + auto size = Utility::Convert::Cast::String::to(args[1]); + if (!size.has_value()) { + return Constants::StandardCapture::Warning::Functional::invalidArgument(domain.capture); + } + + std::vector data(size.value(), 0.0); + for (std::size_t i = 0; i < size.value(); ++i) { + data[i] = static_cast(i % 100); // Fill with some sample data + } + + auto start = Utility::Time::getTime(); + auto const result = Math::Fft::fft(data); + auto end = Utility::Time::getTime(); + + domain.capture.log.println("FFT of size ", size.value(), " computed. Took ", end - start, " ms. First 10 results of ", result.size(), " total:"); + for (std::size_t i = 0; i < std::min(result.size(), static_cast(10)); ++i) { + domain.capture.log.println(result[i]); + } + if (result.size() != std::bit_ceil(size.value())) { + domain.capture.error.println("FFT result size mismatch: expected ", std::bit_ceil(size.value()), " but got ", result.size()); + return Constants::Event::error; + } + return Constants::Event::success; +} + } // namespace Nebulite::Module::Domain::GlobalSpace From 6cfeac7d082966a8da3d0f38730d4a2171f73635 Mon Sep 17 00:00:00 2001 From: Leo Date: Fri, 28 Aug 2026 22:01:24 +0200 Subject: [PATCH 11/11] Optimize FFT operations by eliminating bounds checks and using direct data access --- include/Nebulite/Utility/Ranges.hpp | 18 ++++++++++++++---- src/Nebulite/Math/FFT.cpp | 21 +++++++++++++-------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/include/Nebulite/Utility/Ranges.hpp b/include/Nebulite/Utility/Ranges.hpp index 5c06ba9c5..ba660b2c4 100644 --- a/include/Nebulite/Utility/Ranges.hpp +++ b/include/Nebulite/Utility/Ranges.hpp @@ -295,9 +295,13 @@ struct InplaceBitReversalPermutation { auto const bitCount = static_cast(std::bit_width(n - 1)); assert(r.size() == n); assert(std::has_single_bit(n)); // n must be a power of two + + // Since we verified the size, we can access directly without bounds checking. This is a performance optimization. + auto* data = std::ranges::data(r); + for (auto const i : Generate::indices(n)) { if (auto const b = Convert::Bits::reverse(i, bitCount); i < b) { - std::ranges::swap(r[i], r[b]); + std::ranges::swap(data[i], data[b]); } } } @@ -327,17 +331,23 @@ struct CopyBitReversalPermutation { template static std::vector apply(R const& r, std::size_t const n, T const defaultValue) { + assert(std::has_single_bit(n)); // n must be a power of two + std::vector result(n); auto const bitCount = static_cast(std::bit_width(n - 1)); - assert(std::has_single_bit(n)); // n must be a power of two + + // Since we verified the size, we can access directly without bounds checking. This is a performance optimization. + auto* dstData = std::ranges::data(result); + auto* srcData = std::ranges::data(r); + for (auto const source : Generate::indices(n)) { auto const destination = Convert::Bits::reverse(source, bitCount); if (source >= r.size()) { - result[destination] = defaultValue; + dstData[destination] = defaultValue; } else { - result[destination] = static_cast(r[source]); + dstData[destination] = static_cast(srcData[source]); } } return std::move(result); diff --git a/src/Nebulite/Math/FFT.cpp b/src/Nebulite/Math/FFT.cpp index d4e7db8fb..93a168691 100644 --- a/src/Nebulite/Math/FFT.cpp +++ b/src/Nebulite/Math/FFT.cpp @@ -35,18 +35,23 @@ struct InplaceApplyStages { static void applySingleStage(R& r, std::complex const stageTwiddle, std::size_t const stageSize, std::size_t const n) { assert(r.size() >= n); - auto const halfStageSize = stageSize / 2; + // Since we verified the size, we can access directly without bounds checking. This is a performance optimization. + auto* data = std::ranges::data(r); + // Perform the FFT butterfly operation for the current stage + auto const halfStageSize = stageSize / 2; for (auto const i : Utility::Generate::indices(n) | std::views::stride(stageSize)) { - std::complex w(1.0); + std::complex w(1.0); // Preallocation of ws is about 100% slower than just computing them on the fly for large arrays, so we do that instead - for (auto const j : Utility::Generate::indices(halfStageSize)) { - auto const u = r[i + j]; - auto const v = r[i + j + halfStageSize] * w; - - r[i + j] = u + v; - r[i + j + halfStageSize] = u - v; + auto* lo = data + i; + auto* hi = data + i + halfStageSize; + for (auto const j : Utility::Generate::indices(halfStageSize)) { + assert(i + j + halfStageSize < n); + auto const u = lo[j]; + auto const v = hi[j] * w; + lo[j] = u + v; + hi[j] = u - v; w *= stageTwiddle; } }