Skip to content

File fractal_noise.h

File List > DaisySP > Source > Noise > fractal_noise.h

Go to the documentation of this file

Source Code

/*
Copyright (c) 2020 Electrosmith, Corp, Emilie Gillet

Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/

#pragma once
#ifndef DSY_FRACTAL_H
#define DSY_FRACTAL_H

#include <stdint.h>
#ifdef __cplusplus

namespace daisysp
{
template <typename T, int order>
class FractalRandomGenerator
{
  public:
    FractalRandomGenerator() {}
    ~FractalRandomGenerator() {}

    void Init(float sample_rate)
    {
        sample_rate_ = sample_rate;

        SetColor(.5f);
        SetFreq(440.f);
        for(int i = 0; i < order; ++i)
        {
            generator_[i].Init(sample_rate_);
        }
    }

    float Process()
    {
        float gain      = 0.5f;
        float sum       = 0.0f;
        float frequency = frequency_;

        for(int i = 0; i < order; ++i)
        {
            generator_[i].SetFreq(frequency);
            sum += generator_[i].Process() * gain;
            gain *= decay_;
            frequency *= 2.0f;
        }

        return sum;
    }

    void SetFreq(float freq) { frequency_ = fclamp(freq, 0.f, sample_rate_); }

    void SetColor(float color) { decay_ = fclamp(color, 0.f, 1.f); }

  private:
    float sample_rate_;
    float frequency_;
    float decay_;

    T generator_[order];
};
} // namespace daisysp
#endif
#endif