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-2 에 이어서 작성하였음.

 

<Color.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;
    float4 color : COLOR;
};
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};
 
 
// Vertex Shader
 
PixelInputType ColorVertexShader(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.color = input.color;
 
    return output;
}
cs

 

<Color.ps>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Typedefs
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};
 
// Pixel Shader
 
float4 ColorPixelShader(PixelInputType input) : SV_TARGET
{
    return input.color;
}
cs

 

<ModelClass.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
#pragma once
#ifndef __MODELCLASS_H_
#define __MODELCLASS_H_
 
class ModelClass
{
private:
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT4 color;
    };
 
public:
    ModelClass();
    ModelClass(const ModelClass& other);
    ~ModelClass();
 
    bool Initialize(ID3D11Device* device);
    void Shutdown();
    void Render(ID3D11DeviceContext* deviceContext);
 
    int GetIndexCount();
 
private:
    bool InitializeBuffers(ID3D11Device* device);
    void ShutdownBuffers();
    void RenderBuffers(ID3D11DeviceContext*);
 
 
private:
    ID3D11Buffer* m_vertexBuffer = nullptr;
    ID3D11Buffer* m_indexBuffer = nullptr;
    int m_vertexCount = 0;
    int m_indexCount = 0;
 
 
};
 
 
#endif //__MODELCLASS_H_
 
 
cs

 

<ModelClass.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
#include "stdafx.h"
#include "ModelClass.h"
 
ModelClass::ModelClass()
{
}
 
ModelClass::ModelClass(const ModelClass& other)
{
}
 
ModelClass::~ModelClass()
{
}
 
bool ModelClass::Initialize(ID3D11Device* device)
{
    // 정점 및 인덱스 버퍼를 초기화합니다.
    return InitializeBuffers(device);
}
 
void ModelClass::Shutdown()
{
    ShutdownBuffers();
}
 
void ModelClass::Render(ID3D11DeviceContext* deviceContext)
{
    // 그리기를 준비하기 위해 그래픽 파이프 라인에 꼭지점과 인덱스 버퍼를 놓는다.
    RenderBuffers(deviceContext);
}
 
int ModelClass::GetIndexCount()
{
    return m_indexCount;
}
 
bool ModelClass::InitializeBuffers(ID3D11Device* device)
{
    // 정점 배열의 정점 수를 설정합니다.
    m_vertexCount = 4;
 
    // 인덱스 배열의 인덱스 수를 설정합니다.
    m_indexCount = 6;
 
    // 정점 배열을 만든다.
    VertexType* vertices = new VertexType[m_vertexCount];
    if(!vertices)
    {
        return false;
    }
 
    // 인덱스 배열을 만듭니다.
    unsigned long* indices = new unsigned long[m_indexCount];
    if(!indices)
    {
        return false;
    }
 
    // 정점 배열에 데이터를 설정합니다.
 
    // 삼각형
    //vertices[0].position = XMFLOAT3(-1.0f, -1.0f, 0.0f); // bottom left.
    //vertices[0].color = XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f);
 
    //vertices[1].position = XMFLOAT3(0.0f, 1.0f, 0.0f); // Top middle
    //vertices[1].color = XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f);
 
    //vertices[2].position = XMFLOAT3(1.0f, -1.0f, 0.0f); // bottom right.
    //vertices[2].color = XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f);
 
 
    // 사각형
    vertices[0].position = XMFLOAT3(-1.0f, -1.0f, 0.0f); // bottom left.
    vertices[0].color = XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f);
 
    vertices[1].position = XMFLOAT3(-1.0f, 1.0f, 0.0f); // Top left
    vertices[1].color = XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f);
 
    vertices[2].position = XMFLOAT3(1.0f, 1.0f, 0.0f); // top right.
    vertices[2].color = XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f);
 
    vertices[3].position = XMFLOAT3(1.0f, -1.0f, 0.0f); // bottom right.
    vertices[3].color = XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f);
 
    // 인덱스 배열의 값을 설정한다.
    // 삼각형
    //indices[0] = 0; // Bottom left;
    //indices[1] = 1; // Top middle;
    //indices[2] = 2; // Bottom right;
 
    // 사각형
    indices[0= 0// Bottom left;
    indices[1= 1// Top left;
    indices[2= 2// Top right;
    indices[3= 2// Top right;
    indices[4= 3// Bottom right;
    indices[5= 0// Bottom left;
 
 
    // 정점 버퍼의 description 작성.
    D3D11_BUFFER_DESC vertexBufferDesc;
    vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
    vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = 0;
    vertexBufferDesc.MiscFlags = 0;
    vertexBufferDesc.StructureByteStride = 0;
 
    // 정점 데이터를 가리키는 보조 리소스 구조체를 작성한다.
    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 ModelClass::ShutdownBuffers()
{
    // 인덱스 버퍼 해제
    if (m_indexBuffer)
    {
        m_indexBuffer->Release();
        m_indexBuffer = nullptr;
    }
 
    // 정점 버퍼를 해제합니다.
    if (m_vertexBuffer)
    {
        m_vertexBuffer->Release();
        m_indexBuffer = nullptr;
    }
}
 
void ModelClass::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);
}
 
cs

 

<ColorshaderClass.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
#pragma once
#ifndef __COLORSHADERCLASS_H_
#define __COLORSHADERCLASS_H_
 
class ColorShaderClass
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
public:
 
    ColorShaderClass();
    ColorShaderClass(const ColorShaderClass& other);
    ~ColorShaderClass();
 
    bool Initialize(ID3D11Device* device, HWND hwnd);
    void Shutdown();
    bool Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix);
 
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);
    void RenderShader(ID3D11DeviceContext* deviceContext, int indexCount);
 
private:
    ID3D11VertexShader* m_vertexShader = nullptr;
    ID3D11PixelShader* m_pixelShader = nullptr;
    ID3D11InputLayout* m_layout = nullptr;
    ID3D11Buffer* m_matrixBuffer = nullptr;
    
};
 
 
 
#endif //__COLORSHADERCLASS_H_
cs

 

<ColorshaderClass.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
#include "stdafx.h"
#include "ColorshaderClass.h"
#include <fstream>
 
ColorShaderClass::ColorShaderClass()
{
}
 
ColorShaderClass::ColorShaderClass(const ColorShaderClass& other)
{
}
 
ColorShaderClass::~ColorShaderClass()
{
}
 
bool ColorShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 쉐이더와 픽셀 쉐이더를 초기화 한다.
    return InitializeShader(device, hwnd, L"./color.vs", L"./color.ps");
}
 
void ColorShaderClass::Shutdown()
{
    // 정점쉐이더, 픽셀 쉐이더 및 그와 관련된 것들을 반환.
    ShutdownShader();
}
 
bool ColorShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix,
    XMMATRIX viewMatrix, XMMATRIX projectionMatrix)
{
    // 렌더링에 사용할 쉐이더의 인자를 입력한다.
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix))
    {
        return false;
    }
 
    //쒜이더를 이용하여 준비된 버퍼를 그린다.
    RenderShader(deviceContext, indexCount);
    return true;
}
 
bool ColorShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, const WCHAR* vsFilename, const WCHAR* psFilename)
{
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일 한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    if(FAILED(D3DCompileFromFile(vsFilename, nullptr, nullptr, "ColorVertexShader""vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
        &vertexShaderBuffer, &errorMessage)))
    {
        // 쉐이더 컴파일 실패시 오류메시지 출력.
        if(errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, vsFilename);
        }
        // 컴파일 오류가 아니라면 쉐이더 파일을 찾울 수 없는 경우이다.
        else
        {
            MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK);
        }
 
        return false;
    }
 
    // 픽셀 쉐이더 코드를 컴파일 한다.
    ID3D10Blob* pixelShaderBuffer = nullptr;
    if(FAILED(D3DCompileFromFile(psFilename, nullptr, nullptr, "ColorPixelShader""ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
    &pixelShaderBuffer, &errorMessage)))
    {
        // 쉐이더 컴파일 실패시 오류메시지 출력.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
        }
        // 컴파일 오류가 아니라면 쉐이더 파일을 찾울 수 없는 경우이다.
        else
        {
            MessageBox(hwnd, psFilename, L"Missing 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 = "COLOR";
    polygonLayout[1].SemanticIndex = 0;
    polygonLayout[1].Format = DXGI_FORMAT_R32G32B32A32_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 matrixBufferDesc;
    matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
    matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    matrixBufferDesc.MiscFlags = 0;
    matrixBufferDesc.StructureByteStride = 0;
 
    // 상수 버퍼 포인터를 만들어 이 클래스에서 정점 쉐이더 상수 버퍼에 접근할 수 있게 한다.
    if(FAILED(device->CreateBuffer(&matrixBufferDesc, nullptr, &m_matrixBuffer)))
    {
        return false;
    }
 
    return true;
}
 
void ColorShaderClass::ShutdownShader()
{
    if(m_matrixBuffer)
    {
        m_matrixBuffer->Release();
        m_matrixBuffer = 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 ColorShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, const WCHAR* shaderFilename)
{
    // 에러 메시지를 출력창에 표시한다.
    OutputDebugStringA(reinterpret_cast<const char*>(errorMessage->GetBufferPointer()));
 
    //////////////////////////////////
    // 파일로 에러출력.
 
    //char* compileErrors;
    //unsigned long bufferSize, i;
    //std::ofstream fout;
 
 
    //// 에러 메세지를 담고 있는 문자열 버퍼의 포인터를 가져옵니다.
    //compileErrors = (char*)(errorMessage->GetBufferPointer());
 
    //// 메세지의 길이를 가져옵니다.
    //bufferSize = errorMessage->GetBufferSize();
 
    //// 파일을 열고 안에 메세지를 기록합니다.
    //fout.open("shader-error.txt");
 
    //// 에러 메세지를 씁니다.
    //for (i = 0; i < bufferSize; i++)
    //{
    //    fout << compileErrors[i];
    //}
 
    //// 파일을 닫습니다.
    //fout.close();
 
    /////////////////////////////////////
    /////////////////////////////////////
 
 
    // 에러 메시지를 반환 한다.
    errorMessage->Release();
    errorMessage = nullptr;
 
    // 컴파일 에러가 있음을 팝업 메세지를 알려준다.
    MessageBox(hwnd, L"Error compiling shader.", shaderFilename, MB_OK);
}
 
bool ColorShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix,
    XMMATRIX viewMatrix, XMMATRIX projectionMatrix)
{
    // 행렬을 transpose하여 쉐이더에서 사용할 수 있게 한다.
    worldMatrix = XMMatrixTranspose(worldMatrix);
    viewMatrix = XMMatrixTranspose(viewMatrix);
    projectionMatrix = XMMatrixTranspose(projectionMatrix);
 
    // 상수 버퍼의 내용을 쓸 수 있도록 잠근다.
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    if(FAILED(deviceContext->Map(m_matrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 상수 버퍼의 데이터에 대한 포인터를 가져온다.
    MatrixBufferType* dataPtr = reinterpret_cast<MatrixBufferType*>(mappedResource.pData);
 
    // 상수 버퍼에 행렬을 복사한다.
    dataPtr->world = worldMatrix;
    dataPtr->view = viewMatrix;
    dataPtr->projection = projectionMatrix;
 
    // 상수 버퍼의 잠금을 푼다.
    deviceContext->Unmap(m_matrixBuffer, 0);
 
    // 정점 쉐이더에서의 상수 버퍼의 위치를 설정한다.
    unsigned bufferNumber = 0;
 
    // 마지막으로 정점 쉐이더의 상수 버퍼를 바뀐 값으로 바꾼다.
    deviceContext->VSSetConstantBuffers(bufferNumber, 1&m_matrixBuffer);
 
    return true;
    
}
 
void ColorShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
    // 정점 입력 레이아웃을 설정한다.
    deviceContext->IASetInputLayout(m_layout);
 
    // 삼각형을 그릴 정점 쉐이더와 픽셀 쉐이더를 설정한다.
    deviceContext->VSSetShader(m_vertexShader, nullptr, 0);
    deviceContext->PSSetShader(m_pixelShader, nullptr, 0);
 
    // 삼각형을 그린다.
    deviceContext->DrawIndexed(indexCount, 00);
    
}
 
cs

 

<CameraClass.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
#pragma
#ifndef __CAMERACLASS_H_
#define __CAMERACLASS_H_
 
 
class CameraClass
{
public:
    CameraClass();
    CameraClass(const CameraClass& other);
    ~CameraClass();
 
    void SetPosition(float x, float y, float z);
    void SetRotation(float x, float y, float z);
 
    XMFLOAT3 GetPosition();
    XMFLOAT3 GetRotation();
 
    void Render();
    void GetViewMatrix(XMMATRIX& viewMatrix);
 
private:
    XMFLOAT3 m_position;
    XMFLOAT3 m_rotation;
    XMMATRIX m_viewMatrix;
 
};
 
 
 
#endif // __CAMERACLASS_H_
cs

 

<CameraClass.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
#include "stdafx.h"
#include "CameraClass.h"
 
CameraClass::CameraClass()
{
    m_position = XMFLOAT3(0.0f, 0.0f, 0.0f);
    m_rotation= XMFLOAT3(0.0f, 0.0f, 0.0f);
}
 
CameraClass::CameraClass(const CameraClass& other)
{
}
 
CameraClass::~CameraClass()
{
}
 
void CameraClass::SetPosition(float x, float y, float z)
{
    m_position.x = x;
    m_position.y = y;
    m_position.z = z;
}
 
void CameraClass::SetRotation(float x, float y, float z)
{
    m_rotation.x = x;
    m_rotation.y = y;
    m_rotation.z = y;
}
 
XMFLOAT3 CameraClass::GetPosition()
{
    return m_position;
}
 
XMFLOAT3 CameraClass::GetRotation()
{
    return m_rotation;
}
 
void CameraClass::Render()
{
    XMFLOAT3 up, position, lookAt;
    XMVECTOR upVector, positionVector, lookAtVector;
    float yaw, pitch, roll;
    XMMATRIX rotationMatrix;
 
    // 위쪽을 가리키는 벡터를 설정한다.
    up.x = 0.0f;
    up.y = 1.0f;
    up.z = 0.0f;
 
    // XMVECTOR 구조체에 로드한다.
    upVector = XMLoadFloat3(&up);
 
    // 3D월드에서 카메라의 위치를 설정한다.
    position = m_position;
 
    // XMVECTOR 구조체에 로드한다.
    positionVector = XMLoadFloat3(&position);
 
    // 기본적으로 카메라가 바라보는 위치 설정
    lookAt.x = 0.0f;
    lookAt.y = 0.0f;
    lookAt.z = 1.0f;
 
    // XMVECTOR 구조체에 로드
    lookAtVector = XMLoadFloat3(&lookAt);
 
    // yaw(Y축) , pitch(X축) 그리고 roll(Z축)의 회전값을 라디안 단위로 설정합니다.
    pitch = m_rotation.x * 0.0174532925f;
    yaw = m_rotation.y * 0.0174532925f;
    roll = m_rotation.z * 0.0174532925f;
 
    // yaw, pitch, roll 값을 통해 회전 행렬을 만든다.
    rotationMatrix = XMMatrixRotationRollPitchYaw(pitch, yaw, roll);
 
    // looAt 및 up 벡터를 회전 행렬로 변형하여 뷰가 원점에서 올바르게 회전되도록 한다.
    lookAtVector = XMVector3TransformCoord(lookAtVector, rotationMatrix);
    upVector = XMVector3TransformCoord(upVector, rotationMatrix);
 
    // 회전 된 카메라 위치를 뷰어 위치로 변환한다.
    lookAtVector = XMVectorAdd(positionVector, lookAtVector);
 
    // 마지막으로 세 개의 업데이트 된 벡터에서 뷰 행렬을 만듭니다.
    m_viewMatrix = XMMatrixLookAtLH(positionVector, lookAtVector, upVector);
 
}
 
void CameraClass::GetViewMatrix(XMMATRIX& viewMatrix)
{
    viewMatrix = m_viewMatrix;
}
 
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
#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 GraphicsClass
{
public:
    GraphicsClass();
    GraphicsClass(const GraphicsClass& other);
    ~GraphicsClass();
 
 
    bool Initialize(int screenWidth, int screenHeight, HWND hwnd);
    void Shutdown();
    bool Frame();
 
private:
    bool Render();
 
private:
    D3DClass* m_D3D = nullptr;
    CameraClass* m_Camera = nullptr;
    ModelClass* m_Model = nullptr;
    ColorShaderClass* m_ColorShader = 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
#include "stdafx.h"
#include "graphicsclass.h"
#include "D3dclass.h"
#include "CameraClass.h"
#include "ModelClass.h";
#include "ColorshaderClass.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, -10.0f);
 
    // m_Model 객체 생성
    m_Model = new ModelClass;
    if (!m_Model)
    {
        return false;
    }
 
    // m_Model 초기화
    if (!m_Model->Initialize(m_D3D->GetDevice()))
    {
        MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
    }
 
    // m_ColorShader 객체 생성
    m_ColorShader = new ColorShaderClass;
    if (!m_ColorShader)
    {
        return false;
    }
 
    // m_ColorShader 객체 초기화
    if (!m_ColorShader->Initialize(m_D3D->GetDevice(), hwnd))
    {
        MessageBox(hwnd, L"Could not initialize the color shader object.", L"Error", MB_OK);
        return false;
    }
 
    return true;
}
 
void GraphicsClass::Shutdown()
{
    // m_ColorShader 객체 반환
    if (m_ColorShader)
    {
        m_ColorShader->Shutdown();
        delete m_ColorShader;
        m_ColorShader = 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()
{
    
    //그래픽 렌더링을 수행합니다.
    if (!Render())
    {
        
        return false;
    }
    return true;
}
 
bool GraphicsClass::Render()
{
    // 씬 그리기를 시작하기 위해 버퍼의 내용을 지웁니다.
    m_D3D->BeginScene(1.0f, 1.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성한다.
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져온다.
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
    m_D3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetProjectionMatrix(projectionMatrix);
 
    // 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 드로잉을 준비한다.
    m_Model->Render(m_D3D->GetDeviceContext());
 
    // 색상 쉐이더를 사용하여 모델을 랜더링 한다.
    if (!m_ColorShader->Render(m_D3D->GetDeviceContext(),
        m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix))
    {
        return false;
    }
 
    // 버퍼에 그려진 씬을 화면에 표시합니다.
    m_D3D->EndScene();
 
    return true;
}
 
cs

 

<결과>

<소스코드>

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

 

Release Tutorial_3 · woonhak-kong/DirectX_11_Tutorial

did exams

github.com

 

+ Recent posts