/
d3d11.cpp
8783 lines (7272 loc) · 543 KB
/
d3d11.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
/**
* This file is part of Special K.
*
* Special K is free software : you can redistribute it
* and/or modify it under the terms of the GNU General Public License
* as published by The Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* Special K is distributed in the hope that it will be useful,
*
* But WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Special K.
*
* If not, see <http://www.gnu.org/licenses/>.
*
**/
#include <SpecialK/stdafx.h>
#ifdef __SK_SUBSYSTEM__
#undef __SK_SUBSYSTEM__
#endif
#define __SK_SUBSYSTEM__ L" D3D 11 "
#define _L2(w) L ## w
#define _L(w) _L2(w)
#include <SpecialK/render/dxgi/dxgi_util.h>
#include <SpecialK/render/d3d11/d3d11_shader.h>
#include <SpecialK/render/d3d11/d3d11_tex_mgr.h>
#include <SpecialK/render/d3d11/d3d11_screenshot.h>
#include <SpecialK/render/d3d11/d3d11_state_tracker.h>
#include <SpecialK/render/d3d11/utility/d3d11_texture.h>
#include <SpecialK/render/dxgi/dxgi_hdr.h>
#include <SpecialK/control_panel/d3d11.h>
#include <execution>
#define SK_D3D11_WRAP_IMMEDIATE_CTX
#define SK_D3D11_WRAP_DEFERRED_CTX
// NEVER, under any circumstances, call any functions using this!
ID3D11Device* g_pD3D11Dev = nullptr;
static constexpr auto _MAX_UAVS = 8;
UINT start_uav = 0;
UINT uav_count = _MAX_UAVS;
float uav_clear [4] =
{ 0.0f, 0.0f, 0.0f, 0.0f };
// For effects that blink; updated once per-frame.
//DWORD dwFrameTime = SK::ControlPanel::current_time;
// For effects that blink; updated once per-frame.
DWORD& dwFrameTime = SK::ControlPanel::current_time;
DWORD D3D11_GetFrameTime (void)
{
return dwFrameTime;
}
void
SK_D3D11_SetDebugName ( ID3D11DeviceChild* pDevChild,
const std::wstring& kName )
{
if (! pDevChild)
return;
static int
__SK_D3D11_DebugLayerActive = -1;
if (__SK_D3D11_DebugLayerActive == -1)
{
SK_ComPtr <ID3D11Device> pDev;
pDevChild->GetDevice ( &pDev.p );
SK_ComQIPtr <ID3D11Debug> pDebug (pDev);
__SK_D3D11_DebugLayerActive =
pDebug.p != nullptr ?
1 : 0;
}
// Store object names only if we are logging stuff or if the
// D3D11 debug layer is active
if (kName.empty () /*|| ( __SK_D3D11_DebugLayerActive == 0 &&
config.system.log_level < 2 )*/)
{ // Ignore the comment above,
return; // debug names are useful in SK's built-in debugger :)
}
SK_LOGi2 (
L"Created D3D11 Object: %ws", kName.c_str ()
);
//
// D3D has separate Private Data GUIDs for Wide and ANSI names,
// and various parts of the debug layer use one or the other.
//
// * D3D11 mostly uses ANSI, but it is best to just store
// all possible text encodings and cover all bases.
//
D3D_SET_OBJECT_NAME_N_A (pDevChild, 0, nullptr);
D3D_SET_OBJECT_NAME_N_W (pDevChild, 0, nullptr);
D3D_SET_OBJECT_NAME_N_W ( pDevChild,
static_cast <UINT> ( kName.length () ),
kName.data ()
);
std::string utf8_copy =
SK_WideCharToUTF8 (kName);
D3D_SET_OBJECT_NAME_N_A ( pDevChild,
static_cast <UINT> ( (utf8_copy).length () ),
(utf8_copy).data ()
);
}
template <typename _T>
HRESULT
SK_D3D11_GET_OBJECT_NAME_N ( ID3D11DeviceChild *pObject,
UINT *pBytes,
_T *pName = nullptr );
template <>
HRESULT
SK_D3D11_GET_OBJECT_NAME_N ( ID3D11DeviceChild *pObject,
UINT *pBytes,
char *pName )
{
if ( (! pObject) &&
(! pBytes ) )
return E_POINTER;
return
pObject->GetPrivateData (
WKPDID_D3DDebugObjectName,
pBytes,
pName );
}
template <>
HRESULT
SK_D3D11_GET_OBJECT_NAME_N ( ID3D11DeviceChild *pObject,
UINT *pBytes,
wchar_t *pName )
{
if ( (! pObject) &&
(! pBytes ) )
return E_POINTER;
return
pObject->GetPrivateData (
WKPDID_D3DDebugObjectNameW,
pBytes,
pName );
}
bool
SK_D3D11_HasDebugName (ID3D11DeviceChild* pD3D11Obj)
{
UINT uiNameLen = 0;
HRESULT hr =
pD3D11Obj->GetPrivateData (WKPDID_D3DDebugObjectNameW, &uiNameLen, nullptr);
if (FAILED (hr) && hr != DXGI_ERROR_MORE_DATA)
{
uiNameLen = 0;
hr =
pD3D11Obj->GetPrivateData (WKPDID_D3DDebugObjectName, &uiNameLen, nullptr);
if (FAILED (hr) && hr != DXGI_ERROR_MORE_DATA)
return false;
}
return
( uiNameLen > 0 );
}
template <typename _T>
std::basic_string <_T>
SK_D3D11_GetDebugName (ID3D11DeviceChild* pD3D11Obj)
{
if (pD3D11Obj != nullptr)
{
UINT bufferLen = 0;
HRESULT hr =
SK_D3D11_GET_OBJECT_NAME_N <_T> ( pD3D11Obj,
&bufferLen, nullptr );
if (SUCCEEDED (hr) || bufferLen > 0)
{
if (bufferLen >= sizeof (_T))
{
std::basic_string <_T>
name (
bufferLen / sizeof (_T),
(_T)0 );
if ( SUCCEEDED (
SK_D3D11_GET_OBJECT_NAME_N <_T> ( pD3D11Obj,
&bufferLen, name.data () )
)
)
{
return name;
}
}
}
}
return
std::basic_string <_T> (reinterpret_cast <_T *> (L""));
}
std::wstring
SK_D3D11_GetDebugNameW (ID3D11DeviceChild* pD3D11Obj)
{
return
SK_D3D11_GetDebugName <wchar_t> (pD3D11Obj);
}
std::string
SK_D3D11_GetDebugNameA (ID3D11DeviceChild* pD3D11Obj)
{
return
SK_D3D11_GetDebugName <char> (pD3D11Obj);
}
std::string
SK_D3D11_GetDebugNameUTF8 (ID3D11DeviceChild* pD3D11Obj)
{
auto wide_name =
SK_D3D11_GetDebugName <wchar_t> (pD3D11Obj);
if (wide_name.empty ())
{
auto name =
SK_D3D11_GetDebugName <char> (pD3D11Obj);
if (! name.empty ())
return name;
return "Unnamed";
}
return
SK_WideCharToUTF8 (wide_name);
}
bool
SK_D3D11_DrawCallFilter (int elem_cnt, int vtx_cnt, uint32_t vtx_shader);
extern HRESULT
SK_D3D11_InjectSteamHDR ( _In_ ID3D11DeviceContext *pDevCtx,
_In_ UINT VertexCount,
_In_ UINT StartVertexLocation,
_In_ D3D11_Draw_pfn pfnD3D11Draw );
extern HRESULT
SK_D3D11_InjectGenericHDROverlay ( _In_ ID3D11DeviceContext *pDevCtx,
_In_ UINT VertexCount,
_In_ UINT StartVertexLocation,
_In_ uint32_t crc32,
_In_ D3D11_Draw_pfn pfnD3D11Draw );
extern HRESULT
SK_D3D11_Inject_uPlayHDR ( _In_ ID3D11DeviceContext *pDevCtx,
_In_ UINT IndexCount,
_In_ UINT StartIndexLocation,
_In_ INT BaseVertexLocation,
_In_ D3D11_DrawIndexed_pfn pfnD3D11DrawIndexed );
extern HRESULT
SK_D3D11_Inject_EpicHDR ( _In_ ID3D11DeviceContext *pDevCtx,
_In_ UINT IndexCount,
_In_ UINT StartIndexLocation,
_In_ INT BaseVertexLocation,
_In_ D3D11_DrawIndexed_pfn pfnD3D11DrawIndexed );
extern bool SK_D3D11_ShowShaderModDlg (void);
LPVOID pfnD3D11CreateDevice = nullptr;
LPVOID pfnD3D11CreateDeviceAndSwapChain = nullptr;
HMODULE SK::DXGI::hModD3D11 = nullptr;
SK::DXGI::PipelineStatsD3D11 SK::DXGI::pipeline_stats_d3d11 = { };
volatile HANDLE hResampleThread = nullptr;
static SK_LazyGlobal <
Concurrency::concurrent_unordered_map
< ID3D11DeviceContext *,
SK_ComPtr <ID3D11DeviceContext4> > > wrapped_contexts;
static SK_LazyGlobal <
Concurrency::concurrent_unordered_map
< ID3D11Device *,
SK_ComPtr <ID3D11DeviceContext4> > > wrapped_immediates;
#pragma data_seg (".SK_D3D11_Hooks")
extern "C"
{
// Global DLL's cache
__declspec (dllexport) SK_HookCacheEntryGlobal (D3D11CreateDevice)
__declspec (dllexport) SK_HookCacheEntryGlobal (D3D11CreateDeviceAndSwapChain)
};
#pragma data_seg ()
#pragma comment (linker, "/SECTION:.SK_D3D11_Hooks,RWS")
// Local DLL's cached addresses
SK_HookCacheEntryLocal ( D3D11CreateDevice, L"d3d11.dll",
D3D11CreateDevice_Detour,
nullptr )
SK_HookCacheEntryLocal ( D3D11CreateDeviceAndSwapChain, L"d3d11.dll",
D3D11CreateDeviceAndSwapChain_Detour,
nullptr )
static sk_hook_cache_array global_d3d11_records =
{ &GlobalHook_D3D11CreateDevice,
&GlobalHook_D3D11CreateDeviceAndSwapChain };
static sk_hook_cache_array local_d3d11_records =
{ &LocalHook_D3D11CreateDevice,
&LocalHook_D3D11CreateDeviceAndSwapChain };
SK_LazyGlobal <SK_D3D11_KnownShaders> SK_D3D11_Shaders;
SK_LazyGlobal <target_tracking_s> tracked_rtv;
volatile LONG __SKX_ComputeAntiStall = 1;
volatile LONG SK_D3D11_NumberOfSeenContexts = 0;
volatile LONG _mutex_init = 0;
void
SK_D3D11_InitMutexes (void)
{
if (ReadAcquire (&_mutex_init) > 1)
return;
LocalHook_D3D11CreateDevice.trampoline = static_cast_p2p <void> (&D3D11CreateDevice_Import);
LocalHook_D3D11CreateDeviceAndSwapChain.trampoline = static_cast_p2p <void> (&D3D11CreateDeviceAndSwapChain_Import);
if (0 == InterlockedCompareExchange (&_mutex_init, 1, 0))
{
cs_shader = std::make_unique <SK_Thread_HybridSpinlock> (0x666);
cs_shader_vs = std::make_unique <SK_Thread_HybridSpinlock> (0x300);
cs_shader_ps = std::make_unique <SK_Thread_HybridSpinlock> (0x200);
cs_shader_gs = std::make_unique <SK_Thread_HybridSpinlock> (0x100);
cs_shader_hs = std::make_unique <SK_Thread_HybridSpinlock> (0x100);
cs_shader_ds = std::make_unique <SK_Thread_HybridSpinlock> (0x100);
cs_shader_cs = std::make_unique <SK_Thread_HybridSpinlock> (0x300);
cs_mmio = std::make_unique <SK_Thread_HybridSpinlock> (0xe0);
cs_render_view = std::make_unique <SK_Thread_HybridSpinlock> (0xb0);
InterlockedIncrement (&_mutex_init);
}
else
SK_Thread_SpinUntilAtomicMin (&_mutex_init, 2);
}
void
SK_D3D11_CleanupMutexes (void)
{
if ( ReadAcquire (&_mutex_init) > 1 &&
ReadAcquire (&__SK_DLL_Ending) != 0 )
{
cs_shader.reset ();
cs_shader_vs.reset ();
cs_shader_ps.reset ();
cs_shader_gs.reset ();
cs_shader_hs.reset ();
cs_shader_ds.reset ();
cs_shader_cs.reset ();
cs_mmio.reset ();
cs_render_view.reset ();
}
}
extern std::pair <BOOL*, BOOL>
SK_ImGui_FlagDrawing_OnD3D11Ctx (UINT dev_idx);
extern bool
SK_ImGui_IsDrawing_OnD3D11Ctx (UINT dev_idx, ID3D11DeviceContext* pDevCtx);
SK_LazyGlobal <
std::array < SK_D3D11_ContextResources,
SK_D3D11_MAX_DEV_CONTEXTS + 1 >
> SK_D3D11_PerCtxResources;
SK_LazyGlobal <
std::unordered_set <ID3D11Texture2D *>
> used_textures;
SK_LazyGlobal <
std::unordered_map < ID3D11DeviceContext *,
mapped_resources_s >
> mapped_resources;
void
SK_D3D11_MergeCommandLists ( ID3D11DeviceContext *pSurrogate,
ID3D11DeviceContext *pMerge )
{
SK_LOG_FIRST_CALL
static auto& shaders =
SK_D3D11_Shaders;
auto _GetRegistry =
[&]( SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>** ppShaderDomain,
sk_shader_class type )
{
switch (type)
{
default:
case sk_shader_class::Vertex:
*ppShaderDomain =
reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->vertex);
break;
case sk_shader_class::Pixel:
*ppShaderDomain =
reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->pixel);
break;
case sk_shader_class::Geometry:
*ppShaderDomain =
reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->geometry);
break;
case sk_shader_class::Domain:
*ppShaderDomain =
reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->domain);
break;
case sk_shader_class::Hull:
*ppShaderDomain =
reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->hull);
break;
case sk_shader_class::Compute:
*ppShaderDomain =
reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->compute);
break;
}
return *ppShaderDomain;
};
using _ShaderRepo =
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*;
_ShaderRepo pShaderRepoIn = nullptr;
_ShaderRepo pShaderRepoOut = nullptr;
const UINT dev_ctx_in =
SK_D3D11_GetDeviceContextHandle (pSurrogate);
const UINT dev_ctx_out =
SK_D3D11_GetDeviceContextHandle (pMerge);
if (dev_ctx_in > SK_D3D11_MAX_DEV_CONTEXTS ||
dev_ctx_out > SK_D3D11_MAX_DEV_CONTEXTS)
{
SK_ReleaseAssert (!"Device Context Out of Range");
return;
}
auto& ctx_in_res =
SK_D3D11_PerCtxResources [dev_ctx_in];
auto& ctx_out_res =
SK_D3D11_PerCtxResources [dev_ctx_out];
ctx_out_res.used_textures.insert ( ctx_in_res.used_textures.begin (),
ctx_in_res.used_textures.end () );
ctx_out_res.temp_resources.insert ( ctx_in_res.temp_resources.begin (),
ctx_in_res.temp_resources.end () );
//dll_log->Log ( L"Ctx: %lu -> Ctx: %lu :: %lu Used Textures, %lu Temp Resources",
// dev_ctx_in, dev_ctx_out, SK_D3D11_PerCtxResources [dev_ctx_in].used_textures.size (),
// SK_D3D11_PerCtxResources [dev_ctx_in].temp_resources.size () );
ctx_in_res.used_textures.clear ();
ctx_in_res.temp_resources.clear ();
bool reset = true;// false;
static const sk_shader_class classes [] = {
sk_shader_class::Vertex, sk_shader_class::Pixel,
sk_shader_class::Geometry, sk_shader_class::Hull,
sk_shader_class::Domain, sk_shader_class::Compute
};
for ( auto i : classes )
{
_GetRegistry ( &pShaderRepoIn, i );
_GetRegistry ( &pShaderRepoOut, i )->current.shader [dev_ctx_out] =
pShaderRepoIn->current.shader [dev_ctx_in ];
if (reset)
{
RtlSecureZeroMemory
( pShaderRepoIn->current.views [dev_ctx_in ],
128 * sizeof (ptrdiff_t) );
pShaderRepoIn->current.shader [dev_ctx_in ] = 0x0;
pShaderRepoIn->tracked.deactivate (pSurrogate, dev_ctx_in);
}
}
for ( int i = 0; i < 6; ++i )
{
memcpy ( &d3d11_shader_stages [i][dev_ctx_out].skipped_bindings [0],
&d3d11_shader_stages [i][ dev_ctx_in].skipped_bindings [0],
sizeof (ID3D11ShaderResourceView *) * D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT );
RtlSecureZeroMemory (
&d3d11_shader_stages [i][ dev_ctx_in].skipped_bindings [0],
sizeof (ID3D11ShaderResourceView *) * D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT );
memcpy ( &d3d11_shader_stages [i][dev_ctx_out].real_bindings [0],
&d3d11_shader_stages [i][ dev_ctx_in].real_bindings [0],
sizeof (ID3D11ShaderResourceView *) * D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT );
RtlSecureZeroMemory (
&d3d11_shader_stages [i][ dev_ctx_in].real_bindings [0],
sizeof (ID3D11ShaderResourceView *) * D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT );
}
}
void
SK_D3D11_ResetContextState (ID3D11DeviceContext* pDevCtx, UINT dev_ctx)
{
static auto& shaders =
SK_D3D11_Shaders;
auto _GetRegistry =
[&]( SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>** ppShaderDomain,
sk_shader_class type )
{
switch (type)
{
default:
case sk_shader_class::Vertex:
*ppShaderDomain = reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown> *>
(&shaders->vertex);
break;
case sk_shader_class::Pixel:
*ppShaderDomain = reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->pixel);
break;
case sk_shader_class::Geometry:
*ppShaderDomain = reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->geometry);
break;
case sk_shader_class::Domain:
*ppShaderDomain = reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->domain);
break;
case sk_shader_class::Hull:
*ppShaderDomain = reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->hull);
break;
case sk_shader_class::Compute:
*ppShaderDomain = reinterpret_cast <
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>*
> (&shaders->compute);
break;
}
return
*ppShaderDomain;
};
SK_D3D11_KnownShaders::ShaderRegistry <IUnknown>* pShaderRepo = nullptr;
if (dev_ctx == UINT_MAX)
{
dev_ctx =
SK_D3D11_GetDeviceContextHandle (pDevCtx);
}
if (dev_ctx > SK_D3D11_MAX_DEV_CONTEXTS)
return;
static const sk_shader_class classes [] = {
sk_shader_class::Vertex, sk_shader_class::Pixel,
sk_shader_class::Geometry, sk_shader_class::Hull,
sk_shader_class::Domain, sk_shader_class::Compute
};
for ( auto i : classes )
{
_GetRegistry ( &pShaderRepo, i )->current.shader [dev_ctx] = 0x0;
pShaderRepo->tracked.deactivate (pDevCtx, dev_ctx);
RtlSecureZeroMemory
( pShaderRepo->current.views [dev_ctx],
128 * sizeof (ptrdiff_t) );
}
for ( UINT i = 0 ; i < 6 ; ++i )
{
auto& stage =
d3d11_shader_stages [i][dev_ctx];
UINT k = 1;
// Optimization strategy based on contiguous arrays of binding slots
//
// * Find the lowest NULL slot, this demarcates the size of the array.
//
for ( k = 1 ; k < D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT; k *= 2 )
{
// Divide the search space in 1/2, continue dividing if NULL
if (stage.skipped_bindings [k - 1] == nullptr)
{
// Count downwards to find the highest non-NULL binding slot
while ( k >= 1 &&
stage.skipped_bindings [k--] != nullptr )
{
;
}
break;
}
}
// We now know the size, let's get busy!
for ( UINT j = 0 ; j <= k; ++j )
{
if (stage.skipped_bindings [j] != nullptr)
{ stage.skipped_bindings [j]->Release ();
stage.skipped_bindings [j] = nullptr;
}
}
RtlSecureZeroMemory (
&stage.real_bindings [0],
D3D11_COMMONSHADER_INPUT_RESOURCE_SLOT_COUNT * sizeof (ptrdiff_t)
);
}
}
// Only reset once even if we take two trips through wrappers / hooks.
SK_LazyGlobal <std::array <bool, SK_D3D11_MAX_DEV_CONTEXTS + 1>>
__SK_D3D11_ContextResetQueue;
SK_LazyGlobal <std::array <ID3D11DeviceContext *, SK_D3D11_MAX_DEV_CONTEXTS + 1>>
__SK_D3D11_ContextResetQueueDevices;
bool
SK_D3D11_QueueContextReset ( ID3D11DeviceContext* pDevCtx,
UINT dev_ctx )
{
// We can't do anything about this
SK_ReleaseAssert (dev_ctx != UINT_MAX);
if (dev_ctx > SK_D3D11_MAX_DEV_CONTEXTS)
return false;
bool ret =
__SK_D3D11_ContextResetQueue [dev_ctx];
__SK_D3D11_ContextResetQueue [dev_ctx] = true;
__SK_D3D11_ContextResetQueueDevices [dev_ctx] = pDevCtx;
return ret;
}
bool
SK_D3D11_DispatchContextResetQueue (UINT dev_ctx)
{
if (dev_ctx <= SK_D3D11_MAX_DEV_CONTEXTS)
{
if (__SK_D3D11_ContextResetQueue [dev_ctx])
{ __SK_D3D11_ContextResetQueue [dev_ctx] = false;
SK_D3D11_ResetContextState (__SK_D3D11_ContextResetQueueDevices [dev_ctx],
dev_ctx);
return true;
}
}
return false;
}
int SK_D3D11_AllocatedDevContexts = 0;
BOOL
SK_D3D11_SetDeviceContextHandle ( ID3D11DeviceContext *pDevCtx,
LONG handle )
{
if ( handle >= SK_D3D11_AllocatedDevContexts )
SK_D3D11_AllocatedDevContexts = handle + 1;
SK_ReleaseAssert (handle < SK_D3D11_MAX_DEV_CONTEXTS);
constexpr UINT size =
sizeof (LONG);
if ( FAILED (
pDevCtx->SetPrivateData ( SKID_D3D11DeviceContextHandle,
size, &handle )
)
)
{
return FALSE;
}
return TRUE;
}
LONG
SK_D3D11_GetDeviceContextHandle ( ID3D11DeviceContext *pDevCtx )
{
if (pDevCtx == nullptr) return SK_D3D11_MAX_DEV_CONTEXTS;
const LONG RESOLVE_MAX = 16;
static std::pair <ID3D11DeviceContext*, LONG>
last_resolve [RESOLVE_MAX];
static volatile LONG
resolve_idx = 0;
const auto early_out =
&last_resolve [std::min (RESOLVE_MAX, ReadAcquire (&resolve_idx))];
if (early_out->first == pDevCtx)
return early_out->second;
auto _CacheResolution =
[&](LONG idx, ID3D11DeviceContext* pCtx, LONG handle) ->
void
{
auto new_pair ( std::make_pair (pCtx, handle) );
std::swap ( last_resolve [idx],
new_pair );
InterlockedExchange (&resolve_idx, std::min (RESOLVE_MAX, idx));
};
UINT size = sizeof (LONG);
LONG handle = SK_D3D11_MAX_DEV_CONTEXTS;
LONG idx =
ReadAcquire (&resolve_idx) + 1;
if (idx >= RESOLVE_MAX)
idx = 0;
if ( SUCCEEDED (
pDevCtx->GetPrivateData ( SKID_D3D11DeviceContextHandle,
&size, &handle )
)
)
{
_CacheResolution (idx, pDevCtx, handle);
return handle;
}
std::scoped_lock <SK_Thread_HybridSpinlock>
auto_lock (*cs_shader);
size = sizeof (LONG);
handle = ReadAcquire (&SK_D3D11_NumberOfSeenContexts);
LONG new_handle =
handle;
if ( TRUE != SK_D3D11_SetDeviceContextHandle (pDevCtx, new_handle) )
{
new_handle = 0;
}
else
{
InterlockedIncrement (&SK_D3D11_NumberOfSeenContexts);
}
SK_ReleaseAssert (handle < SK_D3D11_MAX_DEV_CONTEXTS);
_CacheResolution (idx, pDevCtx, handle);
return handle;
}
void
SK_D3D11_CopyContextHandle ( ID3D11DeviceContext *pSrcCtx,
ID3D11DeviceContext *pDstCtx )
{
LONG src_handle =
SK_D3D11_GetDeviceContextHandle (pSrcCtx);
if (src_handle >= 0)
SK_D3D11_SetDeviceContextHandle (pDstCtx, src_handle);
}
uint32_t
__cdecl
SK_D3D11_ChecksumShaderBytecode ( _In_ const void *pShaderBytecode,
_In_ SIZE_T BytecodeLength )
{
uint32_t ret = 0x0;
auto orig_se =
SK_SEH_ApplyTranslator (
SK_FilteringStructuredExceptionTranslator (
EXCEPTION_ACCESS_VIOLATION
)
);
try
{
ret =
crc32c (
0x00, static_cast <const uint8_t *> (pShaderBytecode),
BytecodeLength
);
}
catch (const SK_SEH_IgnoredException&)
{
SK_LOG0 ( (L" >> Threw out disassembled shader due to access violation"
L" during hash."),
L" DXGI ");
}
SK_SEH_RemoveTranslator (orig_se);
return ret;
}
std::string
SK_D3D11_DescribeResource (ID3D11Resource* pRes)
{
if (pRes == nullptr)
{
return "N/A";
}
D3D11_RESOURCE_DIMENSION rDim;
pRes->GetType (&rDim);
switch (rDim)
{
case D3D11_RESOURCE_DIMENSION_BUFFER:
return "Buffer";
break;
case D3D11_RESOURCE_DIMENSION_TEXTURE2D:
{
D3D11_TEXTURE2D_DESC desc = { };
SK_ComQIPtr <ID3D11Texture2D> pTex2D (pRes);
if (pTex2D != nullptr)
pTex2D->GetDesc (&desc);
return (
SK_FormatString ( "Tex2D: (%lux%lu): %hs { %hs/%hs }",
desc.Width,
desc.Height, SK_DXGI_FormatToStr (desc.Format) . data (),
SK_D3D11_DescribeUsage (desc.Usage),
SK_D3D11_DescribeBindFlags (desc.BindFlags).c_str () )
);
} break;
default:
return "Other";
}
};
volatile LONG __d3d11_ready = FALSE;
void WaitForInitD3D11 (void)
{
if (CreateDXGIFactory_Import == nullptr)
{
SK_RunOnce (SK_BootDXGI ());
}
// Load user-defined DLLs (Plug-In)
SK_RunLHIfBitness ( 64, SK_LoadPlugIns64 (),
SK_LoadPlugIns32 () );
if (SK_TLS_Bottom ()->render->d3d11->ctx_init_thread == TRUE)
return;
if ( 0 == ReadAcquire (&__d3d11_ready))
SK_Thread_SpinUntilFlagged (&__d3d11_ready);
}
struct reshade_coeffs_s {
int indexed = 1;
int draw = 1;
int auto_draw = 0;
int indexed_instanced = 1;
int indexed_instanced_indirect = 4096;
int instanced = 1;
int instanced_indirect = 4096;
int dispatch = 1;
int dispatch_indirect = 1;
} SK_D3D11_ReshadeDrawFactors;
SK_RESHADE_CALLBACK_DRAW SK_ReShade_DrawCallback;
SK_RESHADE_CALLBACK_SetDSV SK_ReShade_SetDepthStencilViewCallback;
SK_RESHADE_CALLBACK_GetDSV SK_ReShade_GetDepthStencilViewCallback;
SK_RESHADE_CALLBACK_ClearDSV SK_ReShade_ClearDepthStencilViewCallback;
SK_RESHADE_CALLBACK_CopyResource SK_ReShade_CopyResourceCallback;
uint32_t
__stdcall
SK_D3D11_TextureHashFromCache (ID3D11Texture2D* pTex);
struct d3d11_caps_t {
struct {
bool d3d11_1 = false;
} feature_level;
bool MapNoOverwriteOnDynamicConstantBuffer = false;
} d3d11_caps;
D3D11CreateDeviceAndSwapChain_pfn D3D11CreateDeviceAndSwapChain_Import = nullptr;
D3D11CreateDevice_pfn D3D11CreateDevice_Import = nullptr;
void
SK_D3D11_SetDevice ( ID3D11Device **ppDevice,
D3D_FEATURE_LEVEL FeatureLevel )
{
static SK_RenderBackend_V2& rb =
SK_GetCurrentRenderBackend ();
if ( ppDevice != nullptr )
{
if ( *ppDevice != g_pD3D11Dev )
{
SK_LOG0 ( (L" >> Device = %08" _L(PRIxPTR) L"h (Feature Level:%hs)",
(uintptr_t)*ppDevice,
SK_DXGI_FeatureLevelsToStr ( 1,
(DWORD *)&FeatureLevel
).c_str ()
), __SK_SUBSYSTEM__ );
// We ARE technically holding a reference, but we never make calls to this
// interface - it's just for tracking purposes.
g_pD3D11Dev = *ppDevice;
}
if (config.render.dxgi.exception_mode != -1)
(*ppDevice)->SetExceptionMode (config.render.dxgi.exception_mode);
SK_ComQIPtr <IDXGIDevice> pDXGIDev (ppDevice != nullptr ? *ppDevice : nullptr);
SK_ComPtr <IDXGIAdapter> pAdapter;
if ( pDXGIDev != nullptr )
{
const HRESULT hr =
pDXGIDev->GetParent ( IID_PPV_ARGS (&pAdapter.p) );
if ( SUCCEEDED ( hr ) )
{
if ( pAdapter == nullptr )
return;
const int iver =
SK_GetDXGIAdapterInterfaceVer ( pAdapter );
// IDXGIAdapter3 = DXGI 1.4 (Windows 10+)
if ( iver >= 3 )
{
SK::DXGI::StartBudgetThread_NoAdapter ();
//SK::DXGI::StartBudgetThread ( &pAdapter.p );
}
}
}
}
}
UINT
SK_D3D11_RemoveUndesirableFlags (UINT* Flags) noexcept
{