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

 

<light.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
45
46
47
48
49
50
51
// Globals
 
cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};
 
 
// Typedefs
 
struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};
 
 
// Vertex Shader
 
PixelInputType LightVertexShader(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;
 
    // 월드 행렬에 대해서만 법선 벡터를 계산한다.
    output.normal = mul(input.normal, (float3x3)worldMatrix);
 
    output.normal = normalize(output.normal);
 
    return output;
}
cs

 

<light.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
41
42
43
44
45
46
47
// GLOBALS
Texture2D shaderTexture;
SamplerState SampleType;
 
cbuffer LightBuffer
{
    float4 diffuseColor;
    float3 lightDirection;
    float padding;
};
 
 
// Typedefs
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};
 
// Pixel Shader
 
float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
    float3 lightDir;
    float lightIntensity;
    float4 color;
 
    // 이 텍스쳐 좌표 위치에서 샘플러를 사용하여 텍스쳐에서 픽셀 색상을 샘플링 한다.
    textureColor = shaderTexture.Sample(SampleType, input.tex);
 
    // 계산을 위해 빛 방향을 반전시킨다.
    lightDir = -lightDirection;
 
    // 이 픽셀의 빛의 양을 계산한다.
    lightIntensity = saturate(dot(input.normal, lightDir));
 
    // 빛의 강도와 결합 된 확산 색을 기준으로 최종 색상의 최종 색상을 결정한다.
    color = saturate(diffuseColor * lightIntensity);
 
    // 텍스쳐 픽셀과 최종 확산 색을 곱하여 최종 픽셀 색상 결과를 얻습니다.
    color = color * textureColor;
 
    return color;
}
cs

 

<LightShaderClass.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
#pragma once
#ifndef _LIGHTSHADERCLASS_H_
#define _LIGHTSHADERCLASS_H_
 
class LightShaderClass
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
    struct LightBufferType
    {
        XMFLOAT4 diffuseColor;
        XMFLOAT3 lightDirection;
        float padding; // 구조체가 CreateBuffer 함수 요구사항에 대해 16의 배수가 되어야 함으로 float을 추가하여 32바이트로 만들어준다.
    };
 
public:
    LightShaderClass();
    LightShaderClass(const LightShaderClass& other);
    ~LightShaderClass();
 
    bool Initialize(ID3D11Device* device, HWND hwnd);
    void Shutdown();
    bool Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture,
        XMFLOAT3 lightDirection, XMFLOAT4 diffuseColor);
 
 
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,
        XMFLOAT3 lightDirection, XMFLOAT4 diffuseColor);
    void RenderShader(ID3D11DeviceContext* deviceContext, int indexCount);
 
private:
    ID3D11VertexShader* m_vertexShader = nullptr;
    ID3D11PixelShader* m_pixelShader = nullptr;
    ID3D11InputLayout* m_layout = nullptr;
    ID3D11Buffer* m_matrixBuffer = nullptr;
    ID3D11SamplerState* m_sampleState = nullptr;
 
    ID3D11Buffer* m_lightBuffer = nullptr;
 
};
 
 
 
#endif // _LIGHTSHADERCLASS_H_
cs

 

<LightShaderClass.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
#include "stdafx.h"
#include "LightShaderClass.h"
 
LightShaderClass::LightShaderClass()
{
}
 
LightShaderClass::LightShaderClass(const LightShaderClass& other)
{
}
 
LightShaderClass::~LightShaderClass()
{
}
 
bool LightShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 및 픽셀 쉐이더 초기화
    return InitializeShader(device, hwnd, L"./light.vs", L"./light.ps");
}
 
void LightShaderClass::Shutdown()
{
    // 버텍스 및 픽셀 쉐이더와 관련되 객체 종료
    ShutdownShader();
}
 
bool LightShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture,
    XMFLOAT3 lightDirection, XMFLOAT4 diffuseColor)
{
    // 렌더링에 사용할 쉐이더 매개 변수를 설정
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, lightDirection, diffuseColor))
    {
        return false;
    }
 
    // 설정된 버퍼를 쉐이더로 랜더링 한다.
    RenderShader(deviceContext, indexCount);
    return true;
}
 
bool LightShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, const WCHAR* vsFilename, const WCHAR* psFilename)
{
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일 한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    if (FAILED(D3DCompileFromFile(vsFilename, nullptr, nullptr, "LightVertexShader""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, "LightPixelShader""ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
        &pixelShaderBuffer, &errorMessage)))
    {
        // 쉐이더 컴파일 실패시 오류메시지 출력.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
        }
        // 컴파일 오류가 아니라면 쉐이더 파일을 찾울 수 없는 경우이다.
        else
        {
            MessageBox(hwnd, psFilename, L"Missing PixelShade 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[3];
    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;
 
    polygonLayout[2].SemanticName = "NORMAL";
    polygonLayout[2].SemanticIndex = 0;
    polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
    polygonLayout[2].InputSlot = 0;
    polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
    polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[2].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;
    }
 
    // 텍스처 샘플러 상태 구조체를 생성 및 설정한다.
    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_BIND_CONSTANT_BUFFER를 사용하면 Bytewidth가 항상 16배수 어야하며 그렇지 않으면, CreateBuffer가 실패한다.
    D3D11_BUFFER_DESC lightBufferDesc;
    lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    lightBufferDesc.ByteWidth = sizeof(LightBufferType);
    lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    lightBufferDesc.MiscFlags = 0;
    lightBufferDesc.StructureByteStride = 0;
 
    // 이 클래스 내에서 정점 쉐이더 상수 버퍼에 엑세스 할 수 있도록 상수 버퍼 포인터를 만듭니다.
    if (FAILED(device->CreateBuffer(&lightBufferDesc, nullptr, &m_lightBuffer)))
    {
        return false;
    }
 
    return true;
 
}
 
void LightShaderClass::ShutdownShader()
{
    // light constant 버퍼 해제
    if (m_lightBuffer)
    {
        m_lightBuffer->Release();
        m_lightBuffer = nullptr;
    }
 
    // 샘플러 상태 해제
    if (m_sampleState)
    {
        m_sampleState->Release();
        m_sampleState = nullptr;
    }
 
    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 LightShaderClass::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 LightShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix,
    ID3D11ShaderResourceView* texture, XMFLOAT3 lightDirection, XMFLOAT4 diffuseColor)
{
    // 행렬을 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);
 
    // 픽셀 쉐이더에서 쉐이더 텍스처 리소스를 설정한다.
    deviceContext->PSSetShaderResources(01&texture);
 
    // light constant buffer를 잠글 수 있도록 기록한다.
    if(FAILED(deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 상수 버퍼의 데이터에 대한 포인터를 가져온다.
    LightBufferType* dataPtr2 = reinterpret_cast<LightBufferType*>(mappedResource.pData);
 
    // 조명 변수를 상수 버퍼에 복사한다.
    dataPtr2->diffuseColor = diffuseColor;
    dataPtr2->lightDirection = lightDirection;
    dataPtr2->padding = 0;
 
    // 상수 버퍼의 잠금을 해제한다.
    deviceContext->Unmap(m_lightBuffer, 0);
 
    // 픽셀 쉐이더에서 광원 상수 버퍼의 위치를 설정한다.
    bufferNumber = 0;
 
    // 마지막으로 업데이트 된 값으로 픽셀 쉐이더에서 광원 상수 버퍼를 설정한다.
    deviceContext->PSSetConstantBuffers(bufferNumber, 1&m_lightBuffer);
 
    return true;
}
 
void LightShaderClass::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

 

<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
44
45
46
47
48
49
50
51
52
#pragma once
#ifndef __MODELCLASS_H_
#define __MODELCLASS_H_
 
 
class TextureClass;
 
class ModelClass
{
private:
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
        XMFLOAT3 normal;
    };
 
public:
    ModelClass();
    ModelClass(const ModelClass& other);
    ~ModelClass();
 
    bool Initialize(ID3D11Device* device, const WCHAR* textureFilename);
    void Shutdown();
    void Render(ID3D11DeviceContext* deviceContext);
 
    int GetIndexCount();
    ID3D11ShaderResourceView* GetTexture();
 
private:
    bool InitializeBuffers(ID3D11Device* device);
    void ShutdownBuffers();
    void RenderBuffers(ID3D11DeviceContext*);
 
    // 텍스쳐 로드, 반환
    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;
};
 
 
#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
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
#include "stdafx.h"
#include "ModelClass.h"
 
#include "TextureClass.h"
 
ModelClass::ModelClass()
{
}
 
ModelClass::ModelClass(const ModelClass& other)
{
}
 
ModelClass::~ModelClass()
{
}
 
bool ModelClass::Initialize(ID3D11Device* device, const WCHAR* textureFilename)
{
    // 정점 및 인덱스 버퍼를 초기화합니다.
    if (!InitializeBuffers(device))
    {
        return false;
    }
 
    // 이 모델의 텍스처를 로드한다.
    return LoadTexture(device, textureFilename);
}
 
void ModelClass::Shutdown()
{
    // 모델 텍스처 반환
    ReleaseTexture();
 
    //버텍스 및 인덱스 버퍼 종료
    ShutdownBuffers();
}
 
void ModelClass::Render(ID3D11DeviceContext* deviceContext)
{
    // 그리기를 준비하기 위해 그래픽 파이프 라인에 꼭지점과 인덱스 버퍼를 놓는다.
    RenderBuffers(deviceContext);
}
 
int ModelClass::GetIndexCount()
{
    return m_indexCount;
}
 
ID3D11ShaderResourceView* ModelClass::GetTexture()
{
    return m_texture->GetTexture();
}
 
bool ModelClass::LoadTexture(ID3D11Device* device, const WCHAR* filename)
{
    // 텍스쳐클래스 객체 생성
    m_texture = new TextureClass;
 
 
    if (!m_texture)
    {
        return false;
    }
 
    // 객체 초기화
    return m_texture->Initialize(device, filename);
}
 
void ModelClass::ReleaseTexture()
{
    // 텍스쳐 클래스 객체 반환
    if (m_texture)
    {
        m_texture->Shutdown();
        delete m_texture;
        m_texture = nullptr;
    }
}
 
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].texture = XMFLOAT2(0.0f, 1.0f);
    vertices[0].normal = XMFLOAT3(0.0f, 0.0f, -1.0f);
 
    vertices[1].position = XMFLOAT3(-1.0f, 1.0f, 0.0f); // Top left
    vertices[1].texture = XMFLOAT2(0.0f, 0.0f);
    vertices[1].normal = XMFLOAT3(0.0f, 0.0f, -1.0f);
 
    vertices[2].position = XMFLOAT3(1.0f, 1.0f, 0.0f); // top right.
    vertices[2].texture = XMFLOAT2(1.0f, 0.0f);
    vertices[2].normal = XMFLOAT3(0.0f, 0.0f, -1.0f);
 
    vertices[3].position = XMFLOAT3(1.0f, -1.0f, 0.0f); // bottom right.
    vertices[3].texture = XMFLOAT2(1.0f, 1.0f);
    vertices[3].normal = XMFLOAT3(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

 

 

<LightClass.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
#pragma once
#ifndef _LIGHTCLASS_H_
#define _LIGHTCLASS_H_
 
class LightClass
{
public:
    LightClass();
    LightClass(const LightClass& other);
    ~LightClass();
 
    void SetDiffuseColor(float red, float green, float blue, float alpha);
    void SetDirection(float x, float y, float z);
 
    XMFLOAT4 GetDiffuseColor();
    XMFLOAT3 GetDirection();
 
 
private:
    XMFLOAT4 m_diffuseColor;
    XMFLOAT3 m_direction;
 
};
 
 
 
#endif // _LIGHTCLASS_H_
cs

 

<LightClass.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
#include "stdafx.h"
#include "LightClass.h"
 
LightClass::LightClass()
{
}
 
LightClass::LightClass(const LightClass& other)
{
}
 
LightClass::~LightClass()
{
}
 
void LightClass::SetDiffuseColor(float red, float green, float blue, float alpha)
{
    m_diffuseColor = XMFLOAT4(red, green, blue, alpha);
}
 
void LightClass::SetDirection(float x, float y, float z)
{
    m_direction = XMFLOAT3(x, y, z);
}
 
XMFLOAT4 LightClass::GetDiffuseColor()
{
    return m_diffuseColor;
}
 
XMFLOAT3 LightClass::GetDirection()
{
    return m_direction;
}
 
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
#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 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;
    //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
#include "stdafx.h"
#include "graphicsclass.h"
#include "D3dclass.h"
#include "CameraClass.h"
#include "ModelClass.h";
#include "LightShaderClass.h"
#include "LightClass.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(), 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->SetDiffuseColor(1.0f, 0.0f, 1.0f, 1.0f);
    m_Light->SetDirection(0.0f, 0.0f, 1.0f);
 
    return true;
}
 
void GraphicsClass::Shutdown()
{
    // 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.01f;
    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;
    m_D3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetProjectionMatrix(projectionMatrix);
 
    // 도형이 회전 할 수 있도록 회전 값으로 월드 행렬을 회전한다.
    worldMatrix = 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->GetDiffuseColor()))
    {
        return false;
    }
 
 
    // 텍스처 쉐이더를 사용하여 모델을 랜더링 한다.
    //if (!m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix,
    //    m_Model->GetTexture()))
    //{
    //    return false;
    //}
    
 
    // 버퍼에 그려진 씬을 화면에 표시합니다.
    m_D3D->EndScene();
 
    return true;
}
 
cs

 

 

< 결과 >

 

< 소스코드 >

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

 

 

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

 

 

<texture.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 TextureVertexShader(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

 

<texture.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
// GLOBALS
Texture2D shaderTexture;
SamplerState SampleType;
 
 
 
// Typedefs
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};
 
// Pixel Shader
 
float4 TexturePixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
 
    // 이 텍스쳐 좌표 위치에서 샘플러를 사용하여 텍스쳐에서 픽셀 색상을 샘플링 한다.
    textureColor = shaderTexture.Sample(SampleType, input.tex);
 
    return textureColor;
}
cs

 

<TextureClass.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
#pragma once
#ifndef _TEXTURECLASS_H_
#define _TEXTURECLASS_H_
 
 
class TextureClass
{
public:
    TextureClass();
    TextureClass(const TextureClass& other);
    ~TextureClass();
 
    bool Initialize(ID3D11Device* device, const WCHAR* filename);
    void Shutdown();
 
    ID3D11ShaderResourceView* GetTexture();
 
private:
 
    ID3D11Resource* m_texture = nullptr;
    ID3D11ShaderResourceView* m_textureView = nullptr;
 
};
 
 
#endif //_TEXTURECLASS_H_
cs

 

<TextureClass.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
#include "stdafx.h"
#include "TextureClass.h"
 
#include "DDSTextureLoader.h"
 
TextureClass::TextureClass()
{
}
 
TextureClass::TextureClass(const TextureClass& other)
{
}
 
TextureClass::~TextureClass()
{
}
 
bool TextureClass::Initialize(ID3D11Device* device, const WCHAR* filename)
{
    // 텍스쳐 로드
 
    if (FAILED(CreateDDSTextureFromFile(device, filename, &m_texture, &m_textureView)))
    {
        return false;
    }
 
    return true;
    
}
 
void TextureClass::Shutdown()
{
    // 텍스쳐 뷰 리로스 해제
    if (m_textureView)
    {
        m_textureView->Release();
        m_textureView = nullptr;
    }
 
    if (m_texture)
    {
        m_texture->Release();
        m_texture = nullptr;
    }
 
}
 
ID3D11ShaderResourceView* TextureClass::GetTexture()
{
    return m_textureView;
}
 
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
44
45
46
47
48
49
50
51
52
53
#pragma once
#ifndef __MODELCLASS_H_
#define __MODELCLASS_H_
 
 
class TextureClass;
 
class ModelClass
{
private:
    struct VertexType
    {
        XMFLOAT3 position;
        //XMFLOAT4 color;
        // 텍스쳐 용으로 변경
        XMFLOAT2 texture;
    };
 
public:
    ModelClass();
    ModelClass(const ModelClass& other);
    ~ModelClass();
 
    bool Initialize(ID3D11Device* device, const WCHAR* textureFilename);
    void Shutdown();
    void Render(ID3D11DeviceContext* deviceContext);
 
    int GetIndexCount();
    ID3D11ShaderResourceView* GetTexture();
 
private:
    bool InitializeBuffers(ID3D11Device* device);
    void ShutdownBuffers();
    void RenderBuffers(ID3D11DeviceContext*);
 
    // 텍스쳐 로드, 반환
    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;
};
 
 
#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
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
#include "stdafx.h"
#include "ModelClass.h"
 
#include "TextureClass.h"
 
ModelClass::ModelClass()
{
}
 
ModelClass::ModelClass(const ModelClass& other)
{
}
 
ModelClass::~ModelClass()
{
}
 
bool ModelClass::Initialize(ID3D11Device* device, const WCHAR* textureFilename)
{
    // 정점 및 인덱스 버퍼를 초기화합니다.
    if (!InitializeBuffers(device))
    {
        return false;
    }
 
    // 이 모델의 텍스처를 로드한다.
    return LoadTexture(device, textureFilename);
}
 
void ModelClass::Shutdown()
{
    // 모델 텍스처 반환
    ReleaseTexture();
 
    //버텍스 및 인덱스 버퍼 종료
    ShutdownBuffers();
}
 
void ModelClass::Render(ID3D11DeviceContext* deviceContext)
{
    // 그리기를 준비하기 위해 그래픽 파이프 라인에 꼭지점과 인덱스 버퍼를 놓는다.
    RenderBuffers(deviceContext);
}
 
int ModelClass::GetIndexCount()
{
    return m_indexCount;
}
 
ID3D11ShaderResourceView* ModelClass::GetTexture()
{
    return m_texture->GetTexture();
}
 
bool ModelClass::LoadTexture(ID3D11Device* device, const WCHAR* filename)
{
    // 텍스쳐클래스 객체 생성
    m_texture = new TextureClass;
 
 
    if (!m_texture)
    {
        return false;
    }
 
    // 객체 초기화
    return m_texture->Initialize(device, filename);
}
 
void ModelClass::ReleaseTexture()
{
    // 텍스쳐 클래스 객체 반환
    if (m_texture)
    {
        m_texture->Shutdown();
        delete m_texture;
        m_texture = nullptr;
    }
}
 
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[0].texture = XMFLOAT2(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[1].texture = XMFLOAT2(0.0f, 0.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[2].texture = XMFLOAT2(1.0f, 0.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);
    vertices[3].texture = XMFLOAT2(1.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

 

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

 

<TextureShaderClass.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 "TextureShaderClass.h"
 
TextureShaderClass::TextureShaderClass()
{
}
 
TextureShaderClass::TextureShaderClass(const TextureShaderClass& other)
{
}
 
TextureShaderClass::~TextureShaderClass()
{
}
 
bool TextureShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 및 픽셀 쉐이더 초기화
    return InitializeShader(device, hwnd, L"./texture.vs", L"./texture.ps");
}
 
void TextureShaderClass::Shutdown()
{
    // 버텍스 및 픽셀 쉐이더와 관련되 객체 종료
    ShutdownShader();
}
 
bool TextureShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture)
{
    // 렌더링에 사용할 쉐이더 매개 변수를 설정
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture))
    {
        return false;
    }
 
    // 설정된 버퍼를 쉐이더로 랜더링 한다.
    RenderShader(deviceContext, indexCount);
    return true;
}
 
bool TextureShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, const WCHAR* vsFilename, const WCHAR* psFilename)
{
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일 한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    if (FAILED(D3DCompileFromFile(vsFilename, nullptr, nullptr, "TextureVertexShader""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, "TexturePixelShader""ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
        &pixelShaderBuffer, &errorMessage)))
    {
        // 쉐이더 컴파일 실패시 오류메시지 출력.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
        }
        // 컴파일 오류가 아니라면 쉐이더 파일을 찾울 수 없는 경우이다.
        else
        {
            MessageBox(hwnd, psFilename, L"Missing PixelShade 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 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;
    }
 
    // 텍스처 샘플러 상태 구조체를 생성 및 설정한다.
    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;
    }
 
    return true;
 
}
 
void TextureShaderClass::ShutdownShader()
{
    // 샘플러 상태 해제
    if (m_sampleState)
    {
        m_sampleState->Release();
        m_sampleState = nullptr;
    }
 
    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 TextureShaderClass::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 TextureShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, XMMATRIX projectionMatrix,
    ID3D11ShaderResourceView* texture)
{
    // 행렬을 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);
 
    // 픽셀 쉐이더에서 쉐이더 텍스처 리소스를 설정한다.
    deviceContext->PSSetShaderResources(01&texture);
 
    return true;
}
 
void TextureShaderClass::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

 

<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
#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 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;
    TextureShaderClass* m_TextureShader = 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
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
#include "stdafx.h"
#include "graphicsclass.h"
#include "D3dclass.h"
#include "CameraClass.h"
#include "ModelClass.h";
#include "ColorshaderClass.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, -10.0f);
 
    // m_Model 객체 생성
    m_Model = new ModelClass;
    if (!m_Model)
    {
        return false;
    }
 
    // m_Model 초기화
    if (!m_Model->Initialize(m_D3D->GetDevice(), 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;
    }
 
    //// 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_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()
{
    
    //그래픽 렌더링을 수행합니다.
    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_TextureShader->Render(m_D3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix,
        m_Model->GetTexture()))
    {
        return false;
    }
 
 
    // 색상 쉐이더를 사용하여 모델을 랜더링 한다.
    /*if (!m_ColorShader->Render(m_D3D->GetDeviceContext(),
        m_Model->GetIndexCount(), worldMatrix, viewMatrix, projectionMatrix))
    {
        return false;
    }*/
 
    // 버퍼에 그려진 씬을 화면에 표시합니다.
    m_D3D->EndScene();
 
    return true;
}
 
cs

 

 

<DDSTextureLoader.h  and  DDSTextureLoader.cpp>

 

DDS 텍스처 로드는 다음 라이브러리를 사용한다.

https://github.com/microsoft/DirectXTex

위 깃허브에서 DDSTextureLoader의 DirectX 11 버전을 사용한다.

 

<결과>

<소스코드>

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

 

 

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