-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathQueuedLoader.cpp
More file actions
1978 lines (1709 loc) · 61.2 KB
/
QueuedLoader.cpp
File metadata and controls
1978 lines (1709 loc) · 61.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
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. ============//
//
// Queued Loading of map resources. !!!!Specifically!!! designed for the map loading process.
//
// Not designed for application startup or gameplay time. Layered on top of async i/o.
// Queued loading is allowed during the map load process until full connection only,
// but can complete the remaining low priority jobs during the game render.
// The normal loading path can run in units of seconds if it does not have to do I/O,
// which is why this system runs first and gets all the data in memory unhindered
// by dependency blocking. The I/O delivery process achieves its speed by having all the I/O
// requests at once, performing the I/O, and handing the actual consumption
// of the I/O buffer to another available core/thread (via job pool) for computation work.
// The I/O (should be all unbuffered) is then only throttled by physical transfer rates.
//
// The Load process is broken into three phases. The first phase build up I/O requests.
// The second phase fulfills only the high priority I/O requests. This gets the critical
// data in memory, that has to be there for the normal load path to query, or the renderer
// to run (i.e. models and shaders). The third phase is the normal load process.
// The low priority jobs run concurrently with the normal load process. Low priority jobs
// are those that have been specially built such that the game or loading can operate unblocked
// without the actual data (i.e. d3d texture bits).
//
// Phase 1: The reslist is parsed into seperate lists based on handled extensions. Each list
// call its own loader which in turn generates its own dictionaries and I/O requests through
// "AddJob". A single reslist entry could cause a laoder to request multiple jobs. ( i.e. models )
// A loader marks its jobs as high or low priority.
// Phase 2: The I/O requests are sorted (which achieves seek offset order) and
// async i/o commences. Phase 2 does not end until all the high priority jobs
// are complete. This ensures critical data is resident.
// Phase 3: The !!!NORMAL!!! loading path can commence. The legacy loading path then
// is not expected to do I/O (it can, but that's a hole in the reslist), as all of the data
// that it queries, should be resident.
//
// Late added jobs are non-optimal (should have been in reslist), warned, but handled.
//
//===========================================================================//
#include "basefilesystem.h"
#include "tier0/vprof.h"
#include "tier0/tslist.h"
#include "tier1/utlbuffer.h"
#include "tier1/convar.h"
#include "tier1/KeyValues.h"
#include "tier1/utllinkedlist.h"
#include "tier1/utlstring.h"
#include "tier1/UtlSortVector.h"
#include "tier1/utldict.h"
#include "basefilesystem.h"
#include "tier0/icommandline.h"
#include "vstdlib/jobthread.h"
#include "filesystem/IQueuedLoader.h"
#include "tier2/tier2.h"
#include "characterset.h"
#if !defined( _X360 )
#include "xbox/xboxstubs.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define PRIORITY_HIGH 1
#define PRIORITY_NORMAL 0
#define PRIORITY_LOW -1
// main thread has reason to block and wait for thread pool to finish jobs
#define MAIN_THREAD_YIELD_TIME 20
// discrete stages in the preload process to tick the progress bar
#define PROGRESS_START 0.10f
#define PROGRESS_GOTRESLIST 0.12f
#define PROGRESS_PARSEDRESLIST 0.15f
#define PROGRESS_CREATEDRESOURCES 0.20f
#define PROGRESS_PREPURGE 0.22f
#define PROGRESS_IO 0.25f // up to 1.0
struct FileJob_t
{
FileJob_t()
{
Q_memset( this, 0, sizeof( FileJob_t ) );
}
FileNameHandle_t m_hFilename;
QueuedLoaderCallback_t m_pCallback;
FSAsyncControl_t m_hAsyncControl;
void *m_pContext;
void *m_pContext2;
void *m_pTargetData;
int m_nBytesToRead;
unsigned int m_nStartOffset;
LoaderPriority_t m_Priority;
unsigned int m_SubmitTime;
unsigned int m_FinishTime;
int m_SubmitTag;
int m_nActualBytesRead;
LoaderError_t m_LoaderError;
unsigned int m_ThreadId;
unsigned int m_bFinished : 1;
unsigned int m_bFreeTargetAfterIO : 1;
unsigned int m_bFileExists : 1;
unsigned int m_bClaimed : 1;
};
// dummy stubbed progress interface
class CDummyProgress : public ILoaderProgress
{
void BeginProgress() {}
void UpdateProgress( float progress ) {}
void EndProgress() {}
};
static CDummyProgress s_DummyProgress;
class CQueuedLoader : public CTier2AppSystem< IQueuedLoader >
{
typedef CTier2AppSystem< IQueuedLoader > BaseClass;
public:
CQueuedLoader();
virtual ~CQueuedLoader();
// Inherited from IAppSystem
virtual InitReturnVal_t Init();
virtual void Shutdown();
// IQueuedLoader
virtual void InstallLoader( ResourcePreload_t type, IResourcePreload *pLoader );
virtual void InstallProgress( ILoaderProgress *pProgress );
// Set bOptimizeReload if you want appropriate data (such as static prop lighting)
// to persist - rather than being purged and reloaded - when going from map A to map A.
virtual bool BeginMapLoading( const char *pMapName, bool bLoadForHDR, bool bOptimizeMapReload );
virtual void EndMapLoading( bool bAbort );
virtual bool AddJob( const LoaderJob_t *pLoaderJob );
virtual void AddMapResource( const char *pFilename );
virtual void DynamicLoadMapResource( const char *pFilename, DynamicResourceCallback_t pCallback, void *pContext, void *pContext2 );
virtual void QueueDynamicLoadFunctor( CFunctor* pFunctor );
virtual bool CompleteDynamicLoad();
virtual void QueueCleanupDynamicLoadFunctor( CFunctor* pFunctor );
virtual bool CleanupDynamicLoad();
virtual bool ClaimAnonymousJob( const char *pFilename, QueuedLoaderCallback_t pCallback, void *pContext, void *pContext2 );
virtual bool ClaimAnonymousJob( const char *pFilename, void **pData, int *pDataSize, LoaderError_t *pError );
virtual bool IsMapLoading() const;
virtual bool IsSameMapLoading() const;
virtual bool IsFinished() const;
virtual bool IsBatching() const;
virtual bool IsDynamic() const;
virtual int GetSpewDetail() const;
char *GetFilename( const FileNameHandle_t hFilename, char *pBuff, int nBuffSize );
FileNameHandle_t FindFilename( const char *pFilename );
void SpewInfo();
// submit any queued jobs to the async loader, called by main or async thread to get more work
void SubmitPendingJobs();
void PurgeAll();
private:
class CFileJobsLessFunc
{
public:
int GetLayoutOrderForFilename( const char *pFilename );
bool Less( FileJob_t* const &pFileJobLHS, FileJob_t* const &pFileJobRHS, void *pCtx );
};
class CResourceNameLessFunc
{
public:
bool Less( const FileNameHandle_t &hFilenameLHS, const FileNameHandle_t &hFilenameRHS, void *pCtx );
};
typedef CUtlSortVector< FileNameHandle_t, CResourceNameLessFunc > ResourceList_t;
static void BuildResources( IResourcePreload *pLoader, ResourceList_t *pList, float *pBuildTime );
static void BuildMaterialResources( IResourcePreload *pLoader, ResourceList_t *pList, float *pBuildTime );
void PurgeQueue();
void CleanQueue();
void SubmitBatchedJobs();
void SubmitBatchedJobsAndWait();
void ParseResourceList( CUtlBuffer &resourceList );
void GetJobRequests();
void PurgeUnreferencedResources();
void AddResourceToTable( const char *pFilename );
bool m_bStarted;
bool m_bActive;
bool m_bBatching;
bool m_bDynamic;
bool m_bCanBatch;
bool m_bLoadForHDR;
bool m_bDoProgress;
bool m_bSameMap;
int m_nSubmitCount;
unsigned int m_StartTime;
unsigned int m_EndTime;
char m_szMapNameToCompareSame[MAX_PATH];
DynamicResourceCallback_t m_pfnDynamicCallback;
CUtlString m_DynamicFileName;
void* m_pDynamicContext;
void* m_pDynamicContext2;
CThreadFastMutex m_FunctorQueueMutex;
CUtlVector< CFunctor* > m_FunctorQueue;
CUtlVector< CFunctor* > m_CleanupFunctorQueue;
CUtlFilenameSymbolTable m_Filenames;
CTSList< FileJob_t* > m_PendingJobs;
CTSList< FileJob_t* > m_BatchedJobs;
CUtlLinkedList< FileJob_t* > m_SubmittedJobs;
CUtlDict< FileJob_t*, int > m_AnonymousJobs;
CUtlSymbolTable m_AdditionalResources;
CUtlSortVector< FileNameHandle_t, CResourceNameLessFunc > m_ResourceNames[RESOURCEPRELOAD_COUNT];
IResourcePreload *m_pLoaders[RESOURCEPRELOAD_COUNT];
float m_LoaderTimes[RESOURCEPRELOAD_COUNT];
ILoaderProgress *m_pProgress;
CThreadFastMutex m_Mutex;
};
static CQueuedLoader g_QueuedLoader;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CQueuedLoader, IQueuedLoader, QUEUEDLOADER_INTERFACE_VERSION, g_QueuedLoader );
class CResourcePreloadAnonymous : public IResourcePreload
{
virtual bool CreateResource( const char *pName )
{
// create an anonymous job to get the data in memory, claimed during load, or auto-freed
LoaderJob_t loaderJob;
loaderJob.m_pFilename = pName;
loaderJob.m_pPathID = "GAME";
loaderJob.m_Priority = LOADERPRIORITY_DURINGPRELOAD;
g_QueuedLoader.AddJob( &loaderJob );
return true;
}
virtual void PurgeUnreferencedResources() {}
virtual void OnEndMapLoading( bool bAbort ) {}
virtual void PurgeAll() {}
};
static CResourcePreloadAnonymous s_ResourcePreloadAnonymous;
const char *g_ResourceLoaderNames[RESOURCEPRELOAD_COUNT] =
{
"???", // RESOURCEPRELOAD_UNKNOWN
"Sounds", // RESOURCEPRELOAD_SOUND
"Materials", // RESOURCEPRELOAD_MATERIAL
"Models", // RESOURCEPRELOAD_MODEL
"Cubemaps", // RESOURCEPRELOAD_CUBEMAP
"PropLighting", // RESOURCEPRELOAD_STATICPROPLIGHTING
"Anonymous", // RESOURCEPRELOAD_ANONYMOUS
};
static CInterlockedInt g_nActiveJobs;
static CInterlockedInt g_nQueuedJobs;
static CInterlockedInt g_nHighPriorityJobs; // tracks jobs that must finish during preload
static CInterlockedInt g_nJobsToFinishBeforePlay; // tracks jobs that must finish before gameplay
static CInterlockedInt g_nIOMemory; // tracks I/O data from async delivery until consumed
static CInterlockedInt g_nAnonymousIOMemory; // tracks anonymous I/O data from async delivery until consumed
static CInterlockedInt g_SuspendIO; // used to throttle the I/O
static int g_nIOMemoryPeak;
static int g_nAnonymousIOMemoryPeak;
static int g_nHighIOSuspensionMark;
static int g_nLowIOSuspensionMark;
ConVar loader_spew_info( "loader_spew_info", "0", 0, "0:Off, 1:Timing, 2:Completions, 3:Late Completions, 4:Purges, -1:All " );
// Kyle says: this is here only to change the DLL size to force clients to update! This should be removed
// by whoever sees this comment after we've shipped a DLL using it!
ConVar loader_sped_info_ex( "loader_spew_info_ex", "0", 0, "(internal)" );
CON_COMMAND( loader_dump_table, "" )
{
g_QueuedLoader.SpewInfo();
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CQueuedLoader::CQueuedLoader() : BaseClass( false )
{
m_bStarted = false;
m_bActive = false;
m_bBatching = false;
m_bDynamic = false;
m_bCanBatch = false;
m_bLoadForHDR = false;
m_bDoProgress = false;
m_bSameMap = false;
m_nSubmitCount = 0;
m_pfnDynamicCallback = NULL;
m_pDynamicContext = NULL;
m_pDynamicContext2 = NULL;
m_szMapNameToCompareSame[0] = '\0';
m_pProgress = &s_DummyProgress;
V_memset( m_pLoaders, 0, sizeof( m_pLoaders ) );
// set resource dictionaries sort context
for ( int i = 0; i < RESOURCEPRELOAD_COUNT; i++ )
{
m_ResourceNames[i].SetLessContext( (void *)i );
}
InstallLoader( RESOURCEPRELOAD_ANONYMOUS, &s_ResourcePreloadAnonymous );
}
//-----------------------------------------------------------------------------
// Destructor
//-----------------------------------------------------------------------------
CQueuedLoader::~CQueuedLoader()
{
}
//-----------------------------------------------------------------------------
// Computation job to build out objects
//-----------------------------------------------------------------------------
void CQueuedLoader::BuildResources( IResourcePreload *pLoader, ResourceList_t *pList, float *pBuildTime )
{
float t0 = Plat_FloatTime();
if ( pLoader )
{
pList->RedoSort();
for ( int i = 0; i < pList->Count(); i++ )
{
char szFilename[MAX_PATH];
g_QueuedLoader.GetFilename( pList->Element( i ), szFilename, sizeof( szFilename ) );
if ( szFilename[0] )
{
if ( !pLoader->CreateResource( szFilename ) )
{
Warning( "QueuedLoader: Failed to create resource %s\n", szFilename );
}
}
}
}
// finished with list
pList->Purge();
*pBuildTime = Plat_FloatTime() - t0;
}
//-----------------------------------------------------------------------------
// Computation job to build out material objects
//-----------------------------------------------------------------------------
void CQueuedLoader::BuildMaterialResources( IResourcePreload *pLoader, ResourceList_t *pList, float *pBuildTime )
{
float t0 = Plat_FloatTime();
char szLastFilename[MAX_PATH];
szLastFilename[0] = '\0';
// ensure cubemaps are first
pList->RedoSort();
// run a clean operation to cull the non-patched env_cubemap materials, which are not built directly
for ( int i = 0; i < pList->Count(); i++ )
{
char szFilename[MAX_PATH];
char *pFilename = g_QueuedLoader.GetFilename( pList->Element( i ), szFilename, sizeof( szFilename ) );
if ( !V_stristr( pFilename, "maps\\" ) )
{
// list is sorted, first non-cubemap marks end of relevant list
break;
}
// skip past maps/mapname/
pFilename += 5;
pFilename = strchr( pFilename, '\\' ) + 1;
// back up until end of material name is found, need to strip off _%d_%d_%d.vmt
char *pEndFilename = V_stristr( pFilename, ".vmt" );
if ( !pEndFilename )
{
pEndFilename = pFilename + strlen( pFilename );
}
int numUnderscores = 3;
while ( pEndFilename != pFilename && numUnderscores > 0 )
{
pEndFilename--;
if ( pEndFilename[0] == '_' )
{
numUnderscores--;
}
}
if ( numUnderscores == 0 )
{
*pEndFilename = '\0';
if ( !V_strcmp( szLastFilename, pFilename ) )
{
// same cubemap material base already processed, skip it
continue;
}
V_strncpy( szLastFilename, pFilename, sizeof( szLastFilename ) );
strcat( pFilename, ".vmt" );
FileNameHandle_t hFilename = g_QueuedLoader.FindFilename( pFilename );
if ( hFilename )
{
pList->Remove( hFilename );
}
}
}
// process clean list
BuildResources( pLoader, pList, pBuildTime );
*pBuildTime = Plat_FloatTime() - t0;
}
//-----------------------------------------------------------------------------
// Called by multiple worker threads. Throttle the I/O to ensure too many
// buffers don't flood the work queue. Anonymous I/O is allowed to grow unbounded.
//-----------------------------------------------------------------------------
void AdjustAsyncIOSpeed()
{
if ( g_QueuedLoader.IsDynamic() == true )
{
return;
}
// throttle back the I/O to keep the pending buffers from exhausting memory
if ( g_SuspendIO == 0 )
{
if ( g_nIOMemory >= g_nHighIOSuspensionMark && g_nActiveJobs != 0 )
{
// protect against another worker thread
if ( g_SuspendIO.AssignIf( 0, 1 ) )
{
if ( g_QueuedLoader.GetSpewDetail() )
{
Msg( "QueuedLoader: Suspending I/O at %.2f MB\n", (float)g_nIOMemory / ( 1024.0f * 1024.0f ) );
}
g_pFullFileSystem->AsyncSuspend();
}
}
}
else if ( g_SuspendIO == 1 )
{
if ( g_nIOMemory <= g_nLowIOSuspensionMark )
{
// protect against another worker thread
if ( g_SuspendIO.AssignIf( 1, 0 ) )
{
if ( g_QueuedLoader.GetSpewDetail() )
{
Msg( "QueuedLoader: Resuming I/O at %.2f MB\n", (float)g_nIOMemory / ( 1024.0f * 1024.0f ) );
}
g_pFullFileSystem->AsyncResume();
}
}
}
}
//-----------------------------------------------------------------------------
// Computation job to do work after IO, runs callback
//-----------------------------------------------------------------------------
void IOComputationJob( FileJob_t *pFileJob, void *pData, int nSize, LoaderError_t loaderError )
{
int spewDetail = g_QueuedLoader.GetSpewDetail();
if ( spewDetail & ( LOADER_DETAIL_COMPLETIONS|LOADER_DETAIL_LATECOMPLETIONS ) )
{
const char *pLateString = "";
if ( !g_QueuedLoader.IsMapLoading() )
{
// completed outside of load process
pLateString = "(Late) ";
}
if ( ( spewDetail & LOADER_DETAIL_COMPLETIONS ) || ( ( spewDetail & LOADER_DETAIL_LATECOMPLETIONS ) && pLateString[0] ) )
{
char szFilename[MAX_PATH];
g_QueuedLoader.GetFilename( pFileJob->m_hFilename, szFilename, sizeof( szFilename ) );
Msg( "QueuedLoader: Computation:%8.8x, Size:%7d %s%s\n", ThreadGetCurrentId(), nSize, pLateString, szFilename );
}
}
if ( loaderError != LOADERERROR_NONE && pFileJob->m_bFileExists )
{
char szFilename[MAX_PATH];
g_QueuedLoader.GetFilename( pFileJob->m_hFilename, szFilename, sizeof( szFilename ) );
Warning( "QueuedLoader:: I/O Error on %s\n", szFilename );
}
pFileJob->m_nActualBytesRead = nSize;
pFileJob->m_LoaderError = loaderError;
if ( !pFileJob->m_pCallback )
{
// absent callback means resource loader want this system to delay buffer until ready for it
if ( !pFileJob->m_pTargetData )
{
// track it for later, unclaimed buffers will get freed
pFileJob->m_pTargetData = pData;
}
}
else
{
// regardless of error, call job callback so caller can do cleanup of their context
pFileJob->m_pCallback( pFileJob->m_pContext, pFileJob->m_pContext2, pData, nSize, loaderError );
if ( pFileJob->m_bFreeTargetAfterIO && pData )
{
// free our data only
g_pFullFileSystem->FreeOptimalReadBuffer( pData );
}
// memory has been consumed
g_nIOMemory -= nSize;
}
// mark as completed
pFileJob->m_bFinished = true;
pFileJob->m_FinishTime = Plat_MSTime();
pFileJob->m_ThreadId = ThreadGetCurrentId();
if ( pFileJob->m_Priority == LOADERPRIORITY_DURINGPRELOAD )
{
g_nHighPriorityJobs--;
}
else if ( pFileJob->m_Priority == LOADERPRIORITY_BEFOREPLAY )
{
g_nJobsToFinishBeforePlay--;
}
g_nQueuedJobs--;
if ( g_nQueuedJobs == 0 && ( spewDetail & LOADER_DETAIL_TIMING ) )
{
Msg( "QueuedLoader: Finished I/O of all queued jobs!\n" );
}
AdjustAsyncIOSpeed();
}
//-----------------------------------------------------------------------------
// Computation job to do work after anonymous job was asynchronously claimed, runs callback.
//-----------------------------------------------------------------------------
void FinishAnonymousJob( FileJob_t *pFileJob, QueuedLoaderCallback_t pCallback, void *pContext, void *pContext2 )
{
// regardless of error, call job callback so caller can do cleanup of their context
pCallback( pContext, pContext2, pFileJob->m_pTargetData, pFileJob->m_nActualBytesRead, pFileJob->m_LoaderError );
if ( pFileJob->m_bFreeTargetAfterIO && pFileJob->m_pTargetData )
{
// free our data only
g_pFullFileSystem->FreeOptimalReadBuffer( pFileJob->m_pTargetData );
pFileJob->m_pTargetData = NULL;
}
pFileJob->m_bClaimed = true;
// memory has been consumed
g_nAnonymousIOMemory -= pFileJob->m_nActualBytesRead;
}
//-----------------------------------------------------------------------------
// Callback from I/O job thread. Purposely lightweight as possible to keep i/o from stalling.
//-----------------------------------------------------------------------------
void IOAsyncCallback( const FileAsyncRequest_t &asyncRequest, int numReadBytes, FSAsyncStatus_t asyncStatus )
{
FileJob_t *pFileJob = (FileJob_t *)asyncRequest.pContext;
// interpret the async error
LoaderError_t loaderError;
switch ( asyncStatus )
{
case FSASYNC_OK:
loaderError = LOADERERROR_NONE;
break;
case FSASYNC_ERR_FILEOPEN:
loaderError = LOADERERROR_FILEOPEN;
break;
default:
loaderError = LOADERERROR_READING;
}
// track how much i/o data is in flight, consumption will decrement
if ( !pFileJob->m_pCallback )
{
// anonymous io memory is tracked seperatley
g_nAnonymousIOMemory += numReadBytes;
if ( g_nAnonymousIOMemory > g_nAnonymousIOMemoryPeak )
{
g_nAnonymousIOMemoryPeak = g_nAnonymousIOMemory;
}
}
else
{
g_nIOMemory += numReadBytes;
if ( g_nIOMemory > g_nIOMemoryPeak )
{
g_nIOMemoryPeak = g_nIOMemory;
}
}
// have data or error, do callback as a computation job
if ( !g_QueuedLoader.IsDynamic() )
{
g_pThreadPool->QueueCall( IOComputationJob, pFileJob, asyncRequest.pData, numReadBytes, loaderError )->Release();
}
else
{
g_QueuedLoader.QueueDynamicLoadFunctor( CreateFunctor( IOComputationJob, pFileJob, asyncRequest.pData, numReadBytes, loaderError ) );
}
// don't let the i/o starve, possibly get some more work from the pending queue
g_QueuedLoader.SubmitPendingJobs();
// possibly goes to zero atomically, AFTER submission
// prevents contention between main thread
--g_nActiveJobs;
}
//-----------------------------------------------------------------------------
// Public method to filename dictionary
//-----------------------------------------------------------------------------
char *CQueuedLoader::GetFilename( const FileNameHandle_t hFilename, char *pBuff, int nBuffSize )
{
m_Filenames.String( hFilename, pBuff, nBuffSize );
return pBuff;
}
//-----------------------------------------------------------------------------
// Public method to filename dictionary
//-----------------------------------------------------------------------------
FileNameHandle_t CQueuedLoader::FindFilename( const char *pFilename )
{
return m_Filenames.FindFileName( pFilename );
}
//-----------------------------------------------------------------------------
// Sort function for resource names.
//-----------------------------------------------------------------------------
bool CQueuedLoader::CResourceNameLessFunc::Less( const FileNameHandle_t &hFilenameLHS, const FileNameHandle_t &hFilenameRHS, void *pCtx )
{
switch ( (int)pCtx )
{
case RESOURCEPRELOAD_MATERIAL:
{
// Cubemap materials are expected to be at top of list
char szNameLHS[MAX_PATH];
char szNameRHS[MAX_PATH];
const char *pNameLHS = g_QueuedLoader.GetFilename( hFilenameLHS, szNameLHS, sizeof( szNameLHS ) );
const char *pNameRHS = g_QueuedLoader.GetFilename( hFilenameRHS, szNameRHS, sizeof( szNameRHS ) );
bool bIsCubemapLHS = V_stristr( pNameLHS, "maps\\" ) != NULL;
bool bIsCubemapRHS = V_stristr( pNameRHS, "maps\\" ) != NULL;
if ( bIsCubemapLHS != bIsCubemapRHS )
{
return ( bIsCubemapLHS == true && bIsCubemapRHS == false );
}
return ( V_stricmp( pNameLHS, pNameRHS ) < 0 );
}
break;
default:
// sort not really needed, just use numeric handles
return ( hFilenameLHS < hFilenameRHS );
}
}
//-----------------------------------------------------------------------------
// Resolve filenames to expected disc layout order as...
// bsp, graphs, platform, hl2, episodic, ep2, tf, portal, non-zip
// see XGD layout.
//-----------------------------------------------------------------------------
int CQueuedLoader::CFileJobsLessFunc::GetLayoutOrderForFilename( const char *pFilename )
{
bool bIsLocalizedZip = false;
if ( XBX_IsLocalized() )
{
if ( V_stristr( pFilename, "\\zip" ) && V_stristr( pFilename, XBX_GetLanguageString() ) )
{
bIsLocalizedZip = true;
}
}
int order;
if ( V_stristr( pFilename, "\\maps\\" ) )
{
// bsp's and graphs on the opposite layer, these must be topmost
// the queued loader is expecting to do these first, all at once
// this allows for a single layer switch
if ( V_stristr( pFilename, "\\graphs\\" ) )
{
order = 1;
}
else
{
order = 0;
}
}
else if ( V_stristr( pFilename, "\\platform\\zip" ) )
{
order = 2;
}
else if ( V_stristr( pFilename, "\\hl2\\zip" ) )
{
order = 3;
}
else if ( V_stristr( pFilename, "\\episodic\\zip" ) )
{
order = 4;
}
else if ( V_stristr( pFilename, "\\ep2\\zip" ) )
{
order = 5;
}
else if ( V_stristr( pFilename, "\\tf\\zip" ) )
{
order = 6;
}
else if ( V_stristr( pFilename, "\\portal\\zip" ) )
{
order = 7;
}
else
{
// other
order = 8;
}
// localized zips have same relative sort order, but after all other zips
return bIsLocalizedZip ? 10*order : order;
}
//-----------------------------------------------------------------------------
// Sort function, high priority jobs sort first, then offset, then zip
//-----------------------------------------------------------------------------
bool CQueuedLoader::CFileJobsLessFunc::Less( FileJob_t* const &pFileJobLHS, FileJob_t* const &pFileJobRHS, void *pCtx )
{
if ( pFileJobLHS->m_Priority != pFileJobRHS->m_Priority )
{
// higher priorities sort to top
return ( pFileJobLHS->m_Priority > pFileJobRHS->m_Priority );
}
if ( pFileJobLHS->m_hFilename == pFileJobRHS->m_hFilename )
{
// same file (zip), sort by offset
return pFileJobLHS->m_nStartOffset < pFileJobRHS->m_nStartOffset;
}
char szFilenameLHS[MAX_PATH];
char szFilenameRHS[MAX_PATH];
g_QueuedLoader.GetFilename( pFileJobLHS->m_hFilename, szFilenameLHS, sizeof( szFilenameLHS ) );
g_QueuedLoader.GetFilename( pFileJobRHS->m_hFilename, szFilenameRHS, sizeof( szFilenameRHS ) );
// resolve filename to match disk layout of zips
int layoutLHS = GetLayoutOrderForFilename( szFilenameLHS );
int layoutRHS = GetLayoutOrderForFilename( szFilenameRHS );
if ( layoutLHS != layoutRHS )
{
return layoutLHS < layoutRHS;
}
return CaselessStringLessThan( szFilenameLHS, szFilenameRHS );
}
//-----------------------------------------------------------------------------
// Dump the queue contents to the file system.
//-----------------------------------------------------------------------------
void CQueuedLoader::SubmitPendingJobs()
{
// prevents contention between I/O and main thread attempting to submit
if ( ThreadInMainThread() && g_nActiveJobs != 0 && m_bDynamic == false )
{
// main thread can only kick start work if the I/O is idle
// once the I/O is kicked off, the I/O thread is responsible for continual draining
return;
}
else if ( !ThreadInMainThread() && g_nActiveJobs != 1 && m_bDynamic == false )
{
// I/O thread requests more work, but will only fall through and get some when it expects to go idle
// I/O thread still has jobs and doesn't need any more yet
return;
}
CTSList<FileJob_t *>::Node_t *pNode = m_PendingJobs.Detach();
if ( !pNode )
{
return;
}
// used by spew to indicate submission blocks
m_nSubmitCount++;
// sort entries
CUtlSortVector< FileJob_t*, CFileJobsLessFunc > sortedFiles( 0, 128 );
while ( pNode )
{
FileJob_t *pFileJob = pNode->elem;
sortedFiles.InsertNoSort( pFileJob );
CTSList<FileJob_t *>::Node_t *pNext = (CTSList<FileJob_t *>::Node_t*)pNode->Next;
delete pNode;
pNode = pNext;
}
sortedFiles.RedoSort();
FileAsyncRequest_t asyncRequest;
asyncRequest.pfnCallback = IOAsyncCallback;
char szFilename[MAX_PATH];
for ( int i = 0; i<sortedFiles.Count(); i++ )
{
FileJob_t *pFileJob = sortedFiles[i];
pFileJob->m_SubmitTag = m_nSubmitCount;
pFileJob->m_SubmitTime = Plat_MSTime();
m_SubmittedJobs.AddToTail( pFileJob );
// build an async request
if ( pFileJob->m_Priority == LOADERPRIORITY_DURINGPRELOAD )
{
// must finish during preload
asyncRequest.priority = PRIORITY_HIGH;
g_nHighPriorityJobs++;
}
else if ( pFileJob->m_Priority == LOADERPRIORITY_BEFOREPLAY )
{
// must finish before gameplay
asyncRequest.priority = PRIORITY_NORMAL;
g_nJobsToFinishBeforePlay++;
}
else
{
// can finish during gameplay, normal priority
asyncRequest.priority = PRIORITY_NORMAL;
}
// async will allocate unless caller provided a target
// loader always takes ownership of buffer
asyncRequest.pData = pFileJob->m_pTargetData;
asyncRequest.flags = pFileJob->m_pTargetData ? 0 : FSASYNC_FLAGS_ALLOCNOFREE;
asyncRequest.nOffset = pFileJob->m_nStartOffset;
asyncRequest.nBytes = pFileJob->m_nBytesToRead;
asyncRequest.pszFilename = GetFilename( pFileJob->m_hFilename, szFilename, sizeof( szFilename ) );
asyncRequest.pContext = (void *)pFileJob;
if ( pFileJob->m_bFileExists )
{
// start the valid async request
g_nActiveJobs++;
g_pFullFileSystem->AsyncRead( asyncRequest, &pFileJob->m_hAsyncControl );
}
else
{
// prevent dragging the i/o system down for known failures
// still need to do callback so subsystems can do the right thing based on file absence
if ( IsDynamic() )
QueueDynamicLoadFunctor( CreateFunctor( IOComputationJob, pFileJob, pFileJob->m_pTargetData, 0, LOADERERROR_FILEOPEN ) );
else
g_pThreadPool->QueueCall( IOComputationJob, pFileJob, pFileJob->m_pTargetData, 0, LOADERERROR_FILEOPEN )->Release();
}
}
}
//-----------------------------------------------------------------------------
// Add to queue
//-----------------------------------------------------------------------------
bool CQueuedLoader::AddJob( const LoaderJob_t *pLoaderJob )
{
if ( !m_bActive )
{
return false;
}
Assert( pLoaderJob && pLoaderJob->m_pFilename );
if ( m_bCanBatch && !m_bBatching )
{
// should have been part of pre-load batch
DevWarning( "QueuedLoader: Late Queued Job: %s\n", pLoaderJob->m_pFilename );
}
// anonymous jobs lack callbacks and are heavily restricted to ensure their stability
// the caller is expected to claim these before load ends (which auto-purges them)
if ( !pLoaderJob->m_pCallback && pLoaderJob->m_Priority == LOADERPRIORITY_ANYTIME )
{
Assert( 0 );
DevWarning( "QueuedLoader: Ignoring Anonymous Job: %s\n", pLoaderJob->m_pFilename );
return false;
}
MEM_ALLOC_CREDIT();
// all bsp based files get forced to a higher priority in order to achieve a clustered sort
// the bsp files are not going to be anywhere near the zips, thus we don't want head thrashing
bool bFileIsFromBSP;
bool bExists = false;
char *pFullPath;
char szFullPath[MAX_PATH];
if ( V_IsAbsolutePath( pLoaderJob->m_pFilename ) )
{
// an absolute path is trusted, take as is
pFullPath = (char *)pLoaderJob->m_pFilename;
bFileIsFromBSP = V_stristr( pFullPath, ".bsp" ) != NULL;
bExists = true;
}
else
{
// must resolve now, all submitted paths must be absolute for proper sort which achieves seek linearization
// a resolved absolute file ensures its existence
PathTypeFilter_t pathFilter = FILTER_NONE;
if ( IsX360() && ( g_pFullFileSystem->GetDVDMode() == DVDMODE_STRICT ) )
{
if ( V_stristr( pLoaderJob->m_pFilename, ".bsp" ) || V_stristr( pLoaderJob->m_pFilename, ".ain" ) )
{
// only the bsp/ain are allowed to be external
pathFilter = FILTER_CULLPACK;
}
else
{
// all files are expected to be in zip
pathFilter = FILTER_CULLNONPACK;
}
}
PathTypeQuery_t pathType;
g_pFullFileSystem->RelativePathToFullPath( pLoaderJob->m_pFilename, pLoaderJob->m_pPathID, szFullPath, sizeof( szFullPath ), pathFilter, &pathType );
bExists = V_IsAbsolutePath( szFullPath );
pFullPath = szFullPath;
bFileIsFromBSP = ( (pathType & PATH_IS_MAPPACKFILE) != 0 );
}
// create a file job
FileJob_t *pFileJob = new FileJob_t;
pFileJob->m_hFilename = m_Filenames.FindOrAddFileName( pFullPath );
pFileJob->m_bFileExists = bExists;
pFileJob->m_pCallback = pLoaderJob->m_pCallback;
pFileJob->m_pContext = pLoaderJob->m_pContext;
pFileJob->m_pContext2 = pLoaderJob->m_pContext2;
pFileJob->m_pTargetData = pLoaderJob->m_pTargetData;
pFileJob->m_nBytesToRead = pLoaderJob->m_nBytesToRead;
pFileJob->m_nStartOffset = pLoaderJob->m_nStartOffset;
pFileJob->m_Priority = bFileIsFromBSP ? LOADERPRIORITY_DURINGPRELOAD : pLoaderJob->m_Priority;
if ( pLoaderJob->m_pTargetData )
{
// never free caller's buffer, if they provide, they have to free it
pFileJob->m_bFreeTargetAfterIO = false;
}
else
{
// caller can take over ownership, otherwise it gets freed after I/O
pFileJob->m_bFreeTargetAfterIO = ( pLoaderJob->m_bPersistTargetData == false );
}
if ( !pLoaderJob->m_pCallback )
{
// track anonymous jobs
AUTO_LOCK( m_Mutex );
char szFixedName[MAX_PATH];
V_strncpy( szFixedName, pLoaderJob->m_pFilename, sizeof( szFixedName ) );
V_FixSlashes( szFixedName );
m_AnonymousJobs.Insert( szFixedName, pFileJob );
}
g_nQueuedJobs++;
if ( m_bBatching )
{
m_BatchedJobs.PushItem( pFileJob );
}
else
{
m_PendingJobs.PushItem( pFileJob );
SubmitPendingJobs();
}
return true;
}
//-----------------------------------------------------------------------------
// Allows an external system to append to a map's reslist. The next map load
// will append these specified files. Unhandled resources will just get
// quietly discarded. An external system could use this to patch a hole
// or prevent a purge.
//-----------------------------------------------------------------------------
void CQueuedLoader::AddMapResource( const char *pFilename )
{
if ( !pFilename || !pFilename[0] )
{
// pointless