Created
October 23, 2024 16:40
-
-
Save typoman/b9960d38504a36124959a21931ef2281 to your computer and use it in GitHub Desktop.
cubic bezier curve arc length approximation using gaussian quadrature in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
""" | |
based on | |
https://pomax.github.io/bezierinfo/#arclength | |
we can determine the approximate length of a Bézier curve by computing the Legendre-Gauss sum. | |
""" | |
# Gaussian quadrature coefficients | |
T = [-0.9061798459, -0.5384693101, 0, 0.5384693101, 0.9061798459] | |
C = [0.2369268850, 0.4786286705, 0.5688888889, 0.4786286705, 0.2369268850] | |
def derivative(t, p0, p1, p2, p3): | |
mt = 1 - t | |
dx = 3 * mt * mt * (p1[0] - p0[0]) + 6 * mt * t * (p2[0] - p1[0]) + 3 * t * t * (p3[0] - p2[0]) | |
dy = 3 * mt * mt * (p1[1] - p0[1]) + 6 * mt * t * (p2[1] - p1[1]) + 3 * t * t * (p3[1] - p2[1]) | |
return dx, dy | |
def arc_length_element(t, derivative): | |
return math.sqrt(derivative[0] * derivative[0] + derivative[1] * derivative[1]) | |
def approximateCubicArcLength(p0, p1, p2, p3): | |
z = 0.5 | |
total_length = 0 | |
for t_val, c_val in zip(T, C): | |
t = z * t_val + z | |
deriv = derivative(t, p0, p1, p2, p3) | |
total_length += c_val * arc_length_element(t, deriv) | |
return z * total_length | |
p1 = (0, 0) | |
p2 = (50, 50) | |
p3 = (90, 90) | |
p4 = (230, 230) | |
l = approximateCubicArcLength(p1, p2, p3, p4) | |
print(l) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment