findCurveSphereIntersection function

Offset? findCurveSphereIntersection(
  1. Path path,
  2. Offset center,
  3. double radius,
  4. double maxTolerance,
  5. bool firstIntersection,
)

Finds the intersection point between a curved path and a sphere.

The path parameter represents the curved path. The center parameter represents the center of the sphere. The radius parameter specifies the radius of the sphere. The maxTolerance parameter specifies the maximum tolerance for spacing between points on the path. The firstIntersection parameter specifies whether to find the first or last intersection.

Returns the intersection point as an Offset, or null if no intersection is found.

Implementation

Offset? findCurveSphereIntersection(Path path, Offset center, double radius,
    double maxTolerance, bool firstIntersection) {
  List<Offset> points = adaptivePathToPoints(path, maxTolerance);
  List<Offset> intersections = [];
  Offset previousPoint = points.first;
  for (Offset point in points.skip(1)) {
    double prevDist = (previousPoint - center).distance - radius;
    double currDist = (point - center).distance - radius;

    if (prevDist.sign != currDist.sign) {
      Offset intersection =
          refineIntersection(previousPoint, point, center, radius);
      intersections.add(intersection);
    }

    previousPoint = point;
  }

  if (intersections.isNotEmpty) {
    return firstIntersection ? intersections.first : intersections.last;
  }

  return null;
}