/////////////////////////////////////////////////////////////
//                                                         //
// Copyright (c) 2007-2014 by The University of Queensland //
// Centre for Geoscience Computing                         //
// http://earth.uq.edu.au/centre-geoscience-computing      //
//                                                         //
// Primary Business: Brisbane, Queensland, Australia       //
// Licensed under the Open Software License version 3.0    //
// http://www.opensource.org/licenses/osl-3.0.php          //
//                                                         //
/////////////////////////////////////////////////////////////

#include "LineSegment2D.h"

// -- system includes --
#include <cmath>

using std::fabs;

/*!
  default constructor -> zero all data
*/
LineSegment2D::LineSegment2D() : Line2D()
{}

/*!
  Construct a line segment from 2 points. The order of the points determines
  the direction of the normal.

  \param p1 1st point
  \param p2 2nd point

  \warning doesn't check p1!=p2
*/
LineSegment2D::LineSegment2D(const Vector3& p1,const Vector3& p2) : Line2D(p1,p2)
{}


/*!
  Get the distance of a point from the line segment

  \param p the point
*/
double LineSegment2D::getDist(const Vector3& p) const
{
  double res;

  double du=(p-m_p1)*((m_p2-m_p1).unit());
  if((0<=du) && (du <=(m_p2-m_p1).norm())){// nearest point inside segment
    res=fabs((p-m_p1)*m_normal); 
  } else { // nearest point  outside -> get distance to closest endpoint
    double d1=(p-m_p1).norm();
    double d2=(p-m_p2).norm();
    res = (d1<d2) ? d1 : d2;
  }

  return res;
}

/*!
  output line segment
*/
ostream& operator<< (ostream& ost, const LineSegment2D& L)
{
  ost << L.m_p1 << "-" << L.m_p2;

  return ost;
}
