single pitch stiff string equation simulation

This commit is contained in:
2026-06-20 16:08:39 -05:00
parent a5af4f6283
commit b4df8657dd
7 changed files with 207 additions and 27 deletions

View File

@@ -0,0 +1,68 @@
#pragma once
#include <cmath>
#include "synth/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:
// states
std::vector<float> stringY_current_;
std::vector<float> stringY_previous_;
std::vector<float> stringY_next_;
std::vector<float> stringX_;
// constants
// string parameters
size_t segmentCount_ = 30;
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.001f; // stiffness coefficient
float damping_ = 0.5f; // damping coefficient
static constexpr float stringLength_ = 1.0f; // length of string
static constexpr float strikePosition_ = 0.2f; // x of impulse location
static constexpr float impulseWidth_ = 0.02f; // x of impulse width
static constexpr float impulseVelocity_ = 10000.0f; // x/t of impulse magnitude
static constexpr float samplePosition_ = 0.1f; // 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
// eventually we'll have to dynamically tune our string according to the note that comes in
// an alternative is a fully built piano and then it calls voices under the instrument instead of how we do it currently
float f0_ = waveVelocity_ / (2.0f * stringLength_); // fundamental frequency of a non-stiff string
float f1_ = f0_ * std::sqrt(1.0f + stiffness_); // fundamental frequency of the stiff string
float dx_ = stringLength_ / 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;
};