-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplatform_win.cpp
More file actions
1221 lines (1116 loc) · 39 KB
/
platform_win.cpp
File metadata and controls
1221 lines (1116 loc) · 39 KB
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 Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// testcolorspaces.cpp : Defines the entry point for the application.
//
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "dcomp.lib")
#pragma comment(lib, "dxgi.lib")
#ifndef WINVER // Allow use of features specific to Windows 7 or later.
#define WINVER 0x0A00 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Allow use of features specific to Windows 7 or later.
#define _WIN32_WINNT 0x0A00 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used items from Windows headers
#include "Resource.h"
#include <cassert>
#include <chrono>
#include <sstream>
#include <vector>
#include <Windows.h>
#include <d3d11.h>
#include <dcomp.h>
#include <dxgi1_6.h>
// Rust has better names for the regular types.
using i8 = int8_t;
using u8 = uint8_t;
using i16 = int16_t;
using u16 = uint16_t;
using f32 = float;
using i32 = int32_t;
using u32 = uint32_t;
using f64 = double;
using i64 = int64_t;
using u64 = uint64_t;
using usize = size_t;
template <class T> void SafeRelease(T** ppT)
{
if (*ppT)
{
(*ppT)->Release();
*ppT = NULL;
}
}
enum class Compositor_Status
{
No_Device,
Device_Lost,
Device_Creation_Failed,
Running,
};
class Compositor;
class Compositor_Layer
{
public:
/// Store the layer properties that were used at creation time for
/// convenience when debugging
f32 x = 0;
f32 y = 0;
u32 width = 0;
u32 height = 0;
DXGI_COLOR_SPACE_TYPE dxgiColorspace = DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709;
DXGI_FORMAT dxgiFormat = DXGI_FORMAT_R16G16B16A16_FLOAT;
bool isWindow;
bool isSurface;
/// DirectComposition visual represents the presentation shape (rect) and
/// various rendering properties
IDCompositionVisual* dcompvisual = nullptr;
/// DXGI swap chain is an image flip book of rendered frames, latest one is
/// displayed when the Present method is called, followed by Commit to
/// update the DirectComposition scene
///
/// Both of these refer to the same underlying object, but via different
/// interfaces, it is important that Release is called on swapchain3 before
/// swapchain1 to avoid a race condition, we can't call Release on
/// swapchain1 right after QueryInterface.
/// https://learn.microsoft.com/en-us/windows/win32/api/unknwn/nf-unknwn-iunknown-queryinterface(q)
IDXGISwapChain1* swapchain1 = nullptr;
IDXGISwapChain3* swapchain3 = nullptr;
/// Surface is a single image that retains previous content
IDCompositionSurface* dcompsurface = nullptr;
~Compositor_Layer();
void VisualWithSwapChain(Compositor* comp, f32 _x, f32 _y, u32 _width, u32 _height, DXGI_COLOR_SPACE_TYPE _type, DXGI_FORMAT _format, u8 _bytesPerPixel, void* data);
void VisualWithSurface(Compositor* comp, f32 _x, f32 _y, u32 _width, u32 _height, DXGI_COLOR_SPACE_TYPE _type, DXGI_FORMAT _format, u8 _bytesPerPixel, void* data);
};
Compositor_Layer::~Compositor_Layer()
{
// This crashes for some reason
// SafeRelease(&swapchain3);
SafeRelease(&swapchain1);
SafeRelease(&dcompsurface);
// This crashes for some reason
// SafeRelease(&dcompvisual);
}
class Compositor
{
public:
Compositor_Status status = Compositor_Status::No_Device;
HWND hWindow = nullptr;
f32 scale = 1.0f;
ID3D11Device* d3d = nullptr;
IDXGIDevice* dxgi = nullptr;
IDXGIAdapter* adapter = nullptr;
IDXGIFactory7* factory = nullptr;
IDXGISwapChain1* windowswapchain1 = nullptr;
IDXGISwapChain3* windowswapchain3 = nullptr;
IDCompositionDevice* dcomp = nullptr;
IDCompositionTarget* dcomptarget = nullptr;
ID3D11DeviceContext* context = nullptr;
IDCompositionVisual* rootvisual = nullptr;
// Currently active layers
std::vector<Compositor_Layer> layers;
~Compositor();
void UpdateStatus();
void DestroyDevice();
void CreateDevice(HWND hWnd);
void CreateScene();
void Update(HWND hWnd, bool reset);
void MakeWindowSwapChain(DXGI_COLOR_SPACE_TYPE _type, DXGI_FORMAT _format);
void UpdateSwapChain(IDXGISwapChain1* swapchain, DXGI_COLOR_SPACE_TYPE _type, DXGI_FORMAT _format, u8 _bytesPerPixel, void* data);
};
void Compositor::DestroyDevice()
{
status = Compositor_Status::No_Device;
layers.clear();
if (rootvisual) {
rootvisual->RemoveAllVisuals();
}
SafeRelease(&windowswapchain3);
SafeRelease(&windowswapchain1);
SafeRelease(&rootvisual);
SafeRelease(&adapter);
SafeRelease(&factory);
SafeRelease(&dxgi);
SafeRelease(&dcomp);
SafeRelease(&dcomptarget);
SafeRelease(&context);
SafeRelease(&d3d);
}
void Compositor::UpdateStatus()
{
if (dcomp) {
BOOL bIsValid = FALSE;
HRESULT res = dcomp->CheckDeviceState(&bIsValid);
if (res == S_OK && bIsValid) {
status = Compositor_Status::Running;
} else {
status = Compositor_Status::Device_Lost;
}
} else {
status = Compositor_Status::No_Device;
}
}
void Compositor::CreateDevice(HWND hWnd)
{
// Assume device creation failed if this function exits early.
status = Compositor_Status::Device_Creation_Failed;
hWindow = hWnd;
u32 flags = 0;
flags |= D3D11_CREATE_DEVICE_DEBUG;
constexpr D3D_FEATURE_LEVEL feature_levels[] = {
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
D3D_FEATURE_LEVEL featureLevelSupported = feature_levels[0];
HRESULT hr;
hr = D3D11CreateDevice(
nullptr,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
flags,
feature_levels,
sizeof(feature_levels) / sizeof(feature_levels[0]),
D3D11_SDK_VERSION,
&d3d,
&featureLevelSupported,
nullptr);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
hr = d3d->QueryInterface(&dxgi);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
hr = DCompositionCreateDevice(
dxgi,
__uuidof(IDCompositionDevice),
reinterpret_cast<void**>(&dcomp));
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
hr = dcomp->CreateTargetForHwnd(hWindow, TRUE, &dcomptarget);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
hr = dcomp->CreateVisual(&rootvisual);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
hr = dcomptarget->SetRoot(rootvisual);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
hr = dxgi->GetAdapter(&adapter);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
// COM is a bit confusing here - CreateDXGIFactory2 simply adds a flags
// parameter, the 2 in the name is only the API version of CreateDXGIFactory
// and entirely unrelated to which DXGIFactory version we are requesting
hr = CreateDXGIFactory2(0u, __uuidof(IDXGIFactory7), reinterpret_cast<void**>(&factory));
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
d3d->GetImmediateContext(&context);
status = Compositor_Status::Running;
}
void Compositor::UpdateSwapChain(IDXGISwapChain1* swapchain, DXGI_COLOR_SPACE_TYPE _type, DXGI_FORMAT _format, u8 _bytesPerPixel, void* data)
{
DXGI_SWAP_CHAIN_DESC1 scDesc = {};
swapchain->GetDesc1(&scDesc);
ID3D11Resource* buffer = nullptr;
ID3D11RenderTargetView* view = nullptr;
ID3D11Texture2D* tex = nullptr;
D3D11_TEXTURE2D_DESC tDesc;
tDesc.Width = scDesc.Width;
tDesc.Height = scDesc.Height;
tDesc.MipLevels = 1;
tDesc.ArraySize = 1;
tDesc.Format = _format;
// tDesc uses UINT, so let's check for overflow first.
u64 tPitch = tDesc.Width * _bytesPerPixel;
u64 tSlicePitch = tPitch * tDesc.Height;
if (tPitch > UINT_MAX || tSlicePitch > UINT_MAX)
{
assert(false);
return;
}
tDesc.SampleDesc.Count = 1;
tDesc.SampleDesc.Quality = 0;
tDesc.Usage = D3D11_USAGE_DEFAULT;
tDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
tDesc.CPUAccessFlags = 0;
tDesc.MiscFlags = 0;
HRESULT hr;
hr = swapchain->GetBuffer(0, IID_PPV_ARGS(&buffer));
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr) && buffer)
{
#if !USE_RENDERTARGETVIEW
// Just copy pixels into the backbuffer
D3D11_BOX texBox;
texBox.left = 0;
texBox.right = scDesc.Width;
texBox.top = 0;
texBox.bottom = scDesc.Height;
texBox.front = 0;
texBox.back = 1;
context->UpdateSubresource(buffer, 0, &texBox, data, static_cast<UINT>(tPitch), static_cast<UINT>(tSlicePitch));
#else
// Create a texture to hold the pixels, and set up a shader to
// copy that into the backbuffer
hr = d3d->CreateRenderTargetView(buffer, NULL, &view);
if (SUCCEEDED(hr) && view)
{
f32 debugColor[] = { 1.0f, 0.0f, 0.0f, 0.5f };
context->ClearRenderTargetView(view, debugColor);
D3D11_SUBRESOURCE_DATA tInitData;
tInitData.SysMemPitch = static_cast<UINT>(tPitch);
tInitData.SysMemSlicePitch = static_cast<UINT>(tSlicePitch);
tInitData.pSysMem = tPixels;
hr = d3d->CreateTexture2D(&tDesc, &tInitData, &tex);
if (SUCCEEDED(hr) && tex)
{
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = tDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
ID3D11ShaderResourceView* srv = nullptr;
hr = d3d->CreateShaderResourceView(tex, &srvDesc, &srv);
if (SUCCEEDED(hr) && srv)
{
// TODO
}
}
}
#endif
}
if (tex)
tex->Release();
if (view)
view->Release();
if (buffer)
buffer->Release();
// Flip the backbuffer to front
#if USE_ALLOW_TEARING
hr = swapchain->Present1(0, DXGI_PRESENT_ALLOW_TEARING, nullptr);
#else
hr = swapchain->Present(0, 0);
#endif
assert(SUCCEEDED(hr));
}
void Compositor::MakeWindowSwapChain(DXGI_COLOR_SPACE_TYPE _type, DXGI_FORMAT _format) {
if (!windowswapchain1) {
DXGI_SWAP_CHAIN_DESC1 scDesc = {};
scDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
scDesc.BufferCount = 2;
scDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_BACK_BUFFER | DXGI_USAGE_SHADER_INPUT;
scDesc.Flags = 0;
scDesc.Format = _format;
scDesc.SampleDesc.Count = 1;
scDesc.Scaling = DXGI_SCALING_STRETCH;
scDesc.Stereo = FALSE;
scDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
HRESULT hr = factory->CreateSwapChainForHwnd(
d3d,
hWindow,
&scDesc,
nullptr,
nullptr,
&windowswapchain1
);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
// Convert the IDXGISwapChain1 to IDXGISwapChain3 because we need a few
// more features to do HDR stuff, such as specifying colorspace for
// HDR10 (scRGB doesn't need the hint because the scDesc.Format being
// R16F16B16A16_FLOAT tells dcomp it is scRGB in that case)
hr = windowswapchain1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&windowswapchain3));
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
windowswapchain3->SetColorSpace1(_type);
}
}
void Compositor_Layer::VisualWithSwapChain(Compositor* comp, f32 _x, f32 _y, u32 _width, u32 _height, DXGI_COLOR_SPACE_TYPE _type, DXGI_FORMAT _format, u8 _bytesPerPixel, void* data)
{
x = _x;
y = _y;
width = _width;
height = _height;
dxgiColorspace = _type;
dxgiFormat = _format;
isSurface = false;
isWindow = false;
if (!dcompvisual) {
HRESULT hr = comp->dcomp->CreateVisual(&dcompvisual);
assert(SUCCEEDED(hr));
if (FAILED(hr))
return;
}
dcompvisual->SetOffsetX(x);
dcompvisual->SetOffsetY(y);
if (!swapchain1) {
DXGI_SWAP_CHAIN_DESC1 scDesc = {};
scDesc.Format = dxgiFormat;
scDesc.SampleDesc.Count = 1;
scDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
scDesc.BufferCount = 2;
scDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
scDesc.AlphaMode = DXGI_ALPHA_MODE_IGNORE;
scDesc.Width = static_cast<u32>(width);
scDesc.Height = static_cast<u32>(height);
scDesc.Stereo = FALSE;
scDesc.Scaling = DXGI_SCALING_STRETCH;
// DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT requires Windows
// 8.1 or later, and gives us access to the
// GetFrameLatencyWaitableObject method so we can use
// WaitForSingleObjectEx to wait for the frame to be shown on the
// display, rather than queuing D3D commands to a limit.
//
// DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING is required for support of
// variable refresh rate displays, and requires Windows 10 1511, we
// could check if this is supported but a Windows 10 version from 2016
// is well past EOL so this code doesn't bother checking.
// https://learn.microsoft.com/en-us/windows/win32/direct3ddxgi/variable-refresh-rate-displays
HRESULT hr;
if (_format == DXGI_FORMAT_P010) {
HANDLE handle = INVALID_HANDLE_VALUE;
hr = DCompositionCreateSurfaceHandle(COMPOSITIONOBJECT_ALL_ACCESS, nullptr, &handle);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
IDXGIFactoryMedia* mediaFactory = nullptr;
comp->adapter->GetParent(IID_PPV_ARGS(&mediaFactory));
scDesc.Flags = DXGI_SWAP_CHAIN_FLAG_YUV_VIDEO | DXGI_SWAP_CHAIN_FLAG_FULLSCREEN_VIDEO;
hr = mediaFactory->CreateSwapChainForCompositionSurfaceHandle(comp->d3d, handle, &scDesc, nullptr, &swapchain1);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
SafeRelease(&mediaFactory);
}
else {
scDesc.Flags = 0;
hr = comp->factory->CreateSwapChainForComposition(comp->d3d, &scDesc, NULL, &swapchain1);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
}
// Convert the IDXGISwapChain1 to IDXGISwapChain3 because we need a few
// more features to do HDR stuff, such as specifying colorspace for
// HDR10 (scRGB doesn't need the hint because the scDesc.Format being
// R16F16B16A16_FLOAT tells dcomp it is scRGB in that case)
hr = swapchain1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&swapchain3));
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
swapchain3->SetColorSpace1(dxgiColorspace);
dcompvisual->SetContent(swapchain3);
}
// Render a new frame in the swapchain and present it
if (swapchain1 && width >= 1 && height >= 1) {
comp->UpdateSwapChain(swapchain1, _type, _format, _bytesPerPixel, data);
}
// Add the layer visual to the root visual tree
HRESULT hr = comp->rootvisual->AddVisual(dcompvisual, TRUE, nullptr);
assert(SUCCEEDED(hr));
// We don't actually need to hold on to any of these objects because the
// visual being linked into the tree will keep them alive by itself
if (dcompvisual) {
dcompvisual->Release();
dcompvisual = nullptr;
}
if (swapchain3) {
swapchain3->Release();
swapchain3 = nullptr;
}
if (swapchain1) {
swapchain1->Release();
swapchain1 = nullptr;
}
}
void Compositor_Layer::VisualWithSurface(Compositor* comp, f32 _x, f32 _y, u32 _width, u32 _height, DXGI_COLOR_SPACE_TYPE _type, DXGI_FORMAT _format, u8 _bytesPerPixel, void* data)
{
// Doesn't work. No way to call SetColorSpace1, so probably never will.
return;
x = _x;
y = _y;
width = _width;
height = _height;
dxgiColorspace = _type;
dxgiFormat = _format;
isSurface = true;
isWindow = false;
if (!dcompvisual) {
HRESULT hr = comp->dcomp->CreateVisual(&dcompvisual);
assert(SUCCEEDED(hr));
if (FAILED(hr))
return;
}
dcompvisual->SetOffsetX(x);
dcompvisual->SetOffsetY(y);
HRESULT hr;
hr = comp->dcomp->CreateSurface(_width, _height, _format, DXGI_ALPHA_MODE_IGNORE, &dcompsurface);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
IDXGISurface *surface;
POINT updateOffset;
hr = dcompsurface->BeginDraw(nullptr, __uuidof(IDXGISurface), reinterpret_cast<void**>(&surface), &updateOffset);
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
DXGI_MAPPED_RECT mapped;
hr = surface->Map(&mapped, DXGI_MAP_WRITE | DXGI_MAP_DISCARD);
assert(SUCCEEDED(hr));
if (SUCCEEDED(hr)) {
// Copy pixels into the surface, respecting the pitch of the surface we
// were provided, which may be wider than our requested width*bpp.
size_t bytesPerRow = _width * _bytesPerPixel;
u8* output = mapped.pBits;
size_t outputPitch = mapped.Pitch;
const u8* input = (const u8 *)data;
size_t inputPitch = bytesPerRow;
size_t rows = _height;
// Planar 4:2:0 has full height luma and half height chroma, width of
// chroma plane is also half but that cancels out when you consider it
// is two channels in that plane
if (_format == DXGI_FORMAT_P010) {
rows += rows / 2;
}
for (u32 y = 0; y < rows; y++) {
memcpy(output + y * outputPitch, input + y * inputPitch, bytesPerRow);
}
hr = surface->Unmap();
assert(SUCCEEDED(hr));
}
hr = dcompsurface->EndDraw();
assert(SUCCEEDED(hr));
if (FAILED(hr)) {
return;
}
// Add the layer visual to the root visual tree
hr = comp->rootvisual->AddVisual(dcompvisual, TRUE, nullptr);
assert(SUCCEEDED(hr));
if (dcompvisual) {
dcompvisual->Release();
dcompvisual = nullptr;
}
}
void Compositor::Update(HWND hWnd, bool reset)
{
// Get the current DPI of the display the window is on
f32 newscale = 1.0f;
HDC hdc = GetDC(hWnd);
if (hdc)
{
newscale = GetDeviceCaps(hdc, LOGPIXELSX) / 96.0f;
newscale = newscale < 1.0f / 1024.0f ? 1.0f / 1024.0f : newscale < 1024.0f ? newscale : 1024.0f;
ReleaseDC(hWnd, hdc);
}
// TODO: Get SDRWhiteLevel from DisplayConfigGetDeviceInfo...
if (fabs(scale - newscale) > 0.01f) {
reset = true;
}
scale = newscale;
if (hWindow != hWnd) {
reset = true;
}
if (status != Compositor_Status::Running) {
reset = true;
}
// If an error is encountered, we reinitialize the device and try again, but
// only once, if the device is lost repeatedly we're not going to make
// progress, so two attempts is probably optimal
for (i32 tries = 2; tries >= 0; tries--)
{
UpdateStatus();
if (status != Compositor_Status::Running || reset) {
reset = false;
DestroyDevice();
CreateDevice(hWnd);
CreateScene();
// Commit transaction so it displays the new layers
dcomp->Commit();
}
}
}
Compositor::~Compositor()
{
DestroyDevice();
}
// These test colors represent an scRGB color wheel with deliberately wide gamut
// colors (which often require negative values for other components) and HDR
// intensity (2.0 = 160 nits scene referred)
const f32 testcolors[4][7] = {
// Red
{ 2.00f, 2.00f, -0.20f, -0.20f, -0.20f, 2.00f, 2.00f},
// Green
{ -0.20f, 2.00f, 2.00f, 2.00f, -0.20f, -0.20f, -0.20f},
// Blue
{ -0.20f, -0.20f, -0.20f, 2.00f, 2.00f, 2.00f, -0.20f},
// Alpha
{ 1.00f, 1.00f, 1.00f, 1.00f, 1.00f, 1.00f, 1.00f}
};
void PixelCallback_TestColors_scRGB(float output[], f32 x, f32 y, f32 width, f32 height)
{
constexpr u32 limit = sizeof(testcolors[0]) / sizeof(testcolors[0][0]);
constexpr u32 limit1 = limit - 1;
constexpr u32 limit2 = limit - 2;
f32 f = (x / (width - 1.0f)) * limit1;
f = f < 0.0f ? 0.0f : f < (float)limit1 ? f : (float)limit1;
u32 i = (int)floor(f);
i = i < 0 ? 0 : i < limit2 ? i : limit2;
f32 lerp = (f - i) < 1.0f ? (f - i) : 1.0f;
f32 ilerp = 1.0f - lerp;
for (u32 c = 0; c < 4; c++)
output[c] = testcolors[c][i] * ilerp + testcolors[c][i + 1] * lerp;
}
static void Pixel_To_Int(f32 c[], f32 scale, f32 low, f32 high)
{
for (u32 i = 0; i < 4; i++)
{
f32 f = c[i];
f *= scale;
f = floorf(f + 0.5f);
f = f < low ? low : f < high ? f : high;
c[i] = f;
}
}
/// This converts an f32 to an f16 using bit manipulation (which achieves round
/// toward zero behavior, which may not be the active floating point mode).
/// See https://en.wikipedia.org/wiki/Half-precision_floating-point_format and
/// compare to https://en.wikipedia.org/wiki/Single-precision_floating-point_format
static u16 ToF16(f32 f)
{
// Some notes:
// f32 is 1 sign bit, 8 exponent bits, 23 mantissa bits
// f16 is 1 sign bit, 5 exponent bits, 10 mantissa bits
// 1.0 as f32 is 0x3f800000 (exp=127 of 0-255)
// s0 e01111111 m00000000000000000000000
// 1.0 as f16 is 0x7800 (exp=15 of 0-31)
// s0 e...01111 m0000000000.............
// if we shift the exponents to align the same, 127-15=112, f16 exp is f32
// exp - 112, since the sign bit precedes it we need to mask that off before
// adjusting, the mantissa directly follows the exponent so we can shift
// both by the same amount to align with the f16 format, and subtract 112
// from the exponent and we get f16 from f32 with bit math alone.
//
// e112 = s0 e011100000 m... = 0x38000000
// e113 = s0 e011100001 m... = 0x38800000
//
// We also have to handle the fact that e103 to 112 become denormals, but
// it is easier to simply treat <=e112 as zero, a lot of float
// implementations either ignore denormals or process them very slowly so
// turning them into zero is a reasonable behavior here.
union
{
f32 f;
u32 i;
}
u;
u.f = f;
u32 i = u.i;
// Adjust exponent from +127 bias to +15 bias, if it would become less than
// exponent 1 we treat it as a full zero (rather than try to deal with
// denormals, which typically have a performance penalty anyway)
u32 a = ((i & 0x7FFFFFFF) < 0x38800000) ? 0 : i - 0x38000000;
// Shift exponent and mantissa to the correct place (same shift for both)
// and put the sign bit into place
u16 n = (a >> 13) | ((a & 0x80000000) >> 16);
return n;
}
u16 *GenerateImage_RGBA16F_scRGB(u16 width, u16 height)
{
u16* pixels = new u16[4 * width * height];
for (u16 y = 0; y < height; y++)
{
for (u16 x = 0; x < width; x++)
{
auto p = (u16*)pixels + 4 * (y * width + x);
f32 c[4];
PixelCallback_TestColors_scRGB(c, x, y, width, height);
for (u16 i = 0; i < 4; i++)
p[i] = (u16)ToF16(c[i]);
}
}
return pixels;
}
constexpr f32 scrgb_to_xyzd65[3][3] = {
{ 0.4123908f, 0.3575843f, 0.1804808f},
{ 0.2126390f, 0.7151687f, 0.0721923f},
{ 0.0193308f, 0.1191948f, 0.9505322f} };
constexpr f32 xyzd65_to_rec2020[3][3] = {
{ 1.7166512f, -0.3556708f, -0.2533663f},
{-0.6666844f, 1.6164812f, 0.0157685f},
{ 0.0176399f, -0.0427706f, 0.9421031f} };
constexpr f32 rec709_to_ycbcr[3][3] = {
{ 0.2126f, 0.7152f, 0.0722f},
{-0.1146f, -0.3854f, 0.5000f},
{ 0.5000f, -0.4542f, -0.0458f} };
constexpr f32 rec2020_to_ycbcr[3][3] = {
{ 0.2627f, 0.6780f, 0.0593f},
{-0.1396f, -0.3604f, 0.5000f},
{ 0.5000f, -0.4598f, -0.0402f} };
void Color_rgb_through_mat3(const f32 c[], f32 o[], const f32 mat[3][3]) {
o[0] = c[0] * mat[0][0] + c[1] * mat[0][1] + c[2] * mat[0][2];
o[1] = c[0] * mat[1][0] + c[1] * mat[1][1] + c[2] * mat[1][2];
o[2] = c[0] * mat[2][0] + c[1] * mat[2][1] + c[2] * mat[2][2];
}
void Color_scRGB_To_Rec2020(f32 c[3], f32 o[3])
{
f32 xyz[3];
Color_rgb_through_mat3(c, xyz, scrgb_to_xyzd65);
Color_rgb_through_mat3(xyz, o, xyzd65_to_rec2020);
}
void Color_Transfer_To_PQ(const f32 c[3], f32 o[3])
{
constexpr auto m1 = 2610.0f / 16384.0f;
constexpr auto m2 = 128.0f * 2523.0f / 4096.0f;
constexpr auto c1 = 3424.0f / 4096.0f;
constexpr auto c2 = 32.0f * 2413.0f / 4096.0f;
constexpr auto c3 = 32.0f * 2392.0f / 4096.0f;
for (u32 i = 0; i < 3; i++)
{
f32 y = c[i] * 80.0f / 10000.0f;
y = y < 0.0f ? 0.0f : y;
f32 j = powf(y, m1);
f32 f = powf((c1 + c2 * j) / (1 + c3 * j), m2);
o[i] = f < 0.0f ? 0.0f : f < 1.0f ? f : 1.0f;
}
o[3] = c[3];
}
// Generates an HDR10 image - converts scRGB gradient to Rec2100 (Rec2020 HDR),
// uses PQ transfer function and encodes as RGB10A2.
u32 *GenerateImage_RGB10A2_HDR10(u16 width, u16 height)
{
u32* pixels = new u32[width * height];
for (u16 y = 0; y < height; y++)
{
for (u16 x = 0; x < width; x++)
{
auto p = (u32*)pixels + y * width + x;
f32 scrgb[4];
PixelCallback_TestColors_scRGB(scrgb, x, y, width, height);
f32 rec2020[3];
Color_scRGB_To_Rec2020(scrgb, rec2020);
f32 t[4];
Color_Transfer_To_PQ(rec2020, t);
t[3] = scrgb[3];
Pixel_To_Int(t, 1023.0f, 0.0f, 1023.0f);
*p =
(u32)t[0] * 0x1 +
(u32)t[1] * 0x400 +
(u32)t[2] * 0x100000 +
((u32)t[3] >> 8) * 0xC0000000;
}
}
return pixels;
}
void Color_Transfer_To_sRGB(f32 c[], f32 o[])
{
// sRGB piecewise gamma
for (u32 i = 0; i < 3; i++)
{
f32 f = c[i];
f = f < 0.0f ? 0.0f : f < 1.0f ? f : 1.0f;
o[i] = f < 0.0031308f ? f * 12.92f : 1.055f * powf(f, 0.41666f) - 0.055f;
}
o[3] = c[3];
}
u32 *GenerateImage_BGRA8_sRGB(u16 width, u16 height)
{
u32* pixels = new u32[width * height];
// 8bit sRGB or rec709 (Windows doesn't distinguish between them)
for (u16 y = 0; y < height; y++)
{
for (u16 x = 0; x < width; x++)
{
auto p = pixels + y * width + x;
f32 c[4];
PixelCallback_TestColors_scRGB(c, x, y, width, height);
Color_Transfer_To_sRGB(c, c);
Pixel_To_Int(c, 255.0f, 0.0f, 255.0f);
*p =
(u32)c[2] * 0x1 +
(u32)c[1] * 0x100 +
(u32)c[0] * 0x10000 +
(u32)c[3] * 0x1000000;
}
}
return pixels;
}
/*
void Color_FullRGB_To_YCbCr(const f32 rgb[3], f32 ycbcr[3], f32 a, f32 b, f32 c, u8 full)
{
f32 m1 = 0.0f;
f32 m2 = 1.0f;
f32 s1 = full ? 0.0f : (16.0f / 256.0f);
f32 s2 = full ? 1.0f : (240.0f / 256.0f);
f32 s = s2 - s1;
f32 R = (rgb[0] < m1 ? m1 : rgb[0] < m2 ? rgb[0] : m2);
f32 G = (rgb[1] < m1 ? m1 : rgb[1] < m2 ? rgb[1] : m2);
f32 B = (rgb[2] < m1 ? m1 : rgb[2] < m2 ? rgb[2] : m2);
f32 Y = a * R + b * G + c * B;
f32 Cb = (B - Y) * (0.5f / (1 - c)) * s + 0.5f;
f32 Cr = (R - Y) * (0.5f / (1 - a)) * s + 0.5f;
f32 sY = Y * s + s1;
ycbcr[0] = sY < s1 ? s1 : sY < s2 ? sY : s2;
ycbcr[1] = Cb < s1 ? s1 : Cb < s2 ? Cb : s2;
ycbcr[2] = Cr < s1 ? s1 : Cr < s2 ? Cr : s2;
}
*/
// Generates an HDR10 image in P010 pixel format, this format consists of
// two planes, the first is full resolution Y channel and the second is half
// width and half height and consists of alternating U and V for the top left
// pixel in each 2x2 group.
u16 *GenerateImage_P010(u16 w, u16 h, f32 a, f32 b, f32 c, u8 full, u8 tf, u8 cs)
{
u16* planes = new u16[w * h + w * h / 2];
for (u16 y = 0; y < h; y++)
{
for (u16 x = 0; x < w; x++)
{
f32 scrgb[4];
PixelCallback_TestColors_scRGB(scrgb, x, y, w, h);
f32 csrgb[4];
f32 rgb[3];
f32 ycbcr[4];
switch (cs) {
default:
case 0:
for (u16 i = 0; i < 3; i++) {
csrgb[i] = scrgb[i] < 0.0f ? 0.0f : scrgb[i] < 1.0f ? scrgb[i] : 1.0f;
}
switch (tf) {
default:
case 0:
Color_Transfer_To_sRGB(csrgb, rgb);
break;
case 1:
Color_Transfer_To_PQ(csrgb, rgb);
break;
}
Color_rgb_through_mat3(rgb, ycbcr, rec709_to_ycbcr);
break;
case 1:
Color_scRGB_To_Rec2020(scrgb, csrgb);
switch (tf) {
default:
case 0:
Color_Transfer_To_sRGB(csrgb, rgb);
break;
case 1:
Color_Transfer_To_PQ(csrgb, rgb);
break;
}
Color_rgb_through_mat3(rgb, ycbcr, rec2020_to_ycbcr);
break;
}
if (!full) {
ycbcr[0] = ycbcr[0] * (219.0f / 256.0f) + (16.0f / 256.0f);
ycbcr[1] = ycbcr[1] * (224.0f / 256.0f);
ycbcr[2] = ycbcr[2] * (224.0f / 256.0f);
}
ycbcr[1] += 0.5f;
ycbcr[2] += 0.5f;
ycbcr[3] = scrgb[3];
// Now map it to u16
Pixel_To_Int(ycbcr, 65535.0f, 0.0f, 65535.0f);
// Store the luminance of every pixel
planes[y * w + x] = (u16)ycbcr[0];
// Store the chroma of only the top left pixel
if ((x & 1) == 0 && (y & 1) == 0)
{
planes[w * (h + y / 2) + x] = (u16)ycbcr[1];
planes[w * (h + y / 2) + x + 1] = (u16)ycbcr[2];
}
}
}
return planes;
}
void Compositor::CreateScene()
{
layers.clear();
layers.reserve(16);
#if WINDOW_BACKGROUND
MakeWindowSwapChain(DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, DXGI_FORMAT_R16G16B16A16_FLOAT);
// Get the window swapchain size
DXGI_SWAP_CHAIN_DESC1 scDesc = {};
windowswapchain1->GetDesc1(&scDesc);
u32 windowWidth = static_cast<u16>(scDesc.Width);
u32 windowHeight = static_cast<u16>(scDesc.Height);
windowWidth = windowWidth < 1 ? 1 : windowWidth < 16384 ? windowWidth : 32;
windowHeight = windowHeight < 1 ? 1 : windowHeight < 16384 ? windowHeight : 32;
auto pixelsWindow = new u16[4 * windowWidth * windowHeight];
GenerateImage_RGBA16F_scRGB(pixelsWindow, windowWidth, windowHeight);
UpdateSwapChain(windowswapchain1, DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, DXGI_FORMAT_R16G16B16A16_FLOAT, 8, (void*)pixelsWindow);
#endif
// Always even width and height for sake of 4:2:0 video formats
u32 w2 = (u32)(512.0f * scale) / 2;
u32 h2 = (u32)(48.0f * scale) / 2;
u32 w = w2 * 2;
u32 h = h2 * 2;
w = w < 2 ? 2 : w < 16384 ? w : 16384;
h = h < 2 ? 2 : h < 16384 ? h : 16384;
f32 fw = (f32)w;
f32 fh = (f32)h;
f32 grid_w = fw + 4 * scale;
f32 grid_h = fh;
f32 x = 32 * scale;
f32 y = 32 * scale;
// Add some gradients as visuals using swapchains in various formats
{
layers.push_back(Compositor_Layer());
auto p = GenerateImage_RGBA16F_scRGB(w, h);
layers[layers.size() - 1].VisualWithSwapChain(this, x, y, w, h, DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, DXGI_FORMAT_R16G16B16A16_FLOAT, 8, (void*)p);
delete p;
y += grid_h;
}
{
layers.push_back(Compositor_Layer());
auto p = GenerateImage_RGB10A2_HDR10(w, h);
layers[layers.size() - 1].VisualWithSwapChain(this, x, y, w, h, DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020, DXGI_FORMAT_R10G10B10A2_UNORM, 4, (void*)p);
delete p;
y += grid_h;
}
{
layers.push_back(Compositor_Layer());
auto p = GenerateImage_BGRA8_sRGB(w, h);
layers[layers.size() - 1].VisualWithSwapChain(this, x, y, w, h, DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709, DXGI_FORMAT_B8G8R8A8_UNORM, 4, (void*)p);
delete p;
y += grid_h;
}
{
layers.push_back(Compositor_Layer());
auto p = GenerateImage_P010(w, h, 0.2126f, 0.7152f, 0.0722f, 1, 0, 0);
layers[layers.size() - 1].VisualWithSwapChain(this, x, y, w, h, DXGI_COLOR_SPACE_YCBCR_FULL_G22_LEFT_P709, DXGI_FORMAT_P010, 2, (void*)p);
delete p;
y += grid_h;
}
{
layers.push_back(Compositor_Layer());
auto p = GenerateImage_P010(w, h, 0.2627f, 0.6780f, 0.0593f, 0, 0, 1);
layers[layers.size() - 1].VisualWithSwapChain(this, x, y, w, h, DXGI_COLOR_SPACE_YCBCR_STUDIO_G22_TOPLEFT_P2020, DXGI_FORMAT_P010, 2, (void*)p);
delete p;
y += grid_h;
}
{
layers.push_back(Compositor_Layer());
auto p = GenerateImage_P010(w, h, 0.2627f, 0.6780f, 0.0593f, 0, 1, 1);