-
Notifications
You must be signed in to change notification settings - Fork 82
/
Tutorial00_HelloWin32.cpp
526 lines (448 loc) · 16.5 KB
/
Tutorial00_HelloWin32.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
/*
* Copyright 2019-2022 Diligent Graphics LLC
* Copyright 2015-2019 Egor Yusov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* In no event and under no legal theory, whether in tort (including negligence),
* contract, or otherwise, unless required by applicable law (such as deliberate
* and grossly negligent acts) or agreed to in writing, shall any Contributor be
* liable for any damages, including any direct, indirect, special, incidental,
* or consequential damages of any character arising as a result of this License or
* out of the use or inability to use the software (including but not limited to damages
* for loss of goodwill, work stoppage, computer failure or malfunction, or any and
* all other commercial damages or losses), even if such Contributor has been advised
* of the possibility of such damages.
*/
#include <memory>
#include <iomanip>
#include <iostream>
#ifndef NOMINMAX
# define NOMINMAX
#endif
#include <Windows.h>
#include <crtdbg.h>
#ifndef PLATFORM_WIN32
# define PLATFORM_WIN32 1
#endif
#ifndef ENGINE_DLL
# define ENGINE_DLL 1
#endif
#ifndef D3D11_SUPPORTED
# define D3D11_SUPPORTED 1
#endif
#ifndef D3D12_SUPPORTED
# define D3D12_SUPPORTED 1
#endif
#ifndef GL_SUPPORTED
# define GL_SUPPORTED 1
#endif
#ifndef VULKAN_SUPPORTED
# define VULKAN_SUPPORTED 1
#endif
#include "Graphics/GraphicsEngineD3D11/interface/EngineFactoryD3D11.h"
#include "Graphics/GraphicsEngineD3D12/interface/EngineFactoryD3D12.h"
#include "Graphics/GraphicsEngineOpenGL/interface/EngineFactoryOpenGL.h"
#include "Graphics/GraphicsEngineVulkan/interface/EngineFactoryVk.h"
#include "Graphics/GraphicsEngine/interface/RenderDevice.h"
#include "Graphics/GraphicsEngine/interface/DeviceContext.h"
#include "Graphics/GraphicsEngine/interface/SwapChain.h"
#include "Common/interface/RefCntAutoPtr.hpp"
using namespace Diligent;
// For this tutorial, we will use simple vertex shader
// that creates a procedural triangle
// Diligent Engine can use HLSL source on all supported platforms.
// It will convert HLSL to GLSL in OpenGL mode, while Vulkan backend will compile it directly to SPIRV.
static const char* VSSource = R"(
struct PSInput
{
float4 Pos : SV_POSITION;
float3 Color : COLOR;
};
void main(in uint VertId : SV_VertexID,
out PSInput PSIn)
{
float4 Pos[3];
Pos[0] = float4(-0.5, -0.5, 0.0, 1.0);
Pos[1] = float4( 0.0, +0.5, 0.0, 1.0);
Pos[2] = float4(+0.5, -0.5, 0.0, 1.0);
float3 Col[3];
Col[0] = float3(1.0, 0.0, 0.0); // red
Col[1] = float3(0.0, 1.0, 0.0); // green
Col[2] = float3(0.0, 0.0, 1.0); // blue
PSIn.Pos = Pos[VertId];
PSIn.Color = Col[VertId];
}
)";
// Pixel shader simply outputs interpolated vertex color
static const char* PSSource = R"(
struct PSInput
{
float4 Pos : SV_POSITION;
float3 Color : COLOR;
};
struct PSOutput
{
float4 Color : SV_TARGET;
};
void main(in PSInput PSIn,
out PSOutput PSOut)
{
PSOut.Color = float4(PSIn.Color.rgb, 1.0);
}
)";
class Tutorial00App
{
public:
Tutorial00App()
{
}
~Tutorial00App()
{
m_pImmediateContext->Flush();
}
bool InitializeDiligentEngine(HWND hWnd)
{
SwapChainDesc SCDesc;
switch (m_DeviceType)
{
#if D3D11_SUPPORTED
case RENDER_DEVICE_TYPE_D3D11:
{
EngineD3D11CreateInfo EngineCI;
# if ENGINE_DLL
// Load the dll and import GetEngineFactoryD3D11() function
auto* GetEngineFactoryD3D11 = LoadGraphicsEngineD3D11();
# endif
auto* pFactoryD3D11 = GetEngineFactoryD3D11();
pFactoryD3D11->CreateDeviceAndContextsD3D11(EngineCI, &m_pDevice, &m_pImmediateContext);
Win32NativeWindow Window{hWnd};
pFactoryD3D11->CreateSwapChainD3D11(m_pDevice, m_pImmediateContext, SCDesc, FullScreenModeDesc{}, Window, &m_pSwapChain);
}
break;
#endif
#if D3D12_SUPPORTED
case RENDER_DEVICE_TYPE_D3D12:
{
# if ENGINE_DLL
// Load the dll and import GetEngineFactoryD3D12() function
auto GetEngineFactoryD3D12 = LoadGraphicsEngineD3D12();
# endif
EngineD3D12CreateInfo EngineCI;
auto* pFactoryD3D12 = GetEngineFactoryD3D12();
pFactoryD3D12->CreateDeviceAndContextsD3D12(EngineCI, &m_pDevice, &m_pImmediateContext);
Win32NativeWindow Window{hWnd};
pFactoryD3D12->CreateSwapChainD3D12(m_pDevice, m_pImmediateContext, SCDesc, FullScreenModeDesc{}, Window, &m_pSwapChain);
}
break;
#endif
#if GL_SUPPORTED
case RENDER_DEVICE_TYPE_GL:
{
# if EXPLICITLY_LOAD_ENGINE_GL_DLL
// Load the dll and import GetEngineFactoryOpenGL() function
auto GetEngineFactoryOpenGL = LoadGraphicsEngineOpenGL();
# endif
auto* pFactoryOpenGL = GetEngineFactoryOpenGL();
EngineGLCreateInfo EngineCI;
EngineCI.Window.hWnd = hWnd;
pFactoryOpenGL->CreateDeviceAndSwapChainGL(EngineCI, &m_pDevice, &m_pImmediateContext, SCDesc, &m_pSwapChain);
}
break;
#endif
#if VULKAN_SUPPORTED
case RENDER_DEVICE_TYPE_VULKAN:
{
# if EXPLICITLY_LOAD_ENGINE_VK_DLL
// Load the dll and import GetEngineFactoryVk() function
auto GetEngineFactoryVk = LoadGraphicsEngineVk();
# endif
EngineVkCreateInfo EngineCI;
auto* pFactoryVk = GetEngineFactoryVk();
pFactoryVk->CreateDeviceAndContextsVk(EngineCI, &m_pDevice, &m_pImmediateContext);
if (!m_pSwapChain && hWnd != nullptr)
{
Win32NativeWindow Window{hWnd};
pFactoryVk->CreateSwapChainVk(m_pDevice, m_pImmediateContext, SCDesc, Window, &m_pSwapChain);
}
}
break;
#endif
default:
std::cerr << "Unknown/unsupported device type";
return false;
break;
}
return true;
}
bool ProcessCommandLine(const char* CmdLine)
{
const char* mode = nullptr;
const char* Keys[] = {"--mode ", "--mode=", "-m "};
for (size_t i = 0; i < _countof(Keys); ++i)
{
const auto* Key = Keys[i];
if ((mode = strstr(CmdLine, Key)) != nullptr)
{
mode += strlen(Key);
break;
}
}
if (mode != nullptr)
{
while (*mode == ' ')
++mode;
if (_stricmp(mode, "D3D11") == 0)
{
#if D3D11_SUPPORTED
m_DeviceType = RENDER_DEVICE_TYPE_D3D11;
#else
std::cerr << "Direct3D11 is not supported. Please select another device type";
return false;
#endif
}
else if (_stricmp(mode, "D3D12") == 0)
{
#if D3D12_SUPPORTED
m_DeviceType = RENDER_DEVICE_TYPE_D3D12;
#else
std::cerr << "Direct3D12 is not supported. Please select another device type";
return false;
#endif
}
else if (_stricmp(mode, "GL") == 0)
{
#if GL_SUPPORTED
m_DeviceType = RENDER_DEVICE_TYPE_GL;
#else
std::cerr << "OpenGL is not supported. Please select another device type";
return false;
#endif
}
else if (_stricmp(mode, "VK") == 0)
{
#if VULKAN_SUPPORTED
m_DeviceType = RENDER_DEVICE_TYPE_VULKAN;
#else
std::cerr << "Vulkan is not supported. Please select another device type";
return false;
#endif
}
else
{
std::cerr << mode << " is not a valid device type. Only the following types are supported: D3D11, D3D12, GL, VK";
return false;
}
}
else
{
#if D3D12_SUPPORTED
m_DeviceType = RENDER_DEVICE_TYPE_D3D12;
#elif VULKAN_SUPPORTED
m_DeviceType = RENDER_DEVICE_TYPE_VULKAN;
#elif D3D11_SUPPORTED
m_DeviceType = RENDER_DEVICE_TYPE_D3D11;
#elif GL_SUPPORTED
m_DeviceType = RENDER_DEVICE_TYPE_GL;
#endif
}
return true;
}
void CreateResources()
{
// Pipeline state object encompasses configuration of all GPU stages
GraphicsPipelineStateCreateInfo PSOCreateInfo;
// Pipeline state name is used by the engine to report issues.
// It is always a good idea to give objects descriptive names.
PSOCreateInfo.PSODesc.Name = "Simple triangle PSO";
// This is a graphics pipeline
PSOCreateInfo.PSODesc.PipelineType = PIPELINE_TYPE_GRAPHICS;
// clang-format off
// This tutorial will render to a single render target
PSOCreateInfo.GraphicsPipeline.NumRenderTargets = 1;
// Set render target format which is the format of the swap chain's color buffer
PSOCreateInfo.GraphicsPipeline.RTVFormats[0] = m_pSwapChain->GetDesc().ColorBufferFormat;
// Use the depth buffer format from the swap chain
PSOCreateInfo.GraphicsPipeline.DSVFormat = m_pSwapChain->GetDesc().DepthBufferFormat;
// Primitive topology defines what kind of primitives will be rendered by this pipeline state
PSOCreateInfo.GraphicsPipeline.PrimitiveTopology = PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
// No back face culling for this tutorial
PSOCreateInfo.GraphicsPipeline.RasterizerDesc.CullMode = CULL_MODE_NONE;
// Disable depth testing
PSOCreateInfo.GraphicsPipeline.DepthStencilDesc.DepthEnable = False;
// clang-format on
ShaderCreateInfo ShaderCI;
// Tell the system that the shader source code is in HLSL.
// For OpenGL, the engine will convert this into GLSL under the hood
ShaderCI.SourceLanguage = SHADER_SOURCE_LANGUAGE_HLSL;
// OpenGL backend requires emulated combined HLSL texture samplers (g_Texture + g_Texture_sampler combination)
ShaderCI.Desc.UseCombinedTextureSamplers = true;
// Create a vertex shader
RefCntAutoPtr<IShader> pVS;
{
ShaderCI.Desc.ShaderType = SHADER_TYPE_VERTEX;
ShaderCI.EntryPoint = "main";
ShaderCI.Desc.Name = "Triangle vertex shader";
ShaderCI.Source = VSSource;
m_pDevice->CreateShader(ShaderCI, &pVS);
}
// Create a pixel shader
RefCntAutoPtr<IShader> pPS;
{
ShaderCI.Desc.ShaderType = SHADER_TYPE_PIXEL;
ShaderCI.EntryPoint = "main";
ShaderCI.Desc.Name = "Triangle pixel shader";
ShaderCI.Source = PSSource;
m_pDevice->CreateShader(ShaderCI, &pPS);
}
// Finally, create the pipeline state
PSOCreateInfo.pVS = pVS;
PSOCreateInfo.pPS = pPS;
m_pDevice->CreateGraphicsPipelineState(PSOCreateInfo, &m_pPSO);
}
void Render()
{
// Set render targets before issuing any draw command.
// Note that Present() unbinds the back buffer if it is set as render target.
auto* pRTV = m_pSwapChain->GetCurrentBackBufferRTV();
auto* pDSV = m_pSwapChain->GetDepthBufferDSV();
m_pImmediateContext->SetRenderTargets(1, &pRTV, pDSV, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
// Clear the back buffer
const float ClearColor[] = {0.350f, 0.350f, 0.350f, 1.0f};
// Let the engine perform required state transitions
m_pImmediateContext->ClearRenderTarget(pRTV, ClearColor, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
m_pImmediateContext->ClearDepthStencil(pDSV, CLEAR_DEPTH_FLAG, 1.f, 0, RESOURCE_STATE_TRANSITION_MODE_TRANSITION);
// Set the pipeline state in the immediate context
m_pImmediateContext->SetPipelineState(m_pPSO);
// Typically we should now call CommitShaderResources(), however shaders in this example don't
// use any resources.
DrawAttribs drawAttrs;
drawAttrs.NumVertices = 3; // Render 3 vertices
m_pImmediateContext->Draw(drawAttrs);
}
void Present()
{
m_pSwapChain->Present();
}
void WindowResize(Uint32 Width, Uint32 Height)
{
if (m_pSwapChain)
m_pSwapChain->Resize(Width, Height);
}
RENDER_DEVICE_TYPE GetDeviceType() const { return m_DeviceType; }
private:
RefCntAutoPtr<IRenderDevice> m_pDevice;
RefCntAutoPtr<IDeviceContext> m_pImmediateContext;
RefCntAutoPtr<ISwapChain> m_pSwapChain;
RefCntAutoPtr<IPipelineState> m_pPSO;
RENDER_DEVICE_TYPE m_DeviceType = RENDER_DEVICE_TYPE_D3D11;
};
std::unique_ptr<Tutorial00App> g_pTheApp;
LRESULT CALLBACK MessageProc(HWND, UINT, WPARAM, LPARAM);
// Main
int WINAPI WinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nShowCmd)
{
#if defined(_DEBUG) || defined(DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
g_pTheApp.reset(new Tutorial00App);
const auto* cmdLine = GetCommandLineA();
if (!g_pTheApp->ProcessCommandLine(cmdLine))
return -1;
std::wstring Title(L"Tutorial00: Hello Win32");
switch (g_pTheApp->GetDeviceType())
{
case RENDER_DEVICE_TYPE_D3D11: Title.append(L" (D3D11)"); break;
case RENDER_DEVICE_TYPE_D3D12: Title.append(L" (D3D12)"); break;
case RENDER_DEVICE_TYPE_GL: Title.append(L" (GL)"); break;
case RENDER_DEVICE_TYPE_VULKAN: Title.append(L" (VK)"); break;
}
// Register our window class
WNDCLASSEX wcex = {sizeof(WNDCLASSEX), CS_HREDRAW | CS_VREDRAW, MessageProc,
0L, 0L, hInstance, NULL, NULL, NULL, NULL, L"SampleApp", NULL};
RegisterClassEx(&wcex);
// Create a window
LONG WindowWidth = 1280;
LONG WindowHeight = 1024;
RECT rc = {0, 0, WindowWidth, WindowHeight};
AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);
HWND wnd = CreateWindow(L"SampleApp", Title.c_str(),
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance, NULL);
if (!wnd)
{
MessageBox(NULL, L"Cannot create window", L"Error", MB_OK | MB_ICONERROR);
return 0;
}
ShowWindow(wnd, nShowCmd);
UpdateWindow(wnd);
if (!g_pTheApp->InitializeDiligentEngine(wnd))
return -1;
g_pTheApp->CreateResources();
// Main message loop
MSG msg = {0};
while (WM_QUIT != msg.message)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
g_pTheApp->Render();
g_pTheApp->Present();
}
}
g_pTheApp.reset();
return (int)msg.wParam;
}
// Called every time the NativeNativeAppBase receives a message
LRESULT CALLBACK MessageProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_PAINT:
{
PAINTSTRUCT ps;
BeginPaint(wnd, &ps);
EndPaint(wnd, &ps);
return 0;
}
case WM_SIZE: // Window size has been changed
if (g_pTheApp)
{
g_pTheApp->WindowResize(LOWORD(lParam), HIWORD(lParam));
}
return 0;
case WM_CHAR:
if (wParam == VK_ESCAPE)
PostQuitMessage(0);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_GETMINMAXINFO:
{
LPMINMAXINFO lpMMI = (LPMINMAXINFO)lParam;
lpMMI->ptMinTrackSize.x = 320;
lpMMI->ptMinTrackSize.y = 240;
return 0;
}
default:
return DefWindowProc(wnd, message, wParam, lParam);
}
}