본문 바로가기
Lib/DirectX

Triangle 그리기

by KingCat 2011. 11. 9.
#include "d3dUtility.h"

// 장치를 위한 전역 변수 생성
IDirect3DDevice9* Device=0;

// 화면의 해상도를 정의할 상수 전역 변수 인스턴스
const int Width = 640;
const int Height = 480;

// 버텍스 버퍼를 저장할 전역 변수 인스턴스 생성
IDirect3DVertexBuffer9* Triangle = 0;

// 커스텀 버텍스 포맷을 만들기 위한 구조체
struct Vertex
{
	Vertex(){}
	// 버텍스의 위치 정보만을 보관
	Vertex(float x, float y, float z)
	{
		_x=x; _y=y; _z=z;
	}

	float _x, _y, _z;

	static const DWORD FVF;
};
// 구조체의 유연한 버텍스 포맷 정의
const DWORD Vertex::FVF = D3DFVF_XYZ;

bool Setup()
{
	// 버텍스 버퍼를 생성
	Device->CreateVertexBuffer(
		3*sizeof(Vertex),
		D3DUSAGE_WRITEONLY,
		Vertex::FVF,
		D3DPOOL_MANAGED,
		&Triangle,
		0);

	// 트라이앵글 데이터로 버퍼를 채운다.
	Vertex* vertices;
	Triangle->Lock(0,0,(void**)&vertices,0);
	// 트라이앵글의 버텍스들
	vertices[0] = Vertex(-1.0f, 0.0f, 2.0f);
	vertices[1] = Vertex( 0.0f, 1.0f, 2.0f);
	vertices[2] = Vertex( 1.0f, 0.0f, 2.0f);

	Triangle->Unlock();

	// 투영 행렬을 지정
	D3DXMATRIX proj;
	D3DXMatrixPerspectiveFovLH(
		&proj,
		D3DX_PI * 0.5f,
		(float)Width / (float)Height,
		1.0f,
		1000.0f);
	Device->SetTransform(D3DTS_PROJECTION, &proj);
	// 렌더 상태를 지정한다.
	Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);

	return true;
}

void Cleanup()
{
	// 그 동안 할당했던 메모리(버텍스 버퍼)를 해제.
	d3d::Releasse<IDirect3DVertexBuffer9*>(Triangle);
}

bool Display(float timeDelta)
{
	if(Device)
	{
		// 장면을 그린다.
		Device->Clear(0,0,D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0);
		Device->BeginScene();

		Device->SetStreamSource(0, Triangle, 0, sizeof(Vertex));
		Device->SetFVF(Vertex::FVF);

		Device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);

		Device->EndScene();
		Device->Present(0,0,0,0);
	}
	return true;
}

LRESULT CALLBACK d3d::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch(msg)
	{
	case WM_DESTROY:
		::PostQuitMessage(0);
		break;
	case WM_KEYDOWN:
		if(wParam == VK_ESCAPE)
			::DestroyWindow(hwnd);
		break;
	}
	return ::DefWindowProcA(hwnd, msg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
	PSTR cmdLine, int showCmd)
{
	if(!d3d::InitD3D(hInstance, Width, Height, true, D3DDEVTYPE_HAL, &Device))
	{
		::MessageBox(0, "InitD3D() - FAILED", 0,0);
		return 0;
	}

	if(!Setup())
	{
		::MessageBox(0, "Setup() - FAILED", 0,0);
		return 0;
	}
	d3d::EnterMsgLoop(Display);
	Cleanup();
	Device->Release();
	return 0;
}

결과 :