/*  $Id: pixel_buffer_opengl_frame.cpp,v 1.8 2003/12/17 16:17:02 mbn Exp $
**
**  ClanLib Game SDK
**  Copyright (C) 2003  The ClanLib Team
**  For a total list of contributers see the file CREDITS.
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**
**  This library 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
**  Lesser General Public License for more details.
**
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*/

#include "Display/display_precomp.h"
#include "pixel_buffer_opengl_frame.h"
#include "Display/graphic_context_generic.h"
#include "API/GL/opengl_state.h"
#include "API/GL/opengl_wrap.h"

/////////////////////////////////////////////////////////////////////////////
// CL_PixelBuffer_OpenGL_Frame construction:

CL_PixelBuffer_OpenGL_Frame::CL_PixelBuffer_OpenGL_Frame(CLenum frame, CL_GraphicContext &gc)
: frame(frame), gc(gc), data(0)
{
	format.set_depth(32);
	format.set_red_mask  (0x000000ff);
	format.set_green_mask(0x0000ff00);
	format.set_blue_mask (0x00ff0000);
	format.set_alpha_mask(0xff000000);
	format.enable_colorkey(false);
}

CL_PixelBuffer_OpenGL_Frame::~CL_PixelBuffer_OpenGL_Frame()
{
	delete[] data;
}

/////////////////////////////////////////////////////////////////////////////
// CL_PixelBuffer_OpenGL_Frame operations:

void *CL_PixelBuffer_OpenGL_Frame::get_data()
{
	return data;
}

void CL_PixelBuffer_OpenGL_Frame::perform_lock()
{
	CLint old_frame;

	CL_OpenGLState state(&gc);
	state.set_active();
	state.setup_2d();

	CLdouble viewport[4];
	clGetDoublev(CL_VIEWPORT, viewport);

	CLdouble &viewport_width = viewport[2];
	CLdouble &viewport_height = viewport[3];

	CLint align;
	clGetIntegerv(CL_PACK_ALIGNMENT, &align);

	width  = static_cast<int>(viewport_width);
	height = static_cast<int>(viewport_height);
	pitch  = static_cast<int>((width*4+align-1)/align);
	pitch *= align;

	clGetIntegerv(CL_READ_BUFFER, &old_frame);
	clReadBuffer(frame);

	data = new char[height*pitch];
	clReadPixels(0, 0, width, height, CL_RGBA, CL_UNSIGNED_BYTE, data);

	clReadBuffer(old_frame);
}

void CL_PixelBuffer_OpenGL_Frame::perform_unlock()
{
	delete[] data;
	data = 0;
}

/////////////////////////////////////////////////////////////////////////////
// CL_PixelBuffer_OpenGL_Frame implementation:
