Thinking Different




Tutorial 20 - 범프 매핑



원문 : http://www.rastertek.com/dx11tut20.html



 이 튜토리얼에서는 HLSL 및 C++을 사용하여 DirectX 11에서 범프 매핑을 수행하는 방법에 대해 설명합니다. 이 튜토리얼의 코드는 이전 튜토리얼의 코드를 기반으로합니다.


 사실 범프 매핑의 올바른 명칭은 노멀 매핑(normal mapping)입니다. 그 이유는 범프 매핑을 하기 위해서는 노멀 맵(normal map)이라는 특별한 텍스쳐를 사용하기 때문인데, 노멀 맵은 표면의 법선(normal)을 구하기 위한 참조 테이블로서 사용됩니다.



 예제로 사용할 텍스쳐는 맨 왼쪽과 같고, 그 텍스쳐에 대응되는 노멀맵은 가운데와 같습니다. 노멀 맵을 사용하여 각 픽셀에서의 빛의 방향을 계산하면 맨 오른쪽 그림과 같은 울퉁불퉁한 느낌의 텍스쳐를 얻게 됩니다.



 단지 하나의 평면일 뿐이지만 딱 봐도 느낄 수 있는 것처럼 표현이 대단히 사실적인 데다가 같은 결과를 얻기 위해 많은 폴리곤들을 사용하는 것보다 비용이 훨씬 적게 듭니다.


 노멀 맵을 만들기 위해서는 대개 이미 만들어진 3D 모델을 노멀 맵으로 바꾸어주는 툴을 사용합니다. 물론 2D 텍스쳐만 가지고도 괜찮은 노멀 맵을 만들어주는 툴이 있기는 하지만 전자의 것보다는 퀄리티가 떨어집니다.


 노멀 맵을 만들어주는 툴은 x, y, z좌표를 가지고 해당 픽셀의 red, green, blue 값으로 넣게 되는데, 각 색상은 해당 픽셀에 있게 될 법선의 각도를 표현합니다. 도형의 법선은 여전히 이전과 같이 계산되지만 다른 두 종류의 법선을 계산하기 위해서는 정점과 텍스쳐 좌표의 정보가 필요합니다. 그 다른 두 법선은 각각 탄젠트 법선(tangent)과 종법선(binormal)이라고 합니다.


(역자주: 이 범프 매핑은 탄젠트 공간상의 법선을 노멀 맵에 저장합니다. 따라서 탄젠트 공간에 대한 설명이 필요한데 간단히 말하자면 탄젠트 공간은 normal이 항상 z축이 되는 공간입니다. 나머지 tangent축와 binormal축은 언제나 normal과 수직이며, tangent와 binormal끼리는 수직일 필요는 없습니다. 결국 tangent와 binormal은 같은 평면 위에 존재하는 축입니다.) 아래 그림은 각 법선들의 방향을 보여줍니다.



 법선은 언제나 보는 사람을 향해 뻗어 나갑니다. tangent와 binormal은 폴리곤 평면과 평행한데 tangent는 x축을, binormal은 y축 방향으로 표현됩니다. 이 두 법선은 노멀 맵 텍스쳐의 uv 좌표계에 바로 대응되는데, u좌표가 tangent, v좌표가 binormal이 됩니다.


 binormal과 tangent벡터를 구하기 위해서는 폴리곤의 법선과 텍스쳐 좌표를 이용한 몇 가지 계산을 미리 해야 합니다. 하지만 이 연산은 부동소수점 연산이 많아 비용이 많이 들기 때문에 셰이더에서 하면 안됩니다. 대신에 C++코드를 보면 모델을 불러올 때 이 연산을 하는 부분을 볼 수 있을 것입니다. 또한 범프 맵 효과를 많은 폴리곤으로 이루어진 모델에 적용하려고 할 때에도 서로 다른 법선들을 미리 계산해서 저장해 두는 것이 가장 좋습니다. 일단 tangent와 binormal을 계산했다면 다음 공식과 노멀 맵을 이용하여 변환된 법선을 구합니다.


bumpNormal = normal + bumpMap.x*tangent + bumpMap.y*binormal;



해당 픽셀의 노멀을 구했다면 빛의 방향과 계산하고 텍스쳐 색상을 곱해 최종 결과를 도출해 낼 수 있습니다.




이 튜토리얼의 프레임워크 구조는 다음과 같습니다. 새로운 클래스는 BumpMapShaderClass뿐입니다.


프레임워크





우선 범프맵 HLSL 셰이더 코드부터 시작해 보겠습니다.


Bumpmap.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
////////////////////////////////////////////////////////////////////////////////
// Filename: bumpmap.vs
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// GLOBALS //
/////////////
cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};
 
 
//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
    float3 tangent : TANGENT;
    float3 binormal : BINORMAL;
};
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
       float3 normal : NORMAL;
    float3 tangent : TANGENT;
    float3 binormal : BINORMAL;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType BumpMapVertexShader(VertexInputType input)
{
    PixelInputType output;
    
 
    // 적절한 행렬 계산을 위해 위치 벡터를 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);
 
    // 월드 행렬에 대해서만 접선 벡터를 계산 한 다음 최종 값을 정규화합니다.
    output.tangent = mul(input.tangent, (float3x3)worldMatrix);
    output.tangent = normalize(output.tangent);
 
    // 세계 행렬에 대해서만 비 유효 벡터를 계산 한 다음 최종 값을 정규화합니다.
    output.binormal = mul(input.binormal, (float3x3)worldMatrix);
    output.binormal = normalize(output.binormal);
 
    return output;
}
cs


Bumpmap.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
////////////////////////////////////////////////////////////////////////////////
// Filename: bumpmap.ps
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// GLOBALS //
/////////////
Texture2D shaderTextures[2];
SamplerState SampleType;
 
cbuffer LightBuffer
{
    float4 diffuseColor;
    float3 lightDirection;
};
 
 
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
       float3 normal : NORMAL;
    float3 tangent : TANGENT;
    float3 binormal : BINORMAL;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 BumpMapPixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
    float4 bumpMap;
    float3 bumpNormal;
    float3 lightDir;
    float lightIntensity;
    float4 color;
 
 
    // 이 위치에서 텍스처 픽셀을 샘플링합니다.
    textureColor = shaderTextures[0].Sample(SampleType, input.tex);
    
    // 범프 맵에서 픽셀을 샘플링합니다.
    bumpMap = shaderTextures[1].Sample(SampleType, input.tex);
 
    // 정상 값의 범위를 (0, +1)에서 (-1, +1)로 확장합니다.
    bumpMap = (bumpMap * 2.0f) - 1.0f;
    
    // 범프 맵의 데이터에서 법선을 계산합니다.
    bumpNormal = (bumpMap.x * input.tangent) + (bumpMap.y * input.binormal) + (bumpMap.z * input.normal);
    
    // 결과 범프 법선을 표준화합니다.
    bumpNormal = normalize(bumpNormal);
 
    // 계산을 위해 빛 방향을 반전시킵니다.
    lightDir = -lightDirection;
 
    // 범프 맵 일반 값을 기반으로 픽셀의 빛의 양을 계산합니다.
    lightIntensity = saturate(dot(bumpNormal, lightDir));
 
    // 확산 색과 광 강도의 양에 따라 최종 확산 색을 결정합니다.
    color = saturate(diffuseColor * lightIntensity);
 
    // 최종 범프 라이트 색상과 텍스처 색상을 결합합니다.
    color = color * textureColor;
    
    return color;
}
cs





BumpMapShaderClass 클래스는 이전 튜토리얼들의 셰이더 클래스를 변형한 것입니다.


BumpMapShaderClass.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
#pragma once
 
class BumpMapShaderClass
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
    struct LightBufferType
    {
        XMFLOAT4 diffuseColor;
        XMFLOAT3 lightDirection;
        float padding;
    };
 
public:
    BumpMapShaderClass();
    BumpMapShaderClass(const BumpMapShaderClass&);
    ~BumpMapShaderClass();
 
    bool Initialize(ID3D11Device*, HWND);
    void Shutdown();
    bool Render(ID3D11DeviceContext*int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView**, XMFLOAT3, XMFLOAT4);
 
private:
    bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
    void ShutdownShader();
    void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
 
    bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView**,
 XMFLOAT3, XMFLOAT4);
    void RenderShader(ID3D11DeviceContext*int);
 
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;
};
cs


BumpMapShaderClass.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#include "stdafx.h"
#include "BumpMapShaderClass.h"
 
 
BumpMapShaderClass::BumpMapShaderClass()
{
}
 
 
BumpMapShaderClass::BumpMapShaderClass(const BumpMapShaderClass& other)
{
}
 
 
BumpMapShaderClass::~BumpMapShaderClass()
{
}
 
 
bool BumpMapShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 및 픽셀 쉐이더를 초기화합니다.
    return InitializeShader(device, hwnd, L"../Dx11Demo_20/bumpmap.vs", L"../Dx11Demo_20/bumpmap.ps");
}
 
 
void BumpMapShaderClass::Shutdown()
{
    // 버텍스 및 픽셀 쉐이더와 관련된 객체를 종료합니다.
    ShutdownShader();
}
 
 
bool BumpMapShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, 
XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView** textureArray,
 XMFLOAT3 lightDirection, XMFLOAT4 diffuseColor)
{
    // 렌더링에 사용할 셰이더 매개 변수를 설정합니다.
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, textureArray, lightDirection,
 diffuseColor))
    {
        return false;
    }
 
    // 설정된 버퍼를 셰이더로 렌더링한다.
    RenderShader(deviceContext, indexCount);
 
    return true;
}
 
 
bool BumpMapShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
    HRESULT result;
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    result = D3DCompileFromFile(vsFilename, NULLNULL"BumpMapVertexShader""vs_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
    &vertexShaderBuffer, &errorMessage);
    if (FAILED(result))
    {
        // 셰이더 컴파일 실패시 오류메시지를 출력합니다.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, vsFilename);
        }
        // 컴파일 오류가 아니라면 셰이더 파일을 찾을 수 없는 경우입니다.
        else
        {
            MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK);
        }
 
        return false;
    }
 
    // 픽셀 쉐이더 코드를 컴파일한다.
    ID3D10Blob* pixelShaderBuffer = nullptr;
    result = D3DCompileFromFile(psFilename, NULLNULL"BumpMapPixelShader""ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
 &pixelShaderBuffer, &errorMessage);
    if (FAILED(result))
    {
        // 셰이더 컴파일 실패시 오류메시지를 출력합니다.
        if (errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, psFilename);
        }
        // 컴파일 오류가 아니라면 셰이더 파일을 찾을 수 없는 경우입니다.
        else
        {
            MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK);
        }
 
        return false;
    }
 
    // 버퍼로부터 정점 셰이더를 생성한다.
    result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL,
 &m_vertexShader);
    if (FAILED(result))
    {
        return false;
    }
 
    // 버퍼에서 픽셀 쉐이더를 생성합니다.
    result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL,
 &m_pixelShader);
    if (FAILED(result))
    {
        return false;
    }
 
    // 정점 입력 레이아웃 구조체를 설정합니다.
    // 이 설정은 ModelClass와 셰이더의 VertexType 구조와 일치해야합니다.
    D3D11_INPUT_ELEMENT_DESC polygonLayout[5];
    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;
 
    polygonLayout[3].SemanticName = "TANGENT";
    polygonLayout[3].SemanticIndex = 0;
    polygonLayout[3].Format = DXGI_FORMAT_R32G32B32_FLOAT;
    polygonLayout[3].InputSlot = 0;
    polygonLayout[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
    polygonLayout[3].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[3].InstanceDataStepRate = 0;
 
    polygonLayout[4].SemanticName = "BINORMAL";
    polygonLayout[4].SemanticIndex = 0;
    polygonLayout[4].Format = DXGI_FORMAT_R32G32B32_FLOAT;
    polygonLayout[4].InputSlot = 0;
    polygonLayout[4].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
    polygonLayout[4].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[4].InstanceDataStepRate = 0;
 
    // 레이아웃의 요소 수를 가져옵니다.
    UINT numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);
 
    // 정점 입력 레이아웃을 만듭니다.
    result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(),
        vertexShaderBuffer->GetBufferSize(), &m_layout);
    if (FAILED(result))
    {
        return false;
    }
 
    // 더 이상 사용되지 않는 정점 셰이더 퍼버와 픽셀 셰이더 버퍼를 해제합니다.
    vertexShaderBuffer->Release();
    vertexShaderBuffer = 0;
 
    pixelShaderBuffer->Release();
    pixelShaderBuffer = 0;
 
    // 정점 셰이더에 있는 행렬 상수 버퍼의 구조체를 작성합니다.
    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;
 
    // 상수 버퍼 포인터를 만들어 이 클래스에서 정점 셰이더 상수 버퍼에 접근할 수 있게 합니다.
    result = device->CreateBuffer(&matrixBufferDesc, NULL&m_matrixBuffer);
    if (FAILED(result))
    {
        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;
 
    // 텍스처 샘플러 상태를 만듭니다.
    result = device->CreateSamplerState(&samplerDesc, &m_sampleState);
    if (FAILED(result))
    {
        return false;
    }
 
    // 픽셀 쉐이더에있는 광원 동적 상수 버퍼의 설명을 설정합니다.
    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;
 
    // 이 클래스 내에서 정점 셰이더 상수 버퍼에 액세스 할 수 있도록 상수 버퍼 포인터를 만듭니다.
    result = device->CreateBuffer(&lightBufferDesc, NULL&m_lightBuffer);
    if(FAILED(result))
    {
        return false;
    }
 
    return true;
}
 
 
void BumpMapShaderClass::ShutdownShader()
{
    // 광원 상수 버퍼를 해제합니다.
    if(m_lightBuffer)
    {
        m_lightBuffer->Release();
        m_lightBuffer = 0;
    }
 
    // 샘플러 상태를 해제한다.
    if (m_sampleState)
    {
        m_sampleState->Release();
        m_sampleState = 0;
    }
 
    // 행렬 상수 버퍼를 해제합니다.
    if (m_matrixBuffer)
    {
        m_matrixBuffer->Release();
        m_matrixBuffer = 0;
    }    
 
    // 레이아웃을 해제합니다.
    if (m_layout)
    {
        m_layout->Release();
        m_layout = 0;
    }
 
    // 픽셀 쉐이더를 해제합니다.
    if (m_pixelShader)
    {
        m_pixelShader->Release();
        m_pixelShader = 0;
    }
 
    // 버텍스 쉐이더를 해제합니다.
    if (m_vertexShader)
    {
        m_vertexShader->Release();
        m_vertexShader = 0;
    }
}
 
 
void BumpMapShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, WCHAR* shaderFilename)
{
    // 에러 메시지를 출력창에 표시합니다.
    OutputDebugStringA(reinterpret_cast<const char*>(errorMessage->GetBufferPointer()));
 
    // 에러 메세지를 반환합니다.
    errorMessage->Release();
    errorMessage = 0;
 
    // 컴파일 에러가 있음을 팝업 메세지로 알려줍니다.
    MessageBox(hwnd, L"Error compiling shader.", shaderFilename, MB_OK);
}
 
bool BumpMapShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
    XMMATRIX projectionMatrix, ID3D11ShaderResourceView** textureArray, 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 = (MatrixBufferType*)mappedResource.pData;
 
    // 상수 버퍼에 행렬을 복사합니다.
    dataPtr->world = worldMatrix;
    dataPtr->view = viewMatrix;
    dataPtr->projection = projectionMatrix;
 
    // 상수 버퍼의 잠금을 풉니다.
    deviceContext->Unmap(m_matrixBuffer, 0);
 
    // 정점 셰이더에서의 상수 버퍼의 위치를 설정합니다.
    unsigned int bufferNumber = 0;
 
    // 마지막으로 정점 셰이더의 상수 버퍼를 바뀐 값으로 바꿉니다.
    deviceContext->VSSetConstantBuffers(bufferNumber, 1&m_matrixBuffer);
 
    // 픽셀 셰이더에 셰이더 텍스처 배열 리소스를 설정합니다.
    deviceContext->PSSetShaderResources(02, textureArray);
 
    // light constant buffer를 잠글 수 있도록 기록한다.
    if(FAILED(deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 상수 버퍼의 데이터에 대한 포인터를 가져옵니다.
    LightBufferType* dataPtr2 = (LightBufferType*)mappedResource.pData;
 
    // 조명 변수를 상수 버퍼에 복사합니다.
    dataPtr2->diffuseColor = diffuseColor;
    dataPtr2->lightDirection = lightDirection;
 
    // 상수 버퍼의 잠금을 해제합니다.
    deviceContext->Unmap(m_lightBuffer, 0);
 
    // 픽셀 쉐이더에서 광원 상수 버퍼의 위치를 ​​설정합니다.
    bufferNumber = 0;
 
    // 마지막으로 업데이트 된 값으로 픽셀 쉐이더에서 광원 상수 버퍼를 설정합니다.
    deviceContext->PSSetConstantBuffers(bufferNumber, 1&m_lightBuffer);
 
    return true;
}
 
 
void BumpMapShaderClass::RenderShader(ID3D11DeviceContext* deviceContext, int indexCount)
{
    // 정점 입력 레이아웃을 설정합니다.
    deviceContext->IASetInputLayout(m_layout);
 
    // 삼각형을 그릴 정점 셰이더와 픽셀 셰이더를 설정합니다.
    deviceContext->VSSetShader(m_vertexShader, NULL0);
    deviceContext->PSSetShader(m_pixelShader, NULL0);
 
    // 픽셀 쉐이더에서 샘플러 상태를 설정합니다.
    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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#pragma once
 
class TextureArrayClass;
 
class ModelClass
{
private:
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
        XMFLOAT3 normal;
        XMFLOAT3 tangent;
        XMFLOAT3 binormal;
    };
 
    struct ModelType
    {
        float x, y, z;
        float tu, tv;
        float nx, ny, nz;
        float tx, ty, tz;
        float bx, by, bz;
    };
 
    struct TempVertexType
    {
        float x, y, z;
        float tu, tv;
        float nx, ny, nz;
    };
 
    struct VectorType
    {
        float x, y, z;
    };
 
public:
    ModelClass();
    ModelClass(const ModelClass&);
    ~ModelClass();
 
    bool Initialize(ID3D11Device*char*, WCHAR*, WCHAR*);
    void Shutdown();
    void Render(ID3D11DeviceContext*);
 
    int GetIndexCount();
    ID3D11ShaderResourceView** GetTextureArray();
 
private:
    bool InitializeBuffers(ID3D11Device*);
    void ShutdownBuffers();
    void RenderBuffers(ID3D11DeviceContext*);
 
    bool LoadTextures(ID3D11Device*, WCHAR*, WCHAR*);
    void ReleaseTextures();
 
    bool LoadModel(char*);
    void ReleaseModel();
 
    void CalculateModelVectors();
    void CalculateTangentBinormal(TempVertexType, TempVertexType, TempVertexType, VectorType&, VectorType&);
    void CalculateNormal(VectorType, VectorType, VectorType&);
 
private:
    ID3D11Buffer* m_vertexBuffer = nullptr;
    ID3D11Buffer* m_indexBuffer = nullptr;
    int m_vertexCount = 0;
    int m_indexCount = 0;
    ModelType* m_model = nullptr;
    TextureArrayClass* m_TextureArray = nullptr;
};
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#include "stdafx.h"
#include "TextureArrayClass.h"
#include "modelclass.h"
 
#include <fstream>
using namespace std;
 
 
ModelClass::ModelClass()
{
}
 
 
ModelClass::ModelClass(const ModelClass& other)
{
}
 
 
ModelClass::~ModelClass()
{
}
 
 
bool ModelClass::Initialize(ID3D11Device* device, char* modelFilename, WCHAR* textureFilename1, WCHAR* textureFilename2)
{
    // 모델 데이터를 로드합니다.
    if (!LoadModel(modelFilename))
    {
        return false;
    }
 
    // 모델의 법선, 접선 및 이항 벡터를 계산합니다.
    CalculateModelVectors();
 
    // 정점 및 인덱스 버퍼를 초기화합니다.
    if (!InitializeBuffers(device))
    {
        return false;
    }
 
    // 이 모델의 텍스처를 로드합니다.
    return LoadTextures(device, textureFilename1, textureFilename2);
}
 
 
void ModelClass::Shutdown()
{
    // 모델 텍스쳐를 반환합니다.
    ReleaseTextures();
 
    // 버텍스 및 인덱스 버퍼를 종료합니다.
    ShutdownBuffers();
 
    // 모델 데이터 반환
    ReleaseModel();
}
 
 
void ModelClass::Render(ID3D11DeviceContext* deviceContext)
{
    // 그리기를 준비하기 위해 그래픽 파이프 라인에 꼭지점과 인덱스 버퍼를 놓습니다.
    RenderBuffers(deviceContext);
}
 
 
int ModelClass::GetIndexCount()
{
    return m_indexCount;
}
 
 
ID3D11ShaderResourceView** ModelClass::GetTextureArray()
{
    return m_TextureArray->GetTextureArray();
}
 
 
bool ModelClass::InitializeBuffers(ID3D11Device* device)
{
    // 정점 배열을 만듭니다.
    VertexType* vertices = new VertexType[m_vertexCount];
    if (!vertices)
    {
        return false;
    }
 
    // 인덱스 배열을 만듭니다.
    unsigned long* indices = new unsigned long[m_indexCount];
    if (!indices)
    {
        return false;
    }
 
    // 정점 배열과 인덱스 배열을 데이터로 읽어옵니다.
    for (int i = 0; i < m_vertexCount; i++)
    {
        vertices[i].position = XMFLOAT3(m_model[i].x, m_model[i].y, m_model[i].z);
        vertices[i].texture = XMFLOAT2(m_model[i].tu, m_model[i].tv);
        vertices[i].normal = XMFLOAT3(m_model[i].nx, m_model[i].ny, m_model[i].nz);
        vertices[i].tangent = XMFLOAT3(m_model[i].tx, m_model[i].ty, m_model[i].tz);
        vertices[i].binormal = XMFLOAT3(m_model[i].bx, m_model[i].by, m_model[i].bz);
 
        indices[i] = i;
    }
 
    // 정적 정점 버퍼의 구조체를 설정합니다.
    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;
 
    // subresource 구조에 정점 데이터에 대한 포인터를 제공합니다.
    D3D11_SUBRESOURCE_DATA vertexData;
    vertexData.pSysMem = vertices;
    vertexData.SysMemPitch = 0;
    vertexData.SysMemSlicePitch = 0;
 
    // 이제 정점 버퍼를 만듭니다.
    if (FAILED(device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer)))
    {
        return false;
    }
 
    // 정적 인덱스 버퍼의 구조체를 설정합니다.
    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 = 0;
 
    delete[] indices;
    indices = 0;
 
    return true;
}
 
 
void ModelClass::ShutdownBuffers()
{
    // 인덱스 버퍼를 해제합니다.
    if (m_indexBuffer)
    {
        m_indexBuffer->Release();
        m_indexBuffer = 0;
    }
 
    // 정점 버퍼를 해제합니다.
    if (m_vertexBuffer)
    {
        m_vertexBuffer->Release();
        m_vertexBuffer = 0;
    }
}
 
 
void ModelClass::RenderBuffers(ID3D11DeviceContext* deviceContext)
{
    // 정점 버퍼의 단위와 오프셋을 설정합니다.
    UINT stride = sizeof(VertexType);
    UINT offset = 0;
 
    // 렌더링 할 수 있도록 입력 어셈블러에서 정점 버퍼를 활성으로 설정합니다.
    deviceContext->IASetVertexBuffers(01&m_vertexBuffer, &stride, &offset);
 
    // 렌더링 할 수 있도록 입력 어셈블러에서 인덱스 버퍼를 활성으로 설정합니다.
    deviceContext->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);
 
    // 정점 버퍼로 그릴 기본형을 설정합니다. 여기서는 삼각형으로 설정합니다.
    deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
 
 
bool ModelClass::LoadTextures(ID3D11Device* device, WCHAR* filename1, WCHAR* filename2)
{
    // 텍스처 배열 오브젝트를 생성한다.
    m_TextureArray = new TextureArrayClass;
    if (!m_TextureArray)
    {
        return false;
    }
 
    // 텍스처 배열 오브젝트를 초기화한다.
    return m_TextureArray->Initialize(device, filename1, filename2);
}
 
 
void ModelClass::ReleaseTextures()
{
    // 텍스처 배열 오브젝트를 릴리즈한다.
    if (m_TextureArray)
    {
        m_TextureArray->Shutdown();
        delete m_TextureArray;
        m_TextureArray = 0;
    }
}
 
bool ModelClass::LoadModel(char* filename)
{
    // 모델 파일을 엽니다.
    ifstream fin;
    fin.open(filename);
 
    // 파일을 열 수 없으면 종료합니다.
    if (fin.fail())
    {
        return false;
    }
 
    // 버텍스 카운트의 값까지 읽는다.
    char input = 0;
    fin.get(input);
    while (input != ':')
    {
        fin.get(input);
    }
 
    // 버텍스 카운트를 읽는다.
    fin >> m_vertexCount;
 
    // 인덱스의 수를 정점 수와 같게 설정합니다.
    m_indexCount = m_vertexCount;
 
    // 읽어 들인 정점 개수를 사용하여 모델을 만듭니다.
    m_model = new ModelType[m_vertexCount];
    if (!m_model)
    {
        return false;
    }
 
    // 데이터의 시작 부분까지 읽는다.
    fin.get(input);
    while (input != ':')
    {
        fin.get(input);
    }
    fin.get(input);
    fin.get(input);
 
    // 버텍스 데이터를 읽습니다.
    for (int i = 0; i < m_vertexCount; i++)
    {
        fin >> m_model[i].x >> m_model[i].y >> m_model[i].z;
        fin >> m_model[i].tu >> m_model[i].tv;
        fin >> m_model[i].nx >> m_model[i].ny >> m_model[i].nz;
    }
 
    // 모델 파일을 닫는다.
    fin.close();
 
    return true;
}
 
 
void ModelClass::ReleaseModel()
{
    if (m_model)
    {
        delete[] m_model;
        m_model = 0;
    }
}
 
 
void ModelClass::CalculateModelVectors()
{
    TempVertexType vertex1, vertex2, vertex3;
    VectorType tangent, binormal, normal;
 
 
    // 모델의 면 수를 계산합니다.
    int faceCount = m_vertexCount / 3;
 
    // 모델 데이터에 대한 인덱스를 초기화합니다.
    int index = 0;
 
    // 모든면을 살펴보고 접선, 비공식 및 법선 벡터를 계산합니다.
    for(int i=0; i<faceCount; i++)
    {
        // 모델에서이면에 대한 세 개의 정점을 가져옵니다.
        vertex1.x = m_model[index].x;
        vertex1.y = m_model[index].y;
        vertex1.z = m_model[index].z;
        vertex1.tu = m_model[index].tu;
        vertex1.tv = m_model[index].tv;
        vertex1.nx = m_model[index].nx;
        vertex1.ny = m_model[index].ny;
        vertex1.nz = m_model[index].nz;
        index++;
 
        vertex2.x = m_model[index].x;
        vertex2.y = m_model[index].y;
        vertex2.z = m_model[index].z;
        vertex2.tu = m_model[index].tu;
        vertex2.tv = m_model[index].tv;
        vertex2.nx = m_model[index].nx;
        vertex2.ny = m_model[index].ny;
        vertex2.nz = m_model[index].nz;
        index++;
 
        vertex3.x = m_model[index].x;
        vertex3.y = m_model[index].y;
        vertex3.z = m_model[index].z;
        vertex3.tu = m_model[index].tu;
        vertex3.tv = m_model[index].tv;
        vertex3.nx = m_model[index].nx;
        vertex3.ny = m_model[index].ny;
        vertex3.nz = m_model[index].nz;
        index++;
 
        // 표면의 탄젠트와 바이 노멀을 계산합니다.
        CalculateTangentBinormal(vertex1, vertex2, vertex3, tangent, binormal);
 
        // 접선과 binormal을 사용하여 새 법선을 계산합니다.
        CalculateNormal(tangent, binormal, normal);
 
        // 모델 구조에서 면의 법선, 접선 및 바이 노멀을 저장합니다.
        m_model[index-1].nx = normal.x;
        m_model[index-1].ny = normal.y;
        m_model[index-1].nz = normal.z;
        m_model[index-1].tx = tangent.x;
        m_model[index-1].ty = tangent.y;
        m_model[index-1].tz = tangent.z;
        m_model[index-1].bx = binormal.x;
        m_model[index-1].by = binormal.y;
        m_model[index-1].bz = binormal.z;
 
        m_model[index-2].nx = normal.x;
        m_model[index-2].ny = normal.y;
        m_model[index-2].nz = normal.z;
        m_model[index-2].tx = tangent.x;
        m_model[index-2].ty = tangent.y;
        m_model[index-2].tz = tangent.z;
        m_model[index-2].bx = binormal.x;
        m_model[index-2].by = binormal.y;
        m_model[index-2].bz = binormal.z;
 
        m_model[index-3].nx = normal.x;
        m_model[index-3].ny = normal.y;
        m_model[index-3].nz = normal.z;
        m_model[index-3].tx = tangent.x;
        m_model[index-3].ty = tangent.y;
        m_model[index-3].tz = tangent.z;
        m_model[index-3].bx = binormal.x;
        m_model[index-3].by = binormal.y;
        m_model[index-3].bz = binormal.z;
    }
}
 
 
void ModelClass::CalculateTangentBinormal(TempVertexType vertex1, TempVertexType vertex2, TempVertexType vertex3,
                                          VectorType& tangent, VectorType& binormal)
{
    float vector1[3], vector2[3];
    float tuVector[2], tvVector[2];
 
 
    // 현재 표면의 두 벡터를 계산합니다.
    vector1[0= vertex2.x - vertex1.x;
    vector1[1= vertex2.y - vertex1.y;
    vector1[2= vertex2.z - vertex1.z;
 
    vector2[0= vertex3.x - vertex1.x;
    vector2[1= vertex3.y - vertex1.y;
    vector2[2= vertex3.z - vertex1.z;
 
    // tu 및 tv 텍스처 공간 벡터를 계산합니다.
    tuVector[0= vertex2.tu - vertex1.tu;
    tvVector[0= vertex2.tv - vertex1.tv;
 
    tuVector[1= vertex3.tu - vertex1.tu;
    tvVector[1= vertex3.tv - vertex1.tv;
 
    // 탄젠트 / 바이 노멀 방정식의 분모를 계산합니다.
    float den = 1.0f / (tuVector[0* tvVector[1- tuVector[1* tvVector[0]);
 
    // 교차 곱을 계산하고 계수로 곱하여 접선과 비 구식을 얻습니다.
    tangent.x = (tvVector[1* vector1[0- tvVector[0* vector2[0]) * den;
    tangent.y = (tvVector[1* vector1[1- tvVector[0* vector2[1]) * den;
    tangent.z = (tvVector[1* vector1[2- tvVector[0* vector2[2]) * den;
 
    binormal.x = (tuVector[0* vector2[0- tuVector[1* vector1[0]) * den;
    binormal.y = (tuVector[0* vector2[1- tuVector[1* vector1[1]) * den;
    binormal.z = (tuVector[0* vector2[2- tuVector[1* vector1[2]) * den;
 
    // 이 법선의 길이를 계산합니다.
    float length = sqrt((tangent.x * tangent.x) + (tangent.y * tangent.y) + (tangent.z * tangent.z));
            
    // 법선을 표준화 한 다음 저장합니다.
    tangent.x = tangent.x / length;
    tangent.y = tangent.y / length;
    tangent.z = tangent.z / length;
 
    // 이 법선의 길이를 계산합니다.
    length = sqrt((binormal.x * binormal.x) + (binormal.y * binormal.y) + (binormal.z * binormal.z));
            
    // 법선을 표준화 한 다음 저장합니다.
    binormal.x = binormal.x / length;
    binormal.y = binormal.y / length;
    binormal.z = binormal.z / length;
}
 
 
void ModelClass::CalculateNormal(VectorType tangent, VectorType binormal, VectorType& normal)
{
    // 법선 벡터를 줄 수있는 접선과 binormal의 외적을 계산합니다.
    normal.x = (tangent.y * binormal.z) - (tangent.z * binormal.y);
    normal.y = (tangent.z * binormal.x) - (tangent.x * binormal.z);
    normal.z = (tangent.x * binormal.y) - (tangent.y * binormal.x);
 
    // 법선의 길이를 계산합니다.
    float length = sqrt((normal.x * normal.x) + (normal.y * normal.y) + (normal.z * normal.z));
 
    // 법선을 표준화합니다.
    normal.x = normal.x / length;
    normal.y = normal.y / length;
    normal.z = normal.z / length;
}
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
#pragma once
 
/////////////
// GLOBALS //
/////////////
const bool FULL_SCREEN = false;
const bool VSYNC_ENABLED = true;
const float SCREEN_DEPTH = 1000.0f;
const float SCREEN_NEAR = 0.1f;
 
 
class D3DClass;
class CameraClass;
class ModelClass;
class BumpMapShaderClass;
class LightClass;
 
 
class GraphicsClass
{
public:
    GraphicsClass();
    GraphicsClass(const GraphicsClass&);
    ~GraphicsClass();
 
    bool Initialize(intint, HWND);
    void Shutdown();
    bool Frame();
    bool Render();
 
private:
    D3DClass* m_Direct3D = nullptr;
    CameraClass* m_Camera = nullptr;
    ModelClass* m_Model = nullptr;
    BumpMapShaderClass* m_BumpMapShader = nullptr;
    LightClass* m_Light = nullptr;
};
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
#include "stdafx.h"
#include "d3dclass.h"
#include "cameraclass.h"
#include "modelclass.h"
#include "BumpMapShaderClass.h"
#include "LightClass.h"
#include "graphicsclass.h"
 
 
GraphicsClass::GraphicsClass()
{
}
 
 
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
 
 
GraphicsClass::~GraphicsClass()
{
}
 
 
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
    // Direct3D 객체 생성
    m_Direct3D = new D3DClass;
    if (!m_Direct3D)
    {
        return false;
    }
 
    // Direct3D 객체 초기화
    if (!m_Direct3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR))
    {
        MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK);
        return false;
    }
 
    // m_Camera 객체 생성
    m_Camera = new CameraClass;
    if (!m_Camera)
    {
        return false;
    }
 
    // 카메라 포지션 설정
    XMMATRIX baseViewMatrix;
    m_Camera->SetPosition(0.0f, 0.0f, -1.0f);
    m_Camera->Render();
    m_Camera->GetViewMatrix(baseViewMatrix);
 
    // 모델 객체 생성
    m_Model = new ModelClass;
    if (!m_Model)
    {
        return false;
    }
 
    // 모델 객체 초기화
    if (!m_Model->Initialize(m_Direct3D->GetDevice(), "../Dx11Demo_20/data/cube.txt",    L"../Dx11Demo_20/data/stone01.dds",
                                                    L"../Dx11Demo_20/data/bump01.dds"))
    {
        MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
        return false;
    }
 
    // 범프 맵 쉐이더 객체를 생성합니다.
    m_BumpMapShader = new BumpMapShaderClass;
    if(!m_BumpMapShader)
    {
        return false;
    }
 
    // 범프 맵 쉐이더 객체를 초기화한다.
    if(!m_BumpMapShader->Initialize(m_Direct3D->GetDevice(), hwnd))
    {
        MessageBox(hwnd, L"Could not initialize the bump map shader object.", L"Error", MB_OK);
        return false;
    }
 
    // 조명 객체를 만듭니다.
    m_Light = new LightClass;
    if(!m_Light)
    {
        return false;
    }
 
    // 조명 객체를 초기화합니다.
    m_Light->SetDiffuseColor(1.0f, 1.0f, 1.0f, 1.0f);
    m_Light->SetDirection(0.0f, 0.0f, 1.0f);
    
    return true;
}
 
 
void GraphicsClass::Shutdown()
{
    // 조명 객체를 해제한다.
    if(m_Light)
    {
        delete m_Light;
        m_Light = 0;
    }
 
    // 범프 맵 쉐이더 객체를 해제한다.
    if(m_BumpMapShader)
    {
        m_BumpMapShader->Shutdown();
        delete m_BumpMapShader;
        m_BumpMapShader = 0;
    }
 
    // 모델 객체 반환
    if (m_Model)
    {
        m_Model->Shutdown();
        delete m_Model;
        m_Model = 0;
    }
 
    // m_Camera 객체 반환
    if (m_Camera)
    {
        delete m_Camera;
        m_Camera = 0;
    }
 
    // Direct3D 객체 반환
    if (m_Direct3D)
    {
        m_Direct3D->Shutdown();
        delete m_Direct3D;
        m_Direct3D = 0;
    }
}
 
 
bool GraphicsClass::Frame()
{
    // 카메라 위치 설정
    m_Camera->SetPosition(0.0f, 0.0f, -5.0f);
 
    return true;
}
 
 
bool GraphicsClass::Render()
{
    // 씬을 그리기 위해 버퍼를 지웁니다
    m_Direct3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져옵니다
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix, orthoMatrix;
    m_Camera->GetViewMatrix(viewMatrix);
    m_Direct3D->GetWorldMatrix(worldMatrix);
    m_Direct3D->GetProjectionMatrix(projectionMatrix);
    m_Direct3D->GetOrthoMatrix(orthoMatrix);
 
    // 각 프레임의 rotation 변수를 업데이트합니다.
    static float rotation = 0.0f;
    rotation += (float)XM_PI * 0.0025f;
    if(rotation > 360.0f)
    {
        rotation -= 360.0f;
    }
 
    // 회전 값으로 월드 행렬을 회전합니다.
    worldMatrix = XMMatrixRotationY(rotation);
 
    // 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 렌더링 합니다.
    m_Model->Render(m_Direct3D->GetDeviceContext());
 
 
        // 범프 맵 셰이더를 사용하여 모델을 렌더링합니다.
    m_BumpMapShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix, 
projectionMatrix, m_Model->GetTextureArray(), m_Light->GetDirection(), 
m_Light->GetDiffuseColor());
 
    // 버퍼의 내용을 화면에 출력합니다
    m_Direct3D->EndScene();
 
    return true;
}
cs




출력 화면




마치면서


범프맵 셰이더를 통해 단지 2개의 텍스쳐만으로도 매우 정교한 화면을 만들 수 있습니다.



연습문제


1. 프로그램을 다시 컴파일해 실행시켜 보십시오. 범프맵 효과가 적용된 회전하는 큐브가 보일 것입니다. esc키를 눌러 종료합니다.


2. 픽셀 셰이더 코드에서 'color = color * textureColor;' 부분을 주석 처리하고 어떻게 효과가 달라지는지 확인해 보십시오.


3. 카메라와 광원의 위치를 바꿔 가면서 다른 각도에서의 효과를 확인해 보십시오.



소스코드


소스코드 : Dx11Demo_20.zip