Files
sonobulus/src/synth/Instruments/PianoString.hpp
2026-07-04 13:22:25 -05:00

76 lines
2.6 KiB
C++

#pragma once
#include <cmath>
#include "synth/Instruments/Instrument.hpp"
class PianoString : public Instrument {
public:
PianoString() = default;
PianoString(ConfigService* config, LoggerService* logger);
~PianoString() = default;
void noteOn(float frequency, float velocity) override;
void noteOff() override;
bool isActive() override;
float process(bool& scopeTrigger) override;
private:
void recalculateConstants();
// states
float frequency_ = 0.0f;
std::vector<float> stringY_current_;
std::vector<float> stringY_previous_;
std::vector<float> stringY_next_;
std::vector<float> stringX_;
bool active_ = false;
// constants
// string parameters
size_t segmentCount_ = 80;
static constexpr float rho_ = 8000.0f; // density, steel, kg/m^3
static constexpr float radius_ = 0.001f; // meters
static constexpr float stringTension_ = 1200.0f; // string tension, N
static constexpr float stiffness_ = 0.0f; // stiffness coefficient
float damping_ = 0.5f; // damping coefficient
static constexpr float stringLength_ = 4.0f; // length of string at lowest frequency (20 hz)
static constexpr float strikePosition_ = 0.8f; // x of impulse location
static constexpr float impulseWidth_ = 0.1f; // x% of impulse width
static constexpr float impulseVelocity_ = 10000.0f; // x/t of impulse magnitude
static constexpr float samplePosition_ = 0.2f; // percentage along L of sampling for audio
float crossSectionalArea_ = pi * std::pow(radius_, 2.0f); // string cross sectional area, assuming circular
float mu_ = crossSectionalArea_ * rho_; // linear mass density
float waveVelocity_ = std::sqrt(stringTension_ / mu_); // transverse wave velocity
float L_ = 1.0f; // length of string at a given frequency
float gain_ = 0.5f;
// f0_ = waveVelocity_ / (2.0f * stringLength_); // fundamental frequency of a non-stiff string
// f1_ = f0_ * std::sqrt(1.0f + stiffness_); // fundamental frequency of the stiff string
uint32_t samplingSteps_ = 1;
float phaseTracker_ = 0.0f;
float dx_ = L_ / static_cast<float>(segmentCount_);
float dt_ = 1.0f / sampleRate_;
// derived constants
float r1_ = waveVelocity_ * dt_/dx_;
float r2_ = std::pow(waveVelocity_ * dt_/dx_, 2.0f);
float s1_ = stiffness_ * dt_/std::pow(dx_, 2.0f);
float s2_ = std::pow(stiffness_ * dt_/std::pow(dx_, 2.0f), 2.0f);
float a1_ = 2.0f - 2.0f * damping_ * dt_;
float a2_ = 2.0f * damping_ * dt_ - 1.0f;
// keeping track of the string's activeness
float rms_ = 0.0f;
};