-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathNtcMaterialLoader.cpp
More file actions
1450 lines (1213 loc) · 67.5 KB
/
NtcMaterialLoader.cpp
File metadata and controls
1450 lines (1213 loc) · 67.5 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
/*
* SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: LicenseRef-NvidiaProprietary
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "NtcMaterialLoader.h"
#include "NtcMaterial.h"
#include "NtcChannelMapping.h"
#include <ntc-utils/BufferLoading.h>
#include <ntc-utils/GraphicsDecompressionPass.h>
#include <ntc-utils/GraphicsBlockCompressionPass.h>
#include <ntc-utils/DeviceUtils.h>
#include <donut/core/log.h>
#include <donut/core/string_utils.h>
#include <donut/core/vfs/VFS.h>
#include <donut/engine/Scene.h>
#include <sstream>
#include <fstream>
using namespace donut;
namespace fs = std::filesystem;
// Matches the number of textures in donut::engine::Material
static const uint32_t g_maxTileStagingTextures = 6;
// Skip this many largest latent mips when loading texture sets.
// Set to nonzero for testing purposes.
static const int g_firstLatentMipInTexture = 0;
bool NtcMaterialLoader::Init(bool enableCoopVec, bool enableGpuDeflate, bool debug, nvrhi::ITexture* dummyTexture)
{
ntc::ContextParameters contextParams;
contextParams.cudaDevice = ntc::DisableCudaDevice;
contextParams.graphicsApi = m_device->getGraphicsAPI() == nvrhi::GraphicsAPI::D3D12
? ntc::GraphicsAPI::D3D12
: ntc::GraphicsAPI::Vulkan;
bool const osSupportsCoopVec = (contextParams.graphicsApi == ntc::GraphicsAPI::D3D12)
? IsDX12DeveloperModeEnabled()
: true;
contextParams.d3d12Device = m_device->getNativeObject(nvrhi::ObjectTypes::D3D12_Device);
contextParams.vkInstance = m_device->getNativeObject(nvrhi::ObjectTypes::VK_Instance);
contextParams.vkPhysicalDevice = m_device->getNativeObject(nvrhi::ObjectTypes::VK_PhysicalDevice);
contextParams.vkDevice = m_device->getNativeObject(nvrhi::ObjectTypes::VK_Device);
contextParams.enableCooperativeVector = osSupportsCoopVec && enableCoopVec;
ntc::Status ntcStatus = ntc::CreateContext(m_ntcContext.ptr(), contextParams);
if (ntcStatus != ntc::Status::Ok && ntcStatus != ntc::Status::CudaUnavailable)
{
log::error("Failed to create an NTC context, code = %s: ",
ntc::StatusToString(ntcStatus), ntc::GetLastErrorMessage());
return false;
}
m_coopVec = m_ntcContext->IsCooperativeVectorSupported();
if (enableGpuDeflate)
{
m_gdeflateFeatures = InitGDeflate(m_device, debug);
}
m_dummyTexture = std::make_shared<engine::LoadedTexture>();
m_dummyTexture->texture = dummyTexture;
m_graphicsDecompressionPass = std::make_shared<GraphicsDecompressionPass>(m_device,
/* descriptorTableSize = */ g_maxTileStagingTextures * 2 * TRANSCODE_BATCH_SIZE);
if (!m_graphicsDecompressionPass->Init())
return false;
m_graphicsBlockCompressionPass = std::make_shared<GraphicsBlockCompressionPass>(m_device,
/* maxConstantBufferVersions = */ 128);
if (!m_graphicsBlockCompressionPass->Init())
return false;
m_commandList = m_device->createCommandList(nvrhi::CommandListParameters().setEnableImmediateExecution(false));
// Create a buffer for uploading inference weights before their conversion to CoopVec format
nvrhi::BufferDesc uploadBufferDesc = nvrhi::BufferDesc()
.setByteSize(65536) // Should be enough for all weight types, validated in the upload code
.setDebugName("Weight upload buffer")
.setInitialState(nvrhi::ResourceStates::CopyDest)
.setKeepInitialState(true);
m_weightUploadBuffer = m_device->createBuffer(uploadBufferDesc);
// Create tile staging color textures
// All these textures are transient and could be aliased with other temp texture resources
const uint32_t maxTileWidth = 512;
const uint32_t maxTileHeight = 512;
nvrhi::TextureDesc colorTextureDesc = nvrhi::TextureDesc()
.setDimension(nvrhi::TextureDimension::Texture2D)
.setWidth(maxTileWidth)
.setHeight(maxTileHeight)
.setMipLevels(1)
.setDebugName("Tile color")
.setIsUAV(true)
.setIsTypeless(true)
.setInitialState(nvrhi::ResourceStates::ShaderResource)
.setKeepInitialState(true);
for (uint32_t i = 0; i < g_maxTileStagingTextures * TRANSCODE_BATCH_SIZE; i++)
{
colorTextureDesc.setFormat(nvrhi::Format::R8_UNORM);
colorTextureDesc.setDebugName("Tile Color R8 " + std::to_string(i));
nvrhi::TextureHandle tex = m_device->createTexture(colorTextureDesc);
if (!tex)
return false;
m_texTranscodeTiles.push_back(tex);
}
for (uint32_t i = 0; i < g_maxTileStagingTextures * TRANSCODE_BATCH_SIZE; i++)
{
colorTextureDesc.setFormat(nvrhi::Format::RGBA8_UNORM);
colorTextureDesc.setDebugName("Tile Color RGBA " + std::to_string(i));
nvrhi::TextureHandle tex = m_device->createTexture(colorTextureDesc);
if (!tex)
return false;
m_texTranscodeTiles.push_back(tex);
}
// Create tile staging block textures
nvrhi::TextureDesc blockTextureDesc = nvrhi::TextureDesc()
.setDimension(nvrhi::TextureDimension::Texture2D)
.setWidth(maxTileWidth / 4)
.setHeight(maxTileHeight / 4)
.setDebugName("Tile blocks")
.setIsUAV(true)
.setInitialState(nvrhi::ResourceStates::UnorderedAccess)
.setKeepInitialState(true);
for (uint32_t i = 0; i < g_maxTileStagingTextures * TRANSCODE_BATCH_SIZE; i++)
{
blockTextureDesc.setFormat(nvrhi::Format::RG32_UINT);
blockTextureDesc.setDebugName("Tile Blocks RG " + std::to_string(i));
nvrhi::TextureHandle tex = m_device->createTexture(blockTextureDesc);
if (!tex)
return false;
m_texTranscodeTiles.push_back(tex);
}
for (uint32_t i = 0; i < g_maxTileStagingTextures * TRANSCODE_BATCH_SIZE; i++)
{
blockTextureDesc.setFormat(nvrhi::Format::RGBA32_UINT);
blockTextureDesc.setDebugName("Tile Blocks RGBA " + std::to_string(i));
nvrhi::TextureHandle tex = m_device->createTexture(blockTextureDesc);
if (!tex)
return false;
m_texTranscodeTiles.push_back(tex);
}
m_texTileColorR8Offset = 0;
m_texTileColorRGBAOffset = 1 * g_maxTileStagingTextures * TRANSCODE_BATCH_SIZE;
m_texTileBlocksRGOffset = 2 * g_maxTileStagingTextures * TRANSCODE_BATCH_SIZE;
m_texTileBlocksRGBAOffset = 3 * g_maxTileStagingTextures * TRANSCODE_BATCH_SIZE;
return true;
}
static bool TextureSetHasChannels(uint32_t mask, int first, int count)
{
uint32_t test = ((1u << count) - 1) << first;
return (mask & test) == test;
}
static void FillMaterialTranscodeMapping(NtcMaterial& material, ntc::ITextureSetMetadata* textureSetMetadata,
MaterialChannelMap const& channelMap, bool onlyAlphaMask)
{
// Derive the valid channel mask from the shuffle map, because textureSetMetadata->GetValidChannelMask()
// returns "1" bits for constant channels, and we want to know where actual textures exist.
uint32_t channelMask = 0;
for (int ch = 0; ch < NTC_MAX_CHANNELS; ++ch)
{
if (channelMap.swizzle[ch].type == ntc::ShuffleSourceType::Channel)
channelMask |= (1 << ch);
}
// If we only need to create the alpha mask texture, see if the material actually needs an alpha mask
// and if the NTC texture set has an alpha mask channel.
if (onlyAlphaMask)
{
// Test the channel mask for the presence of opacity channel.
// Note: not testing the material domain because in some cases, one texture set can be reused
// for multiple materials with different domains, and we cache and reuse the transcode mapping.
// One model with such reuse is AlphaBlendModeTest from the Khronos glTF sample asset collection.
bool opacityChannelPresent = TextureSetHasChannels(channelMask, CHANNEL_OPACITY, 1);
if (!opacityChannelPresent)
return;
TextureTranscodeTask& opacityTexture = material.transcodeMapping.emplace_back();
opacityTexture.bcFormat = ntc::BlockCompressedFormat::BC4;
opacityTexture.nvrhiBcFormat = nvrhi::Format::BC4_UNORM;
opacityTexture.firstChannel = CHANNEL_OPACITY;
opacityTexture.numChannels = 1;
opacityTexture.pMaterialTexture = &NtcMaterial::opacityTexture;
opacityTexture.pFeedbackTexture = &NtcMaterial::opacityTextureFeedback;
opacityTexture.name = "Opacity";
}
else
{
if (TextureSetHasChannels(channelMask, CHANNEL_BASE_COLOR, 3))
{
TextureTranscodeTask& baseColorTexture = material.transcodeMapping.emplace_back();
baseColorTexture.bcFormat = ntc::BlockCompressedFormat::BC7;
baseColorTexture.nvrhiBcFormat = nvrhi::Format::BC7_UNORM_SRGB;
baseColorTexture.firstChannel = CHANNEL_BASE_COLOR;
baseColorTexture.numChannels = TextureSetHasChannels(channelMask, CHANNEL_OPACITY, 1) ? 4 : 3;
static_assert(CHANNEL_OPACITY == CHANNEL_BASE_COLOR + 3);
baseColorTexture.sRGB = true;
baseColorTexture.pMaterialTexture = &NtcMaterial::baseOrDiffuseTexture;
baseColorTexture.pFeedbackTexture = &NtcMaterial::baseOrDiffuseTextureFeedback;
baseColorTexture.name = "BaseColor";
}
if (material.useSpecularGlossModel)
{
if (TextureSetHasChannels(channelMask, CHANNEL_SPECULAR_COLOR, 3))
{
TextureTranscodeTask& specularTexture = material.transcodeMapping.emplace_back();
specularTexture.bcFormat = ntc::BlockCompressedFormat::BC7;
specularTexture.nvrhiBcFormat = nvrhi::Format::BC7_UNORM_SRGB;
specularTexture.firstChannel = CHANNEL_SPECULAR_COLOR;
specularTexture.numChannels = TextureSetHasChannels(channelMask, CHANNEL_GLOSSINESS, 1) ? 4 : 3;
static_assert(CHANNEL_GLOSSINESS == CHANNEL_SPECULAR_COLOR + 3);
specularTexture.sRGB = true;
specularTexture.pMaterialTexture = &NtcMaterial::metalRoughOrSpecularTexture;
specularTexture.pFeedbackTexture = &NtcMaterial::metalRoughOrSpecularTextureFeedback;
specularTexture.name = "SpecularColor";
}
}
else
{
if (TextureSetHasChannels(channelMask, CHANNEL_METALNESS, 2))
{
TextureTranscodeTask& metalRoughTexture = material.transcodeMapping.emplace_back();
metalRoughTexture.bcFormat = ntc::BlockCompressedFormat::BC5;
metalRoughTexture.nvrhiBcFormat = nvrhi::Format::BC5_UNORM;
metalRoughTexture.firstChannel = CHANNEL_METALNESS;
metalRoughTexture.numChannels = 2;
static_assert(CHANNEL_ROUGHNESS == CHANNEL_METALNESS + 1);
metalRoughTexture.pMaterialTexture = &NtcMaterial::metalRoughOrSpecularTexture;
metalRoughTexture.pFeedbackTexture = &NtcMaterial::metalRoughOrSpecularTextureFeedback;
metalRoughTexture.name = "MetallicRoughness";
}
if (TextureSetHasChannels(channelMask, CHANNEL_OCCLUSION, 1))
{
TextureTranscodeTask& occlusionTexture = material.transcodeMapping.emplace_back();
occlusionTexture.bcFormat = ntc::BlockCompressedFormat::BC4;
occlusionTexture.nvrhiBcFormat = nvrhi::Format::BC4_UNORM;
occlusionTexture.firstChannel = CHANNEL_OCCLUSION;
occlusionTexture.numChannels = 1;
occlusionTexture.pMaterialTexture = &NtcMaterial::occlusionTexture;
occlusionTexture.pFeedbackTexture = &NtcMaterial::occlusionTextureFeedback;
occlusionTexture.name = "Occlusion";
}
}
if (TextureSetHasChannels(channelMask, CHANNEL_NORMAL, 3))
{
TextureTranscodeTask& normalTexture = material.transcodeMapping.emplace_back();
normalTexture.bcFormat = ntc::BlockCompressedFormat::BC7;
normalTexture.nvrhiBcFormat = nvrhi::Format::BC7_UNORM;
normalTexture.firstChannel = CHANNEL_NORMAL;
normalTexture.numChannels = 3;
normalTexture.pMaterialTexture = &NtcMaterial::normalTexture;
normalTexture.pFeedbackTexture = &NtcMaterial::normalTextureFeedback;
normalTexture.name = "Normal";
}
if (TextureSetHasChannels(channelMask, CHANNEL_EMISSIVE, 3))
{
TextureTranscodeTask& emissiveTexture = material.transcodeMapping.emplace_back();
emissiveTexture.bcFormat = ntc::BlockCompressedFormat::BC7;
emissiveTexture.nvrhiBcFormat = nvrhi::Format::BC7_UNORM_SRGB;
emissiveTexture.firstChannel = CHANNEL_EMISSIVE;
emissiveTexture.numChannels = 3;
emissiveTexture.sRGB = true;
emissiveTexture.pMaterialTexture = &NtcMaterial::emissiveTexture;
emissiveTexture.pFeedbackTexture = &NtcMaterial::emissiveTextureFeedback;
emissiveTexture.name = "Emissive";
}
if (TextureSetHasChannels(channelMask, CHANNEL_TRANSMISSION, 1))
{
TextureTranscodeTask& transmissionTexture = material.transcodeMapping.emplace_back();
transmissionTexture.bcFormat = ntc::BlockCompressedFormat::BC4;
transmissionTexture.nvrhiBcFormat = nvrhi::Format::BC4_UNORM;
transmissionTexture.firstChannel = CHANNEL_TRANSMISSION;
transmissionTexture.numChannels = 1;
transmissionTexture.pMaterialTexture = &NtcMaterial::transmissionTexture;
transmissionTexture.pFeedbackTexture = &NtcMaterial::transmissionTextureFeedback;
transmissionTexture.name = "Transmission";
}
}
ntc::TextureSetDesc const& textureSetDesc = textureSetMetadata->GetDesc();
for (int textureIndex = 0; textureIndex < material.transcodeMapping.size(); ++textureIndex)
{
TextureTranscodeTask& textureVersions = material.transcodeMapping[textureIndex];
// Figure out which channels in the original NTC texture set correspond to the channels for this texture
std::array<int, 4> originalChannels;
originalChannels.fill(-1);
bool originalChannelsSequential = true;
for (int ch = 0; ch < textureVersions.numChannels; ++ch)
{
ntc::ShuffleSource const& src = channelMap.swizzle[textureVersions.firstChannel + ch];
originalChannels[ch] = src.GetChannelIndex();
if (ch > 0 && originalChannels[ch] != originalChannels[ch-1] + 1)
originalChannelsSequential = false;
}
// If this texture covers a contiguous span of channels in the NTC texture set, try to find a matching
// texture metadata object. It's only needed for BC7 encoding acceleration, so no big deal if it's not found.
if (originalChannelsSequential)
{
for (int ntcTextureIndex = 0; ntcTextureIndex < textureSetMetadata->GetTextureCount(); ++ntcTextureIndex)
{
ntc::ITextureMetadata* textureMetadata = textureSetMetadata->GetTexture(ntcTextureIndex);
if (textureMetadata->GetFirstChannel() == originalChannels[0] &&
textureMetadata->GetNumChannels() >= textureVersions.numChannels)
{
textureVersions.metadata = textureMetadata;
break;
}
}
}
}
}
static bool LoadMaterialFile(donut::engine::FilePathOrInlineData const& source, NtcMaterial& material,
ntc::IContext* ntcContext, ntc::FileStreamWrapper& ntcFile, ntc::MemoryStreamWrapper& ntcMemory,
ntc::TextureSetMetadataWrapper& textureSetMetadata)
{
if (material.name.empty())
material.name = "Material";
ntc::Status ntcStatus;
ntc::IStream* stream = nullptr;
if (source.data)
{
ntcStatus = ntcContext->OpenReadOnlyMemory(source.data->buffer->data(), source.data->buffer->size(),
ntcMemory.ptr());
if (ntcStatus != ntc::Status::Ok)
{
log::warning("Cannot open '%s', error code = %s: %s", source.ToString().c_str(),
ntc::StatusToString(ntcStatus), ntc::GetLastErrorMessage());
return false;
}
stream = ntcMemory.Get();
}
else
{
ntcStatus = ntcContext->OpenFile(source.path.c_str(), false, ntcFile.ptr());
if (ntcStatus == ntc::Status::FileUnavailable)
{
log::warning("Material file '%s' does not exist.", source.path.c_str());
return false;
}
else if (ntcStatus != ntc::Status::Ok)
{
log::warning("Cannot open '%s', error code = %s: %s", source.path.c_str(),
ntc::StatusToString(ntcStatus), ntc::GetLastErrorMessage());
return false;
}
stream = ntcFile.Get();
}
ntcStatus = ntcContext->CreateTextureSetMetadataFromStream(stream, textureSetMetadata.ptr());
if (ntcStatus != ntc::Status::Ok)
{
log::warning("Cannot load metadata for '%s', error code = %s: %s", source.ToString().c_str(),
ntc::StatusToString(ntcStatus), ntc::GetLastErrorMessage());
return false;
}
return true;
}
bool NtcMaterialLoader::TranscodeTiles(const std::vector<TranscodeTileInfo>& tiles, nvrhi::ICommandList* commandList,
bool enableBlockCompression)
{
if (tiles.empty())
return true;
assert(tiles.size() <= TRANSCODE_BATCH_SIZE);
// Indices for grabbing the next available texture from the staging textures
uint32_t texTileColorR8Index = m_texTileColorR8Offset;
uint32_t texTileColorRGBAIndex = m_texTileColorRGBAOffset;
uint32_t texTileBlocksRGIndex = m_texTileBlocksRGOffset;
uint32_t texTileBlocksRGBAIndex = m_texTileBlocksRGBAOffset;
// Write all descriptors for the color textures into the decompression pass descriptor table
for (int descriptorIndex = 0; descriptorIndex < m_texTileBlocksRGOffset; ++descriptorIndex)
{
nvrhi::BindingSetItem descriptor = nvrhi::BindingSetItem::Texture_UAV(
descriptorIndex,
m_texTranscodeTiles[descriptorIndex]);
m_graphicsDecompressionPass->WriteDescriptor(descriptor);
}
// Indices which map every tile/textureIndex into the list of temporary textures
std::vector<uint32_t> colorTextureIndices;
std::vector<uint32_t> blockTextureIndices;
std::array<bool, TRANSCODE_BATCH_SIZE> compressThisTexture;
commandList->beginMarker("Transcode Tiles: NTC Decompression");
// Phase 1 - Select the temporary tile textures from the pool and make state transitions
for (size_t tileIndex = 0; tileIndex < tiles.size(); ++tileIndex)
{
const TranscodeTileInfo& transcodeTile = tiles[tileIndex];
const NtcMaterial& material = *transcodeTile.material;
int textureCount = int(material.transcodeMapping.size());
assert(textureCount <= g_maxTileStagingTextures); // Maximum number of textures supported
// TODO: Does this this need to be handled without faulting?
assert(material.transcodeMapping.empty() == false);
for (int textureIndex = 0; textureIndex < textureCount; ++textureIndex)
{
const TextureTranscodeTask& transcodeTask = material.transcodeMapping[textureIndex];
bool const isSingleChannel = transcodeTask.numChannels == 1;
// Select the color texture
uint32_t colorTextureIndex = isSingleChannel ? texTileColorR8Index++ : texTileColorRGBAIndex++;
colorTextureIndices.push_back(colorTextureIndex);
compressThisTexture[tileIndex] = transcodeTask.bcFormat != ntc::BlockCompressedFormat::None
&& enableBlockCompression;
if (compressThisTexture[tileIndex])
{
// Select the block texture
bool const isSmallBlock =
(transcodeTask.bcFormat == ntc::BlockCompressedFormat::BC1) ||
(transcodeTask.bcFormat == ntc::BlockCompressedFormat::BC4);
uint32_t blockTextureIndex = isSmallBlock ? texTileBlocksRGIndex++ : texTileBlocksRGBAIndex++;
blockTextureIndices.push_back(blockTextureIndex);
// Disable automatic UAV barriers for the block texture
commandList->setEnableUavBarriersForTexture(m_texTranscodeTiles[blockTextureIndex], false);
}
// Transition to UAV
commandList->setTextureState(m_texTranscodeTiles[colorTextureIndex], nvrhi::AllSubresources,
nvrhi::ResourceStates::UnorderedAccess);
}
}
commandList->commitBarriers();
// Phase 2 - Run NTC decompression
static_assert(TRANSCODE_BATCH_SIZE <= 32, "successfulTilesMask assumes no more than 32 tiles per batch");
uint32_t successfulTilesMask = 0;
uint32_t colorTextureIndex = 0;
uint32_t blockTextureIndex = 0;
for (size_t tileIndex = 0; tileIndex < tiles.size(); ++tileIndex)
{
const TranscodeTileInfo& transcodeTile = tiles[tileIndex];
const nvfeedback::FeedbackTextureTileInfo tileInfo = transcodeTile.tileInfo;
const NtcMaterial& material = *transcodeTile.material;
ntc::ITextureSetMetadata* textureSetMetadata = material.textureSetMetadata->Get();
ntc::TextureSetDesc const& textureSetDesc = textureSetMetadata->GetDesc();
const uint32_t mipWidth = std::max(1, textureSetDesc.width >> tileInfo.mip);
const uint32_t mipHeight = std::max(1, textureSetDesc.height >> tileInfo.mip);
int textureCount = int(material.transcodeMapping.size());
assert(textureCount <= g_maxTileStagingTextures); // Maximum number of textures supported
// Make sure that the latent and weight buffers have already been created
assert(material.ntcLatentsTexture);
assert(material.ntcWeightsBuffer);
m_graphicsDecompressionPass->SetLatentTexture(material.ntcLatentsTexture);
m_graphicsDecompressionPass->SetWeightBuffer(material.ntcWeightsBuffer);
ntc::Rect rectDecompress;
rectDecompress.left = tileInfo.xInTexels;
rectDecompress.top = tileInfo.yInTexels;
rectDecompress.width = std::min(tileInfo.widthInTexels, mipWidth); // Tiles can be block sizes of 4x4 while the mip could be smaller
rectDecompress.height = std::min(tileInfo.heightInTexels, mipHeight);
ntc::Point offsetDecompress;
offsetDecompress.x = 0;
offsetDecompress.y = 0;
std::array<ntc::OutputTextureDesc, g_maxTileStagingTextures> outputTextureDescs;
for (int textureIndex = 0; textureIndex < textureCount; ++textureIndex)
{
const TextureTranscodeTask& transcodeTask = material.transcodeMapping[textureIndex];
ntc::OutputTextureDesc& outputDesc = outputTextureDescs[textureIndex];
outputDesc.firstChannel = transcodeTask.firstChannel;
outputDesc.numChannels = transcodeTask.numChannels;
outputDesc.descriptorIndex = colorTextureIndices[colorTextureIndex++];
outputDesc.rgbColorSpace = transcodeTask.sRGB ? ntc::ColorSpace::sRGB : ntc::ColorSpace::Linear;
outputDesc.ditherScale = 1.f / 255.f;
}
ntc::MakeDecompressionComputePassParameters decompressionParams;
decompressionParams.textureSetMetadata = textureSetMetadata;
decompressionParams.mipLevel = tileInfo.mip;
decompressionParams.firstOutputDescriptorIndex = 0;
decompressionParams.firstLatentMipInTexture = g_firstLatentMipInTexture;
decompressionParams.pOutputTextures = outputTextureDescs.data();
decompressionParams.numOutputTextures = textureCount;
decompressionParams.weightType = ntc::InferenceWeightType(material.weightType);
decompressionParams.pSrcRect = &rectDecompress;
decompressionParams.pDstOffset = &offsetDecompress;
ntc::ComputePassDesc decompressionPass;
ntc::Status ntcStatus = m_ntcContext->MakeDecompressionComputePass(decompressionParams, &decompressionPass);
if (ntcStatus != ntc::Status::Ok)
{
log::warning("Failed to make a decompression pass for material '%s' mip %d, error code = %s: %s",
material.name.c_str(), tileInfo.mip, ntc::StatusToString(ntcStatus), ntc::GetLastErrorMessage());
continue;
}
m_graphicsDecompressionPass->ExecuteComputePass(commandList, decompressionPass);
successfulTilesMask |= (1 << tileIndex);
}
commandList->endMarker();
// Phase 3 - Compress all mips of the color textures into BCn, where necessary
commandList->beginMarker("Transcode Tiles: BCn Compression");
// Transition textures for BCn compression
colorTextureIndex = 0;
blockTextureIndex = 0;
for (size_t tileIndex = 0; tileIndex < tiles.size(); ++tileIndex)
{
if ((successfulTilesMask & (1 << tileIndex)) == 0)
continue;
const TranscodeTileInfo& transcodeTile = tiles[tileIndex];
const nvfeedback::FeedbackTextureTileInfo tileInfo = transcodeTile.tileInfo;
const NtcMaterial& material = *transcodeTile.material;
int textureCount = int(material.transcodeMapping.size());
for (int textureIndex = 0; textureIndex < textureCount; ++textureIndex)
{
nvrhi::TextureHandle colorTexture = m_texTranscodeTiles[colorTextureIndices[colorTextureIndex++]];
if (compressThisTexture[tileIndex])
{
nvrhi::TextureHandle blockTexture = m_texTranscodeTiles[blockTextureIndices[blockTextureIndex++]];
commandList->setTextureState(colorTexture, nvrhi::AllSubresources, nvrhi::ResourceStates::ShaderResource);
commandList->setTextureState(blockTexture, nvrhi::AllSubresources, nvrhi::ResourceStates::UnorderedAccess);
}
}
}
commandList->commitBarriers();
colorTextureIndex = 0;
blockTextureIndex = 0;
for (size_t tileIndex = 0; tileIndex < tiles.size(); ++tileIndex)
{
if ((successfulTilesMask & (1 << tileIndex)) == 0)
continue;
const TranscodeTileInfo& transcodeTile = tiles[tileIndex];
const nvfeedback::FeedbackTextureTileInfo tileInfo = transcodeTile.tileInfo;
const NtcMaterial& material = *transcodeTile.material;
ntc::ITextureSetMetadata* textureSetMetadata = material.textureSetMetadata->Get();
ntc::TextureSetDesc const& textureSetDesc = textureSetMetadata->GetDesc();
const uint32_t mipWidth = std::max(1, textureSetDesc.width >> tileInfo.mip);
const uint32_t mipHeight = std::max(1, textureSetDesc.height >> tileInfo.mip);
int textureCount = int(material.transcodeMapping.size());
assert(textureCount <= g_maxTileStagingTextures); // Maximum number of textures supported
for (int textureIndex = 0; textureIndex < textureCount; ++textureIndex)
{
const TextureTranscodeTask& transcodeTask = material.transcodeMapping[textureIndex];
nvrhi::TextureHandle colorTexture = m_texTranscodeTiles[colorTextureIndices[colorTextureIndex++]];
if (compressThisTexture[tileIndex])
{
nvrhi::TextureHandle blockTexture = m_texTranscodeTiles[blockTextureIndices[blockTextureIndex++]];
float const alphaThreshold = 1.f / 255.f;
ntc::MakeBlockCompressionComputePassParameters compressionParams;
// Tiles can be block sizes of 4x4 while the mip is smaller
compressionParams.srcRect.width = std::min(tileInfo.widthInTexels, mipWidth);
compressionParams.srcRect.height = std::min(tileInfo.heightInTexels, mipHeight);
compressionParams.dstFormat = transcodeTask.bcFormat;
compressionParams.alphaThreshold = alphaThreshold;
nvrhi::IBuffer* modeBuffer = nullptr;
if (transcodeTask.bc7ModeBuffer && transcodeTask.bc7ModeBufferMipRanges[tileInfo.mip].byteSize != 0)
{
compressionParams.modeBufferSource = ntc::BlockCompressionModeBufferSource::TextureSet;
compressionParams.modeBufferByteOffset = transcodeTask.bc7ModeBufferMipRanges[tileInfo.mip].byteOffset;
compressionParams.modeBufferInfo.textureSet.texture = transcodeTask.metadata;
compressionParams.modeBufferInfo.textureSet.mipLevel = tileInfo.mip;
compressionParams.modeMapOffsetInBlocks.x = tileInfo.xInTexels >> 2;
compressionParams.modeMapOffsetInBlocks.y = tileInfo.yInTexels >> 2;
modeBuffer = transcodeTask.bc7ModeBuffer;
}
else
{
compressionParams.modeBufferSource = ntc::BlockCompressionModeBufferSource::None;
}
ntc::ComputePassDesc compressionPass;
ntc::Status ntcStatus = m_ntcContext->MakeBlockCompressionComputePass(compressionParams, &compressionPass);
if (ntcStatus != ntc::Status::Ok)
{
log::warning("Failed to make a block compression pass for material '%s', error code = %s: %s",
material.name.c_str(), ntc::StatusToString(ntcStatus), ntc::GetLastErrorMessage());
return false;
}
nvrhi::Format const inputFormat = (transcodeTask.numChannels == 1)
? nvrhi::Format::R8_UNORM
: nvrhi::Format::RGBA8_UNORM;
if (!m_graphicsBlockCompressionPass->ExecuteComputePass(commandList, compressionPass,
colorTexture, inputFormat, 0, modeBuffer, blockTexture, 0))
return false;
}
}
}
commandList->endMarker();
// Phase 4 - Copy tiles to the destination tiled resources
commandList->beginMarker("Transcode Tiles: Copy to Tiled Resources");
// Transition textures for copying
colorTextureIndex = 0;
blockTextureIndex = 0;
for (size_t tileIndex = 0; tileIndex < tiles.size(); ++tileIndex)
{
if ((successfulTilesMask & (1 << tileIndex)) == 0)
continue;
const TranscodeTileInfo& transcodeTile = tiles[tileIndex];
const nvfeedback::FeedbackTextureTileInfo tileInfo = transcodeTile.tileInfo;
const NtcMaterial& material = *transcodeTile.material;
int textureCount = int(material.transcodeMapping.size());
for (int textureIndex = 0; textureIndex < textureCount; ++textureIndex)
{
const TextureTranscodeTask& transcodeTask = material.transcodeMapping[textureIndex];
nvrhi::ITexture* pDestTexture = (material.*transcodeTask.pFeedbackTexture)->GetReservedTexture();
commandList->setTextureState(pDestTexture, nvrhi::AllSubresources, nvrhi::ResourceStates::CopyDest);
nvrhi::TextureHandle colorTexture = m_texTranscodeTiles[colorTextureIndices[colorTextureIndex++]];
if (compressThisTexture[tileIndex])
{
nvrhi::TextureHandle blockTexture = m_texTranscodeTiles[blockTextureIndices[blockTextureIndex++]];
commandList->setTextureState(blockTexture, nvrhi::AllSubresources, nvrhi::ResourceStates::CopySource);
}
else
{
commandList->setTextureState(colorTexture, nvrhi::AllSubresources, nvrhi::ResourceStates::CopySource);
}
}
}
commandList->commitBarriers();
colorTextureIndex = 0;
blockTextureIndex = 0;
for (size_t tileIndex = 0; tileIndex < tiles.size(); ++tileIndex)
{
if ((successfulTilesMask & (1 << tileIndex)) == 0)
continue;
const TranscodeTileInfo& transcodeTile = tiles[tileIndex];
const nvfeedback::FeedbackTextureTileInfo tileInfo = transcodeTile.tileInfo;
const NtcMaterial& material = *transcodeTile.material;
ntc::ITextureSetMetadata* textureSetMetadata = material.textureSetMetadata->Get();
ntc::TextureSetDesc const& textureSetDesc = textureSetMetadata->GetDesc();
const uint32_t mipWidth = std::max(1, textureSetDesc.width >> tileInfo.mip);
const uint32_t mipHeight = std::max(1, textureSetDesc.height >> tileInfo.mip);
int textureCount = int(material.transcodeMapping.size());
assert(textureCount <= g_maxTileStagingTextures); // Maximum number of textures supported
for (int textureIndex = 0; textureIndex < textureCount; ++textureIndex)
{
const TextureTranscodeTask& transcodeTask = material.transcodeMapping[textureIndex];
nvrhi::ITexture* pDestTexture = (material.*transcodeTask.pFeedbackTexture)->GetReservedTexture();
nvrhi::TextureSlice textureSliceDst = {};
textureSliceDst.x = tileInfo.xInTexels;
textureSliceDst.y = tileInfo.yInTexels;
textureSliceDst.z = 0;
textureSliceDst.mipLevel = tileInfo.mip;
textureSliceDst.width = tileInfo.widthInTexels;
textureSliceDst.height = tileInfo.heightInTexels;
textureSliceDst.depth = 1;
nvrhi::TextureHandle colorTexture = m_texTranscodeTiles[colorTextureIndices[colorTextureIndex++]];
if (compressThisTexture[tileIndex])
{
nvrhi::TextureHandle blockTexture = m_texTranscodeTiles[blockTextureIndices[blockTextureIndex++]];
nvrhi::TextureSlice textureSliceSrc = {};
textureSliceSrc.x = 0;
textureSliceSrc.y = 0;
textureSliceSrc.z = 0;
textureSliceSrc.mipLevel = 0;
textureSliceSrc.width = (tileInfo.widthInTexels + 3) / 4;
textureSliceSrc.height = (tileInfo.heightInTexels + 3) / 4;
textureSliceSrc.depth = 1;
commandList->copyTexture(pDestTexture, textureSliceDst, blockTexture, textureSliceSrc);
}
else
{
nvrhi::TextureSlice textureSliceSrc = {};
textureSliceSrc.x = 0;
textureSliceSrc.y = 0;
textureSliceSrc.z = 0;
textureSliceSrc.mipLevel = 0;
textureSliceSrc.width = tileInfo.widthInTexels;
textureSliceSrc.height = tileInfo.heightInTexels;
textureSliceSrc.depth = 1;
commandList->copyTexture(pDestTexture, textureSliceDst, colorTexture, textureSliceSrc);
}
}
}
commandList->endMarker();
return true;
}
bool NtcMaterialLoader::CreateAndLoadModeBufferForTexture(ntc::IContext* ntcContext, ntc::IStream* ntcFile,
ntc::ITextureSetMetadata* textureSetMetadata, TextureTranscodeTask& transcodeTask,
nvrhi::ICommandList* commandList, std::string const& materialTextureName)
{
ntc::TextureSetDesc const& textureSetDesc = textureSetMetadata->GetDesc();
std::vector<BufferLoadingTask> modeBufferTasks;
size_t stagingBufferSize = 0;
size_t tempBufferSize = 0;
size_t finalBufferSize = 0;
FillBufferLoadingTasksForBC(textureSetDesc, transcodeTask.metadata, modeBufferTasks,
m_gdeflateFeatures && m_gdeflateFeatures->gpuDecompressionSupported, m_device->getGraphicsAPI(),
stagingBufferSize, tempBufferSize, finalBufferSize);
if (!ExecuteBufferLoadingTasks(m_device, commandList, ntcContext, ntcFile, m_gdeflateFeatures.get(),
modeBufferTasks, transcodeTask.bc7ModeBuffer, stagingBufferSize, tempBufferSize, finalBufferSize))
return false;
transcodeTask.bc7ModeBufferMipRanges.resize(modeBufferTasks.size());
for (size_t mip = 0; mip < modeBufferTasks.size(); ++mip)
{
BufferLoadingTask const& mipTask = modeBufferTasks[mip];
if (mipTask.pipeline != BufferLoadingPipeline::None)
transcodeTask.bc7ModeBufferMipRanges[mip] = mipTask.finalBufferRange;
}
return true;
}
bool NtcMaterialLoader::TranscodeMaterial(ntc::IContext* context, ntc::IStream* ntcFile,
ntc::ITextureSetMetadata* textureSetMetadata,
NtcMaterial& material, nvrhi::ICommandList* commandList, bool enableBlockCompression)
{
if (material.transcodeMapping.empty())
return true;
int const textureCount = int(material.transcodeMapping.size());
// Phase 1 - Create textures (color, block, BCn) and write descriptors for NTC decompression
ntc::TextureSetDesc const& textureSetDesc = textureSetMetadata->GetDesc();
for (int textureIndex = 0; textureIndex < textureCount; ++textureIndex)
{
TextureTranscodeTask& transcodeTask = material.transcodeMapping[textureIndex];
std::string const materialTextureName = material.name + ":" + std::string(transcodeTask.name);
// Create the color texture
nvrhi::TextureDesc colorTextureDesc = nvrhi::TextureDesc()
.setDimension(nvrhi::TextureDimension::Texture2D)
.setWidth(textureSetDesc.width)
.setHeight(textureSetDesc.height)
.setMipLevels(textureSetDesc.mips)
.setFormat((transcodeTask.numChannels == 1)
? nvrhi::Format::R8_UNORM
: transcodeTask.sRGB
? nvrhi::Format::SRGBA8_UNORM
: nvrhi::Format::RGBA8_UNORM)
.setDebugName(materialTextureName)
.setIsUAV(true)
.setIsTypeless(true)
.setInitialState(nvrhi::ResourceStates::ShaderResource)
.setKeepInitialState(true);
transcodeTask.color = m_device->createTexture(colorTextureDesc);
if (!transcodeTask.color)
return false;
bool compressThisTexture = enableBlockCompression && transcodeTask.bcFormat != ntc::BlockCompressedFormat::None;
if (compressThisTexture)
{
// Create the BCn texture
nvrhi::TextureDesc compressedTextureDesc = nvrhi::TextureDesc()
.setDimension(nvrhi::TextureDimension::Texture2D)
.setFormat(transcodeTask.nvrhiBcFormat)
.setWidth(textureSetDesc.width)
.setHeight(textureSetDesc.height)
.setMipLevels(textureSetDesc.mips)
.setDebugName(materialTextureName)
.setInitialState(nvrhi::ResourceStates::ShaderResource)
.setKeepInitialState(true);
transcodeTask.compressed = m_device->createTexture(compressedTextureDesc);
if (!transcodeTask.compressed)
return false;
// Create the block texture
bool const isSmallBlock =
(transcodeTask.bcFormat == ntc::BlockCompressedFormat::BC1) ||
(transcodeTask.bcFormat == ntc::BlockCompressedFormat::BC4);
nvrhi::TextureDesc blockTextureDesc = nvrhi::TextureDesc()
.setDimension(nvrhi::TextureDimension::Texture2D)
.setWidth((textureSetDesc.width + 3) / 4)
.setHeight((textureSetDesc.height + 3) / 4)
.setFormat(isSmallBlock ? nvrhi::Format::RG32_UINT : nvrhi::Format::RGBA32_UINT)
.setDebugName(materialTextureName)
.setIsUAV(true)
.setInitialState(nvrhi::ResourceStates::UnorderedAccess)
.setKeepInitialState(true);
transcodeTask.blocks = m_device->createTexture(blockTextureDesc);
if (!transcodeTask.blocks)
return false;
if (transcodeTask.bcFormat == ntc::BlockCompressedFormat::BC7)
{
if (!CreateAndLoadModeBufferForTexture(context, ntcFile, textureSetMetadata, transcodeTask,
commandList, materialTextureName))
return false;
}
}
// Descriptors for all mip levels of one texture are packed together
transcodeTask.mipZeroDescriptor = textureSetDesc.mips * textureIndex;
// Write descriptors for all mips of the color texture
for (int mipLevel = 0; mipLevel < textureSetDesc.mips; ++mipLevel)
{
int descriptorIndex = transcodeTask.mipZeroDescriptor + mipLevel;
nvrhi::BindingSetItem descriptor = nvrhi::BindingSetItem::Texture_UAV(
descriptorIndex,
transcodeTask.color,
(transcodeTask.numChannels == 1)
? nvrhi::Format::R8_UNORM
: nvrhi::Format::RGBA8_UNORM, // Always use non-sRGB formats so that we can create a UAV
nvrhi::TextureSubresourceSet().setBaseMipLevel(mipLevel));
m_graphicsDecompressionPass->WriteDescriptor(descriptor);
}
// Create a LoadedTexture object to attach the texture to the material
std::shared_ptr<engine::LoadedTexture> loadedTexture = std::make_shared<engine::LoadedTexture>();
loadedTexture->texture = compressThisTexture ? transcodeTask.compressed : transcodeTask.color;
// Count the final texture size in the material's memory consumption metric
size_t const textureMemorySize = m_device->getTextureMemoryRequirements(loadedTexture->texture).size;
material.transcodedMemorySize += textureMemorySize;
// Bind the created texture object to the material texture slot
material.*transcodeTask.pMaterialTexture = loadedTexture;
}
commandList->open();
for (int textureIndex = 0; textureIndex < textureCount; ++textureIndex)
{
TextureTranscodeTask& transcodeTask = material.transcodeMapping[textureIndex];
// Transition the texture to the UAV state because NVRHI won't do that when resources are accessed
// through a descriptor table. Note that there is no need to transition it back to SRV after decompression
// because the next operations are using regular binding sets. There is also no need for commitBarriers()
// because that's called by the decompression dispatch call.
commandList->setTextureState(transcodeTask.color, nvrhi::AllSubresources,
nvrhi::ResourceStates::UnorderedAccess);
}
// Submit the texture transitions performed above via setTextureState(...) to the command list.
// This is not really necessary because the next call to commandList->setComputeState(...) will do it,
// but let's be explicit.
commandList->commitBarriers();
// Phase 2 - Run NTC decompression
// Make sure that the latent and weight buffers have already been created
assert(material.ntcLatentsTexture);
assert(material.ntcWeightsBuffer);
m_graphicsDecompressionPass->SetLatentTexture(material.ntcLatentsTexture);
m_graphicsDecompressionPass->SetWeightBuffer(material.ntcWeightsBuffer);
// Pre-fill the OutputTextureDesc array for decoding of all mip levels
std::vector<ntc::OutputTextureDesc> outputTextureDescs;
outputTextureDescs.resize(textureCount);
for (int textureIndex = 0; textureIndex < textureCount; ++textureIndex)
{
TextureTranscodeTask& transcodeTask = material.transcodeMapping[textureIndex];
ntc::OutputTextureDesc& outputDesc = outputTextureDescs[textureIndex];
outputDesc.firstChannel = transcodeTask.firstChannel;
outputDesc.numChannels = transcodeTask.numChannels;
outputDesc.descriptorIndex = transcodeTask.mipZeroDescriptor;
outputDesc.rgbColorSpace = transcodeTask.sRGB ? ntc::ColorSpace::sRGB : ntc::ColorSpace::Linear;
outputDesc.ditherScale = 1.f / 255.f;
}
uint32_t successfulMipLevelMask = 0;
for (int mipLevel = 0; mipLevel < textureSetDesc.mips; ++mipLevel)
{
// Obtain the description of the decompression pass from LibNTC.
// The description includes the shader code, weights, and constants.
ntc::MakeDecompressionComputePassParameters decompressionParams;
decompressionParams.textureSetMetadata = textureSetMetadata;
decompressionParams.mipLevel = mipLevel;
// This index is added to descriptorIndex from the outputTextureDescs array, so the indexing math works out
decompressionParams.firstOutputDescriptorIndex = mipLevel;
decompressionParams.firstLatentMipInTexture = g_firstLatentMipInTexture;
decompressionParams.pOutputTextures = outputTextureDescs.data();
decompressionParams.numOutputTextures = int(outputTextureDescs.size());
decompressionParams.weightType = ntc::InferenceWeightType(material.weightType);
ntc::ComputePassDesc decompressionPass;
ntc::Status ntcStatus = m_ntcContext->MakeDecompressionComputePass(decompressionParams, &decompressionPass);
if (ntcStatus != ntc::Status::Ok)
{
log::warning("Failed to make a decompression pass for material '%s' mip %d, error code = %s: %s",
material.name.c_str(), mipLevel, ntc::StatusToString(ntcStatus), ntc::GetLastErrorMessage());
continue;
}
// Execute the compute pass to decompress the texture.
// Note: ExecuteComputePass is application code (not LibNTC) and it caches PSOs based on shader code pointers.
m_graphicsDecompressionPass->ExecuteComputePass(commandList, decompressionPass);
successfulMipLevelMask |= (1 << mipLevel);
}
// Phase 3 - Compress all mips of the color textures into BCn, where necessary
for (TextureTranscodeTask const& transcodeTask : material.transcodeMapping)
{
if (!transcodeTask.compressed)
continue;
float const alphaThreshold = 1.f / 255.f;
for (int mipLevel = 0; mipLevel < textureSetDesc.mips; ++mipLevel)
{
if ((successfulMipLevelMask & (1 << mipLevel)) == 0)
continue; // This mip level was not decompressed successfully, skip BCn compression
int const mipWidth = std::max(textureSetDesc.width >> mipLevel, 1);
int const mipHeight = std::max(textureSetDesc.height >> mipLevel, 1);
// Obtain the description of the BC compression pass from LibNTC.
ntc::MakeBlockCompressionComputePassParameters compressionParams;
compressionParams.srcRect.width = mipWidth;
compressionParams.srcRect.height = mipHeight;
compressionParams.dstFormat = transcodeTask.bcFormat;
compressionParams.alphaThreshold = alphaThreshold;