import java.awt.*;
import java.awt.image.*;

/* 
	The sprite class allows drawing of a raster on another.  I had 
originally implemented a form of alpha channel, that seemed to work pretty well,
but was mathematically incorrect (a bitmask approach).  Other methods caused
either a flashing effect, or performance to be too slow, or both.

	One note, I was going to make the action of a Sprite be to switch to
an xor implementation.  I basically got two frames, one as the Sprite with no
background, and the second was the whole picture with the Sprite gone.  I have
two guesses, one is that the Sprite's draw() method gets called twice somehow,
the other is some wierd relationship between ImageObserver and ImageProducer,
where the xor operation actually causes some freak side-effect.  I really don't
know Java well enough (First program).
*/

class Sprite extends Raster
{
	int x, y;
	double maxalpha;
	boolean xor;

	public Sprite(Image image, int xpos, int ypos)
	{
		super(image);
		x = xpos;
		y = ypos;
		maxalpha = 1.0;
	}

// A cheap hack to keep from having to clip the Sprite in negative X.
	public void MoveTo( int newx, int newy)
	{
		x = newx >= 0 ? newx : x;
		y = newy >= 0 ? newy : y;
	}

	public boolean query(int xpos, int ypos)
	{
		if (x <= xpos)
			if (y <= ypos)
				if (y+height >= ypos)
					if (x+width >= xpos)
					{
						int soffset = (ypos - y)*width + xpos - x;
						if (ColorModel.getRGBdefault().getAlpha(pixel[soffset]) > 0)
						{
							return true;
						}
					}
		return false;
    }
    
    void action()
    {}
    
    public int getXhome()
    {
    	return x;
    }
    
    public int getYhome()
    {
    	return y;
    }
	
	public void Draw(Raster bgnd)
	{
		int xpos = x, ypos = y;
		int destx, desty;
		int maxx, maxy;
		desty = ypos;
		destx = xpos;

		int rastpixels[] = bgnd.getPixels();
		
		if (xpos > bgnd.width || ypos > bgnd.height) return;
		maxx = width+destx > bgnd.width ? bgnd.width-destx : width;
		maxy = height+desty > bgnd.height ? bgnd.height-desty : height;
		for ( ypos = 0; ypos < maxy; ++ypos)
		{
			ColorModel color = ColorModel.getRGBdefault();
			int soffset = ypos * width;
			int doffset = desty * bgnd.width;
			destx = x;
			++desty;
			for ( xpos = 0; xpos < maxx ; ++xpos, ++destx)
			{
				if (doffset+destx > bgnd.size())
				{
					return;
				}
				if (color.getAlpha(pixel[soffset+xpos]) == 255)
				{
					if (xor)
						rastpixels[doffset+destx] = ~pixel[soffset+xpos];
					else
						rastpixels[doffset+destx] = pixel[soffset+xpos];
				}	
			}
		}
	}
}

