Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

736 lines
32 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. //=============================================================================
  6. #ifndef CMATERIALSYSTEM_H
  7. #define CMATERIALSYSTEM_H
  8. #include "tier1/delegates.h"
  9. #include "materialsystem_global.h"
  10. #include "materialsystem/imaterialsystem.h"
  11. #include "materialsystem/ishaderapi.h"
  12. #include "imaterialinternal.h"
  13. #include "imaterialsysteminternal.h"
  14. #include "shaderapi/ishaderutil.h"
  15. #include "materialsystem/deformations.h"
  16. #include "tier1/utlintrusivelist.h"
  17. #include "utlvector.h"
  18. #include "utldict.h"
  19. #include "cmaterialdict.h"
  20. #include "cmatlightmaps.h"
  21. #include "cmatrendercontext.h"
  22. #include "cmatqueuedrendercontext.h"
  23. #include "materialsystem_global.h"
  24. #ifndef MATSYS_INTERNAL
  25. #error "This file is private to the implementation of IMaterialSystem/IMaterialSystemInternal"
  26. #endif
  27. #if defined( _WIN32 )
  28. #pragma once
  29. #endif
  30. //-----------------------------------------------------------------------------
  31. class CJob;
  32. class CTextureCompositor;
  33. class IThreadPool;
  34. struct DeferredUpdateLightmapInfo_t;
  35. // typedefs to allow use of delegation macros
  36. typedef int LightmapOffset_t[2];
  37. //-----------------------------------------------------------------------------
  38. extern CThreadFastMutex g_MatSysMutex;
  39. //-----------------------------------------------------------------------------
  40. // The material system implementation
  41. //-----------------------------------------------------------------------------
  42. class CMaterialSystem : public CTier2AppSystem< IMaterialSystemInternal >, public IShaderUtil
  43. {
  44. typedef CTier2AppSystem< IMaterialSystemInternal > BaseClass;
  45. public:
  46. CMaterialSystem();
  47. ~CMaterialSystem();
  48. //---------------------------------------------------------
  49. // Initialization and shutdown
  50. //---------------------------------------------------------
  51. //
  52. // IAppSystem
  53. //
  54. virtual bool Connect( CreateInterfaceFn factory );
  55. virtual void Disconnect();
  56. virtual void * QueryInterface( const char *pInterfaceName );
  57. virtual InitReturnVal_t Init();
  58. virtual void Shutdown();
  59. CreateInterfaceFn Init( const char* pShaderDLL,
  60. IMaterialProxyFactory* pMaterialProxyFactory,
  61. CreateInterfaceFn fileSystemFactory,
  62. CreateInterfaceFn cvarFactory );
  63. // Call this to set an explicit shader version to use
  64. // Must be called before Init().
  65. void SetShaderAPI( const char *pShaderAPIDLL );
  66. // Must be called before Init(), if you're going to call it at all...
  67. void SetAdapter( int nAdapter, int nFlags );
  68. void ModInit();
  69. void ModShutdown();
  70. private:
  71. // Used to dynamically load and unload the shader api
  72. CreateInterfaceFn CreateShaderAPI( const char* pShaderDLL );
  73. void DestroyShaderAPI();
  74. // Method to get at interfaces supported by the SHADDERAPI
  75. void * QueryShaderAPI( const char *pInterfaceName );
  76. // Initializes the color correction terms
  77. void InitColorCorrection();
  78. // force the thread mode to single threaded, synchronizes with render thread if running
  79. void ForceSingleThreaded();
  80. void ThreadRelease( );
  81. void ThreadAcquire( bool bForce = false );
  82. public:
  83. virtual void SetThreadMode( MaterialThreadMode_t nextThreadMode, int nServiceThread );
  84. virtual MaterialThreadMode_t GetThreadMode( ); // current thread mode
  85. virtual bool IsRenderThreadSafe( );
  86. virtual bool AllowThreading( bool bAllow, int nServiceThread );
  87. virtual void ExecuteQueued();
  88. //---------------------------------------------------------
  89. // Component accessors
  90. //---------------------------------------------------------
  91. const CMatLightmaps * GetLightmaps() const { return &m_Lightmaps; }
  92. CMatLightmaps * GetLightmaps() { return &m_Lightmaps; }
  93. IMatRenderContext * GetRenderContext();
  94. IMatRenderContext * CreateRenderContext( MaterialContextType_t type );
  95. IMatRenderContext * SetRenderContext( IMatRenderContext * );
  96. const IMatRenderContextInternal * GetRenderContextInternal() const { IMatRenderContextInternal *pRenderContext = m_pRenderContext.Get(); return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
  97. IMatRenderContextInternal * GetRenderContextInternal() { IMatRenderContextInternal *pRenderContext = m_pRenderContext.Get(); return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
  98. const CMaterialDict * GetMaterialDict() const { return &m_MaterialDict; }
  99. CMaterialDict * GetMaterialDict() { return &m_MaterialDict; }
  100. virtual void ReloadFilesInList( IFileList *pFilesToReload );
  101. public:
  102. //---------------------------------------------------------
  103. // Config management
  104. //---------------------------------------------------------
  105. // IMaterialSystem
  106. virtual IMaterialSystemHardwareConfig * GetHardwareConfig( const char *pVersion, int *returnCode );
  107. // Get the current config for this video card (as last set by control panel or the default if not)
  108. virtual bool UpdateConfig( bool forceUpdate );
  109. virtual bool OverrideConfig( const MaterialSystem_Config_t &config, bool bForceUpdate );
  110. const MaterialSystem_Config_t & GetCurrentConfigForVideoCard() const;
  111. // Gets *recommended* configuration information associated with the display card,
  112. virtual bool GetRecommendedConfigurationInfo( int nDXLevel, KeyValues * pKeyValues );
  113. // IShaderUtil
  114. MaterialSystem_Config_t & GetConfig();
  115. private:
  116. //---------------------------------
  117. // This is called when the config changes
  118. void GenerateConfigFromConfigKeyValues( MaterialSystem_Config_t *pConfig, bool bOverwriteCommandLineValues );
  119. // Read/write config into convars
  120. void ReadConfigFromConVars( MaterialSystem_Config_t *pConfig );
  121. void WriteConfigIntoConVars( const MaterialSystem_Config_t &config );
  122. // Write dxsupport info to configvars
  123. void WriteConfigurationInfoToConVars( bool bOverwriteCommandLineValues = true );
  124. public:
  125. // -----------------------------------------------------------
  126. // Device methods
  127. // -----------------------------------------------------------
  128. int GetDisplayAdapterCount() const;
  129. int GetCurrentAdapter() const;
  130. char *GetDisplayDeviceName() const OVERRIDE;
  131. void GetDisplayAdapterInfo( int adapter, MaterialAdapterInfo_t& info ) const;
  132. int GetModeCount( int adapter ) const;
  133. void GetModeInfo( int adapter, int mode, MaterialVideoMode_t& info ) const;
  134. void AddModeChangeCallBack( ModeChangeCallbackFunc_t func );
  135. void RemoveModeChangeCallBack( ModeChangeCallbackFunc_t func );
  136. // Returns the mode info for the current display device
  137. void GetDisplayMode( MaterialVideoMode_t& info ) const;
  138. bool SetMode( void* hwnd, const MaterialSystem_Config_t &config );
  139. // Reports support for a given MSAA mode
  140. bool SupportsMSAAMode( int nMSAAMode );
  141. // Reports support for a given CSAA mode
  142. bool SupportsCSAAMode( int nNumSamples, int nQualityLevel );
  143. bool SupportsHDRMode( HDRType_t nHDRModede );
  144. bool UsesSRGBCorrectBlending() const;
  145. // Reports support for shadow depth texturing
  146. bool SupportsShadowDepthTextures( void );
  147. // Reports support for fetch4 texture access (useful for shadow map PCF in shader)
  148. bool SupportsFetch4( void );
  149. // Vendor-dependent shadow depth texture format
  150. ImageFormat GetShadowDepthTextureFormat( void );
  151. // Vendor-dependent slim texture format
  152. ImageFormat GetNullTextureFormat( void );
  153. // Shadow depth bias factors
  154. void SetShadowDepthBiasFactors( float fShadowSlopeScaleDepthBias, float fShadowDepthBias );
  155. const MaterialSystemHardwareIdentifier_t &GetVideoCardIdentifier() const;
  156. // Use this to spew information about the 3D layer
  157. void SpewDriverInfo() const;
  158. DELEGATE_TO_OBJECT_2V( GetDXLevelDefaults, uint &, uint &, g_pShaderAPI );
  159. DELEGATE_TO_OBJECT_2VC( GetBackBufferDimensions, int &, int &, g_pShaderDevice );
  160. DELEGATE_TO_OBJECT_0C( ImageFormat, GetBackBufferFormat, g_pShaderDevice );
  161. DELEGATE_TO_OBJECT_1V( PushDeformation, DeformationBase_t const *, g_pShaderAPI );
  162. DELEGATE_TO_OBJECT_0V( PopDeformation, g_pShaderAPI );
  163. DELEGATE_TO_OBJECT_0C(int, GetNumActiveDeformations, g_pShaderAPI );
  164. // -----------------------------------------------------------
  165. // Window methods
  166. // -----------------------------------------------------------
  167. // Creates/ destroys a child window
  168. bool AddView( void* hwnd );
  169. void RemoveView( void* hwnd );
  170. // Sets the view
  171. void SetView( void* hwnd );
  172. // -----------------------------------------------------------
  173. // Control flow
  174. // -----------------------------------------------------------
  175. void BeginFrame( float frameTime );
  176. void EndFrame();
  177. virtual bool IsInFrame( ) const;
  178. void Flush( bool flushHardware = false );
  179. void SwapBuffers();
  180. // Flushes managed textures from the texture cacher
  181. void EvictManagedResources();
  182. void ReleaseResources();
  183. void ReacquireResources();
  184. // Recomputes a state snapshot
  185. void RecomputeAllStateSnapshots();
  186. void NoteAnisotropicLevel( int currentLevel );
  187. // -----------------------------------------------------------
  188. // Device loss/restore
  189. // -----------------------------------------------------------
  190. // Installs a function to be called when we need to release vertex buffers
  191. void AddReleaseFunc( MaterialBufferReleaseFunc_t func );
  192. void RemoveReleaseFunc( MaterialBufferReleaseFunc_t func );
  193. // Installs a function to be called when we need to restore vertex buffers
  194. void AddRestoreFunc( MaterialBufferRestoreFunc_t func );
  195. void RemoveRestoreFunc( MaterialBufferRestoreFunc_t func );
  196. // Called by the shader API when it's just about to lose video memory
  197. void ReleaseShaderObjects();
  198. void RestoreShaderObjects( CreateInterfaceFn shaderFactory, int nChangeFlags = 0 );
  199. // Release temporary HW memory...
  200. void ResetTempHWMemory( bool bExitingLevel = false );
  201. // For dealing with device lost in cases where SwapBuffers isn't called all the time (Hammer)
  202. void HandleDeviceLost();
  203. // -----------------------------------------------------------
  204. // Shaders
  205. // -----------------------------------------------------------
  206. int ShaderCount() const;
  207. int GetShaders( int nFirstShader, int nCount, IShader **ppShaderList ) const;
  208. int ShaderFlagCount() const;
  209. const char * ShaderFlagName( int nIndex ) const;
  210. void GetShaderFallback( const char *pShaderName, char *pFallbackShader, int nFallbackLength );
  211. // -----------------------------------------------------------
  212. // Material proxies
  213. // -----------------------------------------------------------
  214. IMaterialProxyFactory* GetMaterialProxyFactory();
  215. void SetMaterialProxyFactory( IMaterialProxyFactory* pFactory );
  216. // -----------------------------------------------------------
  217. // Editor mode
  218. // -----------------------------------------------------------
  219. bool InEditorMode() const;
  220. // Used to enable editor materials. Must be called before Init.
  221. void EnableEditorMaterials();
  222. // Can we use editor materials?
  223. bool CanUseEditorMaterials() const;
  224. // -----------------------------------------------------------
  225. // Stub mode mode
  226. // -----------------------------------------------------------
  227. void SetInStubMode( bool bInStubMode );
  228. bool IsInStubMode();
  229. //---------------------------------------------------------
  230. // Image formats
  231. //---------------------------------------------------------
  232. ImageFormatInfo_t const& ImageFormatInfo( ImageFormat fmt) const;
  233. int GetMemRequired( int width, int height, int depth, ImageFormat format, bool mipmap );
  234. bool ConvertImageFormat( unsigned char *src, enum ImageFormat srcImageFormat,
  235. unsigned char *dst, enum ImageFormat dstImageFormat,
  236. int width, int height, int srcStride = 0, int dstStride = 0 );
  237. //---------------------------------------------------------
  238. // Debug support
  239. //---------------------------------------------------------
  240. void CreateDebugMaterials();
  241. void CleanUpDebugMaterials();
  242. void CleanUpErrorMaterial();
  243. void DebugPrintUsedMaterials( const char *pSearchSubString, bool bVerbose );
  244. void DebugPrintUsedTextures();
  245. void ToggleSuppressMaterial( const char* pMaterialName );
  246. void ToggleDebugMaterial( const char* pMaterialName );
  247. //---------------------------------------------------------
  248. // Compositor Support
  249. //---------------------------------------------------------
  250. void CreateCompositorMaterials();
  251. void CleanUpCompositorMaterials();
  252. //---------------------------------------------------------
  253. // Misc features
  254. //---------------------------------------------------------
  255. //returns whether fast clipping is being used or not - needed to be exposed for better per-object clip behavior
  256. bool UsingFastClipping();
  257. int StencilBufferBits();
  258. //---------------------------------------------------------
  259. // Standard material and textures
  260. //---------------------------------------------------------
  261. void AllocateStandardTextures();
  262. void ReleaseStandardTextures();
  263. IMaterialInternal * GetDrawFlatMaterial() { return m_pDrawFlatMaterial; }
  264. IMaterialInternal * GetBufferClearObeyStencil( int i ) { return m_pBufferClearObeyStencil[i]; }
  265. IMaterialInternal * GetRenderTargetBlitMaterial() { return m_pRenderTargetBlitMaterial; }
  266. ShaderAPITextureHandle_t GetFullbrightLightmapTextureHandle() const { return m_FullbrightLightmapTextureHandle; }
  267. ShaderAPITextureHandle_t GetFullbrightBumpedLightmapTextureHandle() const { return m_FullbrightBumpedLightmapTextureHandle; }
  268. ShaderAPITextureHandle_t GetBlackTextureHandle() const { return m_BlackTextureHandle; }
  269. ShaderAPITextureHandle_t GetFlatNormalTextureHandle() const { return m_FlatNormalTextureHandle; }
  270. ShaderAPITextureHandle_t GetGreyTextureHandle() const { return m_GreyTextureHandle; }
  271. ShaderAPITextureHandle_t GetGreyAlphaZeroTextureHandle() const { return m_GreyAlphaZeroTextureHandle; }
  272. ShaderAPITextureHandle_t GetWhiteTextureHandle() const { return m_WhiteTextureHandle; }
  273. ShaderAPITextureHandle_t GetLinearToGammaTableTextureHandle() const { return m_LinearToGammaTableTextureHandle; }
  274. ShaderAPITextureHandle_t GetLinearToGammaIdentityTableTextureHandle() const { return m_LinearToGammaIdentityTableTextureHandle; }
  275. ShaderAPITextureHandle_t GetMaxDepthTextureHandle() const { return m_MaxDepthTextureHandle; }
  276. //---------------------------------------------------------
  277. // Material and texture management
  278. //---------------------------------------------------------
  279. // Stop attempting to stream in textures in response to usage. Useful for phases such as loading or other explicit
  280. // operations that shouldn't take usage of textures as a signal to stream them in at full rez.
  281. void SuspendTextureStreaming( );
  282. void ResumeTextureStreaming( );
  283. void UncacheAllMaterials();
  284. void UncacheUnusedMaterials( bool bRecomputeStateSnapshots );
  285. void CacheUsedMaterials();
  286. void ReloadTextures();
  287. void ReloadMaterials( const char *pSubString = NULL );
  288. // Create new materials (currently only used by the editor!)
  289. IMaterial * CreateMaterial( const char *pMaterialName, KeyValues *pVMTKeyValues );
  290. IMaterial * FindMaterial( const char *materialName, const char *pTextureGroupName, bool complain = true, const char *pComplainPrefix = NULL );
  291. virtual IMaterial * FindMaterialEx( char const* pMaterialName, const char *pTextureGroupName, int nContext, bool complain = true, const char *pComplainPrefix = NULL );
  292. bool IsMaterialLoaded( const char *materialName );
  293. virtual IMaterial * FindProceduralMaterial( const char *pMaterialName, const char *pTextureGroupName, KeyValues *pVMTKeyValues );
  294. const char * GetForcedTextureLoadPathID() { return m_pForcedTextureLoadPathID; }
  295. void SetAsyncTextureLoadCache( void* h );
  296. void SetVMTFileLoadCache( void* h );
  297. //---------------------------------
  298. DELEGATE_TO_OBJECT_0C( MaterialHandle_t, FirstMaterial, &m_MaterialDict );
  299. DELEGATE_TO_OBJECT_1C( MaterialHandle_t, NextMaterial, MaterialHandle_t, &m_MaterialDict );
  300. DELEGATE_TO_OBJECT_0C( MaterialHandle_t, InvalidMaterial, &m_MaterialDict );
  301. DELEGATE_TO_OBJECT_1C( IMaterial *, GetMaterial, MaterialHandle_t, &m_MaterialDict );
  302. DELEGATE_TO_OBJECT_1C( IMaterialInternal *, GetMaterialInternal, MaterialHandle_t, &m_MaterialDict );
  303. DELEGATE_TO_OBJECT_0C( int, GetNumMaterials, &m_MaterialDict );
  304. DELEGATE_TO_OBJECT_1V( AddMaterialToMaterialList, IMaterialInternal *, &m_MaterialDict );
  305. DELEGATE_TO_OBJECT_1V( RemoveMaterial, IMaterialInternal *, &m_MaterialDict );
  306. DELEGATE_TO_OBJECT_1V( RemoveMaterialSubRect, IMaterialInternal *, &m_MaterialDict );
  307. //---------------------------------
  308. ITexture * FindTexture( char const* pTextureName, const char *pTextureGroupName, bool complain = true, int nAdditionalCreationFlags = 0 );
  309. bool IsTextureLoaded( const char* pTextureName ) const;
  310. void AddTextureAlias( const char *pAlias, const char *pRealName );
  311. void RemoveTextureAlias( const char *pAlias );
  312. void SetExcludedTextures( const char *pScriptName );
  313. void UpdateExcludedTextures( void );
  314. // Creates a procedural texture
  315. ITexture * CreateProceduralTexture( const char *pTextureName,
  316. const char *pTextureGroupName,
  317. int w,
  318. int h,
  319. ImageFormat fmt,
  320. int nFlags );
  321. //
  322. // Render targets
  323. //
  324. void BeginRenderTargetAllocation();
  325. void EndRenderTargetAllocation(); // Simulate an Alt-Tab in here, which causes a release/restore of all resources
  326. // Creates a texture for use as a render target
  327. ITexture * CreateRenderTargetTexture( int w,
  328. int h,
  329. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  330. ImageFormat format,
  331. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED );
  332. ITexture * CreateNamedRenderTargetTextureEx( const char *pRTName, // Pass in NULL here for an unnamed render target.
  333. int w,
  334. int h,
  335. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  336. ImageFormat format,
  337. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
  338. unsigned int textureFlags = TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
  339. unsigned int renderTargetFlags = 0 );
  340. ITexture * CreateNamedRenderTargetTexture( const char *pRTName,
  341. int w,
  342. int h,
  343. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  344. ImageFormat format,
  345. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
  346. bool bClampTexCoords = true,
  347. bool bAutoMipMap = false );
  348. ITexture * CreateNamedRenderTargetTextureEx2( const char *pRTName, // Pass in NULL here for an unnamed render target.
  349. int w,
  350. int h,
  351. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  352. ImageFormat format,
  353. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
  354. unsigned int textureFlags = TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
  355. unsigned int renderTargetFlags = 0 );
  356. virtual ITexture* CreateTextureFromBits(int w, int h, int mips, ImageFormat fmt, int srcBufferSize, byte* srcBits);
  357. virtual void OverrideRenderTargetAllocation( bool rtAlloc );
  358. virtual ITextureCompositor* NewTextureCompositor( int w, int h, const char* pCompositeName, int nTeamNum, uint64 randomSeed, KeyValues* stageDesc, uint32 texCompositeCreateFlags ) OVERRIDE;
  359. void ScheduleTextureComposite( CTextureCompositor* _texCompositor );
  360. virtual void SetRenderTargetFrameBufferSizeOverrides( int nWidth, int nHeight ) OVERRIDE;
  361. virtual void GetRenderTargetFrameBufferDimensions( int & nWidth, int & nHeight ) OVERRIDE;
  362. virtual void AsyncFindTexture( const char* pFilename, const char *pTextureGroupName, IAsyncTextureOperationReceiver* pRecipient, void* pExtraArgs, bool bComplain = true, int nAdditionalCreationFlags = 0 ) OVERRIDE;
  363. virtual ITexture* CreateNamedTextureFromBitsEx( const char* pName, const char *pTextureGroupName, int w, int h, int mips, ImageFormat fmt, int srcBufferSize, byte* srcBits, int nFlags ) OVERRIDE;
  364. virtual bool AddTextureCompositorTemplate( const char* pName, KeyValues* pTmplDesc, int nTexCompositeTemplateFlags = 0 ) OVERRIDE;
  365. virtual bool VerifyTextureCompositorTemplates() OVERRIDE;
  366. // -----------------------------------------------------------
  367. bool OnDrawMesh( IMesh *pMesh, int firstIndex, int numIndices );
  368. bool OnDrawMesh( IMesh *pMesh, CPrimList *pLists, int nLists );
  369. DELEGATE_TO_OBJECT_3( bool, OnSetFlexMesh, IMesh *, IMesh *, int, GetRenderContextInternal() );
  370. DELEGATE_TO_OBJECT_3( bool, OnSetColorMesh, IMesh *, IMesh *, int, GetRenderContextInternal() );
  371. DELEGATE_TO_OBJECT_2( bool, OnSetPrimitiveType, IMesh *, MaterialPrimitiveType_t, GetRenderContextInternal() );
  372. DELEGATE_TO_OBJECT_0V( SyncMatrices, GetRenderContextInternal() );
  373. DELEGATE_TO_OBJECT_1V( SyncMatrix, MaterialMatrixMode_t, GetRenderContextInternal() );
  374. DELEGATE_TO_OBJECT_0( bool, OnFlushBufferedPrimitives, GetRenderContextInternal() );
  375. void OnThreadEvent( uint32 threadEvent );
  376. ShaderAPITextureHandle_t GetShaderAPITextureBindHandle( ITexture *pTexture, int nFrame, int nTextureChannel ); // JasonM ????
  377. // -----------------------------------------------------------
  378. // Lightmaps delegates
  379. // -----------------------------------------------------------
  380. DELEGATE_TO_OBJECT_0V( BeginLightmapAllocation, &m_Lightmaps );
  381. void EndLightmapAllocation()
  382. {
  383. GetLightmaps()->EndLightmapAllocation();
  384. AllocateStandardTextures();
  385. }
  386. DELEGATE_TO_OBJECT_4( int, AllocateLightmap, int, int, LightmapOffset_t, IMaterial *, &m_Lightmaps );
  387. DELEGATE_TO_OBJECT_1( int, AllocateWhiteLightmap, IMaterial *, &m_Lightmaps );
  388. DELEGATE_TO_OBJECT_3( int, AllocateDynamicLightmap, LightmapOffset_t, int *, int, &m_Lightmaps );
  389. void UpdateLightmap( int, LightmapOffset_t, LightmapOffset_t, float *, float *, float *, float * );
  390. DELEGATE_TO_OBJECT_0( int, GetNumSortIDs, &m_Lightmaps );
  391. DELEGATE_TO_OBJECT_1V( GetSortInfo, MaterialSystem_SortInfo_t *, &m_Lightmaps );
  392. DELEGATE_TO_OBJECT_3VC( GetLightmapPageSize, int, int *, int *, &m_Lightmaps );
  393. DELEGATE_TO_OBJECT_0V( ResetMaterialLightmapPageInfo, &m_Lightmaps );
  394. DELEGATE_TO_OBJECT_1C( int, GetLightmapWidth, int, &m_Lightmaps );
  395. DELEGATE_TO_OBJECT_1C( int, GetLightmapHeight, int, &m_Lightmaps );
  396. DELEGATE_TO_OBJECT_0V( BeginUpdateLightmaps, &m_Lightmaps );
  397. DELEGATE_TO_OBJECT_0V( EndUpdateLightmaps, &m_Lightmaps );
  398. // -----------------------------------------------------------
  399. // Render context delegates
  400. // -----------------------------------------------------------
  401. // IMaterialSystem
  402. DELEGATE_TO_OBJECT_3V( ClearBuffers, bool, bool, bool, GetRenderContextInternal() );
  403. // IMaterialSystemInternal
  404. DELEGATE_TO_OBJECT_0( IMaterial *, GetCurrentMaterial, GetRenderContextInternal() );
  405. DELEGATE_TO_OBJECT_0( int, GetLightmapPage, GetRenderContextInternal() );
  406. DELEGATE_TO_OBJECT_0( ITexture *, GetLocalCubemap, GetRenderContextInternal() );
  407. DELEGATE_TO_OBJECT_1V( ForceDepthFuncEquals, bool, GetRenderContextInternal() );
  408. DELEGATE_TO_OBJECT_0( MaterialHeightClipMode_t, GetHeightClipMode, GetRenderContextInternal() );
  409. DELEGATE_TO_OBJECT_0C( bool, InFlashlightMode, GetRenderContextInternal() );
  410. // IShaderUtil
  411. DELEGATE_TO_OBJECT_2V( BindStandardTexture, Sampler_t, StandardTextureId_t, &m_HardwareRenderContext );
  412. DELEGATE_TO_OBJECT_2V( BindStandardVertexTexture, VertexTextureSampler_t, StandardTextureId_t, &m_HardwareRenderContext );
  413. DELEGATE_TO_OBJECT_2V( GetLightmapDimensions, int *, int *, &m_HardwareRenderContext );
  414. DELEGATE_TO_OBJECT_3V( GetStandardTextureDimensions, int *, int *, StandardTextureId_t, &m_HardwareRenderContext );
  415. DELEGATE_TO_OBJECT_0( MorphFormat_t, GetBoundMorphFormat, &m_HardwareRenderContext );
  416. DELEGATE_TO_OBJECT_1( ITexture *, GetRenderTargetEx, int, &m_HardwareRenderContext );
  417. DELEGATE_TO_OBJECT_7V( DrawClearBufferQuad, unsigned char, unsigned char, unsigned char, unsigned char, bool, bool, bool, &m_HardwareRenderContext );
  418. DELEGATE_TO_OBJECT_0C( int, MaxHWMorphBatchCount, g_pMorphMgr );
  419. DELEGATE_TO_OBJECT_1V( GetCurrentColorCorrection, ShaderColorCorrectionInfo_t*, g_pColorCorrectionSystem );
  420. #if defined( _X360 )
  421. void ListUsedMaterials();
  422. HXUIFONT OpenTrueTypeFont( const char *pFontname, int tall, int style );
  423. void CloseTrueTypeFont( HXUIFONT hFont );
  424. bool GetTrueTypeFontMetrics( HXUIFONT hFont, XUIFontMetrics *pFontMetrics, XUICharMetrics charMetrics[256] );
  425. // Render a sequence of characters and extract the data into a buffer
  426. // For each character, provide the width+height of the font texture subrect,
  427. // an offset to apply when rendering the glyph, and an offset into a buffer to receive the RGBA data
  428. bool GetTrueTypeGlyphs( HXUIFONT hFont, int numChars, wchar_t *pWch, int *pOffsetX, int *pOffsetY, int *pWidth, int *pHeight, unsigned char *pRGBA, int *pOffset );
  429. void ReadBackBuffer( Rect_t *pSrcRect, Rect_t *pDstRect, unsigned char *pData, ImageFormat dstFormat, int nDstStride );
  430. void PersistDisplay();
  431. void *GetD3DDevice();
  432. bool OwnGPUResources( bool bEnable );
  433. #endif
  434. MaterialLock_t Lock();
  435. void Unlock( MaterialLock_t );
  436. CMatCallQueue * GetRenderCallQueue();
  437. uint GetRenderThreadId() const { return m_nRenderThreadID; }
  438. void UnbindMaterial( IMaterial *pMaterial );
  439. IMaterialProxy *DetermineProxyReplacements( IMaterial *pMaterial, KeyValues *pFallbackKeyValues );
  440. void LoadReplacementMaterials();
  441. void ScanDirForReplacements( const char *pszPathName );
  442. void InitReplacementsFromFile( const char *pszPathName );
  443. void PreloadReplacements( );
  444. CUtlDict< KeyValues *, int > m_Replacements;
  445. virtual void CompactMemory();
  446. private:
  447. void OnRenderingAsyncComplete();
  448. // -----------------------------------------------------------
  449. private:
  450. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showmaterials", DebugPrintUsedMaterials, "Show materials.", 0 );
  451. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showmaterialsverbose", DebugPrintUsedMaterialsVerbose, "Show materials (verbose version).", 0 );
  452. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showtextures", DebugPrintUsedTextures, "Show used textures.", 0 );
  453. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_reloadallmaterials", ReloadAllMaterials, "Reloads all materials", FCVAR_CHEAT );
  454. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_reloadmaterial", ReloadMaterials, "Reloads a single material", FCVAR_CHEAT );
  455. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_reloadtextures", ReloadTextures, "Reloads all textures", FCVAR_CHEAT );
  456. #if defined( _X360 )
  457. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_material_list", ListUsedMaterials, "Show used textures.", 0 );
  458. #endif
  459. friend void* InstantiateMaterialSystemV76Interface();
  460. friend CMaterialSystem *CMatLightmaps::GetMaterialSystem() const;
  461. void ThreadExecuteQueuedContext( CMatQueuedRenderContext *pContext );
  462. IThreadPool * CreateMatQueueThreadPool();
  463. void DestroyMatQueueThreadPool();
  464. #ifdef DX_TO_GL_ABSTRACTION
  465. void DoStartupShaderPreloading( void );
  466. #endif
  467. // -----------------------------------------------------------
  468. CMaterialDict m_MaterialDict;
  469. CMatLightmaps m_Lightmaps;
  470. CThreadLocal<IMatRenderContextInternal *> m_pRenderContext;
  471. CMatRenderContext m_HardwareRenderContext;
  472. CMatQueuedRenderContext m_QueuedRenderContexts[2];
  473. int m_iCurQueuedContext;
  474. MaterialThreadMode_t m_ThreadMode;
  475. MaterialThreadMode_t m_IdealThreadMode;
  476. bool m_bThreadingNotAvailable; // this is true if the VirtualAlloc()'s in the threading fail to allocate
  477. int m_nServiceThread;
  478. //---------------------------------
  479. char * m_pShaderDLL;
  480. CSysModule * m_ShaderHInst; // Used to dynamically load the shader DLL
  481. CreateInterfaceFn m_ShaderAPIFactory;
  482. int m_nAdapter;
  483. int m_nAdapterFlags;
  484. //---------------------------------
  485. IMaterialProxyFactory * m_pMaterialProxyFactory;
  486. //---------------------------------
  487. // Callback methods for releasing + restoring video memory
  488. CUtlVector< MaterialBufferReleaseFunc_t > m_ReleaseFunc;
  489. CUtlVector< MaterialBufferRestoreFunc_t > m_RestoreFunc;
  490. //---------------------------------
  491. bool m_bRequestedEditorMaterials;
  492. bool m_bCanUseEditorMaterials;
  493. //---------------------------------
  494. // Store texids for various things
  495. ShaderAPITextureHandle_t m_FullbrightLightmapTextureHandle;
  496. ShaderAPITextureHandle_t m_FullbrightBumpedLightmapTextureHandle;
  497. ShaderAPITextureHandle_t m_BlackTextureHandle;
  498. ShaderAPITextureHandle_t m_FlatNormalTextureHandle;
  499. ShaderAPITextureHandle_t m_GreyTextureHandle;
  500. ShaderAPITextureHandle_t m_GreyAlphaZeroTextureHandle;
  501. ShaderAPITextureHandle_t m_WhiteTextureHandle;
  502. ShaderAPITextureHandle_t m_LinearToGammaTableTextureHandle; //linear to gamma srgb conversion lookup for the current hardware
  503. ShaderAPITextureHandle_t m_LinearToGammaIdentityTableTextureHandle; //An identity lookup for when srgb writes are off
  504. ShaderAPITextureHandle_t m_MaxDepthTextureHandle; //a 1x1 texture with maximum depth values.
  505. // Have we allocated the standard lightmaps?
  506. bool m_StandardTexturesAllocated;
  507. bool m_bReplacementFilesValid;
  508. //---------------------------------
  509. // Shared materials used for debugging....
  510. //---------------------------------
  511. enum BufferClearType_t //bClearColor + ( bClearAlpha << 1 ) + ( bClearDepth << 2 )
  512. {
  513. BUFFER_CLEAR_NONE,
  514. BUFFER_CLEAR_COLOR,
  515. BUFFER_CLEAR_ALPHA,
  516. BUFFER_CLEAR_COLOR_AND_ALPHA,
  517. BUFFER_CLEAR_DEPTH,
  518. BUFFER_CLEAR_COLOR_AND_DEPTH,
  519. BUFFER_CLEAR_ALPHA_AND_DEPTH,
  520. BUFFER_CLEAR_COLOR_AND_ALPHA_AND_DEPTH,
  521. BUFFER_CLEAR_TYPE_COUNT
  522. };
  523. IMaterialInternal * m_pBufferClearObeyStencil[BUFFER_CLEAR_TYPE_COUNT];
  524. IMaterialInternal * m_pDrawFlatMaterial;
  525. IMaterialInternal * m_pRenderTargetBlitMaterial;
  526. CUtlVector< IMaterialInternal* > m_pCompositorMaterials;
  527. //---------------------------------
  528. const char * m_pForcedTextureLoadPathID;
  529. FileCacheHandle_t m_hAsyncLoadFileCache;
  530. uint m_nRenderThreadID;
  531. bool m_bAllocatingRenderTargets;
  532. bool m_bInStubMode;
  533. bool m_bGeneratedConfig;
  534. bool m_bInFrame;
  535. bool m_bForcedSingleThreaded;
  536. bool m_bAllowQueuedRendering;
  537. volatile bool m_bThreadHasOwnership;
  538. uint m_ThreadOwnershipID;
  539. //---------------------------------
  540. CJob * m_pActiveAsyncJob;
  541. CUtlVector<uint32> m_threadEvents;
  542. IThreadPool * m_pMatQueueThreadPool;
  543. //---------------------------------
  544. int m_nRenderTargetFrameBufferWidthOverride;
  545. int m_nRenderTargetFrameBufferHeightOverride;
  546. CUtlVector< CTextureCompositor* > m_scheduledComposites;
  547. CUtlVector< CTextureCompositor* > m_pendingComposites;
  548. };
  549. //-----------------------------------------------------------------------------
  550. inline CMaterialSystem *CMatLightmaps::GetMaterialSystem() const
  551. {
  552. return GET_OUTER( CMaterialSystem, m_Lightmaps );
  553. }
  554. //-----------------------------------------------------------------------------
  555. #endif // CMATERIALSYSTEM_H