src/bezier_curve.cpp

Wed, 12 Apr 2023 01:53:42 +0300

author
Teemu Piippo <teemu.s.piippo@gmail.com>
date
Wed, 12 Apr 2023 01:53:42 +0300
changeset 379
8d88adffb779
parent 373
e34d6a30b96d
permissions
-rw-r--r--

Circular primitive type is now an enum class

#include "bezier_curve.h"

/**
 * @brief computes the point on a Bezier curve
 * @param curve
 * @param t scalar between 0 and 1, with t=0 being P0 and t=1 being P3
 * @return point on curve
 */
glm::vec3 point_on_bezier_curve(const struct bezier_curve &curve, float t)
{
	// clamp t as rounding errors might make it slightly out of bounds
	t = std::clamp(t, 0.0f, 1.0f);
	const float t_squared = t * t;
	const float t_cubed = t * t * t;
	const float coefficients[3] = {
		-1*t_cubed  +3*t_squared  -3*t  +1,
		+3*t_cubed  -6*t_squared  +3*t,
		-3*t_cubed  +3*t_squared,
	};
	return coefficients[0] * curve.points[0]
		+ coefficients[1] * curve.points[1]
		+ coefficients[2] * curve.points[2]
		+ t_cubed * curve.points[3];
}

/**
 * @brief computes the derivative of a point on a Bezier curve
 * @param curve
 * @param t scalar between 0 and 1, with t=0 being P0 and t=1 being P3
 * @return point on curve
 */
glm::vec3 derivate_on_bezier_curve(const struct bezier_curve &curve, float t)
{
	// clamp t as rounding errors might make it slightly out of bounds
	t = std::clamp(t, 0.0f, 1.0f);
	const float t_cubed = t * t;
	const float coefficients[4] = {
		-3*t_cubed + 6*t  -3,
		+9*t_cubed -12*t  +3,
		-9*t_cubed + 6*t,
		+3*t_cubed
	};
	return coefficients[0] * curve.points[0]
		+ coefficients[1] * curve.points[1]
		+ coefficients[2] * curve.points[2]
		+ coefficients[3] * curve.points[3];
}

mercurial