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

 

<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
48
49
50
51
52
53
54
55
56
57
// GLOBALS
Texture2D shaderTexture;
SamplerState SampleType;
 
cbuffer LightBuffer
{
    float4 ambientColor;
    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);
 
    // 모든 픽셀에 색상을 기본으로 주변광으로 설정한다.
    color = ambientColor;
 
    // 계산을 위해 빛 방향을 반전시킨다.
    lightDir = -lightDirection;
 
    // 이 픽셀의 빛의 양을 계산한다.
    lightIntensity = saturate(dot(input.normal, lightDir));
 
    if (lightIntensity > 0.0f)
    {
        // 법선과 빛의 방향의 내적이 0보다 클때만 조명값을 주변광에 더해준다.
        color += (diffuseColor * lightIntensity);
    }
 
    // 주변광과 조명의 조합의 결과가 1이 넘을 수 있으므로 saturate함수로 최종 색상이 적절한 값이 되도록 잘라낸다.
    color = saturate(color);
 
    // 텍스쳐 픽셀과 최종 확산 색을 곱하여 최종 픽셀 색상 결과를 얻습니다.
    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
56
#pragma once
#ifndef _LIGHTSHADERCLASS_H_
#define _LIGHTSHADERCLASS_H_
 
class LightShaderClass
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
    struct LightBufferType
    {
        XMFLOAT4 ambientColor;
        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 ambientColor, 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 ambientColor, 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
330
#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 ambientColor, XMFLOAT4 diffuseColor)
{
    // 렌더링에 사용할 쉐이더 매개 변수를 설정
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, lightDirection, ambientColor, 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 ambientColor, 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->ambientColor = ambientColor;
    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

 

<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
28
29
30
#pragma once
#ifndef _LIGHTCLASS_H_
#define _LIGHTCLASS_H_
 
class LightClass
{
public:
    LightClass();
    LightClass(const LightClass& other);
    ~LightClass();
 
    void SetAmbientColor(float red, float green, float blue, float alpha);
    void SetDiffuseColor(float red, float green, float blue, float alpha);
    void SetDirection(float x, float y, float z);
 
    XMFLOAT4 GetAmbientColor();
    XMFLOAT4 GetDiffuseColor();
    XMFLOAT3 GetDirection();
 
 
private:
    XMFLOAT4 m_ambientColor;
    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
36
37
38
39
40
41
42
43
44
45
#include "stdafx.h"
#include "LightClass.h"
 
LightClass::LightClass()
{
}
 
LightClass::LightClass(const LightClass& other)
{
}
 
LightClass::~LightClass()
{
}
 
void LightClass::SetAmbientColor(float red, float green, float blue, float alpha)
{
    m_ambientColor = XMFLOAT4(red, green, blue, alpha);
}
 
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::GetAmbientColor()
{
    return m_ambientColor;
}
 
XMFLOAT4 LightClass::GetDiffuseColor()
{
    return m_diffuseColor;
}
 
XMFLOAT3 LightClass::GetDirection()
{
    return m_direction;
}
 
cs

 

<GraphicsClass.cpp>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#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(), "./cube.txt", L"./Textures/WoodCrate01.dds"))
    {
        MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
    }
 
    // 텍스쳐 쉐이더 객체 생성
    //m_TextureShader = new TextureShaderClass;
    //if (!m_TextureShader)
    //{
    //    return false;
    //}
 
    //// 텍스터 쉐이더 객테 초기화
    //if (!m_TextureShader->Initialize(m_D3D->GetDevice(), hwnd))
    //{
    //    MessageBox(hwnd, L"Could not initialize texture shader object.", L"Error", MB_OK);
    //    return false;
    //}
 
    // LightShaderClass 객체 생성
    m_LightShader = new LightShaderClass;
    if (!m_LightShader)
    {
        return false;
    }
 
    // LightShader 객체를 초기화한다.
    if (!m_LightShader->Initialize(m_D3D->GetDevice(), hwnd))
    {
        MessageBox(hwnd, L"Could not initialize the light shader object.", L"Error", MB_OK);
        return false;
    }
 
    // LightClass 객체 생성
    m_Light = new LightClass;
    if (!m_Light)
    {
        return false;
    }
 
    // Light 객체 초기화
    m_Light->SetAmbientColor(0.15f, 0.15f, 0.15f, 1.0f);
    m_Light->SetDiffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
    m_Light->SetDirection(1.0f, 0.0f, 0.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.005f;
    if (rotation > 360.0f)
    {
        rotation -= 360.0f;
    }
    //그래픽 렌더링을 수행합니다.
    if (!Render(rotation))
    {
        
        return false;
    }
    return true;
}
 
bool GraphicsClass::Render(float rotation)
{
    // 씬 그리기를 시작하기 위해 버퍼의 내용을 지웁니다.
    m_D3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성한다.
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져온다.
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
    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->GetAmbientColor(), 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_7

 

 

 

+ Recent posts