#include "stdafx.h"
#include "BackBuffer.h"
#include "Utilities.h"

#include "resource.h"

#include <exception>



using namespace std;



CBackBuffer::CBackBuffer( HINSTANCE hInstance, HWND hWnd )
: m_hBackBufferDC( 0 )
, m_hBackBufferDIB( 0 )
, m_puiBackBufferBits( 0 )
{
	// get DC of window
	HDC hDC( ::GetDC( hWnd ) );
	if( 0 == hDC )
	{
		throw( texception( GetStringFromResource( hInstance, IDS_FAILEDTOINITIALIZEBACKBUFFER ) ) );
	}

	// create a compatible memory DC
	m_hBackBufferDC = ::CreateCompatibleDC( hDC );
	if( 0 == m_hBackBufferDC )
	{
		throw( texception( GetStringFromResource( hInstance, IDS_FAILEDTOINITIALIZEBACKBUFFER ) ) );
	}

	// create 32 bit RGB DIB section
	BITMAPINFO sBi;
	BITMAPINFOHEADER& sBiHeader( sBi.bmiHeader );
	sBiHeader.biSize          = sizeof( BITMAPINFOHEADER );
	sBiHeader.biWidth         = c_iWndWidth;
	sBiHeader.biHeight        = -c_iWndHeight;
	sBiHeader.biPlanes        = 1;
	sBiHeader.biBitCount      = 32;
	sBiHeader.biCompression   = BI_RGB;
	sBiHeader.biSizeImage     = 0;
	sBiHeader.biXPelsPerMeter = 0;
	sBiHeader.biYPelsPerMeter = 0;
	sBiHeader.biClrUsed       = 0;
	sBiHeader.biClrImportant  = 0;
	//( (unsigned long*) sBi.bmiColors )[ 0 ] = 0x00FF0000;
	//( (unsigned long*) sBi.bmiColors )[ 1 ] = 0x0000FF00;
	//( (unsigned long*) sBi.bmiColors )[ 2 ] = 0x000000FF;

	m_hBackBufferDIB = ::CreateDIBSection( m_hBackBufferDC, &sBi, DIB_RGB_COLORS, (void**) &m_puiBackBufferBits, 0, 0 );
	if( 0 == m_hBackBufferDIB || 0 == m_puiBackBufferBits )
	{
		throw( texception( GetStringFromResource( hInstance, IDS_FAILEDTOINITIALIZEBACKBUFFER ) ) );
	}

	// select DIB into memory DC
	::SelectObject( m_hBackBufferDC, m_hBackBufferDIB );

	// release DC
	::ReleaseDC( hWnd, hDC );
}



CBackBuffer::~CBackBuffer()
{
	DeleteObject( m_hBackBufferDIB );
	DeleteDC( m_hBackBufferDC );
}