#include "stdafx.h"
#include "volumerenderwindow.h"

VolumeRenderWindow::VolumeRenderWindow(VolumeRenderer* renderer, QWindow* parent)
	: GLWindow(parent),
	m_renderer(renderer)
{
	Q_ASSERT(renderer);
	renderer->setParent(this);

	//connect update signals
	connect(renderer,SIGNAL(requestDraw()),SLOT(rendererWantsDraw()));
	connect(renderer,SIGNAL(requestUpdate()),SLOT(rendererUpdated()));

	this->setFormat(renderer->getDesiredFormat());
}

VolumeRenderWindow::~VolumeRenderWindow()
{

}

bool VolumeRenderWindow::initialize()
{
	//initialize the renderer
	bool ok = m_renderer->initialize();

	if(!ok)
	{
		emit initializeFailed(tr("Error during renderer initialization. Message: %1").arg(m_renderer->error()));
		return false;
	}
	else
	{
		m_renderer->setSize(width(),height());
		return true;
	}
}

void VolumeRenderWindow::render()
{
	m_renderer->drawCurrent();
}

void VolumeRenderWindow::resizeEvent(QResizeEvent* e)
{
	//we can only do this if the context is available
	if(m_context)
	{
		e->accept();
		//gl context needs to be set
		m_context->makeCurrent(this);
		m_renderer->setSize(width(),height());
	}
}

void VolumeRenderWindow::wheelEvent(QWheelEvent* e)
{
	e->accept();
	m_renderer->distanceDelta(  - e->angleDelta().y() / 240.0f);
}

void VolumeRenderWindow::mouseMoveEvent(QMouseEvent* e)
{
	if(e->buttons() & Qt::LeftButton)
	{
		e->accept();
		
		QPoint delta = e->pos() - m_lastMousePos;
		m_renderer->rotationDelta(delta.y() / 2.0f,delta.x() / 2.0f);
	}
	if(e->buttons() & Qt::RightButton)
	{
		e->accept();
		
		QPoint delta = e->pos() - m_lastMousePos;
		m_renderer->lightDelta(delta.x() / 2.0f, - delta.y() / 2.0f);
	}
	m_lastMousePos = e->pos();
}

void VolumeRenderWindow::mousePressEvent(QMouseEvent* e)
{
	m_lastMousePos = e->pos();
}

void VolumeRenderWindow::rendererUpdated()
{
	m_context->makeCurrent(this);
	m_renderer->update();
	m_context->doneCurrent();
}

void VolumeRenderWindow::rendererWantsDraw()
{
	//renderer state has changed, queue a draw
	renderLater();
}