forked from vixorien/D3D11Starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleShader.cpp
1970 lines (1695 loc) · 65.1 KB
/
SimpleShader.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 "SimpleShader.h"
// Default error reporting state
bool ISimpleShader::ReportErrors = false;
bool ISimpleShader::ReportWarnings = false;
// To enable error reporting, use either or both
// of the following lines somewhere in your program,
// preferably before loading/using any shaders.
//
// ISimpleShader::ReportErrors = true;
// ISimpleShader::ReportWarnings = true;
///////////////////////////////////////////////////////////////////////////////
// ------ BASE SIMPLE SHADER --------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------
// Constructor accepts Direct3D device & context
// --------------------------------------------------------
ISimpleShader::ISimpleShader(Microsoft::WRL::ComPtr<ID3D11Device> device, Microsoft::WRL::ComPtr<ID3D11DeviceContext> context)
{
// Save the device
this->device = device;
this->deviceContext = context;
// Set up fields
this->constantBufferCount = 0;
this->constantBuffers = 0;
this->shaderValid = false;
}
// --------------------------------------------------------
// Destructor
// --------------------------------------------------------
ISimpleShader::~ISimpleShader()
{
// Derived class destructors will call this class's CleanUp method
}
// --------------------------------------------------------
// Cleans up the variable table and buffers - Some things will
// be handled by derived classes
// --------------------------------------------------------
void ISimpleShader::CleanUp()
{
// Handle constant buffers and local data buffers
for (unsigned int i = 0; i < constantBufferCount; i++)
{
delete[] constantBuffers[i].LocalDataBuffer;
}
if (constantBuffers)
{
delete[] constantBuffers;
constantBufferCount = 0;
}
for (unsigned int i = 0; i < shaderResourceViews.size(); i++)
delete shaderResourceViews[i];
for (unsigned int i = 0; i < samplerStates.size(); i++)
delete samplerStates[i];
// Clean up tables
varTable.clear();
cbTable.clear();
samplerTable.clear();
textureTable.clear();
}
// --------------------------------------------------------
// Loads the specified shader and builds the variable table
// using shader reflection.
//
// shaderFile - A "wide string" specifying the compiled shader to load
//
// Returns true if shader is loaded properly, false otherwise
// --------------------------------------------------------
bool ISimpleShader::LoadShaderFile(LPCWSTR shaderFile)
{
// Load the shader to a blob and ensure it worked
HRESULT hr = D3DReadFileToBlob(shaderFile, shaderBlob.GetAddressOf());
if (hr != S_OK)
{
if (ReportErrors)
{
LogError("SimpleShader::LoadShaderFile() - Error loading file '");
LogW(shaderFile);
LogError("'. Ensure this file exists and is spelled correctly.\n");
}
return false;
}
// Create the shader - Calls an overloaded version of this abstract
// method in the appropriate child class
shaderValid = CreateShader(shaderBlob);
if (!shaderValid)
{
if (ReportErrors)
{
LogError("SimpleShader::LoadShaderFile() - Error creating shader from file '");
LogW(shaderFile);
LogError("'. Ensure the type of shader (vertex, pixel, etc.) matches the SimpleShader type (SimpleVertexShader, SimplePixelShader, etc.) you're using.\n");
}
return false;
}
// Set up shader reflection to get information about
// this shader and its variables, buffers, etc.
Microsoft::WRL::ComPtr<ID3D11ShaderReflection> refl;
D3DReflect(
shaderBlob->GetBufferPointer(),
shaderBlob->GetBufferSize(),
IID_ID3D11ShaderReflection,
(void**)refl.GetAddressOf());
// Get the description of the shader
D3D11_SHADER_DESC shaderDesc;
refl->GetDesc(&shaderDesc);
// Create resource arrays
constantBufferCount = shaderDesc.ConstantBuffers;
constantBuffers = new SimpleConstantBuffer[constantBufferCount];
// Handle bound resources (like shaders and samplers)
unsigned int resourceCount = shaderDesc.BoundResources;
for (unsigned int r = 0; r < resourceCount; r++)
{
// Get this resource's description
D3D11_SHADER_INPUT_BIND_DESC resourceDesc;
refl->GetResourceBindingDesc(r, &resourceDesc);
// Check the type
switch (resourceDesc.Type)
{
case D3D_SIT_STRUCTURED: // Treat structured buffers as texture resources
case D3D_SIT_TEXTURE: // A texture resource
{
// Create the SRV wrapper
SimpleSRV* srv = new SimpleSRV();
srv->BindIndex = resourceDesc.BindPoint; // Shader bind point
srv->Index = (unsigned int)shaderResourceViews.size(); // Raw index
textureTable.insert(std::pair<std::string, SimpleSRV*>(resourceDesc.Name, srv));
shaderResourceViews.push_back(srv);
}
break;
case D3D_SIT_SAMPLER: // A sampler resource
{
// Create the sampler wrapper
SimpleSampler* samp = new SimpleSampler();
samp->BindIndex = resourceDesc.BindPoint; // Shader bind point
samp->Index = (unsigned int)samplerStates.size(); // Raw index
samplerTable.insert(std::pair<std::string, SimpleSampler*>(resourceDesc.Name, samp));
samplerStates.push_back(samp);
}
break;
}
}
// Loop through all constant buffers
for (unsigned int b = 0; b < constantBufferCount; b++)
{
// Get this buffer
ID3D11ShaderReflectionConstantBuffer* cb =
refl->GetConstantBufferByIndex(b);
// Get the description of this buffer
D3D11_SHADER_BUFFER_DESC bufferDesc;
cb->GetDesc(&bufferDesc);
// Save the type, which we reference when setting these buffers
constantBuffers[b].Type = bufferDesc.Type;
// Get the description of the resource binding, so
// we know exactly how it's bound in the shader
D3D11_SHADER_INPUT_BIND_DESC bindDesc;
refl->GetResourceBindingDescByName(bufferDesc.Name, &bindDesc);
// Set up the buffer and put its pointer in the table
constantBuffers[b].BindIndex = bindDesc.BindPoint;
constantBuffers[b].Name = bufferDesc.Name;
cbTable.insert(std::pair<std::string, SimpleConstantBuffer*>(bufferDesc.Name, &constantBuffers[b]));
// Create this constant buffer
D3D11_BUFFER_DESC newBuffDesc = {};
newBuffDesc.Usage = D3D11_USAGE_DEFAULT;
newBuffDesc.ByteWidth = ((bufferDesc.Size + 15) / 16) * 16; // Quick and dirty 16-byte alignment using integer division
newBuffDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
newBuffDesc.CPUAccessFlags = 0;
newBuffDesc.MiscFlags = 0;
newBuffDesc.StructureByteStride = 0;
device->CreateBuffer(&newBuffDesc, 0, constantBuffers[b].ConstantBuffer.GetAddressOf());
// Set up the data buffer for this constant buffer
constantBuffers[b].Size = bufferDesc.Size;
constantBuffers[b].LocalDataBuffer = new unsigned char[bufferDesc.Size];
ZeroMemory(constantBuffers[b].LocalDataBuffer, bufferDesc.Size);
// Loop through all variables in this buffer
for (unsigned int v = 0; v < bufferDesc.Variables; v++)
{
// Get this variable
ID3D11ShaderReflectionVariable* var =
cb->GetVariableByIndex(v);
// Get the description of the variable and its type
D3D11_SHADER_VARIABLE_DESC varDesc;
var->GetDesc(&varDesc);
// Create the variable struct
SimpleShaderVariable varStruct = {};
varStruct.ConstantBufferIndex = b;
varStruct.ByteOffset = varDesc.StartOffset;
varStruct.Size = varDesc.Size;
// Get a string version
std::string varName(varDesc.Name);
// Add this variable to the table and the constant buffer
varTable.insert(std::pair<std::string, SimpleShaderVariable>(varName, varStruct));
constantBuffers[b].Variables.push_back(varStruct);
}
}
// All set
return true;
}
// --------------------------------------------------------
// Helper for looking up a variable by name and also
// verifying that it is the requested size
//
// name - the name of the variable to look for
// size - the size of the variable (for verification), or -1 to bypass
// --------------------------------------------------------
SimpleShaderVariable* ISimpleShader::FindVariable(std::string name, int size)
{
// Look for the key
std::unordered_map<std::string, SimpleShaderVariable>::iterator result =
varTable.find(name);
// Did we find the key?
if (result == varTable.end())
return 0;
// Grab the result from the iterator
SimpleShaderVariable* var = &(result->second);
// Is the data size correct ?
if (size > 0 && var->Size != size)
return 0;
// Success
return var;
}
// --------------------------------------------------------
// Helper for looking up a constant buffer by name
// --------------------------------------------------------
SimpleConstantBuffer* ISimpleShader::FindConstantBuffer(std::string name)
{
// Look for the key
std::unordered_map<std::string, SimpleConstantBuffer*>::iterator result =
cbTable.find(name);
// Did we find the key?
if (result == cbTable.end())
return 0;
// Success
return result->second;
}
// --------------------------------------------------------
// Prints the specified message to the console with the
// given color and Visual Studio's output window
// --------------------------------------------------------
void ISimpleShader::Log(std::string message, WORD color)
{
// Swap console color
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, color);
printf_s(message.c_str());
OutputDebugStringA(message.c_str());
// Swap back
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
// --------------------------------------------------------
// Prints the specified message, as a wide string, to the
// console with the given color and Visual Studio's output window
// --------------------------------------------------------
void ISimpleShader::LogW(std::wstring message, WORD color)
{
// Swap console color
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, color);
wprintf_s(message.c_str());
OutputDebugStringW(message.c_str());
// Swap back
SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
}
// Helpers for pritning errors and warnings in specific colors using regular and wide character strings
void ISimpleShader::Log(std::string message) { Log(message, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY); }
void ISimpleShader::LogW(std::wstring message) { LogW(message, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY); }
void ISimpleShader::LogError(std::string message) { Log(message, FOREGROUND_RED | FOREGROUND_INTENSITY); }
void ISimpleShader::LogErrorW(std::wstring message) { LogW(message, FOREGROUND_RED | FOREGROUND_INTENSITY); }
void ISimpleShader::LogWarning(std::string message) { Log(message, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY); }
void ISimpleShader::LogWarningW(std::wstring message) { LogW(message, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY); }
// --------------------------------------------------------
// Sets the shader and associated constant buffers in Direct3D
// --------------------------------------------------------
void ISimpleShader::SetShader()
{
// Ensure the shader is valid
if (!shaderValid) return;
// Set the shader and any relevant constant buffers, which
// is an overloaded method in a subclass
SetShaderAndCBs();
}
// --------------------------------------------------------
// Copies the relevant data to the all of this
// shader's constant buffers. To just copy one
// buffer, use CopyBufferData()
// --------------------------------------------------------
void ISimpleShader::CopyAllBufferData()
{
// Ensure the shader is valid
if (!shaderValid) return;
// Loop through the constant buffers and copy all data
for (unsigned int i = 0; i < constantBufferCount; i++)
{
// Copy the entire local data buffer
deviceContext->UpdateSubresource(
constantBuffers[i].ConstantBuffer.Get(), 0, 0,
constantBuffers[i].LocalDataBuffer, 0, 0);
}
}
// --------------------------------------------------------
// Copies local data to the shader's specified constant buffer
//
// index - The index of the buffer to copy.
// Useful for updating more frequently-changing
// variables without having to re-copy all buffers.
//
// NOTE: The "index" of the buffer might NOT be the same
// as its register, especially if you have buffers
// bound to non-sequential registers!
// --------------------------------------------------------
void ISimpleShader::CopyBufferData(unsigned int index)
{
// Ensure the shader is valid
if (!shaderValid) return;
// Validate the index
if(index >= this->constantBufferCount)
return;
// Check for the buffer
SimpleConstantBuffer* cb = &this->constantBuffers[index];
if (!cb) return;
// Copy the data and get out
deviceContext->UpdateSubresource(
cb->ConstantBuffer.Get(), 0, 0,
cb->LocalDataBuffer, 0, 0);
}
// --------------------------------------------------------
// Copies local data to the shader's specified constant buffer
//
// bufferName - Specifies the name of the buffer to copy.
// Useful for updating more frequently-changing
// variables without having to re-copy all buffers.
// --------------------------------------------------------
void ISimpleShader::CopyBufferData(std::string bufferName)
{
// Ensure the shader is valid
if (!shaderValid) return;
// Check for the buffer
SimpleConstantBuffer* cb = this->FindConstantBuffer(bufferName);
if (!cb) return;
// Copy the data and get out
deviceContext->UpdateSubresource(
cb->ConstantBuffer.Get(), 0, 0,
cb->LocalDataBuffer, 0, 0);
}
// --------------------------------------------------------
// Sets a variable by name with arbitrary data of the specified size
//
// name - The name of the shader variable
// data - The data to set in the buffer
// size - The size of the data (this must be less than or equal to the variable's size)
//
// Returns true if data is copied, false if variable doesn't exist
// --------------------------------------------------------
bool ISimpleShader::SetData(std::string name, const void* data, unsigned int size)
{
// Look for the variable and verify
SimpleShaderVariable* var = FindVariable(name, -1);
if (var == 0)
{
if (ReportWarnings)
{
LogWarning("SimpleShader::SetData() - Shader variable '");
Log(name);
LogWarning("' not found. Ensure the name is spelled correctly and that it exists in a constant buffer in the shader.\n");
}
return false;
}
// Ensure we're not trying to copy more data than the variable can hold
// Note: We can copy less data, in the case of a subset of an array
if (size > var->Size)
{
if (ReportWarnings)
{
LogWarning("SimpleShader::SetData() - Shader variable '");
Log(name);
LogWarning("' is smaller than the size of the data being set. Ensure the variable is large enough for the specified data.\n");
}
return false;
}
// Set the data in the local data buffer
memcpy(
constantBuffers[var->ConstantBufferIndex].LocalDataBuffer + var->ByteOffset,
data,
size);
// Success
return true;
}
// --------------------------------------------------------
// Sets INTEGER data
// --------------------------------------------------------
bool ISimpleShader::SetInt(std::string name, int data)
{
return this->SetData(name, (void*)(&data), sizeof(int));
}
// --------------------------------------------------------
// Sets a FLOAT variable by name in the local data buffer
// --------------------------------------------------------
bool ISimpleShader::SetFloat(std::string name, float data)
{
return this->SetData(name, (void*)(&data), sizeof(float));
}
// --------------------------------------------------------
// Sets a FLOAT2 variable by name in the local data buffer
// --------------------------------------------------------
bool ISimpleShader::SetFloat2(std::string name, const float data[2])
{
return this->SetData(name, (void*)data, sizeof(float) * 2);
}
// --------------------------------------------------------
// Sets a FLOAT2 variable by name in the local data buffer
// --------------------------------------------------------
bool ISimpleShader::SetFloat2(std::string name, const DirectX::XMFLOAT2 data)
{
return this->SetData(name, &data, sizeof(float) * 2);
}
// --------------------------------------------------------
// Sets a FLOAT3 variable by name in the local data buffer
// --------------------------------------------------------
bool ISimpleShader::SetFloat3(std::string name, const float data[3])
{
return this->SetData(name, (void*)data, sizeof(float) * 3);
}
// --------------------------------------------------------
// Sets a FLOAT3 variable by name in the local data buffer
// --------------------------------------------------------
bool ISimpleShader::SetFloat3(std::string name, const DirectX::XMFLOAT3 data)
{
return this->SetData(name, &data, sizeof(float) * 3);
}
// --------------------------------------------------------
// Sets a FLOAT4 variable by name in the local data buffer
// --------------------------------------------------------
bool ISimpleShader::SetFloat4(std::string name, const float data[4])
{
return this->SetData(name, (void*)data, sizeof(float) * 4);
}
// --------------------------------------------------------
// Sets a FLOAT4 variable by name in the local data buffer
// --------------------------------------------------------
bool ISimpleShader::SetFloat4(std::string name, const DirectX::XMFLOAT4 data)
{
return this->SetData(name, &data, sizeof(float) * 4);
}
// --------------------------------------------------------
// Sets a MATRIX (4x4) variable by name in the local data buffer
// --------------------------------------------------------
bool ISimpleShader::SetMatrix4x4(std::string name, const float data[16])
{
return this->SetData(name, (void*)data, sizeof(float) * 16);
}
// --------------------------------------------------------
// Sets a MATRIX (4x4) variable by name in the local data buffer
// --------------------------------------------------------
bool ISimpleShader::SetMatrix4x4(std::string name, const DirectX::XMFLOAT4X4 data)
{
return this->SetData(name, &data, sizeof(float) * 16);
}
// --------------------------------------------------------
// Determines if the shader contains the specified
// variable within one of its constant buffers
// --------------------------------------------------------
bool ISimpleShader::HasVariable(std::string name)
{
return FindVariable(name, -1) != 0;
}
// --------------------------------------------------------
// Determines if the shader contains the specified SRV
// --------------------------------------------------------
bool ISimpleShader::HasShaderResourceView(std::string name)
{
return GetShaderResourceViewInfo(name) != 0;
}
// --------------------------------------------------------
// Determines if the shader contains the specified sampler
// --------------------------------------------------------
bool ISimpleShader::HasSamplerState(std::string name)
{
return GetSamplerInfo(name) != 0;
}
// --------------------------------------------------------
// Gets info about a shader variable, if it exists
// --------------------------------------------------------
const SimpleShaderVariable* ISimpleShader::GetVariableInfo(std::string name)
{
return FindVariable(name, -1);
}
// --------------------------------------------------------
// Gets info about an SRV in the shader (or null)
//
// name - the name of the SRV
// --------------------------------------------------------
const SimpleSRV* ISimpleShader::GetShaderResourceViewInfo(std::string name)
{
// Look for the key
std::unordered_map<std::string, SimpleSRV*>::iterator result =
textureTable.find(name);
// Did we find the key?
if (result == textureTable.end())
return 0;
// Success
return result->second;
}
// --------------------------------------------------------
// Gets info about an SRV in the shader (or null)
//
// index - the index of the SRV
// --------------------------------------------------------
const SimpleSRV* ISimpleShader::GetShaderResourceViewInfo(unsigned int index)
{
// Valid index?
if (index >= shaderResourceViews.size()) return 0;
// Grab the bind index
return shaderResourceViews[index];
}
// --------------------------------------------------------
// Gets info about a sampler in the shader (or null)
//
// name - the name of the sampler
// --------------------------------------------------------
const SimpleSampler* ISimpleShader::GetSamplerInfo(std::string name)
{
// Look for the key
std::unordered_map<std::string, SimpleSampler*>::iterator result =
samplerTable.find(name);
// Did we find the key?
if (result == samplerTable.end())
return 0;
// Success
return result->second;
}
// --------------------------------------------------------
// Gets info about a sampler in the shader (or null)
//
// index - the index of the sampler
// --------------------------------------------------------
const SimpleSampler* ISimpleShader::GetSamplerInfo(unsigned int index)
{
// Valid index?
if (index >= samplerStates.size()) return 0;
// Grab the bind index
return samplerStates[index];
}
// --------------------------------------------------------
// Gets the number of constant buffers in this shader
// --------------------------------------------------------
unsigned int ISimpleShader::GetBufferCount() { return constantBufferCount; }
// --------------------------------------------------------
// Gets the size of a particular constant buffer, or -1
// --------------------------------------------------------
unsigned int ISimpleShader::GetBufferSize(unsigned int index)
{
// Valid index?
if (index >= constantBufferCount)
return -1;
// Grab the size
return constantBuffers[index].Size;
}
// --------------------------------------------------------
// Gets info about a particular constant buffer
// by name, if it exists
// --------------------------------------------------------
const SimpleConstantBuffer * ISimpleShader::GetBufferInfo(std::string name)
{
return FindConstantBuffer(name);
}
// --------------------------------------------------------
// Gets info about a particular constant buffer
//
// index - the index of the constant buffer
// --------------------------------------------------------
const SimpleConstantBuffer * ISimpleShader::GetBufferInfo(unsigned int index)
{
// Check for valid index
if (index >= constantBufferCount) return 0;
// Return the specific buffer
return &constantBuffers[index];
}
///////////////////////////////////////////////////////////////////////////////
// ------ SIMPLE VERTEX SHADER ------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------
// Constructor just calls the base
// --------------------------------------------------------
SimpleVertexShader::SimpleVertexShader(Microsoft::WRL::ComPtr<ID3D11Device> device, Microsoft::WRL::ComPtr<ID3D11DeviceContext> context, LPCWSTR shaderFile)
: ISimpleShader(device, context)
{
// Ensure we set to zero to successfully trigger
// the Input Layout creation during LoadShaderFile()
this->perInstanceCompatible = false;
// Load the actual compiled shader file
this->LoadShaderFile(shaderFile);
}
// --------------------------------------------------------
// Constructor overload which takes a custom input layout
//
// Passing in a valid input layout will stop LoadShaderFile()
// from creating an input layout from shader reflection
// --------------------------------------------------------
SimpleVertexShader::SimpleVertexShader(Microsoft::WRL::ComPtr<ID3D11Device> device, Microsoft::WRL::ComPtr<ID3D11DeviceContext> context, LPCWSTR shaderFile, Microsoft::WRL::ComPtr<ID3D11InputLayout> inputLayout, bool perInstanceCompatible)
: ISimpleShader(device, context)
{
// Save the custom input layout
this->inputLayout = inputLayout;
// Unable to determine from an input layout, require user to tell us
this->perInstanceCompatible = perInstanceCompatible;
// Load the actual compiled shader file
this->LoadShaderFile(shaderFile);
}
// --------------------------------------------------------
// Destructor - Clean up actual shader (base will be called automatically)
// --------------------------------------------------------
SimpleVertexShader::~SimpleVertexShader()
{
CleanUp();
}
// --------------------------------------------------------
// Handles cleaning up shader and base class clean up
// --------------------------------------------------------
void SimpleVertexShader::CleanUp()
{
ISimpleShader::CleanUp();
}
// --------------------------------------------------------
// Creates the Direct3D vertex shader
//
// shaderBlob - The shader's compiled code
//
// Returns true if shader is created correctly, false otherwise
// --------------------------------------------------------
bool SimpleVertexShader::CreateShader(Microsoft::WRL::ComPtr<ID3DBlob> shaderBlob)
{
// Clean up first, in the event this method is
// called more than once on the same object
this->CleanUp();
// Create the shader from the blob
HRESULT result = device->CreateVertexShader(
shaderBlob->GetBufferPointer(),
shaderBlob->GetBufferSize(),
0,
shader.GetAddressOf());
// Did the creation work?
if (result != S_OK)
return false;
// Do we already have an input layout?
// (This would come from one of the constructor overloads)
if (inputLayout)
return true;
// Vertex shader was created successfully, so we now use the
// shader code to re-reflect and create an input layout that
// matches what the vertex shader expects. Code adapted from:
// https://takinginitiative.wordpress.com/2011/12/11/directx-1011-basic-shader-reflection-automatic-input-layout-creation/
// Reflect shader info
Microsoft::WRL::ComPtr<ID3D11ShaderReflection> refl;
D3DReflect(
shaderBlob->GetBufferPointer(),
shaderBlob->GetBufferSize(),
IID_ID3D11ShaderReflection,
(void**)refl.GetAddressOf());
// Get shader info
D3D11_SHADER_DESC shaderDesc;
refl->GetDesc(&shaderDesc);
// Read input layout description from shader info
std::vector<D3D11_INPUT_ELEMENT_DESC> inputLayoutDesc;
for (unsigned int i = 0; i< shaderDesc.InputParameters; i++)
{
D3D11_SIGNATURE_PARAMETER_DESC paramDesc;
refl->GetInputParameterDesc(i, ¶mDesc);
// Check the semantic name for "_PER_INSTANCE"
std::string perInstanceStr = "_PER_INSTANCE";
std::string sem = paramDesc.SemanticName;
int lenDiff = (int)sem.size() - (int)perInstanceStr.size();
bool isPerInstance =
lenDiff >= 0 &&
sem.compare(lenDiff, perInstanceStr.size(), perInstanceStr) == 0;
// Fill out input element desc
D3D11_INPUT_ELEMENT_DESC elementDesc = {};
elementDesc.SemanticName = paramDesc.SemanticName;
elementDesc.SemanticIndex = paramDesc.SemanticIndex;
elementDesc.InputSlot = 0;
elementDesc.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
elementDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
elementDesc.InstanceDataStepRate = 0;
// Replace anything affected by "per instance" data
if (isPerInstance)
{
elementDesc.InputSlot = 1; // Assume per instance data comes from another input slot!
elementDesc.InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA;
elementDesc.InstanceDataStepRate = 1;
perInstanceCompatible = true;
}
// Determine DXGI format
if (paramDesc.Mask == 1)
{
if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32_UINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32_SINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32_FLOAT;
}
else if (paramDesc.Mask <= 3)
{
if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32_UINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32_SINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32_FLOAT;
}
else if (paramDesc.Mask <= 7)
{
if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_UINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_SINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT;
}
else if (paramDesc.Mask <= 15)
{
if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_UINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_UINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_SINT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_SINT;
else if (paramDesc.ComponentType == D3D_REGISTER_COMPONENT_FLOAT32) elementDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
}
// Save element desc
inputLayoutDesc.push_back(elementDesc);
}
// Try to create Input Layout
HRESULT hr = device->CreateInputLayout(
&inputLayoutDesc[0],
(unsigned int)inputLayoutDesc.size(),
shaderBlob->GetBufferPointer(),
shaderBlob->GetBufferSize(),
inputLayout.GetAddressOf());
// All done, clean up
return true;
}
// --------------------------------------------------------
// Sets the vertex shader, input layout and constant buffers
// for future Direct3D drawing
// --------------------------------------------------------
void SimpleVertexShader::SetShaderAndCBs()
{
// Is shader valid?
if (!shaderValid) return;
// Set the shader and input layout
deviceContext->IASetInputLayout(inputLayout.Get());
deviceContext->VSSetShader(shader.Get(), 0, 0);
// Set the constant buffers
for (unsigned int i = 0; i < constantBufferCount; i++)
{
// Skip "buffers" that aren't true constant buffers
if (constantBuffers[i].Type != D3D11_CT_CBUFFER)
continue;
// This is a real constant buffer, so set it
deviceContext->VSSetConstantBuffers(
constantBuffers[i].BindIndex,
1,
constantBuffers[i].ConstantBuffer.GetAddressOf());
}
}
// --------------------------------------------------------
// Sets a shader resource view in the vertex shader stage
//
// name - The name of the texture resource in the shader
// srv - The shader resource view of the texture in GPU memory
//
// Returns true if a texture of the given name was found, false otherwise
// --------------------------------------------------------
bool SimpleVertexShader::SetShaderResourceView(std::string name, Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> srv)
{
// Look for the variable and verify
const SimpleSRV* srvInfo = GetShaderResourceViewInfo(name);
if (srvInfo == 0)
{
if (ReportWarnings)
{
LogWarning("SimpleVertexShader::SetShaderResourceView() - SRV named '");
Log(name);
LogWarning("' was not found in the shader. Ensure the name is spelled correctly and that it exists in the shader.\n");
}
return false;
}
// Set the shader resource view
deviceContext->VSSetShaderResources(srvInfo->BindIndex, 1, srv.GetAddressOf());
// Success
return true;
}
// --------------------------------------------------------
// Sets a sampler state in the vertex shader stage
//
// name - The name of the sampler state in the shader
// samplerState - The sampler state in GPU memory
//
// Returns true if a sampler of the given name was found, false otherwise
// --------------------------------------------------------
bool SimpleVertexShader::SetSamplerState(std::string name, Microsoft::WRL::ComPtr<ID3D11SamplerState> samplerState)
{
// Look for the variable and verify
const SimpleSampler* sampInfo = GetSamplerInfo(name);
if (sampInfo == 0)
{
if (ReportWarnings)
{
LogWarning("SimpleVertexShader::SetSamplerState() - Sampler named '");
Log(name);
LogWarning("' was not found in the shader. Ensure the name is spelled correctly and that it exists in the shader.\n");
}
return false;
}
// Set the shader resource view
deviceContext->VSSetSamplers(sampInfo->BindIndex, 1, samplerState.GetAddressOf());
// Success
return true;
}
///////////////////////////////////////////////////////////////////////////////
// ------ SIMPLE PIXEL SHADER -------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------
// Constructor just calls the base
// --------------------------------------------------------
SimplePixelShader::SimplePixelShader(Microsoft::WRL::ComPtr<ID3D11Device> device, Microsoft::WRL::ComPtr<ID3D11DeviceContext> context, LPCWSTR shaderFile)
: ISimpleShader(device, context)
{
// Load the actual compiled shader file
this->LoadShaderFile(shaderFile);
}
// --------------------------------------------------------
// Destructor - Clean up actual shader (base will be called automatically)
// --------------------------------------------------------
SimplePixelShader::~SimplePixelShader()
{
CleanUp();
}
// --------------------------------------------------------
// Handles cleaning up shader and base class clean up
// --------------------------------------------------------
void SimplePixelShader::CleanUp()
{
ISimpleShader::CleanUp();
}
// --------------------------------------------------------
// Creates the Direct3D pixel shader
//
// shaderBlob - The shader's compiled code
//
// Returns true if shader is created correctly, false otherwise
// --------------------------------------------------------
bool SimplePixelShader::CreateShader(Microsoft::WRL::ComPtr<ID3DBlob> shaderBlob)
{
// Clean up first, in the event this method is
// called more than once on the same object
this->CleanUp();
// Create the shader from the blob
HRESULT result = device->CreatePixelShader(
shaderBlob->GetBufferPointer(),
shaderBlob->GetBufferSize(),
0,
shader.GetAddressOf());