Visual Studio 2022에서 작성하였습니다.
 
해당글은 다음 블로그를 참조하였습니다.

http://www.rastertek.com/tutdx11.html

https://ppparkje.tistory.com/category/%EA%B0%95%EC%A2%8C%EB%B2%88%EC%97%AD/DirectX%2011?page=2 
https://copynull.tistory.com/category/DirectX%2011/Basic


Tutorial-10 에 이어서 작성하였음.

 

<DxDefine.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#pragma once
 
// 라이브러리 링크
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3dcompiler.lib")
#pragma comment(lib, "dinput8.lib")
 
 
 
// include
#include <d3d11.h>
#include <d3dcompiler.h>
#include <directxmath.h>
#include <dinput.h>
using namespace DirectX;
 
 
cs

 

<InputClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#pragma once
#ifndef _INPUTCLASS_H_
#define _INPUTCLASS_H_
 
class InputClass
{
public:
    InputClass();
    InputClass(const InputClass& other);
    ~InputClass();
 
    bool Initialize(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight);
    void Shutdown();
    bool Frame();
 
    bool IsEscapePressed();
    void GetMouseLocation(int& mouseX, int& mouseY);
 
private:
    bool ReadKeyboard();
    bool ReadMouse();
    void ProcessInput();
 
private:
    IDirectInput8* m_directInput = nullptr;
    IDirectInputDevice8* m_keyboard = nullptr;
    IDirectInputDevice8* m_mouse = nullptr;
 
    unsigned char m_keyboardState[256= { 0, };
    DIMOUSESTATE m_mouseState;
 
    int m_screenWidth = 0;
    int m_screenHeight = 0;
    int m_mouseX = 0;
    int m_mouseY = 0;
};
 
#endif // _INPUTCLASS_H_
cs

 

<InputClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#include "stdafx.h"
#include "inputclass.h"
 
InputClass::InputClass()
{
}
 
InputClass::InputClass(const InputClass& other)
{
}
 
InputClass::~InputClass()
{
}
 
bool InputClass::Initialize(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight)
{
    // 마우스 커서의 위치 지정에 사용될 화면 크기를 설정한다.
    m_screenWidth = screenWidth;
    m_screenHeight = screenHeight;
 
    // Direct Input 인터페이스를 초기화 합니다.
    HRESULT result = DirectInput8Create(hinstance, DIRECTINPUT_VERSION, IID_IDirectInput8, reinterpret_cast<void**>(&m_directInput), nullptr);
    if (FAILED(result))
    {
        return false;
    }
 
    // 키보드의 Direct Input 인터페이스를 생성한다.
    result = m_directInput->CreateDevice(GUID_SysKeyboard, &m_keyboard, nullptr);
    if (FAILED(result))
    {
        return false;
    }
 
    // 데이터 형식을 설정한다. 이 경우 키보드이므로 사전 정의된 데이터 형식을 사용 할 수 있다.
    result = m_keyboard->SetDataFormat(&c_dfDIKeyboard);
    if (FAILED(result))
    {
        return false;
    }
 
    // 다른 프로그램과 공유 할 수 있도록 키보드의 협력 수준을 설정한다.
    result = m_keyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE);
    if (FAILED(result))
    {
        return false;
    }
 
    // 키보드를 할당 받는다.
    result = m_keyboard->Acquire();
    if (FAILED(result))
    {
        return false;
    }
 
    // 마우스 Direct Input 인터페이스를 생성한다.
    result = m_directInput->CreateDevice(GUID_SysMouse, &m_mouse, nullptr);
    if (FAILED(result))
    {
        return false;
    }
 
    // 미리 정의된 마우스 데이터 형식을 사용하여 마우스의 데이터 형식을 설정한다.
    result = m_mouse->SetDataFormat(&c_dfDIMouse);
    if (FAILED(result))
    {
        return false;
    }
 
    // 다른 프로그램과 공유 할 수 있도록 마우스의 협력 수준을 설정한다.
    result = m_mouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
    if (FAILED(result))
    {
        return false;
    }
 
    // 마우스를 할당받는다.
    result = m_mouse->Acquire();
    if (FAILED(result))
    {
        return false;
    }
 
    return true;
}
 
void InputClass::Shutdown()
{
    // 마우스 반환
    if (m_mouse)
    {
        m_mouse->Unacquire();
        m_mouse->Release();
        m_mouse = nullptr;
    }
 
    // 키보드 반환
    if (m_keyboard)
    {
        m_keyboard->Unacquire();
        m_keyboard->Release();
        m_keyboard = nullptr;
    }
 
    // m_directInput 객체 반환
    if (m_directInput)
    {
        m_directInput->Release();
        m_directInput = nullptr;
    }
}
 
bool InputClass::Frame()
{
    // 키보드의 현재 상태를 읽는다.
    if (!ReadKeyboard())
    {
        return false;
    }
 
    // 마우스의 현재 상태를 읽는다.
    if (!ReadMouse())
    {
        return false;
    }
 
    // 키보드와 마우스의 변경상태를 처리한다.
    ProcessInput();
 
    return true;
}
 
bool InputClass::IsEscapePressed()
{
    // escape 키가 현재 눌려지고 있는지 bit값을 계산하여 확인한다.
    if (m_keyboardState[DIK_ESCAPE] & 0x80)
    {
        return true;
    }
    return false;
}
 
void InputClass::GetMouseLocation(int& mouseX, int& mouseY)
{
    mouseX = m_mouseX;
    mouseY = m_mouseY;
}
 
bool InputClass::ReadKeyboard()
{
    // 키보드 디바이스를 얻는다.
    HRESULT result = m_keyboard->GetDeviceState(sizeof(m_keyboardState), reinterpret_cast<LPVOID>(&m_keyboardState));
    if (FAILED(result))
    {
        // 키보드가 포커스를 잃었거나 획득되지 않은 경우 컨트롤을 다시 가져온다.
        if ((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED))
        {
            m_keyboard->Acquire();
        }
        else
        {
            return false;
        }
    }
    return true;
}
 
bool InputClass::ReadMouse()
{
    // 마우스 디바이스를 얻는다.
    HRESULT result = m_mouse->GetDeviceState(sizeof(DIMOUSESTATE), reinterpret_cast<LPVOID>(&m_mouseState));
    if (FAILED(result))
    {
        // 마우스가 포커스를 잃었거나 획득되지 않은 경우 컨트롤을 다시 가져온다.
        if ((result == DIERR_INPUTLOST) || (result == DIERR_NOTACQUIRED))
        {
            m_mouse->Acquire();
        }
        else
        {
            return false;
        }
    }
    return true;
}
 
void InputClass::ProcessInput()
{
    // 프레임 동안 마우스 위치의 변경을 기반으로 마우스 커서의 위치를 업데이트 한다.
    m_mouseX += m_mouseState.lX;
    m_mouseY += m_mouseState.lY;
 
    // 마우스 위치가 화면 너비 또는 높이를 초과하지 않는지 확인한다.
    if (m_mouseX < 0)
    {
        m_mouseX = 0;
    }
    if (m_mouseY < 0)
    {
        m_mouseY = 0;
    }
 
    if (m_mouseX > m_screenWidth)
    {
        m_mouseX = m_screenWidth;
    }
    if (m_mouseY > m_screenHeight)    
    {
        m_mouseY = m_screenHeight;
    }
 
    
}
 
cs

 

<TextClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#pragma once
#ifndef _TEXTCLASS_H_
#define _TEXTCLASS_H_
 
class FontClass;
class FontShaderClass;
 
 
class TextClass
{
private:
    struct SentenceType
    {
        ID3D11Buffer* vertexBuffer, * indexBuffer;
        int vertexCount, indexCount, maxLength;
        float red, green, blue;
    };
 
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
    };
 
public:
    TextClass();
    TextClass(const TextClass& other);
    ~TextClass();
 
    bool Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, HWND hwnd, int screenWidth, int screenHeight, XMMATRIX baseViewMatrix);
    void Shutdown();
    bool Render(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX orthoMatrix);
    bool SetMousePosition(int mouseX, int mouseY, ID3D11DeviceContext* deviceContext);
 
private:
    bool InitializeSentence(SentenceType** sentence, int maxLength, ID3D11Device* device);
    bool UpdateSentence(SentenceType* sentence, const char* text, int positionX, int positionY, float red, float green, float blue, ID3D11DeviceContext* deviceContext);
    void ReleaseSentence(SentenceType** sentence);
    bool RenderSentence(ID3D11DeviceContext* deviceContext, SentenceType* sentence, XMMATRIX worldMatrix, XMMATRIX orthoMatrix);
 
private:
    FontClass* m_Font = nullptr;
    FontShaderClass* m_FontShader = nullptr;
    int m_screenWidth = 0;
    int m_screenHeight = 0;
    XMMATRIX m_baseViewMatrix;
    SentenceType* m_sentence1 = nullptr;
    SentenceType* m_sentence2 = nullptr;
 
};
 
 
#endif // _TEXTCLASS_H_
 
cs

 

<TextClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
#include "stdafx.h"
#include "TextClass.h"
 
#include "FontClass.h"
#include "FontShaderClass.h"
 
TextClass::TextClass()
{
}
 
TextClass::TextClass(const TextClass& other)
{
}
 
TextClass::~TextClass()
{
}
 
bool TextClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, HWND hwnd, int screenWidth, int screenHeight, XMMATRIX baseViewMatrix)
{
 
    // 화면 너비 높이 값 저장.
    m_screenWidth = screenWidth;
    m_screenHeight = screenHeight;
 
    // baseViewMatrix 저장.
    m_baseViewMatrix = baseViewMatrix;
 
    // Font 객체 생성
    m_Font = new FontClass;
    if (!m_Font)
    {
        return false;
    }
 
    // Font 객체 초기화
    if (!(m_Font->Initialize(device, "./fontdata.txt", L"./Textures/font.dds")))
    {
        MessageBox(hwnd, L"Could not initialize the font object", L"Error", MB_OK);
        return false;
    }
 
    // 폰트 쉐이더 객체 생성
    m_FontShader = new FontShaderClass;
    if (!m_FontShader)
    {
        return false;
    }
 
    // 폰트쉐이더 객체 초기화
    if (!(m_FontShader->Initialize(device, hwnd)))
    {
        MessageBox(hwnd, L"Could not initialize the font shader object", L"Error", MB_OK);
        return false;
    }
 
    // 첫번째 문장 초기화
    if (!(InitializeSentence(&m_sentence1, 16, device)))
    {
        return false;
    }
 
    // 이젠 Sentence Vertex Buffer를 문장으로 업데이트 한다.
    if (!(UpdateSentence(m_sentence1, "Hello"1001001.0f, 1.0f, 1.0f, deviceContext)))
    {
        return false;
    }
 
    // 두번째 문장 초기화
    if (!(InitializeSentence(&m_sentence2, 16, device)))
    {
        return false;
    }
 
    // 이젠 Sentence Vertex Buffer를 문장으로 업데이트 한다.
    if (!(UpdateSentence(m_sentence2, "Goodbye"1002001.0f, 1.0f, 0.0f, deviceContext)))
    {
        return false;
    }
 
    return true;
}
 
void TextClass::Shutdown()
{
    // 문장 객체 해제
    ReleaseSentence(&m_sentence1);
    ReleaseSentence(&m_sentence2);
 
    // 폰트쉐이더 객체 해제
    if (m_FontShader)
    {
        m_FontShader->Shutdown();
        delete m_FontShader;
        m_FontShader = nullptr;
    }
 
    // 폰트 객체 해제
    if (m_Font)
    {
        m_Font->Shutdown();
        delete m_Font;
        m_Font = nullptr;
    }
 
}
 
bool TextClass::Render(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX orthoMatrix)
{
    bool result;
 
    // 첫번째 문자 그리기
    result = RenderSentence(deviceContext, m_sentence1, worldMatrix, orthoMatrix);
    if (!result)
    {
        return false;
    }
 
    // 두번째 문자 그리기
    result = RenderSentence(deviceContext, m_sentence2, worldMatrix, orthoMatrix);
    if (!result)
    {
        return false;
    }
 
    return true;
}
 
bool TextClass::SetMousePosition(int mouseX, int mouseY, ID3D11DeviceContext* deviceContext)
{
    char tempString[16];
    char mouseString[16];
    bool result;
 
    // 마우스X 위치 정수를 문자열로 변경.
    _itoa_s(mouseX, tempString, 10);
 
    // 마우스X 문자열 만들기
    strcpy_s(mouseString, "Mouse X: ");
    strcpy_s(mouseString, tempString);
 
    // Sentence 를 새로운 문자열로 업데이트한다.
    result = UpdateSentence(m_sentence1, mouseString, 20201.0f, 1.0f, 1.0f, deviceContext);
    if (!result)
    {
        return false;
    }
 
    // 마우스Y 위치 정수를 문자열로 변경.
    _itoa_s(mouseY, tempString, 10);
 
    // 마우스Y 문자열 만들기
    strcpy_s(mouseString, "Mouse Y: ");
    strcpy_s(mouseString, tempString);
 
    // Sentence2 를 새로운 문자열로 업데이트한다.
    result = UpdateSentence(m_sentence2, mouseString, 20401.0f, 1.0f, 1.0f, deviceContext);
    if (!result)
    {
        return false;
    }
 
    return true;
}
 
bool TextClass::InitializeSentence(SentenceType** sentence, int maxLength, ID3D11Device* device)
{
    // SentenceType 객체 생성
    *sentence = new SentenceType;
    if (!*sentence)
    {
        return false;
    }
 
    // 센텐스 버퍼를 null로 초기화
    (*sentence)->vertexBuffer = nullptr;
    (*sentence)->indexBuffer = nullptr;
 
    // 최대 길이 초기화
    (*sentence)->maxLength = maxLength;
 
    // 정점수 초기화
    (*sentence)->vertexCount = 6 * maxLength; // 한글자에 6정점 필요(삼각형 2개)
 
    // 인덱스의 수 초기화
    (*sentence)->indexCount = (*sentence)->vertexCount;
 
    // 버텍스 배열 생성
    VertexType* vertices = new VertexType[(*sentence)->vertexCount];
    if (!vertices)
    {
        return false;
    }
 
    // 인덱스 배열 생성
    unsigned long* indices = new unsigned long[(*sentence)->indexCount];
    if (!indices)
    {
        return false;
    }
 
    // 버텍스 어레이 0으로 초기화
    memset(vertices, 0, (sizeof(VertexType) * (*sentence)->vertexCount));
 
    // 인덱스 어레이 초기화
    for (int i = 0; i < (*sentence)->indexCount; i++)
    {
        indices[i] = i;
    }
 
    // 동적 정점 버퍼 디스크립션 설정
    D3D11_BUFFER_DESC vertexBufferDesc;
    vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    vertexBufferDesc.ByteWidth = sizeof(VertexType) * (*sentence)->vertexCount;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    vertexBufferDesc.MiscFlags = 0;
    vertexBufferDesc.StructureByteStride = 0;
 
    // Subresource 구조체에 버텍스 데이터 포인터를 할당.
    D3D11_SUBRESOURCE_DATA vertexData;
    vertexData.pSysMem = vertices;
    vertexData.SysMemPitch = 0;
    vertexData.SysMemSlicePitch = 0;
 
    // 버텍스 버퍼 생성
    auto result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &(*sentence)->vertexBuffer);
    if (FAILED(result))
    {
        return false;
    }
 
    // 정적 인덱스 버퍼의 디스크립션 작성
    D3D11_BUFFER_DESC indexBufferDesc;
    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(unsigned long* (*sentence)->indexCount;
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;
    indexBufferDesc.MiscFlags = 0;
    indexBufferDesc.StructureByteStride = 0;
 
    // Subresource 구조체에 인덱스 데이타 포인터 할당
    D3D11_SUBRESOURCE_DATA indexData;
    indexData.pSysMem = indices;
    indexData.SysMemPitch = 0;
    indexData.SysMemSlicePitch = 0;
 
    // 인덱스 버퍼 생성
    result = device->CreateBuffer(&indexBufferDesc, &indexData, &(*sentence)->indexBuffer);
    if (FAILED(result))
    {
        return false;
    }
 
    // 더이상 사용하지 않는 버텍스, 인덱스 배열 할당 해제
    delete[] vertices;
    vertices = nullptr;
    delete[] indices;
    indices = nullptr;
 
    return true;
}
 
bool TextClass::UpdateSentence(SentenceType* sentence, const char* text, int positionX, int positionY, float red, float green, float blue , ID3D11DeviceContext* deviceContext)
{
    // 문장의 색상 저장
    sentence->red = red;
    sentence->green = green;
    sentence->blue = blue;
 
    // 문장의 길이 가져오기
    auto numLetters = static_cast<int>(strlen(text));
 
    // 버퍼의 오버플로우 확인
    if (numLetters > sentence->maxLength)
    {
        return false;
    }
 
    // 버텍스 어레이 생성
    auto vertices = new VertexType[sentence->vertexCount];
    if (!vertices)
    {
        return false;
    }
 
    // 버텍스 어레이 0으로 초기화
    memset(vertices, 0sizeof(VertexType) * sentence->vertexCount);
 
    // X와 Y의 픽셀위치를 계산한다.
    auto drawX = static_cast<float>(((m_screenWidth / 2* -1+ positionX);
    auto drawY = static_cast<float>((m_screenHeight / 2- positionY);
 
    // 문장 텍스트와 문자 그리는 위치를 사용하여 버텍스 어레이를 빌드하기위해 폰트 클래스를 사용한다.
    m_Font->BuildVertexArray(reinterpret_cast<void*>(vertices), text, drawX, drawY);
 
    // 버텍스 버퍼를 쓰기 위해 잠근다.
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    HRESULT result = deviceContext->Map(sentence->vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource);
    if (FAILED(result))
    {
        return false;
    }
 
    // 버텍스 버퍼의 데이터를 가르키는 포인터를 가져온다.
    auto verticesPtr = reinterpret_cast<VertexType*>(mappedResource.pData);
 
    // 데이타를 버텍스 버퍼로 복사한다.
    memcpy(verticesPtr, reinterpret_cast<void*>(vertices), sizeof(VertexType) * sentence->vertexCount);
 
    // 버텍스 버퍼의 잠금해제 한다.
    deviceContext->Unmap(sentence->vertexBuffer, 0);
 
    // 더이상 사용하지 않는 버텍스 어레이 할당해제
    delete[] vertices;
    vertices = nullptr;
 
    return true;
}
 
void TextClass::ReleaseSentence(SentenceType** sentence)
{
    if (*sentence)
    {
        // 문장 버텍스 버퍼 해제
        if ((*sentence)->vertexBuffer)
        {
            (*sentence)->vertexBuffer->Release();
            (*sentence)->vertexBuffer = nullptr;
        }
 
        // 문장 인덱스 버퍼 해제
        if (((*sentence)->indexBuffer))
        {
            (*sentence)->indexBuffer->Release();
            (*sentence)->indexBuffer = nullptr;
        }
 
        // sentence 해제
        delete* sentence;
        *sentence = nullptr;
    }
}
 
bool TextClass::RenderSentence(ID3D11DeviceContext* deviceContext, SentenceType* sentence, XMMATRIX worldMatrix, XMMATRIX orthoMatrix)
{
    // 버텍스 버퍼의 스트라이드와 오프셋을 설정
    unsigned int stride = sizeof(VertexType);
    unsigned int offset = 0;
 
    // 랜더될수 있도록 인풋 어셈블러에서 버텍스 버퍼가 활성화 되도록 설정한다.
    deviceContext->IASetVertexBuffers(01&sentence->vertexBuffer, &stride, &offset);
 
    // 인덱스 버퍼 활성화
    deviceContext->IASetIndexBuffer(sentence->indexBuffer, DXGI_FORMAT_R32_UINT, 0);
 
    // primitive 타입 설정, 여기서는 삼각형
    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
 
    // 픽셀 생상 벡터를 인풋된 문장 색상으로 만든다.
    auto pixelColor = XMFLOAT4(sentence->red, sentence->green, sentence->blue, 1.0f);
 
    // 폰트쉐이더를 이용하여 텍스트를 랜더한다.
    bool result = m_FontShader->Render(deviceContext, sentence->indexCount, worldMatrix, m_baseViewMatrix, orthoMatrix,
        m_Font->GetTexture(), pixelColor);
    if (!result)
    {
        return false;
    }
    return true;
}
 
cs

 

<GraphicsClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#pragma once
#ifndef _GRAPHICSCLASS_H_
#define _GRAPHICSCLASS_H_
 
// 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 CameraClass;
//class ModelClass;
//class ColorShaderClass;
class TextureShaderClass;
class BitmapClass;
class LightShaderClass;
class LightClass;
class TextClass;
 
class GraphicsClass
{
public:
    GraphicsClass();
    GraphicsClass(const GraphicsClass& other);
    ~GraphicsClass();
 
 
    bool Initialize(int screenWidth, int screenHeight, HWND hwnd);
    void Shutdown();
    bool Frame(int mouseX, int mouseY);
    bool Render();
    
 
private:
    D3DClass* m_D3D = nullptr;
    CameraClass* m_Camera = nullptr;
 
    //ModelClass* m_Model = nullptr;
    //TextureShaderClass* m_TextureShader = nullptr;
    //BitmapClass* m_Bitmap = nullptr;
    //ColorShaderClass* m_ColorShader = nullptr;
    //LightShaderClass* m_LightShader = nullptr;
    //LightClass* m_Light = nullptr;
    TextClass* m_Text = nullptr;
};
 
#endif // _GRAPHICSCLASS_H_
cs

 

<GraphicsClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#include "stdafx.h"
#include "graphicsclass.h"
 
#include "BitmapClass.h"
#include "D3dclass.h"
#include "CameraClass.h"
#include "ModelClass.h"
#include "LightShaderClass.h"
#include "LightClass.h"
#include "TextClass.h"
#include "TextureShaderClass.h"
 
GraphicsClass::GraphicsClass()
{
}
 
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
 
GraphicsClass::~GraphicsClass()
{
}
 
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
    // Direct3D 객체 생성
    m_D3D = new D3DClass;
    if (!m_D3D)
    {
        return false;
    }
 
    // Direct3D 객체를 초기화 한다.
    if (!m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR))
    {
        MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK);
        return false;
    }
 
 
    // m_Camera 객체 생성
    m_Camera = new CameraClass;
    if (!m_Camera)
    {
        return false;
    }
 
    // 카메라 포지션 설정
    XMMATRIX baseViewMatrix;
    m_Camera->SetPosition(0.0f, 0.0f, -5.0f);
    m_Camera->Render();
    m_Camera->GetViewMatrix(baseViewMatrix);
 
    // 텍스트 객체 생성
    m_Text = new TextClass;
    if (!m_Text)
    {
        return false;
    }
 
    // 텍스트 객체 초기화
    if (!m_Text->Initialize(m_D3D->GetDevice(), m_D3D->GetDeviceContext(), hwnd, screenWidth, screenHeight,baseViewMatrix))
    {
        MessageBox(hwnd, L"Could not initialize the Text object.", L"Error", MB_OK);
        return false;
    }
 
    //// m_Model 객체 생성
    //m_Model = new ModelClass;
    //if (!m_Model)
    //{
    //    return false;
    //}
 
    //// m_Model 초기화
    //if (!m_Model->Initialize(m_D3D->GetDevice(), "./cube.txt", L"./Textures/WoodCrate01.dds"))
    //{
    //    MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
    //}
 
    // 텍스쳐 쉐이더 객체 생성
    //m_TextureShader = new TextureShaderClass;
    //if (!m_TextureShader)
    //{
    //    return false;
    //}
 
    //// 텍스터 쉐이더 객테 초기화
    //if (!m_TextureShader->Initialize(m_D3D->GetDevice(), hwnd))
    //{
    //    MessageBox(hwnd, L"Could not initialize texture shader object.", L"Error", MB_OK);
    //    return false;
    //}
 
    //// LightShaderClass 객체 생성
    //m_LightShader = new LightShaderClass;
    //if (!m_LightShader)
    //{
    //    return false;
    //}
 
    //// LightShader 객체를 초기화한다.
    //if (!m_LightShader->Initialize(m_D3D->GetDevice(), hwnd))
    //{
    //    MessageBox(hwnd, L"Could not initialize the light shader object.", L"Error", MB_OK);
    //    return false;
    //}
 
    //// LightClass 객체 생성
    //m_Light = new LightClass;
    //if (!m_Light)
    //{
    //    return false;
    //}
 
    //// Light 객체 초기화
    //m_Light->SetAmbientColor(0.15f, 0.15f, 0.15f, 1.0f);
    //m_Light->SetDiffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
    //m_Light->SetDirection(1.0f, 0.0f, 1.0f);
    //m_Light->SetSpecularColor(1.0f, 1.0f, 1.0f, 1.0f);
    //m_Light->SetSpecularPower(32.0f);
 
    // 비트맵 객체 생성
    //m_Bitmap = new BitmapClass;
    //if (!m_Bitmap)
    //{
    //    return false;
    //}
 
    // 비트맵 객체 초기화
    //if (!m_Bitmap->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight, L"./Textures/WoodCrate01.dds",
    //    512, 512))
    //{
    //    MessageBox(hwnd, L"Could not initialize the bitmap object.", L"Error", MB_OK);
    //    return false;
    //}
 
    return true;
}
 
void GraphicsClass::Shutdown()
{
    // 텍스트 객체 해제
    if (m_Text)
    {
        m_Text->Shutdown();
        delete m_Text;
        m_Text = nullptr;
    }
    // 비트맵 객체 해제
    //if (m_Bitmap)
    //{
    //    m_Bitmap->Shutdown();
    //    delete m_Bitmap;
    //    m_Bitmap = nullptr;
    //}
    //// light 객체 해제
    //if (m_Light)
    //{
    //    delete m_Light;
    //    m_Light = nullptr;
    //}
 
    //// LightShader 객체 해제
    //if (m_LightShader)
    //{
    //    m_LightShader->Shutdown();
    //    delete m_LightShader;
    //    m_LightShader = nullptr;
    //}
 
    // m_TextureShader 객체 반환
    //if (m_TextureShader)
    //{
    //    m_TextureShader->Shutdown();
    //    delete m_TextureShader;
    //    m_TextureShader = nullptr;
    //}
 
    //// m_Model 객체 반환
    //if (m_Model)
    //{
    //    m_Model->Shutdown();
    //    delete m_Model;
    //    m_Model = nullptr;
    //}
 
    // m_Camera 객체 반환
    if (m_Camera)
    {
        delete m_Camera;
        m_Camera = nullptr;
    }
 
    // D3D 객체를 반환합니다.
    if (m_D3D)
    {
        m_D3D->Shutdown();
        delete m_D3D;
        m_D3D = nullptr;
    }
}
 
bool GraphicsClass::Frame(int mouseX, int mouseY)
{
    bool result;
 
    // 마우스 위치 세팅
    result = m_Text->SetMousePosition(mouseX, mouseY, m_D3D->GetDeviceContext());
    if (!result)
    {
        return false;
    }
 
 
    // 카메라 위치 세팅
    //m_Camera->SetPosition(0.0f, 0.0f, -10.0f);
    
    return true;
}
 
 
bool GraphicsClass::Render()
{
    // 씬 그리기를 시작하기 위해 버퍼의 내용을 지웁니다.
    m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성한다.
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져온다.
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix, orthoMatrix;
    m_D3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetProjectionMatrix(projectionMatrix);
    m_D3D->GetOrthoMatrix(orthoMatrix);
 
    // 2D 렌더링을 시작하기 위해 Z버퍼를 끈다.
    m_D3D->TurnZBufferOff();
 
    // 알파 블렌딩을 켠다.
    m_D3D->TurnOnAlphaBlending();
 
    // 비트맵 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 그리기를 준비한다.
    //if (!m_Bitmap->Render(m_D3D->GetDeviceContext(), 100, 100))
    //{
    //    return false;
    //}
 
    // 도형이 회전 할 수 있도록 회전 값으로 월드 행렬을 회전한다.
    // = XMMatrixRotationY(rotation);
 
    // 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 드로잉을 준비한다.
    //m_Model->Render(m_D3D->GetDeviceContext());
 
 
    // Light 쉐이더를 사용하여 모델을 렌더링 한다.
    //if (!m_LightShader->Render(m_D3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix,
    //    viewMatrix, projectionMatrix, m_Model->GetTexture(), m_Light->GetDirection(), m_Light->GetAmbientColor(), m_Light->GetDiffuseColor()
    //    , m_Camera->GetPosition(), m_Light->GetSpecularColor(), m_Light->GetSpecularPower()))
    //{
    //    return false;
    //}
 
    // 텍스트 문자열을 렌더한다.
    if (!m_Text->Render(m_D3D->GetDeviceContext(), worldMatrix, orthoMatrix))
    {
        return false;
    }
 
 
    // 텍스처 쉐이더를 사용하여 모델을 랜더링 한다.
    //if (!m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Bitmap->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix,
    //    m_Bitmap->GetTexture()))
    //{
    //    return false;
    //}
 
    // 모든2D 렌더링이 완료되었으므로 Z버퍼를 다시 켠다.
    m_D3D->TurnZBufferOn();
 
    // 버퍼에 그려진 씬을 화면에 표시합니다.
    m_D3D->EndScene();
 
    return true;
}
 
cs

 

<SystemClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#include "stdafx.h"
#include "systemclass.h"
 
 
SystemClass* SystemClass::ApplicationHandle = nullptr;
 
SystemClass::SystemClass()
{
 
}
 
SystemClass::SystemClass(const SystemClass&)
{
}
 
SystemClass::~SystemClass()
{
}
 
bool SystemClass::Initialize()
{
    int screenWidth, screenHeight;
    bool result;
 
    // 함수에 높이와 너비를 전달하기 전에 변수를 0으로 초기화한다.
    screenWidth = 0;
    screenHeight = 0;
 
    // 윈도우즈 api를 사용하여 초기화한다.
    InitializeWindows(screenWidth, screenHeight);
 
    // input 객체를 생성한다.
    // 이 객체는 유저로부터 들어오는 키보드 입력을 처리하기위해 사용된다.
    m_Input = new InputClass;
    if (!m_Input)
    {
        return false;
    }
 
    // Input 객체를 초기화한다.
    result = m_Input->Initialize(m_hinstance, m_hwnd, screenWidth, screenHeight);
    if (!result)
    {
        MessageBox(m_hwnd, L"Could not initialize the input object.", L"Error", MB_OK);
        return false;
    }
 
    // graphics 객체를 생성한다.
    // 이 객체는 이 어플리케이션의 모든 그래픽 요소를 그리는 일을 한다.
    m_Graphics = new GraphicsClass;
    if (!m_Graphics)
    {
        return false;
    }
 
    // graphics 객체를 초기화 한다.
    result = m_Graphics->Initialize(screenWidth, screenHeight, m_hwnd);
    if (!result)
    {
        return false;
    }
 
    return true;
}
 
void SystemClass::Shutdown()
{
 
    // Graphics 객체를 반환합니다.
    if (m_Graphics)
    {
        m_Graphics->Shutdown();
        delete m_Graphics;
        m_Graphics = nullptr;
    }
 
    // Input 객체를 반환합니다.
    if (m_Input)
    {
        m_Input->Shutdown();
        delete m_Input;
        m_Input = nullptr;
    }
 
    // 창을 종료시킵니다.
    ShutdownWindows();
    return;
}
 
void SystemClass::Run()
{
    MSG msg;
    bool done, result;
 
    // 메세지 구조체를 초기화합니다.
    ZeroMemory(&msg, sizeof(MSG));
 
    // 유저로부터 종료 메시지를 받을 때까지 루프를 돈다.
    done = false;
    while (!done)
    {
        // 윈도우 메시지를 처리합니다.
        if (PeekMessage(&msg, nullptr, 00, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
 
        // 윈도우에서 어플리케이션의 종료를 요청하는 경우 빠져나갑니다.
        if (msg.message == WM_QUIT)
        {
            done = true;
        }
        else
        {
            // 그 외에는 Frame 함수를 처리합니다.
            result = Frame();
            if (!result)
            {
                MessageBox(m_hwnd, L"Frame processing Failed", L"Error", MB_OK);
                done = true;
            }
        }
 
        // 유저가 Escape 키를 눌렀는지 확인한다.
        if (m_Input->IsEscapePressed())
        {
            done = true;
        }
    }
}
 
HWND& SystemClass::GetHWND()
{
    return m_hwnd;
}
 
LRESULT SystemClass::MessageHandler(HWND hwnd, UINT umsg, WPARAM wparam, LPARAM lparam)
{
    return DefWindowProc(hwnd, umsg, wparam, lparam);
}
 
bool SystemClass::Frame()
{
    bool result;
    int mouseX, mouseY;
 
    // 입력 프레임 절차
    result = m_Input->Frame();
    if (!result)
    {
        return false;
    }
 
    // 마우스 위치를 가져온다.
    m_Input->GetMouseLocation(mouseX, mouseY);
 
 
    // graphics 객체의 작업을 처리합니다. 마우스 위치값을 매개변수로
    result = m_Graphics->Frame(mouseX, mouseY);
    if (!result)
    {
        return false;
    }
 
    // 렌더한다.
    result = m_Graphics->Render();
    if (!result)
    {
        return false;
    }
 
    return true;
}
 
void SystemClass::InitializeWindows(int& screenWidth, int& screenHeight)
{
    WNDCLASSEX wc;
    DEVMODE dmScreenSettings;
    int posX, posY;
 
    // 외부 포인터를 이 객체로 설정
    ApplicationHandle = this;
    
    // 이 어플리케이션의 인스턴스 가져오기.
    m_hinstance = GetModuleHandle(nullptr);
 
    // 엎플리케이션의 이름 설정
    m_applicationName = L"Engine";
 
    // 윈도우 클래스를 기본 설정으로 설정.
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = m_hinstance;
    wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
    wc.hIconSm = wc.hIcon;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = m_applicationName;
    wc.cbSize = sizeof(WNDCLASSEX);
 
    // 윈도우 클래스 등록
    RegisterClassEx(&wc);
 
    // 모니터 화면의 해상도 가져오기
    screenWidth = GetSystemMetrics(SM_CXSCREEN);
    screenHeight = GetSystemMetrics(SM_CYSCREEN);
 
    if (FULL_SCREEN)
    {
        memset(&dmScreenSettings, 0sizeof(dmScreenSettings));
        dmScreenSettings.dmSize = sizeof(dmScreenSettings);
        dmScreenSettings.dmPelsWidth = static_cast<unsigned long>(screenWidth);
        dmScreenSettings.dmPelsHeight = static_cast<unsigned long>(screenHeight);
        dmScreenSettings.dmBitsPerPel = 32;
        dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
 
        // 풀스크린에 맞는 디스플레이 설정을 합니다.
        ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);
 
        // 윈도우의 위치를 화면의 왼쪽 위로 맞춥니다.
        posX = posY = 0;
 
    }
    else
    {
        // 윈도우 모드라면 800X600으로 크기 설정
        screenWidth = 800;
        screenHeight = 600;
 
        // 창을 모니터의 중앙에 오도록 설정
        posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2;
        posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2;
    }
 
    // 설정한 것을 가지고 창을 만들고 그 핸들을 가져옵니다.
    m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName,
        WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP,
        posX, posY, screenWidth, screenHeight, nullptr, nullptr, m_hinstance, nullptr);
 
    // 윈도우를 화면에 표시하고 포커스를 줍니다.
    ShowWindow(m_hwnd, SW_SHOW);
    SetForegroundWindow(m_hwnd);
    SetFocus(m_hwnd);
 
    // 마우스 커서 표시설정
    ShowCursor(true);
 
    return;
 
}
 
void SystemClass::ShutdownWindows()
{
    // 마우스 커서를 표시합니다.
    ShowCursor(true);
 
    // 풀스크린 모드를 빠져나올 때 디스플레이 설정을 바꿉니다.
    if (FULL_SCREEN)
    {
        ChangeDisplaySettings(nullptr, 0);
    }
 
    // 창을 제거합니다.
    DestroyWindow(m_hwnd);
    m_hwnd = nullptr;
 
    // 어플리케이션 인스턴스를 제거한다.
    UnregisterClass(m_applicationName, m_hinstance);
    m_hinstance = nullptr;
 
    // 이 클래스에 대한 외부포인터 참조를 제거
    ApplicationHandle = nullptr;
 
}
 
LRESULT WndProc(HWND hwnd, UINT umessage, WPARAM wparam, LPARAM lparam)
{
    switch (umessage)
    {
        // 윈도우가 제거되었는지 확인
        case WM_DESTROY:
        {
            PostQuitMessage(0);
            return 0;
        }
 
        // 윈도우가 닫히는지 확인한다.
        case WM_CLOSE:
        {
            PostQuitMessage(0);
        }
 
        // 다른 모든 메세지들은 system 클래스의 메세지 처리기에 전달합니다.
        default:
        {
            return SystemClass::ApplicationHandle->MessageHandler(hwnd, umessage, wparam, lparam);
        }
    }
}
 
cs

<결과>

<소스코드>

https://github.com/woonhak-kong/DirectX_11_Tutorial/releases/tag/Tutorial_11

 

Visual Studio 2022에서 작성하였습니다.
 
해당글은 다음 블로그를 참조하였습니다.

http://www.rastertek.com/tutdx11.html

https://ppparkje.tistory.com/category/%EA%B0%95%EC%A2%8C%EB%B2%88%EC%97%AD/DirectX%2011?page=2 
https://copynull.tistory.com/category/DirectX%2011/Basic


Tutorial-9 에 이어서 작성하였음.

 

 

<fontdata.txt>

32   0.0        0.0         0
33 ! 0.0        0.000976563 1
34 " 0.00195313 0.00488281  3
35 # 0.00585938 0.0136719   8
36 $ 0.0146484  0.0195313   5
37 % 0.0205078  0.0302734   10
38 & 0.03125    0.0390625   8
39 ' 0.0400391  0.0410156   1
40 ( 0.0419922  0.0449219   3
41 ) 0.0458984  0.0488281   3
42 * 0.0498047  0.0546875   5
43 + 0.0556641  0.0625      7
44 , 0.0634766  0.0644531   1
45 - 0.0654297  0.0683594   3
46 . 0.0693359  0.0703125   1
47 / 0.0712891  0.0751953   4
48 0 0.0761719  0.0820313   6
49 1 0.0830078  0.0859375   3
50 2 0.0869141  0.0927734   6
51 3 0.09375    0.0996094   6
52 4 0.100586   0.106445    6
53 5 0.107422   0.113281    6
54 6 0.114258   0.120117    6
55 7 0.121094   0.126953    6
56 8 0.12793    0.133789    6
57 9 0.134766   0.140625    6
58 : 0.141602   0.142578    1
59 ; 0.143555   0.144531    1
60 < 0.145508   0.151367    6
61 = 0.152344   0.15918     7
62 > 0.160156   0.166016    6
63 ? 0.166992   0.171875    5
64 @ 0.172852   0.18457     12
65 A 0.185547   0.194336    9
66 B 0.195313   0.202148    7
67 C 0.203125   0.209961    7
68 D 0.210938   0.217773    7
69 E 0.21875    0.225586    7
70 F 0.226563   0.232422    6
71 G 0.233398   0.241211    8
72 H 0.242188   0.249023    7
73 I 0.25       0.250977    1
74 J 0.251953   0.256836    5
75 K 0.257813   0.265625    8
76 L 0.266602   0.272461    6
77 M 0.273438   0.282227    9
78 N 0.283203   0.290039    7
79 O 0.291016   0.298828    8
80 P 0.299805   0.306641    7
81 Q 0.307617   0.31543     8
82 R 0.316406   0.323242    7
83 S 0.324219   0.331055    7
84 T 0.332031   0.338867    7
85 U 0.339844   0.34668     7
86 V 0.347656   0.356445    9
87 W 0.357422   0.370117    13
88 X 0.371094   0.37793     7
89 Y 0.378906   0.385742    7
90 Z 0.386719   0.393555    7
91 [ 0.394531   0.396484    2
92 \ 0.397461   0.401367    4
93 ] 0.402344   0.404297    2
94 ^ 0.405273   0.410156    5
95 _ 0.411133   0.417969    7
96 ` 0.418945   0.420898    2
97 a 0.421875   0.426758    5
98 b 0.427734   0.432617    5
99 c 0.433594   0.438477    5
100 d 0.439453  0.444336    5
101 e 0.445313  0.450195    5
102 f 0.451172  0.455078    4
103 g 0.456055  0.460938    5
104 h 0.461914  0.466797    5
105 i 0.467773  0.46875     1
106 j 0.469727  0.472656    3
107 k 0.473633  0.478516    5
108 l 0.479492  0.480469    1
109 m 0.481445  0.490234    9
110 n 0.491211  0.496094    5
111 o 0.49707   0.501953    5
112 p 0.50293   0.507813    5
113 q 0.508789  0.513672    5
114 r 0.514648  0.517578    3
115 s 0.518555  0.523438    5
116 t 0.524414  0.527344    3
117 u 0.52832   0.533203    5
118 v 0.53418   0.539063    5
119 w 0.540039  0.548828    9
120 x 0.549805  0.554688    5
121 y 0.555664  0.560547    5
122 z 0.561523  0.566406    5
123 { 0.567383  0.570313    3
124 | 0.571289  0.572266    1
125 } 0.573242  0.576172    3
126 ~ 0.577148  0.583984    7

 

<FontClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#pragma once
#ifndef _FONTCLASS_H_
#define _FONTCLASS_H_
 
class TextureClass;
 
class FontClass
{
private:
    struct FontType
    {
        float left, right;
        int size;
    };
 
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
    };
 
public:
    FontClass();
    FontClass(const FontClass& other);
    ~FontClass();
 
    bool Initialize(ID3D11Device* device, const char* fontFilename, const WCHAR* textureFilename);
    void Shutdown();
 
    ID3D11ShaderResourceView* GetTexture();
 
    void BuildVertexArray(void* vertices, const char* sentence, float drawX, float drawY);
 
private:
    bool LoadFontData(const char* filename);
    void ReleaseFontData();
    bool LoadTexture(ID3D11Device* device, const WCHAR* filename);
    void ReleaseTexture();
 
private:
    FontType* m_Font = nullptr;
    TextureClass* m_Texture = nullptr;
 
};
 
 
 
#endif // _FONTCLASS_H_
 
 
cs

 

<FontClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#include "stdafx.h"
#include "FontClass.h"
 
#include <fstream>
 
#include "TextureClass.h"
 
FontClass::FontClass()
{
}
 
FontClass::FontClass(const FontClass& other)
{
}
 
FontClass::~FontClass()
{
}
 
bool FontClass::Initialize(ID3D11Device* device, const char* fontFilename, const WCHAR* textureFilename)
{
    // 폰트 데이터 로드
    if (!LoadFontData(fontFilename))
    {
        return false;
    }
 
    // 폰트 문자들을 가지고 있는 텍스쳐 로드
    return LoadTexture(device, textureFilename);
}
 
void FontClass::Shutdown()
{
    // 폰트 텍스쳐 해제
    ReleaseTexture();
 
    // 폰트 데이타 해제
    ReleaseFontData();
}
 
ID3D11ShaderResourceView* FontClass::GetTexture()
{
    return m_Texture->GetTexture();
}
 
void FontClass::BuildVertexArray(void* vertices, const char* sentence, float drawX, float drawY)
{
    VertexType* vertexPtr;
 
    // vertices 를 VertexType 구조체로 강제 변경
    vertexPtr = reinterpret_cast<VertexType*>(vertices);
 
    // 문장의 문자수를 가져온다.
    int numLetters = static_cast<int>(strlen(sentence));
 
    // vertex 배열의 인덱스 초기화
    int index = 0;
 
    // 각 문자를 quad로 그린다.
    for (int i = 0; i < numLetters; i++)
    {
        // 문자의 번호
        int letter = static_cast<int>(sentence[i]) - 32;
 
        // 만약 문자가 단지 공간(스페이스)라면 단지 3픽세 이동시킨다.
        if (letter == 0)
        {
            drawX = drawX + 3.0f;
        }
        else
        {
            // 쿼드위의 첫번째 삼각형
            vertexPtr[index].position = XMFLOAT3(drawX, drawY, 0.0f); // Top left
            vertexPtr[index].texture = XMFLOAT2(m_Font[letter].left, 0.0f); // UV
            index++;
 
            vertexPtr[index].position = XMFLOAT3((drawX + m_Font[letter].size), (drawY - 16), 0.0f); // Bottom right
            vertexPtr[index].texture = XMFLOAT2(m_Font[letter].right, 1.0f); // UV
            index++;
 
            vertexPtr[index].position = XMFLOAT3(drawX, drawY - 160.0f); // Bottom left
            vertexPtr[index].texture = XMFLOAT2(m_Font[letter].left, 1.0f); // UV
            index++;
 
            // 쿼드위의 두버째 삼각형
            vertexPtr[index].position = XMFLOAT3(drawX, drawY, 0.0f); // Top left
            vertexPtr[index].texture = XMFLOAT2(m_Font[letter].left, 0.0f); // UV
            index++;
 
            vertexPtr[index].position = XMFLOAT3((drawX + m_Font[letter].size), drawY, 0.0f); // Top right
            vertexPtr[index].texture = XMFLOAT2(m_Font[letter].right, 0.0f); // UV
            index++;
 
            vertexPtr[index].position = XMFLOAT3(drawX + m_Font[letter].size, drawY - 160.0f); // Bottom right
            vertexPtr[index].texture = XMFLOAT2(m_Font[letter].right, 1.0f); // UV
            index++;
 
            // 다음 글자의 x 위치를 위하여 그 글자의 사이즈보다 1 픽셀 더 이동시킨다.
            drawX = drawX + m_Font[letter].size + 1.0f;
        }
    }
 
}
 
bool FontClass::LoadFontData(const char* filename)
{
    std::ifstream fin;
    int i;
    char temp;
 
    // 폰트버퍼 할당
    m_Font = new FontType[95];
    if (!m_Font)
    {
        return false;
    }
 
 
    // 폰트데이타 오픈
    fin.open(filename);
    if (fin.fail())
    {
        return false;
    }
 
    // 텍스트를 위한 95개의 문자 정보를 저장한다.
    for (i = 0; i < 95; i++)
    {
        fin.get(temp);
        while (temp != ' ')
        {
            fin.get(temp);
        }
        fin.get(temp);
        while (temp != ' ')
        {
            fin.get(temp);
        }
 
        fin >> m_Font[i].left;
        fin >> m_Font[i].right;
        fin >> m_Font[i].size;
    }
 
    // 파일을 닫는다.
    fin.close();
 
    return true;
}
 
void FontClass::ReleaseFontData()
{
    // 폰트 데이타 배열 해제
    if (m_Font)
    {
        delete[] m_Font;
        m_Font = nullptr;
    }
}
 
bool FontClass::LoadTexture(ID3D11Device* device, const WCHAR* filename)
{
    // 텍스쳐 객체 생성
    m_Texture = new TextureClass;
    if (!m_Texture)
    {
        return false;
    }
 
    // 텍스쳐 객체 초기화
    return m_Texture->Initialize(device, filename);
}
 
void FontClass::ReleaseTexture()
{
    // 텍스쳐 객체 해제
    if (m_Texture)
    {
        m_Texture->Shutdown();
        delete m_Texture;
        m_Texture = nullptr;
    }
}
 
cs

 

<Font.vs>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Globals
 
cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};
 
 
// Typedefs
 
struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
};
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};
 
 
// Vertex Shader
 
PixelInputType FontVertexShader(VertexInputType input)
{
    PixelInputType output;
 
    // 올바르게 행렬 연산을 하기 위하여 position 벡터를 w까지 있는 4성분이 있는 것으로 사용한다.
    input.position.w = 1.0f;
 
    // 정점의 위치를 월드, 뷰, 사영의 순으로 계산.
    output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);
 
    // 픽셀 쉐이더의 텍스처 좌표를 저장한다.
    output.tex = input.tex;
 
    return output;
}
cs

 

<Font.ps>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// GLOBALS
Texture2D shaderTexture;
SamplerState SampleType;
 
cbuffer PixelBuffer
{
    float4 pixelColor;
};
 
// Typedefs
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};
 
// Pixel Shader
 
float4 FontPixelShader(PixelInputType input) : SV_TARGET
{
    float4 color;
 
    // 이 텍스쳐 좌표 위치에서 샘플러를 사용하여 텍스쳐에서 픽셀 색상을 샘플링 한다.
    color = shaderTexture.Sample(SampleType, input.tex);
 
    // 텍스처의 색상이 검은색이면 이 픽셀을 투명으로 처리한다.
    if (color.r == 0.0f)
    {
        color.a = 0.0f;
    }
    // 텍스처의 색상이 검은색이 아닐경우 글꼴의 픽셀이므로 글꼴 픽셀 색상을 사용하여 그린다.
    else
    {
        color.rgb = pixelColor.rgb;
        color.a = 1.0f;
    }
 
    return color;
}
cs

 

<FontShaderClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#pragma once
#ifndef _FONTSHADERCLASS_H_
#define _FONTSHADERCLASS_H_
 
 
class FontShaderClass
{
 
private:
    struct ConstantBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
    struct PixelBufferType
    {
        XMFLOAT4 pixelColor;
    };
 
 
public:
    FontShaderClass();
    FontShaderClass(const FontShaderClass& other);
    ~FontShaderClass();
 
    bool Initialize(ID3D11Device* device, HWND hwnd);
    void Shutdown();
    bool Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, XMFLOAT4 pixelColor);
 
 
private:
    bool InitializeShader(ID3D11Device* device, HWND hwnd, const WCHAR* vsFilename, const WCHAR* psFilename);
    void ShutdownShader();
    void OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, const WCHAR* shaderFilename);
 
    bool SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, XMFLOAT4 pixelColor);
    void RenderShader(ID3D11DeviceContext* deviceContext, int indexCount);
 
private:
    ID3D11VertexShader* m_vertexShader = nullptr;
    ID3D11PixelShader* m_pixelShader = nullptr;
    ID3D11InputLayout* m_layout = nullptr;
    ID3D11Buffer* m_constantBuffer = nullptr;
 
    ID3D11SamplerState* m_sampleState = nullptr;
    ID3D11Buffer* m_pixelBuffer = nullptr;
 
 
};
 
 
 
 
#endif // _FONTSHADERCLASS_H_
 
cs

 

<FontShaderClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#include "stdafx.h"
#include "FontShaderClass.h"
 
FontShaderClass::FontShaderClass()
{
}
 
FontShaderClass::FontShaderClass(const FontShaderClass& other)
{
}
 
FontShaderClass::~FontShaderClass()
{
}
 
bool FontShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 및 픽셀 쉐이더 초기화
    return InitializeShader(device, hwnd, L"./Font.vs", L"./Font.ps");
}
 
void FontShaderClass::Shutdown()
{
    // 버텍스 및 픽셀 쉐이더와 관련되 객체 종료
    ShutdownShader();
}
 
bool FontShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix,
    XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, XMFLOAT4 pixelColor)
{
    // 렌더링에 사용할 쉐이더 매개 변수를 설정
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, pixelColor))
    {
        return false;
    }
 
    // 설정된 버퍼를 쉐이더로 랜더링 한다.
    RenderShader(deviceContext, indexCount);
    return true;
}
 
bool FontShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, const WCHAR* vsFilename,
    const WCHAR* psFilename)
{
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일 한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    if (FAILED(D3DCompileFromFile(vsFilename, nullptr, nullptr, "FontVertexShader""vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
        &vertexShaderBuffer, &errorMessage)))
    {
        // 쉐이더 컴파일 실패시 오류메시지 출력.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, vsFilename);
        }
        // 컴파일 오류가 아니라면 쉐이더 파일을 찾울 수 없는 경우이다.
        else
        {
            MessageBox(hwnd, vsFilename, L"Missing VertexShader Shader File", MB_OK);
        }
 
        return false;
    }
 
    // 픽셀 쉐이더 코드를 컴파일 한다.
    ID3D10Blob* pixelShaderBuffer = nullptr;
    if (FAILED(D3DCompileFromFile(psFilename, nullptr, nullptr, "FontPixelShader""ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
        &pixelShaderBuffer, &errorMessage)))
    {
        // 쉐이더 컴파일 실패시 오류메시지 출력.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
        }
        // 컴파일 오류가 아니라면 쉐이더 파일을 찾울 수 없는 경우이다.
        else
        {
            MessageBox(hwnd, psFilename, L"Missing PixelShader Shader File", MB_OK);
        }
 
        return false;
    }
 
    // 버퍼로부터 정점 쉐이더를 생성한다.
    if (FAILED(device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(),
        nullptr, &m_vertexShader)))
    {
        return false;
    }
 
    // 버퍼에서 픽셀 쉐이더를 생성한다.
    if (FAILED(device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(),
        nullptr, &m_pixelShader)))
    {
        return false;
    }
 
    // 정점 입력 레이아웃 구조체를 설정합니다.
    // 이 설정은 ModelClass와 쉐이더의 VertexType 구조와 일치해야 한다.
    D3D11_INPUT_ELEMENT_DESC polygonLayout[2];
    polygonLayout[0].SemanticName = "POSITION";
    polygonLayout[0].SemanticIndex = 0;
    polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
    polygonLayout[0].InputSlot = 0;
    polygonLayout[0].AlignedByteOffset = 0;
    polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[0].InstanceDataStepRate = 0;
 
    polygonLayout[1].SemanticName = "TEXCOORD";
    polygonLayout[1].SemanticIndex = 0;
    polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
    polygonLayout[1].InputSlot = 0;
    polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
    polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[1].InstanceDataStepRate = 0;
 
    // 레이아웃의 요소 수를 가져옵니다.
    unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
 
    // 정점 입력 레이아웃을 만듭니다.
    if (FAILED(device->CreateInputLayout(polygonLayout, numElements,
        vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), &m_layout)))
    {
        return false;
    }
 
    // 더 이상 사용되지 않는 정점 쉐이더 버퍼와 픽셀 쉐이더 버퍼를 해제한다.
    vertexShaderBuffer->Release();
    vertexShaderBuffer = nullptr;
 
    pixelShaderBuffer->Release();
    pixelShaderBuffer = nullptr;
 
    // 정점 쉐이더에 있는 행렬 상수 버퍼의 구조체를 작성한다.
    D3D11_BUFFER_DESC constantBufferDesc;
    constantBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    constantBufferDesc.ByteWidth = sizeof(ConstantBufferType);
    constantBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    constantBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    constantBufferDesc.MiscFlags = 0;
    constantBufferDesc.StructureByteStride = 0;
 
    // 상수 버퍼 포인터를 만들어 이 클래스에서 정점 쉐이더 상수 버퍼에 접근할 수 있게 한다.
    if (FAILED(device->CreateBuffer(&constantBufferDesc, nullptr, &m_constantBuffer)))
    {
        return false;
    }
 
    // 텍스처 샘플러 상태 구조체를 생성 및 설정한다.
    D3D11_SAMPLER_DESC samplerDesc;
    samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.MipLODBias = 0.0f;
    samplerDesc.MaxAnisotropy = 1;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    samplerDesc.BorderColor[0= 0;
    samplerDesc.BorderColor[1= 0;
    samplerDesc.BorderColor[2= 0;
    samplerDesc.BorderColor[3= 0;
    samplerDesc.MinLOD = 0;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;
 
    // 텍스처 샘플러 상태를 만듭니다.
    if (FAILED(device->CreateSamplerState(&samplerDesc, &m_sampleState)))
    {
        return false;
    }
 
    // 동적 픽셀 상수버퍼의 디스크립션을 설정한다.
    D3D11_BUFFER_DESC pixelBufferDesc;
    pixelBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    pixelBufferDesc.ByteWidth = sizeof(PixelBufferType);
    pixelBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    pixelBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    pixelBufferDesc.MiscFlags = 0;
    pixelBufferDesc.StructureByteStride = 0;
 
    // 픽셀 상수 버퍼 포인터를 만들어 픽셀 쉐이더 상수버퍼에 접근할 수 있게한다.
    if (FAILED(device->CreateBuffer(&pixelBufferDesc, nullptr, &m_pixelBuffer)))
    {
        return false;
    }
 
 
    return true;
}
 
void FontShaderClass::ShutdownShader()
{
    if (m_pixelBuffer)
    {
        m_pixelBuffer->Release();
        m_pixelBuffer = nullptr;
    }
 
    // 샘플러 상태 해제
    if (m_sampleState)
    {
        m_sampleState->Release();
        m_sampleState = nullptr;
    }
 
    if (m_constantBuffer)
    {
        m_constantBuffer->Release();
        m_constantBuffer = nullptr;
    }
 
    if (m_layout)
    {
        m_layout->Release();
        m_layout = nullptr;
    }
 
    if (m_pixelShader)
    {
        m_pixelShader->Release();
        m_pixelShader = nullptr;
    }
 
    if (m_vertexShader)
    {
        m_vertexShader->Release();
        m_vertexShader = nullptr;
    }
}
 
void FontShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, const WCHAR* shaderFilename)
{
    // 에러 메시지를 출력창에 표시한다.
    OutputDebugStringA(reinterpret_cast<const char*>(errorMessage->GetBufferPointer()));
 
    // 에러 메시지를 반환 한다.
    errorMessage->Release();
    errorMessage = nullptr;
 
    // 컴파일 에러가 있음을 팝업 메세지를 알려준다.
    MessageBox(hwnd, L"Error compiling shader.", shaderFilename, MB_OK);
}
 
bool FontShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
    XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, XMFLOAT4 pixelColor)
{
    // 행렬을 transpose하여 쉐이더에서 사용할 수 있게 한다.
    worldMatrix = XMMatrixTranspose(worldMatrix);
    viewMatrix = XMMatrixTranspose(viewMatrix);
    projectionMatrix = XMMatrixTranspose(projectionMatrix);
 
    // 상수 버퍼의 내용을 쓸 수 있도록 잠근다.
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    if (FAILED(deviceContext->Map(m_constantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 상수 버퍼의 데이터에 대한 포인터를 가져온다.
    ConstantBufferType* dataPtr = reinterpret_cast<ConstantBufferType*>(mappedResource.pData);
 
    // 상수 버퍼에 행렬을 복사한다.
    dataPtr->world = worldMatrix;
    dataPtr->view = viewMatrix;
    dataPtr->projection = projectionMatrix;
 
    // 상수 버퍼의 잠금을 푼다.
    deviceContext->Unmap(m_constantBuffer, 0);
 
    // 정점 쉐이더에서의 상수 버퍼의 위치를 설정한다.
    unsigned bufferNumber = 0;
 
    // 마지막으로 정점 쉐이더의 상수 버퍼를 바뀐 값으로 바꾼다.
    deviceContext->VSSetConstantBuffers(bufferNumber, 1&m_constantBuffer);
 
    // 픽셀 쉐이더에서 쉐이더 텍스처 리소스를 설정한다.
    deviceContext->PSSetShaderResources(01&texture);
 
    // 픽셀 상수 버퍼의 내용을 쓸 수 있도록 잠근다.
    if (FAILED(deviceContext->Map(m_pixelBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 픽셀 상수 버퍼의 데이터에 대한 포인터를 가져온다.
    PixelBufferType* dataPtr2 = reinterpret_cast<PixelBufferType*>(mappedResource.pData);
 
    // 픽셀 상수 버퍼에 데이타를 복사한다.
    dataPtr2->pixelColor = pixelColor;
 
    // 픽셀 상수 버퍼의 잠금을 푼다.
    deviceContext->Unmap(m_pixelBuffer, 0);
 
    // 픽셀 쉐이더의 픽셀 상수 버퍼의 위치를 설정한다.
    bufferNumber = 0;
 
    // 이젠 픽셀쉐이더의 픽셀 상수 버퍼의 데이터를 업데이트 한다.
    deviceContext->PSSetConstantBuffers(bufferNumber, 1&m_pixelBuffer);
 
    return true;
}
 
void FontShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
    // 정점 입력 레이아웃을 설정한다.
    deviceContext->IASetInputLayout(m_layout);
 
    // 삼각형을 그릴 정점 쉐이더와 픽셀 쉐이더를 설정한다.
    deviceContext->VSSetShader(m_vertexShader, nullptr, 0);
    deviceContext->PSSetShader(m_pixelShader, nullptr, 0);
 
    // 픽셀 쉐이더에서 샘플러 상태를 설정한ㄷ.ㅏ
    deviceContext->PSSetSamplers(01&m_sampleState);
 
    // 삼각형을 그린다.
    deviceContext->DrawIndexed(indexCount, 00);
}
 
cs

 

<TextClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#pragma once
#ifndef _TEXTCLASS_H_
#define _TEXTCLASS_H_
 
class FontClass;
class FontShaderClass;
 
 
class TextClass
{
private:
    struct SentenceType
    {
        ID3D11Buffer* vertexBuffer, * indexBuffer;
        int vertexCount, indexCount, maxLength;
        float red, green, blue;
    };
 
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
    };
 
public:
    TextClass();
    TextClass(const TextClass& other);
    ~TextClass();
 
    bool Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, HWND hwnd, int screenWidth, int screenHeight, XMMATRIX baseViewMatrix);
    void Shutdown();
    bool Render(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX orthoMatrix);
 
private:
    bool InitializeSentence(SentenceType** sentence, int maxLength, ID3D11Device* device);
    bool UpdateSentence(SentenceType* sentence, const char* text, int positionX, int positionY, float red, float green, float blue, ID3D11DeviceContext* deviceContext);
    void ReleaseSentence(SentenceType** sentence);
    bool RenderSentence(ID3D11DeviceContext* deviceContext, SentenceType* sentence, XMMATRIX worldMatrix, XMMATRIX orthoMatrix);
 
private:
    FontClass* m_Font = nullptr;
    FontShaderClass* m_FontShader = nullptr;
    int m_screenWidth = 0;
    int m_screenHeight = 0;
    XMMATRIX m_baseViewMatrix;
    SentenceType* m_sentence1 = nullptr;
    SentenceType* m_sentence2 = nullptr;
 
};
 
 
#endif // _TEXTCLASS_H_
 
cs

 

<TextClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#include "stdafx.h"
#include "TextClass.h"
 
#include "FontClass.h"
#include "FontShaderClass.h"
 
TextClass::TextClass()
{
}
 
TextClass::TextClass(const TextClass& other)
{
}
 
TextClass::~TextClass()
{
}
 
bool TextClass::Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, HWND hwnd, int screenWidth, int screenHeight, XMMATRIX baseViewMatrix)
{
 
    // 화면 너비 높이 값 저장.
    m_screenWidth = screenWidth;
    m_screenHeight = screenHeight;
 
    // baseViewMatrix 저장.
    m_baseViewMatrix = baseViewMatrix;
 
    // Font 객체 생성
    m_Font = new FontClass;
    if (!m_Font)
    {
        return false;
    }
 
    // Font 객체 초기화
    if (!(m_Font->Initialize(device, "./fontdata.txt", L"./Textures/font.dds")))
    {
        MessageBox(hwnd, L"Could not initialize the font object", L"Error", MB_OK);
        return false;
    }
 
    // 폰트 쉐이더 객체 생성
    m_FontShader = new FontShaderClass;
    if (!m_FontShader)
    {
        return false;
    }
 
    // 폰트쉐이더 객체 초기화
    if (!(m_FontShader->Initialize(device, hwnd)))
    {
        MessageBox(hwnd, L"Could not initialize the font shader object", L"Error", MB_OK);
        return false;
    }
 
    // 첫번째 문장 초기화
    if (!(InitializeSentence(&m_sentence1, 16, device)))
    {
        return false;
    }
 
    // 이젠 Sentence Vertex Buffer를 문장으로 업데이트 한다.
    if (!(UpdateSentence(m_sentence1, "Hello"1001001.0f, 1.0f, 1.0f, deviceContext)))
    {
        return false;
    }
 
    // 두번째 문장 초기화
    if (!(InitializeSentence(&m_sentence2, 16, device)))
    {
        return false;
    }
 
    // 이젠 Sentence Vertex Buffer를 문장으로 업데이트 한다.
    if (!(UpdateSentence(m_sentence2, "Goodbye"1002001.0f, 1.0f, 0.0f, deviceContext)))
    {
        return false;
    }
 
    return true;
}
 
void TextClass::Shutdown()
{
    // 문장 객체 해제
    ReleaseSentence(&m_sentence1);
    ReleaseSentence(&m_sentence2);
 
    // 폰트쉐이더 객체 해제
    if (m_FontShader)
    {
        m_FontShader->Shutdown();
        delete m_FontShader;
        m_FontShader = nullptr;
    }
 
    // 폰트 객체 해제
    if (m_Font)
    {
        m_Font->Shutdown();
        delete m_Font;
        m_Font = nullptr;
    }
 
}
 
bool TextClass::Render(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX orthoMatrix)
{
    bool result;
 
    // 첫번째 문자 그리기
    result = RenderSentence(deviceContext, m_sentence1, worldMatrix, orthoMatrix);
    if (!result)
    {
        return false;
    }
 
    // 두번째 문자 그리기
    result = RenderSentence(deviceContext, m_sentence2, worldMatrix, orthoMatrix);
    if (!result)
    {
        return false;
    }
 
    return true;
}
 
bool TextClass::InitializeSentence(SentenceType** sentence, int maxLength, ID3D11Device* device)
{
    // SentenceType 객체 생성
    *sentence = new SentenceType;
    if (!*sentence)
    {
        return false;
    }
 
    // 센텐스 버퍼를 null로 초기화
    (*sentence)->vertexBuffer = nullptr;
    (*sentence)->indexBuffer = nullptr;
 
    // 최대 길이 초기화
    (*sentence)->maxLength = maxLength;
 
    // 정점수 초기화
    (*sentence)->vertexCount = 6 * maxLength; // 한글자에 6정점 필요(삼각형 2개)
 
    // 인덱스의 수 초기화
    (*sentence)->indexCount = (*sentence)->vertexCount;
 
    // 버텍스 배열 생성
    VertexType* vertices = new VertexType[(*sentence)->vertexCount];
    if (!vertices)
    {
        return false;
    }
 
    // 인덱스 배열 생성
    unsigned long* indices = new unsigned long[(*sentence)->indexCount];
    if (!indices)
    {
        return false;
    }
 
    // 버텍스 어레이 0으로 초기화
    memset(vertices, 0, (sizeof(VertexType) * (*sentence)->vertexCount));
 
    // 인덱스 어레이 초기화
    for (int i = 0; i < (*sentence)->indexCount; i++)
    {
        indices[i] = i;
    }
 
    // 동적 정점 버퍼 디스크립션 설정
    D3D11_BUFFER_DESC vertexBufferDesc;
    vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    vertexBufferDesc.ByteWidth = sizeof(VertexType) * (*sentence)->vertexCount;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    vertexBufferDesc.MiscFlags = 0;
    vertexBufferDesc.StructureByteStride = 0;
 
    // Subresource 구조체에 버텍스 데이터 포인터를 할당.
    D3D11_SUBRESOURCE_DATA vertexData;
    vertexData.pSysMem = vertices;
    vertexData.SysMemPitch = 0;
    vertexData.SysMemSlicePitch = 0;
 
    // 버텍스 버퍼 생성
    bool result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &(*sentence)->vertexBuffer);
    if (FAILED(result))
    {
        return false;
    }
 
    // 정적 인덱스 버퍼의 디스크립션 작성
    D3D11_BUFFER_DESC indexBufferDesc;
    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(unsigned long* (*sentence)->indexCount;
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;
    indexBufferDesc.MiscFlags = 0;
    indexBufferDesc.StructureByteStride = 0;
 
    // Subresource 구조체에 인덱스 데이타 포인터 할당
    D3D11_SUBRESOURCE_DATA indexData;
    indexData.pSysMem = indices;
    indexData.SysMemPitch = 0;
    indexData.SysMemSlicePitch = 0;
 
    // 인덱스 버퍼 생성
    result = device->CreateBuffer(&indexBufferDesc, &indexData, &(*sentence)->indexBuffer);
    if (FAILED(result))
    {
        return false;
    }
 
    // 더이상 사용하지 않는 버텍스, 인덱스 배열 할당 해제
    delete[] vertices;
    vertices = nullptr;
    delete[] indices;
    indices = nullptr;
 
    return true;
}
 
bool TextClass::UpdateSentence(SentenceType* sentence, const char* text, int positionX, int positionY, float red, float green, float blue , ID3D11DeviceContext* deviceContext)
{
    // 문장의 색상 저장
    sentence->red = red;
    sentence->green = green;
    sentence->blue = blue;
 
    // 문장의 길이 가져오기
    auto numLetters = static_cast<int>(strlen(text));
 
    // 버퍼의 오버플로우 확인
    if (numLetters > sentence->maxLength)
    {
        return false;
    }
 
    // 버텍스 어레이 생성
    auto vertices = new VertexType[sentence->vertexCount];
    if (!vertices)
    {
        return false;
    }
 
    // 버텍스 어레이 0으로 초기화
    memset(vertices, 0sizeof(VertexType) * sentence->vertexCount);
 
    // X와 Y의 픽셀위치를 계산한다.
    auto drawX = static_cast<float>(((m_screenWidth / 2* -1+ positionX);
    auto drawY = static_cast<float>((m_screenHeight / 2- positionY);
 
    // 문장 텍스트와 문자 그리는 위치를 사용하여 버텍스 어레이를 빌드하기위해 폰트 클래스를 사용한다.
    m_Font->BuildVertexArray(reinterpret_cast<void*>(vertices), text, drawX, drawY);
 
    // 버텍스 버퍼를 쓰기 위해 잠근다.
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    bool result = deviceContext->Map(sentence->vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource);
    if (FAILED(result))
    {
        return false;
    }
 
    // 버텍스 버퍼의 데이터를 가르키는 포인터를 가져온다.
    auto verticesPtr = reinterpret_cast<VertexType*>(mappedResource.pData);
 
    // 데이타를 버텍스 버퍼로 복사한다.
    memcpy(verticesPtr, reinterpret_cast<void*>(vertices), sizeof(VertexType) * sentence->vertexCount);
 
    // 버텍스 버퍼의 잠금해제 한다.
    deviceContext->Unmap(sentence->vertexBuffer, 0);
 
    // 더이상 사용하지 않는 버텍스 어레이 할당해제
    delete[] vertices;
    vertices = nullptr;
 
    return true;
}
 
void TextClass::ReleaseSentence(SentenceType** sentence)
{
    if (*sentence)
    {
        // 문장 버텍스 버퍼 해제
        if ((*sentence)->vertexBuffer)
        {
            (*sentence)->vertexBuffer->Release();
            (*sentence)->vertexBuffer = nullptr;
        }
 
        // 문장 인덱스 버퍼 해제
        if (((*sentence)->indexBuffer))
        {
            (*sentence)->indexBuffer->Release();
            (*sentence)->indexBuffer = nullptr;
        }
 
        // sentence 해제
        delete* sentence;
        *sentence = nullptr;
    }
}
 
bool TextClass::RenderSentence(ID3D11DeviceContext* deviceContext, SentenceType* sentence, XMMATRIX worldMatrix, XMMATRIX orthoMatrix)
{
    // 버텍스 버퍼의 스트라이드와 오프셋을 설정
    unsigned int stride = sizeof(VertexType);
    unsigned int offset = 0;
 
    // 랜더될수 있도록 인풋 어셈블러에서 버텍스 버퍼가 활성화 되도록 설정한다.
    deviceContext->IASetVertexBuffers(01&sentence->vertexBuffer, &stride, &offset);
 
    // 인덱스 버퍼 활성화
    deviceContext->IASetIndexBuffer(sentence->indexBuffer, DXGI_FORMAT_R32_UINT, 0);
 
    // primitive 타입 설정, 여기서는 삼각형
    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
 
    // 픽셀 생상 벡터를 인풋된 문장 색상으로 만든다.
    auto pixelColor = XMFLOAT4(sentence->red, sentence->green, sentence->blue, 1.0f);
 
    // 폰트쉐이더를 이용하여 텍스트를 랜더한다.
    bool result = m_FontShader->Render(deviceContext, sentence->indexCount, worldMatrix, m_baseViewMatrix, orthoMatrix,
        m_Font->GetTexture(), pixelColor);
    if (!result)
    {
        return false;
    }
    return true;
}
 
cs

 

<D3dClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#pragma once
 
#ifndef _D3DCLASS_H_
#define _D3DCLASS_H_
 
class D3DClass
{
public:
    D3DClass();
    D3DClass(const D3DClass&);
    ~D3DClass();
 
    bool Initialize(int screenWidth, int screenHeight, 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);
 
    void TurnZBufferOn();
    void TurnZBufferOff();
 
    void TurnOnAlphaBlending();
    void TurnOffAlphaBlending();
 
private:
    bool m_vsync_enabled = false;
    int m_videoCardMemory = 0;
    char m_videoCardDescription[128= { 0, };
    IDXGISwapChain* m_swapChain = nullptr;
    ID3D11Device* m_device = nullptr;
    ID3D11DeviceContext* m_deviceContext = nullptr;
    ID3D11RenderTargetView* m_renderTargetView = nullptr;
    ID3D11Texture2D* m_depthStencilBuffer = nullptr;
    ID3D11DepthStencilState* m_depthStencilState = nullptr;
    ID3D11DepthStencilView* m_depthStencilView = nullptr;
    ID3D11RasterizerState* m_rasterState = nullptr;
    XMMATRIX m_projectionMatrix;
    XMMATRIX m_worldMatrix;
    XMMATRIX m_orthoMatrix;
 
    ID3D11DepthStencilState* m_depthDisabledStencilState = nullptr;
 
    ID3D11BlendState* m_alphaEnableBlendingState = nullptr;
    ID3D11BlendState* m_alphaDisableBlendingState = nullptr;
 
};
 
 
 
 
 
#endif // _D3DCLASS_H_
cs

 

<D3dClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
#include "stdafx.h"
#include "D3dclass.h"
 
#include <iostream>
 
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)
{
 
    // 수직동기화 상태를 저장한다.
    m_vsync_enabled = vsync;
 
    // DirectX 그래픽 인터페이스 팩토리를 생성한다.
    IDXGIFactory* factory = nullptr;
    if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory))))
    {
        return false;
    }
 
 
    // 팩토리 객체를 사용하여 첫번째 그래픽 카드 인터페이스 어뎁터를 생성한다.
    IDXGIAdapter* adapter = nullptr;
    if (FAILED(factory->EnumAdapters(0&adapter)))  // 0 은 첫번째 그래픽카드 // 컴퓨터에 따라 0번이 내장 그래픽일수 도 있고 외장일 수 도 있다.
    {
        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_B8G8R8A8_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_B8G8R8A8_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 == static_cast<unsigned>(screenWidth))
        {
            if (displayModeList[i].Height == static_cast<unsigned>(screenHeight))
            {
                numerator = displayModeList[i].RefreshRate.Numerator;
                denominator = displayModeList[i].RefreshRate.Denominator;
            }
        }
    }
 
    // 비디오카드의 구조체를 얻는다.
    DXGI_ADAPTER_DESC adapterDesc;
    if (FAILED(adapter->GetDesc(&adapterDesc)))
    {
        return false;
    }
 
    // 비디오카드 메모리 용량 단위를 메가바이트 단위로 저장한다.
    m_videoCardMemory = static_cast<int>(adapterDesc.DedicatedVideoMemory / 1024 / 1024);
 
 
    // 비디오카드의 이름을 저장합니다.
    size_t stringLength = 0;
    if (wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128!= 0)
    {
        return false;
    }
 
 
    // 그래픽 카드 확인 용도.
    const WCHAR* pwcsName; //LPCWSTR
 
    // required size
    int size = MultiByteToWideChar(CP_ACP, 0, m_videoCardDescription, -1NULL0);
    // allocate it
    pwcsName = new WCHAR[stringLength];
    MultiByteToWideChar(CP_ACP, 0, m_videoCardDescription, -1, (LPWSTR)pwcsName, size);
    // use it....
 
    OutputDebugString(pwcsName);
    // delete it
    delete[] pwcsName;
    
    
 
    // 디스플레이 모드 리스트를 해제한다.
    delete[] displayModeList;
    displayModeList = nullptr;
 
    // 출력 어뎁터를 해제한다.
    adapterOutput->Release();
    adapterOutput = nullptr;
 
    // 어뎁터를 해제한다.
    adapter->Release();
    adapter = nullptr;
 
 
    // 스왑체인 구조체를 초기환한다.
    DXGI_SWAP_CHAIN_DESC swapChainDesc;
    ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
 
    // 백버퍼를 1개만 사용하도록 지정한다.
    swapChainDesc.BufferCount = 1;
 
    // 백버퍼의 넓이와 높이를 지정한다.
    swapChainDesc.BufferDesc.Width = screenWidth;
    swapChainDesc.BufferDesc.Height = screenHeight;
 
    // 33bit 서피스를 설정한다.
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
 
    // 백버퍼의 새로고침 비율을 설정한다.
    if (m_vsync_enabled)
    {
        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;
 
    // 피처레벨을 DirectX11로 설정한다.
    D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
 
    // 스왑 체인, Direct3D 장치 및 Direct3D 장치 컨텍스트를 만든다.
    if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL0&featureLevel, 1,
        D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL&m_deviceContext)))
    {
        return false;
    }
 
 
    // 백버퍼 포인터를 얻어온다.
    ID3D11Texture2D* backBufferPtr = nullptr;
    if (FAILED(m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),reinterpret_cast<LPVOID*>(&(backBufferPtr)))))
    {
        return false;
    }
 
 
    // 백 버퍼 포인터로 랜더 타겟 뷰를 생성한다.
    if(FAILED(m_device->CreateRenderTargetView(backBufferPtr, NULL&m_renderTargetView)))
    {
        return false;
    }
 
 
    // 백버퍼 포인터를 해제한다.
    backBufferPtr->Release();
    backBufferPtr = nullptr;
 
 
    // 깊이 버퍼 구조체를 초기화 합니다.
    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(m_device->CreateTexture2D(&depthBufferDesc, NULL& m_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;
 
    // 깊이 스텐실 상태를 설정합니다.
    m_deviceContext->OMSetDepthStencilState(m_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(m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView)))
    {
        return false;
    }
 
    // 랜더링 대상 뷰와 깊이 스텐실 버퍼를  출력 렌더 파이프 라인에 바인딩 한다.
    m_deviceContext->OMSetRenderTargets(1&m_renderTargetView, m_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(m_device->CreateRasterizerState(&rasterDesc, &m_rasterState)))
    {
        return false;
    }
 
    // 이제 레스터 라이저 상태를 설정한다.
    m_deviceContext->RSSetState(m_rasterState);
 
    // 렌더링을 위해 뷰포트를 설정한다.
    D3D11_VIEWPORT viewport;
    viewport.Width = static_cast<float>(screenWidth);
    viewport.Height = static_cast<float>(screenHeight);
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0.0f;
    viewport.TopLeftY = 0.0f;
 
    // 뷰포트를 생성한다.
    m_deviceContext->RSSetViewports(1&viewport);
 
    // 투영 행렬을 설정한다.
    float fieldOfView = 3.141592654f / 4.0f;
    float screenAspect = static_cast<float>(screenWidth) / static_cast<float>(screenHeight);
 
    // 3D 렌더링을 위핸 투영 행렬을 만든다.
    m_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);
 
    // 세계 행렬을 항동 행렬로 초기화 한다.
    m_worldMatrix = XMMatrixIdentity();
 
    // 2D렌더링을위한 직교 투영 행렬을 만든다.
    m_orthoMatrix = XMMatrixOrthographicLH(static_cast<float>(screenWidth), static_cast<float>(screenHeight), screenNear, screenDepth);
 
    // 이제 2D 렌더링을 위한 Z 버퍼를 끄는 두번째 깊이 스텐실 상태를 만든다.
    // 유일한 차이점은 DepthEnable을 false로 설정하며, 다른 모든 매개변수는 다른 깊이 스텐실 상태와 동일하다.
 
    D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
    ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));
 
    // 스텐실 상태 구조체를 작성합니다.
    depthDisabledStencilDesc.DepthEnable = false;
    depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
    
    depthDisabledStencilDesc.StencilEnable = true;
    depthDisabledStencilDesc.StencilReadMask = 0xFF;
    depthDisabledStencilDesc.StencilWriteMask = 0xFF;
 
    // 픽셀 정면의 스텐실 설정입니다.
    depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
 
    // 픽셀 뒷면의 스텐실 설정입니다.
    depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
 
    // 장치를 사용하여 상태를 만든다.
    if (FAILED(m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState)))
    {
        return false;
    }
 
    // BlendState discription 초기화
    D3D11_BLEND_DESC blendStateDescription;
    ZeroMemory(&blendStateDescription, sizeof(D3D11_BLEND_DESC));
 
    // Alpha Enabled blend state 디스크립션 설정
    blendStateDescription.RenderTarget[0].BlendEnable = TRUE;
    blendStateDescription.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
    blendStateDescription.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
    blendStateDescription.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
    blendStateDescription.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
    blendStateDescription.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
    blendStateDescription.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
    blendStateDescription.RenderTarget[0].RenderTargetWriteMask = 0x0f;
 
    // 디스크립션을 이용하여 블렌드 스테이트를 생성한다.
    if(FAILED(m_device->CreateBlendState(&blendStateDescription, &m_alphaEnableBlendingState)))
    {
        return false;
    }
 
    // 알파 비활성화 블렌드 스테이트를 생성하기위해 기존 디스크립션을 수정한다.
    blendStateDescription.RenderTarget[0].BlendEnable = FALSE;
 
    // 디스크립션을 이용하여 블렌드 스테이트를 생성한다.
    if (FAILED(m_device->CreateBlendState(&blendStateDescription, &m_alphaDisableBlendingState)))
    {
        return false;
    }
 
    return true;
}
 
void D3DClass::Shutdown()
{
    // 종료하기 전에 이렇게 윈도우 모드로 바꾸지 않으면 스왑체인을 할당 해제할 때 예외가 발생합니다.
    if (m_swapChain)
    {
        m_swapChain->SetFullscreenState(false, nullptr);
    }
 
    // 두 블렌딩 상태 해제
    if (m_alphaEnableBlendingState)
    {
        m_alphaEnableBlendingState->Release();
        m_alphaEnableBlendingState = nullptr;
    }
 
    if (m_alphaDisableBlendingState)
    {
        m_alphaDisableBlendingState->Release();
        m_alphaDisableBlendingState = nullptr;
    }
 
    if (m_depthDisabledStencilState)
    {
        m_depthDisabledStencilState->Release();
        m_depthDisabledStencilState = nullptr;
    }
 
    if (m_rasterState)
    {
        m_rasterState->Release();
        m_rasterState = nullptr;
    }
 
    if (m_depthStencilView)
    {
        m_depthStencilView->Release();
        m_depthStencilView = nullptr;
    }
 
    if (m_depthStencilState)
    {
        m_depthStencilState->Release();
        m_depthStencilState = nullptr;
    }
 
    if (m_depthStencilBuffer)
    {
        m_depthStencilBuffer->Release();
        m_depthStencilBuffer = nullptr;
    }
 
    if (m_renderTargetView)
    {
        m_renderTargetView->Release();
        m_renderTargetView = nullptr;
    }
 
    if (m_deviceContext)
    {
        m_deviceContext->Release();
        m_deviceContext = nullptr;
    }
 
    if (m_device)
    {
        m_device->Release();
        m_device = nullptr;
    }
 
    if (m_swapChain)
    {
        m_swapChain->Release();
        m_swapChain = nullptr;
    }
 
}
 
void D3DClass::BeginScene(float red, float green, float blue, float alpha)
{
 
    // 버퍼를 지울 색을 설정한다.
    float color[4= { red, green, blue, alpha };
 
    // 백버퍼를 지운다.
    m_deviceContext->ClearRenderTargetView(m_renderTargetView, color);
 
    // 깊이 버퍼를 지운다.
    m_deviceContext->ClearDepthStencilView(m_depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
 
void D3DClass::EndScene()
{
    // 렌더링이 완료되었으므로 화면에 백 버퍼를 표시한다.
    if(m_vsync_enabled)
    {
        // 화면 새로 고침 비율을 고정한다.
        m_swapChain->Present(10);
    }
    else
    {
        // 가능한 빠르게 출력한다.
        m_swapChain->Present(00);
    }
}
 
ID3D11Device* D3DClass::GetDevice()
{
    return m_device;
}
 
ID3D11DeviceContext* D3DClass::GetDeviceContext()
{
    return m_deviceContext;
}
 
void D3DClass::GetProjectionMatrix(XMMATRIX& projectionMatrix)
{
    // 이번 예제에서는 사용 안함.
    projectionMatrix = m_projectionMatrix;
}
 
void D3DClass::GetWorldMatrix(XMMATRIX& worldMatrix)
{
    // 이번 예제에서는 사용 안함.
    worldMatrix = m_worldMatrix;
}
 
void D3DClass::GetOrthoMatrix(XMMATRIX& orthoMatrix)
{
    // 이번 예제에서는 사용 안함.
    orthoMatrix = m_orthoMatrix;
}
 
void D3DClass::GetVideoCardInfo(char* cardname, int& memory)
{
    strcpy_s(cardname, 128, m_videoCardDescription);
    memory = m_videoCardMemory;
}
 
void D3DClass::TurnZBufferOn()
{
    m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);
}
 
void D3DClass::TurnZBufferOff()
{
    m_deviceContext->OMSetDepthStencilState(m_depthDisabledStencilState, 1);
}
 
void D3DClass::TurnOnAlphaBlending()
{
    float blendFactor[4];
 
    // 블렌드 요인들 설정
    blendFactor[0= 0.0f;
    blendFactor[1= 0.0f;
    blendFactor[2= 0.0f;
    blendFactor[3= 0.0f;
 
    // 알파 블렌딩을 켠다.
    m_deviceContext->OMSetBlendState(m_alphaEnableBlendingState, blendFactor, 0xffffffff);
}
 
void D3DClass::TurnOffAlphaBlending()
{
    float blendFactor[4];
 
    // 블렌드 요인들 설정
    blendFactor[0= 0.0f;
    blendFactor[1= 0.0f;
    blendFactor[2= 0.0f;
    blendFactor[3= 0.0f;
 
    // 알파 블렌딩을 끈다.
    m_deviceContext->OMSetBlendState(m_alphaDisableBlendingState, blendFactor, 0xffffffff);
}
 
cs

 

<GraphicsClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#pragma once
#ifndef _GRAPHICSCLASS_H_
#define _GRAPHICSCLASS_H_
 
// 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 CameraClass;
//class ModelClass;
//class ColorShaderClass;
class TextureShaderClass;
class BitmapClass;
class LightShaderClass;
class LightClass;
class TextClass;
 
class GraphicsClass
{
public:
    GraphicsClass();
    GraphicsClass(const GraphicsClass& other);
    ~GraphicsClass();
 
 
    bool Initialize(int screenWidth, int screenHeight, HWND hwnd);
    void Shutdown();
    bool Frame();
 
private:
    bool Render(float rotation);
 
private:
    D3DClass* m_D3D = nullptr;
    CameraClass* m_Camera = nullptr;
 
    //ModelClass* m_Model = nullptr;
    //TextureShaderClass* m_TextureShader = nullptr;
    //BitmapClass* m_Bitmap = nullptr;
    //ColorShaderClass* m_ColorShader = nullptr;
    //LightShaderClass* m_LightShader = nullptr;
    //LightClass* m_Light = nullptr;
    TextClass* m_Text = nullptr;
};
 
#endif // _GRAPHICSCLASS_H_
cs

 

<GraphicsClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#include "stdafx.h"
#include "graphicsclass.h"
 
#include "BitmapClass.h"
#include "D3dclass.h"
#include "CameraClass.h"
#include "ModelClass.h"
#include "LightShaderClass.h"
#include "LightClass.h"
#include "TextClass.h"
#include "TextureShaderClass.h"
 
GraphicsClass::GraphicsClass()
{
}
 
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
 
GraphicsClass::~GraphicsClass()
{
}
 
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
    // Direct3D 객체 생성
    m_D3D = new D3DClass;
    if (!m_D3D)
    {
        return false;
    }
 
    // Direct3D 객체를 초기화 한다.
    if (!m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR))
    {
        MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK);
        return false;
    }
 
 
    // m_Camera 객체 생성
    m_Camera = new CameraClass;
    if (!m_Camera)
    {
        return false;
    }
 
    // 카메라 포지션 설정
    XMMATRIX baseViewMatrix;
    m_Camera->SetPosition(0.0f, 0.0f, -5.0f);
    m_Camera->Render();
    m_Camera->GetViewMatrix(baseViewMatrix);
 
    // 텍스트 객체 생성
    m_Text = new TextClass;
    if (!m_Text)
    {
        return false;
    }
 
    // 텍스트 객체 초기화
    if (!m_Text->Initialize(m_D3D->GetDevice(), m_D3D->GetDeviceContext(), hwnd, screenWidth, screenHeight,baseViewMatrix))
    {
        MessageBox(hwnd, L"Could not initialize the Text object.", L"Error", MB_OK);
        return false;
    }
 
    //// m_Model 객체 생성
    //m_Model = new ModelClass;
    //if (!m_Model)
    //{
    //    return false;
    //}
 
    //// m_Model 초기화
    //if (!m_Model->Initialize(m_D3D->GetDevice(), "./cube.txt", L"./Textures/WoodCrate01.dds"))
    //{
    //    MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
    //}
 
    // 텍스쳐 쉐이더 객체 생성
    //m_TextureShader = new TextureShaderClass;
    //if (!m_TextureShader)
    //{
    //    return false;
    //}
 
    //// 텍스터 쉐이더 객테 초기화
    //if (!m_TextureShader->Initialize(m_D3D->GetDevice(), hwnd))
    //{
    //    MessageBox(hwnd, L"Could not initialize texture shader object.", L"Error", MB_OK);
    //    return false;
    //}
 
    //// LightShaderClass 객체 생성
    //m_LightShader = new LightShaderClass;
    //if (!m_LightShader)
    //{
    //    return false;
    //}
 
    //// LightShader 객체를 초기화한다.
    //if (!m_LightShader->Initialize(m_D3D->GetDevice(), hwnd))
    //{
    //    MessageBox(hwnd, L"Could not initialize the light shader object.", L"Error", MB_OK);
    //    return false;
    //}
 
    //// LightClass 객체 생성
    //m_Light = new LightClass;
    //if (!m_Light)
    //{
    //    return false;
    //}
 
    //// Light 객체 초기화
    //m_Light->SetAmbientColor(0.15f, 0.15f, 0.15f, 1.0f);
    //m_Light->SetDiffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
    //m_Light->SetDirection(1.0f, 0.0f, 1.0f);
    //m_Light->SetSpecularColor(1.0f, 1.0f, 1.0f, 1.0f);
    //m_Light->SetSpecularPower(32.0f);
 
    // 비트맵 객체 생성
    //m_Bitmap = new BitmapClass;
    //if (!m_Bitmap)
    //{
    //    return false;
    //}
 
    // 비트맵 객체 초기화
    //if (!m_Bitmap->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight, L"./Textures/WoodCrate01.dds",
    //    512, 512))
    //{
    //    MessageBox(hwnd, L"Could not initialize the bitmap object.", L"Error", MB_OK);
    //    return false;
    //}
 
    return true;
}
 
void GraphicsClass::Shutdown()
{
    // 텍스트 객체 해제
    if (m_Text)
    {
        m_Text->Shutdown();
        delete m_Text;
        m_Text = nullptr;
    }
    // 비트맵 객체 해제
    //if (m_Bitmap)
    //{
    //    m_Bitmap->Shutdown();
    //    delete m_Bitmap;
    //    m_Bitmap = nullptr;
    //}
    //// light 객체 해제
    //if (m_Light)
    //{
    //    delete m_Light;
    //    m_Light = nullptr;
    //}
 
    //// LightShader 객체 해제
    //if (m_LightShader)
    //{
    //    m_LightShader->Shutdown();
    //    delete m_LightShader;
    //    m_LightShader = nullptr;
    //}
 
    // m_TextureShader 객체 반환
    //if (m_TextureShader)
    //{
    //    m_TextureShader->Shutdown();
    //    delete m_TextureShader;
    //    m_TextureShader = nullptr;
    //}
 
    //// m_Model 객체 반환
    //if (m_Model)
    //{
    //    m_Model->Shutdown();
    //    delete m_Model;
    //    m_Model = nullptr;
    //}
 
    // m_Camera 객체 반환
    if (m_Camera)
    {
        delete m_Camera;
        m_Camera = nullptr;
    }
 
    // D3D 객체를 반환합니다.
    if (m_D3D)
    {
        m_D3D->Shutdown();
        delete m_D3D;
        m_D3D = nullptr;
    }
}
 
bool GraphicsClass::Frame()
{
    static float rotation = 0.0f;
 
    // 각 프레임 마다 rotation 변수값을 업데이트 한다.
    rotation += XM_PI * 0.005f;
    if (rotation > 360.0f)
    {
        rotation -= 360.0f;
    }
    //그래픽 렌더링을 수행합니다.
    if (!Render(rotation))
    {
        
        return false;
    }
    return true;
}
 
bool GraphicsClass::Render(float rotation)
{
    // 씬 그리기를 시작하기 위해 버퍼의 내용을 지웁니다.
    m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성한다.
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져온다.
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix, orthoMatrix;
    m_D3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetProjectionMatrix(projectionMatrix);
    m_D3D->GetOrthoMatrix(orthoMatrix);
 
    // 2D 렌더링을 시작하기 위해 Z버퍼를 끈다.
    m_D3D->TurnZBufferOff();
 
    // 알파 블렌딩을 켠다.
    m_D3D->TurnOnAlphaBlending();
 
    // 비트맵 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 그리기를 준비한다.
    //if (!m_Bitmap->Render(m_D3D->GetDeviceContext(), 100, 100))
    //{
    //    return false;
    //}
 
    // 도형이 회전 할 수 있도록 회전 값으로 월드 행렬을 회전한다.
    // = XMMatrixRotationY(rotation);
 
    // 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 드로잉을 준비한다.
    //m_Model->Render(m_D3D->GetDeviceContext());
 
 
    // Light 쉐이더를 사용하여 모델을 렌더링 한다.
    //if (!m_LightShader->Render(m_D3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix,
    //    viewMatrix, projectionMatrix, m_Model->GetTexture(), m_Light->GetDirection(), m_Light->GetAmbientColor(), m_Light->GetDiffuseColor()
    //    , m_Camera->GetPosition(), m_Light->GetSpecularColor(), m_Light->GetSpecularPower()))
    //{
    //    return false;
    //}
 
    // 텍스트 문자열을 렌더한다.
    if (!m_Text->Render(m_D3D->GetDeviceContext(), worldMatrix, orthoMatrix))
    {
        return false;
    }
 
 
    // 텍스처 쉐이더를 사용하여 모델을 랜더링 한다.
    //if (!m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Bitmap->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix,
    //    m_Bitmap->GetTexture()))
    //{
    //    return false;
    //}
 
    // 모든2D 렌더링이 완료되었으므로 Z버퍼를 다시 켠다.
    m_D3D->TurnZBufferOn();
 
    // 버퍼에 그려진 씬을 화면에 표시합니다.
    m_D3D->EndScene();
 
    return true;
}
 
cs

 

 

<결과>

<소스코드>

https://github.com/woonhak-kong/DirectX_11_Tutorial/releases/tag/Tutorial_10

 

 

Visual Studio 2022에서 작성하였습니다.
 
해당글은 다음 블로그를 참조하였습니다.

http://www.rastertek.com/tutdx11.html

https://ppparkje.tistory.com/category/%EA%B0%95%EC%A2%8C%EB%B2%88%EC%97%AD/DirectX%2011?page=2 
https://copynull.tistory.com/category/DirectX%2011/Basic


Tutorial-8 에 이어서 작성하였음.

 

 

<BitmapClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#pragma once
 
#ifndef _BITMAPCLASS_H_
#define _BITMAPCLASS_H_
 
class TextureClass;
 
class BitmapClass
{
public:
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
    };
 
    BitmapClass();
    BitmapClass(const BitmapClass& other);
    ~BitmapClass();
 
 
    bool Initialize(ID3D11Device* device, int screenWidth, int screenHeight, const WCHAR* textureFilename, int bitmapWidth, int bitmapHeight);
    void Shutdown();
    bool Render(ID3D11DeviceContext* deviceContext, int positionX, int positionY);
 
    int GetIndexCount();
    ID3D11ShaderResourceView* GetTexture();
 
 
private:
 
    bool InitializeBuffers(ID3D11Device* device);
    void ShutdownBuffers();
    bool UpdateBuffers(ID3D11DeviceContext* deviceContext, int positionX, int positionY);
    void RenderBuffers(ID3D11DeviceContext* deviceContext);
 
    // 텍스쳐 로드, 반환
    bool LoadTexture(ID3D11Device* device, const WCHAR* filename);
    void ReleaseTexture();
    
private:
    ID3D11Buffer* m_vertexBuffer = nullptr;
    ID3D11Buffer* m_indexBuffer = nullptr;
    int m_vertexCount = 0;
    int m_indexCount = 0;
 
    TextureClass* m_texture = nullptr;
 
    int m_screenWidth = 0;
    int m_screenHeight = 0;
    int m_bitmapWidth = 0;
    int m_bitmapHeight = 0;
    int m_previousPosX = 0;
    int m_previousPosY = 0;
 
};
 
 
 
#endif // _BITMAPCLASS_H_
cs

 

<BitmapClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#include "stdafx.h"
#include "BitmapClass.h"
 
#include "TextureClass.h"
 
BitmapClass::BitmapClass()
{
}
 
BitmapClass::BitmapClass(const BitmapClass& other)
{
}
 
BitmapClass::~BitmapClass()
{
}
 
bool BitmapClass::Initialize(ID3D11Device* device, int screenWidth, int screenHeight, const WCHAR* textureFilename, int bitmapWidth, int bitmapHeight)
{
    // 화면 크기를 멤버변수에 저장
    m_screenWidth = screenWidth;
    m_screenHeight = screenHeight;
 
    // 렌더링할 비트맵의 픽셀의 크기를 저장
    m_bitmapWidth = bitmapWidth;
    m_bitmapHeight = bitmapHeight;
 
    // 이전 렌더링 위치를 음수로 초기화 한다.
    m_previousPosX = -1;
    m_previousPosY = -1;
 
    // 정점 및 인덱스 버퍼를 초기화 한다.
    if (!InitializeBuffers(device))
    {
        return false;
    }
 
    // 이 모델의 텍스처를 로드한다.
    return LoadTexture(device, textureFilename);
 
}
 
void BitmapClass::Shutdown()
{
    // 모델 텍스쳐를 반환한다.
    ReleaseTexture();
 
    // 버텍스 및 인덱스 버퍼를 종료한다.
    ShutdownBuffers();
}
 
bool BitmapClass::Render(ID3D11DeviceContext* deviceContext, int positionX, int positionY)
{
    // 화면의 다른 위치로 렌더링하기 위해 동적 정점 버퍼를 다시 빌드한ㄷ.
    if (!UpdateBuffers(deviceContext, positionX, positionY))
    {
        return false;
    }
 
    // 그리기를 준비하기 위해 그래픽 파이프 라인에 꼭지점과 인덱스 버퍼를 놓는다.
    RenderBuffers(deviceContext);
 
    return true;
}
 
int BitmapClass::GetIndexCount()
{
    return m_indexCount;
}
 
ID3D11ShaderResourceView* BitmapClass::GetTexture()
{
    return m_texture->GetTexture();
}
 
bool BitmapClass::InitializeBuffers(ID3D11Device* device)
{
    // 정점 배열의 정점 수와 인덱스 배열의 인덱스 수를 지정한다.
    m_indexCount = m_vertexCount = 6;
 
    // 정점 배열을 만든다.
    VertexType* vertices = new VertexType[m_vertexCount];
    if (!vertices)
    {
        return false;
    }
 
 
    // 정점 배열을 0으로 초기화 한다.
    memset(vertices, 0, (sizeof(VertexType) * m_vertexCount));
 
    // 인덱스 배열을 만든다.
    unsigned long* indices = new unsigned long[m_indexCount];
    if (!indices)
    {
        return false;
    }
 
    // 데이터로 인덱스 배열을 로드한다.
    for (int i = 0; i < m_vertexCount; i++)
    {
        indices[i] = i;
    }
 
 
    // 정적 정점 버퍼의 구조체를 설정한다.
    D3D11_BUFFER_DESC vertexBufferDesc;
    vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    vertexBufferDesc.MiscFlags = 0;
    vertexBufferDesc.StructureByteStride = 0;
 
    // subresource 구조에 정점 데이터에 대한 포인터를 제공한다.
    D3D11_SUBRESOURCE_DATA vertexData;
    vertexData.pSysMem = vertices;
    vertexData.SysMemPitch = 0;
    vertexData.SysMemSlicePitch = 0;
 
    // 이제 정점 버퍼를 만듭니다.
    if (FAILED(device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer)))
    {
        return false;
    }
 
    // 인덱스 버퍼 description 생성
    D3D11_BUFFER_DESC indexBufferDesc;
    indexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    indexBufferDesc.ByteWidth = sizeof(unsigned long* m_indexCount;
    indexBufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
    indexBufferDesc.CPUAccessFlags = 0;
    indexBufferDesc.MiscFlags = 0;
    indexBufferDesc.StructureByteStride = 0;
 
    // 인덱스 데이터를 가리키는 보조 리소스 구조체 작성
    D3D11_SUBRESOURCE_DATA indexData;
    indexData.pSysMem = indices;
    indexData.SysMemPitch = 0;
    indexData.SysMemSlicePitch = 0;
 
    // 인덱스 버퍼를 생성합니다.
    if (FAILED(device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer)))
    {
        return false;
    }
 
    // 정점버퍼 인덱스 버퍼 해제
    delete[] vertices;
    vertices = nullptr;
 
    delete[] indices;
    indices = nullptr;
 
    return true;
}
 
void BitmapClass::ShutdownBuffers()
{
    // 인덱스 버퍼 해제
    if (m_indexBuffer)
    {
        m_indexBuffer->Release();
        m_indexBuffer = nullptr;
    }
 
    // 정점 버퍼를 해제합니다.
    if (m_vertexBuffer)
    {
        m_vertexBuffer->Release();
        m_indexBuffer = nullptr;
    }
}
 
bool BitmapClass::UpdateBuffers(ID3D11DeviceContext* deviceContext, int positionX, int positionY)
{
    float left, right, top, bottom;
    VertexType* vertices;
    VertexType* verticesPtr;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
 
 
    // 이 비트맵을 렌더링 할 위치가 변경되지 않은 경우 정점 버퍼를 업데이트 하지 않는다.
    if ((positionX == m_previousPosX) && (positionY == m_previousPosY))
    {
        return true;
    }
 
    // 변경된 경우 렌더링 되는 위치를 업데이트 한다.
    m_previousPosX = positionX;
    m_previousPosY = positionY;
 
    // 비트 맵 왼쪽의 화면 좌표를 계산한다.
    left = static_cast<float>((m_screenWidth / 2* -1+ static_cast<float>(positionX);
 
    // 비트맵 오른쪽의 화면 좌표를 계산한다.
    right = left + static_cast<float>(m_bitmapWidth);
 
    // 비트맵 상단의 화면 좌표를 계산한다.
    top = static_cast<float>(m_screenHeight / 2- static_cast<float>(positionY);
 
    // 비트 맵 아래쪽의 화면 좌표를 계산한다.
    bottom = top - static_cast<float>(m_bitmapHeight);
 
 
    // 정점 배열을 만든다.
    vertices = new VertexType[m_vertexCount];
    if (!vertices)
    {
        return false;
    }
 
    // 정점 배열에 데이터를 로드한다.
    // 첫 번째 삼각형
    vertices[0].position = XMFLOAT3(left, top, 0.0f);
    vertices[0].texture = XMFLOAT2(0.0f, 0.0f);
 
    vertices[1].position = XMFLOAT3(right, bottom, 0.0f);
    vertices[1].texture = XMFLOAT2(1.0f, 1.0f);
 
    vertices[2].position = XMFLOAT3(left, bottom, 0.0f);
    vertices[2].texture = XMFLOAT2(0.0f, 1.0f);
 
 
    // 두번째 삼각형
    vertices[3].position = XMFLOAT3(left, top, 0.0f);
    vertices[3].texture = XMFLOAT2(0.0f, 0.0f);
 
    vertices[4].position = XMFLOAT3(right, top, 0.0f);
    vertices[4].texture = XMFLOAT2(1.0f, 0.0f);
 
    vertices[5].position = XMFLOAT3(right, bottom, 0.0f);
    vertices[5].texture = XMFLOAT2(1.0f, 1.0f);
 
    // 버텍스 버퍼를 쓸 수 있도록 잠근다.
    if (FAILED(deviceContext->Map(m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 정점 버퍼의 데이터를 가리키는 포인터를 얻는다.
    verticesPtr = reinterpret_cast<VertexType*>(mappedResource.pData);
 
    // 데이터를 정점 버퍼에 복사한다.
    memcpy(verticesPtr, vertices, (sizeof(VertexType) * m_vertexCount));
    
    // 정점 버퍼의 잠금을 해제한다.
    deviceContext->Unmap(m_vertexBuffer, 0);
 
    // 더이상 필요하지 않은 꼭지점 배열 해제
    delete[] vertices;
    vertices = 0;
 
    return true;
}
 
void BitmapClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
    unsigned int stride;
    unsigned int offset;
 
    // 정점 버퍼의 단위와 오프셋을 설정한다.
    stride = sizeof(VertexType);
    offset = 0;
 
    // input assembler에 정점 버퍼를 활성화하여 그려질 수 있게 한다.
    deviceContext->IASetVertexBuffers(01&m_vertexBuffer, &stride, &offset);
 
    // input Assembler에 인덱스 버퍼를 활성화여 그려질 수 있게한다.
    deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
 
    // 정점 버퍼로 그릴 기본형을 설정한다.
    // 여기서는 삼각형이다.
    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
 
}
 
bool BitmapClass::LoadTexture(ID3D11Device* device, const WCHAR* filename)
{
    // 텍스쳐 오브젝트를 생성한다.
    m_texture = new TextureClass;
    if (!m_texture)
    {
        return false;
    }
 
    // 텍스처 오브젝트를 초기화한다.
    return m_texture->Initialize(device, filename);
}
 
void BitmapClass::ReleaseTexture()
{
    // 텍스쳐 오브젝트를 릴리즈 한다.
    if (m_texture)
    {
        m_texture->Shutdown();
        delete m_texture;
        m_texture = nullptr;
    }
    
}
 
cs

 

<D3dClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#pragma once
 
#ifndef _D3DCLASS_H_
#define _D3DCLASS_H_
 
class D3DClass
{
public:
    D3DClass();
    D3DClass(const D3DClass&);
    ~D3DClass();
 
    bool Initialize(int screenWidth, int screenHeight, 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);
 
    void TurnZBufferOn();
    void TurnZBufferOff();
 
private:
    bool m_vsync_enabled = false;
    int m_videoCardMemory = 0;
    char m_videoCardDescription[128= { 0, };
    IDXGISwapChain* m_swapChain = nullptr;
    ID3D11Device* m_device = nullptr;
    ID3D11DeviceContext* m_deviceContext = nullptr;
    ID3D11RenderTargetView* m_renderTargetView = nullptr;
    ID3D11Texture2D* m_depthStencilBuffer = nullptr;
    ID3D11DepthStencilState* m_depthStencilState = nullptr;
    ID3D11DepthStencilView* m_depthStencilView = nullptr;
    ID3D11RasterizerState* m_rasterState = nullptr;
    XMMATRIX m_projectionMatrix;
    XMMATRIX m_worldMatrix;
    XMMATRIX m_orthoMatrix;
 
    ID3D11DepthStencilState* m_depthDisabledStencilState = nullptr;
 
};
 
 
 
 
 
#endif // _D3DCLASS_H_
cs

 

<D3dClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#include "stdafx.h"
#include "D3dclass.h"
 
#include <iostream>
 
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)
{
 
    // 수직동기화 상태를 저장한다.
    m_vsync_enabled = vsync;
 
    // DirectX 그래픽 인터페이스 팩토리를 생성한다.
    IDXGIFactory* factory = nullptr;
    if (FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&factory))))
    {
        return false;
    }
 
 
    // 팩토리 객체를 사용하여 첫번째 그래픽 카드 인터페이스 어뎁터를 생성한다.
    IDXGIAdapter* adapter = nullptr;
    if (FAILED(factory->EnumAdapters(0&adapter)))  // 0 은 첫번째 그래픽카드 // 컴퓨터에 따라 0번이 내장 그래픽일수 도 있고 외장일 수 도 있다.
    {
        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_B8G8R8A8_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_B8G8R8A8_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 == static_cast<unsigned>(screenWidth))
        {
            if (displayModeList[i].Height == static_cast<unsigned>(screenHeight))
            {
                numerator = displayModeList[i].RefreshRate.Numerator;
                denominator = displayModeList[i].RefreshRate.Denominator;
            }
        }
    }
 
    // 비디오카드의 구조체를 얻는다.
    DXGI_ADAPTER_DESC adapterDesc;
    if (FAILED(adapter->GetDesc(&adapterDesc)))
    {
        return false;
    }
 
    // 비디오카드 메모리 용량 단위를 메가바이트 단위로 저장한다.
    m_videoCardMemory = static_cast<int>(adapterDesc.DedicatedVideoMemory / 1024 / 1024);
 
 
    // 비디오카드의 이름을 저장합니다.
    size_t stringLength = 0;
    if (wcstombs_s(&stringLength, m_videoCardDescription, 128, adapterDesc.Description, 128!= 0)
    {
        return false;
    }
 
 
    // 그래픽 카드 확인 용도.
    const WCHAR* pwcsName; //LPCWSTR
 
    // required size
    int size = MultiByteToWideChar(CP_ACP, 0, m_videoCardDescription, -1NULL0);
    // allocate it
    pwcsName = new WCHAR[stringLength];
    MultiByteToWideChar(CP_ACP, 0, m_videoCardDescription, -1, (LPWSTR)pwcsName, size);
    // use it....
 
    OutputDebugString(pwcsName);
    // delete it
    delete[] pwcsName;
    
    
 
    // 디스플레이 모드 리스트를 해제한다.
    delete[] displayModeList;
    displayModeList = nullptr;
 
    // 출력 어뎁터를 해제한다.
    adapterOutput->Release();
    adapterOutput = nullptr;
 
    // 어뎁터를 해제한다.
    adapter->Release();
    adapter = nullptr;
 
 
    // 스왑체인 구조체를 초기환한다.
    DXGI_SWAP_CHAIN_DESC swapChainDesc;
    ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
 
    // 백버퍼를 1개만 사용하도록 지정한다.
    swapChainDesc.BufferCount = 1;
 
    // 백버퍼의 넓이와 높이를 지정한다.
    swapChainDesc.BufferDesc.Width = screenWidth;
    swapChainDesc.BufferDesc.Height = screenHeight;
 
    // 33bit 서피스를 설정한다.
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
 
    // 백버퍼의 새로고침 비율을 설정한다.
    if (m_vsync_enabled)
    {
        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;
 
    // 피처레벨을 DirectX11로 설정한다.
    D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0;
 
    // 스왑 체인, Direct3D 장치 및 Direct3D 장치 컨텍스트를 만든다.
    if (FAILED(D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL0&featureLevel, 1,
        D3D11_SDK_VERSION, &swapChainDesc, &m_swapChain, &m_device, NULL&m_deviceContext)))
    {
        return false;
    }
 
 
    // 백버퍼 포인터를 얻어온다.
    ID3D11Texture2D* backBufferPtr = nullptr;
    if (FAILED(m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D),reinterpret_cast<LPVOID*>(&(backBufferPtr)))))
    {
        return false;
    }
 
 
    // 백 버퍼 포인터로 랜더 타겟 뷰를 생성한다.
    if(FAILED(m_device->CreateRenderTargetView(backBufferPtr, NULL&m_renderTargetView)))
    {
        return false;
    }
 
 
    // 백버퍼 포인터를 해제한다.
    backBufferPtr->Release();
    backBufferPtr = nullptr;
 
 
    // 깊이 버퍼 구조체를 초기화 합니다.
    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(m_device->CreateTexture2D(&depthBufferDesc, NULL& m_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;
 
    // 깊이 스텐실 상태를 설정합니다.
    m_deviceContext->OMSetDepthStencilState(m_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(m_device->CreateDepthStencilView(m_depthStencilBuffer, &depthStencilViewDesc, &m_depthStencilView)))
    {
        return false;
    }
 
    // 랜더링 대상 뷰와 깊이 스텐실 버퍼를  출력 렌더 파이프 라인에 바인딩 한다.
    m_deviceContext->OMSetRenderTargets(1&m_renderTargetView, m_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(m_device->CreateRasterizerState(&rasterDesc, &m_rasterState)))
    {
        return false;
    }
 
    // 이제 레스터 라이저 상태를 설정한다.
    m_deviceContext->RSSetState(m_rasterState);
 
    // 렌더링을 위해 뷰포트를 설정한다.
    D3D11_VIEWPORT viewport;
    viewport.Width = static_cast<float>(screenWidth);
    viewport.Height = static_cast<float>(screenHeight);
    viewport.MinDepth = 0.0f;
    viewport.MaxDepth = 1.0f;
    viewport.TopLeftX = 0.0f;
    viewport.TopLeftY = 0.0f;
 
    // 뷰포트를 생성한다.
    m_deviceContext->RSSetViewports(1&viewport);
 
    // 투영 행렬을 설정한다.
    float fieldOfView = 3.141592654f / 4.0f;
    float screenAspect = static_cast<float>(screenWidth) / static_cast<float>(screenHeight);
 
    // 3D 렌더링을 위핸 투영 행렬을 만든다.
    m_projectionMatrix = XMMatrixPerspectiveFovLH(fieldOfView, screenAspect, screenNear, screenDepth);
 
    // 세계 행렬을 항동 행렬로 초기화 한다.
    m_worldMatrix = XMMatrixIdentity();
 
    // 2D렌더링을위한 직교 투영 행렬을 만든다.
    m_orthoMatrix = XMMatrixOrthographicLH(static_cast<float>(screenWidth), static_cast<float>(screenHeight), screenNear, screenDepth);
 
    // 이제 2D 렌더링을 위한 Z 버퍼를 끄는 두번째 깊이 스텐실 상태를 만든다.
    // 유일한 차이점은 DepthEnable을 false로 설정하며, 다른 모든 매개변수는 다른 깊이 스텐실 상태와 동일하다.
 
    D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
    ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));
 
    // 스텐실 상태 구조체를 작성합니다.
    depthDisabledStencilDesc.DepthEnable = false;
    depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
    depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
    
    depthDisabledStencilDesc.StencilEnable = true;
    depthDisabledStencilDesc.StencilReadMask = 0xFF;
    depthDisabledStencilDesc.StencilWriteMask = 0xFF;
 
    // 픽셀 정면의 스텐실 설정입니다.
    depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
    depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
 
    // 픽셀 뒷면의 스텐실 설정입니다.
    depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
    depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
    depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
 
    // 장치를 사용하여 상태를 만든다.
    if (FAILED(m_device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_depthDisabledStencilState)))
    {
        return false;
    }
 
    return true;
}
 
void D3DClass::Shutdown()
{
    // 종료하기 전에 이렇게 윈도우 모드로 바꾸지 않으면 스왑체인을 할당 해제할 때 예외가 발생합니다.
    if (m_swapChain)
    {
        m_swapChain->SetFullscreenState(false, nullptr);
    }
 
    if (m_depthDisabledStencilState)
    {
        m_depthDisabledStencilState->Release();
        m_depthDisabledStencilState = nullptr;
    }
 
    if (m_rasterState)
    {
        m_rasterState->Release();
        m_rasterState = nullptr;
    }
 
    if (m_depthStencilView)
    {
        m_depthStencilView->Release();
        m_depthStencilView = nullptr;
    }
 
    if (m_depthStencilState)
    {
        m_depthStencilState->Release();
        m_depthStencilState = nullptr;
    }
 
    if (m_depthStencilBuffer)
    {
        m_depthStencilBuffer->Release();
        m_depthStencilBuffer = nullptr;
    }
 
    if (m_renderTargetView)
    {
        m_renderTargetView->Release();
        m_renderTargetView = nullptr;
    }
 
    if (m_deviceContext)
    {
        m_deviceContext->Release();
        m_deviceContext = nullptr;
    }
 
    if (m_device)
    {
        m_device->Release();
        m_device = nullptr;
    }
 
    if (m_swapChain)
    {
        m_swapChain->Release();
        m_swapChain = nullptr;
    }
 
}
 
void D3DClass::BeginScene(float red, float green, float blue, float alpha)
{
 
    // 버퍼를 지울 색을 설정한다.
    float color[4= { red, green, blue, alpha };
 
    // 백버퍼를 지운다.
    m_deviceContext->ClearRenderTargetView(m_renderTargetView, color);
 
    // 깊이 버퍼를 지운다.
    m_deviceContext->ClearDepthStencilView(m_depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
}
 
void D3DClass::EndScene()
{
    // 렌더링이 완료되었으므로 화면에 백 버퍼를 표시한다.
    if(m_vsync_enabled)
    {
        // 화면 새로 고침 비율을 고정한다.
        m_swapChain->Present(10);
    }
    else
    {
        // 가능한 빠르게 출력한다.
        m_swapChain->Present(00);
    }
}
 
ID3D11Device* D3DClass::GetDevice()
{
    return m_device;
}
 
ID3D11DeviceContext* D3DClass::GetDeviceContext()
{
    return m_deviceContext;
}
 
void D3DClass::GetProjectionMatrix(XMMATRIX& projectionMatrix)
{
    // 이번 예제에서는 사용 안함.
    projectionMatrix = m_projectionMatrix;
}
 
void D3DClass::GetWorldMatrix(XMMATRIX& worldMatrix)
{
    // 이번 예제에서는 사용 안함.
    worldMatrix = m_worldMatrix;
}
 
void D3DClass::GetOrthoMatrix(XMMATRIX& orthoMatrix)
{
    // 이번 예제에서는 사용 안함.
    orthoMatrix = m_orthoMatrix;
}
 
void D3DClass::GetVideoCardInfo(char* cardname, int& memory)
{
    strcpy_s(cardname, 128, m_videoCardDescription);
    memory = m_videoCardMemory;
}
 
void D3DClass::TurnZBufferOn()
{
    m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 1);
}
 
void D3DClass::TurnZBufferOff()
{
    m_deviceContext->OMSetDepthStencilState(m_depthDisabledStencilState, 1);
}
 
cs

 

<GraphicsClass.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#pragma once
#ifndef _GRAPHICSCLASS_H_
#define _GRAPHICSCLASS_H_
 
// 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 CameraClass;
//class ModelClass;
//class ColorShaderClass;
class TextureShaderClass;
class BitmapClass;
class LightShaderClass;
class LightClass;
 
class GraphicsClass
{
public:
    GraphicsClass();
    GraphicsClass(const GraphicsClass& other);
    ~GraphicsClass();
 
 
    bool Initialize(int screenWidth, int screenHeight, HWND hwnd);
    void Shutdown();
    bool Frame();
 
private:
    bool Render(float rotation);
 
private:
    D3DClass* m_D3D = nullptr;
    CameraClass* m_Camera = nullptr;
 
    //ModelClass* m_Model = nullptr;
    TextureShaderClass* m_TextureShader = nullptr;
    BitmapClass* m_Bitmap = nullptr;
    //ColorShaderClass* m_ColorShader = nullptr;
    //LightShaderClass* m_LightShader = nullptr;
    //LightClass* m_Light = nullptr;
};
 
#endif // _GRAPHICSCLASS_H_
cs

 

<GraphicsClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#include "stdafx.h"
#include "graphicsclass.h"
 
#include "BitmapClass.h"
#include "D3dclass.h"
#include "CameraClass.h"
#include "ModelClass.h"
#include "LightShaderClass.h"
#include "LightClass.h"
#include "TextureShaderClass.h"
 
GraphicsClass::GraphicsClass()
{
}
 
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
 
GraphicsClass::~GraphicsClass()
{
}
 
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
    // Direct3D 객체 생성
    m_D3D = new D3DClass;
    if (!m_D3D)
    {
        return false;
    }
 
    // Direct3D 객체를 초기화 한다.
    if (!m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR))
    {
        MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK);
        return false;
    }
 
 
    // m_Camera 객체 생성
    m_Camera = new CameraClass;
    if (!m_Camera)
    {
        return false;
    }
 
    // 카메라 포지션 설정
    m_Camera->SetPosition(0.0f, 0.0f, -5.0f);
 
    //// m_Model 객체 생성
    //m_Model = new ModelClass;
    //if (!m_Model)
    //{
    //    return false;
    //}
 
    //// m_Model 초기화
    //if (!m_Model->Initialize(m_D3D->GetDevice(), "./cube.txt", L"./Textures/WoodCrate01.dds"))
    //{
    //    MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
    //}
 
    // 텍스쳐 쉐이더 객체 생성
    m_TextureShader = new TextureShaderClass;
    if (!m_TextureShader)
    {
        return false;
    }
 
    //// 텍스터 쉐이더 객테 초기화
    if (!m_TextureShader->Initialize(m_D3D->GetDevice(), hwnd))
    {
        MessageBox(hwnd, L"Could not initialize texture shader object.", L"Error", MB_OK);
        return false;
    }
 
    //// LightShaderClass 객체 생성
    //m_LightShader = new LightShaderClass;
    //if (!m_LightShader)
    //{
    //    return false;
    //}
 
    //// LightShader 객체를 초기화한다.
    //if (!m_LightShader->Initialize(m_D3D->GetDevice(), hwnd))
    //{
    //    MessageBox(hwnd, L"Could not initialize the light shader object.", L"Error", MB_OK);
    //    return false;
    //}
 
    //// LightClass 객체 생성
    //m_Light = new LightClass;
    //if (!m_Light)
    //{
    //    return false;
    //}
 
    //// Light 객체 초기화
    //m_Light->SetAmbientColor(0.15f, 0.15f, 0.15f, 1.0f);
    //m_Light->SetDiffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
    //m_Light->SetDirection(1.0f, 0.0f, 1.0f);
    //m_Light->SetSpecularColor(1.0f, 1.0f, 1.0f, 1.0f);
    //m_Light->SetSpecularPower(32.0f);
 
    // 비트맵 객체 생성
    m_Bitmap = new BitmapClass;
    if (!m_Bitmap)
    {
        return false;
    }
 
    // 비트맵 객체 초기화
    if (!m_Bitmap->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight, L"./Textures/WoodCrate01.dds",
        512512))
    {
        MessageBox(hwnd, L"Could not initialize the bitmap object.", L"Error", MB_OK);
        return false;
    }
 
    return true;
}
 
void GraphicsClass::Shutdown()
{
    // 비트맵 객체 해제
    if (m_Bitmap)
    {
        m_Bitmap->Shutdown();
        delete m_Bitmap;
        m_Bitmap = nullptr;
    }
    //// light 객체 해제
    //if (m_Light)
    //{
    //    delete m_Light;
    //    m_Light = nullptr;
    //}
 
    //// LightShader 객체 해제
    //if (m_LightShader)
    //{
    //    m_LightShader->Shutdown();
    //    delete m_LightShader;
    //    m_LightShader = nullptr;
    //}
 
    // m_TextureShader 객체 반환
    //if (m_TextureShader)
    //{
    //    m_TextureShader->Shutdown();
    //    delete m_TextureShader;
    //    m_TextureShader = nullptr;
    //}
 
    //// m_Model 객체 반환
    //if (m_Model)
    //{
    //    m_Model->Shutdown();
    //    delete m_Model;
    //    m_Model = nullptr;
    //}
 
    // m_Camera 객체 반환
    if (m_Camera)
    {
        delete m_Camera;
        m_Camera = nullptr;
    }
 
    // D3D 객체를 반환합니다.
    if (m_D3D)
    {
        m_D3D->Shutdown();
        delete m_D3D;
        m_D3D = nullptr;
    }
}
 
bool GraphicsClass::Frame()
{
    static float rotation = 0.0f;
 
    // 각 프레임 마다 rotation 변수값을 업데이트 한다.
    rotation += XM_PI * 0.005f;
    if (rotation > 360.0f)
    {
        rotation -= 360.0f;
    }
    //그래픽 렌더링을 수행합니다.
    if (!Render(rotation))
    {
        
        return false;
    }
    return true;
}
 
bool GraphicsClass::Render(float rotation)
{
    // 씬 그리기를 시작하기 위해 버퍼의 내용을 지웁니다.
    m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성한다.
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져온다.
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix, orthoMatrix;
    m_D3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetProjectionMatrix(projectionMatrix);
    m_D3D->GetOrthoMatrix(orthoMatrix);
 
    // 2D 렌더링을 시작하기 위해 Z버퍼를 끈다.
    m_D3D->TurnZBufferOff();
 
    // 비트맵 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 그리기를 준비한다.
    if (!m_Bitmap->Render(m_D3D->GetDeviceContext(), 100100))
    {
        return false;
    }
 
    // 도형이 회전 할 수 있도록 회전 값으로 월드 행렬을 회전한다.
    // = XMMatrixRotationY(rotation);
 
    // 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 드로잉을 준비한다.
    //m_Model->Render(m_D3D->GetDeviceContext());
 
 
    // Light 쉐이더를 사용하여 모델을 렌더링 한다.
    //if (!m_LightShader->Render(m_D3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix,
    //    viewMatrix, projectionMatrix, m_Model->GetTexture(), m_Light->GetDirection(), m_Light->GetAmbientColor(), m_Light->GetDiffuseColor()
    //    , m_Camera->GetPosition(), m_Light->GetSpecularColor(), m_Light->GetSpecularPower()))
    //{
    //    return false;
    //}
 
 
    // 텍스처 쉐이더를 사용하여 모델을 랜더링 한다.
    if (!m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Bitmap->GetIndexCount(), worldMatrix, viewMatrix, orthoMatrix,
        m_Bitmap->GetTexture()))
    {
        return false;
    }
 
    // 모든2D 렌더링이 완료되었으므로 Z버퍼를 다시 켠다.
    m_D3D->TurnZBufferOn();
 
    // 버퍼에 그려진 씬을 화면에 표시합니다.
    m_D3D->EndScene();
 
    return true;
}
 
cs

 

<결과>

<소스코드>

https://github.com/woonhak-kong/DirectX_11_Tutorial/releases/tag/Tutorial_9

 

 

+ Recent posts