2. DirectX 초기화
프레임워크 업데이트
기존의 윈도우 프로그램 프레임워크에 Direct3D 기능을 가지는 클래스를 추가하여 확장할 것 입니다. 새롭게 변경된 프레임워크는 아래와 같습니다.

보기사시피 D3DClass는 GraphicsClass 안에 있습니다. 클래스 다이어그램이 아닌점을 감안하시고 보시기 바라며, 상속 관계가 아닙니다. 이전 튜토리얼에서는 모든 새로운 그래픽 관련 클래스가 GraphicsClass에 캡슐화 되어 새로운 D3DClass에 가장 적합한 위치라는 것을 언급했습니다. 이제 DxDefine.h에 대한 변경 사항을 살펴 보겠습니다.
DirectX SDK를 사용하기 위해서 DirectX에 필요한 헤더 및 라이브러리를 포함했습니다.
DxDefine.h 업데이트
#pragma once
/////////////
// LINKING //
/////////////
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3dcompiler.lib")
//////////////
// INCLUDES //
//////////////
#include <d3d11.h>>
#include <d3dcompiler.h>
#include <DirectXMath.h>
using namespace DirectX;
//////////////////////////
// warning C4316 처리용 //
//////////////////////////
#include "AlignedAllocationPolicy.h"
여기서 먼저 AlignedAllocationPolicy.h 파일을 살펴보도록 하겠습니다.
(AlignedAllocationPolicy 문제 해결 방법)
위에 이슈로 인해 메모리 할당 및 해제 매크로를 추가 했습니다.
stdafx.h
// 매크로 함수 입니다.
#define SAFE_ALIGNED_NEW _aligned_malloc
#define SAFE_ALIGNED_DELETE(p) { if(p) { _aligned_free(p); p = nullptr; }}
#define SAFE_ALIGNED_DELETE_ARRAY(p) { if (p) { _aligned_free[] (p); p = nullptr; }}
#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); p = nullptr; }}
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p) = 0; }}
AlignedAllocationPolicy.h
#pragma once
// warning C4316 처리용
template<size_t T>
class AlignedAllocationPolicy
{
public:
static void* operator new(size_t size)
{
return _aligned_malloc(size,t);
}
static void operator delete(void* memory)
{
_aligned_free(memory);
}
};
다음은 GraphicsClass.h 파일의 변경 사항을 보도록 하겠습니다. D3DClass 사용을 위해서 cpp에 헤더를 추가한 다음 전방선언을 하였습니다. 또한 D3DClass 멤버변수를 해당 클래스 내에서 사용할 수 있도록 선언하였습니다. D3DClass는 DirectX에 필요한 기본적인 기능들을 모두 담당하게 될 것입니다.
GraphicsClass
GraphicsClass.h
#pragma once
/////////////
// GLOBALS //
/////////////
const bool FULL_SCREEN = false;
const bool VSYNC_ENABLED = true;
const float SCREEN_DEPTH = 1000.0f;
const float SCREEN_NEAR = 0.1f;
class D3DClass;
class GraphicsClass
{
public:
GraphicsClass();
GraphicsClass(const GraphicsClass&);
~GraphicsClass();
bool Initialize(int, int, HWND);
void Shutdown();
bool Frame();
private:
bool Render();
private:
D3DClass* _direct3D = nullptr;
};
이전 튜토리얼을 기억하신다면 원래 이 GraphicsClass 클래스의 멤버함수는 아무 코드도 없이 비어있었습니다. 하지만! 지금은 D3DClass 멤버변수를 가지고 있기 때문에 GraphicsCalss에서 이 D3DClass 객체를 초기화 하고 정리하는 코드를 넣을 것입니다. 또한 Render함수에 BeginScene과 EndScene을 호출하는 부분을 넣어 Direct3D를 사용하여 그리는 부분도 넣을 것입니다.
GraphicsClass.cpp
#include "stdafx.h"
#include "d3dclass.h"
#include "graphicsclass.h"
GraphicsClass::GraphicsClass()
{
}
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
GraphicsClass::~GraphicsClass()
{
}
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
// Direct3D 객체 생성
_direct3D = (D3DClass*) SAFE_ALIGNED_NEW(sizeof(D3DClass), 16);
if (!_direct3D)
{
return false;
}
// Direct3D 객체 초기화
if (!_direct3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR))
{
MessageBox(hwnd, L"Could not initialze Direct3D", L"Error", MB_OK);
return false;
}
return true;
}
void GraphicsClass::Shutdown()
{
// Direct3D 객체 반환
if (_direct3D)
{
_direct3D->Shutdown();
SAFE_ALIGNED_DELETE(_direct3D);
_direct3D = 0;
}
}
bool GraphicsClass::Frame()
{
// 그래픽 랜더링 처리
return Render();
}
bool GraphicsClass::Render()
{
// 씬을 그리기 위해 버퍼를 지웁니다.
_direct3D->BeginScene(0.5f, 0.5f, 0.5f, 1.0f);
// 버퍼의 내용을 화면에 출력합니다.
_direct3D->EndScene();
return true;
}
이제 새로운 클래스인 D3DClass의 헤더파일을 보도록 하겠습니다.
D3DClass
D3DClass.h
#pragma once
class D3DClass
{
public:
D3DClass();
D3DClass(const D3DClass&);
~D3DClass();
bool Initialize(int screenWidth, int screenHieght, bool vsync, HWND hwnd, bool fullScreen, float screenDepth, float screenNear);
void Shutdown();
void BeginScene(float red, float green, float blue, float alpha);
void EndScene();
ID3D11Device* GetDevice();
ID3D11DeviceContext* GetDeviceContext();
void GetProjectionMatrix(XMMATRIX& projectionMatrix);
void GetWorldMatrix(XMMATRIX& worldMatrix);
void GetOrthoMatrix(XMMATRIX& orthoMatrix);
void GetVideoCardInfo(char* cardName, int& memory);
private:
bool _vsyncEnabled = false;
int _videoCardMemory = 0;
char _videoCardDescription[128] = {0,};
IDXGISwapChain* _swapChain = nullptr;
ID3D11Device* _device = nullptr;
ID3D11DeviceContext* _deviceContext = nullptr;
ID3D11RenderTargetView* _renderTargetView = nullptr;
ID3D11Texture2D* _depthStencilBuffer = nullptr;
ID3D11DepthStencilState* _depthStencilState = nullptr;
ID3D11DepthStencilView* _depthStencilView = nullptr;
ID3D11RasterizerState* _rasterState = nullptr;
XMMATRIX _projectionMatrix;
XMMATRIX _worldMatrix;
XMMATRIX _orthoMatrix;
};
생각보다 별 내용이 없습니다. 초기화 및 릴리즈, Scene 그리지 함수 부분들, 그리고 디바이스에 대한 부분들 뿐입니다.
이미 Direct3D에 친숙한 분들은 아마 제가 뷰 행렬에 해당하는 변수를 넣지 않았음을 눈치채셨을 것입니다. 그 이유는 나중 튜토리얼에 나올 Camera 클래스에 들어가기 때문입니다.
D3DClass.cpp
#include "stdafx.h"
#include "D3DClass.h"
D3DClass::D3DClass()
{
}
D3DClass::D3DClass(const D3DClass&)
{
}
D3DClass::~D3DClass()
{
}
bool D3DClass::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullScreen, float screenDepth, float screenNear)
{
// 수직동기화 상태를 저장
_vsyncEnabled = vsync;
// DirectX 그래픽 인터페이스 펙토리 생성
IDXGIFactory* factory = nullptr;
if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory)))
{
return false;
}
// 팩토리 객체를 사용하여 첫번째 그래픽 카드 인터페이스 어뎁터를 생성
IDXGIAdapter* adapter = nullptr;
if (FAILED(factory->EnumAdapters(0, &adapter)))
{
return false;
}
// 출력(모니터)에 대한 첫번째 어뎁터를 지정
IDXGIOutput* adapterOutput = nullptr;
if (FAILED(adapter->EnumOutputs(0, &adapterOutput)))
{
return false;
}
// 출력(모니터)에 대한 DXGI_FORMAT_R8G8B8A8_UNORM 표시 형식에 맞는 모드 수를 가져옴
unsigned int numModes = 0;
if (FAILED(adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL)))
{
return false;
}
// 가능한 모든 모니터와 그래픽 카드 조합을 저장할 리스트를 생성
DXGI_MODE_DESC* displayModeList = new DXGI_MODE_DESC[numModes];
if (!displayModeList)
{
return false;
}
// 모든 디스플레이 모드에 대한 리스트를 채움
if (FAILED(adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList)))
{
return false;
}
// 이제 모든 디스플레이 모드에 대해 화면 너비/노퓨이에 맞는 디스플레이 모드를 찾음
// 적합한 것을 찾으면, 모니터의 새로고침 비율의 분모와 분자 값을 저장
unsigned int numerator = 0;
unsigned int denominator = 0;
for (unsigned int i = 0; i < numModes; i++)
{
if (displayModeList[i].Width == (unsigned int)screenWidth)
{
if (displayModeList[i].Height == (unsigned int)screenHeight)
{
numerator = displayModeList[i].RefreshRate.Numerator;
denominator = displayModeList[i].RefreshRate.Denominator;
}
}
}
// 비디오카드의 구조체를 얻음
DXGI_ADAPTER_DESC adapterDesc;
if (FAILED(adapter->GetDesc(&adapterDesc)))
{
return false;
}
// 비디오카드 메모리 용량 단위를 메가바이트 단위로 저장
_videoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);
// 비디오카드의 이름을 저장
size_t stringLength = 0;
if(wcstombs_s(&stringLength, _videoCardDescription, 128, adapterDesc.Description, 128) != 0)
{
return false;
}
// 디스플레이 모드 리스트를 해제
SAFE_DELETE_ARRAY(displayModeList);
displayModeList = 0;
// 출력 어뎁터를 해제
adapterOutput->Release();
adapterOutput = 0;
// 어댑터를 해제
adapter->Release();
adapter = 0;
// 팩토리 객체를 해제
factory->Release();
factory = 0;
// 스왑체인 구조체를 초기화
DXGI_SWAP_CHAIN_DESC swapChainDesc;
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
// 백버퍼를 한개만 사용하도록 저장
swapChainDesc.BufferCount = 1;
// 백버퍼의 넓이와 높이를 지정
swapChainDesc.BufferDesc.Width = screenWidth;
swapChainDesc.BufferDesc.Height = screenHeight;
// 32bit 서페이스 설정
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
// 백버퍼의 새로고침 비율을 설정
if (_vsyncEnabled)
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
}
else
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
}
// 백버퍼의 사용 용도 지정
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
// 랜더링에 사용될 윈도우 핸들을 지정
swapChainDesc.OutputWindow = hwnd;
// 멀티샘플링을 끔
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
// 창모드 or 풀스크린 모드 설정
if (fullScreen)
{
swapChainDesc.Windowed = false;
}
else
{
swapChainDesc.Windowed = true;
}
// 스캔 라인 순서 및 크기를 지정하지 않음으로 설정
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
// 출력된 다음 백버퍼를 비우도록 지정
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
// 추가 옵션 플래그를 사용하지 않음
swapChainDesc.Flags = 0;
// 피처레벨을 DirectX 11로 설정
D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
// 스왑 체인, Direct3D 장치 및 Direct3D 장치 컨텍스트를 만듦
if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1,
D3D11_SDK_VERSION, &swapChainDesc, &_swapChain, &_device, NULL, &_deviceContext)))
{
return false;
}
// 백버퍼 포인터를 얻어옴
ID3D11Texture2D* backBufferPtr = nullptr;
if (FAILED(_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr)))
{
return false;
}
// 백버퍼 포인터로 랜더 타겟 뷰를 생성
if (FAILED(_device->CreateRenderTargetView(backBufferPtr, NULL, &_renderTargetView)))
{
return false;
}
// 백버퍼 포인터를 해제
backBufferPtr->Release();
backBufferPtr = 0;
// 깊이 버퍼 구조체를 초기화
D3D11_TEXTURE2D_DESC depthBufferDesc;
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
// 깊이 버퍼 구조체 작성
depthBufferDesc.Width = screenWidth;
depthBufferDesc.Height = screenHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;
// 설정된 깊이버퍼 구조체를 사용하여 깊이 버퍼 텍스쳐를 생성
if (FAILED(_device->CreateTexture2D(&depthBufferDesc, NULL, &_depthStencilBuffer)))
{
return false;
}
// 스텐실 상태 구조체를 초기화
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
// 스텐실 상태 구조체를 작성
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
// 픽셀 정면의 스텐실 설정
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// 픽셀 뒷면의 스텐실 설정
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// 깊이 스텐실 상태를 생성
if (FAILED(_device->CreateDepthStencilState(&depthStencilDesc, &_depthStencilState)))
{
return false;
}
// 깊이 스텐실 상태를 설정
_deviceContext->OMSetDepthStencilState(_depthStencilState, 1);
// 깊이 스텐실 뷰의 구조체를 초기화
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
// 깊이 스텐실 뷰 구조체를 설정
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
// 깊이 스텐실 뷰를 생성
if (FAILED(_device->CreateDepthStencilView(_depthStencilBuffer, &depthStencilViewDesc, &_depthStencilView)))
{
return false;
}
// 랜더링 대상 뷰와 깊이 스텐실 버퍼를 출력, 출력 렌터더 파이프 라인에 바인딩
_deviceContext->OMSetRenderTargets(1, &_renderTargetView, _depthStencilView);
// 그려지는 폴리곤과 방법을 결정할 래스터 구조체를 설정
D3D11_RASTERIZER_DESC rasterDesc;
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_BACK;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = false;
rasterDesc.SlopeScaledDepthBias = 0.0f;
// 방금 작성한 구조체에서 래스터 라이저 상태를 만듦
if (FAILED(_device->CreateRasterizerState(&rasterDesc, &_rasterState)))
{
return false;
}
// 이제 래스터 라이저 상태를 설정
_deviceContext->RSSetState(_rasterState);
// 랜더링을 위해 뷰포트를 설정
D3D11_VIEWPORT viewport;
viewport.Width = (float)screenWidth;
viewport.Height = (float)screenHeight;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
// 뷰포트를 생성
_deviceContext->RSSetViewports(1, &viewport);
// 투영 행렬을 설정합니다
float fieldOfView = 3.141592654f / 4.0f;
float screenAspect = (float)screenWidth/(float)screenHeight;
// 3D 랜더링을 위한 투영 행렬을 만듦
_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);
// 월드 행렬을 항등 행렬로 초기화
_worldMatrix = XMMatrixIdentity();
// 2D 랜더링을 위한 직교 투영 행렬을 만듦
_orthoMatrix = XMMatrixOrthographicLH((float)screenWidth, (float)screenHeight, screenNear, screenDepth);
return true;
}
void D3DClass::Shutdown()
{
// 종료 전 윈도우 모드로 설정하지 않으면 스왑 체인을 해제 할 때 예외가 발생
if (_swapChain)
{
_swapChain->SetFullscreenState(false, NULL);
}
SAFE_RELEASE(_rasterState);
SAFE_RELEASE(_depthStencilView);
SAFE_RELEASE(_depthStencilState);
SAFE_RELEASE(_depthStencilBuffer);
SAFE_RELEASE(_renderTargetView);
SAFE_RELEASE(_deviceContext);
SAFE_RELEASE(_device);
SAFE_RELEASE(_swapChain);
}
void D3DClass::BeginScene(float red, float green, float blue, float alpha)
{
// 버퍼를 지울 새을 설정
float color[4] = {red, green, blue, alpha};
// 백버퍼를 지움
_deviceContext->ClearRenderTargetView(_renderTargetView, color);
// 깊이 버퍼를 지움
_deviceContext->ClearDepthStencilView(_depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
void D3DClass::EndScene()
{
// 렌더링이 완료되었으므로 화면에 백 버퍼를 표시
if (_vsyncEnabled)
{
// 화면 새로고침 비율을 고정
_swapChain->Present(1, 0);
}
else
{
// 가능한 빠르게 출력
_swapChain->Present(0,0);
}
}
ID3D11Device* D3DClass::GetDevice()
{
return _device;
}
ID3D11DeviceContext* D3DClass::GetDeviceContext()
{
return _deviceContext;
}
void D3DClass::GetProjectionMatrix(XMMATRIX& projectionMatrix)
{
projectionMatrix = _projectionMatrix;
}
void D3DClass::GetWorldMatrix(XMMATRIX& worldMatrix)
{
worldMatrix = _worldMatrix;
}
void D3DClass::GetOrthoMatrix(XMMATRIX& orthoMatrix)
{
orthoMatrix = _orthoMatrix;
}
void D3DClass::GetVideoCardInfo(char* cardName, int& memory)
{
strcpy_s(cardName, 128, _videoCardDescription);
memory = _videoCardMemory;
}
코드 내 주석을 한번 훑어보면 구동되는 방식을 이해하실 수 있습니다.
출력화면
