from operation_vector import *
from scene import *

class Intersection:
    def __init__(self, position, normal, object):
        self.position = position
        self.normal = normal
        self.object = object

def intersect(objet, ray):
    o = ray.starting_point
    l = ray.direction
    if type(objet) is Sphere:
        centre = objet.centre
        r = objet.radius
        a = l*l
        diff = o-centre
        b = 2*(l*diff)
        c = diff*diff - r**2
        delta = b**2 - 4*a*c
        if delta > 0:
            intersection = [(-b - delta**0.5)/(2*a), (-b + delta**0.5)/(2*a)]
        elif delta == 0:
            intersection = [-b/(2*a)]
        else:
            intersection = []
        if len(intersection) == 0 or max(intersection) < 0:
            return None
        elif min(intersection) < 0:
            position = o + l*max(intersection)
        else:
            position = o + l*min(intersection)
        if diff.norm() >= r:
            return Intersection(position, (position - centre).normalized(), objet)
        else:
            return Intersection(position, -(position - centre).normalized(), objet)