/********************************************************************/
/* Copyright (c) 2019 System fugen G.K. and Yuzi Mizuno          */
/* All rights reserved.                                             */
/********************************************************************/
/**
 *  @file   GLDibOperation.cpp
 *  @brief  Implementation for class CGLDibOperation
 */
#include "stdafx.h"
#include "GLDibOperation.h"
#include "fugenView.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

CGLDibOperation::CGLDibOperation():	m_hDib(0),m_pBitmapBits(0){
}

CGLDibOperation::~CGLDibOperation(){
	Clear();
}

void CGLDibOperation::Clear() throw(){
	m_FBO.ReleaseBuffer();
	if(m_hDib){
		::DeleteObject(m_hDib);
		m_hDib = 0;
	}
}

///hDCSrcはPrinterのDC、szDIBは印刷対象のWindow size.
bool CGLDibOperation::Create(HDC hDCSrc, const CSize& szDIB){
	m_FBO.CreateBuffer(szDIB.cx, szDIB.cy, GL_BGR);

	memset(&m_bmi, 0, sizeof(BITMAPINFO));
	m_bmi.bmiHeader.biSize			= sizeof(BITMAPINFOHEADER);
	m_bmi.bmiHeader.biWidth			= szDIB.cx;
	m_bmi.bmiHeader.biHeight		= szDIB.cy;
	m_bmi.bmiHeader.biPlanes		= 1;
	m_bmi.bmiHeader.biBitCount		= 24;
	m_bmi.bmiHeader.biCompression	= BI_RGB;
	m_bmi.bmiHeader.biSizeImage		= szDIB.cx * szDIB.cy * 3;

	if(m_hDib)
		::DeleteObject(m_hDib);
	m_hDib = ::CreateDIBSection(hDCSrc,&m_bmi,DIB_RGB_COLORS,&m_pBitmapBits,0,0);
	if(!m_hDib){
		memset(&m_bmi, 0, sizeof(BITMAPINFO));
		return false;
	}
	return true;
}

void CGLDibOperation::endRender(){
	m_FBO.CopyRenderTexture(m_pBitmapBits);
	m_FBO.endRenderTexture();
}

bool CGLDibOperation::StretchDIBits(
	HDC          hDCDest,
	const CSize& offset,
	const CSize& target
){
	int nRet = ::StretchDIBits(
		hDCDest,
		offset.cx, offset.cy,
		target.cx, target.cy,
		0, 0,
		GetBmpWidth(), GetBmpHeight(),
		m_pBitmapBits,
		&m_bmi, DIB_RGB_COLORS, SRCCOPY);

	if(nRet == GDI_ERROR)
		return false;

	return true;
}
