#include "includes.h"

#include "scene.h"
#include "renderer.h"

SDL_Surface* screen;

Renderer* renderer;

bool has_measured_time = false;

bool input(void) {
	SDL_Event event;
	while (SDL_PollEvent(&event)) {
		switch (event.type) {
			case SDL_KEYDOWN:
				switch (event.key.keysym.sym) {
					case SDLK_ESCAPE:
						return false;
						break;
					case SDLK_s:
						if (renderer->finished) {
							printf("Saving image as \"ray-traced-image.bmp\".\n");
							renderer->save("ray-traced-image.bmp");
						}
						break;
				}
				break;
			case SDL_QUIT:
				return false;
				break;
			default:
				break;
		}
	}
	return true;
}
void draw(void) {
	SDL_BlitSurface(renderer->get_image(),NULL,screen,NULL);
	SDL_Flip(screen);
}
void quit(int status=EXIT_SUCCESS) {
	#ifdef CRT
	#ifdef WIN32
	int leaks = _CrtDumpMemoryLeaks();
	if (leaks) {
		throw glLibError("Memory leak detected!");
	}
	#endif
	#endif

	exit(status);
}
int main(int argc, char **argv) {
	#ifdef CRT
	#ifdef WIN32
	_CrtSetDbgFlag(0xFFFFFFFF);
	//_crtBreakAlloc = ;
	#endif
	#endif

	Scene* scene = new Scene("scene.txt");
	if (scene->valid) {
		SDL_Init(SDL_INIT_EVERYTHING);
		SDL_WM_SetCaption("CS 413 HW 2 (Sphere Ray Tracer) Ian Mallett 2011",NULL); 
		screen = SDL_SetVideoMode(scene->image->width,scene->image->height,32,SDL_DOUBLEBUF);
		SDL_Surface* image = SDL_CreateRGBSurface(SDL_SWSURFACE,scene->image->width,scene->image->height,24,0,0,0,0);

		glLibClock clock;

		renderer = new Renderer(scene,image);
		renderer->begin();

		while (true) {
			if (!has_measured_time&&renderer->finished) {
				printf("Rendered scene in ");
				renderer->print_time();
				printf(".\n");
				has_measured_time = true;
			}
			if (input()==false) break;
			draw();
			clock.tick(30.0);
		}

		delete renderer;

		SDL_FreeSurface(image);
		SDL_FreeSurface(screen);
		SDL_Quit();
	}
	else {
		printf("There was an error loading the scene:\n");
		printf("  \"%s\"\n",scene->error.c_str());
		printf("Press ENTER to exit.\n");
		getchar();
	}
	delete scene;

	quit();

	return 0;
}