diff --git a/README.md b/README.md index ced163e..8f5f692 100644 --- a/README.md +++ b/README.md @@ -58,4 +58,4 @@ J3ML is licensed under the Public Domain. See the LICENSE file for details. # Acknowledgements -J3ML is developed and maintained by Joshua O'Leary from Redacted Software and contributors. Special thanks to William J Tomasine II. \ No newline at end of file +J3ML is developed and maintained by Joshua O'Leary from Redacted Software and contributors. Special thanks to William J Tomasine II. diff --git a/include/J3ML/Algorithm/Bezier.h b/include/J3ML/Algorithm/Bezier.h new file mode 100644 index 0000000..fbffb7e --- /dev/null +++ b/include/J3ML/Algorithm/Bezier.h @@ -0,0 +1,45 @@ +/// @file Bezier.h +/// @desc Cubic Bezier Curve impl. using De Casteljau's Method +/// @author Joshua O'Leary +/// @edited 20 June 2024 +/// @version 2 +/// @copyright (c) Redacted Software 2024 +/// @license Unlicense - Public Domain + +#pragma once + +// Bezier Method: +// p = (1-t)^3 * P0 + 3*t*(1-t)^2*P1 + 3*t^2*(1-t)*P2 + t^3*P3; + +// For cubics: +// p = (1-t)^2 * P0 + 2*(1-t)*t*P1 + t*t*P2; + +// Transcribed from here: explicit form and derivative +// https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B%C3%A9zier_curves + +#include "J3ML/LinearAlgebra/Vector2.h" + +namespace J3ML::Algorithm +{ + using namespace J3ML::LinearAlgebra; + + template + inline T Square(T f) { return f * f; } + + template + inline T Cube(T f) { return f * f * f; } + + template + inline T Bezier(float t, const T& p0, const T& p1, const T& p2, const T& p3) + { + return Cube(1 - t) * p0 + 3 * Square(1 - t) * t * p1 + 3 * (1 - t) * Square(t) * p2 + Cube(t) * p3; + } + + inline Vector2 Bezier(float t, const Vector2& p0, const Vector2& p1, const Vector2& p2, const Vector2& p3); + + // Tangent + Vector2 BezierDerivative(float t, const Vector2& p0, const Vector2& p1, const Vector2& p2, const Vector2& p3); + + // Normal + Vector2 BezierNormal(float t, const Vector2& p0, const Vector2& p1, const Vector2& p2, const Vector2& p3); +} \ No newline at end of file diff --git a/src/J3ML/Algorithm/Bezier.cpp b/src/J3ML/Algorithm/Bezier.cpp new file mode 100644 index 0000000..fdf344e --- /dev/null +++ b/src/J3ML/Algorithm/Bezier.cpp @@ -0,0 +1,20 @@ +#include + +namespace J3ML::Algorithm +{ + using namespace J3ML::LinearAlgebra; + Vector2 BezierNormal(float t, const Vector2 &p0, const Vector2 &p1, + const Vector2 &p2, const Vector2 &p3) { + auto derived = BezierDerivative(t, p0, p1, p2, p3); + return derived.Normalized(); + } + + Vector2 BezierDerivative(float t, const Vector2 &p0, const Vector2 &p1, const Vector2 &p2, const Vector2 &p3) { + return 3 * Square(1 - t) * (p1 - p0) + 6 * (1 - t) * t * (p2 - p1) + 3 * Square(t) * (p3 - p2); + } + + Vector2 Algorithm::Bezier(float t, const Vector2 &p0, const Vector2 &p1, const Vector2 &p2, const Vector2 &p3) { + return {Bezier(t, p0.x, p1.x, p2.x, p3.x), Bezier(t, p0.y, p1.y, p2.y, p3.y)}; + } +} +