import java.awt.*;

public class MandelRenderArea extends RenderArea {
	
	protected double cx, cy, wx, wy;
	protected int maxit;
	
	public MandelRenderArea(int w, int h) {
		super(w, h);
		cx = -.6;
		cy = 0.0;
		wx = 3;
		maxit = 100;
		wy = (double)height*wx/width;
	}
	
	public void setParams(double x, double y, double w, int m) {
		stop();
		cx = x;
		cy = y;
		wx = w;
		wy = (double)height*wx/width;
		maxit = m;
	}
	
	public void setParams(double x, double y, double w) {
		setParams(x, y, w, (maxit == 0)?100:maxit);
	}
	
	protected int render(double x, double y) {
		double cr = cx - wx/2 + (x/(width-1))*wx;
		double ci = cy + wy/2 - (y/(height-1))*wy;
		double zr = 0, zi = 0, nzr;
		int n = 0;
		while(zr*zr + zi*zi <= 4 && ++n <= maxit) {
			nzr = zr*zr - zi*zi + cr;
			zi = 2*zr*zi + ci;
			zr = nzr;
		}
		n--;
		if (n == maxit) return 0x00000000;
		return getColor(n);
	}
	
	public int getColor(int n) {
		n = 1020*n/(maxit-1);
		if (n <= 255) return 0 << 16 | 0 << 8 | n;
		n -= 255;
		if (n <= 255) return n << 16 | 0 << 8 | (255-n);
		n -= 255;
		if (n <= 255) return 255 << 16 | n << 8 | 0;
		n -= 255;
		return 255 << 16 | 255 << 8 | n;
	}
	
}