Skip to content

Instantly share code, notes, and snippets.

@karimnaaji
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karimnaaji/49b968009daf454e6c8a to your computer and use it in GitHub Desktop.
Save karimnaaji/49b968009daf454e6c8a to your computer and use it in GitHub Desktop.
cubic bezier curve
#include <iostream>
#include <string>
#include <cmath>
void bCurveP4Derivative(float t, float p0x, float p0y, float p1x, float p1y, float p2x, float p2y, float p3x, float p3y, float* x, float* y) {
// derivate of cubic b-curve is a quadratic b-curve
float it = 1 - t;
float f0 = 3 * powf(it, 2.f);
float f1 = 6 * t * (it);
float f2 = 3 * powf(t, 2.f);
*x = f0 * (p1x - p0x) + f1 * (p2x - p1x) + f2 * (p3x - p2x);
*y = f0 * (p1y - p0y) + f1 * (p2y - p1y) + f2 * (p3y - p2y);
}
void bCurveP4(float t, float p0x, float p0y, float p1x, float p1y, float p2x, float p2y, float p3x, float p3y, float* x, float* y) {
float it = 1 - t;
float f0 = powf(it, 3.f);
float f1 = 3 * t * powf(it, 2.f);
float f2 = 3 * powf(t, 2.f) * it;
float f3 = powf(t, 3.f);
*x = f0 * p0x + f1 * p1x + f2 * p2x + f3 * p3x;
*y = f0 * p0y + f1 * p1y + f2 * p2y + f3 * p3y;
}
int main() {
// control points
float p0x = 0.0;
float p0y = 0.0;
float p1x = 0.0;
float p1y = 1.0;
float p2x = 1.0;
float p2y = 1.0;
float p3x = 1.0;
float p3y = 0.0;
for (float t = 0.f; t <= 1.1f; t += 0.1f) {
float x, y;
float dx, dy;
bCurveP4(t, p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y, &x, &y);
bCurveP4Derivative(t, p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y, &dx, &dy);
float il = 1.f / sqrtf((dx * dx) + (dy * dy));
float theta = (atan2f(dx * il, -dy * il) - M_PI_2) * 180 / M_PI;;
std::cout << x << " " << y << " " << dx << " " << dy << " " << theta << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment