/// Copyright (c) 2010 Ruben Penalva. All rights reserved.
/// Redistribution and use in source and binary forms, with or without modification, 
/// are permitted provided that the following conditions are met:
///    1. Redistributions of source code must retain the above copyright notice, this 
///    list of conditions and the following disclaimer.
///    2. Redistributions in binary form must reproduce the above copyright notice,
///    this list of conditions and the following disclaimer in the documentation and/or
///    other materials provided with the distribution.
///    3. The name of the author may not be used to endorse or promote products derived
///    from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
/// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
/// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, 
/// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED 
/// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
/// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
/// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 
/// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "OpenglPixelFormat.h"

#include "Win32Window.h"
#include <GL\glew.h>
#include <GL\wglew.h>
#include "Exception.h"
#include "OpenglException.h"

using namespace TestFrameWork;

const int OpenglPixelFormat::m_defaultColorDepth = 24;
const int OpenglPixelFormat::m_defaultDepth = 16;

OpenglPixelFormat::OpenglPixelFormat(int depth, int samples)	:		m_selectedDepth(depth),
																		m_selectedSamples(samples),
																		m_pixelFormat(0)
{
	m_pixelFormat = CreatePixelFormat(m_selectedDepth, m_selectedSamples);
}

OpenglPixelFormat::~OpenglPixelFormat(void)
{
}

int OpenglPixelFormat::GetPixelFormat(void) const
{
	return m_pixelFormat;
}

int OpenglPixelFormat::GetSelectedDepth(void) const
{
	return m_selectedDepth;
}

int OpenglPixelFormat::GetSamples(void) const
{
	return m_selectedSamples;
}

PIXELFORMATDESCRIPTOR& OpenglPixelFormat::GetDescriptor(void)
{
	return m_pixelFormatDesc;
}

/// http://www.opengl.org/wiki/Multisampling
int OpenglPixelFormat::CreatePixelFormat(int& depth, int& samples)
{
	m_pixelFormatDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR);
	m_pixelFormatDesc.nVersion = 1;
	m_pixelFormatDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
	m_pixelFormatDesc.iPixelType = PFD_TYPE_RGBA;
	m_pixelFormatDesc.cColorBits = (BYTE)m_defaultColorDepth;
	m_pixelFormatDesc.cRedBits = 0;
	m_pixelFormatDesc.cRedShift = 0;
	m_pixelFormatDesc.cGreenBits = 0;
	m_pixelFormatDesc.cGreenShift = 0;
	m_pixelFormatDesc.cBlueBits = 0;
	m_pixelFormatDesc.cBlueShift = 0;
	m_pixelFormatDesc.cAlphaBits = 0;
	m_pixelFormatDesc.cAlphaShift = 0;
	m_pixelFormatDesc.cAccumBits = 0;
	m_pixelFormatDesc.cAccumRedBits = 0;
	m_pixelFormatDesc.cAccumGreenBits = 0;
	m_pixelFormatDesc.cAccumBlueBits = 0;
	m_pixelFormatDesc.cAccumAlphaBits = 0;
	m_pixelFormatDesc.cDepthBits = (BYTE)depth;
	m_pixelFormatDesc.cStencilBits = 0;
	m_pixelFormatDesc.cAuxBuffers = 0;
	m_pixelFormatDesc.iLayerType = PFD_MAIN_PLANE;
	m_pixelFormatDesc.bReserved = 0;
	m_pixelFormatDesc.dwLayerMask = 0;
	m_pixelFormatDesc.dwVisibleMask = 0;
	m_pixelFormatDesc.dwDamageMask = 0;

	Win32Window dummyWindow;
	HDC deviceContext = dummyWindow.m_hdc;

	int pixelFormat = ChoosePixelFormat(deviceContext, &m_pixelFormatDesc);
	if (!pixelFormat)
	{
		m_pixelFormatDesc.cDepthBits = m_defaultDepth;
		pixelFormat = ChoosePixelFormat(deviceContext, &m_pixelFormatDesc);
		TestFrameWork::OnGLErrorThrowException();
		if (!pixelFormat)
		{    
			throw Exception();
		}

		depth = m_defaultDepth;
	}

	if (!SetPixelFormat(deviceContext, pixelFormat, &m_pixelFormatDesc))		
	{
		throw Exception();
	}

	HGLRC context = wglCreateContext(deviceContext);
	if (!context)
	{
		throw Exception();
	}

	if (!wglMakeCurrent(deviceContext, context))					
	{
		throw Exception();
	}

	PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB");
	if (!wglChoosePixelFormatARB && WGLMultisampleExtension())
	{
		return pixelFormat;
	}

	int iAttributes[] = 
	{ 
		WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, 
		WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
		WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
		WGL_COLOR_BITS_ARB, m_defaultColorDepth,
		WGL_ALPHA_BITS_ARB, 8,
		WGL_DEPTH_BITS_ARB, depth,
		WGL_STENCIL_BITS_ARB, 0,
		WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
		WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
		WGL_SAMPLES_ARB, samples,
		0,0
	};

	const int samplesIndex = 21;
	for (int i = samples; i > -1; --i)
	{
		iAttributes[samplesIndex] = i;

		int		extendedPixelFormat;
		UINT	numFormats;
		float	fAttributes[] = {0,0};
		int valid = wglChoosePixelFormatARB(deviceContext, iAttributes, fAttributes, 1, &extendedPixelFormat, &numFormats);

		if (valid && numFormats >= 1)
		{
			samples = i;
			pixelFormat = extendedPixelFormat;
			break;
		}
	}

	wglMakeCurrent(deviceContext, 0);
	wglDeleteContext(context);

	return pixelFormat;
}

bool OpenglPixelFormat::WGLMultisampleExtension(void)
{
	const char *extension = "WGL_ARB_multisample";
	const size_t extlen = strlen(extension);
	const char *supported = NULL;

	PROC wglGetExtString = wglGetProcAddress("wglGetExtensionsStringARB");

	if (wglGetExtString)
	{
		supported = ((char*(__stdcall*)(HDC))wglGetExtString)(wglGetCurrentDC());
	}

	if (!supported)
	{
		supported = (char*)glGetString(GL_EXTENSIONS);
		if (!supported)
		{
			return false;
		}
	}

	for (const char* p = supported; ; p++)
	{
		p = strstr(p, extension);

		if (!p)
		{
			return false;
		}

		if ((p==supported || p[-1]==' ') && (p[extlen]=='\0' || p[extlen]==' '))
		{
			return true;														
		}
	}
}
