findInverse method

double findInverse(
  1. double x
)

Returns the parameter t that corresponds to the given x value of the spline.

This will only work properly for curves which are single-valued in x (where every value of x maps to only one value in 'y', i.e. the curve does not loop or curve back over itself). For curves that are not single-valued, it will return the parameter for only one of the values at the given x location.

Implementation

double findInverse(double x) {
  double start = 0.0;
  double end = 1.0;
  late double mid;
  double offsetToOrigin(double pos) => x - transform(pos).dx;
  // Use a binary search to find the inverse point within 1e-6, or 100
  // subdivisions, whichever comes first.
  const double errorLimit = 1e-6;
  int count = 100;
  final double startValue = offsetToOrigin(start);
  while ((end - start) / 2.0 > errorLimit && count > 0) {
    mid = (end + start) / 2.0;
    final double value = offsetToOrigin(mid);
    if (value.sign == startValue.sign) {
      start = mid;
    } else {
      end = mid;
    }
    count--;
  }
  return mid;
}