This repository was archived by the owner on Sep 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathprocessing.cpp
More file actions
1231 lines (1014 loc) · 43.4 KB
/
processing.cpp
File metadata and controls
1231 lines (1014 loc) · 43.4 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
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2016-2019, Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
#include <DirectXTex.h>
#include <ScreenGrab.h>
#include <strsafe.h>
#include <limits>
#include "processing.h"
#include "StopWatch.h" // Timer.
#include <cmath>
CompressionFunc* gCompressionFunc = nullptr;
bool gMultithreaded = true;
double gCompTime = 0.0;
double gCompRate = 0.0;
int gTexWidth = 0;
int gTexHeight = 0;
double gError = 0.0;
double gError2 = 0.0;
ID3D11ShaderResourceView* gUncompressedSRV = NULL;
ID3D11ShaderResourceView* gCompressedSRV = NULL;
ID3D11ShaderResourceView* gErrorSRV = NULL;
ID3D11InputLayout* gVertexLayout = NULL;
ID3D11Buffer* gQuadVB = NULL;
ID3D11Buffer* gConstantBuffer = NULL;
ID3D11VertexShader* gVertexShader = NULL;
ID3D11PixelShader* gRenderErrorTexturePS = NULL;
ID3D11PixelShader* gRenderCompressedTexturePS = NULL;
ID3D11SamplerState* gSamPoint = NULL;
ID3D11DepthStencilState* gDepthStencilState = NULL;
UINT gStencilReference = 0;
// Win32 thread API
const int kMaxWinThreads = 64;
enum EThreadState {
eThreadState_WaitForData,
eThreadState_DataLoaded,
eThreadState_Running,
eThreadState_Done
};
struct WinThreadData {
EThreadState state;
int threadIdx;
//int width;
//int height;
//void (*cmpFunc)(const BYTE* inBuf, BYTE* outBuf, int width, int height);
CompressionFunc* cmpFunc;
rgba_surface input;
BYTE *output;
// Defaults..
WinThreadData() :
state(eThreadState_Done),
threadIdx(-1),
input(),
output(NULL),
cmpFunc(NULL)
{ }
} gWinThreadData[kMaxWinThreads];
HANDLE gWinThreadWorkEvent[kMaxWinThreads];
HANDLE gWinThreadStartEvent = NULL;
HANDLE gWinThreadDoneEvent = NULL;
int gNumWinThreads = 0;
DWORD gNumProcessors = 1; // We have at least one processor.
DWORD dwThreadIdArray[kMaxWinThreads];
HANDLE hThreadArray[kMaxWinThreads];
void Initialize()
{
// Make sure that the event array is set to null...
memset(gWinThreadWorkEvent, 0, sizeof(gWinThreadWorkEvent));
// Figure out how many cores there are on this machine
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
gNumProcessors = sysinfo.dwNumberOfProcessors;
// Make sure all of our threads are empty.
for(int i = 0; i < kMaxWinThreads; i++) {
hThreadArray[i] = NULL;
}
}
// Free previously allocated texture resources and create new texture resources.
HRESULT CreateTextures(LPTSTR file)
{
// Destroy any previously created textures.
DestroyTextures();
// Load the uncompressed texture.
HRESULT hr;
V_RETURN(LoadTexture(file));
// Compress the texture.
V_RETURN(CompressTexture(gUncompressedSRV, &gCompressedSRV));
// Compute the error in the compressed texture.
V_RETURN(ComputeError(gUncompressedSRV, gCompressedSRV, &gErrorSRV));
return S_OK;
}
// Recompresses the already loaded texture and recomputes the error.
HRESULT RecompressTexture()
{
// Destroy any previously created textures.
SAFE_RELEASE(gErrorSRV);
SAFE_RELEASE(gCompressedSRV);
// Compress the texture.
HRESULT hr;
V_RETURN(CompressTexture(gUncompressedSRV, &gCompressedSRV));
// Compute the error in the compressed texture.
V_RETURN(ComputeError(gUncompressedSRV, gCompressedSRV, &gErrorSRV));
return S_OK;
}
// Destroy texture resources.
void DestroyTextures()
{
SAFE_RELEASE(gErrorSRV);
SAFE_RELEASE(gCompressedSRV);
SAFE_RELEASE(gUncompressedSRV);
}
// This functions loads a texture and prepares it for compression. The compressor only works on texture
// dimensions that are divisible by 4. Textures that are not divisible by 4 are resized and padded with the edge values.
HRESULT LoadTexture(LPTSTR file)
{
// Load the uncompressed texture.
HRESULT hr;
DirectX::ScratchImage image;
V_RETURN(DirectX::LoadFromDDSFile(file, DirectX::DDS_FLAGS_FORCE_RGB, nullptr, image));
V_RETURN(DirectX::CreateShaderResourceViewEx(DXUTGetD3D11Device(), image.GetImages(), image.GetImageCount(), image.GetMetadata(), D3D11_USAGE_DEFAULT, D3D11_BIND_SHADER_RESOURCE, 0, 0, true, &gUncompressedSRV));
// Pad the texture.
V_RETURN(PadTexture(&gUncompressedSRV));
// Query the texture description.
ID3D11Texture2D* tex;
gUncompressedSRV->GetResource((ID3D11Resource**)&tex);
D3D11_TEXTURE2D_DESC texDesc;
tex->GetDesc(&texDesc);
SAFE_RELEASE(tex);
gTexWidth = texDesc.Width;
gTexHeight = texDesc.Height;
return S_OK;
}
// Pad the texture to dimensions that are divisible by 4.
HRESULT PadTexture(ID3D11ShaderResourceView** textureSRV)
{
// Query the texture description.
ID3D11Texture2D* tex;
(*textureSRV)->GetResource((ID3D11Resource**)&tex);
D3D11_TEXTURE2D_DESC texDesc;
tex->GetDesc(&texDesc);
// Exit if the texture dimensions are divisible by 4.
if((texDesc.Width % 4 == 0) && (texDesc.Height % 4 == 0))
{
SAFE_RELEASE(tex);
return S_OK;
}
// Compute the size of the padded texture.
UINT padWidth = texDesc.Width / 4 * 4 + 4;
UINT padHeight = texDesc.Height / 4 * 4 + 4;
// Create a buffer for the padded texels.
BYTE* padTexels = new BYTE[padWidth * padHeight * 4];
// Create a staging resource for the texture.
HRESULT hr;
ID3D11Device* device = DXUTGetD3D11Device();
D3D11_TEXTURE2D_DESC stgTexDesc;
memcpy(&stgTexDesc, &texDesc, sizeof(D3D11_TEXTURE2D_DESC));
stgTexDesc.Usage = D3D11_USAGE_STAGING;
stgTexDesc.BindFlags = 0;
stgTexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
ID3D11Texture2D* stgTex;
V_RETURN(device->CreateTexture2D(&stgTexDesc, NULL, &stgTex));
// Copy the texture into the staging resource.
ID3D11DeviceContext* deviceContext = DXUTGetD3D11DeviceContext();
deviceContext->CopyResource(stgTex, tex);
// Map the staging resource.
D3D11_MAPPED_SUBRESOURCE texData;
V_RETURN(deviceContext->Map(stgTex, D3D11CalcSubresource(0, 0, 1), D3D11_MAP_READ_WRITE, 0, &texData));
// Copy the beginning of each row.
BYTE* texels = (BYTE*)texData.pData;
for(UINT row = 0; row < stgTexDesc.Height; row++)
{
UINT rowStart = row * texData.RowPitch;
UINT padRowStart = row * padWidth * 4;
memcpy(padTexels + padRowStart, texels + rowStart, stgTexDesc.Width * 4);
// Pad the end of each row.
if(padWidth > stgTexDesc.Width)
{
BYTE* padVal = texels + rowStart + (stgTexDesc.Width - 1) * 4;
for(UINT padCol = stgTexDesc.Width; padCol < padWidth; padCol++)
{
UINT padColStart = padCol * 4;
memcpy(padTexels + padRowStart + padColStart, padVal, 4);
}
}
}
// Pad the end of each column.
if(padHeight > stgTexDesc.Height)
{
UINT lastRow = (stgTexDesc.Height - 1);
UINT lastRowStart = lastRow * padWidth * 4;
BYTE* padVal = padTexels + lastRowStart;
for(UINT padRow = stgTexDesc.Height; padRow < padHeight; padRow++)
{
UINT padRowStart = padRow * padWidth * 4;
memcpy(padTexels + padRowStart, padVal, padWidth * 4);
}
}
// Unmap the staging resources.
deviceContext->Unmap(stgTex, D3D11CalcSubresource(0, 0, 1));
// Create a padded texture.
D3D11_TEXTURE2D_DESC padTexDesc;
memcpy(&padTexDesc, &texDesc, sizeof(D3D11_TEXTURE2D_DESC));
padTexDesc.Width = padWidth;
padTexDesc.Height = padHeight;
D3D11_SUBRESOURCE_DATA padTexData;
ZeroMemory(&padTexData, sizeof(D3D11_SUBRESOURCE_DATA));
padTexData.pSysMem = padTexels;
padTexData.SysMemPitch = padWidth * sizeof(BYTE) * 4;
ID3D11Texture2D* padTex;
V_RETURN(device->CreateTexture2D(&padTexDesc, &padTexData, &padTex));
// Delete the padded texel buffer.
delete [] padTexels;
// Release the shader resource view for the texture.
SAFE_RELEASE(*textureSRV);
// Create a shader resource view for the padded texture.
D3D11_SHADER_RESOURCE_VIEW_DESC padTexSRVDesc;
padTexSRVDesc.Format = padTexDesc.Format;
padTexSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
padTexSRVDesc.Texture2D.MipLevels = padTexDesc.MipLevels;
padTexSRVDesc.Texture2D.MostDetailedMip = 0;
V_RETURN(device->CreateShaderResourceView(padTex, &padTexSRVDesc, textureSRV));
// Release resources.
SAFE_RELEASE(padTex);
SAFE_RELEASE(stgTex);
SAFE_RELEASE(tex);
return S_OK;
}
// Save a texture to a file.
HRESULT SaveTexture(ID3D11ShaderResourceView* textureSRV, LPTSTR file)
{
// Get the texture resource.
ID3D11Resource* texRes;
textureSRV->GetResource(&texRes);
if(texRes == NULL)
{
return E_POINTER;
}
// Save the texture to a file.
HRESULT hr;
V_RETURN(DirectX::SaveDDSTextureToFile(DXUTGetD3D11DeviceContext(), texRes, file));
// Release the texture resources.
SAFE_RELEASE(texRes);
return S_OK;
}
// Compress a texture.
HRESULT CompressTexture(ID3D11ShaderResourceView* uncompressedSRV, ID3D11ShaderResourceView** compressedSRV)
{
// Query the texture description of the uncompressed texture.
ID3D11Resource* uncompRes;
gUncompressedSRV->GetResource(&uncompRes);
D3D11_TEXTURE2D_DESC uncompTexDesc;
((ID3D11Texture2D*)uncompRes)->GetDesc(&uncompTexDesc);
// Create a 2D texture for the compressed texture.
HRESULT hr;
ID3D11Texture2D* compTex;
D3D11_TEXTURE2D_DESC compTexDesc;
memcpy(&compTexDesc, &uncompTexDesc, sizeof(D3D11_TEXTURE2D_DESC));
compTexDesc.Format = GetFormatFromCompressionFunc(gCompressionFunc);
ID3D11Device* device = DXUTGetD3D11Device();
V_RETURN(device->CreateTexture2D(&compTexDesc, NULL, &compTex));
// Create a shader resource view for the compressed texture.
SAFE_RELEASE(*compressedSRV);
D3D11_SHADER_RESOURCE_VIEW_DESC compSRVDesc;
compSRVDesc.Format = compTexDesc.Format;
compSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
compSRVDesc.Texture2D.MipLevels = compTexDesc.MipLevels;
compSRVDesc.Texture2D.MostDetailedMip = 0;
V_RETURN(device->CreateShaderResourceView(compTex, &compSRVDesc, compressedSRV));
// Create a staging resource for the compressed texture.
compTexDesc.Usage = D3D11_USAGE_STAGING;
compTexDesc.BindFlags = 0;
compTexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
ID3D11Texture2D* compStgTex;
V_RETURN(device->CreateTexture2D(&compTexDesc, NULL, &compStgTex));
// Create a staging resource for the uncompressed texture.
uncompTexDesc.Usage = D3D11_USAGE_STAGING;
uncompTexDesc.BindFlags = 0;
uncompTexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
ID3D11Texture2D* uncompStgTex;
V_RETURN(device->CreateTexture2D(&uncompTexDesc, NULL, &uncompStgTex));
// Copy the uncompressed texture into the staging resource.
ID3D11DeviceContext* deviceContext = DXUTGetD3D11DeviceContext();
deviceContext->CopyResource(uncompStgTex, uncompRes);
// Map the staging resources.
D3D11_MAPPED_SUBRESOURCE uncompData;
V_RETURN(deviceContext->Map(uncompStgTex, D3D11CalcSubresource(0, 0, 1), D3D11_MAP_READ_WRITE, 0, &uncompData));
D3D11_MAPPED_SUBRESOURCE compData;
V_RETURN(deviceContext->Map(compStgTex, D3D11CalcSubresource(0, 0, 1), D3D11_MAP_READ_WRITE, 0, &compData));
const bool isBC4 = IsBC4(gCompressionFunc);
const bool isBC5 = IsBC5(gCompressionFunc);
std::vector<BYTE> bc4bc5bytes;
if(isBC4)
{
bc4bc5bytes.resize(uncompTexDesc.Width * uncompTexDesc.Height);
for(UINT y = 0, offset = 0; y < uncompTexDesc.Height; ++y)
{
for(UINT x = 0; x < uncompTexDesc.Width; ++x, ++offset)
{
// copy R over
bc4bc5bytes[offset] = reinterpret_cast<BYTE*>(uncompData.pData)[(x * 4) + (y * uncompData.RowPitch) + 0];
}
}
}
else if(isBC5)
{
bc4bc5bytes.resize(uncompTexDesc.Width * uncompTexDesc.Height * 2);
for(UINT y = 0, offset = 0; y < uncompTexDesc.Height; ++y)
{
for(UINT x = 0; x < uncompTexDesc.Width; ++x, offset += 2)
{
// copy R and G over
bc4bc5bytes[offset + 0] = reinterpret_cast<BYTE*>(uncompData.pData)[(x * 4) + (y * uncompData.RowPitch) + 0];
bc4bc5bytes[offset + 1] = reinterpret_cast<BYTE*>(uncompData.pData)[(x * 4) + (y * uncompData.RowPitch) + 1];
}
}
}
// Time the compression.
StopWatch stopWatch;
stopWatch.Start();
const int kNumCompressions = 1;
for(int cmpNum = 0; cmpNum < kNumCompressions; cmpNum++)
{
rgba_surface input;
input.ptr = (isBC4 || isBC5) ? bc4bc5bytes.data() : (BYTE*)uncompData.pData;
input.stride = isBC4 ? uncompTexDesc.Width : (isBC5 ? (uncompTexDesc.Width * 2) : uncompData.RowPitch);
input.width = uncompTexDesc.Width;
input.height = uncompTexDesc.Height;
BYTE* output = (BYTE*)compData.pData;
// Compress the uncompressed texels.
CompressImage(&input, output);
// remap for DX (expanding inplace, bottom-up)
int output_stride = (input.width/4)*GetBytesPerBlock(gCompressionFunc);
for (int y=input.height/4-1; y>=0; y--)
{
memmove(output+y*compData.RowPitch, output+y*output_stride, output_stride);
}
}
// Update the compression time.
stopWatch.Stop();
gCompTime = stopWatch.TimeInMilliseconds();
// Compute the compression rate.
INT numPixels = compTexDesc.Width * compTexDesc.Height * kNumCompressions;
gCompRate = (double)numPixels / stopWatch.TimeInSeconds() / 1000000.0;
stopWatch.Reset();
// Unmap the staging resources.
deviceContext->Unmap(compStgTex, D3D11CalcSubresource(0, 0, 1));
deviceContext->Unmap(uncompStgTex, D3D11CalcSubresource(0, 0, 1));
// Copy the staging resourse into the compressed texture.
deviceContext->CopyResource(compTex, compStgTex);
// Release resources.
SAFE_RELEASE(uncompStgTex);
SAFE_RELEASE(compStgTex);
SAFE_RELEASE(compTex);
SAFE_RELEASE(uncompRes);
return S_OK;
}
static inline DXGI_FORMAT GetNonSRGBFormat(DXGI_FORMAT f) {
switch(f) {
case DXGI_FORMAT_BC1_UNORM_SRGB: return DXGI_FORMAT_BC1_UNORM;
case DXGI_FORMAT_BC3_UNORM_SRGB: return DXGI_FORMAT_BC3_UNORM;
case DXGI_FORMAT_BC4_UNORM: return DXGI_FORMAT_BC4_UNORM;
case DXGI_FORMAT_BC5_UNORM: return DXGI_FORMAT_BC5_UNORM;
case DXGI_FORMAT_BC4_SNORM: return DXGI_FORMAT_BC4_SNORM;
case DXGI_FORMAT_BC5_SNORM: return DXGI_FORMAT_BC5_SNORM;
case DXGI_FORMAT_BC7_UNORM_SRGB: return DXGI_FORMAT_BC7_UNORM;
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return DXGI_FORMAT_R8G8B8A8_UNORM;
default: assert(!"Unknown format!");
}
return DXGI_FORMAT_R8G8B8A8_UNORM;
}
void SetIdentity(DirectX::XMFLOAT4X4* mView)
{
ZeroMemory(mView, sizeof(DirectX::XMFLOAT4X4));
mView->m[0][0] = 1;
mView->m[1][1] = 1;
mView->m[2][2] = 1;
mView->m[3][3] = 1;
}
// Compute an "error" texture that represents the absolute difference in color between an
// uncompressed texture and a compressed texture.
HRESULT ComputeError(ID3D11ShaderResourceView* uncompressedSRV, ID3D11ShaderResourceView* compressedSRV, ID3D11ShaderResourceView** errorSRV)
{
HRESULT hr;
ID3D11Device* device = DXUTGetD3D11Device();
// Query the texture description of the uncompressed texture.
ID3D11Resource* uncompRes;
gUncompressedSRV->GetResource(&uncompRes);
D3D11_TEXTURE2D_DESC uncompTexDesc;
((ID3D11Texture2D*)uncompRes)->GetDesc(&uncompTexDesc);
// Query the texture description of the compressed texture.
ID3D11Resource* compRes;
gCompressedSRV->GetResource(&compRes);
D3D11_TEXTURE2D_DESC compTexDesc;
((ID3D11Texture2D*)compRes)->GetDesc(&compTexDesc);
// Create a 2D resource without gamma correction for the two textures.
if (IsBC6H(gCompressionFunc))
{
compTexDesc.Format = DXGI_FORMAT_BC6H_UF16;
uncompTexDesc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;
}
else
{
compTexDesc.Format = GetNonSRGBFormat(compTexDesc.Format);
uncompTexDesc.Format = GetNonSRGBFormat(uncompTexDesc.Format);
}
ID3D11Texture2D* uncompTex;
device->CreateTexture2D(&uncompTexDesc, NULL, &uncompTex);
ID3D11Texture2D* compTex;
device->CreateTexture2D(&compTexDesc, NULL, &compTex);
// Create a shader resource view for the two textures.
D3D11_SHADER_RESOURCE_VIEW_DESC compSRVDesc;
compSRVDesc.Format = compTexDesc.Format;
compSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
compSRVDesc.Texture2D.MipLevels = compTexDesc.MipLevels;
compSRVDesc.Texture2D.MostDetailedMip = 0;
ID3D11ShaderResourceView *compSRV;
V_RETURN(device->CreateShaderResourceView(compTex, &compSRVDesc, &compSRV));
D3D11_SHADER_RESOURCE_VIEW_DESC uncompSRVDesc;
uncompSRVDesc.Format = uncompTexDesc.Format;
uncompSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
uncompSRVDesc.Texture2D.MipLevels = uncompTexDesc.MipLevels;
uncompSRVDesc.Texture2D.MostDetailedMip = uncompTexDesc.MipLevels - 1;
ID3D11ShaderResourceView *uncompSRV;
V_RETURN(device->CreateShaderResourceView(uncompTex, &uncompSRVDesc, &uncompSRV));
// Create a 2D texture for the error texture.
ID3D11Texture2D* errorTex;
D3D11_TEXTURE2D_DESC errorTexDesc;
memcpy(&errorTexDesc, &uncompTexDesc, sizeof(D3D11_TEXTURE2D_DESC));
errorTexDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
V_RETURN(device->CreateTexture2D(&errorTexDesc, NULL, &errorTex));
// Create a render target view for the error texture.
D3D11_RENDER_TARGET_VIEW_DESC errorRTVDesc;
errorRTVDesc.Format = errorTexDesc.Format;
errorRTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
errorRTVDesc.Texture2D.MipSlice = 0;
ID3D11RenderTargetView* errorRTV;
V_RETURN(device->CreateRenderTargetView(errorTex, &errorRTVDesc, &errorRTV));
// Create a shader resource view for the error texture.
D3D11_SHADER_RESOURCE_VIEW_DESC errorSRVDesc;
errorSRVDesc.Format = errorTexDesc.Format;
errorSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
errorSRVDesc.Texture2D.MipLevels = errorTexDesc.MipLevels;
errorSRVDesc.Texture2D.MostDetailedMip = errorTexDesc.MipLevels - 1;
V_RETURN(device->CreateShaderResourceView(errorTex, &errorSRVDesc, errorSRV));
// Create a query for the GPU operations...
D3D11_QUERY_DESC GPUQueryDesc;
GPUQueryDesc.Query = D3D11_QUERY_EVENT;
GPUQueryDesc.MiscFlags = 0;
#ifdef _DEBUG
D3D11_QUERY_DESC OcclusionQueryDesc;
OcclusionQueryDesc.Query = D3D11_QUERY_OCCLUSION;
OcclusionQueryDesc.MiscFlags = 0;
D3D11_QUERY_DESC StatsQueryDesc;
StatsQueryDesc.Query = D3D11_QUERY_PIPELINE_STATISTICS;
StatsQueryDesc.MiscFlags = 0;
#endif
ID3D11Query *GPUQuery;
V_RETURN(device->CreateQuery(&GPUQueryDesc, &GPUQuery));
ID3D11DeviceContext* deviceContext = DXUTGetD3D11DeviceContext();
deviceContext->CopyResource(compTex, compRes);
deviceContext->CopyResource(uncompTex, uncompRes);
#ifdef _DEBUG
ID3D11Query *OcclusionQuery, *StatsQuery;
V_RETURN(device->CreateQuery(&OcclusionQueryDesc, &OcclusionQuery));
V_RETURN(device->CreateQuery(&StatsQueryDesc, &StatsQuery));
deviceContext->Begin(OcclusionQuery);
deviceContext->Begin(StatsQuery);
#endif
// Set the viewport to a 1:1 mapping of pixels to texels.
D3D11_VIEWPORT viewport;
viewport.Width = (FLOAT)errorTexDesc.Width;
viewport.Height = (FLOAT)errorTexDesc.Height;
viewport.MinDepth = 0;
viewport.MaxDepth = 1;
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
deviceContext->RSSetViewports(1, &viewport);
// Bind the render target view of the error texture.
ID3D11RenderTargetView* RTV[1] = { errorRTV };
deviceContext->OMSetRenderTargets(1, RTV, NULL);
// Clear the render target.
FLOAT color[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
deviceContext->ClearRenderTargetView(errorRTV, color);
// Set the input layout.
deviceContext->IASetInputLayout(gVertexLayout);
// Set vertex buffer
UINT stride = sizeof(Vertex);
UINT offset = 0;
deviceContext->IASetVertexBuffers(0, 1, &gQuadVB, &stride, &offset);
// Set the primitive topology
deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// Update the Constant Buffer
D3D11_MAPPED_SUBRESOURCE MappedResource;
deviceContext->Map( gConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource );
VS_CONSTANT_BUFFER* pConstData = ( VS_CONSTANT_BUFFER* )MappedResource.pData;
ZeroMemory(pConstData, sizeof(VS_CONSTANT_BUFFER));
SetIdentity(&pConstData->mView);
deviceContext->Unmap( gConstantBuffer, 0 );
// Set the shaders
ID3D11Buffer* pBuffers[1] = { gConstantBuffer };
deviceContext->VSSetConstantBuffers( 0, 1, pBuffers );
deviceContext->VSSetShader(gVertexShader, NULL, 0);
if (IsBC6H(gCompressionFunc))
{
deviceContext->PSSetShader(gRenderCompressedTexturePS, NULL, 0);
}
else
{
deviceContext->PSSetShader(gRenderErrorTexturePS, NULL, 0);
}
// Set the texture sampler.
deviceContext->PSSetSamplers(0, 1, &gSamPoint);
// Bind the textures.
ID3D11ShaderResourceView* SRV[2] = { compSRV, uncompSRV};
deviceContext->PSSetShaderResources(0, 2, SRV);
// Store the depth/stencil state.
StoreDepthStencilState();
// Disable depth testing.
V_RETURN(DisableDepthTest());
// Render a quad.
deviceContext->Draw(6, 0);
// Restore the depth/stencil state.
RestoreDepthStencilState();
// Reset the render target.
RTV[0] = DXUTGetD3D11RenderTargetView();
deviceContext->OMSetRenderTargets(1, RTV, DXUTGetD3D11DepthStencilView());
// Reset the viewport.
viewport.Width = (FLOAT)DXUTGetDXGIBackBufferSurfaceDesc()->Width;
viewport.Height = (FLOAT)DXUTGetDXGIBackBufferSurfaceDesc()->Height;
deviceContext->RSSetViewports(1, &viewport);
deviceContext->End(GPUQuery);
#ifdef _DEBUG
deviceContext->End(OcclusionQuery);
deviceContext->End(StatsQuery);
#endif
BOOL finishedGPU = false;
// If we do not have a d3d 11 context, we will still hit this line and try to
// finish using the GPU. If this happens this enters an infinite loop.
int infLoopPrevention = 0;
while(!finishedGPU && ++infLoopPrevention < 10000) {
HRESULT ret;
V_RETURN(ret = deviceContext->GetData(GPUQuery, &finishedGPU, sizeof(BOOL), 0));
if(ret != S_OK)
Sleep(1);
}
#ifdef _DEBUG
UINT64 nPixelsWritten = 0;
deviceContext->GetData(OcclusionQuery, (void *)&nPixelsWritten, sizeof(UINT64), 0);
D3D11_QUERY_DATA_PIPELINE_STATISTICS stats;
deviceContext->GetData(StatsQuery, (void *)&stats, sizeof(D3D11_QUERY_DATA_PIPELINE_STATISTICS), 0);
TCHAR nPixelsWrittenMsg[256];
_stprintf_s(nPixelsWrittenMsg, _T("Pixels rendered during error computation: %llu\n"), nPixelsWritten);
OutputDebugString(nPixelsWrittenMsg);
#endif
// Create a copy of the error texture that is accessible by the CPU
ID3D11Texture2D* errorTexCopy;
D3D11_TEXTURE2D_DESC errorTexCopyDesc;
memcpy(&errorTexCopyDesc, &uncompTexDesc, sizeof(D3D11_TEXTURE2D_DESC));
errorTexCopyDesc.Usage = D3D11_USAGE_STAGING;
errorTexCopyDesc.BindFlags = 0;
errorTexCopyDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
V_RETURN(device->CreateTexture2D(&errorTexCopyDesc, NULL, &errorTexCopy));
// Copy the error texture into the copy....
deviceContext->CopyResource(errorTexCopy, errorTex);
// Calculate PSNR
if (!IsBC6H(gCompressionFunc))
{
D3D11_MAPPED_SUBRESOURCE errorData;
V_RETURN(deviceContext->Map(errorTexCopy, D3D11CalcSubresource(0, 0, 1), D3D11_MAP_READ, 0, &errorData));
ComputeRMSE((const BYTE *)(errorData.pData), errorTexCopyDesc.Width, errorTexCopyDesc.Height);
deviceContext->Unmap(errorTexCopy, D3D11CalcSubresource(0, 0, 1));
}
else
{
// Create a staging resource for the uncompressed texture.
//uncompTexDesc.Format = DXGI_FORMAT_R16G16B16A16_FLOAT;
uncompTexDesc.Usage = D3D11_USAGE_STAGING;
uncompTexDesc.BindFlags = 0;
uncompTexDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
ID3D11Texture2D* uncompStgTex;
V_RETURN(device->CreateTexture2D(&uncompTexDesc, NULL, &uncompStgTex));
// Copy the uncompressed texture into the staging resource.
ID3D11DeviceContext* deviceContext = DXUTGetD3D11DeviceContext();
deviceContext->CopyResource(uncompStgTex, uncompRes);
// Map the staging resources.
D3D11_MAPPED_SUBRESOURCE uncompData;
V_RETURN(deviceContext->Map(uncompStgTex, D3D11CalcSubresource(0, 0, 1), D3D11_MAP_READ, 0, &uncompData));
// Map the staging resource.
D3D11_MAPPED_SUBRESOURCE rawData;
V_RETURN(deviceContext->Map(errorTexCopy, D3D11CalcSubresource(0, 0, 1), D3D11_MAP_READ, 0, &rawData));
//V_RETURN(deviceContext->Map(rawTexCopy, D3D11CalcSubresource(0, 0, 1), D3D11_MAP_READ, 0, &rawData));
rgba_surface input;
input.ptr = (BYTE*)uncompData.pData;
input.stride = uncompData.RowPitch;
input.width = uncompTexDesc.Width;
input.height = uncompTexDesc.Height;
rgba_surface raw;
raw.ptr = (BYTE*)rawData.pData;
raw.stride = rawData.RowPitch;
raw.width = uncompTexDesc.Width;
raw.height = uncompTexDesc.Height;
ComputeErrorMetrics(&input, &raw);
deviceContext->Unmap(uncompStgTex, D3D11CalcSubresource(0, 0, 1));
deviceContext->Unmap(errorTexCopy, D3D11CalcSubresource(0, 0, 1));
SAFE_RELEASE(uncompStgTex);
//SAFE_RELEASE(rawTexCopy);
}
// Release resources.
SAFE_RELEASE(errorRTV);
SAFE_RELEASE(errorTex);
SAFE_RELEASE(errorTexCopy);
SAFE_RELEASE(uncompRes);
SAFE_RELEASE(compRes);
SAFE_RELEASE(GPUQuery);
#ifdef _DEBUG
SAFE_RELEASE(OcclusionQuery);
SAFE_RELEASE(StatsQuery);
#endif
SAFE_RELEASE(compSRV);
SAFE_RELEASE(uncompSRV);
SAFE_RELEASE(compTex);
SAFE_RELEASE(uncompTex);
return S_OK;
}
// Store the depth-stencil state.
void StoreDepthStencilState()
{
DXUTGetD3D11DeviceContext()->OMGetDepthStencilState(&gDepthStencilState, &gStencilReference);
}
// Restore the depth-stencil state.
void RestoreDepthStencilState()
{
DXUTGetD3D11DeviceContext()->OMSetDepthStencilState(gDepthStencilState, gStencilReference);
}
// Disable depth testing.
HRESULT DisableDepthTest()
{
D3D11_DEPTH_STENCIL_DESC depStenDesc;
ZeroMemory(&depStenDesc, sizeof(D3D11_DEPTH_STENCIL_DESC));
depStenDesc.DepthEnable = FALSE;
depStenDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depStenDesc.DepthFunc = D3D11_COMPARISON_LESS;
depStenDesc.StencilEnable = FALSE;
depStenDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;
depStenDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;
depStenDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depStenDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
depStenDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depStenDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
depStenDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depStenDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;
depStenDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depStenDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
ID3D11DepthStencilState* depStenState;
HRESULT hr;
V_RETURN(DXUTGetD3D11Device()->CreateDepthStencilState(&depStenDesc, &depStenState));
DXUTGetD3D11DeviceContext()->OMSetDepthStencilState(depStenState, 0);
SAFE_RELEASE(depStenState);
return S_OK;
}
inline float half2float(uint16_t value)
{
float out;
int abs = value & 0x7FFF;
if (abs > 0x7C00)
out = std::numeric_limits<float>::quiet_NaN();
else if (abs == 0x7C00)
out = std::numeric_limits<float>::infinity();
else if (abs > 0x3FF)
out = std::ldexp(static_cast<float>((value & 0x3FF) | 0x400), (abs >> 10) - 15 - 10);
else
out = std::ldexp(static_cast<float>(abs), -24);
return (value & 0x8000) ? -out : out;
}
void ComputeRMSE(const BYTE *errorData, const INT width, const INT height)
{
double sum_sq_rgb = 0.0;
double sum_sq_alpha = 0.0;
for(int i = 0; i < width; i++) {
for(int j = 0; j < height; j++) {
const INT pixel = ((const INT *)errorData)[j * width + i];
double dr = double(pixel & 0xFF);
double dg = double((pixel >> 8) & 0xFF);
double db = double((pixel >> 16) & 0xFF);
double da = double((pixel >> 24) & 0xFF);
sum_sq_rgb += dr*dr+dg*dg+db*db;
sum_sq_alpha += da*da;
}
}
sum_sq_rgb /= (double(width) * double(height));
sum_sq_alpha /= (double(width) * double(height));
gError = 10 * log10((255.0 * 255.0*3)/(sum_sq_rgb));
gError2 = 10 * log10((255.0 * 255.0*4)/(sum_sq_rgb+sum_sq_alpha));
}
void ComputeErrorMetrics(rgba_surface* input, rgba_surface* raw)
{
float metric = 0.0f;
for (int y = 0; y < input->height; y++)
for (int x = 0; x < input->width; x++)
{
uint16_t* rgb_a_fp16 = (uint16_t*)&input->ptr[input->stride*y + x * 8];
uint16_t* rgb_b_fp16 = (uint16_t*)&raw->ptr[raw->stride*y + x * 8];
float rgb_a[3], rgb_b[3];
for (int p = 0; p < 3; p++)
{
rgb_a[p] = half2float(max(1, rgb_a_fp16[p]));
rgb_b[p] = half2float(max(1, rgb_b_fp16[p]));
}
for (int p = 0; p < 3; p++)
{
float Ta = logf(rgb_a[p]) / logf(2);
float Tb = logf(rgb_b[p]) / logf(2);
metric += fabs(Ta - Tb);
}
}
int samples = input->height*input->width * 3;
gError = 100 * (metric / samples);
gError2 = 0;
}
#define CHECK_WIN_THREAD_FUNC(x) \
do { \
if(NULL == (x)) { \
wchar_t wstr[256]; \
swprintf_s(wstr, L"Error detected from call %s at line %d of main.cpp", _T(#x), __LINE__); \
ReportWinThreadError(wstr); \
} \
} \
while(0)
void ReportWinThreadError(const wchar_t *str) {
// Retrieve the system error message for the last-error code.
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
// Display the error message.
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR) lpMsgBuf) + lstrlen((LPCTSTR)str) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s failed with error %d: %s"),
str, dw, lpMsgBuf);
MessageBox(NULL, (LPCTSTR) lpDisplayBuf, TEXT("Error"), MB_OK);
// Free error-handling buffer allocations.
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
void InitWin32Threads() {
// Already initialized?
if(gNumWinThreads > 0) {
return;
}
SetLastError(0);
gNumWinThreads = gNumProcessors;
if(gNumWinThreads >= MAXIMUM_WAIT_OBJECTS)
gNumWinThreads = MAXIMUM_WAIT_OBJECTS;
assert(gNumWinThreads <= kMaxWinThreads);
// Create the synchronization events.
for(int i = 0; i < gNumWinThreads; i++) {
CHECK_WIN_THREAD_FUNC(gWinThreadWorkEvent[i] = CreateEvent(NULL, FALSE, FALSE, NULL));
}
CHECK_WIN_THREAD_FUNC(gWinThreadStartEvent = CreateEvent(NULL, TRUE, FALSE, NULL));
CHECK_WIN_THREAD_FUNC(gWinThreadDoneEvent = CreateEvent(NULL, TRUE, FALSE, NULL));
// Create threads
for(int threadIdx = 0; threadIdx < gNumWinThreads; threadIdx++) {
gWinThreadData[threadIdx].state = eThreadState_WaitForData;
CHECK_WIN_THREAD_FUNC(hThreadArray[threadIdx] = CreateThread(NULL, 0, CompressImageMT_Thread, &gWinThreadData[threadIdx], 0, &dwThreadIdArray[threadIdx]));
}
}
void DestroyThreads()
{
if(gMultithreaded)
{
// Release all windows threads that may be active...
for(int i=0; i < gNumWinThreads; i++) {
gWinThreadData[i].state = eThreadState_Done;
}
// Send the event for the threads to start.
CHECK_WIN_THREAD_FUNC(ResetEvent(gWinThreadDoneEvent));
CHECK_WIN_THREAD_FUNC(SetEvent(gWinThreadStartEvent));
// Wait for all the threads to finish....
DWORD dwWaitRet = WaitForMultipleObjects(gNumWinThreads, hThreadArray, TRUE, INFINITE);
if(WAIT_FAILED == dwWaitRet)
ReportWinThreadError(L"DestroyThreads() -- WaitForMultipleObjects");
// !HACK! This doesn't actually do anything. There is either a bug in the
// Intel compiler or the windows run-time that causes the threads to not
// be cleaned up properly if the following two lines of code are not present.
// Since we're passing INFINITE to WaitForMultipleObjects, that function will
// never time out and per-microsoft spec, should never give this return value...
// Even with these lines, the bug does not consistently disappear unless you
// clean and rebuild. Heigenbug?
//
// If we compile with MSVC, then the following two lines are not necessary.
else if(WAIT_TIMEOUT == dwWaitRet)
OutputDebugString(L"DestroyThreads() -- WaitForMultipleObjects -- TIMEOUT");
// Reset the start event
CHECK_WIN_THREAD_FUNC(ResetEvent(gWinThreadStartEvent));
CHECK_WIN_THREAD_FUNC(SetEvent(gWinThreadDoneEvent));
// Close all thread handles.
for(int i=0; i < gNumWinThreads; i++) {
CHECK_WIN_THREAD_FUNC(CloseHandle(hThreadArray[i]));
}