/* gltest - small OpenGL tearing test program
 * Copyright (C) 2012-2013 Ralf Jung <post@ralfj.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

// stdlib includes
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#include <assert.h>
#include <boost/program_options.hpp>
#include <X11/keysym.h>

namespace po = boost::program_options;

// my GL utility functions and the GL window class
#include "glutil.h"
#include "glwindow.h"
// include proper GL backend (windowing system)
#if defined(WIN_GLX)
#include "glxbackend.h"
static GLBackend *createGLBackend()
{
	return new GLXBackend();
}
#elif defined(WIN_EGL)
#include "eglbackend.h"
static GLBackend *createGLBackend()
{
	return new EGLBackend();
}
#else
#error "No GL window type selected"
#endif

// configuration
static const GLfloat boxWidth = 0.045f;
static const GLfloat boxSpeed = 1.25f; // per second

// profiler
enum ProfilerState { StatePreRender, StateClear, StateDraw, StatePresent, StatePostRender, StateOutsideRender, NumProfilerStates };
static const char *profilerStateNames[NumProfilerStates] = { "Pre-Render", "Clearing", "Drawing", "Presenting", "Post-Render", "Outside renderer"};

// utility functions
static double getTime()
{
	struct timespec tp;
	clock_gettime(CLOCK_MONOTONIC, &tp);
	return tp.tv_sec + 1e-9 * tp.tv_nsec;
}

// the window
class TearTestWindow : public GLWindow {
public:
	TearTestWindow() : GLWindow(XOpenDisplay(0), createGLBackend()),
		overdraw(false), sleep_time(0), boxPos(0), boxDirection(1)
	{}

	void setOverdraw(bool overdraw) { this->overdraw = overdraw; }
	void setSleepTime(int sleep_time) { this->sleep_time = sleep_time; }

	void setSwapInterval(int i) { getBackend()->setSwapInterval(i); }

private:
	bool overdraw;
	int sleep_time;
	// animation control
	double lastFrame;
	GLfloat boxPos, boxDirection;
	// FPS, profiler
	double lastDisplay, lastProfile;                 
	int framect;
	ProfilerState curState;
	double stateTime[NumProfilerStates];

protected:
	virtual void initGL()
	{
		// initialize GL proper
		glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
		glDisable(GL_DEPTH_TEST);
		// initialize clocks
		lastFrame = getTime();
		// initailize profiler
		framect = 0;
		memset(stateTime, 0, sizeof(stateTime));
		curState = NumProfilerStates;
		lastDisplay = lastProfile = getTime();
	}
	
	virtual void resizeGL(unsigned int width, unsigned int height)
	{
		glViewport(0, 0, width, height);
		initialise2dProjection();
		glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	}
	
	void profilerTick(ProfilerState nextState)
	{
		assert (nextState >= 0 && nextState < NumProfilerStates);
		double time = getTime();
		if (curState >= 0 && curState < NumProfilerStates)
			stateTime[curState] += time-lastProfile;
		curState = nextState;
		lastProfile = time;
		// display?
		const double elapsed = time-lastDisplay;
		if (elapsed >= 3) {
			printf("%.1f fps, time spent: ", framect/elapsed);
			for (int i = 0; i < NumProfilerStates; ++i) {
				if (i != 0) printf(", ");
				printf("%s %.1f%%", profilerStateNames[i], stateTime[i]/elapsed*100);
			}
			printf("\n");
			lastDisplay = time;
			framect = 0;
			memset(stateTime, 0, sizeof(stateTime));
		}
	}
	
	void renderGL()
	{              
		//////////////////////////////////////////////
		profilerTick(StatePreRender);
		double time = getTime();
		// anim
		double passedTime = time-lastFrame;
		boxPos += boxSpeed*passedTime*boxDirection;
		while (boxPos < 0 || boxPos+boxWidth > 1) { // wrapover
			if (boxPos < 0) {
				boxPos = -boxPos;
				boxDirection = -boxDirection;
			}
			else {
				boxPos = 1.0-boxWidth-(boxPos+boxWidth-1.0);
				boxDirection = -boxDirection;
			}
		}
		lastFrame = time;
		//////////////////////////////////////////////
		profilerTick(StateClear);
		if (overdraw) {
			// clear manually
			drawQuad(/*color*/0.0f, 0.0f, 0.0f, /*coordinates*/0, 0, 1, 1);
		}
		else {
			glClear(GL_COLOR_BUFFER_BIT);
		}
		//////////////////////////////////////////////
		profilerTick(StateDraw);
		drawQuad(/*color*/0.8f, 1.0f, 0.75f, /*coordinates*/boxPos, 0, boxPos+boxWidth, 1);
		usleep(sleep_time*1000);
		//////////////////////////////////////////////
		profilerTick(StatePresent);
		getBackend()->swapBuffers();
		//////////////////////////////////////////////
		profilerTick(StatePostRender);
		glFinish();
		++framect;
		//////////////////////////////////////////////
		profilerTick(StateOutsideRender);
	}
	
	virtual void handleKeyPress(KeySym key)
	{
		switch (key) {
			case XK_Escape: close(); break;
			case XK_F1: setFullscreen(!getFullscreen()); break;
			default: break;
		}
	}
};

int main(int argc, char ** argv)
{
	// program options handling
	po::options_description desc("Allowed options");
	desc.add_options()
		("help,h", "produce help message")
		("swap-interval,i", po::value<int>(), "set swap interval")
		("overdraw,o", "overdraw previous image (instead of calling glClear)")
		("sleep,s", po::value<int>()->default_value(0), "Number of milliseconds to sleep in each frame (in the drawing phase)")
	;
	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if (vm.count("help")) {
		std::cout << desc << "\n";
		return 1;
	}

	// actual program
	TearTestWindow w;
	w.setOverdraw(vm.count("overdraw"));
	w.setSleepTime(vm["sleep"].as<int>());
	w.open(800, 600);
	if (vm.count("swap-interval"))
		w.setSwapInterval(vm["swap-interval"].as<int>());
	w.exec();
}
