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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
|
#include "renderer-shared.h"
#include "mutable-shader-object.h"
#include "core/slang-io.h"
#include "core/slang-token-reader.h"
#include "../../source/core/slang-file-system.h"
#include "../../slang.h"
#include "../../source/slang/slang-hash-utils.h"
using namespace Slang;
namespace gfx
{
const Slang::Guid GfxGUID::IID_ISlangUnknown = SLANG_UUID_ISlangUnknown;
const Slang::Guid GfxGUID::IID_IShaderProgram = SLANG_UUID_IShaderProgram;
const Slang::Guid GfxGUID::IID_IInputLayout = SLANG_UUID_IInputLayout;
const Slang::Guid GfxGUID::IID_IPipelineState = SLANG_UUID_IPipelineState;
const Slang::Guid GfxGUID::IID_ITransientResourceHeap = SLANG_UUID_ITransientResourceHeap;
const Slang::Guid GfxGUID::IID_IResourceView = SLANG_UUID_IResourceView;
const Slang::Guid GfxGUID::IID_IFramebuffer = SLANG_UUID_IFrameBuffer;
const Slang::Guid GfxGUID::IID_IFramebufferLayout = SLANG_UUID_IFramebufferLayout;
const Slang::Guid GfxGUID::IID_ISwapchain = SLANG_UUID_ISwapchain;
const Slang::Guid GfxGUID::IID_ISamplerState = SLANG_UUID_ISamplerState;
const Slang::Guid GfxGUID::IID_IResource = SLANG_UUID_IResource;
const Slang::Guid GfxGUID::IID_IBufferResource = SLANG_UUID_IBufferResource;
const Slang::Guid GfxGUID::IID_ITextureResource = SLANG_UUID_ITextureResource;
const Slang::Guid GfxGUID::IID_IDevice = SLANG_UUID_IDevice;
const Slang::Guid GfxGUID::IID_IShaderCacheStatistics = SLANG_UUID_IShaderCacheStatistics;
const Slang::Guid GfxGUID::IID_IShaderObject = SLANG_UUID_IShaderObject;
const Slang::Guid GfxGUID::IID_IRenderPassLayout = SLANG_UUID_IRenderPassLayout;
const Slang::Guid GfxGUID::IID_IRayTracingCommandEncoder = IRayTracingCommandEncoder::getTypeGuid();
const Slang::Guid GfxGUID::IID_IResourceCommandEncoder = IResourceCommandEncoder::getTypeGuid();
const Slang::Guid GfxGUID::IID_IComputeCommandEncoder = IComputeCommandEncoder::getTypeGuid();
const Slang::Guid GfxGUID::IID_IRenderCommandEncoder = IRenderCommandEncoder::getTypeGuid();
const Slang::Guid GfxGUID::IID_ICommandBuffer = SLANG_UUID_ICommandBuffer;
const Slang::Guid GfxGUID::IID_ICommandBufferD3D12 = SLANG_UUID_ICommandBufferD3D12;
const Slang::Guid GfxGUID::IID_ICommandQueue = SLANG_UUID_ICommandQueue;
const Slang::Guid GfxGUID::IID_IQueryPool = SLANG_UUID_IQueryPool;
const Slang::Guid GfxGUID::IID_IAccelerationStructure = SLANG_UUID_IAccelerationStructure;
const Slang::Guid GfxGUID::IID_IFence = SLANG_UUID_IFence;
const Slang::Guid GfxGUID::IID_IShaderTable = SLANG_UUID_IShaderTable;
const Slang::Guid GfxGUID::IID_IPipelineCreationAPIDispatcher = SLANG_UUID_IPipelineCreationAPIDispatcher;
const Slang::Guid GfxGUID::IID_ID3D12TransientResourceHeap = SLANG_UUID_ID3D12TransientResourceHeap;
StageType translateStage(SlangStage slangStage)
{
switch (slangStage)
{
default:
SLANG_ASSERT(!"unhandled case");
return gfx::StageType::Unknown;
#define CASE(FROM, TO) \
case SLANG_STAGE_##FROM: \
return gfx::StageType::TO
CASE(VERTEX, Vertex);
CASE(HULL, Hull);
CASE(DOMAIN, Domain);
CASE(GEOMETRY, Geometry);
CASE(FRAGMENT, Fragment);
CASE(COMPUTE, Compute);
CASE(RAY_GENERATION, RayGeneration);
CASE(INTERSECTION, Intersection);
CASE(ANY_HIT, AnyHit);
CASE(CLOSEST_HIT, ClosestHit);
CASE(MISS, Miss);
CASE(CALLABLE, Callable);
#undef CASE
}
}
IFence* FenceBase::getInterface(const Slang::Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IFence)
return static_cast<IFence*>(this);
return nullptr;
}
IResource* BufferResource::getInterface(const Slang::Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IResource ||
guid == GfxGUID::IID_IBufferResource)
return static_cast<IBufferResource*>(this);
return nullptr;
}
SLANG_NO_THROW IResource::Type SLANG_MCALL BufferResource::getType() { return m_type; }
SLANG_NO_THROW IBufferResource::Desc* SLANG_MCALL BufferResource::getDesc() { return &m_desc; }
Result BufferResource::getNativeResourceHandle(InteropHandle* outHandle)
{
outHandle->handleValue = 0;
outHandle->api = InteropHandleAPI::Unknown;
return SLANG_FAIL;
}
Result BufferResource::getSharedHandle(InteropHandle* outHandle)
{
outHandle->api = InteropHandleAPI::Unknown;
outHandle->handleValue = 0;
return SLANG_FAIL;
}
IResource* TextureResource::getInterface(const Slang::Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IResource ||
guid == GfxGUID::IID_ITextureResource)
return static_cast<ITextureResource*>(this);
return nullptr;
}
SLANG_NO_THROW IResource::Type SLANG_MCALL TextureResource::getType() { return m_type; }
SLANG_NO_THROW ITextureResource::Desc* SLANG_MCALL TextureResource::getDesc() { return &m_desc; }
Result TextureResource::getNativeResourceHandle(InteropHandle* outHandle)
{
outHandle->handleValue = 0;
outHandle->api = InteropHandleAPI::Unknown;
return SLANG_FAIL;
}
Result TextureResource::getSharedHandle(InteropHandle* outHandle)
{
outHandle->api = InteropHandleAPI::Unknown;
outHandle->handleValue = 0;
return SLANG_OK;
}
StageType mapStage(SlangStage stage)
{
switch( stage )
{
default:
return StageType::Unknown;
case SLANG_STAGE_AMPLIFICATION: return gfx::StageType::Amplification;
case SLANG_STAGE_ANY_HIT: return gfx::StageType::AnyHit;
case SLANG_STAGE_CALLABLE: return gfx::StageType::Callable;
case SLANG_STAGE_CLOSEST_HIT: return gfx::StageType::ClosestHit;
case SLANG_STAGE_COMPUTE: return gfx::StageType::Compute;
case SLANG_STAGE_DOMAIN: return gfx::StageType::Domain;
case SLANG_STAGE_FRAGMENT: return gfx::StageType::Fragment;
case SLANG_STAGE_GEOMETRY: return gfx::StageType::Geometry;
case SLANG_STAGE_HULL: return gfx::StageType::Hull;
case SLANG_STAGE_INTERSECTION: return gfx::StageType::Intersection;
case SLANG_STAGE_MESH: return gfx::StageType::Mesh;
case SLANG_STAGE_MISS: return gfx::StageType::Miss;
case SLANG_STAGE_RAY_GENERATION: return gfx::StageType::RayGeneration;
case SLANG_STAGE_VERTEX: return gfx::StageType::Vertex;
}
}
IResourceView* ResourceViewBase::getInterface(const Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IResourceView)
return static_cast<IResourceView*>(this);
return nullptr;
}
Result ResourceViewBase::getNativeHandle(InteropHandle* outHandle)
{
outHandle->api = InteropHandleAPI::Unknown;
outHandle->handleValue = 0;
return SLANG_E_NOT_IMPLEMENTED;
}
ISamplerState* SamplerStateBase::getInterface(const Slang::Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_ISamplerState)
return static_cast<ISamplerState*>(this);
return nullptr;
}
Result SamplerStateBase::getNativeHandle(InteropHandle* outHandle)
{
outHandle->api = InteropHandleAPI::Unknown;
outHandle->handleValue = 0;
return SLANG_E_NOT_IMPLEMENTED;
}
IAccelerationStructure* AccelerationStructureBase::getInterface(const Slang::Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IResourceView ||
guid == GfxGUID::IID_IAccelerationStructure)
return static_cast<IAccelerationStructure*>(this);
return nullptr;
}
bool _doesValueFitInExistentialPayload(
slang::TypeLayoutReflection* concreteTypeLayout,
slang::TypeLayoutReflection* existentialTypeLayout)
{
// Our task here is to figure out if a value of `concreteTypeLayout`
// can fit into an existential value using `existentialTypelayout`.
// We can start by asking how many bytes the concrete type of the object consumes.
//
auto concreteValueSize = concreteTypeLayout->getSize();
// We can also compute how many bytes the existential-type value provides,
// but we need to remember that the *payload* part of that value comes after
// the header with RTTI and witness-table IDs, so the payload is 16 bytes
// smaller than the entire value.
//
auto existentialValueSize = existentialTypeLayout->getSize();
auto existentialPayloadSize = existentialValueSize - 16;
// If the concrete type consumes more ordinary bytes than we have in the payload,
// it cannot possibly fit.
//
if(concreteValueSize > existentialPayloadSize)
return false;
// It is possible that the ordinary bytes of `concreteTypeLayout` can fit
// in the payload, but that type might also use storage other than ordinary
// bytes. In that case, the value would *not* fit, because all the non-ordinary
// data can't fit in the payload at all.
//
auto categoryCount = concreteTypeLayout->getCategoryCount();
for(unsigned int i = 0; i < categoryCount; ++i)
{
auto category = concreteTypeLayout->getCategoryByIndex(i);
switch(category)
{
// We want to ignore any ordinary/uniform data usage, since that
// was already checked above.
//
case slang::ParameterCategory::Uniform:
break;
// Any other kind of data consumed means the value cannot possibly fit.
default:
return false;
// TODO: Are there any cases of resource usage that need to be ignored here?
// E.g., if the sub-object contains its own existential-type fields (which
// get reflected as consuming "existential value" storage) should that be
// ignored?
}
}
// If we didn't reject the concrete type above for either its ordinary
// data or some use of non-ordinary data, then it seems like it must fit.
//
return true;
}
IShaderProgram* ShaderProgramBase::getInterface(const Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IShaderProgram)
return static_cast<IShaderProgram*>(this);
return nullptr;
}
IInputLayout* InputLayoutBase::getInterface(const Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IInputLayout)
return static_cast<IInputLayout*>(this);
return nullptr;
}
IFramebufferLayout* FramebufferLayoutBase::getInterface(const Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IFramebufferLayout)
return static_cast<IFramebufferLayout*>(this);
return nullptr;
}
IFramebuffer* FramebufferBase::getInterface(const Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IFramebuffer)
return static_cast<IFramebuffer*>(this);
return nullptr;
}
IQueryPool* QueryPoolBase::getInterface(const Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IQueryPool)
return static_cast<IQueryPool*>(this);
return nullptr;
}
IPipelineState* PipelineStateBase::getInterface(const Guid& guid)
{
if (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IPipelineState)
return static_cast<IPipelineState*>(this);
return nullptr;
}
Result PipelineStateBase::getNativeHandle(InteropHandle* outHandle)
{
outHandle->api = InteropHandleAPI::Unknown;
outHandle->handleValue = 0;
return SLANG_E_NOT_IMPLEMENTED;
}
void PipelineStateBase::initializeBase(const PipelineStateDesc& inDesc)
{
desc = inDesc;
auto program = desc.getProgram();
m_program = program;
isSpecializable = false;
if (program->slangGlobalScope && program->slangGlobalScope->getSpecializationParamCount() != 0)
isSpecializable = true;
for (auto& entryPoint : program->slangEntryPoints)
{
if (entryPoint->getSpecializationParamCount() != 0)
{
isSpecializable = true;
break;
}
}
// Hold a strong reference to inputLayout and framebufferLayout objects to prevent it from
// destruction.
if (inDesc.type == PipelineType::Graphics)
{
inputLayout = static_cast<InputLayoutBase*>(inDesc.graphics.inputLayout);
framebufferLayout = static_cast<FramebufferLayoutBase*>(inDesc.graphics.framebufferLayout);
}
}
void updateCacheEntry(ISlangMutableFileSystem* fileSystem, slang::IBlob* compiledCode, String shaderFilename, slang::Digest ASTHash)
{
auto hashSize = sizeof(slang::Digest);
auto bufferSize = hashSize + compiledCode->getBufferSize();
List<uint8_t> contents;
contents.setCount(bufferSize);
uint8_t* buffer = contents.begin();
memcpy(buffer, &ASTHash, hashSize);
memcpy(buffer + hashSize, (void*)compiledCode->getBufferPointer(), compiledCode->getBufferSize());
fileSystem->saveFile(shaderFilename.getBuffer(), buffer, bufferSize);
}
Result RendererBase::getEntryPointCodeFromShaderCache(
slang::IComponentType* program,
SlangInt entryPointIndex,
SlangInt targetIndex,
slang::IBlob** outCode,
slang::IBlob** outDiagnostics)
{
// TODO: Need a way in filesystem to query both file size and file creation time, if cache size exceeds
// specified maximum size (in bytes or files) then delete oldest files - cache eviction policy
// Immediately call getEntryPointCode if no shader cache was provided on initialization
if (!shaderCacheFileSystem)
{
return program->getEntryPointCode(entryPointIndex, targetIndex, outCode, outDiagnostics);
}
// Produce a string which we can use to query the shader cache by combining two separate hashes which
// together comprise all the compilation arguments for this program.
ComPtr<slang::ISession> session;
getSlangSession(session.writeRef());
slang::Digest shaderKeyHash;
program->computeDependencyBasedHash(entryPointIndex, targetIndex, &shaderKeyHash);
StringBuilder shaderKey = hashToString(shaderKeyHash);
// Produce a hash using the AST for this program - This is needed to check whether a cache entry is effectively dirty,
// or to save along with the compiled code into an entry so the entry can be checked if fetched later on.
slang::Digest ASTHash;
program->computeASTBasedHash(&ASTHash);
ComPtr<ISlangBlob> codeBlob;
// Query shaderCacheFileSystem for an entry whose key matches shaderFilename
// - If we find it, then copy the file contents into memory and return in outCode
auto result = shaderCacheFileSystem->loadFile(shaderKey.getBuffer(), codeBlob.writeRef());
if (SLANG_FAILED(result))
{
// If we didn't find it, call program->getEntryPointCode() to get and return the code. We also
// make sure to save a new entry in the shader cache.
if (SLANG_SUCCEEDED(program->getEntryPointCode(entryPointIndex, targetIndex, codeBlob.writeRef(), outDiagnostics)))
{
if (mutableShaderCacheFileSystem)
{
updateCacheEntry(mutableShaderCacheFileSystem, codeBlob, shaderKey, ASTHash);
}
shaderCacheMissCount++;
}
else
{
// If getEntryPointCode() failed to fetch the code, we return SLANG_FAIL along with the diagnostics output
// in outDiagnostics.
return SLANG_FAIL;
}
}
else
{
// If the entry exists, we need to check that the entry isn't effectively dirty. Since we stored
// the AST hash with the compiled code, we can determine this by comparing the stored hash with the
// AST hash generated earlier.
auto entryContents = codeBlob->getBufferPointer();
auto hashSize = sizeof(slang::Digest);
if (memcmp(ASTHash.values, entryContents, hashSize) != 0)
{
// The AST hash stored in the entry does not match the AST hash generated earlier, indicating
// that the shader code has changed and the entry needs to be updated.
if (SLANG_SUCCEEDED(program->getEntryPointCode(entryPointIndex, targetIndex, codeBlob.writeRef(), outDiagnostics)))
{
if (mutableShaderCacheFileSystem)
{
updateCacheEntry(mutableShaderCacheFileSystem, codeBlob, shaderKey, ASTHash);
}
shaderCacheEntryDirtyCount++;
}
else
{
// If getEntryPointCode() failed to fetch the code, we return SLANG_FAIL along with the diagnostics output
// in outDiagnostics.
return SLANG_FAIL;
}
}
else
{
auto compiledCode = RawBlob::create((uint8_t*)codeBlob->getBufferPointer() + hashSize, codeBlob->getBufferSize() - hashSize);
codeBlob = compiledCode;
shaderCacheHitCount++;
}
}
*outCode = codeBlob.detach();
return SLANG_OK;
}
SlangResult RendererBase::queryInterface(SlangUUID const& uuid, void** outObject)
{
if (uuid == GfxGUID::IID_IShaderCacheStatistics)
{
*outObject = static_cast<IShaderCacheStatistics*>(this);
addRef();
return SLANG_OK;
}
*outObject = getInterface(uuid);
return SLANG_OK;
}
IDevice* gfx::RendererBase::getInterface(const Guid& guid)
{
return (guid == GfxGUID::IID_ISlangUnknown || guid == GfxGUID::IID_IDevice)
? static_cast<IDevice*>(this)
: nullptr;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::initialize(const Desc& desc)
{
// If a shader cache file system was provided, use the provided system.
if (desc.shaderCacheFileSystem)
{
shaderCacheFileSystem = desc.shaderCacheFileSystem;
}
if (desc.shaderCachePath)
{
// Only a path was provided, create a RelativeFileSystem using the path
if (!shaderCacheFileSystem)
{
shaderCacheFileSystem = OSFileSystem::getMutableSingleton();
}
shaderCacheFileSystem = new RelativeFileSystem(shaderCacheFileSystem, desc.shaderCachePath);
}
// If we initialized a file system for the shader cache, check if it's mutable. If so, store a pointer
// to the mutable version in order to save new entries later.
if (shaderCacheFileSystem)
{
shaderCacheFileSystem->queryInterface(ISlangMutableFileSystem::getTypeGuid(), (void**)mutableShaderCacheFileSystem.writeRef());
}
if (desc.apiCommandDispatcher)
{
desc.apiCommandDispatcher->queryInterface(
GfxGUID::IID_IPipelineCreationAPIDispatcher,
(void**)m_pipelineCreationAPIDispatcher.writeRef());
}
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::getNativeDeviceHandles(InteropHandles* outHandles)
{
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::getFeatures(
const char** outFeatures, Size bufferSize, GfxCount* outFeatureCount)
{
if (bufferSize >= (UInt)m_features.getCount())
{
for (Index i = 0; i < m_features.getCount(); i++)
{
outFeatures[i] = m_features[i].getUnownedSlice().begin();
}
}
if (outFeatureCount)
*outFeatureCount = (GfxCount)m_features.getCount();
return SLANG_OK;
}
SLANG_NO_THROW bool SLANG_MCALL RendererBase::hasFeature(const char* featureName)
{
return m_features.findFirstIndex([&](Slang::String x) { return x == featureName; }) != -1;
}
Result RendererBase::getFormatSupportedResourceStates(Format format, ResourceStateSet* outStates)
{
SLANG_UNUSED(format);
outStates->add(ResourceState::AccelerationStructure);
outStates->add(ResourceState::AccelerationStructureBuildInput);
outStates->add(ResourceState::ConstantBuffer);
outStates->add(ResourceState::CopyDestination);
outStates->add(ResourceState::CopySource);
outStates->add(ResourceState::DepthRead);
outStates->add(ResourceState::DepthWrite);
outStates->add(ResourceState::IndexBuffer);
outStates->add(ResourceState::IndirectArgument);
outStates->add(ResourceState::PreInitialized);
outStates->add(ResourceState::Present);
outStates->add(ResourceState::RenderTarget);
outStates->add(ResourceState::ResolveDestination);
outStates->add(ResourceState::ResolveSource);
outStates->add(ResourceState::ShaderResource);
outStates->add(ResourceState::PixelShaderResource);
outStates->add(ResourceState::NonPixelShaderResource);
outStates->add(ResourceState::StreamOutput);
outStates->add(ResourceState::Undefined);
outStates->add(ResourceState::UnorderedAccess);
outStates->add(ResourceState::VertexBuffer);
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::getSlangSession(slang::ISession** outSlangSession)
{
*outSlangSession = slangContext.session.get();
slangContext.session->addRef();
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::createTextureFromNativeHandle(
InteropHandle handle,
const ITextureResource::Desc& srcDesc,
ITextureResource** outResource)
{
SLANG_UNUSED(handle);
SLANG_UNUSED(srcDesc);
SLANG_UNUSED(outResource);
return SLANG_E_NOT_AVAILABLE;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::createTextureFromSharedHandle(
InteropHandle handle,
const ITextureResource::Desc& srcDesc,
const Size size,
ITextureResource** outResource)
{
SLANG_UNUSED(handle);
SLANG_UNUSED(srcDesc);
SLANG_UNUSED(size);
SLANG_UNUSED(outResource);
return SLANG_E_NOT_AVAILABLE;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::createBufferFromNativeHandle(
InteropHandle handle,
const IBufferResource::Desc& srcDesc,
IBufferResource** outResource)
{
SLANG_UNUSED(handle);
SLANG_UNUSED(srcDesc);
SLANG_UNUSED(outResource);
return SLANG_E_NOT_AVAILABLE;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::createBufferFromSharedHandle(
InteropHandle handle,
const IBufferResource::Desc& srcDesc,
IBufferResource** outResource)
{
SLANG_UNUSED(handle);
SLANG_UNUSED(srcDesc);
SLANG_UNUSED(outResource);
return SLANG_E_NOT_AVAILABLE;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::createShaderObject(
slang::TypeReflection* type,
ShaderObjectContainerType container,
IShaderObject** outObject)
{
RefPtr<ShaderObjectLayoutBase> shaderObjectLayout;
SLANG_RETURN_ON_FAIL(getShaderObjectLayout(type, container, shaderObjectLayout.writeRef()));
return createShaderObject(shaderObjectLayout, outObject);
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::createMutableShaderObject(
slang::TypeReflection* type,
ShaderObjectContainerType containerType,
IShaderObject** outObject)
{
RefPtr<ShaderObjectLayoutBase> shaderObjectLayout;
SLANG_RETURN_ON_FAIL(getShaderObjectLayout(type, containerType, shaderObjectLayout.writeRef()));
return createMutableShaderObject(shaderObjectLayout, outObject);
}
Result RendererBase::createProgram2(
const IShaderProgram::CreateDesc2& desc,
IShaderProgram** outProgram,
ISlangBlob** outDiagnostic)
{
auto slangSession = slangContext.session.get();
slang::IModule* module = nullptr;
ComPtr<slang::IBlob> diagnosticsBlob;
switch (desc.sourceType)
{
case ShaderModuleSourceType::SlangSourceFile:
{
auto fileName = (char*)desc.sourceData;
module = slangSession->loadModule(fileName, diagnosticsBlob.writeRef());
if (!module)
return SLANG_FAIL;
break;
}
case ShaderModuleSourceType::SlangSource:
{
auto hash = getStableHashCode32((char*)desc.sourceData, desc.sourceDataSize);
auto hashStr = String(hash);
auto srcBlob = UnownedRawBlob::create(desc.sourceData, desc.sourceDataSize);
module = slangSession->loadModuleFromSource(hashStr.getBuffer(), hashStr.getBuffer(), srcBlob, diagnosticsBlob.writeRef());
if (!module)
return SLANG_FAIL;
break;
}
default:
SLANG_RELEASE_ASSERT(false);
}
Slang::List<ComPtr<slang::IComponentType>> componentTypes;
componentTypes.add(ComPtr<slang::IComponentType>(module));
if (desc.entryPointCount == 0)
{
for (SlangInt32 i = 0; i < module->getDefinedEntryPointCount(); i++)
{
ComPtr<slang::IEntryPoint> entryPoint;
SLANG_RETURN_ON_FAIL(module->getDefinedEntryPoint(i, entryPoint.writeRef()));
componentTypes.add(ComPtr<slang::IComponentType>(entryPoint.get()));
}
}
else
{
for (GfxCount i = 0; i < desc.entryPointCount; i++)
{
ComPtr<slang::IEntryPoint> entryPoint;
SLANG_RETURN_ON_FAIL(module->findEntryPointByName(desc.entryPointNames[i], entryPoint.writeRef()));
componentTypes.add(ComPtr<slang::IComponentType>(entryPoint.get()));
}
}
Slang::List<slang::IComponentType*> rawComponentTypes;
for (auto& compType : componentTypes)
rawComponentTypes.add(compType.get());
ComPtr<slang::IComponentType> linkedProgram;
SlangResult result = slangSession->createCompositeComponentType(
rawComponentTypes.getBuffer(),
rawComponentTypes.getCount(),
linkedProgram.writeRef(),
diagnosticsBlob.writeRef());
SLANG_RETURN_ON_FAIL(result);
gfx::IShaderProgram::Desc programDesc = {};
programDesc.slangGlobalScope = linkedProgram;
SLANG_RETURN_ON_FAIL(createProgram(programDesc, outProgram, outDiagnostic));
return SLANG_OK;
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::createShaderObjectFromTypeLayout(
slang::TypeLayoutReflection* typeLayout, IShaderObject** outObject)
{
RefPtr<ShaderObjectLayoutBase> shaderObjectLayout;
SLANG_RETURN_ON_FAIL(getShaderObjectLayout(typeLayout, shaderObjectLayout.writeRef()));
return createShaderObject(shaderObjectLayout, outObject);
}
SLANG_NO_THROW Result SLANG_MCALL RendererBase::createMutableShaderObjectFromTypeLayout(
slang::TypeLayoutReflection* typeLayout, IShaderObject** outObject)
{
RefPtr<ShaderObjectLayoutBase> shaderObjectLayout;
SLANG_RETURN_ON_FAIL(getShaderObjectLayout(typeLayout, shaderObjectLayout.writeRef()));
return createMutableShaderObject(shaderObjectLayout, outObject);
}
Result RendererBase::getAccelerationStructurePrebuildInfo(
const IAccelerationStructure::BuildInputs& buildInputs,
IAccelerationStructure::PrebuildInfo* outPrebuildInfo)
{
SLANG_UNUSED(buildInputs);
SLANG_UNUSED(outPrebuildInfo);
return SLANG_E_NOT_AVAILABLE;
}
Result RendererBase::createAccelerationStructure(
const IAccelerationStructure::CreateDesc& desc,
IAccelerationStructure** outView)
{
SLANG_UNUSED(desc);
SLANG_UNUSED(outView);
return SLANG_E_NOT_AVAILABLE;
}
Result RendererBase::createShaderTable(const IShaderTable::Desc& desc, IShaderTable** outTable)
{
SLANG_UNUSED(desc);
SLANG_UNUSED(outTable);
return SLANG_E_NOT_AVAILABLE;
}
Result RendererBase::createRayTracingPipelineState(const RayTracingPipelineStateDesc& desc, IPipelineState** outState)
{
SLANG_UNUSED(desc);
SLANG_UNUSED(outState);
return SLANG_E_NOT_AVAILABLE;
}
Result RendererBase::createMutableRootShaderObject(
IShaderProgram* program, IShaderObject** outObject)
{
SLANG_UNUSED(program);
SLANG_UNUSED(outObject);
return SLANG_E_NOT_AVAILABLE;
}
Result RendererBase::createFence(const IFence::Desc& desc, IFence** outFence)
{
SLANG_UNUSED(desc);
*outFence = nullptr;
return SLANG_E_NOT_AVAILABLE;
}
Result RendererBase::waitForFences(
GfxCount fenceCount, IFence** fences, uint64_t* fenceValues, bool waitForAll, uint64_t timeout)
{
SLANG_UNUSED(fenceCount);
SLANG_UNUSED(fences);
SLANG_UNUSED(fenceValues);
SLANG_UNUSED(waitForAll);
SLANG_UNUSED(timeout);
return SLANG_E_NOT_AVAILABLE;
}
Result RendererBase::getTextureAllocationInfo(
const ITextureResource::Desc& desc, Size* outSize, Size* outAlignment)
{
SLANG_UNUSED(desc);
*outSize = 0;
*outAlignment = 0;
return SLANG_E_NOT_AVAILABLE;
}
Result RendererBase::getTextureRowAlignment(Size* outAlignment)
{
*outAlignment = 0;
return SLANG_E_NOT_AVAILABLE;
}
Result RendererBase::getShaderObjectLayout(
slang::TypeReflection* type,
ShaderObjectContainerType container,
ShaderObjectLayoutBase** outLayout)
{
switch (container)
{
case ShaderObjectContainerType::StructuredBuffer:
type = slangContext.session->getContainerType(type, slang::ContainerType::StructuredBuffer);
break;
case ShaderObjectContainerType::Array:
type = slangContext.session->getContainerType(type, slang::ContainerType::UnsizedArray);
break;
default:
break;
}
auto typeLayout = slangContext.session->getTypeLayout(type);
return getShaderObjectLayout(typeLayout, outLayout);
}
Result RendererBase::getShaderObjectLayout(
slang::TypeLayoutReflection* typeLayout, ShaderObjectLayoutBase** outLayout)
{
RefPtr<ShaderObjectLayoutBase> shaderObjectLayout;
if (!m_shaderObjectLayoutCache.TryGetValue(typeLayout, shaderObjectLayout))
{
SLANG_RETURN_ON_FAIL(createShaderObjectLayout(typeLayout, shaderObjectLayout.writeRef()));
m_shaderObjectLayoutCache.Add(typeLayout, shaderObjectLayout);
}
*outLayout = shaderObjectLayout.detach();
return SLANG_OK;
}
GfxCount RendererBase::getCacheMissCount()
{
return shaderCacheMissCount;
}
GfxCount RendererBase::getCacheHitCount()
{
return shaderCacheHitCount;
}
GfxCount RendererBase::getCacheEntryDirtyCount()
{
return shaderCacheEntryDirtyCount;
}
Result RendererBase::resetCacheStatistics()
{
shaderCacheMissCount = 0;
shaderCacheHitCount = 0;
shaderCacheEntryDirtyCount = 0;
return SLANG_OK;
}
ShaderComponentID ShaderCache::getComponentId(slang::TypeReflection* type)
{
ComponentKey key;
key.typeName = UnownedStringSlice(type->getName());
switch (type->getKind())
{
case slang::TypeReflection::Kind::Specialized:
{
auto baseType = type->getElementType();
StringBuilder builder;
builder.append(UnownedTerminatedStringSlice(baseType->getName()));
auto rawType = (SlangReflectionType*) type;
builder.appendChar('<');
SlangInt argCount = spReflectionType_getSpecializedTypeArgCount(rawType);
for(SlangInt a = 0; a < argCount; ++a)
{
if(a != 0) builder.appendChar(',');
if(auto rawArgType = spReflectionType_getSpecializedTypeArgType(rawType, a))
{
auto argType = (slang::TypeReflection*) rawArgType;
builder.append(argType->getName());
}
}
builder.appendChar('>');
key.typeName = builder.getUnownedSlice();
key.updateHash();
return getComponentId(key);
}
// TODO: collect specialization arguments and append them to `key`.
SLANG_UNIMPLEMENTED_X("specialized type");
default:
break;
}
key.updateHash();
return getComponentId(key);
}
ShaderComponentID ShaderCache::getComponentId(UnownedStringSlice name)
{
ComponentKey key;
key.typeName = name;
key.updateHash();
return getComponentId(key);
}
ShaderComponentID ShaderCache::getComponentId(ComponentKey key)
{
ShaderComponentID componentId = 0;
if (componentIds.TryGetValue(key, componentId))
return componentId;
OwningComponentKey owningTypeKey;
owningTypeKey.hash = key.hash;
owningTypeKey.typeName = key.typeName;
owningTypeKey.specializationArgs.addRange(key.specializationArgs);
ShaderComponentID resultId = static_cast<ShaderComponentID>(componentIds.Count());
componentIds[owningTypeKey] = resultId;
return resultId;
}
void ShaderCache::addSpecializedPipeline(PipelineKey key, Slang::RefPtr<PipelineStateBase> specializedPipeline)
{
specializedPipelines[key] = specializedPipeline;
}
void ShaderObjectLayoutBase::initBase(RendererBase* renderer, slang::TypeLayoutReflection* elementTypeLayout)
{
m_renderer = renderer;
m_elementTypeLayout = elementTypeLayout;
m_componentID = m_renderer->shaderCache.getComponentId(m_elementTypeLayout->getType());
}
// Get the final type this shader object represents. If the shader object's type has existential fields,
// this function will return a specialized type using the bound sub-objects' type as specialization argument.
Result ShaderObjectBase::getSpecializedShaderObjectType(ExtendedShaderObjectType* outType)
{
return _getSpecializedShaderObjectType(outType);
}
Result ShaderObjectBase::_getSpecializedShaderObjectType(ExtendedShaderObjectType* outType)
{
if (shaderObjectType.slangType)
*outType = shaderObjectType;
ExtendedShaderObjectTypeList specializationArgs;
SLANG_RETURN_ON_FAIL(collectSpecializationArgs(specializationArgs));
if (specializationArgs.getCount() == 0)
{
shaderObjectType.componentID = getLayoutBase()->getComponentID();
shaderObjectType.slangType = getLayoutBase()->getElementTypeLayout()->getType();
}
else
{
shaderObjectType.slangType = getRenderer()->slangContext.session->specializeType(
_getElementTypeLayout()->getType(),
specializationArgs.components.getArrayView().getBuffer(), specializationArgs.getCount());
shaderObjectType.componentID = getRenderer()->shaderCache.getComponentId(shaderObjectType.slangType);
}
*outType = shaderObjectType;
return SLANG_OK;
}
Result ShaderObjectBase::setExistentialHeader(
slang::TypeReflection* existentialType,
slang::TypeReflection* concreteType,
ShaderOffset offset)
{
// The first field of the tuple (offset zero) is the run-time type information
// (RTTI) ID for the concrete type being stored into the field.
//
// TODO: We need to be able to gather the RTTI type ID from `object` and then
// use `setData(offset, &TypeID, sizeof(TypeID))`.
// The second field of the tuple (offset 8) is the ID of the "witness" for the
// conformance of the concrete type to the interface used by this field.
//
auto witnessTableOffset = offset;
witnessTableOffset.uniformOffset += 8;
//
// Conformances of a type to an interface are computed and then stored by the
// Slang runtime, so we can look up the ID for this particular conformance (which
// will create it on demand).
//
ComPtr<slang::ISession> slangSession;
SLANG_RETURN_ON_FAIL(getRenderer()->getSlangSession(slangSession.writeRef()));
//
// Note: If the type doesn't actually conform to the required interface for
// this sub-object range, then this is the point where we will detect that
// fact and error out.
//
uint32_t conformanceID = 0xFFFFFFFF;
SLANG_RETURN_ON_FAIL(slangSession->getTypeConformanceWitnessSequentialID(
concreteType, existentialType, &conformanceID));
//
// Once we have the conformance ID, then we can write it into the object
// at the required offset.
//
SLANG_RETURN_ON_FAIL(setData(witnessTableOffset, &conformanceID, sizeof(conformanceID)));
return SLANG_OK;
}
ResourceViewBase* SimpleShaderObjectData::getResourceView(
RendererBase* device,
slang::TypeLayoutReflection* elementLayout,
slang::BindingType bindingType)
{
if (!m_structuredBuffer)
{
// Create structured buffer resource if it has not been created.
IBufferResource::Desc desc = {};
desc.allowedStates =
ResourceStateSet(ResourceState::ShaderResource, ResourceState::UnorderedAccess);
desc.defaultState = ResourceState::ShaderResource;
desc.elementSize = (int)elementLayout->getSize();
desc.format = Format::Unknown;
desc.type = IResource::Type::Buffer;
desc.sizeInBytes = (Size)m_ordinaryData.getCount();
ComPtr<IBufferResource> bufferResource;
SLANG_RETURN_NULL_ON_FAIL(device->createBufferResource(
desc, m_ordinaryData.getBuffer(), bufferResource.writeRef()));
m_structuredBuffer = static_cast<BufferResource*>(bufferResource.get());
// Create read-only (shader-resource) and mutable (unordered access) views.
ComPtr<IResourceView> resourceView;
IResourceView::Desc viewDesc = {};
viewDesc.format = Format::Unknown;
viewDesc.type = IResourceView::Type::ShaderResource;
SLANG_RETURN_NULL_ON_FAIL(device->createBufferView(
bufferResource.get(), nullptr, viewDesc, resourceView.writeRef()));
m_structuredBufferView = static_cast<ResourceViewBase*>(resourceView.get());
viewDesc.type = IResourceView::Type::UnorderedAccess;
SLANG_RETURN_NULL_ON_FAIL(
device->createBufferView(
bufferResource.get(), nullptr, viewDesc, resourceView.writeRef()));
m_rwStructuredBufferView = static_cast<ResourceViewBase*>(resourceView.get());
}
switch (bindingType)
{
case slang::BindingType::RawBuffer:
return m_structuredBufferView.Ptr();
case slang::BindingType::MutableRawBuffer:
return m_rwStructuredBufferView.Ptr();
default:
SLANG_ASSERT(false && "Invalid binding type.");
return nullptr;
}
}
void ShaderProgramBase::init(const IShaderProgram::Desc& inDesc)
{
desc = inDesc;
slangGlobalScope = desc.slangGlobalScope;
for (GfxIndex i = 0; i < desc.entryPointCount; i++)
{
slangEntryPoints.add(ComPtr<slang::IComponentType>(desc.slangEntryPoints[i]));
}
auto session = desc.slangGlobalScope ? desc.slangGlobalScope->getSession() : nullptr;
if (desc.linkingStyle == IShaderProgram::LinkingStyle::SingleProgram)
{
List<slang::IComponentType*> components;
if (desc.slangGlobalScope)
{
components.add(desc.slangGlobalScope);
}
for (GfxIndex i = 0; i < desc.entryPointCount; i++)
{
if (!session)
{
session = desc.slangEntryPoints[i]->getSession();
}
components.add(desc.slangEntryPoints[i]);
}
session->createCompositeComponentType(
components.getBuffer(), components.getCount(), linkedProgram.writeRef());
}
else
{
for (GfxIndex i = 0; i < desc.entryPointCount; i++)
{
if (desc.slangGlobalScope)
{
slang::IComponentType* entryPointComponents[2] = {
desc.slangGlobalScope, desc.slangEntryPoints[i]};
ComPtr<slang::IComponentType> linkedEntryPoint;
session->createCompositeComponentType(
entryPointComponents, 2, linkedEntryPoint.writeRef());
linkedEntryPoints.add(linkedEntryPoint);
}
else
{
linkedEntryPoints.add(ComPtr<slang::IComponentType>(desc.slangEntryPoints[i]));
}
}
linkedProgram = desc.slangGlobalScope;
}
}
Result ShaderProgramBase::compileShaders(RendererBase* device)
{
// For a fully specialized program, read and store its kernel code in `shaderProgram`.
auto compileShader = [&](slang::EntryPointReflection* entryPointInfo,
slang::IComponentType* entryPointComponent,
SlangInt entryPointIndex)
{
auto stage = entryPointInfo->getStage();
ComPtr<ISlangBlob> kernelCode;
ComPtr<ISlangBlob> diagnostics;
auto compileResult = device->getEntryPointCodeFromShaderCache(entryPointComponent,
entryPointIndex, 0, kernelCode.writeRef(), diagnostics.writeRef());
if (diagnostics)
{
getDebugCallback()->handleMessage(
compileResult == SLANG_OK ? DebugMessageType::Warning : DebugMessageType::Error,
DebugMessageSource::Slang,
(char*)diagnostics->getBufferPointer());
}
SLANG_RETURN_ON_FAIL(compileResult);
SLANG_RETURN_ON_FAIL(createShaderModule(entryPointInfo, kernelCode));
return SLANG_OK;
};
if (linkedEntryPoints.getCount() == 0)
{
// If the user does not explicitly specify entry point components, find them from
// `linkedEntryPoints`.
auto programReflection = linkedProgram->getLayout();
for (SlangUInt i = 0; i < programReflection->getEntryPointCount(); i++)
{
SLANG_RETURN_ON_FAIL(compileShader(
programReflection->getEntryPointByIndex(i), linkedProgram, (SlangInt)i));
}
}
else
{
// If the user specifies entry point components via the separated entry point array,
// compile code from there.
for (auto& entryPoint : linkedEntryPoints)
{
SLANG_RETURN_ON_FAIL(
compileShader(entryPoint->getLayout()->getEntryPointByIndex(0), entryPoint, 0));
}
}
return SLANG_OK;
}
Result ShaderProgramBase::createShaderModule(
slang::EntryPointReflection* entryPointInfo, ComPtr<ISlangBlob> kernelCode)
{
SLANG_UNUSED(entryPointInfo);
SLANG_UNUSED(kernelCode);
return SLANG_OK;
}
Result RendererBase::maybeSpecializePipeline(
PipelineStateBase* currentPipeline,
ShaderObjectBase* rootObject,
RefPtr<PipelineStateBase>& outNewPipeline)
{
outNewPipeline = static_cast<PipelineStateBase*>(currentPipeline);
auto pipelineType = currentPipeline->desc.type;
if (currentPipeline->unspecializedPipelineState)
currentPipeline = currentPipeline->unspecializedPipelineState;
// If the currently bound pipeline is specializable, we need to specialize it based on bound shader objects.
if (currentPipeline->isSpecializable)
{
specializationArgs.clear();
SLANG_RETURN_ON_FAIL(rootObject->collectSpecializationArgs(specializationArgs));
// Construct a shader cache key that represents the specialized shader kernels.
PipelineKey pipelineKey;
pipelineKey.pipeline = currentPipeline;
pipelineKey.specializationArgs.addRange(specializationArgs.componentIDs);
pipelineKey.updateHash();
RefPtr<PipelineStateBase> specializedPipelineState = shaderCache.getSpecializedPipelineState(pipelineKey);
// Try to find specialized pipeline from shader cache.
if (!specializedPipelineState)
{
auto unspecializedProgram = static_cast<ShaderProgramBase*>(pipelineType == PipelineType::Compute
? currentPipeline->desc.compute.program
: currentPipeline->desc.graphics.program);
auto unspecializedProgramLayout = unspecializedProgram->linkedProgram->getLayout();
ComPtr<slang::IComponentType> specializedComponentType;
ComPtr<slang::IBlob> diagnosticBlob;
auto compileRs = unspecializedProgram->linkedProgram->specialize(
specializationArgs.components.getArrayView().getBuffer(),
specializationArgs.getCount(),
specializedComponentType.writeRef(),
diagnosticBlob.writeRef());
if (diagnosticBlob)
{
getDebugCallback()->handleMessage(
compileRs == SLANG_OK ? DebugMessageType::Warning : DebugMessageType::Error,
DebugMessageSource::Slang,
(char*)diagnosticBlob->getBufferPointer());
}
SLANG_RETURN_ON_FAIL(compileRs);
// Now create the specialized shader program using compiled binaries.
ComPtr<IShaderProgram> specializedProgram;
IShaderProgram::Desc specializedProgramDesc = unspecializedProgram->desc;
specializedProgramDesc.slangGlobalScope = specializedComponentType;
if (specializedProgramDesc.linkingStyle == IShaderProgram::LinkingStyle::SingleProgram)
{
// When linking style is GraphicsCompute, the specialized global scope already contains
// entry-points, so we do not need to supply them again when creating the specialized
// pipeline.
specializedProgramDesc.entryPointCount = 0;
}
SLANG_RETURN_ON_FAIL(createProgram(specializedProgramDesc, specializedProgram.writeRef()));
// Create specialized pipeline state.
ComPtr<IPipelineState> specializedPipelineComPtr;
switch (pipelineType)
{
case PipelineType::Compute:
{
auto pipelineDesc = currentPipeline->desc.compute;
pipelineDesc.program = specializedProgram;
SLANG_RETURN_ON_FAIL(
createComputePipelineState(pipelineDesc, specializedPipelineComPtr.writeRef()));
break;
}
case PipelineType::Graphics:
{
auto pipelineDesc = currentPipeline->desc.graphics;
pipelineDesc.program = static_cast<ShaderProgramBase*>(specializedProgram.get());
SLANG_RETURN_ON_FAIL(createGraphicsPipelineState(
pipelineDesc, specializedPipelineComPtr.writeRef()));
break;
}
case PipelineType::RayTracing:
{
auto pipelineDesc = currentPipeline->desc.rayTracing;
pipelineDesc.program = static_cast<ShaderProgramBase*>(specializedProgram.get());
SLANG_RETURN_ON_FAIL(createRayTracingPipelineState(
pipelineDesc.get(), specializedPipelineComPtr.writeRef()));
break;
}
default:
break;
}
specializedPipelineState =
static_cast<PipelineStateBase*>(specializedPipelineComPtr.get());
specializedPipelineState->unspecializedPipelineState = currentPipeline;
shaderCache.addSpecializedPipeline(pipelineKey, specializedPipelineState);
}
auto specializedPipelineStateBase = static_cast<PipelineStateBase*>(specializedPipelineState.Ptr());
outNewPipeline = specializedPipelineStateBase;
}
return SLANG_OK;
}
IDebugCallback*& _getDebugCallback()
{
static IDebugCallback* callback = nullptr;
return callback;
}
class NullDebugCallback : public IDebugCallback
{
public:
virtual SLANG_NO_THROW void SLANG_MCALL
handleMessage(DebugMessageType type, DebugMessageSource source, const char* message) override
{
SLANG_UNUSED(type);
SLANG_UNUSED(source);
SLANG_UNUSED(message);
}
};
IDebugCallback* _getNullDebugCallback()
{
static NullDebugCallback result = {};
return &result;
}
Result ShaderObjectBase::copyFrom(IShaderObject* object, ITransientResourceHeap* transientHeap)
{
if (auto srcObj = dynamic_cast<MutableRootShaderObject*>(object))
{
setData(gfx::ShaderOffset(), srcObj->m_data.begin(), (size_t)srcObj->m_data.getCount()); // TODO: Change size_t to Count?
for (auto& kv : srcObj->m_objects)
{
ComPtr<IShaderObject> subObject;
SLANG_RETURN_ON_FAIL(kv.Value->getCurrentVersion(transientHeap, subObject.writeRef()));
setObject(kv.Key, subObject);
}
for (auto& kv : srcObj->m_resources)
{
setResource(kv.Key, kv.Value.Ptr());
}
for (auto& kv : srcObj->m_samplers)
{
setSampler(kv.Key, kv.Value.Ptr());
}
for (auto& kv : srcObj->m_specializationArgs)
{
setSpecializationArgs(kv.Key, kv.Value.begin(), (uint32_t)kv.Value.getCount());
}
return SLANG_OK;
}
return SLANG_FAIL;
}
Result ShaderTableBase::init(const IShaderTable::Desc& desc)
{
m_rayGenShaderCount = desc.rayGenShaderCount;
m_missShaderCount = desc.missShaderCount;
m_hitGroupCount = desc.hitGroupCount;
m_shaderGroupNames.reserve(desc.hitGroupCount + desc.missShaderCount + desc.rayGenShaderCount);
m_recordOverwrites.reserve(desc.hitGroupCount + desc.missShaderCount + desc.rayGenShaderCount);
for (GfxIndex i = 0; i < desc.rayGenShaderCount; i++)
{
m_shaderGroupNames.add(desc.rayGenShaderEntryPointNames[i]);
if (desc.rayGenShaderRecordOverwrites)
{
m_recordOverwrites.add(desc.rayGenShaderRecordOverwrites[i]);
}
else
{
m_recordOverwrites.add(ShaderRecordOverwrite{});
}
}
for (GfxIndex i = 0; i < desc.missShaderCount; i++)
{
m_shaderGroupNames.add(desc.missShaderEntryPointNames[i]);
if (desc.missShaderRecordOverwrites)
{
m_recordOverwrites.add(desc.missShaderRecordOverwrites[i]);
}
else
{
m_recordOverwrites.add(ShaderRecordOverwrite{});
}
}
for (GfxIndex i = 0; i < desc.hitGroupCount; i++)
{
m_shaderGroupNames.add(desc.hitGroupNames[i]);
if (desc.hitGroupRecordOverwrites)
{
m_recordOverwrites.add(desc.hitGroupRecordOverwrites[i]);
}
else
{
m_recordOverwrites.add(ShaderRecordOverwrite{});
}
}
return SLANG_OK;
}
bool isDepthFormat(Format format)
{
switch (format)
{
case Format::D16_UNORM:
case Format::D32_FLOAT:
return true;
default:
return false;
}
}
} // namespace gfx
|