-
Notifications
You must be signed in to change notification settings - Fork 187
/
Copy pathKeyValues.cpp
3214 lines (2736 loc) · 84.9 KB
/
KeyValues.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:
//
// $NoKeywords: $
//
//=============================================================================//
#if defined( _WIN32 ) && !defined( _X360 )
#include <windows.h> // for WideCharToMultiByte and MultiByteToWideChar
#elif defined(POSIX)
#include <wchar.h> // wcslen()
#define _alloca alloca
#define _wtoi(arg) wcstol(arg, NULL, 10)
#define _wtoi64(arg) wcstoll(arg, NULL, 10)
#include <dlfcn.h>
#endif
#include <KeyValues.h>
#include "filesystem.h"
#include <vstdlib/IKeyValuesSystem.h>
#include "tier0/icommandline.h"
#include <Color.h>
#include <stdlib.h>
#include "tier0/dbg.h"
#include "tier0/mem.h"
#include "utlbuffer.h"
#include "utlhash.h"
#include "utlvector.h"
#include "utlqueue.h"
#include "UtlSortVector.h"
#include "convar.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
template<typename T>
T *KVStringAlloc(size_t nLength)
{
return reinterpret_cast<T*>(MemAlloc_Alloc(sizeof(T) * nLength));
}
void KVStringDelete(void* pMem)
{
MemAlloc_Free(pMem);
}
static bool BKeyValuesSystemSupportsCache()
{
static bool s_bSupportsCache = false;
static bool s_bCheckedForCacheSupport = false;
if (!s_bCheckedForCacheSupport)
{
// Use Sys_LoadModule to resolve actual bin name.
CSysModule *pTier0 = Sys_LoadModule("tier0");
if (pTier0)
{
#ifdef _WIN32
s_bSupportsCache = !!GetProcAddress(reinterpret_cast<HMODULE>(pTier0), "HushAsserts");
#elif defined(POSIX)
s_bSupportsCache = !!dlsym(reinterpret_cast<void *>(pTier0), "HushAsserts");
#endif
}
s_bCheckedForCacheSupport = true;
}
return s_bSupportsCache;
}
static const char * s_LastFileLoadingFrom = "unknown"; // just needed for error messages
// Statics for the growable string table
int (*KeyValues::s_pfGetSymbolForString)( const char *name, bool bCreate ) = &KeyValues::GetSymbolForStringClassic;
const char *(*KeyValues::s_pfGetStringForSymbol)( int symbol ) = &KeyValues::GetStringForSymbolClassic;
CKeyValuesGrowableStringTable *KeyValues::s_pGrowableStringTable = NULL;
#define KEYVALUES_TOKEN_SIZE 4096
static char s_pTokenBuf[KEYVALUES_TOKEN_SIZE];
#define INTERNALWRITE( pData, len ) InternalWrite( filesystem, f, pBuf, pData, len )
// a simple class to keep track of a stack of valid parsed symbols
const int MAX_ERROR_STACK = 64;
class CKeyValuesErrorStack
{
public:
CKeyValuesErrorStack() : m_pFilename("NULL"), m_errorIndex(0), m_maxErrorIndex(0) {}
void SetFilename( const char *pFilename )
{
m_pFilename = pFilename;
m_maxErrorIndex = 0;
}
// entering a new keyvalues block, save state for errors
// Not save symbols instead of pointers because the pointers can move!
int Push( int symName )
{
if ( m_errorIndex < MAX_ERROR_STACK )
{
m_errorStack[m_errorIndex] = symName;
}
m_errorIndex++;
m_maxErrorIndex = V_max( m_maxErrorIndex, (m_errorIndex-1) );
return m_errorIndex-1;
}
// exiting block, error isn't in this block, remove.
void Pop()
{
m_errorIndex--;
Assert(m_errorIndex>=0);
}
// Allows you to keep the same stack level, but change the name as you parse peers
void Reset( int stackLevel, int symName )
{
Assert( stackLevel >= 0 );
Assert( stackLevel < m_errorIndex );
if ( stackLevel < MAX_ERROR_STACK )
m_errorStack[stackLevel] = symName;
}
// Hit an error, report it and the parsing stack for context
void ReportError( const char *pError )
{
bool bSpewCR = false;
Warning( "KeyValues Error: %s in file %s\n", pError, m_pFilename );
for ( int i = 0; i < m_maxErrorIndex; i++ )
{
if ( i < MAX_ERROR_STACK && m_errorStack[i] != INVALID_KEY_SYMBOL )
{
if ( i < m_errorIndex )
{
Warning( "%s, ", KeyValues::CallGetStringForSymbol(m_errorStack[i]) );
}
else
{
Warning( "(*%s*), ", KeyValues::CallGetStringForSymbol(m_errorStack[i]) );
}
bSpewCR = true;
}
}
if ( bSpewCR )
Warning( "\n" );
}
private:
int m_errorStack[MAX_ERROR_STACK];
const char *m_pFilename;
int m_errorIndex;
int m_maxErrorIndex;
} g_KeyValuesErrorStack;
// a simple helper that creates stack entries as it goes in & out of scope
class CKeyErrorContext
{
public:
CKeyErrorContext( KeyValues *pKv )
{
Init( pKv->GetNameSymbol() );
}
~CKeyErrorContext()
{
g_KeyValuesErrorStack.Pop();
}
CKeyErrorContext( int symName )
{
Init( symName );
}
void Reset( int symName )
{
g_KeyValuesErrorStack.Reset( m_stackLevel, symName );
}
int GetStackLevel() const
{
return m_stackLevel;
}
private:
void Init( int symName )
{
m_stackLevel = g_KeyValuesErrorStack.Push( symName );
}
int m_stackLevel;
};
// Uncomment this line to hit the ~CLeakTrack assert to see what's looking like it's leaking
// #define LEAKTRACK
#ifdef LEAKTRACK
class CLeakTrack
{
public:
CLeakTrack()
{
}
~CLeakTrack()
{
if ( keys.Count() != 0 )
{
Assert( 0 );
}
}
struct kve
{
KeyValues *kv;
char name[ 256 ];
};
void AddKv( KeyValues *kv, char const *name )
{
kve k;
Q_strncpy( k.name, name ? name : "NULL", sizeof( k.name ) );
k.kv = kv;
keys.AddToTail( k );
}
void RemoveKv( KeyValues *kv )
{
int c = keys.Count();
for ( int i = 0; i < c; i++ )
{
if ( keys[i].kv == kv )
{
keys.Remove( i );
break;
}
}
}
CUtlVector< kve > keys;
};
static CLeakTrack track;
#define TRACK_KV_ADD( ptr, name ) track.AddKv( ptr, name )
#define TRACK_KV_REMOVE( ptr ) track.RemoveKv( ptr )
#else
#define TRACK_KV_ADD( ptr, name )
#define TRACK_KV_REMOVE( ptr )
#endif
//-----------------------------------------------------------------------------
// Purpose: An arbitrarily growable string table for KeyValues key names.
// See the comment in the header for more info.
//-----------------------------------------------------------------------------
class CKeyValuesGrowableStringTable
{
public:
// Constructor
CKeyValuesGrowableStringTable() :
#ifdef PLATFORM_64BITS
m_vecStrings( 0, 4 * 512 * 1024 )
#else
m_vecStrings( 0, 512 * 1024 )
#endif
, m_hashLookup( 2048, 0, 0, m_Functor, m_Functor )
{
m_vecStrings.AddToTail( '\0' );
}
// Translates a string to an index
int GetSymbolForString( const char *name, bool bCreate = true )
{
AUTO_LOCK( m_mutex );
// Put the current details into our hash functor
m_Functor.SetCurString( name );
m_Functor.SetCurStringBase( (const char *)m_vecStrings.Base() );
if ( bCreate )
{
bool bInserted = false;
UtlHashHandle_t hElement = m_hashLookup.Insert( -1, &bInserted );
if ( bInserted )
{
int iIndex = m_vecStrings.AddMultipleToTail( V_strlen( name ) + 1, name );
m_hashLookup[ hElement ] = iIndex;
}
return m_hashLookup[ hElement ];
}
else
{
UtlHashHandle_t hElement = m_hashLookup.Find( -1 );
if ( m_hashLookup.IsValidHandle( hElement ) )
return m_hashLookup[ hElement ];
else
return -1;
}
}
// Translates an index back to a string
const char *GetStringForSymbol( int symbol )
{
return (const char *)m_vecStrings.Base() + symbol;
}
private:
// A class plugged into CUtlHash that allows us to change the behavior of the table
// and store only the index in the table.
class CLookupFunctor
{
public:
CLookupFunctor() : m_pchCurString( NULL ), m_pchCurBase( NULL ) {}
// Sets what we are currently inserting or looking for.
void SetCurString( const char *pchCurString ) { m_pchCurString = pchCurString; }
void SetCurStringBase( const char *pchCurBase ) { m_pchCurBase = pchCurBase; }
// The compare function.
bool operator()( int nLhs, int nRhs ) const
{
const char *pchLhs = nLhs > 0 ? m_pchCurBase + nLhs : m_pchCurString;
const char *pchRhs = nRhs > 0 ? m_pchCurBase + nRhs : m_pchCurString;
return ( 0 == V_stricmp( pchLhs, pchRhs ) );
}
// The hash function.
unsigned int operator()( int nItem ) const
{
return HashStringCaseless( m_pchCurString );
}
private:
const char *m_pchCurString;
const char *m_pchCurBase;
};
CThreadFastMutex m_mutex;
CLookupFunctor m_Functor;
CUtlHash<int, CLookupFunctor &, CLookupFunctor &> m_hashLookup;
CUtlVector<char> m_vecStrings;
};
//-----------------------------------------------------------------------------
// Purpose: Sets whether the KeyValues system should use an arbitrarily growable
// string table. See the comment in the header for more info.
//-----------------------------------------------------------------------------
void KeyValues::SetUseGrowableStringTable( bool bUseGrowableTable )
{
if ( bUseGrowableTable )
{
s_pfGetStringForSymbol = &(KeyValues::GetStringForSymbolGrowable);
s_pfGetSymbolForString = &(KeyValues::GetSymbolForStringGrowable);
if ( NULL == s_pGrowableStringTable )
{
s_pGrowableStringTable = new CKeyValuesGrowableStringTable;
}
}
else
{
s_pfGetStringForSymbol = &(KeyValues::GetStringForSymbolClassic);
s_pfGetSymbolForString = &(KeyValues::GetSymbolForStringClassic);
delete s_pGrowableStringTable;
s_pGrowableStringTable = NULL;
}
}
//-----------------------------------------------------------------------------
// Purpose: Bodys of the function pointers used for interacting with the key
// name string table
//-----------------------------------------------------------------------------
int KeyValues::GetSymbolForStringClassic( const char *name, bool bCreate )
{
return KeyValuesSystem()->GetSymbolForString( name, bCreate );
}
const char *KeyValues::GetStringForSymbolClassic( int symbol )
{
return KeyValuesSystem()->GetStringForSymbol( symbol );
}
int KeyValues::GetSymbolForStringGrowable( const char *name, bool bCreate )
{
return s_pGrowableStringTable->GetSymbolForString( name, bCreate );
}
const char *KeyValues::GetStringForSymbolGrowable( int symbol )
{
return s_pGrowableStringTable->GetStringForSymbol( symbol );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName )
{
TRACK_KV_ADD( this, setName );
Init();
SetName ( setName );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName, const char *firstKey, const char *firstValue )
{
TRACK_KV_ADD( this, setName );
Init();
SetName( setName );
SetString( firstKey, firstValue );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName, const char *firstKey, const wchar_t *firstValue )
{
TRACK_KV_ADD( this, setName );
Init();
SetName( setName );
SetWString( firstKey, firstValue );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName, const char *firstKey, int firstValue )
{
TRACK_KV_ADD( this, setName );
Init();
SetName( setName );
SetInt( firstKey, firstValue );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName, const char *firstKey, const char *firstValue, const char *secondKey, const char *secondValue )
{
TRACK_KV_ADD( this, setName );
Init();
SetName( setName );
SetString( firstKey, firstValue );
SetString( secondKey, secondValue );
}
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
KeyValues::KeyValues( const char *setName, const char *firstKey, int firstValue, const char *secondKey, int secondValue )
{
TRACK_KV_ADD( this, setName );
Init();
SetName( setName );
SetInt( firstKey, firstValue );
SetInt( secondKey, secondValue );
}
//-----------------------------------------------------------------------------
// Purpose: Initialize member variables
//-----------------------------------------------------------------------------
void KeyValues::Init()
{
m_iKeyName = INVALID_KEY_SYMBOL;
m_iDataType = TYPE_NONE;
m_pSub = NULL;
m_pPeer = NULL;
m_pChain = NULL;
m_sValue = NULL;
m_wsValue = NULL;
m_pValue = NULL;
m_bHasEscapeSequences = false;
m_bEvaluateConditionals = true;
// for future proof
memset( unused, 0, sizeof(unused) );
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
KeyValues::~KeyValues()
{
TRACK_KV_REMOVE( this );
RemoveEverything();
}
//-----------------------------------------------------------------------------
// Purpose: remove everything
//-----------------------------------------------------------------------------
void KeyValues::RemoveEverything()
{
KeyValues *dat;
KeyValues *datNext = NULL;
for ( dat = m_pSub; dat != NULL; dat = datNext )
{
datNext = dat->m_pPeer;
dat->m_pPeer = NULL;
delete dat;
}
for ( dat = m_pPeer; dat && dat != this; dat = datNext )
{
datNext = dat->m_pPeer;
dat->m_pPeer = NULL;
delete dat;
}
KVStringDelete(m_sValue);
m_sValue = NULL;
KVStringDelete(m_wsValue);
m_wsValue = NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *f -
//-----------------------------------------------------------------------------
void KeyValues::RecursiveSaveToFile( CUtlBuffer& buf, int indentLevel, bool sortKeys /*= false*/, bool bAllowEmptyString /*= false*/ )
{
RecursiveSaveToFile( NULL, FILESYSTEM_INVALID_HANDLE, &buf, indentLevel, sortKeys, bAllowEmptyString );
}
//-----------------------------------------------------------------------------
// Adds a chain... if we don't find stuff in this keyvalue, we'll look
// in the one we're chained to.
//-----------------------------------------------------------------------------
void KeyValues::ChainKeyValue( KeyValues* pChain )
{
m_pChain = pChain;
}
//-----------------------------------------------------------------------------
// Purpose: Get the name of the current key section
//-----------------------------------------------------------------------------
const char *KeyValues::GetName( void ) const
{
return s_pfGetStringForSymbol( m_iKeyName );
}
//-----------------------------------------------------------------------------
// Purpose: Read a single token from buffer (0 terminated)
//-----------------------------------------------------------------------------
#ifdef _WIN32
#pragma warning (disable:4706)
#endif
const char *KeyValues::ReadToken( CUtlBuffer &buf, bool &wasQuoted, bool &wasConditional )
{
wasQuoted = false;
wasConditional = false;
if ( !buf.IsValid() )
return NULL;
// eating white spaces and remarks loop
while ( true )
{
buf.EatWhiteSpace();
if ( !buf.IsValid() )
return NULL; // file ends after reading whitespaces
// stop if it's not a comment; a new token starts here
if ( !buf.EatCPPComment() )
break;
}
const char *c = (const char*)buf.PeekGet( sizeof(char), 0 );
if ( !c )
return NULL;
// read quoted strings specially
if ( *c == '\"' )
{
wasQuoted = true;
buf.GetDelimitedString( m_bHasEscapeSequences ? GetCStringCharConversion() : GetNoEscCharConversion(),
s_pTokenBuf, KEYVALUES_TOKEN_SIZE );
return s_pTokenBuf;
}
if ( *c == '{' || *c == '}' )
{
// it's a control char, just add this one char and stop reading
s_pTokenBuf[0] = *c;
s_pTokenBuf[1] = 0;
buf.SeekGet( CUtlBuffer::SEEK_CURRENT, 1 );
return s_pTokenBuf;
}
// read in the token until we hit a whitespace or a control character
bool bReportedError = false;
bool bConditionalStart = false;
int nCount = 0;
while ( ( c = (const char*)buf.PeekGet( sizeof(char), 0 ) ) )
{
// end of file
if ( *c == 0 )
break;
// break if any control character appears in non quoted tokens
if ( *c == '"' || *c == '{' || *c == '}' )
break;
if ( *c == '[' )
bConditionalStart = true;
if ( *c == ']' && bConditionalStart )
{
wasConditional = true;
}
// break on whitespace
if ( isspace(*c) )
break;
if (nCount < (KEYVALUES_TOKEN_SIZE-1) )
{
s_pTokenBuf[nCount++] = *c; // add char to buffer
}
else if ( !bReportedError )
{
bReportedError = true;
g_KeyValuesErrorStack.ReportError(" ReadToken overflow" );
}
buf.SeekGet( CUtlBuffer::SEEK_CURRENT, 1 );
}
s_pTokenBuf[ nCount ] = 0;
return s_pTokenBuf;
}
#ifdef _WIN32
#pragma warning (default:4706)
#endif
//-----------------------------------------------------------------------------
// Purpose: if parser should translate escape sequences ( /n, /t etc), set to true
//-----------------------------------------------------------------------------
void KeyValues::UsesEscapeSequences(bool state)
{
m_bHasEscapeSequences = state;
}
//-----------------------------------------------------------------------------
// Purpose: if parser should evaluate conditional blocks ( [$WINDOWS] etc. )
//-----------------------------------------------------------------------------
void KeyValues::UsesConditionals(bool state)
{
m_bEvaluateConditionals = state;
}
//-----------------------------------------------------------------------------
// Purpose: Load keyValues from disk
//-----------------------------------------------------------------------------
bool KeyValues::LoadFromFile( IBaseFileSystem *filesystem, const char *resourceName, const char *pathID, bool refreshCache )
{
Assert(filesystem);
#ifdef WIN32
Assert( IsX360() || ( IsPC() && _heapchk() == _HEAPOK ) );
#endif
#ifdef STAGING_ONLY
static bool s_bCacheEnabled = !!CommandLine()->FindParm( "-enable_keyvalues_cache" );
const bool bUseCache = s_bCacheEnabled && ( s_pfGetSymbolForString == KeyValues::GetSymbolForStringClassic );
#else
/*
People are cheating with the keyvalue cache enabled by doing the below, so disable it.
For example if one is to allow a blue demoman texture on sv_pure they
change it to this, "$basetexture" "temp/demoman_blue". Remember to move the
demoman texture to the temp folder in the materials folder. It will likely
not be there so make a new folder for it. Once the directory in the
demoman_blue vmt is changed to the temp folder and the vtf texture is in
the temp folder itself you are finally done.
I packed my mods into a vpk but I don't think it's required. Once in game
you must create a server via the create server button and select the map
that will load the custom texture before you join a valve server. I suggest
you only do this with player textures and such as they are always loaded.
After you load the map you join the valve server and the textures should
appear and work on valve servers.
This can be done on any sv_pure 1 server but it depends on what is type of
files are allowed. All valve servers allow temp files so that is the
example I used here."
So all vmt's files can bypass sv_pure 1. And I believe this mod is mostly
made of vmt files, so valve's sv_pure 1 bull is pretty redundant.
*/
const bool bUseCache = false;
#endif
// If pathID is null, we cannot cache the result because that has a weird iterate-through-a-bunch-of-locations behavior.
const bool bUseCacheForRead = bUseCache && !refreshCache && pathID != NULL;
const bool bUseCacheForWrite = bUseCache && pathID != NULL;
COM_TimestampedLog( "KeyValues::LoadFromFile(%s%s%s): Begin", pathID ? pathID : "", pathID && resourceName ? "/" : "", resourceName ? resourceName : "" );
// Keep a cache of keyvalues, try to load it here.
if ( bUseCacheForRead && KeyValuesSystem()->LoadFileKeyValuesFromCache( this, resourceName, pathID, filesystem ) ) {
COM_TimestampedLog( "KeyValues::LoadFromFile(%s%s%s): End / CacheHit", pathID ? pathID : "", pathID && resourceName ? "/" : "", resourceName ? resourceName : "" );
return true;
}
FileHandle_t f = filesystem->Open(resourceName, "rb", pathID);
if ( !f )
{
COM_TimestampedLog("KeyValues::LoadFromFile(%s%s%s): End / FileNotFound", pathID ? pathID : "", pathID && resourceName ? "/" : "", resourceName ? resourceName : "");
return false;
}
s_LastFileLoadingFrom = (char*)resourceName;
// load file into a null-terminated buffer
int fileSize = filesystem->Size( f );
unsigned bufSize = ((IFileSystem *)filesystem)->GetOptimalReadSize( f, fileSize + 2 );
char *buffer = (char*)((IFileSystem *)filesystem)->AllocOptimalReadBuffer( f, bufSize );
Assert( buffer );
// read into local buffer
bool bRetOK = ( ((IFileSystem *)filesystem)->ReadEx( buffer, bufSize, fileSize, f ) != 0 );
filesystem->Close( f ); // close file after reading
if ( bRetOK )
{
buffer[fileSize] = 0; // null terminate file as EOF
buffer[fileSize+1] = 0; // double NULL terminating in case this is a unicode file
bRetOK = LoadFromBuffer( resourceName, buffer, filesystem );
}
// The cache relies on the KeyValuesSystem string table, which will only be valid if we're
// using classic mode.
if ( bUseCacheForWrite && bRetOK )
{
KeyValuesSystem()->AddFileKeyValuesToCache( this, resourceName, pathID );
}
( (IFileSystem *)filesystem )->FreeOptimalReadBuffer( buffer );
COM_TimestampedLog("KeyValues::LoadFromFile(%s%s%s): End / Success", pathID ? pathID : "", pathID && resourceName ? "/" : "", resourceName ? resourceName : "");
return bRetOK;
}
//-----------------------------------------------------------------------------
// Purpose: Save the keyvalues to disk
// Creates the path to the file if it doesn't exist
//-----------------------------------------------------------------------------
bool KeyValues::SaveToFile( IBaseFileSystem *filesystem, const char *resourceName, const char *pathID, bool sortKeys /*= false*/, bool bAllowEmptyString /*= false*/, bool bCacheResult /*= false*/ )
{
// create a write file
FileHandle_t f = filesystem->Open(resourceName, "wb", pathID);
if ( f == FILESYSTEM_INVALID_HANDLE )
{
DevMsg(1, "KeyValues::SaveToFile: couldn't open file \"%s\" in path \"%s\".\n",
resourceName?resourceName:"NULL", pathID?pathID:"NULL" );
return false;
}
bool bSupportsCache = BKeyValuesSystemSupportsCache();
if (bSupportsCache)
{
KeyValuesSystem()->InvalidateCacheForFile(resourceName, pathID);
}
if ( bCacheResult && bSupportsCache ) {
KeyValuesSystem()->AddFileKeyValuesToCache( this, resourceName, pathID );
}
RecursiveSaveToFile(filesystem, f, NULL, 0, sortKeys, bAllowEmptyString );
filesystem->Close(f);
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Write out a set of indenting
//-----------------------------------------------------------------------------
void KeyValues::WriteIndents( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, int indentLevel )
{
for ( int i = 0; i < indentLevel; i++ )
{
INTERNALWRITE( "\t", 1 );
}
}
//-----------------------------------------------------------------------------
// Purpose: Write out a string where we convert the double quotes to backslash double quote
//-----------------------------------------------------------------------------
void KeyValues::WriteConvertedString( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, const char *pszString )
{
// handle double quote chars within the string
// the worst possible case is that the whole string is quotes
int len = Q_strlen(pszString);
char *convertedString = (char *) _alloca ((len + 1) * sizeof(char) * 2);
int j=0;
for (int i=0; i <= len; i++)
{
if (pszString[i] == '\"')
{
convertedString[j] = '\\';
j++;
}
else if ( m_bHasEscapeSequences && pszString[i] == '\\' )
{
convertedString[j] = '\\';
j++;
}
convertedString[j] = pszString[i];
j++;
}
INTERNALWRITE(convertedString, Q_strlen(convertedString));
}
void KeyValues::InternalWrite( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, const void *pData, int len )
{
if ( filesystem )
{
filesystem->Write( pData, len, f );
}
if ( pBuf )
{
pBuf->Put( pData, len );
}
}
//-----------------------------------------------------------------------------
// Purpose: Save keyvalues from disk, if subkey values are detected, calls
// itself to save those
//-----------------------------------------------------------------------------
void KeyValues::RecursiveSaveToFile( IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, int indentLevel, bool sortKeys, bool bAllowEmptyString )
{
// write header
WriteIndents( filesystem, f, pBuf, indentLevel );
INTERNALWRITE("\"", 1);
WriteConvertedString(filesystem, f, pBuf, GetName());
INTERNALWRITE("\"\n", 2);
WriteIndents( filesystem, f, pBuf, indentLevel );
INTERNALWRITE("{\n", 2);
// loop through all our keys writing them to disk
if ( sortKeys )
{
CUtlSortVector< KeyValues*, CUtlSortVectorKeyValuesByName > vecSortedKeys;
for ( KeyValues *dat = m_pSub; dat != NULL; dat = dat->m_pPeer )
{
vecSortedKeys.InsertNoSort(dat);
}
vecSortedKeys.RedoSort();
FOR_EACH_VEC( vecSortedKeys, i )
{
SaveKeyToFile( vecSortedKeys[i], filesystem, f, pBuf, indentLevel, sortKeys, bAllowEmptyString );
}
}
else
{
for ( KeyValues *dat = m_pSub; dat != NULL; dat = dat->m_pPeer )
SaveKeyToFile( dat, filesystem, f, pBuf, indentLevel, sortKeys, bAllowEmptyString );
}
// write tail
WriteIndents(filesystem, f, pBuf, indentLevel);
INTERNALWRITE("}\n", 2);
}
void KeyValues::SaveKeyToFile( KeyValues *dat, IBaseFileSystem *filesystem, FileHandle_t f, CUtlBuffer *pBuf, int indentLevel, bool sortKeys, bool bAllowEmptyString )
{
if ( dat->m_pSub )
{
dat->RecursiveSaveToFile( filesystem, f, pBuf, indentLevel + 1, sortKeys, bAllowEmptyString );
}
else
{
// only write non-empty keys
switch (dat->m_iDataType)
{
case TYPE_STRING:
{
if ( dat->m_sValue && ( bAllowEmptyString || *(dat->m_sValue) ) )
{
WriteIndents(filesystem, f, pBuf, indentLevel + 1);
INTERNALWRITE("\"", 1);
WriteConvertedString(filesystem, f, pBuf, dat->GetName());
INTERNALWRITE("\"\t\t\"", 4);
WriteConvertedString(filesystem, f, pBuf, dat->m_sValue);
INTERNALWRITE("\"\n", 2);
}
break;
}
case TYPE_WSTRING:
{
if ( dat->m_wsValue )
{
static char buf[KEYVALUES_TOKEN_SIZE];
// make sure we have enough space
int result = Q_UnicodeToUTF8( dat->m_wsValue, buf, KEYVALUES_TOKEN_SIZE);
if (result)
{
WriteIndents(filesystem, f, pBuf, indentLevel + 1);
INTERNALWRITE("\"", 1);
INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName()));
INTERNALWRITE("\"\t\t\"", 4);
WriteConvertedString(filesystem, f, pBuf, buf);
INTERNALWRITE("\"\n", 2);
}
}
break;
}
case TYPE_INT:
{
WriteIndents(filesystem, f, pBuf, indentLevel + 1);
INTERNALWRITE("\"", 1);
INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName()));
INTERNALWRITE("\"\t\t\"", 4);
char buf[32];
Q_snprintf(buf, sizeof( buf ), "%d", dat->m_iValue);
INTERNALWRITE(buf, Q_strlen(buf));
INTERNALWRITE("\"\n", 2);
break;
}
case TYPE_UINT64:
{
WriteIndents(filesystem, f, pBuf, indentLevel + 1);
INTERNALWRITE("\"", 1);
INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName()));
INTERNALWRITE("\"\t\t\"", 4);
char buf[32];
// write "0x" + 16 char 0-padded hex encoded 64 bit value
#ifdef WIN32
Q_snprintf( buf, sizeof( buf ), "0x%016I64X", *( (uint64 *)dat->m_sValue ) );
#else
Q_snprintf( buf, sizeof( buf ), "0x%016llX", *( (uint64 *)dat->m_sValue ) );
#endif
INTERNALWRITE(buf, Q_strlen(buf));
INTERNALWRITE("\"\n", 2);
break;
}
case TYPE_FLOAT:
{
WriteIndents(filesystem, f, pBuf, indentLevel + 1);
INTERNALWRITE("\"", 1);
INTERNALWRITE(dat->GetName(), Q_strlen(dat->GetName()));
INTERNALWRITE("\"\t\t\"", 4);
char buf[48];
Q_snprintf(buf, sizeof( buf ), "%f", dat->m_flValue);
INTERNALWRITE(buf, Q_strlen(buf));
INTERNALWRITE("\"\n", 2);
break;