Newsgroups: comp.robotics
Path: brunix!cat.cis.Brown.EDU!agate!howland.reston.ans.net!europa.eng.gtefsd.com!swiss.ans.net!newsgate.watson.ibm.com!watnews.watson.ibm.com!eclipse!toc.torolab.ibm.com!dchapman
From: dchapman@toc.torolab.ibm.com (Dale Chapman Tic)
Subject: Re: Point in a rectangle
Sender: usenet@eclipse.torolab.ibm.com (eclipse sysadm)
Message-ID: <Cu2pB1.13Mn@eclipse.torolab.ibm.com>
Date: Fri, 5 Aug 1994 17:45:01 GMT
References:  <31q3jj$hoh@schema.fiu.edu> <Donald.Heller.153.00085A91@jpl.nasa.gov>
Organization: IBM Canada, Toronto Lab
Lines: 43

>>Maybe this question has been asked a million times before, but I would
>>really appreciate if someone could tell me an efficient way of finding if
>>a particular point lies inside a rectangle (of arbitrary orientation).

>>Please direct all responses to mookherj@fiu.edu.

>>Thanks in advance,
>>Jay

>Why don't you buy or borrow a first year college book on Vector Analysis.
>There is an easy section on finding the distance from a point to a line.
>You take each edge of the rectangle and convert it to vector notation.
>Then you do this for each of the four edges.  If the two vectors (from
>the point to each of the opposite parallel edges) have opposite directions,
>the point is between those edges.  If the other two vectors (from the point
>to each of the remaining two edges) also have opposite directions, then the
>point is totally within the rectangle.  The degenerate cases are easy...
>If a vector has zero length, the point is ON the edge.  If two orthogonal
>vectors are both zero, the point is ON the corner.

The solution above is an excellent solution to determine if a specified
point lies within a given rectangle. However, it is not an efficient method
to determine which points on a grid lie within an arbitrary rectangle.
The above solution will work, however it is an exhaustive search of the 
problem domain, with multiple calculations for each point. A more direct 
method of calculating "occupancy" is through a polygon fill method.
The algorithm is as follows:
1) locate the four corners.
2) rasterize the four lines (see basic graphics text for algorithm)
3) start at the corner with the highest Y value.
4) move down one row from the corner and fill in spaces to the
       left until a line is encountered, then proceed to the right until the
       right line is encountered.
5) move down another row.
6) repeat 4 & 5 until the corner with the lowest y value is encountered.

This will yield a map that indicates ALL points that lie within an 
arbitrary rectangle within a given grid.

I hope that one of these two algorithms will satisfy your problem.

Dale Chapman
dchapman@vnet.ibm.com
