r/CodingHelp • u/Catamituz • 24d ago
[C++] WHAT am i doing wrong theres like 500+ lines of code and millions of errors (C++ code drone aeronamics) ⬇️⬇️I put the code below


/**
* Multi-rotor drone aerodynamics simulation
* Models forces, moments, propeller dynamics, and 6-DOF rigid body motion
* with simplified atmospheric and induced velocity effects.
*
* Intended for educational / numerical experimentation use.
*/
#include <iostream>
#include <vector>
#include <array>
#include <cmath>
#include <iomanip>
#include <fstream>
#include <stdexcept>
#include <algorithm>
#include <numeric>
#include <random>
#include <chrono>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// ---------------------------------------------------------------------------
// Constants & utility
// ---------------------------------------------------------------------------
constexpr double g = 9.80665; // m/s²
constexpr double rho0 = 1.225; // kg/m³ sea-level density
constexpr double R_earth = 6371000.0; // m
constexpr double T0 = 288.15; // K
constexpr double L = 0.0065; // K/m temperature lapse
constexpr double R_specific = 287.05; // J/(kg·K)
inline double deg2rad(double d) { return d * M_PI / 180.0; }
inline double rad2deg(double r) { return r * 180.0 / M_PI; }
inline double clamp(double v, double lo, double hi) {
return std::max(lo, std::min(v, hi));
}
// ---------------------------------------------------------------------------
// 3-D vector (lightweight)
// ---------------------------------------------------------------------------
struct Vec3 {
double x = 0.0, y = 0.0, z = 0.0;
Vec3() = default;
Vec3(double x_, double y_, double z_) : x(x_), y(y_), z(z_) {}
Vec3 operator+(const Vec3& o) const { return {x + o.x, y + o.y, z + o.z}; }
Vec3 operator-(const Vec3& o) const { return {x - o.x, y - o.y, z - o.z}; }
Vec3 operator*(double s) const { return {x * s, y * s, z * s}; }
Vec3 operator/(double s) const { return {x / s, y / s, z / s}; }
Vec3& operator+=(const Vec3& o) { x += o.x; y += o.y; z += o.z; return *this; }
Vec3& operator-=(const Vec3& o) { x -= o.x; y -= o.y; z -= o.z; return *this; }
Vec3& operator*=(double s) { x *= s; y *= s; z *= s; return *this; }
double norm() const { return std::sqrt(x*x + y*y + z*z); }
double norm2() const { return x*x + y*y + z*z; }
Vec3 normalized() const {
double n = norm();
return n > 1e-12 ? (*this)/n : Vec3{0,0,0};
}
double dot(const Vec3& o) const { return x*o.x + y*o.y + z*o.z; }
Vec3 cross(const Vec3& o) const {
return {y*o.z - z*o.y, z*o.x - x*o.z, x*o.y - y*o.x};
}
};
inline Vec3 operator*(double s, const Vec3& v) { return v * s; }
std::ostream& operator<<(std::ostream& os, const Vec3& v) {
os << std::fixed << std::setprecision(4)
<< "(" << v.x << ", " << v.y << ", " << v.z << ")";
return os;
}
// ---------------------------------------------------------------------------
// Atmosphere model (ISA troposphere approximation)
// ---------------------------------------------------------------------------
struct Atmosphere {
static double density(double altitude) {
// altitude in meters above MSL
if (altitude < 0.0) altitude = 0.0;
double T = T0 - L * altitude;
double p = 101325.0 * std::pow(T / T0, g / (R_specific * L));
return p / (R_specific * T);
}
static double temperature(double altitude) {
return T0 - L * std::max(0.0, altitude);
}
static double speedOfSound(double altitude) {
return std::sqrt(1.4 * R_specific * temperature(altitude));
}
};
// ---------------------------------------------------------------------------
// Propeller / rotor model (blade-element momentum theory simplified)
// ---------------------------------------------------------------------------
struct Rotor {
double radius; // m
double chord; // m (mean)
int numBlades;
double pitch; // rad (collective)
double rpm; // revolutions per minute
double Ct_coeff; // empirical thrust coefficient scale
double Cq_coeff; // torque coefficient scale
Vec3 position; // body-frame position relative to CoM
Vec3 axis; // unit vector of rotation axis (body frame)
bool clockwise; // rotation direction
Rotor(double r, double c, int n, double p, const Vec3& pos, const Vec3& ax, bool cw)
: radius(r), chord(c), numBlades(n), pitch(p), rpm(0.0),
Ct_coeff(0.12), Cq_coeff(0.008),
position(pos), axis(ax.normalized()), clockwise(cw) {}
// Angular velocity in rad/s
double omega() const { return rpm * 2.0 * M_PI / 60.0; }
// Disk area
double area() const { return M_PI * radius * radius; }
// Advance ratio / induced velocity estimation (very simplified)
double inducedVelocity(double v_axial, double rho) const {
// Momentum theory: T = 2 * rho * A * vi * (v + vi)
// Solve quadratic for vi given thrust estimate
double T_est = thrust(rho, v_axial); // circular dependency resolved iteratively later
double a = 2.0 * rho * area();
double disc = v_axial*v_axial + 2.0*T_est / a;
return 0.5 * (-v_axial + std::sqrt(std::max(0.0, disc)));
}
// Thrust (body axis direction)
double thrust(double rho, double v_axial) const {
double Om = omega();
double tip_speed = Om * radius;
// Simplified: Ct ≈ k * (pitch - alpha0) * (1 - something*mu)
double Ct = Ct_coeff * pitch * (1.0 - 0.15 * std::abs(v_axial) / (tip_speed + 1e-6));
Ct = clamp(Ct, 0.0, 0.25);
return Ct * rho * area() * tip_speed * tip_speed;
}
// Torque about rotor axis
double torque(double rho, double v_axial) const {
double Om = omega();
double tip_speed = Om * radius;
double Cq = Cq_coeff * pitch * (1.0 + 0.3 * std::abs(v_axial)/(tip_speed+1e-6));
Cq = clamp(Cq, 0.0, 0.03);
return Cq * rho * area() * radius * tip_speed * tip_speed;
}
// Force & moment contribution in body frame
void forcesAndMoments(double rho, const Vec3& bodyVel, const Vec3& bodyOmega,
Vec3& F_out, Vec3& M_out) const {
// Relative axial velocity (projection of velocity onto rotor axis)
Vec3 relVel = bodyVel + bodyOmega.cross(position);
double v_ax = relVel.dot(axis);
double T = thrust(rho, v_ax);
double Q = torque(rho, v_ax);
// Thrust force along axis
Vec3 F = axis * T;
// Reaction torque opposite to rotation
double sign = clockwise ? 1.0 : -1.0;
Vec3 M_torque = axis * (Q * sign);
// Moment due to force offset from CoM
Vec3 M_force = position.cross(F);
F_out = F;
M_out = M_torque + M_force;
}
};
// ---------------------------------------------------------------------------
// Rigid-body 6-DOF state
// ---------------------------------------------------------------------------
struct State {
Vec3 pos; // inertial position (NED-ish: x North, y East, z Down)
Vec3 vel; // inertial velocity
Vec3 euler; // roll, pitch, yaw (rad)
Vec3 omega; // body angular rates (p,q,r)
State() = default;
};
// Direction cosine matrix (body to inertial) from Euler angles (ZYX)
struct DCM {
std::array<std::array<double,3>,3> m;
static DCM fromEuler(const Vec3& e) {
double cphi = std::cos(e.x), sphi = std::sin(e.x);
double cth = std::cos(e.y), sth = std::sin(e.y);
double cpsi = std::cos(e.z), spsi = std::sin(e.z);
DCM d;
// ZYX rotation
d.m[0][0] = cth*cpsi;
d.m[0][1] = cth*spsi;
d.m[0][2] = -sth;
d.m[1][0] = sphi*sth*cpsi - cphi*spsi;
d.m[1][1] = sphi*sth*spsi + cphi*cpsi;
d.m[1][2] = sphi*cth;
d.m[2][0] = cphi*sth*cpsi + sphi*spsi;
d.m[2][1] = cphi*sth*spsi - sphi*cpsi;
d.m[2][2] = cphi*cth;
return d;
}
Vec3 transform(const Vec3& v) const {
return {
m[0][0]*v.x + m[0][1]*v.y + m[0][2]*v.z,
m[1][0]*v.x + m[1][1]*v.y + m[1][2]*v.z,
m[2][0]*v.x + m[2][1]*v.y + m[2][2]*v.z
};
}
Vec3 inverseTransform(const Vec3& v) const {
// transpose because orthonormal
return {
m[0][0]*v.x + m[1][0]*v.y + m[2][0]*v.z,
m[0][1]*v.x + m[1][1]*v.y + m[2][1]*v.z,
m[0][2]*v.x + m[1][2]*v.y + m[2][2]*v.z
};
}
};
// ---------------------------------------------------------------------------
// Drone configuration
// ---------------------------------------------------------------------------
struct Drone {
double mass;
Vec3 inertia; // principal moments (Ixx, Iyy, Izz)
std::vector<Rotor> rotors;
double Cd_body; // body drag coefficient
double refArea; // reference area for body drag
double armLength;
Drone(double m, const Vec3& I, double arm)
: mass(m), inertia(I), Cd_body(0.8), refArea(0.05), armLength(arm)
{
// X configuration, 4 rotors
// Front-right, rear-left clockwise; others counter-clockwise
double a = arm * std::cos(M_PI/4.0);
rotors.emplace_back(0.12, 0.025, 2, deg2rad(12.0),
Vec3{ a, a, 0.02}, Vec3{0,0,-1}, true); // FR
rotors.emplace_back(0.12, 0.025, 2, deg2rad(12.0),
Vec3{-a, a, 0.02}, Vec3{0,0,-1}, false); // FL
rotors.emplace_back(0.12, 0.025, 2, deg2rad(12.0),
Vec3{-a, -a, 0.02}, Vec3{0,0,-1}, true); // RL
rotors.emplace_back(0.12, 0.025, 2, deg2rad(12.0),
Vec3{ a, -a, 0.02}, Vec3{0,0,-1}, false); // RR
}
void setRPMs(const std::array<double,4>& rpms) {
for (size_t i = 0; i < 4; ++i) rotors[i].rpm = rpms[i];
}
// Compute total force & moment in body frame
void computeForcesMoments(const State& s, double rho,
Vec3& F_body, Vec3& M_body) const {
F_body = {0,0,0};
M_body = {0,0,0};
// Rotor contributions
for (const auto& r : rotors) {
Vec3 Fr, Mr;
r.forcesAndMoments(rho, s.vel, s.omega, Fr, Mr); // NOTE: using inertial vel!
F_body += Fr;
M_body += Mr;
}
// Body aerodynamic drag (simple quadratic, opposite to velocity)
// Transform inertial velocity to body frame
DCM dcm = DCM::fromEuler(s.euler);
Vec3 vel_body = dcm.inverseTransform(s.vel);
double v = vel_body.norm();
if (v > 1e-3) {
Vec3 drag_dir = vel_body.normalized() * (-1.0);
double q = 0.5 * rho * v * v;
F_body += drag_dir * (q * Cd_body * refArea);
}
// Gravity in body frame
Vec3 g_inertial{0, 0, g}; // NED: +z down
Vec3 g_body = dcm.inverseTransform(g_inertial);
F_body += g_body * mass;
}
};
// ---------------------------------------------------------------------------
// Numerical integration (RK4)
// ---------------------------------------------------------------------------
struct Derivatives {
Vec3 dpos;
Vec3 dvel;
Vec3 deuler;
Vec3 domega;
};
Derivatives computeDerivatives(const Drone& drone, const State& s, double rho) {
Derivatives d;
// Position derivative = velocity
d.dpos = s.vel;
// Force & moment
Vec3 Fb, Mb;
drone.computeForcesMoments(s, rho, Fb, Mb);
// Acceleration in inertial frame
DCM dcm = DCM::fromEuler(s.euler);
Vec3 F_inertial = dcm.transform(Fb);
d.dvel = F_inertial / drone.mass;
// Euler angle rates (kinematic equations)
double phi = s.euler.x, th = s.euler.y;
double p = s.omega.x, q = s.omega.y, r = s.omega.z;
d.deuler.x = p + std::sin(phi)*std::tan(th)*q + std::cos(phi)*std::tan(th)*r;
d.deuler.y = std::cos(phi)*q - std::sin(phi)*r;
d.deuler.z = (std::sin(phi)/std::cos(th))*q + (std::cos(phi)/std::cos(th))*r;
// Angular acceleration (Euler equations for principal axes)
// I * domega = M - omega × (I omega)
Vec3 Iomega{drone.inertia.x * p, drone.inertia.y * q, drone.inertia.z * r};
Vec3 gyro = s.omega.cross(Iomega);
d.domega.x = (Mb.x - gyro.x) / drone.inertia.x;
d.domega.y = (Mb.y - gyro.y) / drone.inertia.y;
d.domega.z = (Mb.z - gyro.z) / drone.inertia.z;
return d;
}
State rk4Step(const Drone& drone, const State& s, double dt, double rho) {
auto addScaled = [](const State& a, const Derivatives& d, double k) {
State r = a;
r.pos += d.dpos * k;
r.vel += d.dvel * k;
r.euler += d.deuler * k;
r.omega += d.domega * k;
return r;
};
Derivatives k1 = computeDerivatives(drone, s, rho);
State s2 = addScaled(s, k1, dt*0.5);
Derivatives k2 = computeDerivatives(drone, s2, rho);
State s3 = addScaled(s, k2, dt*0.5);
Derivatives k3 = computeDerivatives(drone, s3, rho);
State s4 = addScaled(s, k3, dt);
Derivatives k4 = computeDerivatives(drone, s4, rho);
State next = s;
next.pos += (k1.dpos + 2.0*k2.dpos + 2.0*k3.dpos + k4.dpos) * (dt/6.0);
next.vel += (k1.dvel + 2.0*k2.dvel + 2.0*k3.dvel + k4.dvel) * (dt/6.0);
next.euler += (k1.deuler + 2.0*k2.deuler + 2.0*k3.deuler + k4.deuler) * (dt/6.0);
next.omega += (k1.domega + 2.0*k2.domega + 2.0*k3.domega + k4.domega) * (dt/6.0);
// Keep yaw in [-pi, pi]
while (next.euler.z > M_PI) next.euler.z -= 2.0*M_PI;
while (next.euler.z < -M_PI) next.euler.z += 2.0*M_PI;
return next;
}
// ---------------------------------------------------------------------------
// Simple attitude / altitude controller (PID-ish)
// ---------------------------------------------------------------------------
struct Controller {
double targetAlt = 5.0;
double targetYaw = 0.0;
double hoverRPM = 4500.0;
// gains
double Kp_alt = 800.0, Kd_alt = 400.0;
double Kp_att = 120.0, Kd_att = 40.0;
double Kp_yaw = 60.0, Kd_yaw = 25.0;
std::array<double,4> update(const State& s, double dt) {
// Altitude error (NED: z positive down → altitude = -pos.z)
double alt = -s.pos.z;
double alt_err = targetAlt - alt;
double vz = -s.vel.z; // climb rate positive up
double thrust_cmd = hoverRPM + Kp_alt * alt_err - Kd_alt * vz;
// Attitude: simple PD on roll/pitch, yaw rate damping
double roll_err = 0.0 - s.euler.x;
double pitch_err = 0.0 - s.euler.y;
double yaw_err = targetYaw - s.euler.z;
// wrap yaw error
while (yaw_err > M_PI) yaw_err -= 2*M_PI;
while (yaw_err < -M_PI) yaw_err += 2*M_PI;
double droll = Kp_att * roll_err - Kd_att * s.omega.x;
double dpitch = Kp_att * pitch_err - Kd_att * s.omega.y;
double dyaw = Kp_yaw * yaw_err - Kd_yaw * s.omega.z;
// Mixer (X configuration)
// FR, FL, RL, RR
std::array<double,4> rpm;
rpm[0] = thrust_cmd - droll + dpitch - dyaw; // FR
rpm[1] = thrust_cmd + droll + dpitch + dyaw; // FL
rpm[2] = thrust_cmd + droll - dpitch - dyaw; // RL
rpm[3] = thrust_cmd - droll - dpitch + dyaw; // RR
for (auto& r : rpm) r = clamp(r, 1000.0, 9000.0);
return rpm;
}
};
// ---------------------------------------------------------------------------
// Main simulation
// ---------------------------------------------------------------------------
int main() {
std::cout << "=== Drone Aerodynamics Simulation ===\n\n";
// Create a 1.2 kg quadrotor with ~0.25 m arm
Drone drone(1.2, Vec3{0.015, 0.015, 0.025}, 0.25);
State state;
state.pos = {0.0, 0.0, -0.1}; // start almost on ground
state.vel = {0,0,0};
state.euler = {0.05, -0.03, 0.1}; // small initial attitude error
state.omega = {0,0,0};
Controller ctrl;
ctrl.targetAlt = 8.0;
ctrl.hoverRPM = 4800.0; // approximate hover
const double dt = 0.002; // 500 Hz
const double t_end = 12.0;
double t = 0.0;
std::ofstream log("drone_log.csv");
log << "t,x,y,z,vx,vy,vz,roll,pitch,yaw,p,q,r,rpm0,rpm1,rpm2,rpm3,rho\n";
std::cout << std::fixed << std::setprecision(3);
std::cout << "Time Alt Roll Pitch Yaw |V| RPMs\n";
std::cout << "----------------------------------------------------------\n";
int step = 0;
while (t < t_end) {
double rho = Atmosphere::density(-state.pos.z); // altitude = -z
auto rpms = ctrl.update(state, dt);
drone.setRPMs(rpms);
state = rk4Step(drone, state, dt, rho);
// Ground collision (simple)
if (state.pos.z > 0.0) {
state.pos.z = 0.0;
state.vel.z = std::min(0.0, state.vel.z);
// crude friction
state.vel.x *= 0.8;
state.vel.y *= 0.8;
state.omega *= 0.5;
}
if (step % 250 == 0) { // print every 0.5 s
double alt = -state.pos.z;
double spd = state.vel.norm();
std::cout << std::setw(5) << t
<< " " << std::setw(6) << alt
<< " " << std::setw(6) << rad2deg(state.euler.x)
<< " " << std::setw(6) << rad2deg(state.euler.y)
<< " " << std::setw(6) << rad2deg(state.euler.z)
<< " " << std::setw(5) << spd
<< " [" << int(rpms[0]) << "," << int(rpms[1])
<< "," << int(rpms[2]) << "," << int(rpms[3]) << "]\n";
}
log << t << ","
<< state.pos.x << "," << state.pos.y << "," << state.pos.z << ","
<< state.vel.x << "," << state.vel.y << "," << state.vel.z << ","
<< state.euler.x << "," << state.euler.y << "," << state.euler.z << ","
<< state.omega.x << "," << state.omega.y << "," << state.omega.z << ","
<< rpms[0] << "," << rpms[1] << "," << rpms[2] << "," << rpms[3] << ","
<< rho << "\n";
t += dt;
++step;
}
log.close();
std::cout << "\nSimulation finished. Log written to drone_log.csv\n";
std::cout << "Final altitude : " << -state.pos.z << " m\n";
std::cout << "Final attitude : roll=" << rad2deg(state.euler.x)
<< "° pitch=" << rad2deg(state.euler.y)
<< "° yaw=" << rad2deg(state.euler.z) << "°\n";
return 0;
}


