forked from vixorien/D3D11Starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGame.cpp
1884 lines (1582 loc) · 64.5 KB
/
Game.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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Game.h"
#include "Graphics.h"
#include "Vertex.h"
#include "Input.h"
#include "PathHelpers.h"
#include "Window.h"
#include "WICTextureLoader.h"
#include <cmath>
// Needed for a helper function to load pre-compiled shader files
#pragma comment(lib, "d3dcompiler.lib")
#include <d3dcompiler.h>
// This code assumes files are in "ImGui" subfolder!
// Adjust as necessary for your own folder structure and project setup
#include "ImGui/imgui.h"
#include "ImGui/imgui_impl_dx11.h"
#include "ImGui/imgui_impl_win32.h"
// For the DirectX Math library
using namespace std;
using namespace DirectX;
// --------------------------------------------------------
// Called once per program, after the window and graphics API
// are initialized but before the game loop begins
// --------------------------------------------------------
void Game::Initialize()
{
// Helper methods for loading shaders, creating some basic
// geometry to draw and some simple camera matrices.
// - You'll be expanding and/or replacing these later
InitializeSimulationParameters();
LoadShaders();
CreateLights();
CreateMaterials();
BuildShadowMap();
BuildShadowMatrices();
CreateGeometry();
CreateCameras();
CreateSkyboxes();
BuildPostProcesses();
// Set initial graphics API state
// - These settings persist until we change them
// - Some of these, like the primitive topology & input layout, probably won't change
// - Others, like setting shaders, will need to be moved elsewhere later
{
// Tell the input assembler (IA) stage of the pipeline what kind of
// geometric primitives (points, lines or triangles) we want to draw.
// Essentially: "What kind of shape should the GPU draw with our vertices?"
Graphics::Context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
}
// Initialize ImGui itself & platform/renderer backends
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGui_ImplWin32_Init(Window::Handle());
ImGui_ImplDX11_Init(Graphics::Device.Get(), Graphics::Context.Get());
// Pick a style (uncomment one of these 3)
//ImGui::StyleColorsDark();
//ImGui::StyleColorsLight();
ImGui::StyleColorsClassic();
}
// --------------------------------------------------------
// Clean up memory or objects created by this class
//
// Note: Using smart pointers means there probably won't
// be much to manually clean up here!
// --------------------------------------------------------
Game::~Game()
{
// ImGui cleanup
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
// Cleanup other variables from helper methods
CleanupSimulationParameters();
}
// --------------------------------------------------------
// Loads shaders from compiled shader object (.cso) files
// and creates the Input Layout that describes our vertex
// data to the rendering pipeline.
// - Input Layout creation is done here because it must
// be verified against vertex shader byte code
// - We'll have that byte code already loaded below
// --------------------------------------------------------
void Game::LoadShaders()
{
// Load shaders in with SimpleShader
// MATERIAL SHADERS
// VERTEX SHADERS
AddVertexShader(L"VS_DiffuseSpecular.cso", vsDiffuseSpecular);
AddVertexShader(L"VS_DiffuseNormal.cso", vsDiffuseNormal);
AddVertexShader(L"VS_PBR.cso", vsPBR);
AddVertexShader(L"VS_Skybox.cso", vsSkybox);
AddVertexShader(L"VS_ShadowMap.cso", vsShadowMap);
// PIXEL SHADERS
AddPixelShader(L"PS_DiffuseSpecular.cso", psDiffuseSpecular);
AddPixelShader(L"PS_DiffuseNormal.cso", psDiffuseNormal);
AddPixelShader(L"PS_PBR.cso", psPBR);
AddPixelShader(L"PS_Normals.cso", psNormals);
AddPixelShader(L"PS_UVs.cso", psUVs);
AddPixelShader(L"PS_Custom.cso", psCustom);
AddPixelShader(L"PS_Skybox.cso", psSkybox);
// POST-PROCESS SHADERS
// VERTEX SHADER
AddVertexShader(L"VS_PostProcess.cso", ppVS);
// PIXEL SHADERS
AddPixelShader(L"PS_PostProcess_Blur.cso", ppBlurPS);
AddPixelShader(L"PS_PostProcess_Dither.cso", ppDitherPS);
}
// --------------------------------------------------------
// Loads textures and creates materials
// --------------------------------------------------------
void Game::CreateMaterials()
{
// Load textures
// TEXTURES 0-13
AddTexture(L"../../Assets/Textures/T_bronze_AM.png");
AddTexture(L"../../Assets/Textures/T_bronze_NR.png");
AddTexture(L"../../Assets/Textures/T_cobblestone_AM.png");
AddTexture(L"../../Assets/Textures/T_cobblestone_NR.png");
AddTexture(L"../../Assets/Textures/T_floor_AM.png");
AddTexture(L"../../Assets/Textures/T_floor_NR.png");
AddTexture(L"../../Assets/Textures/T_paint_AM.png");
AddTexture(L"../../Assets/Textures/T_paint_NR.png");
AddTexture(L"../../Assets/Textures/T_rough_AM.png");
AddTexture(L"../../Assets/Textures/T_rough_NR.png");
AddTexture(L"../../Assets/Textures/T_scratched_AM.png");
AddTexture(L"../../Assets/Textures/T_scratched_NR.png");
AddTexture(L"../../Assets/Textures/T_wood_AM.png");
AddTexture(L"../../Assets/Textures/T_wood_NR.png");
AddTexture(L"../../Assets/Textures/Particles/circle_05.png");
AddTexture(L"../../Assets/Textures/Particles/flame_animated.png");
AddTexture(L"../../Assets/Textures/Particles/spark_01.png");
AddTexture(L"../../Assets/Textures/Particles/spark_02.png");
AddTexture(L"../../Assets/Textures/Particles/spark_03.png");
AddTexture(L"../../Assets/Textures/Particles/spark_04.png");
AddTexture(L"../../Assets/Textures/Particles/z_Pepper.png");
// Set default sampler state settings
pSamplerFilter = D3D11_FILTER_ANISOTROPIC;
pAnisotropyPower = 4;
// Create the sampler state
SetGlobalSamplerState(pSamplerFilter, (int)pow(2, pAnisotropyPower));
// Create materials
// MATERIALS 0-2
AddMaterial("Mat_Normals", vsDiffuseSpecular, psNormals);
AddMaterial("Mat_UVs", vsDiffuseSpecular, psUVs);
AddMaterial("Mat_Custom", vsDiffuseSpecular, psCustom);
// MATERIALS 3-9
AddPBRMaterial("Mat_Bronze_PBR", vsPBR, psPBR, 1.0f, 1.0f);
materials[3]->AddTextureSRV("MapAlbedoMetalness", textures[0]);
materials[3]->AddTextureSRV("MapNormalRoughness", textures[1]);
materials[3]->AddSampler("BasicSampler", samplerState);
AddPBRMaterial("Mat_Cobblestone_PBR", vsPBR, psPBR, 1.0f, 1.0f);
materials[4]->AddTextureSRV("MapAlbedoMetalness", textures[2]);
materials[4]->AddTextureSRV("MapNormalRoughness", textures[3]);
materials[4]->AddSampler("BasicSampler", samplerState);
AddPBRMaterial("Mat_Floor_PBR", vsPBR, psPBR, 1.0f, 1.0f);
materials[5]->AddTextureSRV("MapAlbedoMetalness", textures[4]);
materials[5]->AddTextureSRV("MapNormalRoughness", textures[5]);
materials[5]->AddSampler("BasicSampler", samplerState);
AddPBRMaterial("Mat_Paint_PBR", vsPBR, psPBR, 1.0f, 1.0f);
materials[6]->AddTextureSRV("MapAlbedoMetalness", textures[6]);
materials[6]->AddTextureSRV("MapNormalRoughness", textures[7]);
materials[6]->AddSampler("BasicSampler", samplerState);
AddPBRMaterial("Mat_Rough_PBR", vsPBR, psPBR, 1.0f, 1.0f);
materials[7]->AddTextureSRV("MapAlbedoMetalness", textures[8]);
materials[7]->AddTextureSRV("MapNormalRoughness", textures[9]);
materials[7]->AddSampler("BasicSampler", samplerState);
AddPBRMaterial("Mat_Scratched_PBR", vsPBR, psPBR, 1.0f, 1.0f);
materials[8]->AddTextureSRV("MapAlbedoMetalness", textures[10]);
materials[8]->AddTextureSRV("MapNormalRoughness", textures[11]);
materials[8]->AddSampler("BasicSampler", samplerState);
AddPBRMaterial("Mat_Wood_PBR", vsPBR, psPBR, 1.0f, 1.0f);
materials[9]->AddTextureSRV("MapAlbedoMetalness", textures[12]);
materials[9]->AddTextureSRV("MapNormalRoughness", textures[13]);
materials[9]->AddSampler("BasicSampler", samplerState);
materials[9]->SetUVScale(XMFLOAT2(3.0f, 3.0f));
}
// --------------------------------------------------------
// Creates the geometry we're going to draw and all
// entities in the scene
// --------------------------------------------------------
void Game::CreateGeometry()
{
// Create meshes from OBJ models
// MESHES 0-6
meshes.push_back(make_shared<Mesh>("M_Cube", FixPath(L"../../Assets/Models/cube.obj").c_str()));
meshes.push_back(make_shared<Mesh>("M_Cylinder", FixPath(L"../../Assets/Models/cylinder.obj").c_str()));
meshes.push_back(make_shared<Mesh>("M_Helix", FixPath(L"../../Assets/Models/helix.obj").c_str()));
meshes.push_back(make_shared<Mesh>("M_Quad-SingleSided", FixPath(L"../../Assets/Models/quad.obj").c_str()));
meshes.push_back(make_shared<Mesh>("M_Quad-DoubleSided", FixPath(L"../../Assets/Models/quad_double_sided.obj").c_str()));
meshes.push_back(make_shared<Mesh>("M_Sphere", FixPath(L"../../Assets/Models/sphere.obj").c_str()));
meshes.push_back(make_shared<Mesh>("M_Torus", FixPath(L"../../Assets/Models/torus.obj").c_str()));
// ENTITIES 0-6
AddEntity("E_ObjectBronze", 0, 3, XMFLOAT3(-9.0f, 0.0f, 0.0f));
AddEntity("E_ObjectCobblestone", 1, 4, XMFLOAT3(-6.0f, 0.0f, 0.0f));
AddEntity("E_ObjectFloor", 2, 5, XMFLOAT3(-3.0f, 0.0f, 0.0f));
AddEntity("E_ObjectPaint", 3, 6, XMFLOAT3( 0.0f, -1.0f, 0.0f));
AddEntity("E_ObjectRough", 4, 7, XMFLOAT3( 3.0f, -1.0f, 0.0f));
AddEntity("E_ObjectScratched", 5, 8, XMFLOAT3( 6.0f, 0.0f, 0.0f));
AddEntity("E_ObjectWood", 6, 9, XMFLOAT3( 9.0f, 0.0f, 0.0f));
// ENTITY 7-9
AddEntity("E_Floor", 0, 9, XMFLOAT3( 0.0f, -2.0f, 0.0f));
entities[7]->GetTransform()->Scale(XMFLOAT3(50.0f, 0.125f, 50.0f));
AddEntity("E_Wall1", 0, 6, XMFLOAT3( -12.0f, 1.0f, 0.0f));
entities[8]->GetTransform()->Scale(XMFLOAT3(0.125f, 3.0f, 5.0f));
AddEntity("E_Wall2", 0, 6, XMFLOAT3( 0.0f, 1.0f, 5.0f));
entities[9]->GetTransform()->Scale(XMFLOAT3(12.0f, 3.0f, 0.125f));
// ENTITIES 10-11
AddEntity("E_BouncerSpring", 2, 7, XMFLOAT3( 0.0f, -1.0f, 3.0f));
AddEntity("E_BouncerCylinder", 1, 3, XMFLOAT3( 0.0f, 0.0f, 3.0f));
entities[11]->GetTransform()->Scale(XMFLOAT3(1.2f, 1.0f, 1.2f));
}
// --------------------------------------------------------
// Creates the lights to be rendered in the scene
// --------------------------------------------------------
void Game::CreateLights() {
// Create lights
// LIGHT 0
AddLightSpot(XMFLOAT3(5.0f, 3.0f, -3.0f), XMFLOAT3(-0.25f, -0.5f, 0.5f), XMFLOAT3(1.0f, 1.0f, 1.0f), 1.0f, 25.0f, 0.0f, 1.4f, true);
lights[0].Type = LIGHT_TYPE_DIRECTIONAL;
// LIGHTS 1-2
AddLightDirectional(XMFLOAT3(1.0f, -1.0f, -1.0f), XMFLOAT3(1.0f, 1.0f, 1.0f), 0.5f, true);
AddLightDirectional(XMFLOAT3(-1.0f, 1.0f, -1.0f), XMFLOAT3(1.0f, 1.0f, 1.0f), 1.0f, false);
}
// --------------------------------------------------------
// Creates the cameras we'll need in the scene
// --------------------------------------------------------
void Game::CreateCameras() {
// Create cameras
float aspect = (Window::Width() + 0.0f) / Window::Height();
// CAMERAS 0-3
AddCamera("C_Main", XMFLOAT3(0.0f, 0.0f, -5.0f), XMFLOAT3(0.0f, 0.0f, 0.0f), aspect, false);
AddCamera("C_OrthoYZ", XMFLOAT3(100.0f, 0.0f, 0.0f), XMFLOAT3(0.0f, -XM_PIDIV2, 0.0f), aspect, true);
cameras[1]->SetLookSpeed(1.0f);
AddCamera("C_OrthoXZ", XMFLOAT3(0.0f, 100.0f, 0.0f), XMFLOAT3(XM_PIDIV2 - 0.001f, 0.0f, 0.0f), aspect, true);
cameras[2]->SetLookSpeed(1.0f);
AddCamera("C_OrthoXY", XMFLOAT3(0.0f, 0.0f, -100.0f), XMFLOAT3(0.0f, 0.0f, 0.0f), aspect, true);
cameras[3]->SetLookSpeed(1.0f);
}
void Game::CreateSkyboxes() {
// SKYBOXES 0
AddSkybox("SB_Blank", L"../../Assets/Textures/Cubemaps/Blank/CM_Blank", XMFLOAT3(0.0f, 0.0f, 0.0f));
// SKYBOXES 1-4
AddSkybox("SB_CloudsBlue", L"../../Assets/Textures/Cubemaps/CloudsBlue/CM_CloudsBlue", XMFLOAT3(0.0f, 0.0f, 0.075f));
// Set this as the environment map used by each material with normal map calculations
SetMaterialEnvironmentMaps(skyboxes[1]);
AddSkybox("SB_CloudsPink", L"../../Assets/Textures/Cubemaps/CloudsPink/CM_CloudsPink", XMFLOAT3(0.025f, 0.0f, 0.05f));
AddSkybox("SB_ColdSunset", L"../../Assets/Textures/Cubemaps/ColdSunset/CM_ColdSunset", XMFLOAT3(0.05f, 0.05f, 0.125f));
AddSkybox("SB_Planet", L"../../Assets/Textures/Cubemaps/Planet/CM_Planet", XMFLOAT3(0.0f, 0.0f, 0.025f));
}
void Game::CreateParticleEmitters()
{
}
// --------------------------------------------------------
// Handle resizing to match the new window size
// - Eventually, we'll want to update our 3D camera
// --------------------------------------------------------
void Game::OnResize()
{
// Only run these functions if the Window has been initialized
if (isInitialized) {
// If cameras exist, resize it
if (cameras.size() > 0) {
cameras[pCameraCurrent]->SetAspect((Window::Width() + 0.0f) / Window::Height());
}
ppPixelSize = XMFLOAT2(1.0f / Window::Width(), 1.0f / Window::Height());
RebuildPostProcesses();
}
}
// --------------------------------------------------------
// Update your game here - user input, move objects, AI, etc.
// --------------------------------------------------------
void Game::Update(float deltaTime, float totalTime)
{
// Update current camera
cameras[pCameraCurrent]->Update(deltaTime);
// Rotate meshes
for (int i = 0; i <= 6; i++) {
entities[i]->GetTransform()->Rotate(0.0f, deltaTime * pObjectRotationSpeed, 0.0f);
}
// Move bouncer
shared_ptr<Transform> bouncerSpringTransform = entities[10]->GetTransform();
bouncerSpringTransform->SetPosition(0.0f,
sin(totalTime * 4.0f) * 2.0f - sin((totalTime + 0.225f) * 8.0f) * 0.8f,
3.0f);
bouncerSpringTransform->SetScale(1.0f,
1.2f + sin((totalTime + 0.225f) * 8.0f) * 0.8f,
1.0f);
entities[11]->GetTransform()->SetPosition(0.0f,
sin(totalTime * 4.0f) * 2.0f + 2.0f,
3.0f);
ImGuiUpdate(deltaTime);
ImGuiBuild();
// Example input checking: Quit if the escape key is pressed
if (Input::KeyDown(VK_ESCAPE))
Window::Quit();
}
// --------------------------------------------------------
// Clear the screen, redraw everything, present to the user
// --------------------------------------------------------
void Game::Draw(float deltaTime, float totalTime)
{
// Frame START
// - These things should happen ONCE PER FRAME
// - At the beginning of Game::Draw() before drawing *anything*
{
// Clear the back buffer (erase what's on screen) and depth buffer
Graphics::Context->ClearRenderTargetView(Graphics::BackBufferRTV.Get(), pBackgroundColor);
Graphics::Context->ClearDepthStencilView(Graphics::DepthBufferDSV.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
}
// RENDER SHADOW MAP
// Clear shadow map depth buffer
Graphics::Context->ClearDepthStencilView(shadowDSV.Get(), D3D11_CLEAR_DEPTH, 1.0f, 0);
// Set shadow map rasterizer state
Graphics::Context->RSSetState(shadowRasterizer.Get());
// Set render target to nothing, depth buffer to shadow map
ID3D11RenderTargetView* nullRTV{};
Graphics::Context->OMSetRenderTargets(1, &nullRTV, shadowDSV.Get());
// Change viewport
D3D11_VIEWPORT viewport = {};
viewport.Width = (float)pShadowResolution;
viewport.Height = (float)pShadowResolution;
viewport.MaxDepth = 1.0f;
Graphics::Context->RSSetViewports(1, &viewport);
// Set shaders
Graphics::Context->PSSetShader(0, 0, 0);
vsShadowMap->SetShader();
vsShadowMap->SetMatrix4x4("view", shadowLightViewMatrix);
vsShadowMap->SetMatrix4x4("projection", shadowLightProjectionMatrix);
// Draw all entities
for (int i = 0; i < entities.size(); i++) {
vsShadowMap->SetMatrix4x4("world", entities[i]->GetTransform()->GetWorld());
vsShadowMap->CopyAllBufferData();
// Draw the entity's mesh
entities[i]->GetMesh()->Draw();
}
// Reset viewport, render target, depth buffer, and rasterizer state for normal rendering
viewport.Width = (float)Window::Width();
viewport.Height = (float)Window::Height();
Graphics::Context->RSSetViewports(1, &viewport);
// POST-PROCESS SETUP
// Clear RTVs for active post-processes
if (ppBlurRun) {
Graphics::Context->ClearRenderTargetView(ppBlurRTV.Get(), pBackgroundColor);
}
if (ppDitherRun) {
Graphics::Context->ClearRenderTargetView(ppDitherRTV.Get(), pBackgroundColor);
}
// Set render target based on the first post-process that will run, if any
if (ppBlurRun) {
// Set render target to our blur's render target
Graphics::Context->OMSetRenderTargets(
1,
ppBlurRTV.GetAddressOf(),
Graphics::DepthBufferDSV.Get()
);
}
// If no blur but yes dither, set render target to the dither's texture
else if (ppDitherRun) {
// Set render target to our dither's render target
Graphics::Context->OMSetRenderTargets(
1,
ppDitherRTV.GetAddressOf(),
Graphics::DepthBufferDSV.Get()
);
}
// If no blur or dither, set render target to back buffer
else {
Graphics::Context->OMSetRenderTargets(
1,
Graphics::BackBufferRTV.GetAddressOf(),
Graphics::DepthBufferDSV.Get()
);
}
Graphics::Context->RSSetState(0);
// RENDER OBJECTS
// Loop through every entity and draw it
for (int i = 0; i < entities.size(); i++) {
// Get entity material
std::shared_ptr<Material> material = entities[i]->GetMaterial();
// Prepare the material for drawing
material->PrepareMaterial();
// Get entity's shaders
std::shared_ptr<SimpleVertexShader> vs = material->GetVertexShader();
std::shared_ptr<SimplePixelShader> ps = material->GetPixelShader();
// Set vertex and pixel shaders
vs->SetShader();
ps->SetShader();
// Fill constant buffers with entity's data
// VERTEX
vs->SetMatrix4x4("tfWorld", entities[i]->GetTransform()->GetWorld());
vs->SetMatrix4x4("tfView", cameras[pCameraCurrent]->GetViewMatrix());
vs->SetMatrix4x4("tfProjection", cameras[pCameraCurrent]->GetProjectionMatrix());
vs->SetMatrix4x4("tfWorldIT", entities[i]->GetTransform()->GetWorldInverseTranspose());
vs->SetMatrix4x4("tfShadowView", shadowLightViewMatrix);
vs->SetMatrix4x4("tfShadowProjection", shadowLightProjectionMatrix);
// PIXEL
ps->SetFloat4("colorTint", material->GetColorTint());
ps->SetFloat("roughness", material->GetRoughness());
ps->SetFloat3("cameraPosition", cameras[pCameraCurrent]->GetTransform()->GetPosition());
ps->SetFloat2("uvPosition", material->GetUVPosition());
ps->SetFloat2("uvScale", material->GetUVScale());
// Set lights on pixel shader
ps->SetData("lights", &lights[0], sizeof(Light) * (int)lights.size());
// MATERIAL-SPECIFIC PIXEL SHADER CONSTANT BUFFER INPUTS
if (material->GetName() == "Mat_Custom") {
ps->SetFloat("totalTime", totalTime);
ps->SetFloat2("imageCenter", pMatCustomImage);
ps->SetFloat2("zoomCenter", pMatCustomZoom);
ps->SetInt("maxIterations", pMatCustomIterations);
}
if (material->isPBR) {
// Only use metalness for PBR materials
ps->SetFloat("metalness", material->GetMetalness());
}
else {
// Only use ambient light for non-PBR materials
ps->SetFloat3("lightAmbient", skyboxAmbientColors[pSkyboxCurrent]);
}
// COPY DATA TO CONSTANT BUFFERS
vs->CopyAllBufferData();
ps->CopyAllBufferData();
// Draw the entity's mesh
entities[i]->GetMesh()->Draw();
}
// Draw the selected skybox
skyboxes[pSkyboxCurrent]->Draw(cameras[pCameraCurrent]);
// POST-PROCESS
// Blur
if (ppBlurRun) {
// If doing dither after this, set render target to dither's RTV
if (ppDitherRun) {
Graphics::Context->OMSetRenderTargets(1, ppDitherRTV.GetAddressOf(), 0);
}
// If not, set render target to back buffer
else {
Graphics::Context->OMSetRenderTargets(1, Graphics::BackBufferRTV.GetAddressOf(), 0);
}
// Bind shaders
ppVS->SetShader();
ppBlurPS->SetShader();
ppBlurPS->SetShaderResourceView("BaseRender", ppBlurSRV.Get());
ppBlurPS->SetSamplerState("ClampSampler", ppSampler.Get());
// Set constant buffer data
ppBlurPS->SetInt("blurRadius", ppBlurRadius);
ppBlurPS->SetFloat2("pixelSize", ppPixelSize);
ppBlurPS->CopyAllBufferData();
// Draw
Graphics::Context->Draw(3, 0);
}
// Dither
if (ppDitherRun) {
// Set render target to back buffer
Graphics::Context->OMSetRenderTargets(1, Graphics::BackBufferRTV.GetAddressOf(), 0);
// Bind shaders
ppVS->SetShader();
ppDitherPS->SetShader();
ppDitherPS->SetShaderResourceView("BaseRender", ppDitherSRV.Get());
// Set the appropriate dither map
ppDitherPS->SetShaderResourceView("MapDither", ppDitherMaps[ppDitherMapTextureID].Get());
ppDitherPS->SetSamplerState("ClampSampler", ppSampler.Get());
// Set the appropriate sampler
ppDitherPS->SetSamplerState("DitherMapSampler", ppDitherMapSampler.Get());
// Set constant buffer data
ppDitherPS->SetFloat3("colorLight", ppDitherColorLight);
ppDitherPS->SetInt("ditherPixelSize", ppDitherPixelSize);
ppDitherPS->SetFloat3("colorDark", ppDitherColorDark);
ppDitherPS->SetFloat("bias", ppDitherBias);
XMFLOAT3 camRotation = cameras[pCameraCurrent]->GetTransform()->GetRotation();
float camFov = cameras[pCameraCurrent]->GetFov();
ppDitherPS->SetFloat3("cameraRotation", camRotation);
ppDitherPS->SetFloat("cameraFov", camFov);
ppDitherPS->SetFloat2("pixelSize", ppPixelSize);
ppDitherPS->SetFloat2("screenSize", XMFLOAT2((float)Window::Width(), (float)Window::Height()));
ppDitherPS->CopyAllBufferData();
// Draw
Graphics::Context->Draw(3, 0);
}
// RENDER IMGUI
ImGui::Render(); // Turns this frames UI into renderable triangles
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); // Draws it to the screen
// FRAME END
// - These should happen exactly ONCE PER FRAME
// - At the very end of the frame (after drawing *everything*)
{
// Present at the end of the frame
bool vsync = Graphics::VsyncState();
Graphics::SwapChain->Present(
vsync ? 1 : 0,
vsync ? 0 : DXGI_PRESENT_ALLOW_TEARING);
// Re-bind back buffer and depth buffer after presenting
Graphics::Context->OMSetRenderTargets(
1,
Graphics::BackBufferRTV.GetAddressOf(),
Graphics::DepthBufferDSV.Get());
// Unbind all SRVs at the end of the frame
ID3D11ShaderResourceView* nullSRVs[128] = {};
Graphics::Context->PSSetShaderResources(0, 128, nullSRVs);
}
}
// --------------------------------------------------------
//
// CUSTOM HELPER METHODS
//
// --------------------------------------------------------
// --------------------------------------------------------
// Initializes the all simulation variables
// to their default values
// --------------------------------------------------------
void Game::InitializeSimulationParameters() {
// IMGUI PARAMETERS
igShowDemo = false;
// Uncomment for original cornflower blue
//float bgColor[4] = { 0.4f, 0.6f, 0.75f, 1.0f };
float bgColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
memcpy(pBackgroundColor, bgColor, sizeof(float) * 4);
pObjectRotationSpeed = 1.0f;
pSelectedSamplerFilter = 5;
pMatCustomIterations = 100;
pMatCustomImage = XMFLOAT2(-1.77f, -0.02f);
pMatCustomZoom = XMFLOAT2(-0.2f, -0.61f);
pCameraCurrent = 0;
pSkyboxCurrent = 1;
pRenderShadows = true;
pShadowResolutionExponent = 10;
pShadowResolution = 1024;
pShadowAreaWidth = 30.0f;
pShadowAreaCenter = XMFLOAT3(0.0f, -5.0f, 0.0f);
pShadowLightDistance = 500.0f;
ppPixelSize = XMFLOAT2(1.0f / Window::Width(), 1.0f / Window::Height());
ppBlurRun = false;
ppBlurRadius = 5;
ppDitherRun = false;
ppDitherMapTextureID = 3;
ppDitherPixelSize = 2;
ppDitherBias = -0.25f;
ppDitherColorLight = XMFLOAT3(1.0f, 1.0f, 1.0f);
ppDitherColorDark = XMFLOAT3(0.25f, 0.25f, 0.25f);
// Framerate graph variables
igFrameGraphSamples = new float[IG_FRAME_GRAPH_TOTAL_SAMPLES];
// Zero out all of our sample array
for (int i = 0; i < IG_FRAME_GRAPH_TOTAL_SAMPLES; i++) {
igFrameGraphSamples[i] = 0;
}
igFrameGraphSampleCount = 240;
igFrameGraphSampleRate = 60.0f;
igFrameGraphNextSampleTime = 0.0;
igFrameGraphSampleOffset = 0;
igFrameGraphHighest = 0.0f;
igFrameGraphDoAnimate = true;
isInitialized = true;
}
// --------------------------------------------------------
// Adds a vertex shader to the list of vertex shaders
// --------------------------------------------------------
void Game::AddVertexShader(const wchar_t* _path, std::shared_ptr<SimpleVertexShader>& _shader)
{
_shader = make_shared<SimpleVertexShader>(
Graphics::Device,
Graphics::Context,
FixPath(_path).c_str()
);
}
// --------------------------------------------------------
// Adds a pixel shader to the list of pixel shaders
// --------------------------------------------------------
void Game::AddPixelShader(const wchar_t* _path, std::shared_ptr<SimplePixelShader>& _shader)
{
_shader = make_shared<SimplePixelShader>(
Graphics::Device,
Graphics::Context,
FixPath(_path).c_str()
);
}
// --------------------------------------------------------
// Adds a texture to the list of material textures
// --------------------------------------------------------
void Game::AddTexture(const wchar_t* _path)
{
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> srv;
LoadTexture(_path, srv);
textures.push_back(srv);
}
// --------------------------------------------------------
// Adds a texture to a given list of textures
// --------------------------------------------------------
void Game::LoadTexture(const wchar_t* _path, std::vector<Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>>& _srvVector)
{
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> srv;
LoadTexture(_path, srv);
_srvVector.push_back(srv);
}
// --------------------------------------------------------
// Loads a texture into the given SRV
// --------------------------------------------------------
void Game::LoadTexture(const wchar_t* _path, Microsoft::WRL::ComPtr<ID3D11ShaderResourceView>& _srv)
{
CreateWICTextureFromFile(
Graphics::Device.Get(),
Graphics::Context.Get(),
FixPath(_path).c_str(),
nullptr,
_srv.GetAddressOf()
);
}
// --------------------------------------------------------
// Adds a Material to the list of Materials
// --------------------------------------------------------
void Game::AddMaterial(const char* _name, std::shared_ptr<SimpleVertexShader> _vertexShader, std::shared_ptr<SimplePixelShader> _pixelShader, DirectX::XMFLOAT4 _colorTint, float _roughness, bool _useGlobalEnvironmentMap)
{
materials.push_back(make_shared<Material>(
_name,
_vertexShader,
_pixelShader,
_colorTint,
_roughness,
_useGlobalEnvironmentMap
));
}
void Game::AddMaterial(const char* _name, std::shared_ptr<SimpleVertexShader> _vertexShader, std::shared_ptr<SimplePixelShader> _pixelShader, DirectX::XMFLOAT4 _colorTint, float _roughness)
{
AddMaterial(_name, _vertexShader, _pixelShader, _colorTint, _roughness, false);
}
void Game::AddMaterial(const char* _name, std::shared_ptr<SimpleVertexShader> _vertexShader, std::shared_ptr<SimplePixelShader> _pixelShader, DirectX::XMFLOAT4 _colorTint)
{
AddMaterial(_name, _vertexShader, _pixelShader, _colorTint, 0.0f, false);
}
void Game::AddMaterial(const char* _name, std::shared_ptr<SimpleVertexShader> _vertexShader, std::shared_ptr<SimplePixelShader> _pixelShader, float _roughness, bool _useGlobalEnvironmentMap)
{
AddMaterial(_name, _vertexShader, _pixelShader, XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), _roughness, _useGlobalEnvironmentMap);
}
void Game::AddMaterial(const char* _name, std::shared_ptr<SimpleVertexShader> _vertexShader, std::shared_ptr<SimplePixelShader> _pixelShader, float _roughness)
{
AddMaterial(_name, _vertexShader, _pixelShader, XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), _roughness, false);
}
void Game::AddMaterial(const char* _name, std::shared_ptr<SimpleVertexShader> _vertexShader, std::shared_ptr<SimplePixelShader> _pixelShader)
{
AddMaterial(_name, _vertexShader, _pixelShader, XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), 0.0f, false);
}
void Game::AddPBRMaterial(const char* _name, std::shared_ptr<SimpleVertexShader> _vertexShader, std::shared_ptr<SimplePixelShader> _pixelShader, DirectX::XMFLOAT4 _colorTint, float _roughness, float _metalness)
{
materials.push_back(make_shared<Material>(
_name,
_vertexShader,
_pixelShader,
_colorTint,
_roughness,
_metalness
));
}
void Game::AddPBRMaterial(const char* _name, std::shared_ptr<SimpleVertexShader> _vertexShader, std::shared_ptr<SimplePixelShader> _pixelShader, float _roughness, float _metalness)
{
AddPBRMaterial(_name, _vertexShader, _pixelShader, XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f), 1.0f, 1.0f);
}
// --------------------------------------------------------
// Adds an Entity to the list of Entities
// --------------------------------------------------------
void Game::AddEntity(const char* _name, unsigned int _meshIndex, unsigned int _materialIndex, DirectX::XMFLOAT3 _position)
{
shared_ptr<Entity> entity = make_shared<Entity>(
_name,
meshes[_meshIndex],
materials[_materialIndex]
);
entity->GetTransform()->SetPosition(_position);
entities.push_back(entity);
}
// --------------------------------------------------------
// Adds a Light of a given type to the list of Lights
// --------------------------------------------------------
void Game::AddLightDirectional(DirectX::XMFLOAT3 _direction, DirectX::XMFLOAT3 _color, float _intensity, bool _isActive)
{
Light light = {};
light.Type = LIGHT_TYPE_DIRECTIONAL;
light.Direction = _direction;
light.Color = _color;
light.Intensity = _intensity;
light.Active = _isActive ? 1 : 0;
lights.push_back(light);
}
void Game::AddLightPoint(DirectX::XMFLOAT3 _position, DirectX::XMFLOAT3 _color, float _intensity, float _range, bool _isActive)
{
Light light = {};
light.Type = LIGHT_TYPE_POINT;
light.Position = _position;
light.Color = _color;
light.Intensity = _intensity;
light.Range = _range;
light.Active = _isActive ? 1 : 0;
lights.push_back(light);
}
void Game::AddLightSpot(DirectX::XMFLOAT3 _position, DirectX::XMFLOAT3 _direction, DirectX::XMFLOAT3 _color, float _intensity, float _range, float _innerAngle, float _outerAngle, bool _isActive)
{
Light light = {};
light.Type = LIGHT_TYPE_SPOT;
light.Position = _position;
light.Direction = _direction;
light.Color = _color;
light.Intensity = _intensity;
light.Range = _range;
light.SpotInnerAngle = _innerAngle;
light.SpotOuterAngle = _outerAngle;
light.Active = _isActive ? 1 : 0;
lights.push_back(light);
}
// --------------------------------------------------------
// Adds a Camera to the list of Cameras
// --------------------------------------------------------
void Game::AddCamera(const char* _name, DirectX::XMFLOAT3 _position, DirectX::XMFLOAT3 _rotation, float _aspect)
{
shared_ptr<Camera> camera = make_shared<Camera>(
_name,
make_shared<Transform>(),
_aspect
);
camera->GetTransform()->SetPosition(_position);
camera->GetTransform()->SetRotation(_rotation);
cameras.push_back(camera);
}
void Game::AddCamera(const char* _name, DirectX::XMFLOAT3 _position, DirectX::XMFLOAT3 _rotation, float _aspect, float _fov)
{
shared_ptr<Camera> camera = make_shared<Camera>(
_name,
make_shared<Transform>(),
_aspect,
_fov
);
camera->GetTransform()->SetPosition(_position);
camera->GetTransform()->SetRotation(_rotation);
cameras.push_back(camera);
}
void Game::AddCamera(const char* _name, DirectX::XMFLOAT3 _position, DirectX::XMFLOAT3 _rotation, float _aspect, bool _isOrthographic)
{
shared_ptr<Camera> camera = make_shared<Camera>(
_name,
make_shared<Transform>(),
_aspect,
_isOrthographic
);
camera->GetTransform()->SetPosition(_position);
camera->GetTransform()->SetRotation(_rotation);
cameras.push_back(camera);
}
void Game::AddCamera(const char* _name, DirectX::XMFLOAT3 _position, DirectX::XMFLOAT3 _rotation, float _aspect, bool _isOrthographic, float _orthoWidth)
{
shared_ptr<Camera> camera = make_shared<Camera>(
_name,
make_shared<Transform>(),
_aspect,
_isOrthographic,
_orthoWidth
);
camera->GetTransform()->SetPosition(_position);
camera->GetTransform()->SetRotation(_rotation);
cameras.push_back(camera);
}
// --------------------------------------------------------
// Adds a Skybox to the list of Skyboxes
// --------------------------------------------------------
void Game::AddSkybox(const char* _name, std::wstring _pathBase, DirectX::XMFLOAT3 _ambientColor)
{
skyboxes.push_back(make_shared<Skybox>(
_name, meshes[0], samplerState, vsSkybox, psSkybox,
_pathBase
));
skyboxAmbientColors.push_back(_ambientColor);
}
// --------------------------------------------------------
// Sets the sampler state in the samplerState variable
// based on the given graphics settings
// --------------------------------------------------------
void Game::SetGlobalSamplerState(D3D11_FILTER _filter, int _anisotropyLevel) {
// Reset sampler state if one exists
samplerState = nullptr;
// Sampler state description for changing sampler state with UI
D3D11_SAMPLER_DESC samplerDescription = {};
// Set default sampler state values
samplerDescription.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDescription.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDescription.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDescription.Filter = _filter;
samplerDescription.MaxAnisotropy = _anisotropyLevel;
samplerDescription.MaxLOD = D3D11_FLOAT32_MAX;
// Create sampler state
Graphics::Device->CreateSamplerState(&samplerDescription, &samplerState);
}
// --------------------------------------------------------
// Sets the sampler states of each Material
// --------------------------------------------------------
void Game::SetMaterialSamplerStates() {
for (int i = 0; i < materials.size(); i++) {
materials[i]->AddSampler("BasicSampler", samplerState);
}
}
// --------------------------------------------------------
// Sets the environment map of each Material, if they use one
// --------------------------------------------------------
void Game::SetMaterialEnvironmentMaps(shared_ptr<Skybox> _skybox)
{
for (int i = 0; i < materials.size(); i++) {
if (materials[i]->useGlobalEnvironmentMap) {
materials[i]->AddTextureSRV("MapCube", _skybox->GetSRV());
}
}
}
// --------------------------------------------------------
// Builds all DirectX resources for the shadow map for the first time
// Code written by Chris Cascioli
// --------------------------------------------------------
void Game::BuildShadowMap() {
// Create the rasterizer state for rendering the shadow map
D3D11_RASTERIZER_DESC shadowRastDesc = {};
shadowRastDesc.FillMode = D3D11_FILL_SOLID;
shadowRastDesc.CullMode = D3D11_CULL_BACK;
shadowRastDesc.DepthClipEnable = true;
shadowRastDesc.DepthBias = 1000; // Min. precision units, not world units!
shadowRastDesc.SlopeScaledDepthBias = 1.0f; // Bias more based on slope
Graphics::Device->CreateRasterizerState(&shadowRastDesc, &shadowRasterizer);
// Create the sampler for the shadow map texture
D3D11_SAMPLER_DESC shadowSampDesc = {};
shadowSampDesc.Filter = D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR;
shadowSampDesc.ComparisonFunc = D3D11_COMPARISON_LESS;
shadowSampDesc.AddressU = D3D11_TEXTURE_ADDRESS_BORDER;
shadowSampDesc.AddressV = D3D11_TEXTURE_ADDRESS_BORDER;
shadowSampDesc.AddressW = D3D11_TEXTURE_ADDRESS_BORDER;
shadowSampDesc.BorderColor[0] = 1.0f; // Only need the first component
Graphics::Device->CreateSamplerState(&shadowSampDesc, &shadowSampler);
// Add shadow map sampler state to materials that need it
for (int i = 3; i < materials.size(); i++) {
materials[i]->AddSampler("ShadowSampler", shadowSampler);
}
// Build DSV and SRV
RebuildShadowMap();
}
// --------------------------------------------------------
// Rebuilds just the shadow map's DSV and SRV
// Code written by Chris Cascioli