/*
 * Copyright (C) 1998  Ralf Wiebicke
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package de.rw7.polygon;

import java.awt.Polygon;

/*
       +y
    Q0  |  Q1
-x -----+----- +x
    Q3  |  Q2
       -y
Die Quadranten werden nach dem obigen Schema nummeriert. Die Geraden werden
jeweils dem links bzw. oberhalb gelegenen Quadranten zugeschlagen.

Ein Vollwinkel entspricht einem alpha=4.
*/

public class Ahlemeyer implements Algo
{

	Polygon P;

	synchronized public void setPolygon(Polygon P)
	{
		this.P = P;
	}

	public int isInside(int x, int y)
	{
		if (P.npoints <= 0)
			return (-1);
		int alpha = 0;
		int ax = P.xpoints[P.npoints - 1];
		int ay = P.ypoints[P.npoints - 1];
		int aQ;
		if (ay <= y)
			if (ax <= x)
				aQ = 0;
			else
				aQ = 1;
		else if (ax <= x)
			aQ = 3;
		else
			aQ = 2;
		int bx, by, bQ, zx;

		for (int i = 0; i < P.npoints; i++)
		{
			bx = P.xpoints[i];
			by = P.ypoints[i];
			if (by <= y)
				if (bx <= x)
					bQ = 0;
				else
					bQ = 1;
			else if (bx <= x)
				bQ = 3;
			else
				bQ = 2;

			switch ((bQ - aQ) & 3)
			{
				case 0 :
					break;
				case 1 :
					alpha++;
					break;
				case 3 :
					alpha--;
					break;
				default :
					{
						if (x == (zx = ((bx - ax) * (y - ay) / (by - ay)) + ax))
							return (0);
						if ((x > zx) == (by > ay))
							alpha -= 2;
						else
							alpha += 2;
					}
			}
			ax = bx;
			ay = by;
			aQ = bQ;
		}

		switch (alpha)
		{
			case 0 :
				return (-1);
			case 4 :
			case -4 :
				return (1);
			default :
				if ((alpha & 3) == 0)
					return (alpha); // Das waere ein "geringeltes" Polygon..
				else
					throw (new IllegalArgumentException());
				// ..und das ein Programmierfehler.
		}
	}

}
