forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctexture.cpp
4945 lines (4106 loc) · 154 KB
/
ctexture.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:
//
//=====================================================================================//
#ifdef PROTECTED_THINGS_ENABLE
#undef PROTECTED_THINGS_ENABLE
#endif
#include "platform.h"
// HACK: Need ShellExecute for PSD updates
#ifdef IS_WINDOWS_PC
#include <windows.h>
#include <shellapi.h>
#pragma comment ( lib, "shell32" )
#endif
#include "materialsystem_global.h"
#include "shaderapi/ishaderapi.h"
#include "itextureinternal.h"
#include "utlsymbol.h"
#include "time.h"
#include <sys/types.h>
#include <sys/stat.h>
#include "bitmap/imageformat.h"
#include "bitmap/tgaloader.h"
#include "bitmap/tgawriter.h"
#ifdef _WIN32
#include "direct.h"
#endif
#include "colorspace.h"
#include "string.h"
#include <stdlib.h>
#include "utlmemory.h"
#include "IHardwareConfigInternal.h"
#include "filesystem.h"
#include "tier1/strtools.h"
#include "vtf/vtf.h"
#include "materialsystem/materialsystem_config.h"
#include "mempool.h"
#include "texturemanager.h"
#include "utlbuffer.h"
#include "pixelwriter.h"
#include "tier1/callqueue.h"
#include "tier1/UtlStringMap.h"
#include "filesystem/IQueuedLoader.h"
#include "tier2/fileutils.h"
#include "filesystem.h"
#include "tier2/p4helpers.h"
#include "tier2/tier2.h"
#include "p4lib/ip4.h"
#include "ctype.h"
#include "ifilelist.h"
#include "tier0/icommandline.h"
#include "tier0/vprof.h"
// NOTE: This must be the last file included!!!
#include "tier0/memdbgon.h"
// this allows the command line to force the "all mips" flag to on for all textures
bool g_bForceTextureAllMips = false;
#if defined(IS_WINDOWS_PC)
static void ConVarChanged_mat_managedtextures( IConVar *var, const char *pOldValue, float flOldValue );
static ConVar mat_managedtextures( "mat_managedtextures", "1", FCVAR_ARCHIVE, "If set, allows Direct3D to manage texture uploading at the cost of extra system memory", &ConVarChanged_mat_managedtextures );
static void ConVarChanged_mat_managedtextures( IConVar *var, const char *pOldValue, float flOldValue )
{
if ( mat_managedtextures.GetBool() != (flOldValue != 0) )
{
materials->ReleaseResources();
materials->ReacquireResources();
}
}
#endif
static ConVar mat_spew_on_texture_size( "mat_spew_on_texture_size", "0", 0, "Print warnings about vtf content that isn't of the expected size" );
static ConVar mat_lodin_time( "mat_lodin_time", "5.0", FCVAR_DEVELOPMENTONLY );
static ConVar mat_lodin_hidden_pop( "mat_lodin_hidden_pop", "1", FCVAR_DEVELOPMENTONLY );
#define TEXTURE_FNAME_EXTENSION ".vtf"
#define TEXTURE_FNAME_EXTENSION_LEN 4
#define TEXTURE_FNAME_EXTENSION_NORMAL "_normal.vtf"
#ifdef STAGING_ONLY
ConVar mat_spewalloc( "mat_spewalloc", "0" );
#else
ConVar mat_spewalloc( "mat_spewalloc", "0", FCVAR_ARCHIVE | FCVAR_DEVELOPMENTONLY );
#endif
struct TexDimensions_t
{
uint16 m_nWidth;
uint16 m_nHeight;
uint16 m_nMipCount;
uint16 m_nDepth;
TexDimensions_t( uint16 nWidth = 0, uint nHeight = 0, uint nMipCount = 0, uint16 nDepth = 1 )
: m_nWidth( nWidth )
, m_nHeight( nHeight )
, m_nMipCount( nMipCount )
, m_nDepth( nDepth )
{ }
};
#ifdef STAGING_ONLY
struct TexInfo_t
{
CUtlString m_Name;
unsigned short m_nWidth;
unsigned short m_nHeight;
unsigned short m_nDepth;
unsigned short m_nMipCount;
unsigned short m_nFrameCount;
unsigned short m_nCopies;
ImageFormat m_Format;
uint64 ComputeTexSize() const
{
uint64 total = 0;
unsigned short width = m_nWidth;
unsigned short height = m_nHeight;
unsigned short depth = m_nDepth;
for ( int mip = 0; mip < m_nMipCount; ++mip )
{
// Make sure that mip count lines up with the count
Assert( width > 1 || height > 1 || depth > 1 || ( mip == ( m_nMipCount - 1 ) ) );
total += ImageLoader::GetMemRequired( width, height, depth, m_Format, false );
width = Max( 1, width >> 1 );
height = Max( 1, height >> 1 );
depth = Max( 1, depth >> 1 );
}
return total * Min( (unsigned short) 1, m_nFrameCount ) * Min( (unsigned short) 1, m_nCopies );
}
TexInfo_t( const char* name = "", unsigned short w = 0, unsigned short h = 0, unsigned short d = 0, unsigned short mips = 0, unsigned short frames = 0, unsigned short copies = 0, ImageFormat fmt = IMAGE_FORMAT_UNKNOWN )
: m_nWidth( w )
, m_nHeight( h )
, m_nDepth( d )
, m_nMipCount( mips )
, m_nFrameCount( frames )
, m_nCopies( copies )
, m_Format( fmt )
{
if ( name && name[0] )
m_Name = name;
else
m_Name = "<unnamed>";
}
};
CUtlMap< ITexture*, TexInfo_t > g_currentTextures( DefLessFunc( ITexture* ) );
#endif
//-----------------------------------------------------------------------------
// Internal texture flags
//-----------------------------------------------------------------------------
enum InternalTextureFlags
{
TEXTUREFLAGSINTERNAL_ERROR = 0x00000001,
TEXTUREFLAGSINTERNAL_ALLOCATED = 0x00000002,
TEXTUREFLAGSINTERNAL_PRELOADED = 0x00000004, // 360: textures that went through the preload process
TEXTUREFLAGSINTERNAL_QUEUEDLOAD = 0x00000008, // 360: load using the queued loader
TEXTUREFLAGSINTERNAL_EXCLUDED = 0x00000020, // actual exclusion state
TEXTUREFLAGSINTERNAL_SHOULDEXCLUDE = 0x00000040, // desired exclusion state
TEXTUREFLAGSINTERNAL_TEMPRENDERTARGET = 0x00000080, // 360: should only allocate texture bits upon first resolve, destroy at level end
};
static int GetThreadId();
static bool SLoadTextureBitsFromFile( IVTFTexture **ppOutVtfTexture, FileHandle_t hFile, unsigned int nFlags, TextureLODControlSettings_t* pInOutCachedFileLodSettings, int nDesiredDimensionLimit, unsigned short* pOutStreamedMips, const char* pName, const char* pCacheFileName, TexDimensions_t* pOptOutMappingDims = NULL, TexDimensions_t* pOptOutActualDims = NULL, TexDimensions_t* pOptOutAllocatedDims = NULL, unsigned int* pOptOutStripFlags = NULL );
static int ComputeActualMipCount( const TexDimensions_t& actualDims, unsigned int nFlags );
static int ComputeMipSkipCount( const char* pName, const TexDimensions_t& mappingDims, bool bIgnorePicmip, IVTFTexture *pOptVTFTexture, unsigned int nFlags, int nDesiredDimensionLimit, unsigned short* pOutStreamedMips, TextureLODControlSettings_t* pInOutCachedFileLodSettings, TexDimensions_t* pOptOutActualDims, TexDimensions_t* pOptOutAllocatedDims, unsigned int* pOptOutStripFlags );
static int GetOptimalReadBuffer( CUtlBuffer *pOutOptimalBuffer, FileHandle_t hFile, int nFileSize );
static void FreeOptimalReadBuffer( int nMaxSize );
//-----------------------------------------------------------------------------
// Use Warning to show texture flags.
//-----------------------------------------------------------------------------
static void PrintFlags( unsigned int flags )
{
if ( flags & TEXTUREFLAGS_NOMIP )
{
Warning( "TEXTUREFLAGS_NOMIP|" );
}
if ( flags & TEXTUREFLAGS_NOLOD )
{
Warning( "TEXTUREFLAGS_NOLOD|" );
}
if ( flags & TEXTUREFLAGS_SRGB )
{
Warning( "TEXTUREFLAGS_SRGB|" );
}
if ( flags & TEXTUREFLAGS_POINTSAMPLE )
{
Warning( "TEXTUREFLAGS_POINTSAMPLE|" );
}
if ( flags & TEXTUREFLAGS_TRILINEAR )
{
Warning( "TEXTUREFLAGS_TRILINEAR|" );
}
if ( flags & TEXTUREFLAGS_CLAMPS )
{
Warning( "TEXTUREFLAGS_CLAMPS|" );
}
if ( flags & TEXTUREFLAGS_CLAMPT )
{
Warning( "TEXTUREFLAGS_CLAMPT|" );
}
if ( flags & TEXTUREFLAGS_HINT_DXT5 )
{
Warning( "TEXTUREFLAGS_HINT_DXT5|" );
}
if ( flags & TEXTUREFLAGS_ANISOTROPIC )
{
Warning( "TEXTUREFLAGS_ANISOTROPIC|" );
}
if ( flags & TEXTUREFLAGS_PROCEDURAL )
{
Warning( "TEXTUREFLAGS_PROCEDURAL|" );
}
if ( flags & TEXTUREFLAGS_ALL_MIPS )
{
Warning( "TEXTUREFLAGS_ALL_MIPS|" );
}
if ( flags & TEXTUREFLAGS_SINGLECOPY )
{
Warning( "TEXTUREFLAGS_SINGLECOPY|" );
}
if ( flags & TEXTUREFLAGS_STAGING_MEMORY )
{
Warning( "TEXTUREFLAGS_STAGING_MEMORY|" );
}
if ( flags & TEXTUREFLAGS_IGNORE_PICMIP )
{
Warning( "TEXTUREFLAGS_IGNORE_PICMIP|" );
}
if ( flags & TEXTUREFLAGS_IMMEDIATE_CLEANUP )
{
Warning( "TEXTUREFLAGS_IMMEDIATE_CLEANUP|" );
}
}
namespace TextureLodOverride
{
struct OverrideInfo
{
OverrideInfo() : x( 0 ), y( 0 ) {}
OverrideInfo( int8 x_, int8 y_ ) : x( x_ ), y( y_ ) {}
int8 x, y;
};
// Override map
typedef CUtlStringMap< OverrideInfo > OverrideMap_t;
OverrideMap_t s_OverrideMap;
// Retrieves the override info adjustments
OverrideInfo Get( char const *szName )
{
UtlSymId_t idx = s_OverrideMap.Find( szName );
if ( idx != s_OverrideMap.InvalidIndex() )
return s_OverrideMap[ idx ];
else
return OverrideInfo();
}
// Combines the existing override info adjustments with the given one
void Add( char const *szName, OverrideInfo oi )
{
OverrideInfo oiex = Get( szName );
oiex.x += oi.x;
oiex.y += oi.y;
s_OverrideMap[ szName ] = oiex;
}
}; // end namespace TextureLodOverride
class CTextureStreamingJob;
//-----------------------------------------------------------------------------
// Base texture class
//-----------------------------------------------------------------------------
class CTexture : public ITextureInternal
{
public:
CTexture();
virtual ~CTexture();
virtual const char *GetName( void ) const;
const char *GetTextureGroupName( void ) const;
// Stats about the texture itself
virtual ImageFormat GetImageFormat() const;
NormalDecodeMode_t GetNormalDecodeMode() const { return NORMAL_DECODE_NONE; }
virtual int GetMappingWidth() const;
virtual int GetMappingHeight() const;
virtual int GetActualWidth() const;
virtual int GetActualHeight() const;
virtual int GetNumAnimationFrames() const;
virtual bool IsTranslucent() const;
virtual void GetReflectivity( Vector& reflectivity );
// Reference counting
virtual void IncrementReferenceCount( );
virtual void DecrementReferenceCount( );
virtual int GetReferenceCount( );
// Used to modify the texture bits (procedural textures only)
virtual void SetTextureRegenerator( ITextureRegenerator *pTextureRegen );
// Little helper polling methods
virtual bool IsNormalMap( ) const;
virtual bool IsCubeMap( void ) const;
virtual bool IsRenderTarget( ) const;
virtual bool IsTempRenderTarget( void ) const;
virtual bool IsProcedural() const;
virtual bool IsMipmapped() const;
virtual bool IsError() const;
// For volume textures
virtual bool IsVolumeTexture() const;
virtual int GetMappingDepth() const;
virtual int GetActualDepth() const;
// Various ways of initializing the texture
void InitFileTexture( const char *pTextureFile, const char *pTextureGroupName );
void InitProceduralTexture( const char *pTextureName, const char *pTextureGroupName, int w, int h, int d, ImageFormat fmt, int nFlags, ITextureRegenerator* generator = NULL );
// Releases the texture's hw memory
void ReleaseMemory();
virtual void OnRestore();
// Sets the filtering modes on the texture we're modifying
void SetFilteringAndClampingMode( bool bOnlyLodValues = false );
void Download( Rect_t *pRect = NULL, int nAdditionalCreationFlags = 0 );
// Loads up information about the texture
virtual void Precache();
// FIXME: Bogus methods... can we please delete these?
virtual void GetLowResColorSample( float s, float t, float *color ) const;
// Gets texture resource data of the specified type.
// Params:
// eDataType type of resource to retrieve.
// pnumBytes on return is the number of bytes available in the read-only data buffer or is undefined
// Returns:
// pointer to the resource data, or NULL. Note that the data from this pointer can disappear when
// the texture goes away - you want to copy this data!
virtual void *GetResourceData( uint32 eDataType, size_t *pNumBytes ) const;
virtual int GetApproximateVidMemBytes( void ) const;
// Stretch blit the framebuffer into this texture.
virtual void CopyFrameBufferToMe( int nRenderTargetID = 0, Rect_t *pSrcRect = NULL, Rect_t *pDstRect = NULL );
virtual void CopyMeToFrameBuffer( int nRenderTargetID = 0, Rect_t *pSrcRect = NULL, Rect_t *pDstRect = NULL );
virtual ITexture *GetEmbeddedTexture( int nIndex );
// Get the shaderapi texture handle associated w/ a particular frame
virtual ShaderAPITextureHandle_t GetTextureHandle( int nFrame, int nChannel = 0 );
// Sets the texture as the render target
virtual void Bind( Sampler_t sampler );
virtual void Bind( Sampler_t sampler1, int nFrame, Sampler_t sampler2 = (Sampler_t) -1 );
virtual void BindVertexTexture( VertexTextureSampler_t stage, int nFrame );
// Set this texture as a render target
bool SetRenderTarget( int nRenderTargetID );
// Set this texture as a render target (optionally set depth texture as depth buffer as well)
bool SetRenderTarget( int nRenderTargetID, ITexture *pDepthTexture);
virtual void MarkAsPreloaded( bool bSet );
virtual bool IsPreloaded() const;
virtual void MarkAsExcluded( bool bSet, int nDimensionsLimit );
virtual bool UpdateExcludedState( void );
// Retrieve the vtf flags mask
virtual unsigned int GetFlags( void ) const;
virtual void ForceLODOverride( int iNumLodsOverrideUpOrDown );
void GetFilename( char *pOut, int maxLen ) const;
virtual void ReloadFilesInList( IFileList *pFilesToReload );
// Save texture to a file.
virtual bool SaveToFile( const char *fileName );
// Load the texture from a file.
bool AsyncReadTextureFromFile( IVTFTexture* pVTFTexture, unsigned int nAdditionalCreationFlags );
void AsyncCancelReadTexture( );
virtual void Map( void** pOutBits, int* pOutPitch );
virtual void Unmap();
virtual ResidencyType_t GetCurrentResidence() const { return m_residenceCurrent; }
virtual ResidencyType_t GetTargetResidence() const { return m_residenceTarget; }
virtual bool MakeResident( ResidencyType_t newResidence );
virtual void UpdateLodBias();
protected:
bool IsDepthTextureFormat( ImageFormat fmt );
void ReconstructTexture( bool bCopyFromCurrent );
void GetCacheFilename( char* pOutBuffer, int bufferSize ) const;
bool GetFileHandle( FileHandle_t *pOutFileHandle, char *pCacheFilename, char **ppResolvedFilename ) const;
void ReconstructPartialTexture( const Rect_t *pRect );
bool HasBeenAllocated() const;
void WriteDataToShaderAPITexture( int nFrameCount, int nFaceCount, int nFirstFace, int nMipCount, IVTFTexture *pVTFTexture, ImageFormat fmt );
// Initializes/shuts down the texture
void Init( int w, int h, int d, ImageFormat fmt, int iFlags, int iFrameCount );
void Shutdown();
// Sets the texture name
void SetName( const char* pName );
// Assigns/releases texture IDs for our animation frames
void AllocateTextureHandles( );
void ReleaseTextureHandles( );
// Calculates info about whether we can make the texture smaller and by how much
// Returns the number of skipped mip levels
int ComputeActualSize( bool bIgnorePicmip = false, IVTFTexture *pVTFTexture = NULL, bool bTextureMigration = false );
// Computes the actual format of the texture given a desired src format
ImageFormat ComputeActualFormat( ImageFormat srcFormat );
// Creates/releases the shader api texture
bool AllocateShaderAPITextures();
void FreeShaderAPITextures();
void MigrateShaderAPITextures();
void NotifyUnloadedFile();
// Download bits
void DownloadTexture( Rect_t *pRect, bool bCopyFromCurrent = false );
void ReconstructTextureBits(Rect_t *pRect);
// Gets us modifying a particular frame of our texture
void Modify( int iFrame );
// Sets the texture clamping state on the currently modified frame
void SetWrapState( );
// Sets the texture filtering state on the currently modified frame
void SetFilterState();
// Sets the lod state on the currently modified frame
void SetLodState();
// Loads the texture bits from a file. Optionally provides absolute path
IVTFTexture *LoadTextureBitsFromFile( char *pCacheFileName, char **pResolvedFilename );
IVTFTexture *HandleFileLoadFailedTexture( IVTFTexture *pVTFTexture );
// Generates the procedural bits
IVTFTexture *ReconstructProceduralBits( );
IVTFTexture *ReconstructPartialProceduralBits( const Rect_t *pRect, Rect_t *pActualRect );
// Sets up debugging texture bits, if appropriate
bool SetupDebuggingTextures( IVTFTexture *pTexture );
// Generate a texture that shows the various mip levels
void GenerateShowMipLevelsTextures( IVTFTexture *pTexture );
void Cleanup( void );
// Converts a source image read from disk into its actual format
bool ConvertToActualFormat( IVTFTexture *pTexture );
// Builds the low-res image from the texture
void LoadLowResTexture( IVTFTexture *pTexture );
void CopyLowResImageToTexture( IVTFTexture *pTexture );
void GetDownloadFaceCount( int &nFirstFace, int &nFaceCount );
void ComputeMipLevelSubRect( const Rect_t* pSrcRect, int nMipLevel, Rect_t *pSubRect );
IVTFTexture *GetScratchVTFTexture( );
void ReleaseScratchVTFTexture( IVTFTexture* tex );
void ApplyRenderTargetSizeMode( int &width, int &height, ImageFormat fmt );
virtual void CopyToStagingTexture( ITexture* pDstTex );
virtual void SetErrorTexture( bool _isErrorTexture );
// Texture streaming
void MakeNonResident();
void MakePartiallyResident();
bool MakeFullyResident();
void CancelStreamingJob( bool bJobMustExist = true );
void OnStreamingJobComplete( ResidencyType_t newResidenceCurrent );
protected:
#ifdef _DEBUG
char *m_pDebugName;
#endif
// Reflectivity vector
Vector m_vecReflectivity;
CUtlSymbol m_Name;
// What texture group this texture is in (winds up setting counters based on the group name,
// then the budget panel views the counters).
CUtlSymbol m_TextureGroupName;
unsigned int m_nFlags;
unsigned int m_nInternalFlags;
CInterlockedInt m_nRefCount;
// This is the *desired* image format, which may or may not represent reality
ImageFormat m_ImageFormat;
// mapping dimensions and actual dimensions can/will vary due to user settings, hardware support, etc.
// Allocated is what is physically allocated on the hardware at this instant, and considers texture streaming.
TexDimensions_t m_dimsMapping;
TexDimensions_t m_dimsActual;
TexDimensions_t m_dimsAllocated;
// This is the iWidth/iHeight for whatever is downloaded to the card, ignoring current streaming settings
// Some callers want to know how big the texture is if all data was present, and that's this.
// TODO: Rename this before check in.
unsigned short m_nFrameCount;
// These are the values for what is truly allocated on the card, including streaming settings.
unsigned short m_nStreamingMips;
unsigned short m_nOriginalRTWidth; // The values they initially specified. We generated a different width
unsigned short m_nOriginalRTHeight; // and height based on screen size and the flags they specify.
unsigned char m_LowResImageWidth;
unsigned char m_LowResImageHeight;
unsigned short m_nDesiredDimensionLimit; // part of texture exclusion
unsigned short m_nActualDimensionLimit; // value not necessarily accurate, but mismatch denotes dirty state
// m_pStreamingJob is refcounted, but it is not safe to call SafeRelease directly on it--you must call
// CancelStreamingJob to ensure that releasing it doesn't cause a crash.
CTextureStreamingJob* m_pStreamingJob;
IVTFTexture* m_pStreamingVTF;
ResidencyType_t m_residenceTarget;
ResidencyType_t m_residenceCurrent;
int m_lodClamp;
int m_lastLodBiasAdjustFrame;
float m_lodBiasInitial;
float m_lodBiasCurrent;
double m_lodBiasStartTime;
// If the read failed, this will be true. We can't just return from the function because the call may
// happen in the async thread.
bool m_bStreamingFileReadFailed;
// The set of texture ids for each animation frame
ShaderAPITextureHandle_t *m_pTextureHandles;
TextureLODControlSettings_t m_cachedFileLodSettings;
// lowresimage info - used for getting color data from a texture
// without having a huge system mem overhead.
// FIXME: We should keep this in compressed form. .is currently decompressed at load time.
unsigned char *m_pLowResImage;
ITextureRegenerator *m_pTextureRegenerator;
// Used to help decide whether or not to recreate the render target if AA changes.
RenderTargetType_t m_nOriginalRenderTargetType;
RenderTargetSizeMode_t m_RenderTargetSizeMode;
// Fixed-size allocator
// DECLARE_FIXEDSIZE_ALLOCATOR( CTexture );
public:
void InitRenderTarget( const char *pRTName, int w, int h, RenderTargetSizeMode_t sizeMode,
ImageFormat fmt, RenderTargetType_t type, unsigned int textureFlags,
unsigned int renderTargetFlags );
virtual void DeleteIfUnreferenced();
void FixupTexture( const void *pData, int nSize, LoaderError_t loaderError );
void SwapContents( ITexture *pOther );
protected:
// private data, generally from VTF resource extensions
struct DataChunk
{
void Allocate( unsigned int numBytes )
{
m_pvData = new unsigned char[ numBytes ];
m_numBytes = numBytes;
}
void Deallocate() const { delete [] m_pvData; }
unsigned int m_eType;
unsigned int m_numBytes;
unsigned char *m_pvData;
};
CUtlVector< DataChunk > m_arrDataChunks;
struct ScratchVTF
{
ScratchVTF( CTexture* _tex ) : m_pParent( _tex ), m_pScratchVTF( _tex->GetScratchVTFTexture( ) ) { }
~ScratchVTF( )
{
if ( m_pScratchVTF )
m_pParent->ReleaseScratchVTFTexture( m_pScratchVTF );
m_pScratchVTF = NULL;
}
IVTFTexture* Get() const { return m_pScratchVTF; }
void TakeOwnership() { m_pScratchVTF = NULL; }
CTexture* m_pParent;
IVTFTexture* m_pScratchVTF;
};
friend class CTextureStreamingJob;
};
class CTextureStreamingJob : public IAsyncTextureOperationReceiver
{
public:
CTextureStreamingJob( CTexture* pTex ) : m_referenceCount( 0 ), m_pOwner( pTex ) { Assert( m_pOwner != NULL ); m_pOwner->AddRef(); }
virtual ~CTextureStreamingJob() { SafeRelease( &m_pOwner ); }
virtual int AddRef() OVERRIDE { return ++m_referenceCount; }
virtual int Release() OVERRIDE { int retVal = --m_referenceCount; Assert( retVal >= 0 ); if ( retVal == 0 ) { delete this; } return retVal; }
virtual int GetRefCount() const OVERRIDE { return m_referenceCount; }
virtual void OnAsyncCreateComplete( ITexture* pTex, void* pExtraArgs ) OVERRIDE { Assert( !"unimpl" ); }
virtual void OnAsyncFindComplete( ITexture* pTex, void* pExtraArgs ) OVERRIDE;
virtual void OnAsyncMapComplete( ITexture* pTex, void* pExtraArgs, void* pMemory, int nPitch ) { Assert( !"unimpl" ); }
virtual void OnAsyncReadbackBegin( ITexture* pDst, ITexture* pSrc, void* pExtraArgs ) OVERRIDE { Assert( !"unimpl" ); }
void ForgetOwner( ITextureInternal* pTex ) { Assert( pTex == m_pOwner ); SafeRelease( &m_pOwner ); }
private:
CInterlockedInt m_referenceCount;
CTexture* m_pOwner;
};
//////////////////////////////////////////////////////////////////////////
//
// CReferenceToHandleTexture is a special implementation of ITexture
// to be used solely for binding the texture handle when rendering.
// It is used when a D3D texture handle is available, but should be used
// at a higher level of abstraction requiring an ITexture or ITextureInternal.
//
//////////////////////////////////////////////////////////////////////////
class CReferenceToHandleTexture : public ITextureInternal
{
public:
CReferenceToHandleTexture();
virtual ~CReferenceToHandleTexture();
virtual const char *GetName( void ) const { return m_Name.String(); }
const char *GetTextureGroupName( void ) const { return m_TextureGroupName.String(); }
// Stats about the texture itself
virtual ImageFormat GetImageFormat() const { return IMAGE_FORMAT_UNKNOWN; }
virtual NormalDecodeMode_t GetNormalDecodeMode() const { return NORMAL_DECODE_NONE; }
virtual int GetMappingWidth() const { return 1; }
virtual int GetMappingHeight() const { return 1; }
virtual int GetActualWidth() const { return 1; }
virtual int GetActualHeight() const { return 1; }
virtual int GetNumAnimationFrames() const { return 1; }
virtual bool IsTranslucent() const { return false; }
virtual void GetReflectivity( Vector& reflectivity ) { reflectivity.Zero(); }
// Reference counting
virtual void IncrementReferenceCount( ) { ++ m_nRefCount; }
virtual void DecrementReferenceCount( ) { -- m_nRefCount; }
virtual int GetReferenceCount( ) { return m_nRefCount; }
// Used to modify the texture bits (procedural textures only)
virtual void SetTextureRegenerator( ITextureRegenerator *pTextureRegen ) { NULL; }
// Little helper polling methods
virtual bool IsNormalMap( ) const { return false; }
virtual bool IsCubeMap( void ) const { return false; }
virtual bool IsRenderTarget( ) const { return false; }
virtual bool IsTempRenderTarget( void ) const { return false; }
virtual bool IsProcedural() const { return true; }
virtual bool IsMipmapped() const { return false; }
virtual bool IsError() const { return false; }
// For volume textures
virtual bool IsVolumeTexture() const { return false; }
virtual int GetMappingDepth() const { return 1; }
virtual int GetActualDepth() const { return 1; }
// Releases the texture's hw memory
void ReleaseMemory() { NULL; }
virtual void OnRestore() { NULL; }
// Sets the filtering modes on the texture we're modifying
void SetFilteringAndClampingMode( bool bOnlyLodValues = false ) { NULL; }
void Download( Rect_t *pRect = NULL, int nAdditionalCreationFlags = 0 ) { NULL; }
// Loads up information about the texture
virtual void Precache() { NULL; }
// FIXME: Bogus methods... can we please delete these?
virtual void GetLowResColorSample( float s, float t, float *color ) const { NULL; }
// Gets texture resource data of the specified type.
// Params:
// eDataType type of resource to retrieve.
// pnumBytes on return is the number of bytes available in the read-only data buffer or is undefined
// Returns:
// pointer to the resource data, or NULL. Note that the data from this pointer can disappear when
// the texture goes away - you want to copy this data!
virtual void *GetResourceData( uint32 eDataType, size_t *pNumBytes ) const { return NULL; }
virtual int GetApproximateVidMemBytes( void ) const { return 32; }
// Stretch blit the framebuffer into this texture.
virtual void CopyFrameBufferToMe( int nRenderTargetID = 0, Rect_t *pSrcRect = NULL, Rect_t *pDstRect = NULL ) { NULL; }
virtual void CopyMeToFrameBuffer( int nRenderTargetID = 0, Rect_t *pSrcRect = NULL, Rect_t *pDstRect = NULL ) { NULL; }
virtual ITexture *GetEmbeddedTexture( int nIndex ) { return ( nIndex == 0 ) ? this : NULL; }
// Get the shaderapi texture handle associated w/ a particular frame
virtual ShaderAPITextureHandle_t GetTextureHandle( int nFrame, int nTextureChannel = 0 ) { return m_hTexture; }
// Bind the texture
virtual void Bind( Sampler_t sampler );
virtual void Bind( Sampler_t sampler1, int nFrame, Sampler_t sampler2 = (Sampler_t) -1 );
virtual void BindVertexTexture( VertexTextureSampler_t stage, int nFrame );
// Set this texture as a render target
bool SetRenderTarget( int nRenderTargetID ) { return SetRenderTarget( nRenderTargetID, NULL ); }
// Set this texture as a render target (optionally set depth texture as depth buffer as well)
bool SetRenderTarget( int nRenderTargetID, ITexture *pDepthTexture) { return false; }
virtual void MarkAsPreloaded( bool bSet ) { NULL; }
virtual bool IsPreloaded() const { return true; }
virtual void MarkAsExcluded( bool bSet, int nDimensionsLimit ) { NULL; }
virtual bool UpdateExcludedState( void ) { return true; }
// Retrieve the vtf flags mask
virtual unsigned int GetFlags( void ) const { return 0; }
virtual void ForceLODOverride( int iNumLodsOverrideUpOrDown ) { NULL; }
virtual void ReloadFilesInList( IFileList *pFilesToReload ) {}
// Save texture to a file.
virtual bool SaveToFile( const char *fileName ) { return false; }
virtual bool AsyncReadTextureFromFile( IVTFTexture* pVTFTexture, unsigned int nAdditionalCreationFlags ) { Assert( !"Should never get here." ); return false; }
virtual void AsyncCancelReadTexture() { Assert( !"Should never get here." ); }
virtual void CopyToStagingTexture( ITexture* pDstTex ) { Assert( !"Should never get here." ); };
// Map and unmap. These can fail. And can cause a very significant perf penalty. Be very careful with them.
virtual void Map( void** pOutBits, int* pOutPitch ) { }
virtual void Unmap() { }
virtual ResidencyType_t GetCurrentResidence() const { return RESIDENT_FULL; }
virtual ResidencyType_t GetTargetResidence() const { return RESIDENT_FULL; }
virtual bool MakeResident( ResidencyType_t newResidence ) { Assert( !"Unimpl" ); return true; }
virtual void UpdateLodBias() {}
virtual void SetErrorTexture( bool isErrorTexture ) { }
protected:
#ifdef _DEBUG
char *m_pDebugName;
#endif
CUtlSymbol m_Name;
// What texture group this texture is in (winds up setting counters based on the group name,
// then the budget panel views the counters).
CUtlSymbol m_TextureGroupName;
// The set of texture ids for each animation frame
ShaderAPITextureHandle_t m_hTexture;
// Refcount
int m_nRefCount;
public:
virtual void DeleteIfUnreferenced();
void FixupTexture( const void *pData, int nSize, LoaderError_t loaderError ) { NULL; }
void SwapContents( ITexture *pOther ) { NULL; }
public:
void SetName( char const *szName );
void InitFromHandle(
const char *pTextureName,
const char *pTextureGroupName,
ShaderAPITextureHandle_t hTexture );
};
CReferenceToHandleTexture::CReferenceToHandleTexture() :
m_hTexture( INVALID_SHADERAPI_TEXTURE_HANDLE ),
#ifdef _DEBUG
m_pDebugName( NULL ),
#endif
m_nRefCount( 0 )
{
NULL;
}
CReferenceToHandleTexture::~CReferenceToHandleTexture()
{
#ifdef _DEBUG
if ( m_nRefCount != 0 )
{
Warning( "Reference Count(%d) != 0 in ~CReferenceToHandleTexture for texture \"%s\"\n", m_nRefCount, m_Name.String() );
}
if ( m_pDebugName )
{
delete [] m_pDebugName;
}
#endif
}
void CReferenceToHandleTexture::SetName( char const *szName )
{
// normalize and convert to a symbol
char szCleanName[MAX_PATH];
m_Name = NormalizeTextureName( szName, szCleanName, sizeof( szCleanName ) );
#ifdef _DEBUG
if ( m_pDebugName )
{
delete [] m_pDebugName;
}
int nLen = V_strlen( szCleanName ) + 1;
m_pDebugName = new char[nLen];
V_memcpy( m_pDebugName, szCleanName, nLen );
#endif
}
void CReferenceToHandleTexture::InitFromHandle( const char *pTextureName, const char *pTextureGroupName, ShaderAPITextureHandle_t hTexture )
{
SetName( pTextureName );
m_TextureGroupName = pTextureGroupName;
m_hTexture = hTexture;
}
void CReferenceToHandleTexture::Bind( Sampler_t sampler )
{
if ( g_pShaderDevice->IsUsingGraphics() )
{
g_pShaderAPI->BindTexture( sampler, m_hTexture );
}
}
// TODO: make paired textures work with mat_texture_list
void CReferenceToHandleTexture::Bind( Sampler_t sampler1, int nFrame, Sampler_t sampler2 /* = -1 */ )
{
if ( g_pShaderDevice->IsUsingGraphics() )
{
g_pShaderAPI->BindTexture( sampler1, m_hTexture );
}
}
void CReferenceToHandleTexture::BindVertexTexture( VertexTextureSampler_t sampler, int nFrame )
{
if ( g_pShaderDevice->IsUsingGraphics() )
{
g_pShaderAPI->BindVertexTexture( sampler, m_hTexture );
}
}
void CReferenceToHandleTexture::DeleteIfUnreferenced()
{
if ( m_nRefCount > 0 )
return;
TextureManager()->RemoveTexture( this );
}
//-----------------------------------------------------------------------------
// Fixed-size allocator
//-----------------------------------------------------------------------------
//DEFINE_FIXEDSIZE_ALLOCATOR( CTexture, 1024, true );
//-----------------------------------------------------------------------------
// Static instance of VTF texture
//-----------------------------------------------------------------------------
#define MAX_RENDER_THREADS 4
// For safety's sake, we allow any of the threads that intersect with rendering
// to have their own state vars. In practice, we expect only the matqueue thread
// and the main thread to ever hit s_pVTFTexture.
static IVTFTexture *s_pVTFTexture[ MAX_RENDER_THREADS ] = { NULL };
// We only expect that the main thread or the matqueue thread to actually touch
// these, but we still need a NULL and size of 0 for the other threads.
static void *s_pOptimalReadBuffer[ MAX_RENDER_THREADS ] = { NULL };
static int s_nOptimalReadBufferSize[ MAX_RENDER_THREADS ] = { 0 };
//-----------------------------------------------------------------------------
// Class factory methods
//-----------------------------------------------------------------------------
ITextureInternal *ITextureInternal::CreateFileTexture( const char *pFileName, const char *pTextureGroupName )
{
CTexture *pTex = new CTexture;
pTex->InitFileTexture( pFileName, pTextureGroupName );
return pTex;
}
ITextureInternal *ITextureInternal::CreateReferenceTextureFromHandle(
const char *pTextureName,
const char *pTextureGroupName,
ShaderAPITextureHandle_t hTexture )
{
CReferenceToHandleTexture *pTex = new CReferenceToHandleTexture;
pTex->InitFromHandle( pTextureName, pTextureGroupName, hTexture );
return pTex;
}
ITextureInternal *ITextureInternal::CreateProceduralTexture(
const char *pTextureName,
const char *pTextureGroupName,
int w,
int h,
int d,
ImageFormat fmt,
int nFlags,
ITextureRegenerator *generator)
{
CTexture *pTex = new CTexture;
pTex->InitProceduralTexture( pTextureName, pTextureGroupName, w, h, d, fmt, nFlags, generator );
pTex->IncrementReferenceCount();
return pTex;
}
// GR - named RT
ITextureInternal *ITextureInternal::CreateRenderTarget(
const char *pRTName,
int w,
int h,
RenderTargetSizeMode_t sizeMode,
ImageFormat fmt,
RenderTargetType_t type,
unsigned int textureFlags,
unsigned int renderTargetFlags )
{
CTexture *pTex = new CTexture;
pTex->InitRenderTarget( pRTName, w, h, sizeMode, fmt, type, textureFlags, renderTargetFlags );
return pTex;
}
//-----------------------------------------------------------------------------
// Rebuild and exisiting render target in place.
//-----------------------------------------------------------------------------
void ITextureInternal::ChangeRenderTarget(
ITextureInternal *pTex,
int w,
int h,
RenderTargetSizeMode_t sizeMode,
ImageFormat fmt,
RenderTargetType_t type,
unsigned int textureFlags,
unsigned int renderTargetFlags )
{
pTex->ReleaseMemory();
dynamic_cast< CTexture * >(pTex)->InitRenderTarget( pTex->GetName(), w, h, sizeMode, fmt, type, textureFlags, renderTargetFlags );
}
void ITextureInternal::Destroy( ITextureInternal *pTex, bool bSkipTexMgrCheck )
{
#ifdef STAGING_ONLY
if ( !bSkipTexMgrCheck && TextureManager()->HasPendingTextureDestroys() )
{
// Multithreading badness. This will cause a crash later! Grab JohnS or McJohn know!
DebuggerBreakIfDebugging_StagingOnly();
}
#endif
int iIndex = g_pTextureRefList->Find( static_cast<ITexture*>( pTex ) );
if ( iIndex != g_pTextureRefList->InvalidIndex () )
{