forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmaterial.cpp
3609 lines (3032 loc) · 98.3 KB
/
cmaterial.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: Implementation of a material
//
//===========================================================================//
#include "imaterialinternal.h"
#include "bitmap/tgaloader.h"
#include "colorspace.h"
#include "materialsystem/imaterialvar.h"
#include "materialsystem/itexture.h"
#include <string.h>
#include "materialsystem_global.h"
#include "shaderapi/ishaderapi.h"
#include "materialsystem/imaterialproxy.h"
#include "shadersystem.h"
#include "materialsystem/imaterialproxyfactory.h"
#include "IHardwareConfigInternal.h"
#include "utlsymbol.h"
#ifdef OSX
#include <malloc/malloc.h>
#else
#include <malloc.h>
#endif
#include "filesystem.h"
#include <KeyValues.h>
#include "mempool.h"
#include "shaderapi/ishaderutil.h"
#include "vtf/vtf.h"
#include "tier1/strtools.h"
#include <ctype.h>
#include "utlbuffer.h"
#include "mathlib/vmatrix.h"
#include "texturemanager.h"
#include "itextureinternal.h"
#include "mempool.h"
#include "tier1/callqueue.h"
#include "cmaterial_queuefriendly.h"
#include "ifilelist.h"
#include "tier0/icommandline.h"
#include "tier0/minidump.h"
// #define PROXY_TRACK_NAMES
//-----------------------------------------------------------------------------
// Material implementation
//-----------------------------------------------------------------------------
class CMaterial : public IMaterialInternal
{
public:
// Members of the IMaterial interface
const char *GetName() const;
const char *GetTextureGroupName() const;
PreviewImageRetVal_t GetPreviewImageProperties( int *width, int *height,
ImageFormat *imageFormat, bool* isTranslucent ) const;
PreviewImageRetVal_t GetPreviewImage( unsigned char *data, int width, int height,
ImageFormat imageFormat ) const;
int GetMappingWidth( );
int GetMappingHeight( );
int GetNumAnimationFrames( );
bool InMaterialPage( void ) { return false; }
void GetMaterialOffset( float *pOffset );
void GetMaterialScale( float *pOffset );
IMaterial *GetMaterialPage( void ) { return NULL; }
void IncrementReferenceCount( );
void DecrementReferenceCount( );
int GetEnumerationID( ) const;
void GetLowResColorSample( float s, float t, float *color ) const;
IMaterialVar * FindVar( char const *varName, bool *found, bool complain = true );
IMaterialVar * FindVarFast( char const *pVarName, unsigned int *pToken );
// Sets new VMT shader parameters for the material
virtual void SetShaderAndParams( KeyValues *pKeyValues );
bool UsesEnvCubemap( void );
bool NeedsSoftwareSkinning( void );
virtual bool NeedsSoftwareLighting( void );
bool NeedsTangentSpace( void );
bool NeedsPowerOfTwoFrameBufferTexture( bool bCheckSpecificToThisFrame = true );
bool NeedsFullFrameBufferTexture( bool bCheckSpecificToThisFrame = true );
virtual bool IsUsingVertexID( ) const;
// GR - Is lightmap alpha needed?
bool NeedsLightmapBlendAlpha( void );
virtual void AlphaModulate( float alpha );
virtual void ColorModulate( float r, float g, float b );
virtual float GetAlphaModulation();
virtual void GetColorModulation( float *r, float *g, float *b );
// Gets the morph format
virtual MorphFormat_t GetMorphFormat() const;
void SetMaterialVarFlag( MaterialVarFlags_t flag, bool on );
bool GetMaterialVarFlag( MaterialVarFlags_t flag ) const;
bool IsTranslucent();
bool IsTranslucentInternal( float fAlphaModulation ) const; //need to centralize the logic without relying on the *current* alpha modulation being that which is stored in m_pShaderParams[ALPHA].
bool IsAlphaTested();
bool IsVertexLit();
virtual bool IsSpriteCard();
void GetReflectivity( Vector& reflect );
bool GetPropertyFlag( MaterialPropertyTypes_t type );
// Is the material visible from both sides?
bool IsTwoSided();
int GetNumPasses( void );
int GetTextureMemoryBytes( void );
void SetUseFixedFunctionBakedLighting( bool bEnable );
virtual bool IsPrecached( ) const;
public:
// stuff that is visible only from within the material system
// constructor, destructor
CMaterial( char const* materialName, const char *pTextureGroupName, KeyValues *pVMTKeyValues );
virtual ~CMaterial();
void DrawMesh( VertexCompressionType_t vertexCompression );
int GetReferenceCount( ) const;
void Uncache( bool bPreserveVars = false );
void Precache();
void ReloadTextures( void );
// If provided, pKeyValues and pPatchKeyValues should come from LoadVMTFile()
bool PrecacheVars( KeyValues *pKeyValues = NULL, KeyValues *pPatchKeyValues = NULL, CUtlVector<FileNameHandle_t> *pIncludes = NULL, int nFindContext = MATERIAL_FINDCONTEXT_NONE );
void SetMinLightmapPageID( int pageID );
void SetMaxLightmapPageID( int pageID );
int GetMinLightmapPageID( ) const;
int GetMaxLightmapPageID( ) const;
void SetNeedsWhiteLightmap( bool val );
bool GetNeedsWhiteLightmap( ) const;
bool IsPrecachedVars( ) const;
IShader * GetShader() const;
const char *GetShaderName() const;
virtual void DeleteIfUnreferenced();
void SetEnumerationID( int id );
void CallBindProxy( void *proxyData );
virtual IMaterial *CheckProxyReplacement( void *proxyData );
bool HasProxy( void ) const;
// Sets the shader associated with the material
void SetShader( const char *pShaderName );
// Can we override this material in debug?
bool NoDebugOverride() const;
// Gets the vertex format
VertexFormat_t GetVertexFormat() const;
// diffuse bump lightmap?
bool IsUsingDiffuseBumpedLighting() const;
// lightmap?
bool IsUsingLightmap() const;
// Gets the vertex usage flags
VertexFormat_t GetVertexUsage() const;
// Debugs this material
bool PerformDebugTrace() const;
// Are we suppressed?
bool IsSuppressed() const;
// Do we use fog?
bool UseFog( void ) const;
// Should we draw?
void ToggleSuppression();
void ToggleDebugTrace();
// Refresh material based on current var values
void Refresh();
void RefreshPreservingMaterialVars();
// This computes the state snapshots for this material
void RecomputeStateSnapshots();
// Gets at the shader parameters
virtual int ShaderParamCount() const;
virtual IMaterialVar **GetShaderParams( void );
virtual void AddMaterialVar( IMaterialVar *pMaterialVar );
virtual bool IsErrorMaterial() const;
// Was this manually created (not read from a file?)
virtual bool IsManuallyCreated() const;
virtual bool NeedsFixedFunctionFlashlight() const;
virtual void MarkAsPreloaded( bool bSet );
virtual bool IsPreloaded() const;
virtual void ArtificialAddRef( void );
virtual void ArtificialRelease( void );
virtual void ReportVarChanged( IMaterialVar *pVar )
{
m_ChangeID++;
}
virtual void ClearContextData( void );
virtual uint32 GetChangeID() const { return m_ChangeID; }
virtual bool IsRealTimeVersion( void ) const { return true; }
virtual IMaterialInternal *GetRealTimeVersion( void ) { return this; }
virtual IMaterialInternal *GetQueueFriendlyVersion( void ) { return &m_QueueFriendlyVersion; }
void DecideShouldReloadFromWhitelist( IFileList *pFilesToReload );
void ReloadFromWhitelistIfMarked();
bool WasReloadedFromWhitelist();
private:
// Initializes, cleans up the shader params
void CleanUpShaderParams();
// Sets up an error shader when we run into problems.
void SetupErrorShader();
// Does this material have a UNC-file name?
bool UsesUNCFileName() const;
// Prints material flags.
void PrintMaterialFlags( int flags, int flagsDefined );
// Parses material flags
bool ParseMaterialFlag( KeyValues* pParseValue, IMaterialVar* pFlagVar,
IMaterialVar* pFlagDefinedVar, bool parsingOverrides, int& flagMask, int& overrideMask );
// Computes the material vars for the shader
int ParseMaterialVars( IShader* pShader, KeyValues& keyValues,
KeyValues* pOverride, bool modelDefault, IMaterialVar** ppVars, int nFindContext = MATERIAL_FINDCONTEXT_NONE );
// Figures out the preview image for worldcraft
char const* GetPreviewImageName( );
char const* GetPreviewImageFileName( void ) const;
// Hooks up the shader, returns keyvalues of fallback that was used
KeyValues* InitializeShader( KeyValues &keyValues, KeyValues &patchKeyValues, int nFindContext = MATERIAL_FINDCONTEXT_NONE );
// Finds the flag associated with a particular flag name
int FindMaterialVarFlag( char const* pFlagName ) const;
// Initializes, cleans up the state snapshots
bool InitializeStateSnapshots();
void CleanUpStateSnapshots();
// Initializes, cleans up the material proxy
void InitializeMaterialProxy( KeyValues* pFallbackKeyValues );
void CleanUpMaterialProxy();
void DetermineProxyReplacements( KeyValues *pFallbackKeyValues );
// Creates, destroys snapshots
RenderPassList_t *CreateRenderPassList();
void DestroyRenderPassList( RenderPassList_t *pPassList );
// Grabs the texture width and height from the var list for faster access
void PrecacheMappingDimensions( );
// Gets the renderstate
virtual ShaderRenderState_t *GetRenderState();
// Do we have a valid renderstate?
bool IsValidRenderState() const;
// Get the material var flags
int GetMaterialVarFlags() const;
void SetMaterialVarFlags( int flags, bool on );
int GetMaterialVarFlags2() const;
void SetMaterialVarFlags2( int flags, bool on );
// Returns a dummy material variable
IMaterialVar* GetDummyVariable();
IMaterialVar* GetShaderParam( int id );
void FindRepresentativeTexture( void );
bool ShouldSkipVar( KeyValues *pMaterialVar, bool * pWasConditional );
// Fixed-size allocator
DECLARE_FIXEDSIZE_ALLOCATOR( CMaterial );
private:
enum
{
MATERIAL_NEEDS_WHITE_LIGHTMAP = 0x1,
MATERIAL_IS_PRECACHED = 0x2,
MATERIAL_VARS_IS_PRECACHED = 0x4,
MATERIAL_VALID_RENDERSTATE = 0x8,
MATERIAL_IS_MANUALLY_CREATED = 0x10,
MATERIAL_USES_UNC_FILENAME = 0x20,
MATERIAL_IS_PRELOADED = 0x40,
MATERIAL_ARTIFICIAL_REFCOUNT = 0x80,
};
int m_iEnumerationID;
int m_minLightmapPageID;
int m_maxLightmapPageID;
unsigned short m_MappingWidth;
unsigned short m_MappingHeight;
IShader *m_pShader;
CUtlSymbol m_Name;
// Any textures created for this material go under this texture group.
CUtlSymbol m_TextureGroupName;
CInterlockedInt m_RefCount;
unsigned short m_Flags;
unsigned char m_VarCount;
CUtlVector< IMaterialProxy * > m_ProxyInfo;
#ifdef PROXY_TRACK_NAMES
// Array to track names of above material proxies. Useful for tracking down issues with proxies.
CUtlVector< CUtlString > m_ProxyInfoNames;
#endif
IMaterialVar** m_pShaderParams;
IMaterialProxy *m_pReplacementProxy;
ShaderRenderState_t m_ShaderRenderState;
// This remembers filenames of VMTs that we included so we can sv_pure/flush ourselves if any of them need to be reloaded.
CUtlVector<FileNameHandle_t> m_VMTIncludes;
bool m_bShouldReloadFromWhitelist; // Tells us if the material decided it should be reloaded due to sv_pure whitelist changes.
ITextureInternal *m_representativeTexture;
Vector m_Reflectivity;
uint32 m_ChangeID;
// Used only by procedural materials; it essentially is an in-memory .VMT file
KeyValues *m_pVMTKeyValues;
#if defined( _DEBUG )
// Makes it easier to see what's going on
char *m_pDebugName;
#endif
protected:
CMaterial_QueueFriendly m_QueueFriendlyVersion;
};
// NOTE: This must be the last file included
// Has to exist *after* fixed size allocator declaration
#include "tier0/memdbgon.h"
// Forward decls of helper functions for dealing with patch vmts.
static void ApplyPatchKeyValues( KeyValues &keyValues, KeyValues &patchKeyValues );
static bool AccumulateRecursiveVmtPatches( KeyValues &patchKeyValuesOut, KeyValues **ppBaseKeyValuesOut,
const KeyValues& keyValues, const char *pPathID, CUtlVector<FileNameHandle_t> *pIncludes );
//-----------------------------------------------------------------------------
// Parser utilities
//-----------------------------------------------------------------------------
static inline bool IsWhitespace( char c )
{
return c == ' ' || c == '\t';
}
static inline bool IsEndline( char c )
{
return c == '\n' || c == '\0';
}
static inline bool IsVector( char const* v )
{
while (IsWhitespace(*v))
{
++v;
if (IsEndline(*v))
return false;
}
return *v == '[' || *v == '{';
}
//-----------------------------------------------------------------------------
// Methods to create state snapshots
//-----------------------------------------------------------------------------
#include "tier0/memdbgoff.h"
#ifndef _CONSOLE
struct EditorRenderStateList_t
{
// Store combo of alpha, color, fixed-function baked lighting, flashlight, editor mode
RenderPassList_t m_Snapshots[SNAPSHOT_COUNT_EDITOR];
DECLARE_FIXEDSIZE_ALLOCATOR( EditorRenderStateList_t );
};
#endif
struct StandardRenderStateList_t
{
// Store combo of alpha, color, fixed-function baked lighting, flashlight
RenderPassList_t m_Snapshots[SNAPSHOT_COUNT_NORMAL];
DECLARE_FIXEDSIZE_ALLOCATOR( StandardRenderStateList_t );
};
#include "tier0/memdbgon.h"
#ifndef _CONSOLE
DEFINE_FIXEDSIZE_ALLOCATOR( EditorRenderStateList_t, 256, true );
#endif
DEFINE_FIXEDSIZE_ALLOCATOR( StandardRenderStateList_t, 256, true );
//-----------------------------------------------------------------------------
// class factory methods
//-----------------------------------------------------------------------------
DEFINE_FIXEDSIZE_ALLOCATOR( CMaterial, 256, true );
IMaterialInternal* IMaterialInternal::CreateMaterial( char const* pMaterialName, const char *pTextureGroupName, KeyValues *pVMTKeyValues )
{
MaterialLock_t hMaterialLock = MaterialSystem()->Lock();
IMaterialInternal *pResult = new CMaterial( pMaterialName, pTextureGroupName, pVMTKeyValues );
MaterialSystem()->Unlock( hMaterialLock );
return pResult;
}
void IMaterialInternal::DestroyMaterial( IMaterialInternal* pMaterial )
{
MaterialLock_t hMaterialLock = MaterialSystem()->Lock();
if (pMaterial)
{
Assert( pMaterial->IsRealTimeVersion() );
CMaterial* pMatImp = static_cast<CMaterial*>(pMaterial);
// Deletion of the error material is deferred until after all other materials have been deleted.
// See CMaterialSystem::CleanUpErrorMaterial() in cmaterialsystem.cpp.
if ( !pMatImp->IsErrorMaterial() )
{
delete pMatImp;
}
}
MaterialSystem()->Unlock( hMaterialLock );
}
//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------
CMaterial::CMaterial( char const* materialName, const char *pTextureGroupName, KeyValues *pKeyValues )
{
m_Reflectivity.Init( 0.2f, 0.2f, 0.2f );
int len = Q_strlen(materialName);
char* pTemp = (char*)_alloca( len + 1 );
// Strip off the extension
Q_StripExtension( materialName, pTemp, len+1 );
Q_strlower( pTemp );
#if defined( _X360 )
// material names are expected to be forward slashed for correct sort and find behavior!
// assert now to track alternate or regressed path that is source of inconsistency
Assert( strchr( pTemp, '\\' ) == NULL );
#endif
// Convert it to a symbol
m_Name = pTemp;
#if defined( _DEBUG )
m_pDebugName = new char[strlen(pTemp) + 1];
Q_strncpy( m_pDebugName, pTemp, strlen(pTemp) + 1 );
#endif
m_bShouldReloadFromWhitelist = false;
m_Flags = 0;
m_pShader = NULL;
m_pShaderParams = NULL;
m_RefCount = 0;
m_representativeTexture = NULL;
m_pReplacementProxy = NULL;
m_VarCount = 0;
m_MappingWidth = m_MappingHeight = 0;
m_iEnumerationID = 0;
m_minLightmapPageID = m_maxLightmapPageID = 0;
m_TextureGroupName = pTextureGroupName;
m_pVMTKeyValues = pKeyValues;
if (m_pVMTKeyValues)
{
m_Flags |= MATERIAL_IS_MANUALLY_CREATED;
}
if ( pTemp[0] == '/' && pTemp[1] == '/' && pTemp[2] != '/' )
{
m_Flags |= MATERIAL_USES_UNC_FILENAME;
}
// Initialize the renderstate to something indicating nothing should be drawn
m_ShaderRenderState.m_Flags = 0;
m_ShaderRenderState.m_VertexFormat = m_ShaderRenderState.m_VertexUsage = 0;
m_ShaderRenderState.m_MorphFormat = 0;
m_ShaderRenderState.m_pSnapshots = CreateRenderPassList();
m_ChangeID = 0;
m_QueueFriendlyVersion.SetRealTimeVersion( this );
}
CMaterial::~CMaterial()
{
MaterialSystem()->UnbindMaterial( this );
Uncache();
if ( m_RefCount != 0 )
{
DevWarning( 2, "Reference Count for Material %s (%d) != 0\n", GetName(), (int) m_RefCount );
}
if ( m_pVMTKeyValues )
{
m_pVMTKeyValues->deleteThis();
m_pVMTKeyValues = NULL;
}
DestroyRenderPassList( m_ShaderRenderState.m_pSnapshots );
m_representativeTexture = NULL;
#if defined( _DEBUG )
delete [] m_pDebugName;
#endif
// Deliberately stomp our VTable so that we can detect cases where code tries to access freed materials.
int *p = (int *)this;
*p = 0xc0dedbad;
}
void CMaterial::ClearContextData( void )
{
int nSnapshotCount = SnapshotTypeCount();
for( int i = 0 ; i < nSnapshotCount ; i++ )
for( int j = 0 ; j < m_ShaderRenderState.m_pSnapshots[i].m_nPassCount; j++ )
{
if ( m_ShaderRenderState.m_pSnapshots[i].m_pContextData[j] )
{
delete m_ShaderRenderState.m_pSnapshots[i].m_pContextData[j];
m_ShaderRenderState.m_pSnapshots[i].m_pContextData[j] = NULL;
}
}
}
//-----------------------------------------------------------------------------
// Sets new VMT shader parameters for the material
//-----------------------------------------------------------------------------
void CMaterial::SetShaderAndParams( KeyValues *pKeyValues )
{
Uncache();
if ( m_pVMTKeyValues )
{
m_pVMTKeyValues->deleteThis();
m_pVMTKeyValues = NULL;
}
m_pVMTKeyValues = pKeyValues ? pKeyValues->MakeCopy() : NULL;
if (m_pVMTKeyValues)
{
m_Flags |= MATERIAL_IS_MANUALLY_CREATED;
}
// Apply patches
const char *pMaterialName = GetName();
char pFileName[MAX_PATH];
const char *pPathID = "GAME";
if ( !UsesUNCFileName() )
{
Q_snprintf( pFileName, sizeof( pFileName ), "materials/%s.vmt", pMaterialName );
}
else
{
Q_snprintf( pFileName, sizeof( pFileName ), "%s.vmt", pMaterialName );
if ( pMaterialName[0] == '/' && pMaterialName[1] == '/' && pMaterialName[2] != '/' )
{
// UNC, do full search
pPathID = NULL;
}
}
KeyValues *pLoadedKeyValues = new KeyValues( "vmt" );
if ( pLoadedKeyValues->LoadFromFile( g_pFullFileSystem, pFileName, pPathID ) )
{
// Load succeeded, check if it's a patch file
if ( V_stricmp( pLoadedKeyValues->GetName(), "patch" ) == 0 )
{
// it's a patch file, recursively build up patch keyvalues
KeyValues *pPatchKeyValues = new KeyValues( "vmt_patch" );
bool bSuccess = AccumulateRecursiveVmtPatches( *pPatchKeyValues, NULL, *pLoadedKeyValues, pPathID, NULL );
if ( bSuccess )
{
// Apply accumulated patches to final vmt
ApplyPatchKeyValues( *m_pVMTKeyValues, *pPatchKeyValues );
}
pPatchKeyValues->deleteThis();
}
}
pLoadedKeyValues->deleteThis();
if ( g_pShaderDevice->IsUsingGraphics() )
{
Precache();
}
}
//-----------------------------------------------------------------------------
// Creates, destroys snapshots
//-----------------------------------------------------------------------------
RenderPassList_t *CMaterial::CreateRenderPassList()
{
RenderPassList_t *pRenderPassList;
if ( IsConsole() || !MaterialSystem()->CanUseEditorMaterials() )
{
StandardRenderStateList_t *pList = new StandardRenderStateList_t;
pRenderPassList = (RenderPassList_t*)pList->m_Snapshots;
}
#ifndef _CONSOLE
else
{
EditorRenderStateList_t *pList = new EditorRenderStateList_t;
pRenderPassList = (RenderPassList_t*)pList->m_Snapshots;
}
#endif
int nSnapshotCount = SnapshotTypeCount();
memset( pRenderPassList, 0, nSnapshotCount * sizeof(RenderPassList_t) );
return pRenderPassList;
}
void CMaterial::DestroyRenderPassList( RenderPassList_t *pPassList )
{
if ( !pPassList )
return;
int nSnapshotCount = SnapshotTypeCount();
for( int i = 0 ; i < nSnapshotCount ; i++ )
for( int j = 0 ; j < pPassList[i].m_nPassCount; j++ )
{
if ( pPassList[i].m_pContextData[j] )
{
delete pPassList[i].m_pContextData[j];
pPassList[i].m_pContextData[j] = NULL;
}
}
if ( IsConsole() || !MaterialSystem()->CanUseEditorMaterials() )
{
StandardRenderStateList_t *pList = (StandardRenderStateList_t*)pPassList;
delete pList;
}
#ifndef _CONSOLE
else
{
EditorRenderStateList_t *pList = (EditorRenderStateList_t*)pPassList;
delete pList;
}
#endif
}
//-----------------------------------------------------------------------------
// Gets the renderstate
//-----------------------------------------------------------------------------
ShaderRenderState_t *CMaterial::GetRenderState()
{
Precache();
return &m_ShaderRenderState;
}
//-----------------------------------------------------------------------------
// Returns a dummy material variable
//-----------------------------------------------------------------------------
IMaterialVar* CMaterial::GetDummyVariable()
{
static IMaterialVar* pDummyVar = 0;
if (!pDummyVar)
pDummyVar = IMaterialVar::Create( 0, "$dummyVar", 0 );
return pDummyVar;
}
//-----------------------------------------------------------------------------
// Are vars precached?
//-----------------------------------------------------------------------------
bool CMaterial::IsPrecachedVars( ) const
{
return (m_Flags & MATERIAL_VARS_IS_PRECACHED) != 0;
}
//-----------------------------------------------------------------------------
// Are we precached?
//-----------------------------------------------------------------------------
bool CMaterial::IsPrecached( ) const
{
return (m_Flags & MATERIAL_IS_PRECACHED) != 0;
}
//-----------------------------------------------------------------------------
// Cleans up shader parameters
//-----------------------------------------------------------------------------
void CMaterial::CleanUpShaderParams()
{
if( m_pShaderParams )
{
for (int i = 0; i < m_VarCount; ++i)
{
IMaterialVar::Destroy( m_pShaderParams[i] );
}
free( m_pShaderParams );
m_pShaderParams = 0;
}
m_VarCount = 0;
}
//-----------------------------------------------------------------------------
// Initializes the material proxy
//-----------------------------------------------------------------------------
void CMaterial::InitializeMaterialProxy( KeyValues* pFallbackKeyValues )
{
IMaterialProxyFactory *pMaterialProxyFactory;
pMaterialProxyFactory = MaterialSystem()->GetMaterialProxyFactory();
if( !pMaterialProxyFactory )
return;
DetermineProxyReplacements( pFallbackKeyValues );
if ( m_pReplacementProxy )
{
m_ProxyInfo.AddToTail( m_pReplacementProxy );
#ifdef PROXY_TRACK_NAMES
m_ProxyInfoNames.AddToTail( "__replacementproxy" );
#endif
}
// See if we've got a proxy section; obey fallbacks
KeyValues* pProxySection = pFallbackKeyValues->FindKey("Proxies");
if ( pProxySection )
{
// Iterate through the section + create all of the proxies
KeyValues* pProxyKey = pProxySection->GetFirstSubKey();
for ( ; pProxyKey; pProxyKey = pProxyKey->GetNextKey() )
{
// Each of the proxies should themselves be databases
IMaterialProxy* pProxy = pMaterialProxyFactory->CreateProxy( pProxyKey->GetName() );
if (!pProxy)
{
Warning( "Error: Material \"%s\" : proxy \"%s\" not found!\n", GetName(), pProxyKey->GetName() );
continue;
}
if (!pProxy->Init( this->GetQueueFriendlyVersion(), pProxyKey ))
{
pMaterialProxyFactory->DeleteProxy( pProxy );
Warning( "Error: Material \"%s\" : proxy \"%s\" unable to initialize!\n", GetName(), pProxyKey->GetName() );
}
else
{
m_ProxyInfo.AddToTail( pProxy );
#ifdef PROXY_TRACK_NAMES
m_ProxyInfoNames.AddToTail( pProxyKey->GetName() );
#endif
}
}
}
}
//-----------------------------------------------------------------------------
// Cleans up the material proxy
//-----------------------------------------------------------------------------
void CMaterial::CleanUpMaterialProxy()
{
if ( !m_ProxyInfo.Count() )
return;
IMaterialProxyFactory *pMaterialProxyFactory;
pMaterialProxyFactory = MaterialSystem()->GetMaterialProxyFactory();
if ( !pMaterialProxyFactory )
return;
// Clean up material proxies
for ( int i = m_ProxyInfo.Count() - 1; i >= 0; i-- )
{
IMaterialProxy *pProxy = m_ProxyInfo[ i ];
pMaterialProxyFactory->DeleteProxy( pProxy );
}
m_ProxyInfo.RemoveAll();
#ifdef PROXY_TRACK_NAMES
m_ProxyInfoNames.RemoveAll();
#endif
}
void CMaterial::DetermineProxyReplacements( KeyValues *pFallbackKeyValues )
{
m_pReplacementProxy = MaterialSystem()->DetermineProxyReplacements( this, pFallbackKeyValues );
}
static char const *GetVarName( KeyValues *pVar )
{
char const *pVarName = pVar->GetName();
char const *pQuestion = strchr( pVarName, '?' );
if (! pQuestion )
return pVarName;
else
return pQuestion + 1;
}
//-----------------------------------------------------------------------------
// Finds the index of the material var associated with a var
//-----------------------------------------------------------------------------
static int FindMaterialVar( IShader* pShader, char const* pVarName )
{
if ( !pShader )
return -1;
// Strip preceeding spaces
pVarName += strspn( pVarName, " \t" );
for (int i = pShader->GetNumParams(); --i >= 0; )
{
// Makes the parser a little more lenient.. strips off bogus spaces in the var name.
const char *pParamName = pShader->GetParamName(i);
const char *pFound = Q_stristr( pVarName, pParamName );
// The found string had better start with the first non-whitespace character
if ( pFound != pVarName )
continue;
// Strip spaces at the end
int nLen = Q_strlen( pParamName );
pFound += nLen;
while ( true )
{
if ( !pFound[0] )
return i;
if ( !IsWhitespace( pFound[0] ) )
break;
++pFound;
}
}
return -1;
}
//-----------------------------------------------------------------------------
// Creates a vector material var
//-----------------------------------------------------------------------------
int ParseVectorFromKeyValueString( KeyValues *pKeyValue, const char *pMaterialName, float vecVal[4] )
{
char const* pScan = pKeyValue->GetString();
bool divideBy255 = false;
// skip whitespace
while( IsWhitespace(*pScan) )
{
++pScan;
}
if( *pScan == '{' )
{
divideBy255 = true;
}
else
{
Assert( *pScan == '[' );
}
// skip the '['
++pScan;
int i;
for( i = 0; i < 4; i++ )
{
// skip whitespace
while( IsWhitespace(*pScan) )
{
++pScan;
}
if( IsEndline(*pScan) || *pScan == ']' || *pScan == '}' )
{
if (*pScan != ']' && *pScan != '}')
{
Warning( "Warning in .VMT file (%s): no ']' or '}' found in vector key \"%s\".\n"
"Did you forget to surround the vector with \"s?\n", pMaterialName, pKeyValue->GetName() );
}
// allow for vec2's, etc.
vecVal[i] = 0.0f;
break;
}
char* pEnd;
vecVal[i] = strtod( pScan, &pEnd );
if (pScan == pEnd)
{
Warning( "Error in .VMT file: error parsing vector element \"%s\" in \"%s\"\n", pKeyValue->GetName(), pMaterialName );
return 0;
}
pScan = pEnd;
}
if( divideBy255 )
{
vecVal[0] *= ( 1.0f / 255.0f );
vecVal[1] *= ( 1.0f / 255.0f );
vecVal[2] *= ( 1.0f / 255.0f );
vecVal[3] *= ( 1.0f / 255.0f );
}
return i;
}
static IMaterialVar* CreateVectorMaterialVarFromKeyValue( IMaterial* pMaterial, KeyValues* pKeyValue )
{
char const *pszName = GetVarName( pKeyValue );
float vecVal[4];
int nDim = ParseVectorFromKeyValueString( pKeyValue, pszName, vecVal );
if ( nDim == 0 )
return NULL;
// Create the variable!
return IMaterialVar::Create( pMaterial, pszName, vecVal, nDim );
}
//-----------------------------------------------------------------------------
// Creates a vector material var
//-----------------------------------------------------------------------------
static IMaterialVar* CreateMatrixMaterialVarFromKeyValue( IMaterial* pMaterial, KeyValues* pKeyValue )
{
char const* pScan = pKeyValue->GetString();
char const *pszName = GetVarName( pKeyValue );
// Matrices can be specified one of two ways:
// [ # # # # # # # # # # # # # # # # ]
// or
// center # # scale # # rotate # translate # #
VMatrix mat;
int count = sscanf( pScan, " [ %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f ]",
&mat.m[0][0], &mat.m[0][1], &mat.m[0][2], &mat.m[0][3],
&mat.m[1][0], &mat.m[1][1], &mat.m[1][2], &mat.m[1][3],
&mat.m[2][0], &mat.m[2][1], &mat.m[2][2], &mat.m[2][3],
&mat.m[3][0], &mat.m[3][1], &mat.m[3][2], &mat.m[3][3] );
if (count == 16)
{
return IMaterialVar::Create( pMaterial, pszName, mat );
}
Vector2D scale, center;
float angle;
Vector2D translation;
count = sscanf( pScan, " center %f %f scale %f %f rotate %f translate %f %f",
¢er.x, ¢er.y, &scale.x, &scale.y, &angle, &translation.x, &translation.y );
if (count != 7)
return NULL;
VMatrix temp;
MatrixBuildTranslation( mat, -center.x, -center.y, 0.0f );
MatrixBuildScale( temp, scale.x, scale.y, 1.0f );
MatrixMultiply( temp, mat, mat );
MatrixBuildRotateZ( temp, angle );
MatrixMultiply( temp, mat, mat );
MatrixBuildTranslation( temp, center.x + translation.x, center.y + translation.y, 0.0f );
MatrixMultiply( temp, mat, mat );