diff -r 3089611c99d1 -r 5933250813a3 geometry.py --- a/geometry.py Tue Jan 23 12:29:30 2018 +0200 +++ b/geometry.py Tue Jan 23 14:09:44 2018 +0200 @@ -410,3 +410,48 @@ assert(len(polygon.vertices) == 3) a, b, c = polygon.vertices[:3] return cross_product(b - a, b - c) + +def line_intersection_xy(line_1, line_2): + ''' + Computes 2D line intersection. Can return a point outside the given + segments. Z is ignored. + ''' + a, b = line_1.vertices + c, d = line_2.vertices + denominator = (a.x - b.x) * (c.y - d.y) - (a.y - b.y) * (c.x - d.x) + x = (c.x - d.x) * (a.x * b.y - a.y * b.x) + x -= (a.x - b.x) * (c.x * d.y - c.y * d.x) + y = (c.y - d.y) * (a.x * b.y - a.y * b.x) + y -= (a.y - b.y) * (c.x * d.y - c.y * d.x) + try: + x /= denominator + y /= denominator + except ZeroDivisionError: + return None + else: + return Vertex(x, y, 0) + +def line_segment_intersection_xy(line_1, line_2): + ''' + Computes 2D line intersection. Only returns a result if it falls + inside the line segments. Z is ignored. + ''' + from math import inf + intersection = line_intersection_xy(line_1, line_2) + if intersection: + a, b = line_1.vertices + c, d = line_2.vertices + try: + t = (intersection.x - a.x) / (b.x - a.x) + except ZeroDivisionError: + t = inf + try: + u = (intersection.y - a.y) / (b.y - a.y) + except ZeroDivisionError: + u = inf + if 0 < t < 1 or 0 < u < 1: + return intersection + else: + return None + else: + return None