MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / BezierCurve

Class BezierCurve

graphics/bezier_curve.py:8–104  ·  view source on GitHub ↗

Bezier curve is a weighted sum of a set of control points. Generate Bezier curves from a given set of control points. This implementation works only for 2d coordinates in the xy plane.

Source from the content-addressed store, hash-verified

6
7
8class BezierCurve:
9 """
10 Bezier curve is a weighted sum of a set of control points.
11 Generate Bezier curves from a given set of control points.
12 This implementation works only for 2d coordinates in the xy plane.
13 """
14
15 def __init__(self, list_of_points: list[tuple[float, float]]):
16 """
17 list_of_points: Control points in the xy plane on which to interpolate. These
18 points control the behavior (shape) of the Bezier curve.
19 """
20 self.list_of_points = list_of_points
21 # Degree determines the flexibility of the curve.
22 # Degree = 1 will produce a straight line.
23 self.degree = len(list_of_points) - 1
24
25 def basis_function(self, t: float) -> list[float]:
26 """
27 The basis function determines the weight of each control point at time t.
28 t: time value between 0 and 1 inclusive at which to evaluate the basis of
29 the curve.
30 returns the x, y values of basis function at time t
31
32 >>> curve = BezierCurve([(1,1), (1,2)])
33 >>> [float(x) for x in curve.basis_function(0)]
34 [1.0, 0.0]
35 >>> [float(x) for x in curve.basis_function(1)]
36 [0.0, 1.0]
37 """
38 assert 0 <= t <= 1, "Time t must be between 0 and 1."
39 output_values: list[float] = []
40 for i in range(len(self.list_of_points)):
41 # basis function for each i
42 output_values.append(
43 comb(self.degree, i) * ((1 - t) ** (self.degree - i)) * (t**i)
44 )
45 # the basis must sum up to 1 for it to produce a valid Bezier curve.
46 assert round(sum(output_values), 5) == 1
47 return output_values
48
49 def bezier_curve_function(self, t: float) -> tuple[float, float]:
50 """
51 The function to produce the values of the Bezier curve at time t.
52 t: the value of time t at which to evaluate the Bezier function
53 Returns the x, y coordinates of the Bezier curve at time t.
54 The first point in the curve is when t = 0.
55 The last point in the curve is when t = 1.
56
57 >>> curve = BezierCurve([(1,1), (1,2)])
58 >>> tuple(float(x) for x in curve.bezier_curve_function(0))
59 (1.0, 1.0)
60 >>> tuple(float(x) for x in curve.bezier_curve_function(1))
61 (1.0, 2.0)
62 """
63
64 assert 0 <= t <= 1, "Time t must be between 0 and 1."
65

Callers 1

bezier_curve.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected