#include <psychlops.h>
using namespace Psychlops;

struct GaborVar : public Psychlops::Rectangle {
	double contrast, wavelength, orientation, phase;
};

void psychlops_main() {
	//Canvas cnvs(1024,768,Canvas::window);
	Canvas cnvs(Canvas::fullscreen);
	cnvs.watchFPS();
	cnvs.showFPS();
	Mouse::show();

	const int N = 2500;
	Figures::ShaderPlaid *plaid;
	plaid = new Figures::ShaderPlaid[N];
	for(int y=0; y<N; y++) {
		plaid[y].phase = random(2*PI);
		plaid[y].contrast = random(1.0);
		plaid[y].wavelength = 5+random(10.0);
		plaid[y].phase2 = random(2*PI);
		plaid[y].contrast2 = random(1.0);
		plaid[y].wavelength2 = 10+random(20.0);
	}

	Image img;
	GaborVar gaborVar[100];
	for(int y=0; y<100; y++) {
		gaborVar[y].contrast = 0.5+random(0.5);
		gaborVar[y].phase = random(2*PI);
		gaborVar[y].wavelength = 5+random(10.0);
	}


	double sigma = 6.0;
	int n1 = 3, n2 = 0;
	Widgets::Slider slider1, slider2;
	slider1.link(n1, Interval(-1,10), 1).set(200, 30).centering().shift(-cnvs.getHcenter()/2,0);
	slider2.link(n2, Interval(-1,1000), 4).set(200, 30).centering().shift(cnvs.getHcenter()/2,0);

	while(!Keyboard::esc.pushed()) {
		cnvs.clear(Color::gray);
		if(slider1.changed()) for(int i=0; i<n1; i++) gaborVar[i].centering(Psychlops::random(cnvs.getWidth()/2), Psychlops::random(cnvs.getHeight())).shift(0, 0);
		if(slider2.changed()) for(int i=0; i<n2; i++) plaid[i].centering(Psychlops::random(cnvs.getWidth()/2), Psychlops::random(cnvs.getHeight())).shift( cnvs.getWidth()/2, 0);
		for(int i=0; i<n1; i++) {
			gaborVar[i].phase += PI/6;
			gaborVar[i].wavelength = gaborVar[i].wavelength + .5*sin(gaborVar[i].phase);
			gaborVar[i].orientation = -atan2(gaborVar[i].getCenter().x-cnvs.mouse().x, gaborVar[i].getCenter().y-cnvs.mouse().y);
			Figures::drawGaborToImage(img, sigma, 1.0/gaborVar[i].wavelength, gaborVar[i].contrast, gaborVar[i].orientation, gaborVar[i].phase);
			img.centering(gaborVar[i]).draw();
		}
		for(int i=0; i<n2; i++) {
			plaid[i].resize(sigma*8, sigma*8);
			plaid[i].phase += PI/6;
			plaid[i].wavelength = plaid[i].wavelength + .5*sin(plaid[i].phase);
			plaid[i].orientation = -atan2(plaid[i].getCenter().x-cnvs.mouse().x, plaid[i].getCenter().y-cnvs.mouse().y);
			plaid[i].contrast2 = Keyboard::spc.pressed() ? .5 : 0;
			plaid[i].phase2 += PI/6;
			plaid[i].wavelength2 = plaid[i].wavelength2 + .5*sin(plaid[i].phase2);
			plaid[i].orientation2 = -PI/2-atan2(plaid[i].getCenter().x-cnvs.mouse().x, plaid[i].getCenter().y-cnvs.mouse().y);
			plaid[i].draw();
		}
		slider1.draw();
		slider2.draw();
		cnvs.flip();
	}
	delete [] plaid;
}

