Thinking Different




Tutorial 10 - 정반사광



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



이 듀토리얼에서는 DirectX 11에서 HLSL을 사용하여 정반사광을 사용하는 방법을 소개합니다. 이 듀토리얼의 코드는 이전 듀토리얼의 코드를 기반으로합니다.


정반사광은 밝은 점광원의 위치가 어디인지 알려주는 단서의 역할을 합니다. 예를 들어 단순 조명과 주변광이 적용된 빨간 구체가 있다면 왼쪽과 같을 것입니다.



여기에 정반사광을 적용하면 오른쪽 구체와 같이 나타날 것입니다. 보다 사실적이게 보이지요?


정반사광은 거울이나 광택이 잘되고 반사되는 금속 표면과 같은 금속 표면에서 빛을 반사시키는 데 가장 일반적으로 사용됩니다. 물의 햇빛 반사와 같은 다른 재료에도 사용됩니다. 잘 사용하면 대부분의 3D 장면에 어느 정도 사실적인 사진을 추가 할 수 있습니다.


정반사광의 방정식은 다음과 같습니다.

반사광 = 반사색 * ( 반사된빛의색 * ((법선과 하프벡터의 내적) ^ 반사강도) * 감쇄계수 * 스폿라이트계수 )


기본적인 정반사광 효과만을 위해 다음과 같이 식을 수정합니다.

반사광 = 반사빛의색 * (보는방향과 반사광의 내적) ^ 반사강도


이 식에서 반사광 벡터는 빛의 강도의 두배의 크기를 정점의 법선에 곱하고 여기에 빛의 방향을 빼서 얻어집니다.

반사벡터 = 2 * 빛의강도 * 법선 - 빛의방향


식에서 보는방향은 카메라의 위치에서 정점의 위치를 뺌으로 계산됩니다.

보는방향 = 카메라위치 - 정점위치






이제 수정된 라이트 쉐이더를 살펴보고 이것이 어떻게 구현되는지 살펴 봅니다.


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
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
////////////////////////////////////////////////////////////////////////////////
// Filename: light.vs
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// GLOBALS //
/////////////
cbuffer MatrixBuffer : register( b0 )
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};
 
cbuffer CameraBuffer
{
    float3 cameraPosition;
    float padding;
};
 
//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};
 
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
    float3 viewDirection : TEXCOORD1;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType LightVertexShader(VertexInputType input)
{
    PixelInputType output = (PixelInputType)0;
    
 
    // 적절한 행렬 계산을 위해 위치 벡터를 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);
 
    // 세계의 정점 위치를 계산합니다.
    float4 worldPosition = mul(input.position, worldMatrix);
 
    // 카메라의 위치와 세계의 정점 위치를 기준으로 보기 방향을 결정합니다.
    output.viewDirection = cameraPosition.xyz - worldPosition.xyz;
    
    // 뷰 방향 벡터를 표준화합니다.
    output.viewDirection = normalize(output.viewDirection);
 
    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
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
////////////////////////////////////////////////////////////////////////////////
// Filename: light.ps
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// GLOBALS //
/////////////
Texture2D shaderTexture;
SamplerState SampleType;
 
cbuffer LightBuffer
{
    float4 ambientColor;
    float4 diffuseColor;
    float3 lightDirection;
    float specularPower;
    float4 specularColor;
};
 
 
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
    float3 viewDirection : TEXCOORD1;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
    // 이 텍스처 좌표 위치에서 샘플러를 사용하여 텍스처에서 픽셀 색상을 샘플링합니다.
    float4 textureColor = shaderTexture.Sample(SampleType, input.tex);
 
    // 모든 픽셀의 기본 출력 색상을 주변 광원 값으로 설정합니다.
    float4 color = ambientColor;
 
    // specular color를 초기화한다.
    float4 specular = float4 (0.0f, 0.0f, 0.0f, 0.0f);
 
    // 계산을 위해 빛 방향을 반전시킵니다.
    float3 lightDir = -lightDirection;
 
    // 이 픽셀의 빛의 양을 계산합니다.
    float lightIntensity = saturate(dot(input.normal, lightDir));
 
    if(lightIntensity > 0.0f)
    {
        // 확산 색과 광 강도의 양에 따라 최종 확산 색을 결정합니다.
        color += (diffuseColor * lightIntensity);
    
        // 최종 빛의 색상을 채 웁니다.
        color = saturate(color);
 
        // 빛의 강도, 법선 벡터 및 빛의 방향에 따라 반사 벡터를 계산합니다.
        float3 reflection = normalize(2 * lightIntensity * input.normal - lightDir); 
 
        // 반사 벡터, 시선 방향 및 반사 출력을 기준으로 반사 조명의 양을 결정합니다.
        specular = pow(saturate(dot(reflection, input.viewDirection)), specularPower);
    }
 
    // 텍스처 픽셀과 최종 확산 색을 곱하여 최종 픽셀 색상 결과를 얻습니다.
    color = color * textureColor;
 
    // 출력 색상의 마지막에 반사 컴포넌트를 추가합니다.
    color = saturate(color + specular);
 
    return color;
}
cs



LightShaderClass가 정반사광 처리를 위해 수정되었습니다.


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
 
class LightShaderClass
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
    class CameraBufferType
    {
    public:
        XMFLOAT3 cameraPosition;
        float padding;
    };
 
    struct LightBufferType
    {
        XMFLOAT4 ambientColor;
        XMFLOAT4 diffuseColor;
        XMFLOAT3 lightDirection;
        float specularPower;
        XMFLOAT4 specularColor;
    };
public:
    LightShaderClass();
    LightShaderClass(const LightShaderClass&);
    ~LightShaderClass();
 
    bool Initialize(ID3D11Device*, HWND);
    void Shutdown();
    bool Render(ID3D11DeviceContext*int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT3, XMFLOAT4, 
XMFLOAT4, XMFLOAT3, XMFLOAT4, float);
 
private:
    bool InitializeShader(ID3D11Device*, HWND, WCHAR*, WCHAR*);
    void ShutdownShader();
    void OutputShaderErrorMessage(ID3D10Blob*, HWND, WCHAR*);
 
    bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*, XMFLOAT3,
 XMFLOAT4, XMFLOAT4, XMFLOAT3, XMFLOAT4, float);
    void RenderShader(ID3D11DeviceContext*int);
 
private:
    ID3D11VertexShader* m_vertexShader = nullptr;
    ID3D11PixelShader* m_pixelShader = nullptr;
    ID3D11InputLayout* m_layout = nullptr;
    ID3D11SamplerState* m_sampleState = nullptr;
    ID3D11Buffer* m_matrixBuffer = nullptr;
    ID3D11Buffer* m_cameraBuffer = nullptr;
    ID3D11Buffer* m_lightBuffer = nullptr;
};
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
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
#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"../Dx11Demo_10/light.vs", L"../Dx11Demo_10/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, XMFLOAT3 cameraPosition, XMFLOAT4 specularColor, float specularPower)
{
    // 렌더링에 사용할 셰이더 매개 변수를 설정합니다.
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, lightDirection, ambientColor,
diffuseColor, cameraPosition, specularColor, specularPower))
    {
        return false;
    }
 
    // 설정된 버퍼를 셰이더로 렌더링한다.
    RenderShader(deviceContext, indexCount);
 
    return true;
}
 
 
bool LightShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
    HRESULT result;
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    result = D3DCompileFromFile(vsFilename, NULLNULL"LightVertexShader""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"LightPixelShader""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[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;
 
    // 레이아웃의 요소 수를 가져옵니다.
    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_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 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_BUFFER_DESC cameraBufferDesc;
    cameraBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    cameraBufferDesc.ByteWidth = sizeof(CameraBufferType);
    cameraBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    cameraBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    cameraBufferDesc.MiscFlags = 0;
    cameraBufferDesc.StructureByteStride = 0;
 
    // 이 클래스 내에서 정점 셰이더 상수 버퍼에 액세스 할 수 있도록 카메라 상수 버퍼 포인터를 만듭니다.
    result = device->CreateBuffer(&cameraBufferDesc, NULL&m_cameraBuffer);
    if(FAILED(result))
    {
        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;
 
    // 이 클래스 내에서 정점 셰이더 상수 버퍼에 액세스 할 수 있도록 상수 버퍼 포인터를 만듭니다.
    result = device->CreateBuffer(&lightBufferDesc, NULL&m_lightBuffer);
    if(FAILED(result))
    {
        return false;
    }    
 
    return true;
}
 
 
void LightShaderClass::ShutdownShader()
{
    // 광원 상수 버퍼를 해제합니다.
    if(m_lightBuffer)
    {
        m_lightBuffer->Release();
        m_lightBuffer = 0;
    }
 
    // 카메라 상수 버퍼를 해제합니다.
    if(m_cameraBuffer)
    {
        m_cameraBuffer->Release();
        m_cameraBuffer = 0;
    }
 
    // 행렬 상수 버퍼를 해제합니다.
    if (m_matrixBuffer)
    {
        m_matrixBuffer->Release();
        m_matrixBuffer = 0;
    }
 
    // 샘플러 상태를 해제한다.
    if (m_sampleState)
    {
        m_sampleState->Release();
        m_sampleState = 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 LightShaderClass::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 LightShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
    XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, XMFLOAT3 lightDirection, XMFLOAT4 ambientColor,
    XMFLOAT4 diffuseColor, XMFLOAT3 cameraPosition, XMFLOAT4 specularColor, float specularPower)
{
    // 행렬을 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);
 
    // 쓸 수 있도록 카메라 상수 버퍼를 잠급니다.
    if(FAILED(deviceContext->Map(m_cameraBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 상수 버퍼의 데이터에 대한 포인터를 가져옵니다.
    CameraBufferType* dataPtr3 = (CameraBufferType*)mappedResource.pData;
 
    // 카메라 위치를 상수 버퍼에 복사합니다.
    dataPtr3->cameraPosition = cameraPosition;
    dataPtr3->padding = 0.0f;
 
    // 카메라 상수 버퍼를 잠금 해제합니다.
    deviceContext->Unmap(m_cameraBuffer, 0);
 
    // 버텍스 쉐이더에서 카메라 상수 버퍼의 위치를 ​​설정합니다.
    bufferNumber = 1;
 
    // 이제 업데이트 된 값으로 버텍스 쉐이더에서 카메라 상수 버퍼를 설정합니다.
    deviceContext->VSSetConstantBuffers(bufferNumber, 1&m_cameraBuffer);
 
    // 픽셀 셰이더에서 셰이더 텍스처 리소스를 설정합니다.
    deviceContext->PSSetShaderResources(01&texture);
 
    // light constant buffer를 잠글 수 있도록 기록한다.
    if(FAILED(deviceContext->Map(m_lightBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 상수 버퍼의 데이터에 대한 포인터를 가져옵니다.
    LightBufferType* dataPtr2 = (LightBufferType*)mappedResource.pData;
 
    // 조명 변수를 상수 버퍼에 복사합니다.
    dataPtr2->ambientColor = ambientColor;
    dataPtr2->diffuseColor = diffuseColor;
    dataPtr2->lightDirection = lightDirection;
    dataPtr2->specularColor = specularColor;
    dataPtr2->specularPower = specularPower;
 
    // 상수 버퍼의 잠금을 해제합니다.
    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, NULL0);
    deviceContext->PSSetShader(m_pixelShader, NULL0);
 
    // 픽셀 쉐이더에서 샘플러 상태를 설정합니다.
    deviceContext->PSSetSamplers(01&m_sampleState);
 
    // 삼각형을 그립니다.
    deviceContext->DrawIndexed(indexCount, 00);
}
cs



LightClass는 specular 구성 요소와 specular 관련 보조 기능을 포함하도록 수정되었습니다.


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
#pragma once
 
class LightClass
{
public:
    LightClass();
    LightClass(const LightClass&);
    ~LightClass();
 
    void SetAmbientColor(floatfloatfloatfloat);
    void SetDiffuseColor(floatfloatfloatfloat);
    void SetDirection(floatfloatfloat);
    void SetSpecularColor(floatfloatfloatfloat);
    void SetSpecularPower(float);
 
    XMFLOAT4 GetAmbientColor();
    XMFLOAT4 GetDiffuseColor();
    XMFLOAT3 GetDirection();
    XMFLOAT4 GetSpecularColor();
    float GetSpecularPower();
 
private:
    XMFLOAT4 m_ambientColor;
    XMFLOAT4 m_diffuseColor;
    XMFLOAT3 m_direction;
    XMFLOAT4 m_specularColor;
    float m_specularPower;
};
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
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
#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);
    return;
}
 
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);
}
 
void LightClass::SetSpecularColor(float red, float green, float blue, float alpha)
{
    m_specularColor = XMFLOAT4(red, green, blue, alpha);
}
 
 
void LightClass::SetSpecularPower(float power)
{
    m_specularPower = power;
}
 
XMFLOAT4 LightClass::GetAmbientColor()
{
    return m_ambientColor;
}
 
XMFLOAT4 LightClass::GetDiffuseColor()
{
    return m_diffuseColor;
}
 
 
XMFLOAT3 LightClass::GetDirection()
{
    return m_direction;
}
 
XMFLOAT4 LightClass::GetSpecularColor()
{
    return m_specularColor;
}
 
 
float LightClass::GetSpecularPower()
{
    return m_specularPower;
}
cs





이 튜토리얼에서는 GraphicsClass의 헤더 파일은 변경되지 않았으므로 생략하겠습니다.


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 "lightclass.h"
#include "lightshaderclass.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;
    }
 
    // 카메라 포지션 설정
    m_Camera->SetPosition(0.0f, 0.0f, -6.0f);
 
    // m_Model 객체 생성
    m_Model = new ModelClass;
    if (!m_Model)
    {
        return false;
    }
 
    // m_Model 객체 초기화
    if (!m_Model->Initialize(m_Direct3D->GetDevice(), "../Dx11Demo_10/data/cube.txt", L"../Dx11Demo_10/data/seafloor.dds"))
    {
        MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
        return false;
    }
 
    // m_LightShader 객체 생성
    m_LightShader = new LightShaderClass;
    if (!m_LightShader)
    {
        return false;
    }
 
    // m_LightShader 객체 초기화
    if (!m_LightShader->Initialize(m_Direct3D->GetDevice(), hwnd))
    {
        MessageBox(hwnd, L"Could not initialize the light shader object.", L"Error", MB_OK);
        return false;
    }
 
    // m_Light 객체 생성
    m_Light = new LightClass;
    if(!m_Light)
    {
        return false;
    }
 
    // m_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(0.0f, 0.0f, 1.0f);
    m_Light->SetSpecularColor(1.0f, 1.0f, 1.0f, 1.0f);
    m_Light->SetSpecularPower(32.0f);
 
    return true;
}
 
 
void GraphicsClass::Shutdown()
{
    // m_Light 객체 반환
    if(m_Light)
    {
        delete m_Light;
        m_Light = 0;
    }
 
    // m_LightShader 객체 반환
    if (m_LightShader)
    {
        m_LightShader->Shutdown();
        delete m_LightShader;
        m_LightShader = 0;
    }
 
    // m_Model 객체 반환
    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()
{
    static float rotation = 0.0f;
 
    // 각 프레임의 rotation 변수를 업데이트합니다.
    rotation += (float)XM_PI * 0.005f;
    if(rotation > 360.0f)
    {
        rotation -= 360.0f;
    }
    
    // 그래픽 랜더링 처리
    return Render(rotation);
}
 
 
bool GraphicsClass::Render(float rotation)
{
    // 씬을 그리기 위해 버퍼를 지웁니다
    m_Direct3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져옵니다
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
    m_Direct3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_Direct3D->GetProjectionMatrix(projectionMatrix);
 
    // 삼각형이 회전 할 수 있도록 회전 값으로 월드 행렬을 회전합니다.
    worldMatrix = XMMatrixRotationY(rotation);
 
    // 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 드로잉을 준비합니다.
    m_Model->Render(m_Direct3D->GetDeviceContext());
 
    // Light 쉐이더를 사용하여 모델을 렌더링합니다.
    if (!m_LightShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix,
 projectionMatrix, m_Model->GetTexture(), m_Light->GetDirection(), m_Light->GetAmbientColor(),
 m_Light->GetDiffuseColor(), m_Camera->GetPosition(), m_Light->GetSpecularColor(),
 m_Light->GetSpecularPower()))
    {
        return false;
    }
 
    // 버퍼의 내용을 화면에 출력합니다
    m_Direct3D->EndScene();
 
    return true;
}
cs



출력 화면




마치면서


정반사광(specular lighting)을 추가하여 육면체가 카메라의 방향과 맞을 때 밝은 흰색의 반사광 효과를 낼 수 있게 되었습니다.



연습문제


1. 프로젝트를 다시 컴파일하고 실행하여 육면체가 카메라와 맞을 때 밝은 반사광 효과가 나타나는 것을 확인해 보십시오.


2. m_Light->SetDirection(1.0f, 0.0f, 1.0f)와 같이 빛의 방향을 수정하여 광원이 다른 방향일 때의 결과를 확인해 보십시오.


3. 폴리곤 5000개 이상의 빨간 텍스쳐를 가진 공 모델을 만들고 튜토리얼의 맨 윗부분의 이미지를 다시 만들어 보십시오.



소스코드


소스코드 : 

Dx11Demo_10.zip