distance_from_point_to_line_segment Function

public pure function distance_from_point_to_line_segment(x1, x2, x) result(d)

Compute the distance between a line segment and a point.

References

  1. http://forums.codeguru.com/showthread.php?194400-Distance-between-point-and-line-segment

Note

x,x1,x2 should all be the same length

Arguments

Type IntentOptional Attributes Name
real(kind=wp), intent(in), dimension(:) :: x1
real(kind=wp), intent(in), dimension(:) :: x2
real(kind=wp), intent(in), dimension(:) :: x

Return Value real(kind=wp)


Called by

proc~~distance_from_point_to_line_segment~~CalledByGraph proc~distance_from_point_to_line_segment geometry_module::distance_from_point_to_line_segment proc~distance_from_point_to_path geometry_module::distance_from_point_to_path proc~distance_from_point_to_path->proc~distance_from_point_to_line_segment proc~geometry_unit_test geometry_module::geometry_unit_test proc~geometry_unit_test->proc~distance_from_point_to_path

Source Code

    pure function distance_from_point_to_line_segment(x1, x2, x) result(d)

    implicit none

    real(wp),dimension(:),intent(in) :: x1
    real(wp),dimension(:),intent(in) :: x2
    real(wp),dimension(:),intent(in) :: x
    real(wp)                         :: d

    real(wp),dimension(size(x1)) :: x12
    real(wp) :: s
    real(wp) :: x12_mag

    x12 = x1 - x2
    x12_mag = norm2(x12)

    if (x12_mag==0.0_wp) then

        d = norm2(x1 - x)

    else

        s = dot_product( x1-x, x12 ) / dot_product( x12, x12 )

        !if the projection is not on the segment,
        ! then use the closest end point:
        if (s<0.0_wp) then
            s = 0.0_wp
        else if (s>1.0_wp) then
            s = 1.0_wp
        end if

        d = norm2( x - x1 + s*x12 )

    end if

    end function distance_from_point_to_line_segment