forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvtf.cpp
3497 lines (2992 loc) · 96.4 KB
/
vtf.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: The VTF file format I/O class to help simplify access to VTF files
//
//=====================================================================================//
#undef fopen
#include "bitmap/imageformat.h"
#include "cvtf.h"
#include "utlbuffer.h"
#include "tier0/dbg.h"
#include "mathlib/vector.h"
#include "mathlib/mathlib.h"
#include "tier1/strtools.h"
#include "tier0/mem.h"
#include "s3tc_decode.h"
#include "utlvector.h"
#include "vprof_telemetry.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// byteswap data descriptions
BEGIN_BYTESWAP_DATADESC( VTFFileBaseHeader_t )
DEFINE_ARRAY( fileTypeString, FIELD_CHARACTER, 4 ),
DEFINE_ARRAY( version, FIELD_INTEGER, 2 ),
DEFINE_FIELD( headerSize, FIELD_INTEGER ),
END_DATADESC()
BEGIN_BYTESWAP_DATADESC( VTFFileHeaderV7_1_t )
DEFINE_ARRAY( fileTypeString, FIELD_CHARACTER, 4 ),
DEFINE_ARRAY( version, FIELD_INTEGER, 2 ),
DEFINE_FIELD( headerSize, FIELD_INTEGER ),
DEFINE_FIELD( width, FIELD_SHORT ),
DEFINE_FIELD( height, FIELD_SHORT ),
DEFINE_FIELD( flags, FIELD_INTEGER ),
DEFINE_FIELD( numFrames, FIELD_SHORT ),
DEFINE_FIELD( startFrame, FIELD_SHORT ),
DEFINE_FIELD( reflectivity, FIELD_VECTOR ),
DEFINE_FIELD( bumpScale, FIELD_FLOAT ),
DEFINE_FIELD( imageFormat, FIELD_INTEGER ),
DEFINE_FIELD( numMipLevels, FIELD_CHARACTER ),
DEFINE_FIELD( lowResImageFormat, FIELD_INTEGER ),
DEFINE_FIELD( lowResImageWidth, FIELD_CHARACTER ),
DEFINE_FIELD( lowResImageHeight, FIELD_CHARACTER ),
END_DATADESC()
BEGIN_BYTESWAP_DATADESC( VTFFileHeaderV7_2_t )
DEFINE_ARRAY( fileTypeString, FIELD_CHARACTER, 4 ),
DEFINE_ARRAY( version, FIELD_INTEGER, 2 ),
DEFINE_FIELD( headerSize, FIELD_INTEGER ),
DEFINE_FIELD( width, FIELD_SHORT ),
DEFINE_FIELD( height, FIELD_SHORT ),
DEFINE_FIELD( flags, FIELD_INTEGER ),
DEFINE_FIELD( numFrames, FIELD_SHORT ),
DEFINE_FIELD( startFrame, FIELD_SHORT ),
DEFINE_FIELD( reflectivity, FIELD_VECTOR ),
DEFINE_FIELD( bumpScale, FIELD_FLOAT ),
DEFINE_FIELD( imageFormat, FIELD_INTEGER ),
DEFINE_FIELD( numMipLevels, FIELD_CHARACTER ),
DEFINE_FIELD( lowResImageFormat, FIELD_INTEGER ),
DEFINE_FIELD( lowResImageWidth, FIELD_CHARACTER ),
DEFINE_FIELD( lowResImageHeight, FIELD_CHARACTER ),
DEFINE_FIELD( depth, FIELD_SHORT ),
END_DATADESC()
BEGIN_BYTESWAP_DATADESC( VTFFileHeaderV7_3_t )
DEFINE_ARRAY( fileTypeString, FIELD_CHARACTER, 4 ),
DEFINE_ARRAY( version, FIELD_INTEGER, 2 ),
DEFINE_FIELD( headerSize, FIELD_INTEGER ),
DEFINE_FIELD( width, FIELD_SHORT ),
DEFINE_FIELD( height, FIELD_SHORT ),
DEFINE_FIELD( flags, FIELD_INTEGER ),
DEFINE_FIELD( numFrames, FIELD_SHORT ),
DEFINE_FIELD( startFrame, FIELD_SHORT ),
DEFINE_FIELD( reflectivity, FIELD_VECTOR ),
DEFINE_FIELD( bumpScale, FIELD_FLOAT ),
DEFINE_FIELD( imageFormat, FIELD_INTEGER ),
DEFINE_FIELD( numMipLevels, FIELD_CHARACTER ),
DEFINE_FIELD( lowResImageFormat, FIELD_INTEGER ),
DEFINE_FIELD( lowResImageWidth, FIELD_CHARACTER ),
DEFINE_FIELD( lowResImageHeight, FIELD_CHARACTER ),
DEFINE_FIELD( depth, FIELD_SHORT ),
DEFINE_FIELD( numResources, FIELD_INTEGER ),
END_DATADESC()
BEGIN_BYTESWAP_DATADESC_( VTFFileHeaderX360_t, VTFFileBaseHeader_t )
DEFINE_FIELD( flags, FIELD_INTEGER ),
DEFINE_FIELD( width, FIELD_SHORT ),
DEFINE_FIELD( height, FIELD_SHORT ),
DEFINE_FIELD( depth, FIELD_SHORT ),
DEFINE_FIELD( numFrames, FIELD_SHORT ),
DEFINE_FIELD( preloadDataSize, FIELD_SHORT ),
DEFINE_FIELD( mipSkipCount, FIELD_CHARACTER ),
DEFINE_FIELD( numResources, FIELD_CHARACTER ),
DEFINE_FIELD( reflectivity, FIELD_VECTOR ),
DEFINE_FIELD( bumpScale, FIELD_FLOAT ),
DEFINE_FIELD( imageFormat, FIELD_INTEGER ),
DEFINE_ARRAY( lowResImageSample, FIELD_CHARACTER, 4 ),
DEFINE_FIELD( compressedSize, FIELD_INTEGER ),
END_DATADESC()
#if defined( POSIX ) || defined( _X360 )
// stub functions
const char* S3TC_GetBlock(
const void *pCompressed,
ImageFormat format,
int nBlocksWide, // How many blocks wide is the image (pixels wide / 4).
int xBlock,
int yBlock )
{
return NULL;
}
char* S3TC_GetBlock(
void *pCompressed,
ImageFormat format,
int nBlocksWide, // How many blocks wide is the image (pixels wide / 4).
int xBlock,
int yBlock )
{
return NULL;
}
S3PaletteIndex S3TC_GetPaletteIndex(
unsigned char *pFaceData,
ImageFormat format,
int imageWidth,
int x,
int y )
{
S3PaletteIndex nullPalette;
memset(&nullPalette, 0x0, sizeof(nullPalette));
return nullPalette;
}
// Merge the two palettes and copy the colors
void S3TC_MergeBlocks(
char **blocks,
S3RGBA **pOriginals,
int nBlocks,
int lPitch, // (in BYTES)
ImageFormat format
)
{
}
// Note: width, x, and y are in texels, not S3 blocks.
void S3TC_SetPaletteIndex(
unsigned char *pFaceData,
ImageFormat format,
int imageWidth,
int x,
int y,
S3PaletteIndex paletteIndex )
{
}
#endif
// This gives a vertex number to each of the 4 verts on each face.
// We use this to match the verts and determine which edges need to be blended together.
// The vert ordering is lower-left, top-left, top-right, bottom-right.
int g_leftFaceVerts[4] = { 2, 6, 7, 3 };
int g_frontFaceVerts[4] = { 2, 3, 5, 4 };
int g_downFaceVerts[4] = { 4, 0, 6, 2 };
int g_rightFaceVerts[4] = { 5, 1, 0, 4 };
int g_backFaceVerts[4] = { 7, 6, 0, 1 };
int g_upFaceVerts[4] = { 3, 7, 1, 5 };
int *g_FaceVerts[6] =
{
g_rightFaceVerts,
g_leftFaceVerts,
g_backFaceVerts,
g_frontFaceVerts,
g_upFaceVerts,
g_downFaceVerts
};
// For skyboxes..
// These were constructed for the engine skybox, which looks like this
// (assuming X goes forward, Y goes left, and Z goes up).
//
// 6 ------------- 5
// / /
// / | / |
// / | / |
// 2 ------------- 1 |
// | |
// | |
// | 7 ------|------ 4
// | / | /
// | / | /
// / /
// 3 ------------- 0
//
int g_skybox_rightFaceVerts[4] = { 7, 6, 5, 4 };
int g_skybox_leftFaceVerts[4] = { 0, 1, 2, 3 };
int g_skybox_backFaceVerts[4] = { 3, 2, 6, 7 };
int g_skybox_frontFaceVerts[4] = { 4, 5, 1, 0 };
int g_skybox_upFaceVerts[4] = { 6, 2, 1, 5 };
int g_skybox_downFaceVerts[4] = { 3, 7, 4, 0 };
int *g_skybox_FaceVerts[6] =
{
g_skybox_rightFaceVerts,
g_skybox_leftFaceVerts,
g_skybox_backFaceVerts,
g_skybox_frontFaceVerts,
g_skybox_upFaceVerts,
g_skybox_downFaceVerts
};
//-----------------------------------------------------------------------------
// Class factory
//-----------------------------------------------------------------------------
IVTFTexture *CreateVTFTexture()
{
return new CVTFTexture;
}
void DestroyVTFTexture( IVTFTexture *pTexture )
{
CVTFTexture *pTex = static_cast<CVTFTexture*>(pTexture);
if ( pTex )
{
delete pTex;
}
}
//-----------------------------------------------------------------------------
// Allows us to only load in the first little bit of the VTF file to get info
//-----------------------------------------------------------------------------
int VTFFileHeaderSize( int nMajorVersion, int nMinorVersion )
{
if ( nMajorVersion == -1 )
{
nMajorVersion = VTF_MAJOR_VERSION;
}
if ( nMinorVersion == -1 )
{
nMinorVersion = VTF_MINOR_VERSION;
}
switch ( nMajorVersion )
{
case VTF_MAJOR_VERSION:
switch ( nMinorVersion )
{
case 0: // fall through
case 1:
return sizeof( VTFFileHeaderV7_1_t );
case 2:
return sizeof( VTFFileHeaderV7_2_t );
case 3:
return sizeof( VTFFileHeaderV7_3_t ) + sizeof( ResourceEntryInfo ) * MAX_RSRC_DICTIONARY_ENTRIES;
case 4:
case VTF_MINOR_VERSION:
int size1 = sizeof( VTFFileHeader_t );
int size2 = sizeof( ResourceEntryInfo ) * MAX_RSRC_DICTIONARY_ENTRIES;
int result = size1 + size2;
//printf("\n VTFFileHeaderSize (%i %i) is %i + %i -> %i",nMajorVersion,nMinorVersion, size1, size2, result );
return result;
}
break;
case VTF_X360_MAJOR_VERSION:
return sizeof( VTFFileHeaderX360_t ) + sizeof( ResourceEntryInfo ) * MAX_X360_RSRC_DICTIONARY_ENTRIES;
}
return 0;
}
//-----------------------------------------------------------------------------
// Constructor, destructor
//-----------------------------------------------------------------------------
CVTFTexture::CVTFTexture()
{
m_nVersion[0] = 0;
m_nVersion[1] = 0;
m_nWidth = 0;
m_nHeight = 0;
m_nDepth = 1;
m_Format = IMAGE_FORMAT_UNKNOWN;
m_nMipCount = 0;
m_nFaceCount = 0;
m_nFrameCount = 0;
// FIXME: Is the start frame needed?
m_iStartFrame = 0;
m_flAlphaThreshhold = -1.0f;
m_flAlphaHiFreqThreshhold = -1.0f;
m_flBumpScale = 1.0f;
m_vecReflectivity.Init( 1.0, 1.0, 1.0f );
m_nFlags = 0;
m_pImageData = NULL;
m_nImageAllocSize = 0;
// LowRes data
m_LowResImageFormat = IMAGE_FORMAT_UNKNOWN;
m_nLowResImageWidth = 0;
m_nLowResImageHeight = 0;
m_pLowResImageData = NULL;
m_nLowResImageAllocSize = 0;
#if defined( _X360 )
m_nMipSkipCount = 0;
*(unsigned int *)m_LowResImageSample = 0;
#endif
Assert( m_arrResourcesInfo.Count() == 0 );
Assert( m_arrResourcesData.Count() == 0 );
Assert( m_arrResourcesData_ForReuse.Count() == 0 );
memset( &m_Options, 0, sizeof( m_Options ) );
m_Options.cbSize = sizeof( m_Options );
m_nFinestMipmapLevel = 0;
m_nCoarsestMipmapLevel = 0;
}
CVTFTexture::~CVTFTexture()
{
Shutdown();
}
//-----------------------------------------------------------------------------
// Compute the mip count based on the size + flags
//-----------------------------------------------------------------------------
int CVTFTexture::ComputeMipCount() const
{
if ( IsX360() && ( m_nVersion[0] == VTF_X360_MAJOR_VERSION ) && ( m_nFlags & TEXTUREFLAGS_NOMIP ) )
{
// 360 vtf format culled unused mips at conversion time
return 1;
}
// NOTE: No matter what, all mip levels should be created because
// we have to worry about various fallbacks
return ImageLoader::GetNumMipMapLevels( m_nWidth, m_nHeight, m_nDepth );
}
//-----------------------------------------------------------------------------
// Allocate data blocks with an eye toward re-using memory
//-----------------------------------------------------------------------------
static bool GenericAllocateReusableData( unsigned char **ppData, int *pNumAllocated, int numRequested )
{
// If we're asking for memory and we have way more than we expect, free some.
if ( *pNumAllocated < numRequested || ( numRequested > 0 && *pNumAllocated > 16 * numRequested ) )
{
delete [] *ppData;
*ppData = new unsigned char[ numRequested ];
if ( *ppData )
{
*pNumAllocated = numRequested;
return true;
}
*pNumAllocated = 0;
return false;
}
return true;
}
bool CVTFTexture::AllocateImageData( int nMemorySize )
{
return GenericAllocateReusableData( &m_pImageData, &m_nImageAllocSize, nMemorySize );
}
bool CVTFTexture::ResourceMemorySection::AllocateData( int nMemorySize )
{
if ( GenericAllocateReusableData( &m_pData, &m_nDataAllocSize, nMemorySize ) )
{
m_nDataLength = nMemorySize;
return true;
}
return false;
}
bool CVTFTexture::AllocateLowResImageData( int nMemorySize )
{
return GenericAllocateReusableData( &m_pLowResImageData, &m_nLowResImageAllocSize, nMemorySize );
}
inline bool IsMultipleOf4( int value )
{
// NOTE: This catches powers of 2 less than 4 also
return ( value <= 2 ) || ( (value & 0x3) == 0 );
}
//-----------------------------------------------------------------------------
// Initialization
//-----------------------------------------------------------------------------
bool CVTFTexture::Init( int nWidth, int nHeight, int nDepth, ImageFormat fmt, int iFlags, int iFrameCount, int nForceMipCount )
{
if ( nDepth == 0 )
{
nDepth = 1;
}
if (iFlags & TEXTUREFLAGS_ENVMAP)
{
if (nWidth != nHeight)
{
Warning( "Height and width must be equal for cubemaps!\n" );
return false;
}
if (nDepth != 1)
{
Warning( "Depth must be 1 for cubemaps!\n" );
return false;
}
}
if ( ( fmt == IMAGE_FORMAT_DXT1 ) || ( fmt == IMAGE_FORMAT_DXT3 ) || ( fmt == IMAGE_FORMAT_DXT5 ) ||
( fmt == IMAGE_FORMAT_DXT1_RUNTIME ) || ( fmt == IMAGE_FORMAT_DXT5_RUNTIME ) )
{
if ( !IsMultipleOf4( nWidth ) || !IsMultipleOf4( nHeight ) || !IsMultipleOf4( nDepth ) )
{
Warning( "Image dimensions must be multiple of 4!\n" );
return false;
}
}
if ( fmt == IMAGE_FORMAT_DEFAULT )
{
fmt = IMAGE_FORMAT_RGBA8888;
}
m_nWidth = nWidth;
m_nHeight = nHeight;
m_nDepth = nDepth;
m_Format = fmt;
m_nFlags = iFlags;
// THIS CAUSED A BUG!!! We want all of the mip levels in the vtf file even with nomip in case we have lod.
// NOTE: But we don't want more than 1 mip level for procedural textures
if ( (iFlags & (TEXTUREFLAGS_NOMIP | TEXTUREFLAGS_PROCEDURAL)) == (TEXTUREFLAGS_NOMIP | TEXTUREFLAGS_PROCEDURAL) )
{
nForceMipCount = 1;
}
if ( nForceMipCount == -1 )
{
m_nMipCount = ComputeMipCount();
}
else
{
m_nMipCount = nForceMipCount;
}
m_nFrameCount = iFrameCount;
m_nFaceCount = (iFlags & TEXTUREFLAGS_ENVMAP) ? CUBEMAP_FACE_COUNT : 1;
#if defined( _X360 )
m_nMipSkipCount = 0;
#endif
// Need to do this because Shutdown deallocates the low-res image
m_nLowResImageWidth = m_nLowResImageHeight = 0;
// Allocate me some bits!
int iMemorySize = ComputeTotalSize();
if ( !AllocateImageData( iMemorySize ) )
return false;
// As soon as we have image indicate so in the resources
if ( iMemorySize )
FindOrCreateResourceEntryInfo( VTF_LEGACY_RSRC_IMAGE );
else
RemoveResourceEntryInfo( VTF_LEGACY_RSRC_IMAGE );
return true;
}
//-----------------------------------------------------------------------------
// Methods to initialize the low-res image
//-----------------------------------------------------------------------------
void CVTFTexture::InitLowResImage( int nWidth, int nHeight, ImageFormat fmt )
{
m_nLowResImageWidth = nWidth;
m_nLowResImageHeight = nHeight;
m_LowResImageFormat = fmt;
// Allocate low-res bits
int iLowResImageSize = ImageLoader::GetMemRequired( m_nLowResImageWidth,
m_nLowResImageHeight, 1, m_LowResImageFormat, false );
if ( !AllocateLowResImageData( iLowResImageSize ) )
return;
// As soon as we have low-res image indicate so in the resources
if ( iLowResImageSize )
FindOrCreateResourceEntryInfo( VTF_LEGACY_RSRC_LOW_RES_IMAGE );
else
RemoveResourceEntryInfo( VTF_LEGACY_RSRC_LOW_RES_IMAGE );
}
//-----------------------------------------------------------------------------
// Methods to set other texture fields
//-----------------------------------------------------------------------------
void CVTFTexture::SetBumpScale( float flScale )
{
m_flBumpScale = flScale;
}
void CVTFTexture::SetReflectivity( const Vector &vecReflectivity )
{
VectorCopy( vecReflectivity, m_vecReflectivity );
}
// Sets threshhold values for alphatest mipmapping
void CVTFTexture::SetAlphaTestThreshholds( float flBase, float flHighFreq )
{
m_flAlphaThreshhold = flBase;
m_flAlphaHiFreqThreshhold = flHighFreq;
}
//-----------------------------------------------------------------------------
// Release and reset the resources.
//-----------------------------------------------------------------------------
void CVTFTexture::ReleaseResources()
{
m_arrResourcesInfo.RemoveAll();
for ( ResourceMemorySection *pRms = m_arrResourcesData.Base(),
*pRmsEnd = pRms + m_arrResourcesData.Count(); pRms < pRmsEnd; ++pRms )
{
delete [] pRms->m_pData;
}
m_arrResourcesData.RemoveAll();
for ( ResourceMemorySection *pRms = m_arrResourcesData_ForReuse.Base(),
*pRmsEnd = pRms + m_arrResourcesData_ForReuse.Count(); pRms < pRmsEnd; ++pRms )
{
delete [] pRms->m_pData;
}
m_arrResourcesData_ForReuse.RemoveAll();
}
//-----------------------------------------------------------------------------
// Shutdown
//-----------------------------------------------------------------------------
void CVTFTexture::Shutdown()
{
#if defined( _X360 )
// must be first to ensure X360 aliased pointers are unhooked, otherwise memory corruption
ReleaseImageMemory();
#endif
delete[] m_pImageData;
m_pImageData = NULL;
m_nImageAllocSize = 0;
delete[] m_pLowResImageData;
m_pLowResImageData = NULL;
m_nLowResImageAllocSize = 0;
ReleaseResources();
}
//-----------------------------------------------------------------------------
// These are methods to help with optimization of file access
//-----------------------------------------------------------------------------
void CVTFTexture::LowResFileInfo( int *pStartLocation, int *pSizeInBytes ) const
{
// Once the header is read in, they indicate where to start reading
// other data, and how many bytes to read....
if ( ResourceEntryInfo const *pLowResData = FindResourceEntryInfo( VTF_LEGACY_RSRC_LOW_RES_IMAGE ) )
{
*pStartLocation = pLowResData->resData;
*pSizeInBytes = ImageLoader::GetMemRequired( m_nLowResImageWidth,
m_nLowResImageHeight, 1, m_LowResImageFormat, false );
}
else
{
*pStartLocation = 0;
*pSizeInBytes = 0;
}
}
void CVTFTexture::ImageFileInfo( int nFrame, int nFace, int nMipLevel, int *pStartLocation, int *pSizeInBytes) const
{
int i;
int iMipWidth;
int iMipHeight;
int iMipDepth;
ResourceEntryInfo const *pImageDataInfo = FindResourceEntryInfo( VTF_LEGACY_RSRC_IMAGE );
if ( pImageDataInfo == NULL )
{
// This should never happen for real, but can happen if someone intentionally fed us a bad VTF.
Assert( pImageDataInfo );
( *pStartLocation ) = 0;
( *pSizeInBytes ) = 0;
return;
}
// The image data start offset
int nOffset = pImageDataInfo->resData;
// get to the right miplevel
for( i = m_nMipCount - 1; i > nMipLevel; --i )
{
ComputeMipLevelDimensions( i, &iMipWidth, &iMipHeight, &iMipDepth );
int iMipLevelSize = ImageLoader::GetMemRequired( iMipWidth, iMipHeight, iMipDepth, m_Format, false );
nOffset += iMipLevelSize * m_nFrameCount * m_nFaceCount;
}
// get to the right frame
ComputeMipLevelDimensions( nMipLevel, &iMipWidth, &iMipHeight, &iMipDepth );
int nFaceSize = ImageLoader::GetMemRequired( iMipWidth, iMipHeight, iMipDepth, m_Format, false );
// For backwards compatibility, we don't read in the spheremap fallback on
// older format .VTF files...
int nFacesToRead = m_nFaceCount;
if ( IsCubeMap() )
{
if ((m_nVersion[0] == 7) && (m_nVersion[1] < 1 || m_nVersion[1] > 4))
{
nFacesToRead = 6;
if (nFace == CUBEMAP_FACE_SPHEREMAP)
{
--nFace;
}
}
}
int nFrameSize = nFacesToRead * nFaceSize;
nOffset += nFrameSize * nFrame;
// get to the right face
nOffset += nFace * nFaceSize;
*pStartLocation = nOffset;
*pSizeInBytes = nFaceSize;
}
int CVTFTexture::FileSize( int nMipSkipCount ) const
{
ResourceEntryInfo const *pImageDataInfo = FindResourceEntryInfo( VTF_LEGACY_RSRC_IMAGE );
// Can be null when someone gives us an intentionally malformed VTF.
if ( pImageDataInfo == NULL )
{
// Still do the assert so we can catch this in debug--we don't expect this for well formed files.
Assert( pImageDataInfo != NULL );
return 0;
}
int nOffset = pImageDataInfo->resData;
int nFaceSize = ComputeFaceSize( nMipSkipCount );
int nImageSize = nFaceSize * m_nFaceCount * m_nFrameCount;
return nOffset + nImageSize;
}
//-----------------------------------------------------------------------------
// Unserialization of low-res data
//-----------------------------------------------------------------------------
bool CVTFTexture::LoadLowResData( CUtlBuffer &buf )
{
// Allocate low-res bits
InitLowResImage( m_nLowResImageWidth, m_nLowResImageHeight, m_LowResImageFormat );
int nLowResImageSize = ImageLoader::GetMemRequired( m_nLowResImageWidth,
m_nLowResImageHeight, 1, m_LowResImageFormat, false );
buf.Get( m_pLowResImageData, nLowResImageSize );
bool bValid = buf.IsValid();
return bValid;
}
//-----------------------------------------------------------------------------
// Unserialization of image data
//-----------------------------------------------------------------------------
bool CVTFTexture::LoadImageData( CUtlBuffer &buf, const VTFFileHeader_t &header, int nSkipMipLevels )
{
// Fix up the mip count + size based on how many mip levels we skip...
if (nSkipMipLevels > 0)
{
Assert( m_nMipCount > nSkipMipLevels );
if (header.numMipLevels < nSkipMipLevels)
{
// NOTE: This can only happen with older format .vtf files
Warning("Warning! Encountered old format VTF file; please rebuild it!\n");
return false;
}
ComputeMipLevelDimensions( nSkipMipLevels, &m_nWidth, &m_nHeight, &m_nDepth );
m_nMipCount -= nSkipMipLevels;
}
// read the texture image (including mipmaps if they are there and needed.)
int iImageSize = ComputeFaceSize();
iImageSize *= m_nFaceCount * m_nFrameCount;
if ( !AllocateImageData( iImageSize ) )
return false;
// NOTE: The mip levels are stored ascending from smallest (1x1) to largest (NxN)
// in order to allow for truncated reads of the minimal required data
// NOTE: I checked in a bad version 4 where it stripped out the spheremap.
// To make it all work, need to check for that bad case.
bool bNoSkip = false;
if ( IsCubeMap() && ( header.version[0] == 7 ) && ( header.version[1] == 4 ) )
{
int nBytesRemaining = buf.TellMaxPut() - buf.TellGet();
int nFileSize = ComputeFaceSize( nSkipMipLevels ) * m_nFaceCount * m_nFrameCount;
if ( nBytesRemaining == nFileSize )
{
bNoSkip = true;
}
}
int nGet = buf.TellGet();
retryCubemapLoad:
for (int iMip = m_nMipCount; --iMip >= 0; )
{
// NOTE: This is for older versions...
if ( header.numMipLevels - nSkipMipLevels <= iMip )
continue;
int iMipSize = ComputeMipSize( iMip );
for (int iFrame = 0; iFrame < m_nFrameCount; ++iFrame)
{
for (int iFace = 0; iFace < m_nFaceCount; ++iFace)
{
// printf("\n tex %p mip %i frame %i face %i size %i buf offset %i", this, iMip, iFrame, iFace, iMipSize, buf.TellGet() );
unsigned char *pMipBits = ImageData( iFrame, iFace, iMip );
buf.Get( pMipBits, iMipSize );
}
// Strip out the spheremap in older versions
if ( IsCubeMap() && !bNoSkip && ( header.version[0] == 7 ) && ( header.version[1] >= 1 ) && ( header.version[1] < 5 ) )
{
buf.SeekGet( CUtlBuffer::SEEK_CURRENT, iMipSize );
}
}
}
bool bOk = buf.IsValid();
if ( !bOk && IsCubeMap() && ( header.version[0] == 7 ) && ( header.version[1] <= 4 ) )
{
if ( !bNoSkip )
{
bNoSkip = true;
buf.SeekGet( CUtlBuffer::SEEK_HEAD, nGet );
goto retryCubemapLoad;
}
Warning( "** Encountered stale cubemap! Please rebuild the following vtf:\n" );
}
return bOk;
}
void *CVTFTexture::SetResourceData( uint32 eType, void const *pData, size_t nNumBytes )
{
Assert( ( eType & RSRCF_MASK ) == 0 );
eType &= ~RSRCF_MASK;
// Very inefficient to set less than 4 bytes of data
Assert( !nNumBytes || ( nNumBytes >= sizeof( uint32 ) ) );
if ( nNumBytes )
{
ResourceEntryInfo *pInfo = FindOrCreateResourceEntryInfo( eType );
int idx = pInfo - m_arrResourcesInfo.Base();
ResourceMemorySection &rms = m_arrResourcesData[ idx ];
if ( nNumBytes == sizeof( pInfo->resData ) )
{
// store 4 bytes directly
pInfo->eType |= RSRCF_HAS_NO_DATA_CHUNK;
if ( pData )
pInfo->resData = reinterpret_cast< const int * >( pData )[0];
return &pInfo->resData;
}
else
{
if ( !rms.AllocateData( nNumBytes ) )
{
RemoveResourceEntryInfo( eType );
return NULL;
}
if ( pData )
memcpy( rms.m_pData, pData, nNumBytes );
return rms.m_pData;
}
}
else
{
RemoveResourceEntryInfo( eType );
return NULL;
}
}
void *CVTFTexture::GetResourceData( uint32 eType, size_t *pDataSize ) const
{
Assert( ( eType & RSRCF_MASK ) == 0 );
eType &= ~RSRCF_MASK;
ResourceEntryInfo const *pInfo = FindResourceEntryInfo( eType );
if ( pInfo )
{
if ( ( pInfo->eType & RSRCF_HAS_NO_DATA_CHUNK ) == 0 )
{
int idx = pInfo - m_arrResourcesInfo.Base();
ResourceMemorySection const &rms = m_arrResourcesData[ idx ];
if ( pDataSize )
{
*pDataSize = rms.m_nDataLength;
}
return rms.m_pData;
}
else
{
if ( pDataSize )
{
*pDataSize = sizeof( pInfo->resData );
}
return (void *)&pInfo->resData;
}
}
else
{
if ( pDataSize )
*pDataSize = 0;
}
return NULL;
}
bool CVTFTexture::HasResourceEntry( uint32 eType ) const
{
return ( FindResourceEntryInfo( eType ) != NULL );
}
unsigned int CVTFTexture::GetResourceTypes( unsigned int *arrTypesBuffer, int numTypesBufferElems ) const
{
for ( ResourceEntryInfo const *pInfo = m_arrResourcesInfo.Base(),
*pInfoEnd = pInfo + m_arrResourcesInfo.Count();
numTypesBufferElems-- > 0 && pInfo < pInfoEnd; )
{
*( arrTypesBuffer++ ) = ( ( pInfo++ )->eType & ~RSRCF_MASK );
}
return m_arrResourcesInfo.Count();
}
//-----------------------------------------------------------------------------
// Serialization/Unserialization of resource data
//-----------------------------------------------------------------------------
bool CVTFTexture::ResourceMemorySection::LoadData( CUtlBuffer &buf, CByteswap &byteSwap )
{
// Read the size
int iDataSize = 0;
buf.Get( &iDataSize, sizeof( iDataSize ) );
byteSwap.SwapBufferToTargetEndian( &iDataSize );
// Read the actual data
if ( !AllocateData( iDataSize ) )
return false;
buf.Get( m_pData, iDataSize );
// Test valid
bool bValid = buf.IsValid();
return bValid;
}
bool CVTFTexture::ResourceMemorySection::WriteData( CUtlBuffer &buf ) const
{
Assert( m_nDataLength && m_pData );
int iBufSize = m_nDataLength;
buf.Put( &iBufSize, sizeof( iBufSize ) );
buf.Put( m_pData, m_nDataLength );
return buf.IsValid();
}
//-----------------------------------------------------------------------------
// Checks if the file data needs to be swapped
//-----------------------------------------------------------------------------
bool CVTFTexture::SetupByteSwap( CUtlBuffer &buf )
{
VTFFileBaseHeader_t *header = (VTFFileBaseHeader_t*)buf.PeekGet();
if ( header->version[0] == SwapLong( VTF_MAJOR_VERSION ) )
{
m_Swap.ActivateByteSwapping( true );
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Unserialization
//-----------------------------------------------------------------------------
static bool ReadHeaderFromBufferPastBaseHeader( CUtlBuffer &buf, VTFFileHeader_t &header )
{
unsigned char *pBuf = (unsigned char*)(&header) + sizeof(VTFFileBaseHeader_t);
if ( header.version[1] <= VTF_MINOR_VERSION && header.version[1] >= 4 )
{
buf.Get( pBuf, sizeof(VTFFileHeader_t) - sizeof(VTFFileBaseHeader_t) );
}
else if ( header.version[1] == 3 )
{
buf.Get( pBuf, sizeof(VTFFileHeaderV7_3_t) - sizeof(VTFFileBaseHeader_t) );
}
else if ( header.version[1] == 2 )
{
buf.Get( pBuf, sizeof(VTFFileHeaderV7_2_t) - sizeof(VTFFileBaseHeader_t) );
}
else if ( header.version[1] == 1 || header.version[1] == 0 )
{
// previous version 7.0 or 7.1
buf.Get( pBuf, sizeof(VTFFileHeaderV7_1_t) - sizeof(VTFFileBaseHeader_t) );
}
else
{
Warning( "*** Encountered VTF file with an invalid minor version!\n" );
return false;
}
return buf.IsValid();
}
bool CVTFTexture::ReadHeader( CUtlBuffer &buf, VTFFileHeader_t &header )
{
if ( IsX360() && SetupByteSwap( buf ) )
{
VTFFileBaseHeader_t baseHeader;
m_Swap.SwapFieldsToTargetEndian( &baseHeader, (VTFFileBaseHeader_t*)buf.PeekGet() );
// Swap the header inside the UtlBuffer
if ( baseHeader.version[0] == VTF_MAJOR_VERSION )
{
if ( baseHeader.version[1] == 0 || baseHeader.version[1] == 1 )
{
// version 7.0 or 7.1
m_Swap.SwapFieldsToTargetEndian( (VTFFileHeaderV7_1_t*)buf.PeekGet() );
}
else if ( baseHeader.version[1] == 2 )
{
// version 7.2
m_Swap.SwapFieldsToTargetEndian( (VTFFileHeaderV7_2_t*)buf.PeekGet() );
}
else if ( baseHeader.version[1] == 3 )
{
m_Swap.SwapFieldsToTargetEndian( (VTFFileHeaderV7_3_t*)buf.PeekGet() );
}
else if ( baseHeader.version[1] >= 4 && baseHeader.version[1] <= VTF_MINOR_VERSION )
{
m_Swap.SwapFieldsToTargetEndian( (VTFFileHeader_t*)buf.PeekGet() );
}
}
}
memset( &header, 0, sizeof(VTFFileHeader_t) );
buf.Get( &header, sizeof(VTFFileBaseHeader_t) );
if ( !buf.IsValid() )
{
Warning( "*** Error unserializing VTF file... is the file empty?\n" );
return false;
}
// Validity check
if ( Q_strncmp( header.fileTypeString, "VTF", 4 ) )
{
Warning( "*** Tried to load a non-VTF file as a VTF file!\n" );
return false;
}
if ( header.version[0] != VTF_MAJOR_VERSION )
{
Warning( "*** Encountered VTF file with an invalid version!\n" );