intersectAsSegments method

Vector2? intersectAsSegments(
  1. Line other
)

Implementation

vm.Vector2? intersectAsSegments(Line other) {
  Line line1 = this;
  final p = line1.a;
  final p2 = line1.b;

  final q = other.a;
  final q2 = other.b;

  var r = p2 - p;
  var s = q2 - q;
  var rxs = r.cross(s);
  var qpxr = (q - p).cross(r);

  // If r x s = 0 and (q - p) x r = 0, then the two lines are collinear.
  if (_isZero(rxs) && _isZero(qpxr)) {
    // // 1. If either  0 <= (q - p) * r <= r * r or 0 <= (p - q) * s <= * s
    // // then the two lines are overlapping,
    // if (considerCollinearOverlapAsIntersect) if ((0 <= (q - p).dot(r) &&
    //         (q - p).dot(r) <= r.dot(r)) ||
    //     (0 <= (p - q).dot(s) && (p - q).dot(s) <= s.dot(s))) return true;

    // 2. If neither 0 <= (q - p) * r = r * r nor 0 <= (p - q) * s <= s * s
    // then the two lines are collinear but disjoint.
    // No need to implement this expression, as it follows from the expression above.
    return null;
  }

  // 3. If r x s = 0 and (q - p) x r != 0, then the two lines are parallel and non-intersecting.
  if (_isZero(rxs) && !_isZero(qpxr)) return null;

  // t = (q - p) x s / (r x s)
  var t = (q - p).cross(s) / rxs;

  // u = (q - p) x r / (r x s)

  var u = (q - p).cross(r) / rxs;

  // 4. If r x s != 0 and 0 <= t <= 1 and 0 <= u <= 1
  // the two line segments meet at the point p + t r = q + u s.
  if (!_isZero(rxs) && (0 <= t && t <= 1) && (0 <= u && u <= 1)) {
    // We can calculate the intersection point using either t or u.
    // An intersection was found.
    return p + (r * t);
  }

  // 5. Otherwise, the two line segments are not parallel but do not intersect.
  return null;
}