View Javadoc
1   package org.djutils.draw.line;
2   
3   import java.util.Map;
4   import java.util.NavigableMap;
5   import java.util.TreeMap;
6   
7   import org.djutils.draw.DrawRuntimeException;
8   import org.djutils.draw.Transform2d;
9   import org.djutils.draw.point.Point2d;
10  import org.djutils.draw.point.Point3d;
11  import org.djutils.exceptions.Throw;
12  
13  /**
14   * Generation of B&eacute;zier curves. <br>
15   * The class implements the cubic(...) method to generate a cubic B&eacute;zier curve using the following formula: B(t) = (1 -
16   * t)<sup>3</sup>P<sub>0</sub> + 3t(1 - t)<sup>2</sup> P<sub>1</sub> + 3t<sup>2</sup> (1 - t) P<sub>2</sub> + t<sup>3</sup>
17   * P<sub>3</sub> where P<sub>0</sub> and P<sub>3</sub> are the end points, and P<sub>1</sub> and P<sub>2</sub> the control
18   * points. <br>
19   * For a smooth movement, one of the standard implementations if the cubic(...) function offered is the case where P<sub>1</sub>
20   * is positioned halfway between P<sub>0</sub> and P<sub>3</sub> starting from P<sub>0</sub> in the direction of P<sub>3</sub>,
21   * and P<sub>2</sub> is positioned halfway between P<sub>3</sub> and P<sub>0</sub> starting from P<sub>3</sub> in the direction
22   * of P<sub>0</sub>.<br>
23   * Finally, an n-point generalization of the B&eacute;zier curve is implemented with the bezier(...) function.
24   * <p>
25   * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
26   * BSD-style license. See <a href="http://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
27   * </p>
28   * @author <a href="https://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
29   * @author <a href="https://www.tudelft.nl/pknoppers">Peter Knoppers</a>
30   */
31  public final class Bezier
32  {
33      /** The default number of points to use to construct a B&eacute;zier curve. */
34      public static final int DEFAULT_BEZIER_SIZE = 64;
35  
36      /** Cached factorial values. */
37      private static long[] fact = new long[] {1L, 1L, 2L, 6L, 24L, 120L, 720L, 5040L, 40320L, 362880L, 3628800L, 39916800L,
38              479001600L, 6227020800L, 87178291200L, 1307674368000L, 20922789888000L, 355687428096000L, 6402373705728000L,
39              121645100408832000L, 2432902008176640000L};
40  
41      /** Utility class. */
42      private Bezier()
43      {
44          // do not instantiate
45      }
46  
47      /**
48       * Approximate a cubic B&eacute;zier curve from start to end with two control points.
49       * @param size int; the number of points of the B&eacute;zier curve
50       * @param start Point2d; the start point of the B&eacute;zier curve
51       * @param control1 Point2d; the first control point
52       * @param control2 Point2d; the second control point
53       * @param end Point2d; the end point of the B&eacute;zier curve
54       * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, using the two provided control
55       *         points
56       * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
57       *             constructed
58       */
59      public static PolyLine2d cubic(final int size, final Point2d start, final Point2d control1, final Point2d control2,
60              final Point2d end) throws DrawRuntimeException
61      {
62          Throw.when(size < 2, DrawRuntimeException.class, "Too few points (specified %d; minimum is 2)", size);
63          Point2d[] points = new Point2d[size];
64          for (int n = 0; n < size; n++)
65          {
66              double t = n / (size - 1.0);
67              double x = B3(t, start.x, control1.x, control2.x, end.x);
68              double y = B3(t, start.y, control1.y, control2.y, end.y);
69              points[n] = new Point2d(x, y);
70          }
71          return new PolyLine2d(points);
72      }
73  
74      /**
75       * Approximate a cubic B&eacute;zier curve from start to end with two control points with a specified precision.
76       * @param epsilon double; the precision.
77       * @param start Point2d; the start point of the B&eacute;zier curve
78       * @param control1 Point2d; the first control point
79       * @param control2 Point2d; the second control point
80       * @param end Point2d; the end point of the B&eacute;zier curve
81       * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, using the two provided control
82       *         points
83       * @throws DrawRuntimeException in case the number of points is less than 2, or the B&eacute;zier curve could not be
84       *             constructed
85       */
86      public static PolyLine2d cubic(final double epsilon, final Point2d start, final Point2d control1, final Point2d control2,
87              final Point2d end) throws DrawRuntimeException
88      {
89          return bezier(epsilon, start, control1, control2, end);
90      }
91  
92      /**
93       * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
94       * start and end.
95       * @param size int; the number of points of the B&eacute;zier curve
96       * @param start Ray2d; the start point and start direction of the B&eacute;zier curve
97       * @param end Ray2d; the end point and end direction of the B&eacute;zier curve
98       * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, using the directions of those
99       *         points at start and end
100      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
101      *             constructed
102      */
103     public static PolyLine2d cubic(final int size, final Ray2d start, final Ray2d end) throws DrawRuntimeException
104     {
105         return cubic(size, start, end, 1.0);
106     }
107 
108     /**
109      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
110      * start and end with specified precision.
111      * @param epsilon double; the precision.
112      * @param start Ray2d; the start point and start direction of the B&eacute;zier curve
113      * @param end Ray2d; the end point and end direction of the B&eacute;zier curve
114      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, using the directions of those
115      *         points at start and end
116      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
117      *             constructed
118      */
119     public static PolyLine2d cubic(final double epsilon, final Ray2d start, final Ray2d end) throws DrawRuntimeException
120     {
121         return cubic(epsilon, start, end, 1.0);
122     }
123 
124     /**
125      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
126      * start and end.
127      * @param size int; the number of points for the B&eacute;zier curve
128      * @param start Ray2d; the start point and start direction of the B&eacute;zier curve
129      * @param end Ray2d; the end point and end direction of the B&eacute;zier curve
130      * @param shape shape factor; 1 = control points at half the distance between start and end, &gt; 1 results in a pointier
131      *            shape, &lt; 1 results in a flatter shape, value should be above 0 and finite
132      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, using the directions of those
133      *         points at start and end
134      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
135      *             constructed
136      */
137     public static PolyLine2d cubic(final int size, final Ray2d start, final Ray2d end, final double shape)
138             throws DrawRuntimeException
139     {
140         Throw.when(Double.isNaN(shape) || Double.isInfinite(shape) || shape <= 0, DrawRuntimeException.class,
141                 "shape must be a finite, positive value");
142         return cubic(size, start, end, shape, false);
143     }
144 
145     /**
146      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
147      * start and end with specified precision.
148      * @param epsilon double; the precision.
149      * @param start Ray2d; the start point and start direction of the B&eacute;zier curve
150      * @param end Ray2d; the end point and end direction of the B&eacute;zier curve
151      * @param shape shape factor; 1 = control points at half the distance between start and end, &gt; 1 results in a pointier
152      *            shape, &lt; 1 results in a flatter shape, value should be above 0 and finite
153      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, using the directions of those
154      *         points at start and end
155      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
156      *             constructed
157      */
158     public static PolyLine2d cubic(final double epsilon, final Ray2d start, final Ray2d end, final double shape)
159             throws DrawRuntimeException
160     {
161         Throw.when(Double.isNaN(shape) || Double.isInfinite(shape) || shape <= 0, DrawRuntimeException.class,
162                 "shape must be a finite, positive value");
163         return cubic(epsilon, start, end, shape, false);
164     }
165 
166     /**
167      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
168      * start and end.
169      * @param size int; the number of points for the B&eacute;zier curve
170      * @param start Ray2d; the start point and start direction of the B&eacute;zier curve
171      * @param end Ray2d; the end point and end direction of the B&eacute;zier curve
172      * @param shape shape factor; 1 = control points at half the distance between start and end, &gt; 1 results in a pointier
173      *            shape, &lt; 1 results in a flatter shape, value should be above 0, finite and not NaN
174      * @param weighted boolean; control point distance relates to distance to projected point on extended line from other end
175      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, with the two determined
176      *         control points
177      * @throws NullPointerException when start or end is null
178      * @throws DrawRuntimeException in case size is less than 2, start is at the same location as end, shape is invalid, or the
179      *             B&eacute;zier curve could not be constructed
180      */
181     public static PolyLine2d cubic(final int size, final Ray2d start, final Ray2d end, final double shape,
182             final boolean weighted) throws NullPointerException, DrawRuntimeException
183     {
184         Point2d[] points = createControlPoints(start, end, shape, weighted);
185         return cubic(size, points[0], points[1], points[2], points[3]);
186     }
187 
188     /**
189      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
190      * start and end with specified precision.
191      * @param epsilon double; the precision.
192      * @param start Ray2d; the start point and start direction of the B&eacute;zier curve
193      * @param end Ray2d; the end point and end direction of the B&eacute;zier curve
194      * @param shape shape factor; 1 = control points at half the distance between start and end, &gt; 1 results in a pointier
195      *            shape, &lt; 1 results in a flatter shape, value should be above 0, finite and not NaN
196      * @param weighted boolean; control point distance relates to distance to projected point on extended line from other end
197      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, with the two determined
198      *         control points
199      * @throws NullPointerException when start or end is null
200      * @throws DrawRuntimeException in case size is less than 2, start is at the same location as end, shape is invalid
201      */
202     public static PolyLine2d cubic(final double epsilon, final Ray2d start, final Ray2d end, final double shape,
203             final boolean weighted) throws NullPointerException, DrawRuntimeException
204     {
205         Point2d[] points = createControlPoints(start, end, shape, weighted);
206         return cubic(epsilon, points[0], points[1], points[2], points[3]);
207     }
208 
209     /** Unit vector for transformations in createControlPoints. */
210     private static final Point2d UNIT_VECTOR2D = new Point2d(1, 0);
211 
212     /**
213      * Create control points for a cubic B&eacute;zier curve defined by two Rays.
214      * @param start Ray2d; the start point (and direction)
215      * @param end Ray2d; the end point (and direction)
216      * @param shape double; the shape; higher values put the generated control points further away from end and result in a
217      *            pointier B&eacute;zier curve
218      * @param weighted boolean;
219      * @return Point2d[]; an array of four Point2d elements: start, the first control point, the second control point, end.
220      * @throws DrawRuntimeException when shape is invalid
221      */
222     private static Point2d[] createControlPoints(final Ray2d start, final Ray2d end, final double shape, final boolean weighted)
223             throws DrawRuntimeException
224     {
225         Throw.whenNull(start, "start");
226         Throw.whenNull(end, "end");
227         Throw.when(start.distanceSquared(end) == 0, DrawRuntimeException.class,
228                 "Cannot create control points if start and end points coincide");
229         Throw.when(Double.isNaN(shape) || shape <= 0 || Double.isInfinite(shape), DrawRuntimeException.class,
230                 "shape must be a finite, positive value");
231 
232         Point2d control1;
233         Point2d control2;
234         if (weighted)
235         {
236             // each control point is 'w' * the distance between the end-points away from the respective end point
237             // 'w' is a weight given by the distance from the end point to the extended line of the other end point
238             double distance = shape * start.distance(end);
239             double dStart = start.distance(end.projectOrthogonalExtended(start));
240             double dEnd = end.distance(start.projectOrthogonalExtended(end));
241             double wStart = dStart / (dStart + dEnd);
242             double wEnd = dEnd / (dStart + dEnd);
243             control1 = new Transform2d().translate(start).rotation(start.dirZ).scale(distance * wStart, distance * wStart)
244                     .transform(UNIT_VECTOR2D);
245             // - (minus) as the angle is where the line leaves, i.e. from shape point to end
246             control2 = new Transform2d().translate(end).rotation(end.dirZ + Math.PI).scale(distance * wEnd, distance * wEnd)
247                     .transform(UNIT_VECTOR2D);
248         }
249         else
250         {
251             // each control point is half the distance between the end-points away from the respective end point
252             double distance = shape * start.distance(end) / 2.0;
253             control1 = start.getLocation(distance);
254             // new Transform2d().translate(start).rotation(start.phi).scale(distance, distance).transform(UNIT_VECTOR2D);
255             control2 = end.getLocationExtended(-distance);
256             // new Transform2d().translate(end).rotation(end.phi + Math.PI).scale(distance, distance).transform(UNIT_VECTOR2D);
257         }
258         return new Point2d[] {start, control1, control2, end};
259     }
260 
261     /**
262      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
263      * start and end. The size of the constructed curve is <code>DEFAULT_BEZIER_SIZE</code>.
264      * @param start Ray2d; the start point and start direction of the B&eacute;zier curve
265      * @param end Ray2d; the end point and end direction of the B&eacute;zier curve
266      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, following the directions of
267      *         those points at start and end
268      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
269      *             constructed
270      */
271     public static PolyLine2d cubic(final Ray2d start, final Ray2d end) throws DrawRuntimeException
272     {
273         return cubic(DEFAULT_BEZIER_SIZE, start, end);
274     }
275 
276     /**
277      * Approximate a B&eacute;zier curve of degree n.
278      * @param size int; the number of points for the B&eacute;zier curve to be constructed
279      * @param points Point2d...; the points of the curve, where the first and last are begin and end point, and the intermediate
280      *            ones are control points. There should be at least two points.
281      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, using the provided control
282      *         points
283      * @throws NullPointerException when points contains a null
284      * @throws DrawRuntimeException in case the number of points is less than 2, size is less than 2, or the B&eacute;zier curve
285      *             could not be constructed
286      */
287     public static PolyLine2d bezier(final int size, final Point2d... points) throws NullPointerException, DrawRuntimeException
288     {
289         Throw.when(points.length < 2, DrawRuntimeException.class, "Too few points; need at least two");
290         Throw.when(size < 2, DrawRuntimeException.class, "size too small (must be at least 2)");
291         Point2d[] result = new Point2d[size];
292         double[] px = new double[points.length];
293         double[] py = new double[points.length];
294         for (int i = 0; i < points.length; i++)
295         {
296             Point2d p = points[i];
297             Throw.whenNull(p, "points may not contain a null value");
298             px[i] = p.x;
299             py[i] = p.y;
300         }
301         for (int n = 0; n < size; n++)
302         {
303             double t = n / (size - 1.0);
304             double x = Bn(t, px);
305             double y = Bn(t, py);
306             result[n] = new Point2d(x, y);
307         }
308         return new PolyLine2d(result);
309     }
310 
311     /**
312      * Approximate a B&eacute;zier curve of degree n using <code>DEFAULT_BEZIER_SIZE</code> points.
313      * @param points Point2d...; the points of the curve, where the first and last are begin and end point, and the intermediate
314      *            ones are control points. There should be at least two points.
315      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, using the provided control
316      *         points
317      * @throws NullPointerException when points contains a null value
318      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
319      *             constructed
320      */
321     public static PolyLine2d bezier(final Point2d... points) throws NullPointerException, DrawRuntimeException
322     {
323         return bezier(DEFAULT_BEZIER_SIZE, points);
324     }
325 
326     /**
327      * Approximate a B&eacute;zier curve of degree n with a specified precision.
328      * @param epsilon double; the precision.
329      * @param points Point2d...; the points of the curve, where the first and last are begin and end point, and the intermediate
330      *            ones are control points. There should be at least two points.
331      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, with the provided control
332      *         points
333      * @throws NullPointerException when points contains a null value
334      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
335      *             constructed
336      */
337     public static PolyLine2d bezier(final double epsilon, final Point2d... points)
338             throws NullPointerException, DrawRuntimeException
339     {
340         Throw.when(points.length < 2, DrawRuntimeException.class, "Too few points; need at least two");
341         Throw.when(Double.isNaN(epsilon) || epsilon <= 0, DrawRuntimeException.class,
342                 "epsilonPosition must be a positive number");
343         if (points.length == 2)
344         {
345             return new PolyLine2d(points[0], points[1]);
346         }
347         NavigableMap<Double, Point2d> result = new TreeMap<>();
348         double[] px = new double[points.length];
349         double[] py = new double[points.length];
350         for (int i = 0; i < points.length; i++)
351         {
352             Point2d p = points[i];
353             Throw.whenNull(p, "points may not contain a null value");
354             px[i] = p.x;
355             py[i] = p.y;
356         }
357         int initialSize = points.length - 1;
358         for (int n = 0; n < initialSize; n++)
359         {
360             double t = n / (initialSize - 1.0);
361             double x = Bn(t, px);
362             double y = Bn(t, py);
363             result.put(t, new Point2d(x, y));
364         }
365         // Walk along all point pairs and see if additional points need to be inserted
366         Double prevT = result.firstKey();
367         Point2d prevPoint = result.get(prevT);
368         Map.Entry<Double, Point2d> entry;
369         while ((entry = result.higherEntry(prevT)) != null)
370         {
371             Double nextT = entry.getKey();
372             Point2d nextPoint = entry.getValue();
373             double medianT = (prevT + nextT) / 2;
374             double x = Bn(medianT, px);
375             double y = Bn(medianT, py);
376             Point2d medianPoint = new Point2d(x, y);
377             Point2d projectedPoint = medianPoint.closestPointOnSegment(prevPoint, nextPoint);
378             double errorPosition = medianPoint.distance(projectedPoint);
379             if (errorPosition >= epsilon)
380             {
381                 // We need to insert another point
382                 result.put(medianT, medianPoint);
383                 continue;
384             }
385             if (prevPoint.distance(nextPoint) > epsilon)
386             {
387                 // Check for an inflection point by creating additional points at one quarter and three quarters. If these
388                 // are on opposite sides of the line from prevPoint to nextPoint; there must be an inflection point.
389                 // https://stackoverflow.com/questions/1560492/how-to-tell-whether-a-point-is-to-the-right-or-left-side-of-a-line
390                 double quarterT = (prevT + medianT) / 2;
391                 double quarterX = Bn(quarterT, px);
392                 double quarterY = Bn(quarterT, py);
393                 int sign1 = (int) Math.signum((nextPoint.x - prevPoint.x) * (quarterY - prevPoint.y)
394                         - (nextPoint.y - prevPoint.y) * (quarterX - prevPoint.x));
395                 double threeQuarterT = (nextT + medianT) / 2;
396                 double threeQuarterX = Bn(threeQuarterT, px);
397                 double threeQuarterY = Bn(threeQuarterT, py);
398                 int sign2 = (int) Math.signum((nextPoint.x - prevPoint.x) * (threeQuarterY - prevPoint.y)
399                         - (nextPoint.y - prevPoint.y) * (threeQuarterX - prevPoint.x));
400                 if (sign1 != sign2)
401                 {
402                     // There is an inflection point
403                     // System.out.println("Detected inflection point between " + prevPoint + " and " + nextPoint);
404                     // Inserting the halfway point should take care of this
405                     result.put(medianT, medianPoint);
406                     continue;
407                 }
408             }
409             // TODO check angles
410             prevT = nextT;
411             prevPoint = nextPoint;
412         }
413         return new PolyLine2d(result.values().iterator());
414     }
415 
416     /**
417      * Approximate a cubic B&eacute;zier curve from start to end with two control points.
418      * @param size int; the number of points for the B&eacute;zier curve
419      * @param start Point3d; the start point of the B&eacute;zier curve
420      * @param control1 Point3d; the first control point
421      * @param control2 Point3d; the second control point
422      * @param end Point3d; the end point of the B&eacute;zier curve
423      * @return PolyLine3d; an approximation of a cubic B&eacute;zier curve between start and end, with the two provided control
424      *         points
425      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
426      *             constructed
427      */
428     public static PolyLine3d cubic(final int size, final Point3d start, final Point3d control1, final Point3d control2,
429             final Point3d end) throws DrawRuntimeException
430     {
431         return bezier(size, start, control1, control2, end);
432     }
433 
434     /**
435      * Approximate a cubic B&eacute;zier curve from start to end with two control points with a specified precision.
436      * @param epsilon double; the precision.
437      * @param start Point3d; the start point of the B&eacute;zier curve
438      * @param control1 Point3d; the first control point
439      * @param control2 Point3d; the second control point
440      * @param end Point3d; the end point of the B&eacute;zier curve
441      * @return PolyLine3d; an approximation of a cubic B&eacute;zier curve between start and end, with the two provided control
442      *         points
443      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
444      *             constructed
445      */
446     public static PolyLine3d cubic(final double epsilon, final Point3d start, final Point3d control1, final Point3d control2,
447             final Point3d end) throws DrawRuntimeException
448     {
449         return bezier(epsilon, start, control1, control2, end);
450     }
451 
452     /**
453      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
454      * start and end.
455      * @param size int; the number of points for the B&eacute;zier curve
456      * @param start Ray3d; the start point and start direction of the B&eacute;zier curve
457      * @param end Ray3d; the end point and end direction of the B&eacute;zier curve
458      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, with the two provided control
459      *         points
460      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
461      *             constructed
462      */
463     public static PolyLine3d cubic(final int size, final Ray3d start, final Ray3d end) throws DrawRuntimeException
464     {
465         return cubic(size, start, end, 1.0);
466     }
467 
468     /**
469      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
470      * start and end with specified precision.
471      * @param epsilon double; the precision.
472      * @param start Ray3d; the start point and start direction of the B&eacute;zier curve
473      * @param end Ray3d; the end point and end direction of the B&eacute;zier curve
474      * @return PolyLine2d; an approximation of a cubic B&eacute;zier curve between start and end, with the two provided control
475      *         points
476      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
477      *             constructed
478      */
479     public static PolyLine3d cubic(final double epsilon, final Ray3d start, final Ray3d end) throws DrawRuntimeException
480     {
481         return cubic(epsilon, start, end, 1.0);
482     }
483 
484     /**
485      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
486      * start and end.
487      * @param size int; the number of points for the B&eacute;zier curve
488      * @param start Ray3d; the start point and start direction of the B&eacute;zier curve
489      * @param end Ray3d; the end point and end direction of the B&eacute;zier curve
490      * @param shape shape factor; 1 = control points at half the distance between start and end, &gt; 1 results in a pointier
491      *            shape, &lt; 1 results in a flatter shape, value should be above 0 and finite
492      * @return a cubic B&eacute;zier curve between start and end, with the two determined control points
493      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
494      *             constructed
495      */
496     public static PolyLine3d cubic(final int size, final Ray3d start, final Ray3d end, final double shape)
497             throws DrawRuntimeException
498     {
499         Throw.when(Double.isNaN(shape) || Double.isInfinite(shape) || shape <= 0, DrawRuntimeException.class,
500                 "shape must be a finite, positive value");
501         return cubic(size, start, end, shape, false);
502     }
503 
504     /**
505      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
506      * start and end with specified precision.
507      * @param epsilon double; the precision.
508      * @param start Ray3d; the start point and start direction of the B&eacute;zier curve
509      * @param end Ray3d; the end point and end direction of the B&eacute;zier curve
510      * @param shape shape factor; 1 = control points at half the distance between start and end, &gt; 1 results in a pointier
511      *            shape, &lt; 1 results in a flatter shape, value should be above 0 and finite
512      * @return a cubic B&eacute;zier curve between start and end, with the two determined control points
513      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
514      *             constructed
515      */
516     public static PolyLine3d cubic(final double epsilon, final Ray3d start, final Ray3d end, final double shape)
517             throws DrawRuntimeException
518     {
519         Throw.when(Double.isNaN(shape) || Double.isInfinite(shape) || shape <= 0, DrawRuntimeException.class,
520                 "shape must be a finite, positive value");
521         return cubic(epsilon, start, end, shape, false);
522     }
523 
524     /**
525      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
526      * start and end. The z-value is interpolated in a linear way.
527      * @param size int; the number of points for the B&eacute;zier curve
528      * @param start Ray3d; the start point and start direction of the B&eacute;zier curve
529      * @param end Ray3d; the end point and end direction of the B&eacute;zier curve
530      * @param shape shape factor; 1 = control points at half the distance between start and end, &gt; 1 results in a pointier
531      *            shape, &lt; 1 results in a flatter shape, value should be above 0
532      * @param weighted boolean; control point distance relates to distance to projected point on extended line from other end
533      * @return a cubic B&eacute;zier curve between start and end, with the two determined control points
534      * @throws NullPointerException when start or end is null
535      * @throws DrawRuntimeException in case size is less than 2, start is at the same location as end, shape is invalid, or the
536      *             B&eacute;zier curve could not be constructed
537      */
538     public static PolyLine3d cubic(final int size, final Ray3d start, final Ray3d end, final double shape,
539             final boolean weighted) throws NullPointerException, DrawRuntimeException
540     {
541         Point3d[] points = createControlPoints(start, end, shape, weighted);
542         return cubic(size, points[0], points[1], points[2], points[3]);
543     }
544 
545     /**
546      * Approximate a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
547      * start and end with specified precision.
548      * @param epsilon double; the precision.
549      * @param start Ray3d; the start point and start direction of the B&eacute;zier curve
550      * @param end Ray3d; the end point and end direction of the B&eacute;zier curve
551      * @param shape shape factor; 1 = control points at half the distance between start and end, &gt; 1 results in a pointier
552      *            shape, &lt; 1 results in a flatter shape, value should be above 0, finite and not NaN
553      * @param weighted boolean; control point distance relates to distance to projected point on extended line from other end
554      * @return PolyLine3d; an approximation of a cubic B&eacute;zier curve between start and end, with the two determined
555      *         control points
556      * @throws NullPointerException when start or end is null
557      * @throws DrawRuntimeException in case size is less than 2, start is at the same location as end, shape is invalid, or the
558      *             B&eacute;zier curve could not be constructed
559      */
560     public static PolyLine3d cubic(final double epsilon, final Ray3d start, final Ray3d end, final double shape,
561             final boolean weighted) throws NullPointerException, DrawRuntimeException
562     {
563         Point3d[] points = createControlPoints(start, end, shape, weighted);
564         return cubic(epsilon, points[0], points[1], points[2], points[3]);
565     }
566 
567     /**
568      * Create control points for a cubic B&eacute;zier curve defined by two Rays.
569      * @param start Ray3d; the start point (and direction)
570      * @param end Ray3d; the end point (and direction)
571      * @param shape double; the shape; higher values put the generated control points further away from end and result in a
572      *            pointier B&eacute;zier curve
573      * @param weighted boolean;
574      * @return Point3d[]; an array of four Point3d elements: start, the first control point, the second control point, end.
575      */
576     private static Point3d[] createControlPoints(final Ray3d start, final Ray3d end, final double shape, final boolean weighted)
577     {
578         Throw.whenNull(start, "start");
579         Throw.whenNull(end, "end");
580         Throw.when(start.distanceSquared(end) == 0, DrawRuntimeException.class,
581                 "Cannot create control points if start and end points coincide");
582         Throw.when(Double.isNaN(shape) || shape <= 0 || Double.isInfinite(shape), DrawRuntimeException.class,
583                 "shape must be a finite, positive value");
584 
585         Point3d control1;
586         Point3d control2;
587         if (weighted)
588         {
589             // each control point is 'w' * the distance between the end-points away from the respective end point
590             // 'w' is a weight given by the distance from the end point to the extended line of the other end point
591             double distance = shape * start.distance(end);
592             double dStart = start.distance(end.projectOrthogonalExtended(start));
593             double dEnd = end.distance(start.projectOrthogonalExtended(end));
594             double wStart = dStart / (dStart + dEnd);
595             double wEnd = dEnd / (dStart + dEnd);
596             control1 = start.getLocation(distance * wStart);
597             control2 = end.getLocationExtended(-distance * wEnd);
598         }
599         else
600         {
601             // each control point is half the distance between the end-points away from the respective end point
602             double distance = shape * start.distance(end) / 2.0;
603             control1 = start.getLocation(distance);
604             control2 = end.getLocationExtended(-distance);
605         }
606         return new Point3d[] {start, control1, control2, end};
607     }
608 
609     /**
610      * Construct a cubic B&eacute;zier curve from start to end with two generated control points at half the distance between
611      * start and end. The z-value is interpolated in a linear way. The size of the constructed curve is
612      * <code>DEFAULT_BEZIER_SIZE</code>.
613      * @param start Ray3d; the start point and orientation of the B&eacute;zier curve
614      * @param end Ray3d; the end point and orientation of the B&eacute;zier curve
615      * @return a cubic B&eacute;zier curve between start and end, with the two provided control points
616      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
617      *             constructed
618      */
619     public static PolyLine3d cubic(final Ray3d start, final Ray3d end) throws DrawRuntimeException
620     {
621         return cubic(DEFAULT_BEZIER_SIZE, start, end);
622     }
623 
624     /**
625      * Calculate the cubic B&eacute;zier point with B(t) = (1 - t)<sup>3</sup>P<sub>0</sub> + 3t(1 - t)<sup>2</sup>
626      * P<sub>1</sub> + 3t<sup>2</sup> (1 - t) P<sub>2</sub> + t<sup>3</sup> P<sub>3</sub>.
627      * @param t double; the fraction
628      * @param p0 double; the first point of the curve
629      * @param p1 double; the first control point
630      * @param p2 double; the second control point
631      * @param p3 double; the end point of the curve
632      * @return the cubic bezier value B(t)
633      */
634     @SuppressWarnings("checkstyle:methodname")
635     private static double B3(final double t, final double p0, final double p1, final double p2, final double p3)
636     {
637         double t2 = t * t;
638         double t3 = t2 * t;
639         double m = (1.0 - t);
640         double m2 = m * m;
641         double m3 = m2 * m;
642         return m3 * p0 + 3.0 * t * m2 * p1 + 3.0 * t2 * m * p2 + t3 * p3;
643     }
644 
645     /**
646      * Construct a B&eacute;zier curve of degree n.
647      * @param size int; the number of points for the B&eacute;zier curve to be constructed
648      * @param points Point3d...; the points of the curve, where the first and last are begin and end point, and the intermediate
649      *            ones are control points. There should be at least two points.
650      * @return the B&eacute;zier value B(t) of degree n, where n is the number of points in the array
651      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
652      *             constructed
653      */
654     public static PolyLine3d bezier(final int size, final Point3d... points) throws DrawRuntimeException
655     {
656         Throw.when(points.length < 2, DrawRuntimeException.class, "Too few points; need at least two");
657         Throw.when(size < 2, DrawRuntimeException.class, "size too small (must be at least 2)");
658         Point3d[] result = new Point3d[size];
659         double[] px = new double[points.length];
660         double[] py = new double[points.length];
661         double[] pz = new double[points.length];
662         for (int i = 0; i < points.length; i++)
663         {
664             px[i] = points[i].x;
665             py[i] = points[i].y;
666             pz[i] = points[i].z;
667         }
668         for (int n = 0; n < size; n++)
669         {
670             double t = n / (size - 1.0);
671             double x = Bn(t, px);
672             double y = Bn(t, py);
673             double z = Bn(t, pz);
674             result[n] = new Point3d(x, y, z);
675         }
676         return new PolyLine3d(result);
677     }
678 
679     /**
680      * Approximate a B&eacute;zier curve of degree n using <code>DEFAULT_BEZIER_SIZE</code> points.
681      * @param points Point3d...; the points of the curve, where the first and last are begin and end point, and the intermediate
682      *            ones are control points. There should be at least two points.
683      * @return the B&eacute;zier value B(t) of degree n, where n is the number of points in the array
684      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
685      *             constructed
686      */
687     public static PolyLine3d bezier(final Point3d... points) throws DrawRuntimeException
688     {
689         return bezier(DEFAULT_BEZIER_SIZE, points);
690     }
691 
692     /**
693      * Approximate a B&eacute;zier curve of degree n with a specified precision.
694      * @param epsilon double; the precision.
695      * @param points Point3d...; the points of the curve, where the first and last are begin and end point, and the intermediate
696      *            ones are control points. There should be at least two points.
697      * @return PolyLine3d; an approximation of a cubic B&eacute;zier curve between start and end, with the provided control
698      *         points
699      * @throws NullPointerException when points contains a null value
700      * @throws DrawRuntimeException in case the number of points is less than 2 or the B&eacute;zier curve could not be
701      *             constructed
702      */
703     public static PolyLine3d bezier(final double epsilon, final Point3d... points)
704             throws NullPointerException, DrawRuntimeException
705     {
706         Throw.when(points.length < 2, DrawRuntimeException.class, "Too few points; need at least two");
707         Throw.when(Double.isNaN(epsilon) || epsilon <= 0, DrawRuntimeException.class,
708                 "epsilonPosition must be a positive number");
709         if (points.length == 2)
710         {
711             return new PolyLine3d(points[0], points[1]);
712         }
713         NavigableMap<Double, Point3d> result = new TreeMap<>();
714         double[] px = new double[points.length];
715         double[] py = new double[points.length];
716         double[] pz = new double[points.length];
717         for (int i = 0; i < points.length; i++)
718         {
719             Point3d p = points[i];
720             Throw.whenNull(p, "points may not contain a null value");
721             px[i] = p.x;
722             py[i] = p.y;
723             pz[i] = p.z;
724         }
725         int initialSize = points.length - 1;
726         for (int n = 0; n < initialSize; n++)
727         {
728             double t = n / (initialSize - 1.0);
729             double x = Bn(t, px);
730             double y = Bn(t, py);
731             double z = Bn(t, pz);
732             result.put(t, new Point3d(x, y, z));
733         }
734         // Walk along all point pairs and see if additional points need to be inserted
735         Double prevT = result.firstKey();
736         Point3d prevPoint = result.get(prevT);
737         Map.Entry<Double, Point3d> entry;
738         while ((entry = result.higherEntry(prevT)) != null)
739         {
740             Double nextT = entry.getKey();
741             Point3d nextPoint = entry.getValue();
742             double medianT = (prevT + nextT) / 2;
743             double x = Bn(medianT, px);
744             double y = Bn(medianT, py);
745             double z = Bn(medianT, pz);
746             Point3d medianPoint = new Point3d(x, y, z);
747             Point3d projectedPoint = medianPoint.closestPointOnSegment(prevPoint, nextPoint);
748             double errorPosition = medianPoint.distance(projectedPoint);
749             if (errorPosition >= epsilon)
750             {
751                 // We need to insert another point
752                 result.put(medianT, medianPoint);
753                 continue;
754             }
755             if (prevPoint.distance(nextPoint) > epsilon)
756             {
757                 // Check for an inflection point by creating additional points at one quarter and three quarters. If these
758                 // are on opposite sides of the line from prevPoint to nextPoint; there must be an inflection point.
759                 // https://stackoverflow.com/questions/1560492/how-to-tell-whether-a-point-is-to-the-right-or-left-side-of-a-line
760                 double quarterT = (prevT + medianT) / 2;
761                 double quarterX = Bn(quarterT, px);
762                 double quarterY = Bn(quarterT, py);
763                 int sign1 = (int) Math.signum((nextPoint.x - prevPoint.x) * (quarterY - prevPoint.y)
764                         - (nextPoint.y - prevPoint.y) * (quarterX - prevPoint.x));
765                 double threeQuarterT = (nextT + medianT) / 2;
766                 double threeQuarterX = Bn(threeQuarterT, px);
767                 double threeQuarterY = Bn(threeQuarterT, py);
768                 int sign2 = (int) Math.signum((nextPoint.x - prevPoint.x) * (threeQuarterY - prevPoint.y)
769                         - (nextPoint.y - prevPoint.y) * (threeQuarterX - prevPoint.x));
770                 if (sign1 != sign2)
771                 {
772                     // There is an inflection point
773                     System.out.println("Detected inflection point between " + prevPoint + " and " + nextPoint);
774                     // Inserting the halfway point should take care of this
775                     result.put(medianT, medianPoint);
776                     continue;
777                 }
778             }
779             // TODO check angles
780             prevT = nextT;
781             prevPoint = nextPoint;
782         }
783         return new PolyLine3d(result.values().iterator());
784     }
785 
786     /**
787      * Calculate the B&eacute;zier point of degree n, with B(t) = Sum(i = 0..n) [C(n, i) * (1 - t)<sup>n-i</sup> t<sup>i</sup>
788      * P<sub>i</sub>], where C(n, k) is the binomial coefficient defined by n! / ( k! (n-k)! ), ! being the factorial operator.
789      * @param t double; the fraction
790      * @param p double...; the points of the curve, where the first and last are begin and end point, and the intermediate ones
791      *            are control points
792      * @return the B&eacute;zier value B(t) of degree n, where n is the number of points in the array
793      */
794     @SuppressWarnings("checkstyle:methodname")
795     private static double Bn(final double t, final double... p)
796     {
797         double b = 0.0;
798         double m = (1.0 - t);
799         int n = p.length - 1;
800         double fn = factorial(n);
801         for (int i = 0; i <= n; i++)
802         {
803             double c = fn / (factorial(i) * (factorial(n - i)));
804             b += c * Math.pow(m, n - i) * Math.pow(t, i) * p[i];
805         }
806         return b;
807     }
808 
809     /**
810      * Calculate factorial(k), which is k * (k-1) * (k-2) * ... * 1. For factorials up to 20, a lookup table is used.
811      * @param k int; the parameter
812      * @return factorial(k)
813      */
814     private static double factorial(final int k)
815     {
816         if (k < fact.length)
817         {
818             return fact[k];
819         }
820         double f = 1;
821         for (int i = 2; i <= k; i++)
822         {
823             f = f * i;
824         }
825         return f;
826     }
827 
828 }