hf_repo4 / src /core /spring.cpp
fava21's picture
Backup: patch pack applied + verified on Win11 22000 (d446cc1, ba8617e, dcf5cb8)
2edf277 verified
Raw History Blame Contribute Delete
2.98 kB
// FCS Glass - src/core/spring.cpp. See spring.h for the design notes.
#include "core/spring.h"
#include <cmath>
namespace fcs {
namespace core {
namespace {
constexpr double kPi = 3.14159265358979323846;
// |zeta - 1| under this is treated as critical: the under- and over-damped formulas
// divide by a term that goes to zero at zeta = 1, so they must not be used there.
constexpr double kCriticalBand = 1e-6;
double Clamp(double v, double lo, double hi) { return v < lo ? lo : (v > hi ? hi : v); }
} // namespace
void Spring::Snap() {
x_ = target_;
v_ = 0.0;
active_ = false;
}
void Spring::Reset(double value) {
x_ = value;
target_ = value;
v_ = 0.0;
active_ = false;
}
void Spring::SetTarget(double target) {
if (target != target_) {
target_ = target;
active_ = true;
}
}
void Spring::Kick(double velocity) {
if (!std::isfinite(velocity)) return;
v_ = velocity;
active_ = true;
}
void Spring::Step(double dt) {
if (!active_) return;
if (!(dt > 0.0) || !std::isfinite(dt)) return;
const double w = 2.0 * kPi * params_.freq_hz;
if (!(w > 0.0) || !std::isfinite(w)) { // no restoring force: do not hang, just arrive
Snap();
return;
}
double z = params_.damping;
if (!(z == z)) z = 1.0; // NaN damping -> critical
z = Clamp(z, kMinDamping, kMaxDamping);
const double d = x_ - target_; // displacement from the target
const double v = v_;
double nd = 0.0;
double nv = 0.0;
if (std::fabs(z - 1.0) < kCriticalBand) {
// d(t) = e^{-wt} (d0 + c t), c = v0 + w d0
const double c = v + w * d;
const double e = std::exp(-w * dt);
nd = e * (d + c * dt);
nv = e * (v - w * c * dt);
} else if (z > 1.0) {
// Over-damped: two real decaying modes. z2 uses the stable form -w/(z+s), because
// -wz + w*s cancels badly for large z.
const double s = std::sqrt(z * z - 1.0);
const double r1 = -w * (z + s);
const double r2 = -w / (z + s);
const double c2 = (v - d * r1) / (r2 - r1);
const double c1 = d - c2;
const double e1 = std::exp(r1 * dt);
const double e2 = std::exp(r2 * dt);
nd = c1 * e1 + c2 * e2;
nv = c1 * r1 * e1 + c2 * r2 * e2;
} else {
// Under-damped: decaying oscillation at wd.
const double a = z * w;
const double wd = w * std::sqrt(1.0 - z * z);
const double b = (v + a * d) / wd;
const double e = std::exp(-a * dt);
const double cs = std::cos(wd * dt);
const double sn = std::sin(wd * dt);
nd = e * (d * cs + b * sn);
nv = e * ((-a * d + b * wd) * cs + (-a * b - d * wd) * sn);
}
if (!std::isfinite(nd) || !std::isfinite(nv)) { // belt and braces; should not happen
Snap();
return;
}
x_ = target_ + nd;
v_ = nv;
if (std::fabs(nd) < rest_.pos_eps && std::fabs(nv) < rest_.vel_eps) Snap();
}
} // namespace core
} // namespace fcs