Thinking Different




Tutorial 32 - 유리, 얼음



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



 이번 예제에서는 HLSL과 C++를 사용하여 유리 및 얼음 셰이더를 구현하는 방법을 살펴봅니다. 코드는 이전 튜토리얼에 기초해 있습니다.


유리와 얼음 셰이더는 둘 다 같은 방법으로 구현되어 있습니다. 유리나 얼음에서 빛이 어떻게 꺾이는지에 대해서는 노말맵을 사용했습니다. 노말맵의 각 픽셀들은 유리나 얼음 뒤에 있는 픽셀을 샘플링할 때 오프셋의 역할을 합니다. 이렇게 빛의 굴절처럼 보이는 효과를 만들어 냄으로 빛이 유리나 얼음을 통과하는 모습을 비슷하게 흉내내어 그 뒤에 있는 물체를 비춥니다. 이런 굴절 효과를 섭동이라고 부릅니다.


셰이더를 짤 때 유리와 얼음의 차이는 사소한 정도입니다. 유리와 얼음은 표면의 색상을 표현하기 위해 서로 다른 색상의 색상 텍스쳐를 사용할 것입니다. 노말맵 역시 서로 다른 표면의 재질감 때문에 다른 텍스쳐를 사용하겠지만, 다시 말하지만 셰이더 입장에서는 노말 벡터를 계산하기 위한 룩업 텍스쳐가 다른 것일 뿐입니다. 마지막 차이점은 어느 정도의 섭동이 사용되었는가 하는 것입니다. refractionScale이라는 변수를 이용하여 섭동의 크기를 조절합니다. 이 변수를 통해 유리에는 좀 더 적은 섭동이 발생하고 얼음에는 좀 더 강한 섭동을 시뮬레이션합니다.


여러분이 이전의 물 셰이더 예제를 읽고 이해하셨다면 이번 예제에 사용된 기법도 반사만 없을 뿐이지 물을 그리는 데 사용된 기법의 응용이라는 것을 깨달을 것입니다. 좀 더 실제적인 유리나 얼음 표면을 만들기 위해 매우 약한 정도의 반사를 추가해볼 수 있습니다.


이번 셰이더에서 사용하는 기본적인 알고리즘을 검토해 본 뒤 유리와 얼음 예제를 단계별로 보도록 하겠습니다.



셰이더 알고리즘


1단계: 유리 뒤에 있는 씬을 텍스쳐에 그립니다. 이것을 굴절 텍스쳐라고 부릅니다.

2단계: 유리 표면에 굴절 텍스쳐를 투영시킵니다.

3단계: 유리를 투과하는 빛을 흉내내기 위하여 노말맵을 이용하여 굴절 텍스쳐의 좌표를 흔듭니다.

4단계: 섭동이 끝난 굴절 텍스쳐와 유리의 색상 텍스쳐를 혼합하여 최종 결과물을 만들어 냅니다.


유리와 얼음이 각 단계별로 어떻게 구현되는지 살펴보겠습니다.



유리

우선 유리 뒤에 보이는 장면을 텍스쳐에 그려야 합니다. 그리고 나서 이 텍스쳐를 유리 표면에 투영시켜 단순히 삼각형 2개짜리 도형인 유리가 전체 씬을 투과해 볼 수 있는 것처럼 보일 것입니다. 여기에 사용한 렌더 투 텍스쳐와 텍스쳐 투영은 이전 튜토리얼에서 살펴본 바 있습니다.


예제를 단순화하기 위해 다양한 물체들로 이루어진 복잡한 장면 대신 텍스쳐가 그려진 사각형 하나를 씬으로 하겠습니다. 따라서 장면을 텍스쳐에 그리고 유리 모델에 투영한 것은 아래와 같은 굴절 텍스쳐를 만들어 냅니다





씬이 좀 더 복잡하다면 유리창이 보이지 않게 되고 모든 것이 똑같이 보일 것입니다. 이렇게 되는 이유는 텍스쳐가 완벽하게 투영되면 단지 3D 장면의 부분을 똑같은 내용의 2D 텍스쳐로 덮은 것이기 때문에 유리가 완벽히 깨끗한 3D 장면을 보여주게 되어 기존 장면과 구분할 수 없게 됩니다. 최소한 무엇이 유리고 무엇이 장면인지 구분지을 수 있게 하려면 디버그 용도로 유리 텍스쳐를 좀 더 어둡거나 밝게 할 수 있습니다.


씬이 텍스쳐에 그려졌다면 노말맵을 이용하여 이 굴절 텍스쳐를 요동시켜 마치 장면이 유리 뒤에 있는 것처럼 보이게 합니다. 아래 노말맵을 사용하여 줄무늬 모양의 유리 효과를 만들 것입니다.




노말맵이 있으니 이것의 각 픽셀을 이용하여 굴절 텍스쳐의 어느 부분이 샘플링될지 수정할 수 있습니다. 이렇게 하여 굴절 텍스쳐의 샘플링 위치를 조금씩 위나 아래, 양옆으로 바꾸어 실제 유리처럼 빛이 직선으로 가지 않고 살짝 휘어지는 것처럼 보이게 합니다. 빛이 얼마나 꺾이는지는 refractionScale 변수로 조절하는데, 이 예제에서는 0.01정도로 매우 낮게 설정되었습니다. 참고로 노말맵의 모양에 따라 크기가 달라지기 때문에 이 변수의 값도 원하는 결과를 얻기 위해 노말맵에 따라 달라집니다.


이렇게 노말맵을 이용하여 0.01 스케일로 굴절 텍스쳐를 샘플링하면 아래와 같은 이미지를 얻을 수 있습니다



기본적인 효과는 거의 다 나왔습니다. 하지만 대부분의 실제 유리는 살짝 색깔이 물들어 있고 어떤 경우는 문양이 있기도 합니다. 예제에 사용한 유리에는 아래 색상 텍스쳐를 사용할 것입니다




색상 텍스쳐와 섭동이 적용된 굴절 텍스쳐를 혼합하여 아래와 같은 최종 유리 효과를 만들어 냅니다





얼음

얼음은 셰이더에 입력만 다를 뿐 유리와 완전히 동일합니다.


시작은 똑같이 얼음 모델의 표면에 투영된 텍스쳐가 있는 사각형에서 출발합니다.




얼음은 최종 결과가 다르게 나오길 원하므로 다른 색상 텍스쳐를 사용할 것입니다




노말맵 역시 얼음 표면 전체에 걸쳐있는 작은 굴곡들을 흉내내기 위해 다른 것을 사용합니다. 다행히도 색상 텍스쳐가 노말맵으로 쓰기에 적당한 노이즈가 있습니다. 이 텍스쳐를 포토샵에서 5배수로 Nvidia 노말맵 필터를 적용시켜 다음과 같은 노말맵을 얻습니다




이 노말맵에 refractionScale 변수를 0.1과 같이 큰 값을 주면(유리에 적용한 0.01 대신) 섭동이 강하게 적용된 굴절 이미지를 얻습니다




마지막으로 섭동이 적용된 굴절 이미지와 얼음 색상 텍스쳐를 혼합하면 아래와 같은 매우 사실적인 이미지를 얻을 수 있습니다




코드를 살펴보기 전에 마지막으로 한마디 하자면 움직이는 배경 위에 구현한 셰이더를 보게 되면(유리나 얼음 뒤에 회전하는 육면체와 같이) 매우 사실적으로 보입니다. 무슨 뜻인지 확인하기 위해 이 예제를 한번이라도 실행해 보기를 권합니다.




이번 예제의 프레임워크는 이전 튜토리얼과 비슷합니다. 얼음과 유리 셰이딩을 위한 GlassShaderClass가 추가됩니다. 3D 씬을 텍스쳐에 그리기 위해 RenderTextureClass가 예제에서 사용됩니다. 또한 유리 뒤에서 배경을 사용할 회전하는 육면체를 그리기 위해 TextureShaderClass 역시 사용할 것입니다.


프레임워크





glass_vs.hlsl


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
////////////////////////////////////////////////////////////////////////////////
// Filename: glass_vs.hlsl
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// 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;
    float4 refractionPosition : TEXCOORD1;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType GlassVertexShader(VertexInputType input)
{
    PixelInputType output;
    matrix viewProjectWorld;
 
 
    // 적절한 행렬 계산을 위해 위치 벡터를 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;
 
    // 굴절을위한 뷰 투영 세계 행렬을 만듭니다.
    viewProjectWorld = mul(viewMatrix, projectionMatrix);
    viewProjectWorld = mul(worldMatrix, viewProjectWorld);
 
    // viewProjectWorld 행렬에 대해 입력 위치를 계산합니다.
    output.refractionPosition = mul(input.position, viewProjectWorld);
 
    return output;
}
cs



glass_ps.hlsl


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
////////////////////////////////////////////////////////////////////////////////
// Filename: glass_ps.hlsl
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// GLOBALS //
/////////////
SamplerState SampleType;
Texture2D colorTexture : register(t0);
Texture2D normalTexture : register(t1);
Texture2D refractionTexture : register(t2);
 
cbuffer GlassBuffer
{
    float refractionScale;
    float3 padding;
};
 
 
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float4 refractionPosition : TEXCOORD1;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 GlassPixelShader(PixelInputType input) : SV_TARGET
{
    float2 refractTexCoord;
    float4 normalMap;
    float3 normal;
    float4 refractionColor;
    float4 textureColor;
    float4 color;
 
    
    // 투영 된 굴절 텍스처 좌표를 계산합니다.
    refractTexCoord.x = input.refractionPosition.x / input.refractionPosition.w / 2.0f + 0.5f;
    refractTexCoord.y = -input.refractionPosition.y / input.refractionPosition.w / 2.0f + 0.5f;
 
    // 노멀 맵 텍스처로부터 법선을 샘플링합니다.
    normalMap = normalTexture.Sample(SampleType, input.tex);
 
    // 법선의 범위를 (0,1)에서 (-1, + 1)로 확장합니다.
    normal = (normalMap.xyz * 2.0f) - 1.0f;
 
    // 유리를 통해 가벼운 왜곡을 시뮬레이트하기 위해 텍스처 좌표 샘플링 위치를 법선 맵 값으로 다시 배치합니다.
    refractTexCoord = refractTexCoord + (normal.xy * refractionScale);
 
    // 교란 된 텍스처 좌표를 사용하여 굴절 텍스처에서 텍스처 픽셀을 샘플링합니다.
    refractionColor = refractionTexture.Sample(SampleType, refractTexCoord);
 
    // 유리색 텍스처에서 텍스처 픽셀을 샘플링합니다.
    textureColor = colorTexture.Sample(SampleType, input.tex);
 
    // 최종 색상의 유리 색상과 굴절 값을 균등하게 결합합니다.
    color = lerp(refractionColor, textureColor, 0.5f);
 
    return color;
}
 
cs



Glassshaderclass.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
 
class GlassShaderClass : public AlignedAllocationPolicy<16>
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
    struct GlassBufferType
    {
        float refractionScale;
        XMFLOAT3 padding;
    };
 
 
public:
    GlassShaderClass();
    GlassShaderClass(const GlassShaderClass&);
    ~GlassShaderClass();
 
    bool Initialize(ID3D11Device*, HWND);
    void Shutdown();
    bool Render(ID3D11DeviceContext*int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*,
                ID3D11ShaderResourceView*, ID3D11ShaderResourceView*float);
 
private:
    bool InitializeShader(ID3D11Device*, HWND, const WCHAR*const WCHAR*);
    void ShutdownShader();
    void OutputShaderErrorMessage(ID3D10Blob*, HWND, const WCHAR*);
 
    bool SetShaderParameters(ID3D11DeviceContext*, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*
                             ID3D11ShaderResourceView*, ID3D11ShaderResourceView*float);
    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_glassBuffer = nullptr;
};
cs




Glassshaderclass.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
#include "stdafx.h"
#include "GlassShaderClass.h"
 
 
GlassShaderClass::GlassShaderClass()
{
}
 
 
GlassShaderClass::GlassShaderClass(const GlassShaderClass& other)
{
}
 
 
GlassShaderClass::~GlassShaderClass()
{
}
 
 
bool GlassShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 및 픽셀 쉐이더를 초기화합니다.
    return InitializeShader(device, hwnd, L"../Dx11Demo_32/glass_vs.hlsl", L"../Dx11Demo_32/glass_ps.hlsl");
}
 
 
void GlassShaderClass::Shutdown()
{
    // 버텍스 및 픽셀 쉐이더와 관련된 객체를 종료합니다.
    ShutdownShader();
}
 
 
bool GlassShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix, 
                              XMMATRIX projectionMatrix, ID3D11ShaderResourceView* colorTexture, 
                              ID3D11ShaderResourceView* normalTexture, ID3D11ShaderResourceView* refractionTexture, 
                              float refractionScale)
{
    // 렌더링에 사용할 셰이더 매개 변수를 설정합니다.
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, colorTexture, 
                                 normalTexture, refractionTexture, refractionScale))
    {
        return false;
    }
 
    // 설정된 버퍼를 셰이더로 렌더링한다.
    RenderShader(deviceContext, indexCount);
 
    return true;
}
 
 
bool GlassShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, const WCHAR* vsFilename, const WCHAR* psFilename)
{
    HRESULT result;
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    result = D3DCompileFromFile(vsFilename, NULLNULL"GlassVertexShader""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"GlassPixelShader""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[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;
 
    // 레이아웃의 요소 수를 가져옵니다.
    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 glassBufferDesc;
    glassBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    glassBufferDesc.ByteWidth = sizeof(GlassBufferType);
    glassBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    glassBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    glassBufferDesc.MiscFlags = 0;
    glassBufferDesc.StructureByteStride = 0;
 
    // 이 클래스 내에서 픽셀 쉐이더 상수 버퍼에 액세스 할 수 있도록 상수 버퍼 포인터를 만듭니다.
    result = device->CreateBuffer(&glassBufferDesc, NULL&m_glassBuffer);
    if(FAILED(result))
    {
        return false;
    }
 
    return true;
}
 
 
void GlassShaderClass::ShutdownShader()
{
    // 유리 상수 버퍼를 놓습니다.
    if (m_glassBuffer)
    {
        m_glassBuffer->Release();
        m_glassBuffer = 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 GlassShaderClass::OutputShaderErrorMessage(ID3D10Blob* errorMessage, HWND hwnd, const WCHAR* shaderFilename)
{
    // 에러 메시지를 출력창에 표시합니다.
    OutputDebugStringA(reinterpret_cast<const char*>(errorMessage->GetBufferPointer()));
 
    // 에러 메세지를 반환합니다.
    errorMessage->Release();
    errorMessage = 0;
 
    // 컴파일 에러가 있음을 팝업 메세지로 알려줍니다.
    MessageBox(hwnd, L"Error compiling shader.", shaderFilename, MB_OK);
}
 
 
bool GlassShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix, 
             XMMATRIX projectionMatrix, ID3D11ShaderResourceView* colorTexture, ID3D11ShaderResourceView* normalTexture,
 ID3D11ShaderResourceView* refractionTexture, float refractionScale)
{
    // 행렬을 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);
 
    // 픽셀 쉐이더에 3 개의 쉐이더 텍스처 리소스를 설정합니다.
    deviceContext->PSSetShaderResources(01&colorTexture);
    deviceContext->PSSetShaderResources(11&normalTexture);
    deviceContext->PSSetShaderResources(21&refractionTexture);
 
    // 쓸 수 있도록 유리 상수 버퍼를 잠급니다.
    if(FAILED(deviceContext->Map(m_glassBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 유리 상수 버퍼의 데이터에 대한 포인터를 가져옵니다.
    GlassBufferType* dataPtr2 = (GlassBufferType*)mappedResource.pData;
 
    // 변수를 유리 상수 버퍼에 복사합니다.
    dataPtr2->refractionScale = refractionScale;
    dataPtr2->padding = XMFLOAT3(0.0f, 0.0f, 0.0f);
 
    // 유리 상수 버퍼의 잠금을 해제합니다.
    deviceContext->Unmap(m_glassBuffer, 0);
 
    // 픽셀 쉐이더에서 유리 상수 버퍼의 위치를 ​​설정합니다.
    bufferNumber = 0;
 
    // 업데이트 된 값으로 픽셀 쉐이더에 유리 상수 버퍼를 설정합니다.
    deviceContext->PSSetConstantBuffers(bufferNumber, 1&m_glassBuffer);
 
    return true;
}
 
 
void GlassShaderClass::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



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
#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 TextureShaderClass;
class RenderTextureClass;
class GlassShaderClass;
 
class GraphicsClass
{
public:
    GraphicsClass();
    GraphicsClass(const GraphicsClass&);
    ~GraphicsClass();
 
    bool Initialize(intint, HWND);
    void Shutdown();
    bool Frame();
 
private:
    bool RenderToTexture(float);
    bool Render(float);
 
private:
    D3DClass* m_Direct3D = nullptr;
    CameraClass* m_Camera = nullptr;
    ModelClass* m_Model = nullptr;
    ModelClass* m_WindowModel = nullptr;
    RenderTextureClass* m_RenderTexture = nullptr;
    TextureShaderClass* m_TextureShader = nullptr;
    GlassShaderClass* m_GlassShader = 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
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
#include "stdafx.h"
#include "d3dclass.h"
#include "cameraclass.h"
#include "modelclass.h"
#include "textureshaderclass.h"
#include "rendertextureclass.h"
#include "GlassShaderClass.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 = new CameraClass;
    if (!m_Camera)
    {
        return false;
    }
 
    // 모델 객체 생성
    m_Model = new ModelClass;
    if (!m_Model)
    {
        return false;
    }
 
    // 모델 객체 초기화
    if (!m_Model->Initialize(m_Direct3D->GetDevice(), "../Dx11Demo_32/data/cube.txt", L"../Dx11Demo_32/data/seafloor.dds",
 L"../Dx11Demo_32/data/bump03.dds"))
    {
        MessageBox(hwnd, L"Could not initialize the model object.", L"Error", MB_OK);
        return false;
    }
 
    // 창 모델 객체를 만듭니다.
    m_WindowModel = new ModelClass;
    if(!m_WindowModel)
    {
        return false;
    }
 
#define GLASS    true    // t유리, f얼음
 
    // 창 모델 객체를 초기화합니다.    
#if GLASS
    if(!m_WindowModel->Initialize(m_Direct3D->GetDevice(), "../Dx11Demo_32/data/square.txt"
L"../Dx11Demo_32/data/glass01.dds", L"../Dx11Demo_32/data/bump03.dds"))    // 유리
#else
    if (!m_WindowModel->Initialize(m_Direct3D->GetDevice(), "../Dx11Demo_32/data/square.txt",
 L"../Dx11Demo_32/data/ice01.dds", L"../Dx11Demo_32/data/icebump01.dds"))   // 얼음
#endif
    {
        MessageBox(hwnd, L"Could not initialize the window model object.", L"Error", MB_OK);
        return false;
    }
 
    // 렌더링 텍스처 객체를 생성한다.
    m_RenderTexture = new RenderTextureClass;
    if(!m_RenderTexture)
    {
        return false;
    }
 
    // 렌더링 텍스처 객체를 초기화한다.
    if(!m_RenderTexture->Initialize(m_Direct3D->GetDevice(), screenWidth, screenHeight))
    {
        return false;
    }
 
    // 텍스처 쉐이더 객체를 생성한다.
    m_TextureShader = new TextureShaderClass;
    if(!m_TextureShader)
    {
        return false;
    }
 
    // 텍스처 쉐이더 객체를 초기화한다.
    if(!m_TextureShader->Initialize(m_Direct3D->GetDevice(), hwnd))
    {
        MessageBox(hwnd, L"Could not initialize the texture shader object.", L"Error", MB_OK);
        return false;
    }
 
    // 유리 쉐이더 객체를 만듭니다.
    m_GlassShader = new GlassShaderClass;
    if(!m_GlassShader)
    {
        return false;
    }
 
    // 유리 쉐이더 객체를 초기화합니다.
    if(!m_GlassShader->Initialize(m_Direct3D->GetDevice(), hwnd))
    {
        MessageBox(hwnd, L"Could not initialize the glass shader object.", L"Error", MB_OK);
        return false;
    }
 
    return true;
}
 
 
void GraphicsClass::Shutdown()
{
    // 유리 쉐이더 객체를 해제합니다.
    if(m_GlassShader)
    {
        m_GlassShader->Shutdown();
        delete m_GlassShader;
        m_GlassShader = 0;
    }
 
    // 텍스처 쉐이더 객체를 해제합니다.
    if(m_TextureShader)
    {
        m_TextureShader->Shutdown();
        delete m_TextureShader;
        m_TextureShader = 0;
    }
 
    // 렌더 텍스쳐 객체를 해제합니다.
    if (m_RenderTexture)
    {
        m_RenderTexture->Shutdown();
        delete m_RenderTexture;
        m_RenderTexture = 0;
    }
 
    // 창 모델 객체를 해제합니다.
    if(m_WindowModel)
    {
        m_WindowModel->Shutdown();
        delete m_WindowModel;
        m_WindowModel = 0;
    }
 
    // 모델 객체를 해제합니다.
    if (m_Model)
    {
        m_Model->Shutdown();
        delete m_Model;
        m_Model = 0;
    }
 
    // 카메라 객체를 해제합니다.
    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;
    }
    
    // 카메라 위치를 설정합니다.
    m_Camera->SetPosition(0.0f, 0.0f, -5.0f);
 
    // 페이드 인이 완료되지 않은 경우 장면을 텍스처로 렌더링하고 텍스처를 페이드 인합니다.
    if(!RenderToTexture(rotation))
    {
        return false;
    }
 
    // 장면을 렌더링 합니다.
    if(!Render(rotation))
    {
        return false;
    }
 
    return true;
}
 
bool GraphicsClass::RenderToTexture(float rotation)
{
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
    
    // 렌더링 대상을 렌더링에 맞게 설정합니다.
    m_RenderTexture->SetRenderTarget(m_Direct3D->GetDeviceContext(), m_Direct3D->GetDepthStencilView());
 
    // 렌더링을 텍스처에 지 웁니다.
    m_RenderTexture->ClearRenderTarget(m_Direct3D->GetDeviceContext(), m_Direct3D->GetDepthStencilView(), 0.0f, 0.0f, 
0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다.
    m_Camera->Render();
    
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져옵니다.
    m_Direct3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_Direct3D->GetProjectionMatrix(projectionMatrix);
 
    // 회전에 의해 월드 행렬에 곱합니다.
    worldMatrix = XMMatrixRotationY(rotation);
 
    // 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 드로잉을 준비합니다.
    m_Model->Render(m_Direct3D->GetDeviceContext());
 
    // 텍스처 쉐이더로 모델을 렌더링한다.
    m_TextureShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix,
                            projectionMatrix, m_Model->GetTexture());
 
    // 렌더링 대상을 원래의 백 버퍼로 다시 설정하고 렌더링에 대한 렌더링을 더 이상 다시 설정하지 않습니다.
    m_Direct3D->SetBackBufferRenderTarget();
 
    return true;
}
 
 
bool GraphicsClass::Render(float rotation)
{
    XMMATRIX worldMatrix, viewMatrix, projectionMatrix;
    
    // 유리 쉐이더의 굴절 스케일을 설정합니다.
#if GLASS
    float refractionScale = 0.01f;    // 유리 효과
#else
    float refractionScale = 0.1f;    // 얼음 효과
#endif
    
    // 장면을 시작할 버퍼를 지운다.
    m_Direct3D->BeginScene(0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다.
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 오쏘 (ortho) 행렬을 가져옵니다.
    m_Direct3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_Direct3D->GetProjectionMatrix(projectionMatrix);
 
    // 회전에 의해 월드 행렬에 곱합니다.
    worldMatrix = XMMatrixRotationY(rotation);
    
    // 모델 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 드로잉을 준비합니다.
    m_Model->Render(m_Direct3D->GetDeviceContext());
 
    // 텍스처 쉐이더로 모델을 렌더링한다.
    if(!m_TextureShader->Render(m_Direct3D->GetDeviceContext(), m_Model->GetIndexCount(), worldMatrix, viewMatrix,
        projectionMatrix, m_Model->GetTexture()))
    {
        return false;
    }
 
    // 월드 행렬을 재설정합니다.
    m_Direct3D->GetWorldMatrix(worldMatrix);
 
    // 윈도우 모델이 렌더링 될 곳으로 되돌립니다.
    worldMatrix = XMMatrixTranslation(0.0f, 0.0f, -1.5f);
 
    // 창 모델 정점과 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 그리기를 준비합니다.
    m_WindowModel->Render(m_Direct3D->GetDeviceContext());
 
    // 유리 쉐이더를 사용하여 창 모델을 렌더링합니다.
    if(!m_GlassShader->Render(m_Direct3D->GetDeviceContext(), m_WindowModel->GetIndexCount(), worldMatrix, viewMatrix,
 projectionMatrix, m_WindowModel->GetTexture(), m_WindowModel->GetNormalMap(), m_RenderTexture->GetShaderResourceView(),
       refractionScale))
    {
        return false;
    }
 
    // 렌더링 된 장면을 화면에 표시합니다.
    m_Direct3D->EndScene();
 
    return true;
}
cs



출력 화면




마치면서


굴절 및 노말맵으로 섭동을 적용하여 유리와 얼음 효과를 렌더링할 수 있습니다.



연습문제


1. 프로그램을 다시 컴파일하여 실행해 보십시오. 녹색 유리 뒤로 회전하는 육면체가 보일 것입니다. ESC키로 종료합니다.


2. 얼음 효과로 바꾸기 위해 GraphicsClass::Initialize 함수의 아래 부분을 true에서 false로 바꾸어 보십시오. 간단히 처리하기 위해 매크로로 작성하였습니다.

#define GLASS true // t유리, f얼음 (true: 유리, false: 얼음)


3. refractionScale 값을 바꾸어 섭동에 어떤 영향을 주는지 살펴보십시오.


4. 픽셀 셰이더에서 색상 텍스쳐와 섭동이 적용된 굴절 텍스쳐의 혼합을 바꾸어 다른 결과를 만들어 보십시오.


5. 여러분만의 유리 색상 텍스쳐와 노말맵을 이용하여 여러분만의 유리 효과를 만들어 보십시오(또한 refractionScale 값을 조절하여 노말맵에 적절하게 보이도록 해 보시기 바랍니다).



소스코드


소스코드 : Dx11Demo_32.zip