

import java.util.*;
import java.awt.*;
import java.applet.*;


public class MathArt08 extends Applet{
	
	int w, h;
	private Image offImage;
   	private Dimension offDimension;
	private Graphics offGraphics;
	Color c = new Color(0,0,0);
	int posx, posy;
	
	public void init() {
		
		Dimension d = this.size(); 
		w = d.width;
		h = d.height;
		
		if ((offImage == null) || (w != offDimension.width) || (h != offDimension.height)) {
			offImage = createImage(w, h);
			offDimension = d;
			offGraphics = offImage.getGraphics();
		}
		
		offGraphics.setColor(Color.black);	
		offGraphics.fillRect(0,0,w,h);

//		color2(w/2-6,h/2-8,w,h,6,8);
		color1(w/2,h/2,w,h,6,8);
		repaint();	
	}
	
	public void update(Graphics g) {
		paint(g);
	}
	
	public void paint(Graphics g) {	
		g.drawImage(offImage, 0, 0, this);
	}

	public void color1(int x, int y, int rW, int rH, int sW, int sH) {
		
		for (int i=x-rW/2; i<x+rW/2; i=i+sW) {
			for (int j=y-rH/2; j<y+rH/2; j=j+sH) {		
				
				int red   = ((i-posx)*255)/(2*w);				
				int green = ((j-posy)*255)/h;
				int blue  = (i*j)/45;
	

			//	int red   = (i-2*(posx+w/2))/2;				
			//	int green = (j-4*posy/3)/2;


				if (red>510) red=red%510;
				if ((red < 0)   || (red > 255))   red=red%255;
				red=red/2+122;

		//		if ((red < 0)   || (red > 255))   red=255-(red%255);

				if (green>510) green=green%510;
				if ((green < 0) || (green > 255)) green = green%255;
				
		//		if ((green < 0) || (green > 255)) green = 255-(green%255);

		//		if (blue>510) blue=blue%510;

				if ((blue < 0)  || (blue > 255))  blue = blue%255;
				blue=blue/2+122;
				
				c = new Color(red,green,blue);
				
				offGraphics.setColor(c);
				offGraphics.fillRect(i,j,sW-1,sH-1);	
			}
		}
	
	}

		public void color2(int x, int y, int rW, int rH, int sW, int sH) {


		int q = posx+posy;

		for (int i=x-rW; i<x+rW+1; i=i+sW) {
			for (int j=y-rH; j<y+rH+1; j=j+sH) {
	
					double sin = Math.sin((double)j*i/(double)384);
					double cos = Math.cos((double)i/(double)24);
					double hue = 2*( (sin + cos)/(double)(20) + (double)(q)*(double)(0.001125));
					
		//				if (hue > (0.2)) hue = (double)(0.4) - hue;
					if (hue <0) hue = hue * (double)(-1);
					if (hue >1) hue = 1 - (hue -1);

			//		double sat = ((double)posx/(double)w)/2 + (double)(0.15);

			//		double value = ((double)(posy)/(double)(h))/2 + (double)(0.35);
					
					c = new Color(Color.HSBtoRGB ((float)(hue) , (float)(0.4), (float)(0.4))); 
					
					offGraphics.setColor(c);

				offGraphics.fillRect(i,j,sW,sH);	
			}
		}
	
	}

			


	public boolean mouseDown(Event e, int x, int y) {	
		posx=x;
		posy=y;
	//	color2(w/2-6,h/2-8,w,h,6,8);
		color1(w/2,h/2,w,h,6,8);
		repaint();

		return true;
	}
		
}









