intersectSphere Function

public function intersectSphere(orig, dir, t, centre, radius)

calculates where a line, with origin:orig and direction:dir hits a sphere, centre:centre and radius:radius returns true if intersection exists returns t, the paramertised parameter of the line equation adapted from scratchapixel

Arguments

Type IntentOptional Attributes Name
type(vector), intent(in) :: orig

Origin of the ray

type(vector), intent(in) :: dir

Direction vector of the ray

real(kind=wp), intent(out) :: t

Distance from orig to the intersection point

type(vector), intent(in) :: centre

Centre of the sphere

real(kind=wp), intent(in) :: radius

Radius of the sphere

Return Value logical


Source Code

    logical function intersectSphere(orig, dir, t, centre, radius)
    !! calculates where a line, with origin:orig and direction:dir hits a sphere, centre:centre and radius:radius
    !! returns true if intersection exists
    !! returns t, the paramertised parameter of the line equation
    !! adapted from scratchapixel
        !> Direction vector of the ray
        type(vector),  intent(IN)  :: dir
        !> Origin of the ray
        type(vector),  intent(IN)  :: orig
        !> Centre of the sphere
        type(vector),  intent(IN)  :: centre
        !> Distance from orig to the intersection point
        real(kind=wp), intent(OUT) :: t
        !> Radius of the sphere
        real(kind=wp), intent(IN)  :: radius

        type(vector)  :: L
        real(kind=wp) :: t0, t1, a, b, c, tmp

        intersectSphere = .false.

        L = orig - centre
        a = dir .dot. dir
        b = 2._wp * (dir .dot. L)
        c = (l .dot. l) - radius**2

        if(.not. solveQuadratic(a, b, c, t0, t1))return
        if(t0 > t1)then
            tmp = t1
            t1 = t0
            t0 = tmp
        end if
        if(t0 < 0._wp)then
            t0 = t1
            if(t0 < 0._wp)return
        end if

        t = t0
        intersectSphere = .true.
        return

    end function intersectSphere