import java.awt.*;
import java.awt.image.*;

class Sprite extends Raster2 {
  int x, y;           // current position of sprite on playfield
  Image output;
  Raster2 bgnd;

  public Sprite(Image image, int ix, int iy, Raster2 bg) {    // initialize sprite with an image
    super(image);
    x = ix;
    y = iy;
    bgnd = bg;

    for(int i=0; i<pixel.length; i++)
      if((pixel[i] & 0xFFFFFF) == 0)
    	pixel[i] = 0;

    //    render();
  }

  public void render() {
    int ix = 0, iy = 0, iw = width, ih = height;
    int i, j;

    // off edge top
    if((y + height/2) < 0)
      return;

    // off edge bottom
    if((y - height/2) > bgnd.height)
      return;

    // off edge left
    if((x + width/2) < 0)
      return;

    // off edge right
    if((x - width/2) > bgnd.width)
      return;

    // on edge top
    if((y - height/2) < 0)
      iy = height/2 - y;

    // on edge left
    if((x - width/2) < 0)
      ix = width/2 - x;

    // on edge right
    if((x + width/2) > bgnd.width)
      iw = bgnd.width - (x - width/2);

    // on edge bottom
    if((y + height/2) > bgnd.height)
      ih = bgnd.height - (y - height/2);

    for(j=iy; j<ih; j++)
      for(i=ix; i<iw; i++) {
	int ipix = getPixel(i, j);
	int bpix = bgnd.getPixel(i + x - width/2, j + y - height/2);
	int at, r, b, g, br, bg, bb, ar, ag, ab;
	double a;

	at = ((ipix >>> 24));
	a = at/255.0;
	r = ((ipix >>> 16) & 0xFF);
	g = ((ipix >>> 8) & 0xFF);
	b = ((ipix >>> 0) & 0xFF);
	br = ((bpix >>> 16) & 0xFF);
	bg = ((bpix >>> 8) & 0xFF);
	bb = ((bpix >>> 0) & 0xFF);
	ar = (int)((1.0 - a) * br) + (int)(a * r);
	ag = (int)((1.0 - a) * bg) + (int)(a * g);
	ab = (int)((1.0 - a) * bb) + (int)(a * b);

	ar &= 0xFF;
	ag &= 0xFF;
	ab &= 0xFF;
	
	bgnd.setPixel((255 << 24) + (ar << 16) + (ag << 8) + (ab << 0), i + x - width/2, j + y - height/2);
      }
    //System.out.println(ix + " " + iy + " " + iw + " " + ih);
    //((Playfield)bgnd).mem.newPixels(ix + x - width/2 - 10, iy + y - height/2 - 10, iw + 10, ih + 10);
  }

  public void Draw(Component win, Graphics g) { // draws sprite on a Raster
    g.drawImage(output, x - width/2, y - height/2, win);
  }

}
