-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTexture.cpp
More file actions
910 lines (819 loc) · 31.6 KB
/
Copy pathTexture.cpp
File metadata and controls
910 lines (819 loc) · 31.6 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
#include "Texture.h"
#include "PathFinder.h"
#include "Core.Memory.hpp"
// Win32::ThrowIfFailed가 여기 있다. 유니티 빌드에서는 같은 블롭의 앞선
// 파일이 공급했다.
#include "DirectXHelper.h"
#include <DirectXTex.h>
// 유니티 빌드에서는 같은 블롭의 앞선 파일이 이 using을 공급했다.
// ASan 구성은 블롭을 끄므로 직접 받는다(PHASE 9-9).
using namespace DirectX;
// ── 코덱 산출물 (축 A) ────────────────────────────────────────────────────
//
// Texture 가 드는 것은 이 struct 이고, 정의는 이 파일에만 있다. 헤더는
// 전방선언만 알므로 DirectXTex 도 DirectX:: 이름도 나가지 않는다.
//
// ★ 픽셀을 옮기지 않는다. 디코더가 낸 자리에 그대로 두고 서브리소스 표만
// 만든다 — 그 표가 가리키는 것이 scratch(또는 owned)의 내부 버퍼다.
// 컨테이너로 옮기면 로드마다 전량 복사가 붙는데, 4K HDR equirect 한 장이
// 128MB 라 그 한 번이 무시되지 않는다.
struct Texture::CodecImage
{
/// 출처 A — 파일·메모리 디코드. DirectXTex 가 픽셀을 소유한 채 남는다.
ScratchImage scratch;
/// 출처 B — 이미 중립인 픽셀을 받아 든 것(cooked generation · 합성 픽셀).
TextureImage owned;
/// 위 둘 중 살아 있는 쪽의 내부를 가리킨다.
std::vector<TextureSubimage> subresources;
RHIFormat format{ RHIFormat::Unknown };
uint32_t width{ 0 };
uint32_t height{ 0 };
uint32_t mipLevels{ 0 };
uint32_t arraySize{ 0 };
bool isCube{ false };
};
// ── DirectXTex 와 나머지 엔진의 유일한 접점 (축 A) ──────────────────────
//
// 이 파일 위쪽(로더 넷)은 DirectXTex 로 디코드·압축하고, 아래 헬퍼가 그
// 결과를 중립 서술로 감싼다. 그 지점부터는 저장소 어디에도
// DirectX::ScratchImage 가 없다 — 디코더나 압축기를 갈아 끼우는 날 봐야
// 할 파일은 이것 하나다.
//
// ★ 익명 네임스페이스인데 이름이 긴 이유: 유니티 빌드가 여러 .cpp 를 한
// TU 로 합치므로 흔한 이름은 옆 파일과 충돌한다.
namespace
{
/// DirectXTex 디코더·압축기가 실제로 내는 포맷만 담은 표.
///
/// ★ 백엔드 대응표(DX12Format.h · VulkanFormat.h)와 성격이 다르다.
/// 저쪽은 "엔진 어휘 <-> API 어휘"이고 이것은 "디코더 어휘 -> 엔진
/// 어휘"다. 축 B 에서 디코더가 바뀌면 이 표는 함께 사라진다.
RHIFormat TextureDecodedFormatToRHI(DXGI_FORMAT format)
{
switch (format)
{
case DXGI_FORMAT_R8G8B8A8_UNORM: return RHIFormat::RGBA8Unorm;
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: return RHIFormat::RGBA8UnormSrgb;
case DXGI_FORMAT_B8G8R8A8_UNORM: return RHIFormat::BGRA8Unorm;
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: return RHIFormat::BGRA8UnormSrgb;
case DXGI_FORMAT_R16G16B16A16_FLOAT: return RHIFormat::RGBA16Float;
case DXGI_FORMAT_R32G32B32A32_FLOAT: return RHIFormat::RGBA32Float;
case DXGI_FORMAT_BC1_UNORM: return RHIFormat::BC1Unorm;
case DXGI_FORMAT_BC1_UNORM_SRGB: return RHIFormat::BC1UnormSrgb;
case DXGI_FORMAT_BC3_UNORM: return RHIFormat::BC3Unorm;
case DXGI_FORMAT_BC3_UNORM_SRGB: return RHIFormat::BC3UnormSrgb;
default: return RHIFormat::Unknown;
}
}
/// 2D 밉·배열 체인으로 다룰 수 있는 이미지인지.
bool TextureIsUploadableShape(const TexMetadata& metadata)
{
return TEX_DIMENSION_TEXTURE2D == metadata.dimension
&& 0 != metadata.width && 0 != metadata.height
&& 0 != metadata.mipLevels && 0 != metadata.arraySize
&& metadata.width <= UINT32_MAX && metadata.height <= UINT32_MAX;
}
/// scratch 를 CodecImage 로 **옮긴 뒤** 서브리소스 표를 채운다.
///
/// ★ 옮긴 뒤여야 한다. ScratchImage 의 이동은 내부 버퍼를 넘기므로,
/// 옮기기 전에 얻은 GetImage() 포인터는 그 뒤로 유효를 보장하지 않는다.
bool TextureAdoptScratch(Texture::CodecImage& out, ScratchImage&& image,
RHIFormat format)
{
out.scratch = std::move(image);
const TexMetadata& metadata = out.scratch.GetMetadata();
out.format = format;
out.width = static_cast<uint32_t>(metadata.width);
out.height = static_cast<uint32_t>(metadata.height);
out.mipLevels = static_cast<uint32_t>(metadata.mipLevels);
out.arraySize = static_cast<uint32_t>(metadata.arraySize);
out.isCube = metadata.IsCubemap();
out.subresources.clear();
out.subresources.reserve(
static_cast<size_t>(out.arraySize) * out.mipLevels);
// item 바깥, mip 안쪽 — TextureImage.h 의 레이아웃 규약과 같다.
for (uint32_t item = 0; item < out.arraySize; ++item)
{
for (uint32_t mip = 0; mip < out.mipLevels; ++mip)
{
const Image* source = out.scratch.GetImage(mip, item, 0);
if (nullptr == source || nullptr == source->pixels) return false;
TextureSubimage subresource;
subresource.pixels = reinterpret_cast<const std::byte*>(source->pixels);
subresource.rowPitch = source->rowPitch;
subresource.slicePitch = source->slicePitch;
subresource.width = static_cast<uint32_t>(source->width);
subresource.height = static_cast<uint32_t>(source->height);
out.subresources.push_back(subresource);
}
}
return !out.subresources.empty();
}
/// 이미 중립인 이미지를 CodecImage 로 옮긴다(cooked generation · 합성 픽셀).
bool TextureAdoptImage(Texture::CodecImage& out, TextureImage&& image)
{
if (!image.IsValid()) return false;
out.owned = std::move(image);
out.format = out.owned.Format();
out.width = out.owned.Width();
out.height = out.owned.Height();
out.mipLevels = out.owned.MipLevels();
out.arraySize = out.owned.ArraySize();
out.isCube = out.owned.IsCube();
out.subresources.clear();
out.subresources.reserve(
static_cast<size_t>(out.arraySize) * out.mipLevels);
for (uint32_t item = 0; item < out.arraySize; ++item)
{
for (uint32_t mip = 0; mip < out.mipLevels; ++mip)
{
const TextureSubimage* source = out.owned.Find(mip, item);
if (nullptr == source || nullptr == source->pixels) return false;
out.subresources.push_back(*source);
}
}
return !out.subresources.empty();
}
/// 표에 없는 디코더 산출 포맷을 RGBA8 로 내린다.
///
/// ★ 거절하지 않는 이유: 거절하면 그 자산이 화면에서 통째로 사라진다.
/// 어휘에 이름이 없다는 이유로 그림을 잃는 것보다 한 번 변환하는 편이
/// 낫고, 여기 걸리는 포맷이 실제로 나오면 그것이 어휘에 더할 후보다.
/// 전달 함수는 건드리지 않는다 — 목표의 sRGB 성질을 소스와 같게 두면
/// DirectXTex 가 감마에 손대지 않는다(Texture::DecodeToRgba8 주석 참고).
bool TextureLowerToRgba8(const ScratchImage& image, ScratchImage& out)
{
const TexMetadata& metadata = image.GetMetadata();
const DXGI_FORMAT target = IsSRGB(metadata.format)
? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB : DXGI_FORMAT_R8G8B8A8_UNORM;
const HRESULT lowering = IsCompressed(metadata.format)
? Decompress(image.GetImages(), image.GetImageCount(), metadata,
target, out)
: Convert(image.GetImages(), image.GetImageCount(), metadata, target,
TEX_FILTER_DEFAULT, TEX_THRESHOLD_DEFAULT, out);
return SUCCEEDED(lowering) && 0 != out.GetImageCount();
}
/// 디코드 결과를 Texture 가 들 형태로 감싼다. 픽셀 복사 0.
std::shared_ptr<Texture::CodecImage> TextureMakeCodecImage(ScratchImage&& image)
{
if (!TextureIsUploadableShape(image.GetMetadata())) return nullptr;
auto codec = std::make_shared<Texture::CodecImage>();
const RHIFormat known = TextureDecodedFormatToRHI(image.GetMetadata().format);
if (RHIFormat::Unknown != known)
{
if (!TextureAdoptScratch(*codec, std::move(image), known)) return nullptr;
return codec;
}
ScratchImage lowered;
if (!TextureLowerToRgba8(image, lowered)) return nullptr;
const RHIFormat loweredFormat =
TextureDecodedFormatToRHI(lowered.GetMetadata().format);
if (RHIFormat::Unknown == loweredFormat) return nullptr;
if (!TextureAdoptScratch(*codec, std::move(lowered), loweredFormat))
return nullptr;
return codec;
}
/// 이미 중립인 이미지를 Texture 가 들 형태로 감싼다.
std::shared_ptr<Texture::CodecImage> TextureMakeCodecImage(TextureImage&& image)
{
auto codec = std::make_shared<Texture::CodecImage>();
if (!TextureAdoptImage(*codec, std::move(image))) return nullptr;
return codec;
}
/// 디코드 결과를 소유 컨테이너로 **복사한다**. cook 경로 전용이다 —
/// 그쪽은 픽셀을 ModelTextureAsset 으로 다시 옮기므로 어차피 한 번 복사가
/// 필요하고, 런타임 로드 경로처럼 128MB 를 다루지 않는다.
bool TextureCopyScratchToImage(const ScratchImage& image, RHIFormat format,
TextureImage& out)
{
const TexMetadata& metadata = image.GetMetadata();
out = TextureImage::Allocate(format,
static_cast<uint32_t>(metadata.width),
static_cast<uint32_t>(metadata.height),
static_cast<uint32_t>(metadata.arraySize),
static_cast<uint32_t>(metadata.mipLevels),
metadata.IsCubemap());
if (!out.IsValid()) return false;
for (uint32_t item = 0; item < out.ArraySize(); ++item)
{
for (uint32_t mip = 0; mip < out.MipLevels(); ++mip)
{
const TextureSubimage* destination = out.Find(mip, item);
const Image* source = image.GetImage(mip, item, 0);
if (nullptr == destination || nullptr == source
|| nullptr == source->pixels) return false;
std::byte* destinationPixels = out.MutablePixelsAt(*destination);
if (nullptr == destinationPixels) return false;
CopyImageRows(destinationPixels, destination->rowPitch,
reinterpret_cast<const std::byte*>(source->pixels),
source->rowPitch,
RHIFormatRowCount(format, destination->height),
destination->rowPitch);
}
}
return true;
}
/// 인코딩된 바이트를 매직으로 갈라 디코드한다.
///
/// DDS·HDR 는 매직이 있고, 나머지는 WIC 가 스스로 판별한다. TGA 는
/// 매직이 없어 WIC 가 거절한 뒤에만 시도한다.
bool TextureDecodeImageBytes(std::span<const std::byte> bytes,
TexMetadata& metadata, ScratchImage& image, bool& outAlreadyFinal)
{
outAlreadyFinal = false;
if (bytes.empty()) return false;
const auto startsWith = [&bytes](std::string_view magic)
{
if (bytes.size() < magic.size()) return false;
for (size_t index = 0; index < magic.size(); ++index)
{
if (static_cast<char>(bytes[index]) != magic[index]) return false;
}
return true;
};
HRESULT result = E_FAIL;
if (startsWith("DDS "))
{
result = LoadFromDDSMemory(bytes.data(), bytes.size(),
DDS_FLAGS_FORCE_RGB, &metadata, image);
outAlreadyFinal = true;
}
else if (startsWith("#?RADIANCE") || startsWith("#?RGBE"))
{
result = LoadFromHDRMemory(bytes.data(), bytes.size(), &metadata, image);
outAlreadyFinal = true;
}
else
{
result = LoadFromWICMemory(bytes.data(), bytes.size(),
WIC_FLAGS_IGNORE_SRGB, &metadata, image);
if (FAILED(result))
{
result = LoadFromTGAMemory(bytes.data(), bytes.size(),
TGA_FLAGS_NONE, &metadata, image);
}
}
return SUCCEEDED(result) && 0 != image.GetImageCount();
}
}
TextureImageView Texture::GetImageView() const
{
if (!m_codecImage || m_codecImage->subresources.empty()) return {};
const CodecImage& codec = *m_codecImage;
return TextureImageView(m_samplingFormat == RHIFormat::Unknown ? codec.format : m_samplingFormat,
codec.width, codec.height,
codec.mipLevels, codec.arraySize, codec.isCube,
codec.subresources.data(),
static_cast<uint32_t>(codec.subresources.size()));
}
std::shared_ptr<Texture> Texture::WithColorSpace(
const std::shared_ptr<Texture>& source, bool srgb)
{
if (!source || source->GetImageView().IsEmpty()) return nullptr;
const auto format = source->GetImageView().Format();
RHIFormat target = format;
switch (format)
{
case RHIFormat::RGBA8Unorm: case RHIFormat::RGBA8UnormSrgb:
target = srgb ? RHIFormat::RGBA8UnormSrgb : RHIFormat::RGBA8Unorm; break;
case RHIFormat::BGRA8Unorm: case RHIFormat::BGRA8UnormSrgb:
target = srgb ? RHIFormat::BGRA8UnormSrgb : RHIFormat::BGRA8Unorm; break;
case RHIFormat::BC1Unorm: case RHIFormat::BC1UnormSrgb:
target = srgb ? RHIFormat::BC1UnormSrgb : RHIFormat::BC1Unorm; break;
case RHIFormat::BC3Unorm: case RHIFormat::BC3UnormSrgb:
target = srgb ? RHIFormat::BC3UnormSrgb : RHIFormat::BC3Unorm; break;
// Floating-point HDR images are already linear radiance.
case RHIFormat::RGBA16Float: case RHIFormat::RGBA32Float: break;
default: if (srgb) return nullptr; break;
}
if (target == format) return source;
auto texture = std::make_shared<Texture>();
texture->m_codecImage = source->m_codecImage;
texture->m_samplingFormat = target;
texture->m_textureType = source->m_textureType;
texture->m_name = source->m_name;
texture->m_extension = source->m_extension;
texture->m_size = source->m_size;
texture->m_isTextureAlpha = source->m_isTextureAlpha;
return texture;
}
//static functions
Texture* Texture::CreateFromPixels(_In_ uint32 width, _In_ uint32 height,
_In_ std::string_view name, _In_ RHIFormat textureFormat,
_In_reads_bytes_(rowPitch* height) const void* pixels, _In_opt_ size_t rowPitch)
{
if (0 == width || 0 == height || nullptr == pixels) return nullptr;
// ★ 예전에는 여기서도 ScratchImage 를 세웠다(축 A 전). 만들려는 것이
// CPU 픽셀 한 장뿐인데 디코더 라이브러리의 컨테이너를 거칠 이유가
// 없다 — 지금은 중립 이미지를 직접 잡는다.
TextureImage image = TextureImage::Allocate(textureFormat, width, height, 1, 1);
if (!image.IsValid()) return nullptr;
const TextureSubimage* destination = image.Find(0, 0);
if (nullptr == destination) return nullptr;
std::byte* destinationPixels = image.MutablePixelsAt(*destination);
if (nullptr == destinationPixels) return nullptr;
// 원본 행 간격을 안 주면 빈틈없이 채워진 것으로 본다.
//
// ★ 행 단위로 옮긴다. 대상의 행 간격은 정렬 때문에 원본보다 클 수
// 있고, 그때 통째로 memcpy하면 그림이 한 행씩 밀려 비스듬해진다 —
// 1x1에서는 안 드러나고 폭이 커지는 순간 나타나는 부류다.
const size_t sourcePitch = (0 != rowPitch)
? rowPitch : static_cast<size_t>(RHIFormatRowPitch(textureFormat, width));
CopyImageRows(destinationPixels, destination->rowPitch,
static_cast<const std::byte*>(pixels), sourcePitch,
RHIFormatRowCount(textureFormat, height), destination->rowPitch);
Texture* texture = new Texture();
texture->m_name = std::string(name);
texture->m_textureType = TextureType::ImageTexture;
texture->m_size = { float(width), float(height) };
// 파일 로더가 남기는 자리와 같다 — 텍스처 캐시가 여기서 가져간다(T1·T4).
texture->m_codecImage = TextureMakeCodecImage(std::move(image));
if (!texture->m_codecImage)
{
delete texture;
return nullptr;
}
return texture;
}
std::shared_ptr<Texture> Texture::CreateSharedFromImage(
std::string_view name, TextureImage image)
{
if (!image.IsValid()) return nullptr;
const bool isCube = image.IsCube();
const uint32_t arraySize = image.ArraySize();
const float width = float(image.Width());
const float height = float(image.Height());
const RHIFormat format = image.Format();
std::shared_ptr<CodecImage> codecImage = TextureMakeCodecImage(std::move(image));
if (!codecImage) return nullptr;
auto texture = std::shared_ptr<Texture>(new Texture());
texture->m_name = std::string(name);
texture->m_textureType = isCube
? TextureType::TextureCube
: (arraySize > 1 ? TextureType::TextureArray : TextureType::ImageTexture);
texture->m_size = { width, height };
// ★ 예전에는 DirectX::HasAlpha(포맷)를 물었다. 그 물음은 "이 포맷에
// 알파 채널이 있는가"이지 "이 그림에 투명한 데가 있는가"가 아니다 —
// 중립 어휘의 8비트 색 포맷은 전부 알파를 가지므로 답이 늘 참이었다.
// 지금은 채널 수로 같은 답을 준다(뜻이 바뀌지 않는다).
texture->m_isTextureAlpha = (4 == RHIFormatChannels(format))
|| RHIFormatIsBlockCompressed(format);
texture->m_codecImage = std::move(codecImage);
return texture;
}
Texture* Texture::LoadFormPath(_In_ const file::path& path, bool isCompress)
{
file::path matPath = PathFinder::RelativeToMaterial(path.string());
if (!file::exists(path) && !file::exists(matPath))
{
return nullptr;
}
file::path preparePath{};
if (file::exists(matPath))
{
preparePath = matPath;
}
else
{
preparePath = path;
}
ScratchImage image{};
TexMetadata metadata{};
Benchmark banch3;
if (path.extension() == ".dds")
{
//load dds
Win32::ThrowIfFailed(
LoadFromDDSFile(
preparePath.c_str(),
DDS_FLAGS_FORCE_RGB,
&metadata,
image
)
);
}
else if (path.extension() == ".tga")
{
//load tga
Win32::ThrowIfFailed(
LoadFromTGAFile(
preparePath.c_str(),
&metadata,
image
)
);
}
else if (path.extension() == ".hdr")
{
//load hdr
Win32::ThrowIfFailed(
LoadFromHDRFile(
preparePath.c_str(),
&metadata,
image
)
);
}
else
{
//load wic
Win32::ThrowIfFailed(
LoadFromWICFile(
preparePath.c_str(),
WIC_FLAGS_IGNORE_SRGB,
&metadata,
image
)
);
}
if(isCompress)
{
ScratchImage compressedImage{};
if (!IsCompressed(metadata.format) && path.extension() != ".hdr" && path.extension() != ".dds")
{
DirectX::TexMetadata tempMetadata = metadata;
// DXGI_FORMAT_BC1_UNORM_SRGB (== DXT1, 감마 디코드 라벨)
Win32::ThrowIfFailed(
DirectX::Compress(
image.GetImages(),
image.GetImageCount(),
metadata,
DXGI_FORMAT_BC1_UNORM_SRGB,
TEX_COMPRESS_PARALLEL,
0.5f,
compressedImage
)
);
metadata = compressedImage.GetMetadata(); // 메타데이터 갱신
image = std::move(compressedImage); // 압축된 이미지로 교체
}
}
// 코덱 산출물을 감싼 뒤에 자산을 세운다 — 감싸지 못하면 텍스처 자체를
// 만들지 않는다(픽셀 없는 Texture는 캐시에서 흰색으로 나온다).
// image 를 옮기기 전에 읽어 둔다 — 옮긴 뒤로는 원본이 비어 있다.
// (코덱 산출물을 복사하지 않고 그대로 넘기는 것이 축 A 의 요점이다)
const bool hasAlpha = !image.IsAlphaAllOpaque();
std::shared_ptr<CodecImage> codecImage = TextureMakeCodecImage(std::move(image));
if (!codecImage) return nullptr;
Texture* texture = new Texture();
// ★ 여기 있던 DX11 SRV 생성을 걷었다 (T6, 2026-08-08).
//
// 이 로더가 만들던 것은 둘이었다 - CPU 픽셀(m_cpuPixels)과 DX11
// SRV. 앞의 것은 DX12TextureCache가 읽어 올리고, 뒤의 것은
// 에디터 썸네일의 폴백 하나가 마지막 소비자였다(EditorImGuiTexture).
// 그 폴백이 사라지면서 소비자가 0이 됐다.
texture->m_textureType = TextureType::ImageTexture;
texture->m_size = { float(metadata.width),float(metadata.height) };
texture->m_isTextureAlpha = hasAlpha;
// 압축까지 끝난 최종 이미지를 캐시가 가져가도록 남긴다(T1).
// 예전에는 여기서 버렸고 DX12는 방금 만든 DX11 텍스처에서 되읽었다.
texture->m_codecImage = std::move(codecImage);
return texture;
}
std::shared_ptr<Texture> Texture::LoadSharedFromPath(const file::path& path, bool isCompress)
{
file::path matPath = PathFinder::RelativeToMaterial(path.string());
if (!file::exists(path) && !file::exists(matPath))
{
return nullptr;
}
const file::path preparePath = file::exists(path) ? path : matPath;
ScratchImage image{};
TexMetadata metadata{};
Benchmark banch3;
if (path.extension() == ".dds")
{
//load dds
Win32::ThrowIfFailed(
LoadFromDDSFile(
preparePath.c_str(),
DDS_FLAGS_FORCE_RGB,
&metadata,
image
)
);
}
else if (path.extension() == ".tga")
{
//load tga
Win32::ThrowIfFailed(
LoadFromTGAFile(
preparePath.c_str(),
&metadata,
image
)
);
}
else if (path.extension() == ".hdr")
{
//load hdr
Win32::ThrowIfFailed(
LoadFromHDRFile(
preparePath.c_str(),
&metadata,
image
)
);
}
else
{
//load wic
Win32::ThrowIfFailed(
LoadFromWICFile(
preparePath.c_str(),
WIC_FLAGS_IGNORE_SRGB,
&metadata,
image
)
);
}
if (isCompress)
{
ScratchImage compressedImage{};
if (!IsCompressed(metadata.format) && path.extension() != ".hdr" && path.extension() != ".dds")
{
DirectX::TexMetadata tempMetadata = metadata;
// DXGI_FORMAT_BC1_UNORM_SRGB (== DXT1, 감마 디코드 라벨)
Win32::ThrowIfFailed(
// ★ _SRGB 라벨을 단다. isCompress 가 켜지는 자리는 baseColorMap
// 하나뿐이고(FinalizeMaterialRuntime · MaterialResolver 모두
// 그 property 에서만 true 를 넘긴다), 그 텍스처의 바이트는
// sRGB 로 인코딩돼 있다. 예전처럼 BC1_UNORM 으로 라벨하면
// 샘플러가 감마 디코드를 하지 않아 셰이더가 받는 알베도가
// sRGB 값 그대로였다 — 밝고 탈색된 그림의 legacy 경로판이다.
// 아래 TEX_COMPRESS_SRGB 도 같은 전제를 이미 깔고 있었다.
DirectX::Compress(
image.GetImages(),
image.GetImageCount(),
image.GetMetadata(),
DXGI_FORMAT_BC1_UNORM_SRGB,
TEX_COMPRESS_SRGB | TEX_COMPRESS_DITHER | TEX_COMPRESS_UNIFORM,
0.5f,
compressedImage
)
);
metadata = compressedImage.GetMetadata(); // 메타데이터 갱신
image = std::move(compressedImage); // 압축된 이미지로 교체
}
}
const float imageWidth = float(image.GetMetadata().width);
const float imageHeight = float(image.GetMetadata().height);
// image 를 옮기기 전에 읽어 둔다 — 옮긴 뒤로는 원본이 비어 있다.
// (코덱 산출물을 복사하지 않고 그대로 넘기는 것이 축 A 의 요점이다)
const bool hasAlpha = !image.IsAlphaAllOpaque();
std::shared_ptr<CodecImage> codecImage = TextureMakeCodecImage(std::move(image));
if (!codecImage) return nullptr;
auto texture = std::make_shared<Texture>();
// ★ DX11 SRV 생성 제거 (T6) - 위 LoadFormPath의 주석과 같은 이유다.
texture->m_textureType = TextureType::ImageTexture;
texture->m_size = { imageWidth, imageHeight };
texture->m_isTextureAlpha = hasAlpha;
// 압축까지 끝난 최종 이미지를 캐시가 가져가도록 남긴다(T1).
// 예전에는 여기서 버렸고 DX12는 방금 만든 DX11 텍스처에서 되읽었다.
texture->m_codecImage = std::move(codecImage);
return texture;
}
std::shared_ptr<Texture> Texture::LoadSharedFromMemory(
std::span<const std::byte> bytes, bool isCompress)
{
ScratchImage image{};
TexMetadata metadata{};
// DDS/HDR 는 LoadSharedFromPath 와 같이 재압축하지 않는다.
bool alreadyFinal = false;
if (!TextureDecodeImageBytes(bytes, metadata, image, alreadyFinal)) return nullptr;
if (isCompress && !alreadyFinal && !IsCompressed(metadata.format))
{
ScratchImage compressedImage{};
// DXGI_FORMAT_BC1_UNORM_SRGB (== DXT1, 감마 디코드 라벨) — LoadSharedFromPath 와 같은 정책.
if (SUCCEEDED(DirectX::Compress(image.GetImages(), image.GetImageCount(),
image.GetMetadata(), DXGI_FORMAT_BC1_UNORM_SRGB,
TEX_COMPRESS_SRGB | TEX_COMPRESS_DITHER | TEX_COMPRESS_UNIFORM,
0.5f, compressedImage)))
{
metadata = compressedImage.GetMetadata();
image = std::move(compressedImage);
}
}
const float imageWidth = float(image.GetMetadata().width);
const float imageHeight = float(image.GetMetadata().height);
// image 를 옮기기 전에 읽어 둔다 — 옮긴 뒤로는 원본이 비어 있다.
// (코덱 산출물을 복사하지 않고 그대로 넘기는 것이 축 A 의 요점이다)
const bool hasAlpha = !image.IsAlphaAllOpaque();
std::shared_ptr<CodecImage> codecImage = TextureMakeCodecImage(std::move(image));
if (!codecImage) return nullptr;
auto texture = std::make_shared<Texture>();
texture->m_textureType = TextureType::ImageTexture;
texture->m_size = { imageWidth, imageHeight };
texture->m_isTextureAlpha = hasAlpha;
texture->m_codecImage = std::move(codecImage);
return texture;
}
std::unique_ptr<Texture> Texture::LoadManagedFromPath(const file::path& path, bool isCompress)
{
file::path matPath = PathFinder::RelativeToMaterial(path.string());
if (!file::exists(path) && !file::exists(matPath))
{
return nullptr;
}
file::path preparePath{};
if (file::exists(matPath))
{
preparePath = matPath;
}
else
{
preparePath = path;
}
ScratchImage image{};
TexMetadata metadata{};
Benchmark banch3;
if (path.extension() == ".dds")
{
//load dds
Win32::ThrowIfFailed(
LoadFromDDSFile(
preparePath.c_str(),
DDS_FLAGS_FORCE_RGB,
&metadata,
image
)
);
}
else if (path.extension() == ".tga")
{
//load tga
Win32::ThrowIfFailed(
LoadFromTGAFile(
preparePath.c_str(),
&metadata,
image
)
);
}
else if (path.extension() == ".hdr")
{
//load hdr
Win32::ThrowIfFailed(
LoadFromHDRFile(
preparePath.c_str(),
&metadata,
image
)
);
}
else
{
//load wic
Win32::ThrowIfFailed(
LoadFromWICFile(
preparePath.c_str(),
WIC_FLAGS_IGNORE_SRGB,
&metadata,
image
)
);
}
if (isCompress)
{
ScratchImage compressedImage{};
if (!IsCompressed(metadata.format) && path.extension() != ".hdr" && path.extension() != ".dds")
{
DirectX::TexMetadata tempMetadata = metadata;
// DXGI_FORMAT_BC1_UNORM (== DXT1)
Win32::ThrowIfFailed(
DirectX::Compress(
image.GetImages(),
image.GetImageCount(),
metadata,
DXGI_FORMAT_BC1_UNORM,
TEX_COMPRESS_PARALLEL,
0.5f,
compressedImage
)
);
metadata = compressedImage.GetMetadata(); // 메타데이터 갱신
image = std::move(compressedImage); // 압축된 이미지로 교체
}
}
// image 를 옮기기 전에 읽어 둔다 — 옮긴 뒤로는 원본이 비어 있다.
// (코덱 산출물을 복사하지 않고 그대로 넘기는 것이 축 A 의 요점이다)
const bool hasAlpha = !image.IsAlphaAllOpaque();
std::shared_ptr<CodecImage> codecImage = TextureMakeCodecImage(std::move(image));
if (!codecImage) return nullptr;
auto texture = std::make_unique<Texture>();
// ★ DX11 SRV 생성 제거 (T6) - 위 LoadFormPath의 주석과 같은 이유다.
texture->m_textureType = TextureType::ImageTexture;
texture->m_size = { float(metadata.width),float(metadata.height) };
texture->m_isTextureAlpha = hasAlpha;
// 압축까지 끝난 최종 이미지를 캐시가 가져가도록 남긴다(T1).
// 예전에는 여기서 버렸고 DX12는 방금 만든 DX11 텍스처에서 되읽었다.
texture->m_codecImage = std::move(codecImage);
return texture;
}
// ── cook 경로의 디코드 창구 (축 A) ──────────────────────────────────────
//
// ★ 이 함수의 몸통은 ModelAssetGeneration::CopyTexturePixels 에 있던 것이다.
// 그쪽이 필요한 것은 "인코딩된 바이트 -> 중립 RGBA8" 하나였는데, 그것
// 때문에 DirectXTex 의 Convert·Decompress·IsSRGB 를 직접 불렀다. 디코더를
// 갈아 끼우려면 봐야 할 파일이 둘이 되는 자리였다.
bool Texture::DecodeToRgba8(std::span<const std::byte> bytes,
TextureImage& outImage, std::string& outFailure)
{
ScratchImage image{};
TexMetadata metadata{};
bool alreadyFinal = false;
if (!TextureDecodeImageBytes(bytes, metadata, image, alreadyFinal))
{
outFailure = "image decoder가 픽셀을 만들지 못했다.";
return false;
}
// ── 색공간은 라벨로만 정한다 ──────────────────────────────────
//
// ★ 여기 있던 코드는 target 을 semantic(_UNORM_SRGB)으로 잡고
// Convert 를 불렀다. DirectXTex 는 **출력 포맷이 IsSRGB 면
// SRGB_OUT 이 기본 on** 이라고 스스로 문서화한다
// (DirectXTex.h "if the output format type is IsSRGB(), then
// SRGB_OUT is on by default"). 입력은 _UNORM 이라 SRGB_IN 이
// 꺼진 채로, 이미 sRGB 로 인코딩된 PNG 바이트에 linear→sRGB
// 인코드가 한 번 더 먹었다.
//
// 런타임 SRV 는 호출자가 정하는 semantic 포맷을 쓰므로 하드웨어가
// 디코드를 한 번 한다. 두 연산이 정확히 상쇄돼 **셰이더가 받는
// 알베도가 sRGB 바이트값 그대로**였다 — Gunner 본체 텍스처
// 기준 밝기 2.1~3.7 배, 채도비 2.96 → 1.70 (43% 탈색).
//
// 고침은 "바이트를 건드리지 않는다"다. 레이아웃만 RGBA8 로
// 맞추되 목표 포맷의 sRGB 성질을 **소스와 같게** 두면
// DirectXTex 가 전달 함수에 손대지 않는다. 최종 라벨은 호출자가
// 색공간으로 따로 정한다.
const DXGI_FORMAT layoutTarget = IsSRGB(metadata.format)
? DXGI_FORMAT_R8G8B8A8_UNORM_SRGB
: DXGI_FORMAT_R8G8B8A8_UNORM;
ScratchImage converted;
const ScratchImage* finalImage = ℑ
HRESULT conversion = S_OK;
if (IsCompressed(metadata.format))
{
conversion = Decompress(image.GetImages(), image.GetImageCount(),
metadata, layoutTarget, converted);
finalImage = &converted;
}
else if (metadata.format != layoutTarget)
{
conversion = Convert(image.GetImages(), image.GetImageCount(), metadata,
layoutTarget, TEX_FILTER_DEFAULT, TEX_THRESHOLD_DEFAULT, converted);
finalImage = &converted;
}
if (FAILED(conversion) || 0 == finalImage->GetImageCount())
{
outFailure = "image를 backend-neutral RGBA8로 변환하지 못했다.";
return false;
}
const TexMetadata& finalMetadata = finalImage->GetMetadata();
if (TEX_DIMENSION_TEXTURE2D != finalMetadata.dimension
|| 0 == finalMetadata.width || 0 == finalMetadata.height
|| 0 == finalMetadata.mipLevels || 0 == finalMetadata.arraySize
|| finalMetadata.width > UINT32_MAX || finalMetadata.height > UINT32_MAX)
{
outFailure = "2D texture descriptor 범위를 벗어났다.";
return false;
}
const RHIFormat format = TextureDecodedFormatToRHI(finalMetadata.format);
if (RHIFormat::Unknown == format
|| !TextureCopyScratchToImage(*finalImage, format, outImage))
{
outFailure = "decoded texture subresource가 비었다.";
return false;
}
return true;
}
// ★ DX11 생성자·뷰 이관을 걷어낸 뒤의 수명 (T6, 2026-08-08).
//
// 예전 이동 생성자는 ID3D11 핸들 다섯과 desc를 옮기고, 화면 리사이즈
// 델리게이트 둘을 해제했다가 새 객체로 다시 걸었다. 그 전부가 DX11
// 자원과 화면 추종 정책의 것이라 함께 사라졌다.
//
// 남은 것은 CPU 자료뿐이고, 그것은 shared_ptr과 값이라 옮기기만 하면 된다.
Texture::Texture(Texture&& texture) noexcept
{
m_codecImage = std::move(texture.m_codecImage);
m_samplingFormat = texture.m_samplingFormat;
m_assetId = texture.m_assetId;
m_textureType = texture.m_textureType;
m_name = std::move(texture.m_name);
m_extension = std::move(texture.m_extension);
m_size = texture.m_size;
m_isTextureAlpha = texture.m_isTextureAlpha;
texture.m_textureType = TextureType::Unknown;
texture.m_size = {};
texture.m_isTextureAlpha = false;
}
Texture::~Texture() = default;
math::vector2 Texture::GetImageSize() const
{
// ★ 예전에는 m_sizeRatio로 나눴다 (T6에서 정리).
// 그 비율은 '화면의 1/N 해상도로 따라가는 렌더 타깃'을 위한 것이었고,
// 화면 추종 정책과 함께 사라졌다. 파일에서 읽은 텍스처의 비율은 늘
// 1이었으므로 이 함수가 돌려주던 값은 그대로다.
return m_size;
}