intersectRay method

Vector3? intersectRay(
  1. Ray ray,
  2. Vector3 target
)

Implementation

Vector3? intersectRay(Ray ray, Vector3 target) {
  // based on "Fast Ray-Convex Polyhedron Intersection"  by Eric Haines, GRAPHICS GEMS II

  final faces = this.faces;

  double tNear = -double.infinity;
  double tFar = double.infinity;

  for (int i = 0, l = faces.length; i < l; i++) {
    final face = faces[i];

    // interpret faces as planes for the further computation

    final vN = face.distanceToPoint(ray.origin);
    final vD = face.normal.dot(ray.direction);

    // if the origin is on the positive side of a plane (so the plane can "see" the origin) and
    // the ray is turned away or parallel to the plane, there is no intersection

    if (vN > 0 && vD >= 0) return null;

    // compute the distance from the ray’s origin to the intersection with the plane

    double t = (vD != 0) ? (-vN / vD) : 0;

    // only proceed if the distance is positive. a negative distance means the intersection point
    // lies "behind" the origin

    if (t <= 0) continue;

    // now categorized plane as front-facing or back-facing

    if (vD > 0) {
      //  plane faces away from the ray, so this plane is a back-face

      tFar = math.min(t, tFar);
    } else {
      // front-face

      tNear = math.max(t, tNear);
    }

    if (tNear > tFar) {
      // if tNear ever is greater than tFar, the ray must miss the convex hull

      return null;
    }
  }

  // evaluate intersection point

  // always try tNear first since its the closer intersection point

  if (tNear != -double.infinity) {
    ray.at(tNear, target);
  } else {
    ray.at(tFar, target);
  }

  return target;
}