libgeda: Remove some exit() calls and assertions.
[geda-gaf/peter-b.git] / libgeda / src / m_line.c
blob40dd84c40cf78e4d6a38dbddbb396635bd3415a9
1 /* gEDA - GPL Electronic Design Automation
2 * libgeda - gEDA's library
3 * Copyright (C) 1998-2010 Ales Hvezda
4 * Copyright (C) 1998-2010 gEDA Contributors (see ChangeLog for details)
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 /*! \file m_line.c
23 * \brief Low-level mathmatical functions for lines
26 #include <config.h>
27 #include <math.h>
28 #include <stdio.h>
30 #include "libgeda_priv.h"
32 #ifdef HAVE_LIBDMALLOC
33 #include <dmalloc.h>
34 #endif
37 /*! \brief Calculates the distance between the given point and the closest
38 * point on the given line segment.
40 * If the closest point on the line resides beyond the line segment's
41 * end point, this function returns the distance from the given point to the
42 * closest end point.
44 * If the line represents a single point (the endpoints are the same), this
45 * function calcualtes the distance to that point.
47 * \param [in] line The LINE object.
48 * \param [in] x The x coordinate of the given point.
49 * \param [in] y The y coordinate of the given point.
50 * \return The shortest distance from the object to the point. With an
51 * invalid parameter, this function returns G_MAXDOUBLE.
53 double m_line_shortest_distance (LINE *line, int x, int y)
55 double cx, cy;
56 double dx, dy;
57 double dx0, dy0;
58 double lx0, ly0;
59 double ldx, ldy;
60 double t;
62 g_return_val_if_fail (line != NULL, G_MAXDOUBLE);
64 lx0 = (double)line->x[0];
65 ly0 = (double)line->y[0];
66 ldx = (double)(line->x[1] - line->x[0]);
67 ldy = (double)(line->y[1] - line->y[0]);
69 if (ldx == 0 && ldy == 0) {
70 /* if line is a point, just calculate distance to the point */
71 dx = x - lx0;
72 dy = y - ly0;
74 } else {
75 /* calculate parametric value of perpendicular intersection */
76 dx0 = ldx * (x - lx0);
77 dy0 = ldy * (y - ly0);
79 t = (dx0 + dy0) / (ldx * ldx + ldy * ldy);
81 /* constrain the parametric value to a point on the line */
82 t = max (t, 0);
83 t = min (t, 1);
85 /* calculate closest point on the line */
86 cx = t * ldx + lx0;
87 cy = t * ldy + ly0;
89 /* calculate distance to closest point */
90 dx = x - cx;
91 dy = y - cy;
94 return sqrt ((dx * dx) + (dy * dy));