// cDisplay.cpp: implementation of the cDisplay class.
//
//////////////////////////////////////////////////////////////////////

#include "cDisplay.h"
//#include "TOOLMemory.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

cDisplay::cDisplay(){
	pDD = NULL;
	pDDClipper = NULL;

}

cDisplay::~cDisplay(){
	Destroy();
}

//////////////////////////////////////////////////////////////////////
// Creating
//////////////////////////////////////////////////////////////////////

bool cDisplay::Create(HWND _hWnd){
	if(pDD) return false;

	hWnd = _hWnd;
	if(DirectDrawCreate(NULL, &pDD, NULL) != DD_OK){
		MessageBox(NULL, "DirectX Initialization Failed.\nPlease reinstall DirectX3.0\n\nDirectDrawCreate() Failed", "DirectX Error!", MB_OK);
		return false;
	}
	CooperativeLevel = 0;
	// cPicture 에 cDisplay를 바인딩한다.

	cPicture::SetDisplay(this);

	return true;
}

void cDisplay::Destroy(){
	if(pDD){
		pDD->Release();
		pDD = NULL;
	}
}

bool cDisplay::SetCooperativeLevel(DWORD Mode){
	CooperativeLevel = Mode;
	if(pDD->SetCooperativeLevel(hWnd, Mode) != DD_OK)
		return false;
	return true;
}

bool cDisplay::SetDisplayMode(DWORD Width, DWORD Height, DWORD BPP){
	return pDD->SetDisplayMode(Width, Height, BPP) == DD_OK;
}

bool cDisplay::RestoreDisplayMode(){
	return pDD->RestoreDisplayMode() == DD_OK;
}


// 더블 버퍼의 생성 권한은 디스플레이만이 맏는다.
bool cDisplay::CreateDoubleBuffer(){
	if((CooperativeLevel & DDSCL_EXCLUSIVE)
		&& (CooperativeLevel & DDSCL_FULLSCREEN)){
		// 플립핑이 가능한 이중 표면을 만든다.
		if(!FrontPic.Create(1)) 
			return false;
		BackPic = FrontPic.GetBackPic();
	}else{
		// 플립핑이 불가능한 일반 표면을 만든다.
		if(!FrontPic.Create()) return false;
		if(!BackPic.Create(FrontPic)) return false;
	}
	CreateClipper();
	return true;

}

void cDisplay::DestroyDoubleBuffer(){
	DestroyClipper();
	BackPic.Destroy();
	FrontPic.Destroy();
}


bool cDisplay::CreateClipper(){
	// 클립퍼를 붙인다.
	if(pDD->CreateClipper(0, &pDDClipper, NULL) != DD_OK)
		return false;
	if(pDDClipper->SetHWnd(0, hWnd) != DD_OK)
		return false;
	if(FrontPic.GetDDS()->SetClipper(pDDClipper) != DD_OK)
		return false;
	if(BackPic.GetDDS()->SetClipper(pDDClipper) != DD_OK)
		return false;
	return true;

}

void cDisplay::DestroyClipper(){
	if(pDDClipper){
		pDDClipper->Release();
		pDDClipper = NULL;
	}
}