Thinking Different




Tutorial 46 - 광선 효과



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



 이 듀토리얼에서는 DirectX 11 및 HLSL을 사용하여 장면에 광선을 추가하는 방법에 대해 설명합니다. 이 듀토리얼에서는 흐림 효과를 만드는 데 필요한 단계 인 DirectX 흐림 효과 듀토리얼의 개념을 기반으로 합니다.


일반적으로 사용자 인터페이스 요소 (예 : 메뉴 시스템)와 3D 객체는 2D 및 3D 응용 프로그램에서 광선이 적용되는 두 가지 요소입니다. 둘 다 똑같은 방식으로 이루어집니다. 이 듀토리얼에서는 튜토리얼을 단순하게 만들고 가장 널리 사용되는 광선을 다루기 위해 하나의 2D 사용자 인터페이스 객체에만 광선을 적용할 것입니다. 그러나 이 단계는 3D 객체와 완전히 동일합니다.


먼저 다음과 같은 간단한 메뉴 버튼을 만들었습니다.




이제 텍스트가 아닌 단추의 테두리에만 광선을 적용하려고 한다고 가정해 보겠습니다. 우리가 빛을 적용하는 위치를 제어하는 것은 일반적으로 모든 것이 빛나는 것을 원치 않기 때문에 매우 중요합니다. 이렇게 하려면 글로우 효과를 적용할 위치를 나타내는 흑백 글로우 맵을 만듭니다. 이는 투명성을 위해 알파 맵을 만드는 것과 유사합니다. 메뉴 버튼의 경우 테두리에 광선을 적용하기만 하면 다음과 같은 광선 맵을 만듭니다.




이제 우리는 글로우 맵 비트맵과 메뉴 버튼 비트 맵을 가지고 있으므로 글로우 효과를 생성할 수 있습니다. 첫 번째 단계는 렌더링에 적용된 광선이 텍스처를 원하는 메뉴 버튼의 비트맵 부분만 렌더링하는 것입니다. 우리는 두 개의 비트맵을 사용하는 글로우 맵 쉐이더를 생성하고 렌더링에서 컬러 비트맵의 픽셀을 검정색 픽셀이 없는 경우에만 텍스처 객체로 렌더링합니다. 이 방법으로 우리의 글로우 맵은 기본적으로 투명도 스크가 되어 메뉴 버튼의 테두리만 텍스처 객체에 렌더링되도록 렌더링합니다.


테두리를 렌더링하여 텍스처 객체로 렌더링하면 다음 번에 흐림 효과를 적용할 수 있습니다. 텍스처를 샘플링하고 수평으로 흐리게 처리 한 다음 수직으로 흐리게 처리한 다음 샘플을 샘플링 합니다. 이것은 이 웹 사이트의 DirectX 흐림효과 듀토리얼에서 수행되었으므로 이 듀토리얼의 흐림효과 처리 정보는 다루지 않습니다. 일단 텍스처에 렌더링이 흐려지면 우리는 글로우 강도 값으로 색상을 곱함으로써 글로를 밝게 만듭니다. 다음 이미지는 3.0의 발광 강도를 사용했습니다.




이제 글로우가 텍스처로 렌더링 되었으므로 최종 장면에 적용할 것입니다. 우리는 먼저 모든 사용자 인터페이스 요소를 렌더해야 합니다. 일반적으로 텍스처 자체 렌더링에 빛을 내지 않는 것처럼 말입니다. 그런 다음 렌더링 된 텍스처를 텍스처 객체로 가져오고 흐림처리된 렌더링을 텍스처 객체로 가져와 글로우 쉐이더에서 두 텍스처를 결합합니다. 모든 글로우 쉐이더는 텍스쳐를 함께 추가 한 다음 백 버퍼에 그려줍니다. 다음 이미지가 그 결과입니다.




글로우 맵을 사용하여 3D 오브젝트의 일부를 렌더링하여 질감에 렌더링하고 흐리게 처리한 다음 글로우 셰이더를 사용하여 일반 3D 장면과 결합합니다.



이 튜토리얼에서는 다음 단계와 각 단계의 텍스처 오브젝트에 대한 렌더링이 다음과 같이 됩니다.


1. 글로우 맵을 렌더링하여 텍스처 객체로 렌더링합니다 (출력은 m_RenderTexture)


2. 렌더링의 샘플을 광선의 텍스처로 샘플링하여 절반 크기의 텍스처 객체에 매핑합니다 (새로운 출력은 m_DownSampleTexure)


3. 이전 단계의 출력에서 수평 흐림효과를 수행합니다 (새 출력은 m_HorizontalBlurTexture)


4. 수평 블러 텍스처에 수직 흐림효과를 수행합니다 (새로운 출력은 m_VerticalBlurTexture)


5. 수직 흐림효과가 처리된 텍스처를 다시 표준 스크린 크기로 샘플링합니다 (새로운 출력은 m_UpSampleTexure)


6. 이제 사용자 인터페이스 요소를 렌더링하여 텍스처로 렌더링합니다 (출력은 m_RenderTexture가 됩니다)


7. 글로우 쉐이더를 사용하여 사용자 샘플 요소의 렌더링 텍스처와 샘플링 된 텍스처를 결합하여 백버퍼에 씁니다.



이 듀토리얼의 코드 섹션에서는 흐림 듀토리얼에서 이미 다뤘던 흐림 관련 항목에 대해서는 다루지 않습니다. 수정 된 BitmapClass를 살펴 보겠습니다.


Bitmapclass.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
#pragma once
 
class TextureClass;
 
class BitmapClass
{
private:
    struct VertexType
    {
        XMFLOAT3 position;
        XMFLOAT2 texture;
    };
 
public:
    BitmapClass();
    BitmapClass(const BitmapClass&);
    ~BitmapClass();
 
    bool Initialize(ID3D11Device*intintconst WCHAR*const WCHAR*intint);
    void Shutdown();
    bool Render(ID3D11DeviceContext*intint);
 
    int GetIndexCount();
    ID3D11ShaderResourceView* GetTexture();
    ID3D11ShaderResourceView* GetGlowMap();
 
private:
    bool InitializeBuffers(ID3D11Device*);
    void ShutdownBuffers();
    bool UpdateBuffers(ID3D11DeviceContext*intint);
    void RenderBuffers(ID3D11DeviceContext*);
 
    bool LoadTextures(ID3D11Device*const WCHAR*const WCHAR*);
    void ReleaseTextures();
 
private:
    ID3D11Buffer* m_vertexBuffer = nullptr;
    ID3D11Buffer* m_indexBuffer = nullptr;
    int m_vertexCount = 0;
    int m_indexCount = 0;
    TextureClass* m_Texture = nullptr;
    TextureClass* m_GlowMap = nullptr;
    int m_screenWidth = 0;
    int m_screenHeight = 0;
    int m_bitmapWidth = 0;
    int m_bitmapHeight = 0;
    int m_previousPosX = 0;
    int m_previousPosY = 0;
};
cs



Bitmapclass.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
#include "stdafx.h"
#include "TextureClass.h"
#include "BitmapClass.h"
 
 
BitmapClass::BitmapClass()
{
}
 
 
BitmapClass::BitmapClass(const BitmapClass& other)
{
}
 
 
BitmapClass::~BitmapClass()
{
}
 
 
bool BitmapClass::Initialize(ID3D11Device* device, int screenWidth, int screenHeight, const WCHAR* textureFilename,
 const WCHAR* glowMapFilename, int bitmapWidth, int bitmapHeight)
{
    // 화면 크기를 멤버변수에 저장
    m_screenWidth = screenWidth;
    m_screenHeight = screenHeight;
 
    // 렌더링할 비트맵의 픽셀의 크기를 저장
    m_bitmapWidth = bitmapWidth;
    m_bitmapHeight = bitmapHeight;
 
    // 이전 렌더링 위치를 음수로 초기화합니다.
    m_previousPosX = -1;
    m_previousPosY = -1;
 
    // 정점 및 인덱스 버퍼를 초기화합니다.
    if (!InitializeBuffers(device))
    {
        return false;
    }
 
    // 이 모델의 텍스처를 로드합니다.
    return LoadTextures(device, textureFilename, glowMapFilename);
}
 
 
void BitmapClass::Shutdown()
{
    // 모델 텍스쳐를 반환합니다.
    ReleaseTextures();
 
    // 버텍스 및 인덱스 버퍼를 종료합니다.
    ShutdownBuffers();
}
 
 
bool BitmapClass::Render(ID3D11DeviceContext* deviceContext, int positionX, int positionY)
{
    // 화면의 다른 위치로 렌더링하기 위해 동적 정점 버퍼를 다시 빌드합니다.
    if(!UpdateBuffers(deviceContext, positionX, positionY))
    {
        return false;
    }
 
    // 그리기를 준비하기 위해 그래픽 파이프 라인에 꼭지점과 인덱스 버퍼를 놓습니다.
    RenderBuffers(deviceContext);
 
    return true;
}
 
 
int BitmapClass::GetIndexCount()
{
    return m_indexCount;
}
 
 
ID3D11ShaderResourceView* BitmapClass::GetTexture()
{
    return m_Texture->GetTexture();
}
 
 
ID3D11ShaderResourceView* BitmapClass::GetGlowMap()
{
    return m_GlowMap->GetTexture();
}
 
 
bool BitmapClass::InitializeBuffers(ID3D11Device* device)
{
    // 정점 배열의 정점 수와 인덱스 배열의 인덱스 수를 지정합니다.
    m_indexCount = m_vertexCount = 6;
 
    // 정점 배열을 만듭니다.
    VertexType* vertices = new VertexType[m_vertexCount];
    if (!vertices)
    {
        return false;
    }
 
    // 인덱스 배열을 만듭니다.
    unsigned long* indices = new unsigned long[m_indexCount];
    if (!indices)
    {
        return false;
    }
 
    // 정점 배열을 0으로 초기화합니다.
    memset(vertices, 0, (sizeof(VertexType) * m_vertexCount));
    
    // 데이터로 인덱스 배열을 로드합니다.
    for (int i = 0; i < m_indexCount; i++)
    {
        indices[i] = i;
    }
 
    // 정적 정점 버퍼의 구조체를 설정합니다.
    D3D11_BUFFER_DESC vertexBufferDesc;
    vertexBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    vertexBufferDesc.ByteWidth = sizeof(VertexType) * m_vertexCount;
    vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vertexBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    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 BitmapClass::ShutdownBuffers()
{
    // 인덱스 버퍼를 해제합니다.
    if (m_indexBuffer)
    {
        m_indexBuffer->Release();
        m_indexBuffer = 0;
    }
 
    // 정점 버퍼를 해제합니다.
    if (m_vertexBuffer)
    {
        m_vertexBuffer->Release();
        m_vertexBuffer = 0;
    }
}
 
bool BitmapClass::UpdateBuffers(ID3D11DeviceContext* deviceContext, int positionX, int positionY)
{
    float left, right, top, bottom;
    VertexType* vertices;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    VertexType* verticesPtr;
    HRESULT result;
 
 
    // 이 비트맵을 렌더링 할 위치가 변경되지 않은 경우 정점 버퍼를 업데이트 하지 마십시오.
    // 현재 올바른 매개 변수가 있습니다.
    if((positionX == m_previousPosX) && (positionY == m_previousPosY))
    {
        return true;
    }
    
    // 변경된 경우 렌더링되는 위치를 업데이트합니다.
    m_previousPosX = positionX;
    m_previousPosY = positionY;
 
    // 비트 맵 왼쪽의 화면 좌표를 계산합니다.
    left = (float)((m_screenWidth / 2* -1+ (float)positionX;
 
    // 비트 맵 오른쪽의 화면 좌표를 계산합니다.
    right = left + (float)m_bitmapWidth;
 
    // 비트 맵 상단의 화면 좌표를 계산합니다.
    top = (float)(m_screenHeight / 2- (float)positionY;
 
    // 비트 맵 아래쪽의 화면 좌표를 계산합니다.
    bottom = top - (float)m_bitmapHeight;
 
    // 정점 배열을 만듭니다.
    vertices = new VertexType[m_vertexCount];
    if(!vertices)
    {
        return false;
    }
 
    // 정점 배열에 데이터를로드합니다.
    // 첫 번째 삼각형
    vertices[0].position = XMFLOAT3(left, top, 0.0f);  // Top left.
    vertices[0].texture = XMFLOAT2(0.0f, 0.0f);
 
    vertices[1].position = XMFLOAT3(right, bottom, 0.0f);  // Bottom right.
    vertices[1].texture = XMFLOAT2(1.0f, 1.0f);
 
    vertices[2].position = XMFLOAT3(left, bottom, 0.0f);  // Bottom left.
    vertices[2].texture = XMFLOAT2(0.0f, 1.0f);
 
    // 두 번째 삼각형
    vertices[3].position = XMFLOAT3(left, top, 0.0f);  // Top left.
    vertices[3].texture = XMFLOAT2(0.0f, 0.0f);
 
    vertices[4].position = XMFLOAT3(right, top, 0.0f);  // Top right.
    vertices[4].texture = XMFLOAT2(1.0f, 0.0f);
 
    vertices[5].position = XMFLOAT3(right, bottom, 0.0f);  // Bottom right.
    vertices[5].texture = XMFLOAT2(1.0f, 1.0f);
 
    // 버텍스 버퍼를 쓸 수 있도록 잠급니다.
    result = deviceContext->Map(m_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource);
    if(FAILED(result))
    {
        return false;
    }
 
    // 정점 버퍼의 데이터를 가리키는 포인터를 얻는다.
    verticesPtr = (VertexType*)mappedResource.pData;
 
    // 데이터를 정점 버퍼에 복사합니다.
    memcpy(verticesPtr, (void*)vertices, (sizeof(VertexType) * m_vertexCount));
 
    // 정점 버퍼의 잠금을 해제합니다.
    deviceContext->Unmap(m_vertexBuffer, 0);
 
    // 더 이상 필요하지 않은 꼭지점 배열을 해제합니다.
    delete [] vertices;
    vertices = 0;
 
    return true;
}
 
void BitmapClass::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 BitmapClass::LoadTextures(ID3D11Device* device, const WCHAR* filename, const WCHAR* glowMapFilename)
{
    // 텍스처 오브젝트를 생성한다.
    m_Texture = new TextureClass;
    if (!m_Texture)
    {
        return false;
    }
 
    // 텍스처 오브젝트를 초기화한다.
    if(!m_Texture->Initialize(device, filename))
    {
        return false;
    }
 
    // 글로우 맵 텍스처 객체를 만듭니다.
    m_GlowMap = new TextureClass;
    if(!m_GlowMap)
    {
        return false;
    }
 
    // 글로우 맵 텍스처 객체를 초기화합니다.
    if(!m_GlowMap->Initialize(device, glowMapFilename))
    {
        return false;
    }
 
    return true;
}
 
 
void BitmapClass::ReleaseTextures()
{
    // 텍스처 오브젝트를 릴리즈한다.
    if (m_Texture)
    {
        m_Texture->Shutdown();
        delete m_Texture;
        m_Texture = 0;
    }
 
    if(m_GlowMap)
    {
        m_GlowMap->Shutdown();
        delete m_GlowMap;
        m_GlowMap = 0;
    }
}
cs



글로우 맵 셰이더의 목적은 색상 비트 맵의 글로우 맵 부분만 텍스처로 렌더링하여 처리 (흐리게 처리) 할 수 있도록 하는 것입니다. HLSL 글로우 맵 셰이더의 코드는 글로우 맵 렌더링을 처리하도록 수정 된 텍스처 셰이더 HLSL 코드입니다.


Glowmap_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
////////////////////////////////////////////////////////////////////////////////
// Filename: glowmap_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;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType GlowMapVertexShader(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;
    
    return output;
}
cs



Glowmap_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
////////////////////////////////////////////////////////////////////////////////
// Filename: glowmap_ps.hlsl
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// GLOBALS //
/////////////
Texture2D shaderTexture : register(t0);
Texture2D glowMapTexture : register(t1);
SamplerState SampleType;
 
 
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 GlowMapPixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
    float4 glowMap;
    float4 color;
 
 
    // 이 텍스처 좌표 위치에서 샘플러를 사용하여 텍스처에서 픽셀 색상을 샘플링합니다.
    textureColor = shaderTexture.Sample(SampleType, input.tex);
 
    // 글로우 맵을 샘플링합니다.
    glowMap = glowMapTexture.Sample(SampleType, input.tex);
 
    // 글로우 맵이 검은 색이면 검은 색으로 표시됩니다. 그렇지 않으면 글로우 맵에 색상이있는 경우 텍스처에서 색상을 반환합니다.
    if((glowMap.r == 0.0f) && (glowMap.g == 0.0f) && (glowMap.b == 0.0f))
    {
        color = float4(0.0f, 0.0f, 0.0f, 1.0f);
    }
    else
    {
        color = textureColor;
    }
 
    return color;
}
cs



GlowMapShaderClass는 TextureShaderClass가 추가 텍스처 (글로우 맵)를 처리하도록 수정 된 것입니다.


Glowmapshaderclass.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
#pragma once
 
class GlowMapShaderClass
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
public:
    GlowMapShaderClass();
    GlowMapShaderClass(const GlowMapShaderClass&);
    ~GlowMapShaderClass();
 
    bool Initialize(ID3D11Device*, HWND);
    void Shutdown();
    bool Render(ID3D11DeviceContext*int, XMMATRIX, XMMATRIX, XMMATRIX, ID3D11ShaderResourceView*,
 ID3D11ShaderResourceView*);
 
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*);
    void RenderShader(ID3D11DeviceContext*int);
 
private:
    ID3D11VertexShader* m_vertexShader;
    ID3D11PixelShader* m_pixelShader;
    ID3D11InputLayout* m_layout;
    ID3D11Buffer* m_matrixBuffer;
    ID3D11SamplerState* m_sampleState;
};
cs



Glowmapshaderclass.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
#include "stdafx.h"
#include "glowmapshaderclass.h"
 
 
GlowMapShaderClass::GlowMapShaderClass()
{
    m_vertexShader = 0;
    m_pixelShader = 0;
    m_layout = 0;
    m_matrixBuffer = 0;
    m_sampleState = 0;
}
 
 
GlowMapShaderClass::GlowMapShaderClass(const GlowMapShaderClass& other)
{
}
 
 
GlowMapShaderClass::~GlowMapShaderClass()
{
}
 
 
bool GlowMapShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 및 픽셀 쉐이더를 초기화합니다.
    return InitializeShader(device, hwnd, L"../Dx11Demo_46/glowmap_vs.hlsl", L"../Dx11Demo_46/glowmap_ps.hlsl");
}
 
 
void GlowMapShaderClass::Shutdown()
{
    // 버텍스 및 픽셀 쉐이더와 관련된 객체를 종료합니다.
    ShutdownShader();
}
 
 
bool GlowMapShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix,
XMMATRIX viewMatrix, XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, ID3D11ShaderResourceView* glowMap)
{
    // 렌더링에 사용할 셰이더 매개 변수를 설정합니다.
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, texture, glowMap))
    {
        return false;
    }
 
    // 설정된 버퍼를 셰이더로 렌더링한다.
    RenderShader(deviceContext, indexCount);
 
    return true;
}
 
 
bool GlowMapShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, const WCHAR* vsFilename, const WCHAR* psFilename)
{
    HRESULT result;
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    result = D3DCompileFromFile(vsFilename, NULLNULL"GlowMapVertexShader""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"GlowMapPixelShader""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_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_CLAMP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
    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;
    }
 
    return true;
}
 
 
void GlowMapShaderClass::ShutdownShader()
{
    // 샘플러 상태를 해제한다.
    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 GlowMapShaderClass::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 GlowMapShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
                           XMMATRIX projectionMatrix, ID3D11ShaderResourceView* texture, ID3D11ShaderResourceView* glowMap)
{
    // 행렬을 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(01&texture);
    deviceContext->PSSetShaderResources(11&glowMap);
 
    return true;
}
 
 
void GlowMapShaderClass::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



글로우 쉐이더의 목적은 흐림효과 처리된 글로우 맵 텍스처를 실제 씬의 일반적인 컬러 렌더링과 결합하는 것입니다. 일반 장면은 입력 colorTexture로 렌더링되고 장면의 광선 (흐리게 처리 된 광선지도) 부분은 입력 glowTexture로 렌더링됩니다. 그 다음 쉐이더는 glowTexture에 glowStrength 값을 곱하여 광선을 증가시킵니다. 그런 다음 최종 픽셀 결과를 얻기 위해 색상 텍스쳐가 있는 글로우 텍스처를 추가합니다.


Glow_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
////////////////////////////////////////////////////////////////////////////////
// Filename: glow_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;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Vertex Shader
////////////////////////////////////////////////////////////////////////////////
PixelInputType GlowVertexShader(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;
    
    return output;
}
cs



Glow_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
////////////////////////////////////////////////////////////////////////////////
// Filename: glow_ps.hlsl
////////////////////////////////////////////////////////////////////////////////
 
 
/////////////
// GLOBALS //
/////////////
Texture2D colorTexture : register(t0);
Texture2D glowTexture : register(t1);
SamplerState SampleType;
 
cbuffer GlowBuffer
{
    float glowStrength;
    float3 padding;
};
 
 
//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
};
 
 
////////////////////////////////////////////////////////////////////////////////
// Pixel Shader
////////////////////////////////////////////////////////////////////////////////
float4 GlowPixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
    float4 glowColor;
    float4 color;
 
 
    // 이 텍스처 좌표 위치에서 샘플러를 사용하여 텍스처에서 픽셀 색상을 샘플링합니다.
    textureColor = colorTexture.Sample(SampleType, input.tex);
 
    // 광선 텍스처를 샘플링합니다.
    glowColor = glowTexture.Sample(SampleType, input.tex);
 
    // 광선의 길이에 곱한 광선의 색상에 텍스처 색상을 추가합니다.
    color = saturate(textureColor + (glowColor * glowStrength));
 
    return color;
}
cs




GlowShaderClass는 글로우 관련 변수를 처리하도록 수정 된 TextureShaderClass입니다.


Glowshaderclass.h


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#pragma once
 
class GlowShaderClass
{
private:
    struct MatrixBufferType
    {
        XMMATRIX world;
        XMMATRIX view;
        XMMATRIX projection;
    };
 
    struct GlowBufferType
    {
        float glowStrength;
        XMFLOAT3 padding;
    };
 
public:
    GlowShaderClass();
    GlowShaderClass(const GlowShaderClass&);
    ~GlowShaderClass();
 
    bool Initialize(ID3D11Device*, HWND);
    void Shutdown();
    bool Render(ID3D11DeviceContext*int, XMMATRIX, XMMATRIX, XMMATRIX, 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*float);
    void RenderShader(ID3D11DeviceContext*int);
 
private:
    ID3D11VertexShader* m_vertexShader;
    ID3D11PixelShader* m_pixelShader;
    ID3D11InputLayout* m_layout;
    ID3D11Buffer* m_matrixBuffer;
    ID3D11Buffer* m_glowBuffer;
    ID3D11SamplerState* m_sampleState;
};
cs



Glowshaderclass.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
#include "stdafx.h"
#include "glowshaderclass.h"
 
 
GlowShaderClass::GlowShaderClass()
{
}
 
 
GlowShaderClass::GlowShaderClass(const GlowShaderClass& other)
{
}
 
 
GlowShaderClass::~GlowShaderClass()
{
}
 
 
bool GlowShaderClass::Initialize(ID3D11Device* device, HWND hwnd)
{
    // 정점 및 픽셀 쉐이더를 초기화합니다.
    return InitializeShader(device, hwnd, L"../Dx11Demo_46/glow_vs.hlsl", L"../Dx11Demo_46/glow_ps.hlsl");
}
 
 
void GlowShaderClass::Shutdown()
{
    // 버텍스 및 픽셀 쉐이더와 관련된 객체를 종료합니다.
    ShutdownShader();
}
 
 
bool GlowShaderClass::Render(ID3D11DeviceContext* deviceContext, int indexCount, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
                             XMMATRIX projectionMatrix, ID3D11ShaderResourceView* colorTexture,
 ID3D11ShaderResourceView* glowTexture, float glowStrength)
{
    // 렌더링에 사용할 셰이더 매개 변수를 설정합니다.
    if (!SetShaderParameters(deviceContext, worldMatrix, viewMatrix, projectionMatrix, colorTexture, glowTexture,
 glowStrength))
    {
        return false;
    }
 
    // 설정된 버퍼를 셰이더로 렌더링한다.
    RenderShader(deviceContext, indexCount);
 
    return true;
}
 
 
bool GlowShaderClass::InitializeShader(ID3D11Device* device, HWND hwnd, const WCHAR* vsFilename, const WCHAR* psFilename)
{
    HRESULT result;
    ID3D10Blob* errorMessage = nullptr;
 
    // 버텍스 쉐이더 코드를 컴파일한다.
    ID3D10Blob* vertexShaderBuffer = nullptr;
    result = D3DCompileFromFile(vsFilename, NULLNULL"GlowVertexShader""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"GlowPixelShader""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_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 glowBufferDesc;
    glowBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    glowBufferDesc.ByteWidth = sizeof(GlowBufferType);
    glowBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    glowBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    glowBufferDesc.MiscFlags = 0;
    glowBufferDesc.StructureByteStride = 0;
 
    // 이 클래스 내에서 픽셀 쉐이더 상수 버퍼에 액세스 할 수 있도록 상수 버퍼 포인터를 만듭니다.
    result = device->CreateBuffer(&glowBufferDesc, NULL&m_glowBuffer);
    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;
    }
 
    return true;
}
 
 
void GlowShaderClass::ShutdownShader()
{
    // 샘플러 상태를 해제한다.
    if (m_sampleState)
    {
        m_sampleState->Release();
        m_sampleState = 0;
    }
 
    // 글로우 상수 버퍼를 해제합니다.
    if(m_glowBuffer)
    {
        m_glowBuffer->Release();
        m_glowBuffer = 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 GlowShaderClass::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 GlowShaderClass::SetShaderParameters(ID3D11DeviceContext* deviceContext, XMMATRIX worldMatrix, XMMATRIX viewMatrix,
                                          XMMATRIX projectionMatrix, ID3D11ShaderResourceView* colorTexture, 
                                          ID3D11ShaderResourceView* glowTexture, float glowStrength)
{
    // 행렬을 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_glowBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0&mappedResource)))
    {
        return false;
    }
 
    // 상수 버퍼의 데이터에 대한 포인터를 가져옵니다.
    GlowBufferType* dataPtr2 = (GlowBufferType*)mappedResource.pData;
 
    // 데이터를 상수 버퍼에 복사합니다.
    dataPtr2->glowStrength = glowStrength;
    dataPtr2->padding = XMFLOAT3(0.0f, 0.0f, 0.0f);
 
    // 상수 버퍼의 잠금을 해제합니다.
    deviceContext->Unmap(m_glowBuffer, 0);
 
    // 픽셀 쉐이더에서 상수 버퍼의 위치를 ​​설정합니다.
    bufferNumber = 0;
 
    // 업데이트 된 값으로 픽셀 쉐이더에 상수 버퍼를 설정합니다.
    deviceContext->PSSetConstantBuffers(bufferNumber, 1&m_glowBuffer);
 
    // 픽셀 셰이더에서 셰이더 텍스처 리소스를 설정합니다.
    deviceContext->PSSetShaderResources(01&colorTexture);
    deviceContext->PSSetShaderResources(11&glowTexture);
 
    return true;
}
 
 
void GlowShaderClass::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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#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 TextureShaderClass;
class BitmapClass;
class RenderTextureClass;
class OrthoWindowClass;
class HorizontalBlurShaderClass;
class VerticalBlurShaderClass;
class GlowMapShaderClass;
class GlowShaderClass;
 
 
class GraphicsClass
{
public:
    GraphicsClass();
    GraphicsClass(const GraphicsClass&);
    ~GraphicsClass();
 
    bool Initialize(intint, HWND);
    void Shutdown();
    bool Frame();
 
private:
    bool Render();
    bool RenderGlowMapToTexture();
    bool DownSampleTexture();
    bool RenderHorizontalBlurToTexture();
    bool RenderVerticalBlurToTexture();
    bool UpSampleTexture();
    bool RenderUIElementsToTexture();
    bool RenderGlowScene();
 
private:
    D3DClass* m_D3D = nullptr;
    CameraClass* m_Camera = nullptr;
    TextureShaderClass* m_TextureShader = nullptr;
    BitmapClass* m_Bitmap = nullptr;
    RenderTextureClass *m_RenderTexture = nullptr;
    RenderTextureClass *m_DownSampleTexure = nullptr;
    RenderTextureClass *m_HorizontalBlurTexture = nullptr;
    RenderTextureClass *m_VerticalBlurTexture = nullptr;
    RenderTextureClass *m_UpSampleTexure = nullptr;
    OrthoWindowClass *m_SmallWindow = nullptr;
    OrthoWindowClass *m_FullScreenWindow = nullptr;
    HorizontalBlurShaderClass* m_HorizontalBlurShader = nullptr;
    VerticalBlurShaderClass* m_VerticalBlurShader = nullptr;
    GlowMapShaderClass* m_GlowMapShader = nullptr;
    GlowShaderClass* m_GlowShader = 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
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
#include "stdafx.h"
#include "d3dclass.h"
#include "cameraclass.h"
#include "textureshaderclass.h"
#include "bitmapclass.h"
#include "rendertextureclass.h"
#include "orthowindowclass.h"
#include "horizontalblurshaderclass.h"
#include "verticalblurshaderclass.h"
#include "glowmapshaderclass.h"
#include "glowshaderclass.h"
#include "graphicsclass.h"
 
 
GraphicsClass::GraphicsClass()
{
}
 
 
GraphicsClass::GraphicsClass(const GraphicsClass& other)
{
}
 
 
GraphicsClass::~GraphicsClass()
{
}
 
 
bool GraphicsClass::Initialize(int screenWidth, int screenHeight, HWND hwnd)
{
    // Direct3D 개체를 만듭니다.
    m_D3D = new D3DClass;
    if(!m_D3D)
    {
        return false;
    }
 
    // Direct3D 객체 초기화
    bool result = m_D3D->Initialize(screenWidth, screenHeight, VSYNC_ENABLED, hwnd, FULL_SCREEN, SCREEN_DEPTH, SCREEN_NEAR);
    if (!result)
    {
        MessageBox(hwnd, L"Could not initialize Direct3D.", L"Error", MB_OK);
        return false;
    }
 
    // m_Camera 객체 생성
    m_Camera = new CameraClass;
    if (!m_Camera)
    {
        return false;
    }
 
    // 카메라의 초기 위치를 초기화합니다.
    m_Camera->SetPosition(0.0f, 0.0f, -5.0f);
    
    // 텍스처 쉐이더 객체를 생성한다.
    m_TextureShader = new TextureShaderClass;
    if(!m_TextureShader)
    {
        return false;
    }
 
    // 텍스처 쉐이더 객체를 초기화한다.
    result = m_TextureShader->Initialize(m_D3D->GetDevice(), hwnd);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the texture shader object.", L"Error", MB_OK);
        return false;
    }
    
    // 비트 맵 객체를 만듭니다.
    m_Bitmap = new BitmapClass;
    if(!m_Bitmap)
    {
        return false;
    }
 
    // 비트 맵 객체를 초기화합니다.
    result = m_Bitmap->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight, L"../Dx11Demo_46/data/test.dds",
 L"../Dx11Demo_46/data/glowmap.dds"25632);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the bitmap object.", L"Error", MB_OK);
        return false;
    }
    
    // 렌더링 텍스처 객체를 생성한다.
    m_RenderTexture = new RenderTextureClass;
    if(!m_RenderTexture)
    {
        return false;
    }
 
    // 렌더링 텍스처 객체를 초기화한다.
    result = m_RenderTexture->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight, SCREEN_DEPTH, SCREEN_NEAR);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the render to texture object.", L"Error", MB_OK);
        return false;
    }
 
    // 다운 샘플 렌더링을 텍스처 오브젝트에 생성한다.
    m_DownSampleTexure = new RenderTextureClass;
    if(!m_DownSampleTexure)
    {
        return false;
    }
 
    // 다운 샘플 렌더를 텍스처 오브젝트로 초기화한다.
    result = m_DownSampleTexure->Initialize(m_D3D->GetDevice(), (screenWidth / 2), (screenHeight / 2), 
SCREEN_DEPTH, SCREEN_NEAR);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the down sample render to texture object.", L"Error", MB_OK);
        return false;
    }
    
    // 작은 ortho 윈도우 객체를 만듭니다.
    m_SmallWindow = new OrthoWindowClass;
    if(!m_SmallWindow)
    {
        return false;
    }
 
    // 작은 ortho 윈도우 객체를 초기화합니다.
    result = m_SmallWindow->Initialize(m_D3D->GetDevice(), (screenWidth / 2), (screenHeight / 2));
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the small ortho window object.", L"Error", MB_OK);
        return false;
    }
    
    // 텍스처 객체에 수평 블러 렌더링을 만듭니다.
    m_HorizontalBlurTexture = new RenderTextureClass;
    if(!m_HorizontalBlurTexture)
    {
        return false;
    }
 
    // 텍스처 객체에 수평 블러 렌더링을 초기화합니다.
    result = m_HorizontalBlurTexture->Initialize(m_D3D->GetDevice(), (screenWidth / 2), (screenHeight / 2), 
SCREEN_DEPTH, SCREEN_NEAR);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the horizontal blur render to texture object.", L"Error", MB_OK);
        return false;
    }
 
    // 수평 블러 쉐이더 객체를 만듭니다.
    m_HorizontalBlurShader = new HorizontalBlurShaderClass;
    if(!m_HorizontalBlurShader)
    {
        return false;
    }
 
    // 수평 블러 쉐이더 객체를 초기화합니다.
    result = m_HorizontalBlurShader->Initialize(m_D3D->GetDevice(), hwnd);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the horizontal blur shader object.", L"Error", MB_OK);
        return false;
    }
    
    // 텍스처 오브젝트에 수직 블러 렌더를 만듭니다.
    m_VerticalBlurTexture = new RenderTextureClass;
    if(!m_VerticalBlurTexture)
    {
        return false;
    }
 
    // 텍스처 오브젝트에 수직 블러 렌더를 초기화합니다.
    result = m_VerticalBlurTexture->Initialize(m_D3D->GetDevice(), (screenWidth / 2), (screenHeight / 2),
 SCREEN_DEPTH, SCREEN_NEAR);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the vertical blur render to texture object.", L"Error", MB_OK);
        return false;
    }
 
    // 수직 블러 셰이더 오브젝트를 생성한다.
    m_VerticalBlurShader = new VerticalBlurShaderClass;
    if(!m_VerticalBlurShader)
    {
        return false;
    }
 
    // 수직 블러 쉐이더 객체를 초기화합니다.
    result = m_VerticalBlurShader->Initialize(m_D3D->GetDevice(), hwnd);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the vertical blur shader object.", L"Error", MB_OK);
        return false;
    }
 
    // 텍스쳐 객체에 업 샘플 렌더를 생성한다.
    m_UpSampleTexure = new RenderTextureClass;
    if(!m_UpSampleTexure)
    {
        return false;
    }
 
    // up 샘플 렌더를 텍스처 오브젝트로 초기화한다.
    result = m_UpSampleTexure->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight, SCREEN_DEPTH, SCREEN_NEAR);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the up sample render to texture object.", L"Error", MB_OK);
        return false;
    }
 
    // 전체 화면 ortho window 객체를 만듭니다.
    m_FullScreenWindow = new OrthoWindowClass;
    if(!m_FullScreenWindow)
    {
        return false;
    }
 
    // 전체 화면 ortho window 객체를 초기화합니다.
    result = m_FullScreenWindow->Initialize(m_D3D->GetDevice(), screenWidth, screenHeight);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the full screen ortho window object.", L"Error", MB_OK);
        return false;
    }
 
    // 글로우 맵 셰이더 개체를 만듭니다.
    m_GlowMapShader = new GlowMapShaderClass;
    if(!m_GlowMapShader)
    {
        return false;
    }
 
    // 글로우 맵 쉐이더 객체를 초기화합니다.
    result = m_GlowMapShader->Initialize(m_D3D->GetDevice(), hwnd);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the glow map shader object.", L"Error", MB_OK);
        return false;
    }
 
    // 글로우 쉐이더 객체를 만듭니다.
    m_GlowShader = new GlowShaderClass;
    if(!m_GlowShader)
    {
        return false;
    }
 
    // 글로우 쉐이더 객체를 초기화합니다.
    result = m_GlowShader->Initialize(m_D3D->GetDevice(), hwnd);
    if(!result)
    {
        MessageBox(hwnd, L"Could not initialize the glow shader object.", L"Error", MB_OK);
        return false;
    }
 
    return true;
}
 
 
void GraphicsClass::Shutdown()
{
    // 글로우 쉐이더 객체를 해제합니다.
    if(m_GlowShader)
    {
        m_GlowShader->Shutdown();
        delete m_GlowShader;
        m_GlowShader = 0;
    }
 
    // 글로우 맵 셰이더 객체를 해제합니다.
    if(m_GlowMapShader)
    {
        m_GlowMapShader->Shutdown();
        delete m_GlowMapShader;
        m_GlowMapShader = 0;
    }
 
    // 전체 화면 ortho window 객체를 해제합니다.
    if(m_FullScreenWindow)
    {
        m_FullScreenWindow->Shutdown();
        delete m_FullScreenWindow;
        m_FullScreenWindow = 0;
    }
 
    // up 샘플 렌더를 텍스쳐 객체로 릴리즈한다.
    if(m_UpSampleTexure)
    {
        m_UpSampleTexure->Shutdown();
        delete m_UpSampleTexure;
        m_UpSampleTexure = 0;
    }
 
    // 수직 블러 쉐이더 객체를 해제한다.
    if(m_VerticalBlurShader)
    {
        m_VerticalBlurShader->Shutdown();
        delete m_VerticalBlurShader;
        m_VerticalBlurShader = 0;
    }
 
    // 수직 블러 렌더를 텍스처 객체에 놓습니다.
    if(m_VerticalBlurTexture)
    {
        m_VerticalBlurTexture->Shutdown();
        delete m_VerticalBlurTexture;
        m_VerticalBlurTexture = 0;
    }
 
    // 수평 블러 쉐이더 객체를 해제합니다.
    if(m_HorizontalBlurShader)
    {
        m_HorizontalBlurShader->Shutdown();
        delete m_HorizontalBlurShader;
        m_HorizontalBlurShader = 0;
    }
 
    // 수평 블러 렌더를 텍스처 객체에 놓습니다.
    if(m_HorizontalBlurTexture)
    {
        m_HorizontalBlurTexture->Shutdown();
        delete m_HorizontalBlurTexture;
        m_HorizontalBlurTexture = 0;
    }
 
    // 작은 ortho 윈도우 객체를 놓습니다.
    if(m_SmallWindow)
    {
        m_SmallWindow->Shutdown();
        delete m_SmallWindow;
        m_SmallWindow = 0;
    }
 
    // 다운 샘플 렌더를 텍스쳐 객체로 릴리즈한다.
    if(m_DownSampleTexure)
    {
        m_DownSampleTexure->Shutdown();
        delete m_DownSampleTexure;
        m_DownSampleTexure = 0;
    }
 
    // 렌더를 텍스쳐 객체로 릴리즈한다.
    if(m_RenderTexture)
    {
        m_RenderTexture->Shutdown();
        delete m_RenderTexture;
        m_RenderTexture = 0;
    }
 
    // 비트 맵 객체를 해제합니다.
    if(m_Bitmap)
    {
        m_Bitmap->Shutdown();
        delete m_Bitmap;
        m_Bitmap = 0;
    }
 
    // 텍스처 쉐이더 객체를 해제한다.
    if(m_TextureShader)
    {
        m_TextureShader->Shutdown();
        delete m_TextureShader;
        m_TextureShader = 0;
    }
 
    // 카메라 객체를 해제합니다.
    if(m_Camera)
    {
        delete m_Camera;
        m_Camera = 0;
    }
 
    // Direct3D 객체 반환
    if (m_D3D)
    {
        m_D3D->Shutdown();
        delete m_D3D;
        m_D3D = 0;
    }
}
 
 
bool GraphicsClass::Frame()
{
    // 그래픽 장면을 렌더링합니다.
    return Render();
}
 
 
bool GraphicsClass::Render()
{
    // 글로우 맵을 렌더링 텍스처에 먼저 렌더링합니다.
    bool result = RenderGlowMapToTexture();
    if(!result)
    {
        return false;
    }
 
    // 다음으로 렌더 텍스처를 작은 크기의 텍스처로 샘플링합니다.
    result = DownSampleTexture();
    if (!result)
    {
        return false;
    }
 
    // 다운 샘플링 된 렌더링 텍스처에 수평 블러를 수행합니다.
    result = RenderHorizontalBlurToTexture();
    if (!result)
    {
        return false;
    }
 
    // 이제 수평 흐림 렌더 텍스처에서 수직 흐림 효과를 수행합니다.
    result = RenderVerticalBlurToTexture();
    if (!result)
    {
        return false;
    }
 
    // 최종 흐린 렌더링 텍스처를 화면 크기로 다시 샘플링합니다.
    result = UpSampleTexture();
    if (!result)
    {
        return false;
    }
 
    // 일반 UI 요소를 전체 화면 텍스처로 렌더링합니다.
    result = RenderUIElementsToTexture();
    if(!result)
    {
        return false;
    }
    
    // UI 요소와 빛나는 UI 요소를 결합한 최종 장면을 렌더링합니다.
    RenderGlowScene();
 
    return true;
}
 
 
bool GraphicsClass::RenderGlowMapToTexture()
{
    XMMATRIX worldMatrix, viewMatrix, orthoMatrix;
    
    // 렌더링 대상을 렌더링에 맞게 설정합니다.
    m_RenderTexture->SetRenderTarget(m_D3D->GetDeviceContext());
 
    // 렌더링을 텍스처에 지웁니다.
    m_RenderTexture->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다.
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 투영 행렬을 가져옵니다.
    m_D3D->GetWorldMatrix(worldMatrix);
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetOrthoMatrix(orthoMatrix);
 
    // 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
    m_D3D->TurnZBufferOff();
 
    // 비트 맵 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 그리기를 준비합니다.
    if(!m_Bitmap->Render(m_D3D->GetDeviceContext(), 100100))
    {
        return false;
    }
 
    // 글로우 맵 셰이더를 사용하여 비트 맵을 렌더링합니다.
    m_GlowMapShader->Render(m_D3D->GetDeviceContext(), m_Bitmap->GetIndexCount(), worldMatrix, viewMatrix,
 orthoMatrix, m_Bitmap->GetTexture(), m_Bitmap->GetGlowMap());
 
    //모든 2D 렌더링이 완료되었으므로 Z 버퍼를 다시 켜십시오.
    m_D3D->TurnZBufferOn();
 
    // 렌더링 대상을 원래의 백 버퍼로 다시 설정하고 렌더링에 대한 렌더링을 더 이상 다시 설정하지 않습니다.
    m_D3D->SetBackBufferRenderTarget();
 
    // 뷰포트를 원본으로 다시 설정합니다.
    m_D3D->ResetViewport();
 
    return true;
}
 
 
bool GraphicsClass::DownSampleTexture()
{
    XMMATRIX worldMatrix, viewMatrix, orthoMatrix;
 
    // 렌더링 대상을 렌더링에 맞게 설정합니다.
    m_DownSampleTexure->SetRenderTarget(m_D3D->GetDeviceContext());
 
    // 렌더링을 텍스처에 지웁니다.
    m_DownSampleTexure->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 1.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다.
    m_Camera->Render();
 
    // 카메라와 d3d 객체로부터 월드와 뷰 매트릭스를 얻는다.
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetWorldMatrix(worldMatrix);
    
    // 질감이 크기가 작기 때문에 렌더링에서 텍스처로 ortho 행렬을 가져옵니다.
    m_DownSampleTexure->GetOrthoMatrix(orthoMatrix);
 
    // 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
    m_D3D->TurnZBufferOff();
 
    // 드로잉을 준비하기 위해 그래픽 파이프 라인에 작은 ortho window 버텍스와 인덱스 버퍼를 놓습니다.
    m_SmallWindow->Render(m_D3D->GetDeviceContext());
 
    // 텍스처 쉐이더를 사용하여 작은 ortho 창을 렌더링하고 씬의 텍스처를 텍스처 리소스로 렌더링합니다.
    if(!m_TextureShader->Render(m_D3D->GetDeviceContext(), m_SmallWindow->GetIndexCount(), worldMatrix, viewMatrix,
 orthoMatrix, m_RenderTexture->GetShaderResourceView()))
    {
        return false;
    }
 
    // 모든 2D 렌더링이 완료되었으므로 Z 버퍼를 다시 켜십시오.
    m_D3D->TurnZBufferOn();
    
    // 렌더링 대상을 원래의 백 버퍼로 다시 설정하고 렌더링에 대한 렌더링을 더 이상 다시 설정하지 않습니다.
    m_D3D->SetBackBufferRenderTarget();
 
    // 뷰포트를 원본으로 다시 설정합니다.
    m_D3D->ResetViewport();
 
    return true;
}
 
 
bool GraphicsClass::RenderHorizontalBlurToTexture()
{
    XMMATRIX worldMatrix, viewMatrix, orthoMatrix;
    
    // 렌더링 대상을 렌더링에 맞게 설정합니다.
    m_HorizontalBlurTexture->SetRenderTarget(m_D3D->GetDeviceContext());
 
    // 렌더링을 텍스처에 지웁니다.
    m_HorizontalBlurTexture->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다.
    m_Camera->Render();
 
    // 카메라와 d3d 객체로부터 월드와 뷰 매트릭스를 얻는다.
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetWorldMatrix(worldMatrix);
 
    // 텍스쳐가 다른 차원을 가지므로 렌더링에서 오쏘 (ortho) 행렬을 텍스처로 가져옵니다.
    m_HorizontalBlurTexture->GetOrthoMatrix(orthoMatrix);
 
    // 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
    m_D3D->TurnZBufferOff();
 
    // 수평 블러 쉐이더에서 사용될 float에 화면 폭을 저장합니다.
    float screenSizeX = (float)m_HorizontalBlurTexture->GetTextureWidth();
    
    // 드로잉을 준비하기 위해 그래픽 파이프 라인에 작은 ortho window 버텍스와 인덱스 버퍼를 놓습니다.
    m_SmallWindow->Render(m_D3D->GetDeviceContext());
    
    // horizontal blur shader와 down sampled render를 사용하여 작은 ortho 윈도우를 텍스처 리소스로 렌더링합니다.    
    if(!m_HorizontalBlurShader->Render(m_D3D->GetDeviceContext(), m_SmallWindow->GetIndexCount(), worldMatrix,
 viewMatrix, orthoMatrix, m_DownSampleTexure->GetShaderResourceView(), screenSizeX))
    {
        return false;
    }
 
    // 모든 2D 렌더링이 완료되었으므로 Z 버퍼를 다시 켜십시오.
    m_D3D->TurnZBufferOn();
 
    // 렌더링 대상을 원래의 백 버퍼로 다시 설정하고 렌더링에 대한 렌더링을 더 이상 다시 설정하지 않습니다.
    m_D3D->SetBackBufferRenderTarget();
 
    // 뷰포트를 원본으로 다시 설정합니다.
    m_D3D->ResetViewport();
 
    return true;
}
 
 
bool GraphicsClass::RenderVerticalBlurToTexture()
{
    XMMATRIX worldMatrix, viewMatrix, orthoMatrix;
    
    // 렌더링 대상을 렌더링에 맞게 설정합니다.
    m_VerticalBlurTexture->SetRenderTarget(m_D3D->GetDeviceContext());
 
    // 렌더링을 텍스처에 지웁니다.
    m_VerticalBlurTexture->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다.
    m_Camera->Render();
 
    // 카메라와 d3d 객체로부터 월드와 뷰 매트릭스를 얻는다.
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetWorldMatrix(worldMatrix);
 
    // 텍스쳐가 다른 차원을 가지므로 렌더링에서 오쏘 (ortho) 행렬을 텍스처로 가져옵니다.
    m_VerticalBlurTexture->GetOrthoMatrix(orthoMatrix);
 
    // 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
    m_D3D->TurnZBufferOff();
 
    // 수직 블러 셰이더에서 사용되는 부동 소수점에 화면 높이를 저장합니다.
    float screenSizeY = (float)m_VerticalBlurTexture->GetTextureHeight();
    
    // 드로잉을 준비하기 위해 그래픽 파이프 라인에 작은 ortho window 버텍스와 인덱스 버퍼를 놓습니다.
    m_SmallWindow->Render(m_D3D->GetDeviceContext());
    
    // 수직 블러 쉐이더와 수평 블러 링을 사용하여 작은 ortho 윈도우를 텍스처 리소스로 렌더합니다.
    if(!m_VerticalBlurShader->Render(m_D3D->GetDeviceContext(), m_SmallWindow->GetIndexCount(), worldMatrix,
 viewMatrix, orthoMatrix, m_HorizontalBlurTexture->GetShaderResourceView(), screenSizeY))
    {
        return false;
    }
 
    // 모든 2D 렌더링이 완료되었으므로 Z 버퍼를 다시 켜십시오.
    m_D3D->TurnZBufferOn();
 
    // 렌더링 대상을 원래의 백 버퍼로 다시 설정하고 렌더링에 대한 렌더링을 더 이상 다시 설정하지 않습니다.
    m_D3D->SetBackBufferRenderTarget();
 
    // 뷰포트를 원본으로 다시 설정합니다.
    m_D3D->ResetViewport();
 
    return true;
}
 
 
bool GraphicsClass::UpSampleTexture()
{
    XMMATRIX worldMatrix, viewMatrix, orthoMatrix;
 
    // 렌더링 대상을 렌더링에 맞게 설정합니다.
    m_UpSampleTexure->SetRenderTarget(m_D3D->GetDeviceContext());
 
    // 렌더링을 텍스처에 지웁니다.
    m_UpSampleTexure->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다.
    m_Camera->Render();
 
    // 카메라와 d3d 객체로부터 월드와 뷰 매트릭스를 얻는다.
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetWorldMatrix(worldMatrix);
 
    // 텍스쳐가 다른 차원을 가지므로 렌더링에서 오쏘 (ortho) 행렬을 텍스처로 가져옵니다.
    m_UpSampleTexure->GetOrthoMatrix(orthoMatrix);
 
    // 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
    m_D3D->TurnZBufferOff();
 
    // 그래픽 파이프 라인에 전체 화면 직교 윈도우 버텍스와 인덱스 버퍼를 배치하여 그리기를 준비합니다.
    m_FullScreenWindow->Render(m_D3D->GetDeviceContext());
 
    // 텍스처 쉐이더와 텍스처 리소스에 대한 작은 크기의 최종 흐리게 렌더링을 사용하여 전체 화면 ortho 창을 렌더링합니다.
    if(!m_TextureShader->Render(m_D3D->GetDeviceContext(), m_FullScreenWindow->GetIndexCount(), worldMatrix,
 viewMatrix, orthoMatrix,
        m_VerticalBlurTexture->GetShaderResourceView()))
    {
        return false;
    }
 
    // 모든 2D 렌더링이 완료되었으므로 Z 버퍼를 다시 켜십시오.
    m_D3D->TurnZBufferOn();
    
    // 렌더링 대상을 원래의 백 버퍼로 다시 설정하고 렌더링에 대한 렌더링을 더 이상 다시 설정하지 않습니다.
    m_D3D->SetBackBufferRenderTarget();
 
    // 뷰포트를 원본으로 다시 설정합니다.
    m_D3D->ResetViewport();
 
    return true;
}
 
 
bool GraphicsClass::RenderUIElementsToTexture()
{
    XMMATRIX worldMatrix, viewMatrix, orthoMatrix;
    bool result;
 
 
    // 렌더링 대상을 렌더링에 맞게 설정합니다.
    m_RenderTexture->SetRenderTarget(m_D3D->GetDeviceContext());
 
    // 렌더링을 텍스처에 지웁니다.
    m_RenderTexture->ClearRenderTarget(m_D3D->GetDeviceContext(), 0.0f, 0.0f, 0.0f, 1.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다.
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 오쏘 (ortho) 행렬을 가져옵니다.
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetWorldMatrix(worldMatrix);
    m_D3D->GetOrthoMatrix(orthoMatrix);
 
    // 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
    m_D3D->TurnZBufferOff();
 
    // 비트 맵 버텍스와 인덱스 버퍼를 그래픽 파이프 라인에 배치하여 그리기를 준비합니다.
    result = m_Bitmap->Render(m_D3D->GetDeviceContext(), 100100);
    if(!result)
    {
        return false;
    }
 
    // 텍스처 쉐이더를 사용하여 비트 맵을 렌더링합니다.
    result = m_TextureShader->Render(m_D3D->GetDeviceContext(), m_Bitmap->GetIndexCount(), worldMatrix, viewMatrix, 
orthoMatrix, m_Bitmap->GetTexture());
    if(!result)
    {
        return false;
    }
 
    // 모든 2D 렌더링이 완료되었으므로 Z 버퍼를 다시 켜십시오.
    m_D3D->TurnZBufferOn();
 
    // 렌더링 대상을 원래의 백 버퍼로 다시 설정하고 렌더링에 대한 렌더링을 더 이상 다시 설정하지 않습니다.
    m_D3D->SetBackBufferRenderTarget();
 
    // 뷰포트를 원본으로 다시 설정합니다.
    m_D3D->ResetViewport();
 
    return true;
}
 
 
bool GraphicsClass::RenderGlowScene()
{
    XMMATRIX worldMatrix, viewMatrix, orthoMatrix;
 
    // 장면을 시작할 버퍼를 지운다.
    m_D3D->BeginScene(1.0f, 0.0f, 0.0f, 0.0f);
 
    // 카메라의 위치에 따라 뷰 행렬을 생성합니다.
    m_Camera->Render();
 
    // 카메라 및 d3d 객체에서 월드, 뷰 및 오쏘 (ortho) 행렬을 가져옵니다.
    m_Camera->GetViewMatrix(viewMatrix);
    m_D3D->GetWorldMatrix(worldMatrix);
    m_D3D->GetOrthoMatrix(orthoMatrix);
 
    // 모든 2D 렌더링을 시작하려면 Z 버퍼를 끕니다.
    m_D3D->TurnZBufferOff();
 
    // 그래픽 파이프 라인에 전체 화면 직교 윈도우 버텍스와 인덱스 버퍼를 배치하여 그리기를 준비합니다.
    m_FullScreenWindow->Render(m_D3D->GetDeviceContext());
 
    // 텍스처 쉐이더를 사용하여 전체 화면 ortho 창을 렌더링하고 텍스처 리소스에 전체 화면 크기로 흐리게 렌더링합니다.
    m_GlowShader->Render(m_D3D->GetDeviceContext(), m_FullScreenWindow->GetIndexCount(), worldMatrix, viewMatrix,
 orthoMatrix, m_RenderTexture->GetShaderResourceView(), m_UpSampleTexure->GetShaderResourceView(), 3.0f);
 
    // 모든 2D 렌더링이 완료되었으므로 Z 버퍼를 다시 켜십시오.
    m_D3D->TurnZBufferOn();
    
    // 렌더링 된 장면을 화면에 표시합니다.
    m_D3D->EndScene();
 
    return true;
}
cs



출력 화면




마치면서


글로우 맵을 사용하여 장면에 선택적 광선을 적용 할 수 있습니다.



연습문제


1. 프로그램을 컴파일하고 실행하십시오. 비트맵 객체에 광선이 적용된 것을 볼 수 있습니다. 종료하려면 ESC 키를 누릅니다.


2. 글로우 강도를 수정하여 효과를 확인합니다.


3. 텍스트 글로우만 만들려면 다른 글로우 맵을 작성하십시오.


4. 3D 장면 (예 : 다른 듀토리얼의 회전 큐브)에 광선을 추가합니다.


5. 노이즈 또는 그라디언트와 같은 추가 텍스처를 사용하고 노이즈 또는 그라디언트 텍스처를 변환하고 광선의 강도로 사용하여 광선을 애니메이션으로 만듭니다.



소스코드


소스코드 : Dx11Demo_46.zip