This commit is contained in:
nephacks committed 2025-06-04 03:22:50 +02:00
1 parent f234f23848
commit f12416cffd
14243 files changed
+6446499 -26

No files matched your search

+992
View File
@@ -0,0 +1,992 @@
//====== Copyright 1996-2005, Valve Corporation, All rights reserved. =======
//
// Purpose: Color correction system
//
//==============================================================================
#if defined (WIN32) && !defined( _X360 )
#include <windows.h>
#elif defined( POSIX )
#define _cdecl
#endif
#include "materialsystem/IColorCorrection.h"
#include "materialsystem_global.h"
#include "shaderapi/ishaderapi.h"
#include "texturemanager.h"
#include "utlvector.h"
#include "generichash.h"
#include "filesystem.h"
#include "filesystem/IQueuedLoader.h"
#include "tier2/fileutils.h"
#include "pixelwriter.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
class ITextureInternal;
//-----------------------------------------------------------------------------
// Color correction textures are procedural. Handle the download
//-----------------------------------------------------------------------------
class CColorCorrectionRegen : public ITextureRegenerator
{
public:
CColorCorrectionRegen( ColorCorrectionHandle_t handle ) : m_ColorCorrectionHandle( handle )
{
}
virtual void RegenerateTextureBits( ITexture *pTexture, IVTFTexture *pVTFTexture, Rect_t *pSubRect )
{
int nWidth = pVTFTexture->Width();
int nHeight = pVTFTexture->Height();
int nDepth = pVTFTexture->Depth();
Assert( nWidth == COLOR_CORRECTION_TEXTURE_SIZE && nHeight == COLOR_CORRECTION_TEXTURE_SIZE && nDepth == COLOR_CORRECTION_TEXTURE_SIZE );
for ( int z = 0; z < nDepth; ++z )
{
CPixelWriter pixelWriter;
pixelWriter.SetPixelMemory( pVTFTexture->Format(),
pVTFTexture->ImageData( 0, 0, 0, 0, 0, z ), pVTFTexture->RowSizeInBytes( 0 ) );
for ( int y = 0; y < nHeight; ++y )
{
pixelWriter.Seek( 0, y );
for (int x = 0; x < nWidth; ++x)
{
RGBX5551_t inColor;
inColor.r = x;
inColor.g = y;
inColor.b = z;
color24 col = ColorCorrectionSystem()->GetLookup( m_ColorCorrectionHandle, inColor );
pixelWriter.WritePixel( col.r, col.g, col.b, 255 );
}
}
}
if ( IsX360() )
{
g_pColorCorrectionSystem->OnProceduralRegenComplete( m_ColorCorrectionHandle );
}
}
virtual void Release()
{
delete this;
}
private:
ColorCorrectionHandle_t m_ColorCorrectionHandle;
};
//-----------------------------------------------------------------------------
// Holds all the necessary information for a single color correction lookup
// function
//-----------------------------------------------------------------------------
struct ColorCorrectionLookup_t
{
ColorCorrectionLookup_t( ColorCorrectionHandle_t handle );
~ColorCorrectionLookup_t();
void ReleaseTexture();
void RestoreTexture();
void AllocTexture();
ColorCorrectionHandle_t m_Handle;
ITextureInternal *m_pColorCorrectionTexture;
color24 *m_pColorCorrection;
bool m_bLocked;
float m_flWeight;
bool m_bResetable;
};
ColorCorrectionLookup_t::ColorCorrectionLookup_t( ColorCorrectionHandle_t handle )
{
m_Handle = handle;
m_bLocked = false;
m_flWeight = 1.0f;
m_bResetable = true;
// these are the backing bits for the volume, either the file gets pushed into this or a caller can procedurally build
m_pColorCorrection = new color24[COLOR_CORRECTION_TEXTURE_SIZE*COLOR_CORRECTION_TEXTURE_SIZE*COLOR_CORRECTION_TEXTURE_SIZE];
AllocTexture();
}
ColorCorrectionLookup_t::~ColorCorrectionLookup_t()
{
// We must remove the texture from the active color correction
// textures, otherwise we may leak a reference
if ( m_pColorCorrectionTexture )
{
for ( int i=0; i<COLOR_CORRECTION_MAX_TEXTURES; i++ )
{
if ( m_pColorCorrectionTexture == TextureManager()->ColorCorrectionTexture( i ) )
{
TextureManager()->SetColorCorrectionTexture( i, NULL );
}
}
m_pColorCorrectionTexture->DecrementReferenceCount();
ITextureInternal::Destroy( m_pColorCorrectionTexture );
m_pColorCorrectionTexture = NULL;
}
delete [] m_pColorCorrection;
}
void ColorCorrectionLookup_t::AllocTexture()
{
char szFilename[MAX_PATH];
char szShortName[MAX_PATH];
g_pFullFileSystem->String( (FileNameHandle_t)m_Handle, szFilename, sizeof( szFilename ) );
V_FileBase( szFilename, szShortName, sizeof( szShortName ) );
char szName[128];
V_snprintf( szName, sizeof( szName ), "ColorCorrection (%s)", szShortName );
m_pColorCorrectionTexture = ITextureInternal::CreateProceduralTexture( szName, TEXTURE_GROUP_OTHER,
COLOR_CORRECTION_TEXTURE_SIZE, COLOR_CORRECTION_TEXTURE_SIZE, COLOR_CORRECTION_TEXTURE_SIZE, IMAGE_FORMAT_BGRX8888,
TEXTUREFLAGS_NOMIP | TEXTUREFLAGS_NOLOD | TEXTUREFLAGS_SINGLECOPY | TEXTUREFLAGS_CLAMPS |
TEXTUREFLAGS_CLAMPT | TEXTUREFLAGS_CLAMPU | TEXTUREFLAGS_NODEBUGOVERRIDE );
// color correction textures are procedural, provide the download interface
ITextureRegenerator *pRegen = new CColorCorrectionRegen( m_Handle );
m_pColorCorrectionTexture->SetTextureRegenerator( pRegen );
// xbox needs to defer the real download (only once) to when the volume data is pushed in
if ( !IsX360() )
{
m_pColorCorrectionTexture->Download();
}
}
void ColorCorrectionLookup_t::ReleaseTexture()
{
if ( IsX360() )
{
// there is no release/restore ability on the xbox
Assert( 0 );
return;
}
m_pColorCorrectionTexture->Release();
}
void ColorCorrectionLookup_t::RestoreTexture()
{
if ( IsX360() )
{
// there is no release/restore ability on the xbox
Assert( 0 );
return;
}
// Put the texture back onto the board
m_pColorCorrectionTexture->OnRestore(); // Give render targets a chance to reinitialize themselves if necessary (due to AA changes).
m_pColorCorrectionTexture->Download();
}
//-----------------------------------------------------------------------------
// IColorCorrectionSystem interface implementation
//-----------------------------------------------------------------------------
class CColorCorrectionSystem : public IColorCorrectionSystem
{
public:
virtual void Init();
virtual void Shutdown();
virtual void LockLookup();
virtual void SetLookup( RGBX5551_t inColor, color24 outColor );
virtual void UnlockLookup();
virtual color24 GetLookup( RGBX5551_t inColor );
virtual void LoadLookup( const char *pLookupName );
virtual void CopyLookup( const color24 *pSrcColorCorrection );
virtual void ResetLookup();
virtual ColorCorrectionHandle_t AddLookup( const char *pName );
virtual bool RemoveLookup( ColorCorrectionHandle_t handle );
virtual void SetLookupWeight( ColorCorrectionHandle_t handle, float flWeight );
virtual float GetLookupWeight( ColorCorrectionHandle_t handle );
virtual float GetLookupWeight( int i );
virtual void LockLookup( ColorCorrectionHandle_t handle );
virtual void SetLookup( ColorCorrectionHandle_t handle, RGBX5551_t inColor, color24 outColor );
virtual color24 GetLookup( ColorCorrectionHandle_t handle, RGBX5551_t inColor );
virtual void UnlockLookup( ColorCorrectionHandle_t handle, bool bDownload );
virtual void LoadLookup( ColorCorrectionHandle_t handle, const char *pLookupName );
virtual void CopyLookup( ColorCorrectionHandle_t handle, const color24 *pSrcColorCorrection );
virtual void ResetLookup( ColorCorrectionHandle_t handle );
virtual void ResetLookupWeights();
virtual void ReleaseTextures();
virtual void RestoreTextures();
virtual color24 ConvertToColor24( RGBX5551_t inColor );
virtual int GetNumLookups();
virtual void SetResetable( ColorCorrectionHandle_t handle, bool bResetable );
virtual void GetCurrentColorCorrection( ShaderColorCorrectionInfo_t* pInfo );
virtual void EnableColorCorrection( bool bEnable );
virtual void OnProceduralRegenComplete( ColorCorrectionHandle_t handle );
// returns NULL if not found
virtual ColorCorrectionHandle_t FindLookup( const char *pName );
protected:
CUtlVector< ColorCorrectionLookup_t * > m_ColorCorrectionList;
ColorCorrectionHandle_t m_DefaultColorCorrectionHandle;
ColorCorrectionHandle_t m_UnnamedColorCorrectionHandle;
float m_DefaultColorCorrectionWeight;
bool m_bEnabled;
void SortLookups();
ColorCorrectionLookup_t *FindLookup( ColorCorrectionHandle_t handle );
ColorCorrectionHandle_t GetLookupHandle( const char *pName );
void SetLookupPtr( ColorCorrectionLookup_t *lookup, RGBX5551_t inColor, color24 outColor );
void GetNormalizedWeights( float *pDefaultWeight, float *pLookupWeights );
};
CColorCorrectionSystem g_ColorCorrectionSystem;
IColorCorrectionSystem *g_pColorCorrectionSystem = &g_ColorCorrectionSystem;
#ifndef _X360
// Don't allow this on the 360.. it doesn't work in mat_queued_mode
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CColorCorrectionSystem, IColorCorrectionSystem, COLORCORRECTION_INTERFACE_VERSION, g_ColorCorrectionSystem );
#endif
//-----------------------------------------------------------------------------
// Wrappers for release/restore functionality
//-----------------------------------------------------------------------------
void ReleaseColorCorrection( int nChangeFlags )
{
if ( IsX360() )
{
// there is no release/restore ability on the xbox
Assert( 0 );
return;
}
if ( nChangeFlags & MATERIAL_RESTORE_VERTEX_FORMAT_CHANGED )
return;
g_pColorCorrectionSystem->ReleaseTextures();
}
void RestoreColorCorrection( int nChangeFlags )
{
if ( IsX360() )
{
// there is no release/restore ability on the xbox
Assert( 0 );
return;
}
if ( nChangeFlags & MATERIAL_RESTORE_VERTEX_FORMAT_CHANGED )
return;
g_pColorCorrectionSystem->RestoreTextures();
}
//-----------------------------------------------------------------------------
// Init function
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::Init()
{
m_DefaultColorCorrectionHandle = (ColorCorrectionHandle_t)-1;
m_UnnamedColorCorrectionHandle = GetLookupHandle( "unnamed" );
m_DefaultColorCorrectionWeight = 0.0f;
m_bEnabled = true;
MaterialSystem()->AddReleaseFunc( ReleaseColorCorrection );
MaterialSystem()->AddRestoreFunc( RestoreColorCorrection );
}
//-----------------------------------------------------------------------------
// Shutdown function
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::Shutdown()
{
for ( int i=0;i<m_ColorCorrectionList.Count();i++ )
{
delete m_ColorCorrectionList[i];
}
MaterialSystem()->RemoveReleaseFunc( ReleaseColorCorrection );
MaterialSystem()->RemoveRestoreFunc( RestoreColorCorrection );
}
//-----------------------------------------------------------------------------
// Global enable/disable of color correction
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::EnableColorCorrection( bool bEnable )
{
m_bEnabled = bEnable;
}
//-----------------------------------------------------------------------------
// Lock the "unnamed" color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::LockLookup()
{
ColorCorrectionLookup_t *lookup = FindLookup( m_UnnamedColorCorrectionHandle );
if ( !lookup )
{
AddLookup( "unnamed" );
}
LockLookup( m_UnnamedColorCorrectionHandle );
}
//-----------------------------------------------------------------------------
// Set the specified mapping for the "unnamed" color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::SetLookup( RGBX5551_t inColor, color24 outColor )
{
ColorCorrectionLookup_t *lookup = FindLookup( m_UnnamedColorCorrectionHandle );
if ( !lookup )
return;
SetLookup( m_UnnamedColorCorrectionHandle, inColor, outColor );
}
//-----------------------------------------------------------------------------
// Unlock the "unnamed" color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::UnlockLookup()
{
ColorCorrectionLookup_t *lookup = FindLookup( m_UnnamedColorCorrectionHandle );
if ( !lookup )
return;
UnlockLookup( m_UnnamedColorCorrectionHandle, true );
}
//-----------------------------------------------------------------------------
// Get the specified mapping from the "unnamed" color correction lookup
//-----------------------------------------------------------------------------
color24 CColorCorrectionSystem::GetLookup( RGBX5551_t inColor )
{
ColorCorrectionLookup_t *lookup = FindLookup( m_UnnamedColorCorrectionHandle );
if ( !lookup )
AddLookup( "unnamed" );
return GetLookup( m_UnnamedColorCorrectionHandle, inColor );
}
//-----------------------------------------------------------------------------
// Load the specified file into the "unnamed" color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::LoadLookup( const char *pLookupName )
{
ColorCorrectionLookup_t *lookup = FindLookup( m_UnnamedColorCorrectionHandle );
if ( !lookup )
return;
return LoadLookup( m_UnnamedColorCorrectionHandle, pLookupName );
}
//-----------------------------------------------------------------------------
// Copy the specified data into the "unnamed" color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::CopyLookup( const color24 *pSrcColorCorrection )
{
ColorCorrectionLookup_t *lookup = FindLookup( m_UnnamedColorCorrectionHandle );
if ( !lookup )
return;
CopyLookup( m_UnnamedColorCorrectionHandle, pSrcColorCorrection );
}
//-----------------------------------------------------------------------------
// Reset the "unnamed" color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::ResetLookup()
{
ColorCorrectionLookup_t *lookup = FindLookup( m_UnnamedColorCorrectionHandle );
if ( !lookup )
return;
return ResetLookup( m_UnnamedColorCorrectionHandle );
}
//-----------------------------------------------------------------------------
// ColorCorrectionLookup_t sorting function
//-----------------------------------------------------------------------------
typedef ColorCorrectionLookup_t * CCLPtr;
int _cdecl CompareLookups( const CCLPtr *lookup_a, const CCLPtr *lookup_b )
{
if ( (*lookup_a)->m_flWeight < (*lookup_b)->m_flWeight )
return 1;
else if ( (*lookup_a)->m_flWeight > (*lookup_b)->m_flWeight )
return -1;
return 0;
}
//-----------------------------------------------------------------------------
// Sort ColorCorrectionLookup_t vector based on decreasing weight
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::SortLookups()
{
m_ColorCorrectionList.Sort( CompareLookups );
for ( int i=0;i<COLOR_CORRECTION_MAX_TEXTURES && i<m_ColorCorrectionList.Count();i++ )
{
TextureManager()->SetColorCorrectionTexture( i, m_ColorCorrectionList[i]->m_pColorCorrectionTexture );
}
for ( int i=m_ColorCorrectionList.Count();i<COLOR_CORRECTION_MAX_TEXTURES;i++ )
{
TextureManager()->SetColorCorrectionTexture( i, NULL );
}
}
//-----------------------------------------------------------------------------
// Find the ColorCorrectionLookup_t corresponding to the specified handle
//-----------------------------------------------------------------------------
ColorCorrectionLookup_t *CColorCorrectionSystem::FindLookup( ColorCorrectionHandle_t handle )
{
for ( int i=0; i<m_ColorCorrectionList.Count(); i++ )
{
if ( m_ColorCorrectionList[i]->m_Handle == handle )
{
return m_ColorCorrectionList[i];
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Find the handle associated with a specified name
//-----------------------------------------------------------------------------
ColorCorrectionHandle_t CColorCorrectionSystem::GetLookupHandle( const char *pName )
{
// case and slash insensitive
FileNameHandle_t hName = g_pFullFileSystem->FindOrAddFileName( pName );
COMPILE_TIME_ASSERT( sizeof( FileNameHandle_t ) == sizeof( ColorCorrectionHandle_t ) );
return (ColorCorrectionHandle_t)hName;
}
//-----------------------------------------------------------------------------
// Add a color correction lookup with the specified name
//-----------------------------------------------------------------------------
ColorCorrectionHandle_t CColorCorrectionSystem::AddLookup( const char *pName )
{
ColorCorrectionHandle_t handle = GetLookupHandle( pName );
if ( handle == m_DefaultColorCorrectionHandle )
return handle;
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( lookup )
{
// Already got one by this name
return handle;
}
lookup = new ColorCorrectionLookup_t( handle );
m_ColorCorrectionList.AddToTail( lookup );
// xbox needs to defer the real download (only once) to when the volume data is pushed in
// the PC downloads becuase that was the legacy behavior (silly to me)
bool bDownload = !IsX360();
LockLookup( handle );
ResetLookup( handle );
UnlockLookup( handle, bDownload );
SetLookupWeight( handle, 1.0f );
return handle;
}
ColorCorrectionHandle_t CColorCorrectionSystem::FindLookup( const char *pName )
{
ColorCorrectionHandle_t handle = GetLookupHandle( pName );
if ( handle == m_DefaultColorCorrectionHandle )
return handle;
ColorCorrectionLookup_t *pLookup = FindLookup( handle );
if ( pLookup )
{
// Already got one by this name
return handle;
}
// not found
return (ColorCorrectionHandle_t)0;
}
//-----------------------------------------------------------------------------
// Remove the specified color correction lookup
//-----------------------------------------------------------------------------
bool CColorCorrectionSystem::RemoveLookup( ColorCorrectionHandle_t handle )
{
if ( handle == m_DefaultColorCorrectionHandle )
return false;
for ( int i=0;i<m_ColorCorrectionList.Count();i++ )
{
ColorCorrectionLookup_t *lookup = m_ColorCorrectionList[i];
if ( lookup->m_Handle == handle )
{
m_ColorCorrectionList.Remove( i );
delete lookup;
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Sets the weight for the specified color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::SetLookupWeight( ColorCorrectionHandle_t handle, float flWeight )
{
if ( handle == m_DefaultColorCorrectionHandle )
{
m_DefaultColorCorrectionWeight = flWeight;
return;
}
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( lookup && flWeight>lookup->m_flWeight )
{
lookup->m_flWeight = flWeight;
}
SortLookups();
}
//-----------------------------------------------------------------------------
// Gets the weight for the specified color correction lookup
//-----------------------------------------------------------------------------
float CColorCorrectionSystem::GetLookupWeight( ColorCorrectionHandle_t handle )
{
if ( handle == m_DefaultColorCorrectionHandle )
{
return m_DefaultColorCorrectionWeight;
}
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( !lookup )
return 0.0f;
return lookup->m_flWeight;
}
//-----------------------------------------------------------------------------
// Gets the weight for the color correction lookup specified by index
//-----------------------------------------------------------------------------
float CColorCorrectionSystem::GetLookupWeight( int i )
{
if ( i<m_ColorCorrectionList.Count() )
{
if ( i==-1 )
return m_DefaultColorCorrectionWeight;
ColorCorrectionLookup_t *lookup = m_ColorCorrectionList[ i ];
return lookup->m_flWeight;
}
return 0.0f;
}
//-----------------------------------------------------------------------------
// Lock the specified color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::LockLookup( ColorCorrectionHandle_t handle )
{
if ( handle == m_DefaultColorCorrectionHandle )
{
return;
}
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( !lookup )
return;
lookup->m_bLocked = true;
}
//-----------------------------------------------------------------------------
// Set the mapping for the specified color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::SetLookup( ColorCorrectionHandle_t handle, RGBX5551_t inColor, color24 outColor )
{
if ( handle == m_DefaultColorCorrectionHandle )
return;
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( !lookup )
return;
SetLookupPtr( lookup, inColor, outColor );
}
//-----------------------------------------------------------------------------
// Set the mapping for the specified color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::SetLookupPtr( ColorCorrectionLookup_t *lookup, RGBX5551_t inColor, color24 outColor )
{
Assert( lookup->m_bLocked );
if ( !lookup->m_pColorCorrection )
{
// Uh oh, contract broken, the backing volume was freed, no access should have occured
Assert( 0 );
return;
}
lookup->m_pColorCorrection[inColor.r + inColor.g*COLOR_CORRECTION_TEXTURE_SIZE + inColor.b*COLOR_CORRECTION_TEXTURE_SIZE*COLOR_CORRECTION_TEXTURE_SIZE] = outColor;
}
//-----------------------------------------------------------------------------
// Get the mapping for the specified color correction lookup
//-----------------------------------------------------------------------------
color24 CColorCorrectionSystem::GetLookup( ColorCorrectionHandle_t handle, RGBX5551_t inColor )
{
if ( handle == m_DefaultColorCorrectionHandle )
{
color24 col = ConvertToColor24( inColor );
return col;
}
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( !lookup )
{
color24 col; col.r = 0; col.g = 0; col.b = 0;
return col;
}
if ( !lookup->m_pColorCorrection )
{
// Uh oh, contract broken, the backing volume was freed, no access should have occured
Assert( 0 );
color24 col; col.r = 0; col.g = 0; col.b = 0;
return col;
}
return lookup->m_pColorCorrection[inColor.r + inColor.g*COLOR_CORRECTION_TEXTURE_SIZE + inColor.b*COLOR_CORRECTION_TEXTURE_SIZE*COLOR_CORRECTION_TEXTURE_SIZE];
}
//-----------------------------------------------------------------------------
// Unlock the specified color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::UnlockLookup( ColorCorrectionHandle_t handle, bool bDownload )
{
if ( handle == m_DefaultColorCorrectionHandle )
{
return;
}
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( !lookup )
return;
lookup->m_bLocked = false;
if ( bDownload )
{
lookup->m_pColorCorrectionTexture->Download();
}
}
//-----------------------------------------------------------------------------
// Load the specified file into the color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::LoadLookup( ColorCorrectionHandle_t handle, const char *pLookupName )
{
if ( handle == m_DefaultColorCorrectionHandle )
{
return;
}
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( !lookup )
return;
Assert( lookup->m_bLocked );
Assert( pLookupName );
char szXboxName[MAX_PATH];
if ( IsX360() || IsPS3() )
{
pLookupName = CreatePlatformFilename( pLookupName, szXboxName, sizeof( szXboxName ) );
}
CUtlBuffer colorBuff;
if ( !g_pFullFileSystem->ReadFile( pLookupName, "GAME", colorBuff ) )
{
Warning( "CColorCorrectionSystem: Missing '%s'\n", pLookupName );
return;
}
int res = (int)powf( (float)( colorBuff.TellMaxPut()/sizeof( color24 ) ), 1.0f/3.0f );
if ( res != COLOR_CORRECTION_TEXTURE_SIZE || res*res*res*(int)sizeof( color24 ) != colorBuff.TellMaxPut() )
{
Warning( "CColorCorrectionSystem: Raw file '%s' has bad size (%d)\n", pLookupName, colorBuff.TellMaxPut() );
return;
}
color24 *pColors = (color24 *)colorBuff.Base();
int colorIndex = 0;
RGBX5551_t inColor;
inColor.b = 0;
for ( int b = 0; b < COLOR_CORRECTION_TEXTURE_SIZE; ++b, ++inColor.b )
{
inColor.g = 0;
for ( int g = 0; g < COLOR_CORRECTION_TEXTURE_SIZE; ++g, ++inColor.g )
{
inColor.r = 0;
for ( int r = 0; r < COLOR_CORRECTION_TEXTURE_SIZE; ++r, ++inColor.r )
{
color24 vOutColor24 = pColors[colorIndex];
SetLookupPtr( lookup, inColor, vOutColor24 );
colorIndex++;
}
}
}
}
//-----------------------------------------------------------------------------
// Copy the data to the specified color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::CopyLookup( ColorCorrectionHandle_t handle, const color24 *pSrcColorCorrection )
{
if ( handle == m_DefaultColorCorrectionHandle )
{
return;
}
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( !lookup )
return;
Assert( lookup->m_bLocked );
Assert( pSrcColorCorrection );
if ( !lookup->m_pColorCorrection )
{
// Uh oh, contract broken, the backing volume was freed, no access should have occured
Assert( 0 );
return;
}
Q_memcpy( lookup->m_pColorCorrection, pSrcColorCorrection, sizeof(color24)*COLOR_CORRECTION_TEXTURE_SIZE*COLOR_CORRECTION_TEXTURE_SIZE*COLOR_CORRECTION_TEXTURE_SIZE );
}
//-----------------------------------------------------------------------------
// Reset the mapping for the specified color correction lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::ResetLookup( ColorCorrectionHandle_t handle )
{
if ( handle == m_DefaultColorCorrectionHandle )
{
return;
}
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( !lookup )
return;
Assert( lookup->m_bLocked );
RGBX5551_t inColor;
inColor.b = 0;
for ( int b = 0; b < COLOR_CORRECTION_TEXTURE_SIZE; ++b, ++inColor.b )
{
inColor.g = 0;
for ( int g = 0; g < COLOR_CORRECTION_TEXTURE_SIZE; ++g, ++inColor.g )
{
inColor.r = 0;
for ( int r = 0; r < COLOR_CORRECTION_TEXTURE_SIZE; ++r, ++inColor.r )
{
color24 outColor = ConvertToColor24( inColor );
SetLookupPtr( lookup, inColor, outColor );
}
}
}
}
//-----------------------------------------------------------------------------
// Reset the weight to zero for all lookups
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::ResetLookupWeights()
{
m_DefaultColorCorrectionWeight = 0.0f;
for ( int i=0;i<m_ColorCorrectionList.Count();i++ )
{
ColorCorrectionLookup_t *lookup = m_ColorCorrectionList[i];
if ( lookup->m_bResetable )
{
lookup->m_flWeight = 0.0f;
}
else
{
lookup->m_flWeight = 1.0f;
}
}
}
//-----------------------------------------------------------------------------
// Convert a color from RGBX5551_t to color24
//-----------------------------------------------------------------------------
color24 CColorCorrectionSystem::ConvertToColor24( RGBX5551_t inColor )
{
color24 out;
out.r = (inColor.r << 3) | (inColor.r >> 2);
out.g = (inColor.g << 3) | (inColor.g >> 2);
out.b = (inColor.b << 3) | (inColor.b >> 2);
return out;
}
//-----------------------------------------------------------------------------
// Call ReleaseTexture for all ColorCorrectionLookup_t
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::ReleaseTextures()
{
if ( IsX360() )
{
// there is no release/restore ability on the xbox
Assert( 0 );
return;
}
for ( int i=0;i<m_ColorCorrectionList.Count();i++ )
{
m_ColorCorrectionList[i]->ReleaseTexture();
}
}
//-----------------------------------------------------------------------------
// Call RestoreTexture for all ColorCorrectionLookup_t
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::RestoreTextures()
{
if ( IsX360() )
{
// there is no release/restore ability on the xbox
Assert( 0 );
return;
}
for ( int i=0;i<m_ColorCorrectionList.Count();i++ )
{
m_ColorCorrectionList[i]->RestoreTexture();
}
}
//-----------------------------------------------------------------------------
// Normalize the active set of color correction weights
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::GetNormalizedWeights( float *pDefaultWeight, float *pLookupWeights )
{
float total_weight = 0.0f;
int nLoopCount = MIN( m_ColorCorrectionList.Count(), COLOR_CORRECTION_MAX_TEXTURES );
for ( int i=0; i<nLoopCount; i++ )
{
total_weight += m_ColorCorrectionList[i]->m_flWeight;
pLookupWeights[i] = m_ColorCorrectionList[i]->m_flWeight;
}
for ( int i = nLoopCount; i < COLOR_CORRECTION_MAX_TEXTURES; ++i )
{
pLookupWeights[i] = 0.0f;
}
if ( total_weight <= ( 1.0f - 1e-3 ) )
{
*pDefaultWeight = 1.0f - total_weight;
}
else
{
*pDefaultWeight = 0.0f;
float inv_total_weight = 1.0f / total_weight;
for ( int i=0; i< nLoopCount; i++ )
{
pLookupWeights[i] *= inv_total_weight;
}
}
}
//-----------------------------------------------------------------------------
// Returns the number of active lookup
//-----------------------------------------------------------------------------
int CColorCorrectionSystem::GetNumLookups()
{
int i;
for ( i=0;i<m_ColorCorrectionList.Count()&&i<COLOR_CORRECTION_MAX_TEXTURES;i++ )
{
if ( m_ColorCorrectionList[i]->m_flWeight<=0.0f )
break;
}
return i;
}
//-----------------------------------------------------------------------------
// Enables/disables resetting of this lookup
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::SetResetable( ColorCorrectionHandle_t handle, bool bResetable )
{
ColorCorrectionLookup_t *lookup = FindLookup( handle );
if ( lookup )
{
lookup->m_bResetable = bResetable;
}
}
//-----------------------------------------------------------------------------
// Returns info for the shaders to control color correction
//-----------------------------------------------------------------------------
void CColorCorrectionSystem::GetCurrentColorCorrection( ShaderColorCorrectionInfo_t* pInfo )
{
COMPILE_TIME_ASSERT( COLOR_CORRECTION_MAX_TEXTURES == ARRAYSIZE( pInfo->m_pLookupWeights ) );
pInfo->m_bIsEnabled = m_bEnabled && ( GetNumLookups() > 0 || m_DefaultColorCorrectionWeight != 0.0f );
pInfo->m_nLookupCount = GetNumLookups();
GetNormalizedWeights( &pInfo->m_flDefaultWeight, pInfo->m_pLookupWeights );
}
void CColorCorrectionSystem::OnProceduralRegenComplete( ColorCorrectionHandle_t handle )
{
if ( !IsX360() )
{
// xbox only
return;
}
ColorCorrectionLookup_t *pLookup = FindLookup( handle );
if ( !pLookup )
{
// huh? should have been there
Assert( 0 );
return;
}
// Based on nefarious knowledge, the backing volume can be ditched on the xbox.
// The xbox only uses file based color correction, and does not support release/restore.
// For memory savings on L4D, at 98k per instance, l42_hospita01_aparments with ~20
// correction volumes, saves 2MB. The inept design enforces a unique instance per weight/entity.
delete [] pLookup->m_pColorCorrection;
// mark as free, used to check validity of this hack
pLookup->m_pColorCorrection = NULL;
}
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Header: $
// $NoKeywords: $
//=============================================================================//
#ifndef IHARDWARECONFIGINTERNAL_H
#define IHARDWARECONFIGINTERNAL_H
#ifdef _WIN32
#pragma once
#endif
#include "materialsystem/imaterialsystemhardwareconfig.h"
//-----------------------------------------------------------------------------
// Material system configuration
//-----------------------------------------------------------------------------
class IHardwareConfigInternal : public IMaterialSystemHardwareConfig
{
public:
// Gets at the HW specific shader DLL name
virtual const char *GetHWSpecificShaderDLLName() const = 0;
};
#endif // IHARDWARECONFIGINTERNAL_H
+63
View File
@@ -0,0 +1,63 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""afxres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
+109
View File
@@ -0,0 +1,109 @@
//Microsoft Developer Studio generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE DISCARDABLE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE DISCARDABLE
BEGIN
"#include ""afxres.h""\r\n"
"\0"
END
3 TEXTINCLUDE DISCARDABLE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#ifndef _MAC
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,1
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x40004L
FILETYPE 0x2L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0"
BEGIN
VALUE "Comments", "\0"
VALUE "CompanyName", "VALVE\0"
VALUE "FileDescription", "materialsystem\0"
VALUE "FileVersion", "1, 0, 0, 1\0"
VALUE "InternalName", "materialsystem\0"
VALUE "LegalCopyright", "Copyright © 2003\0"
VALUE "LegalTrademarks", "\0"
VALUE "OriginalFilename", "materialsystem.dll\0"
VALUE "PrivateBuild", "\0"
VALUE "ProductName", "VALVE materialsystem\0"
VALUE "ProductVersion", "1, 0, 0, 1\0"
VALUE "SpecialBuild", "\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200
END
END
#endif // !_MAC
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
+170
View File
@@ -0,0 +1,170 @@
//===== Copyright © 1996-2008, Valve Corporation, All rights reserved. ======//
//
// Purpose: Manager for texture containing subd data
//
//===========================================================================//
#include "isubdinternal.h"
#include "tier0/dbg.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/MaterialSystemUtil.h"
#include "materialsystem/itexture.h"
#include "materialsystem/imesh.h"
#include "utlsortvector.h"
#include "materialsystem_global.h"
#include "IHardwareConfigInternal.h"
#include "pixelwriter.h"
#include "itextureinternal.h"
#include "tier1/keyvalues.h"
#include "texturemanager.h"
#include "imaterialsysteminternal.h"
#include "imatrendercontextinternal.h"
#include "studio.h"
#include "tier0/vprof.h"
#include "renderparm.h"
#include "tier2/renderutils.h"
#include "bitmap/imageformat.h"
#include "materialsystem/IShader.h"
#include "imaterialinternal.h"
#include "tier0/memdbgon.h"
#define SUBD_TEXTURE_FORMAT IMAGE_FORMAT_RGBA32323232F
#define SUBD_TEXTURE_WIDTH 30
#define SUBD_TEXTURE_HEIGHT 8192 // If we need more than 8192 patches, we may be in trouble
//-----------------------------------------------------------------------------
// Subdivision surface manager class
//-----------------------------------------------------------------------------
class CSubDMgr : public ISubDMgr
{
public:
CSubDMgr();
virtual bool ShouldAllocateTextures();
virtual void AllocateTextures();
virtual void FreeTextures();
virtual void ReacquireResources();
virtual void ReleaseResources();
virtual int GetWidth();
virtual int GetHeight();
virtual int GetOffsetGeometry();
virtual int GetOffsetTangents();
virtual float* Lock( int nNumRows );
virtual void Unlock();
virtual ShaderAPITextureHandle_t SubDTexture();
private:
ShaderAPITextureHandle_t m_hSysMem;
ShaderAPITextureHandle_t m_hDefaultPool;
int m_nRowsLocked;
int m_nOffsetGeometry;
int m_nOffsetTangents;
};
//-----------------------------------------------------------------------------
// Singleton
//-----------------------------------------------------------------------------
static CSubDMgr s_SubDMgr;
ISubDMgr *g_pSubDMgr = &s_SubDMgr;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CSubDMgr::CSubDMgr()
{
m_nRowsLocked = 0;
m_nOffsetGeometry = 0;
m_nOffsetTangents = 0;
m_hSysMem = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_hDefaultPool = INVALID_SHADERAPI_TEXTURE_HANDLE;
}
bool CSubDMgr::ShouldAllocateTextures()
{
return true;
// return g_pMaterialSystemHardwareConfig->SupportsSubdivisionSurfaces();
}
int CSubDMgr::GetWidth()
{
return SUBD_TEXTURE_WIDTH;
}
int CSubDMgr::GetHeight()
{
return SUBD_TEXTURE_HEIGHT;
}
int CSubDMgr::GetOffsetGeometry()
{
return m_nOffsetGeometry;
}
int CSubDMgr::GetOffsetTangents()
{
return m_nOffsetTangents;
}
void CSubDMgr::AllocateTextures()
{
ReacquireResources();
}
void CSubDMgr::FreeTextures()
{
ReleaseResources();
}
void CSubDMgr::ReleaseResources()
{
if ( g_pShaderAPI->IsTexture( m_hSysMem ) )
{
g_pShaderAPI->DeleteTexture( m_hSysMem );
m_hSysMem = INVALID_SHADERAPI_TEXTURE_HANDLE;
}
if ( g_pShaderAPI->IsTexture( m_hDefaultPool ) )
{
g_pShaderAPI->DeleteTexture( m_hDefaultPool );
m_hDefaultPool = INVALID_SHADERAPI_TEXTURE_HANDLE;
}
}
void CSubDMgr::ReacquireResources()
{
Assert( m_hSysMem == INVALID_SHADERAPI_TEXTURE_HANDLE );
Assert( m_hDefaultPool == INVALID_SHADERAPI_TEXTURE_HANDLE );
// These scratch textures are ~4mb (30*8192*16 bytes) and can
// accommodate data for 8192 patches
g_pShaderAPI->CreateTextures( &m_hSysMem, 1, SUBD_TEXTURE_WIDTH, SUBD_TEXTURE_HEIGHT, 0, SUBD_TEXTURE_FORMAT, 1, 1, TEXTURE_CREATE_SYSMEM, "_SubDSysMemTexture", "SubD Textures" );
g_pShaderAPI->CreateTextures( &m_hDefaultPool, 1, SUBD_TEXTURE_WIDTH, SUBD_TEXTURE_HEIGHT, 0, SUBD_TEXTURE_FORMAT, 1, 1, TEXTURE_CREATE_DEFAULT_POOL | TEXTURE_CREATE_VERTEXTEXTURE, "_SubDVidMemTexture", "SubD Textures" );
g_pShaderAPI->ModifyTexture( m_hDefaultPool );
g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_NEAREST );
g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_NEAREST );
}
float *CSubDMgr::Lock( int nRows )
{
m_nRowsLocked = nRows;
return (float *) g_pShaderAPI->LockTex( m_hSysMem );
}
void CSubDMgr::Unlock()
{
g_pShaderAPI->UnlockTex( m_hSysMem );
g_pShaderAPI->UpdateTexture( 0, 0, SUBD_TEXTURE_WIDTH, m_nRowsLocked, m_hDefaultPool, m_hSysMem );
}
ShaderAPITextureHandle_t CSubDMgr::SubDTexture()
{
return m_hDefaultPool;
}
@@ -0,0 +1,179 @@
// ----------------------------------------- //
// File generated by VPC //
// ----------------------------------------- //
Source file: F:\csgo_64\cstrike15_src\materialsystem\base_visuals_data_processor.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\base_visuals_data_processor.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\base_visuals_data_processor.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\CColorCorrection.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\CColorCorrection.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\CColorCorrection.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\cmaterial.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\cmaterial.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\cmaterial.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\cmaterial_queuefriendly.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\cmaterial_queuefriendly.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\cmaterial_queuefriendly.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\cmaterialdict.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\cmaterialdict.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\cmaterialdict.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\CMaterialSubRect.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\CMaterialSubRect.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\CMaterialSubRect.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\cmaterialsystem.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\cmaterialsystem.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\cmaterialsystem.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\cmaterialvar.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\cmaterialvar.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\cmaterialvar.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\cmatlightmaps.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\cmatlightmaps.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\cmatlightmaps.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\cmatnullrendercontext.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\cmatnullrendercontext.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\cmatnullrendercontext.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\cmatpaintmaps.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\cmatpaintmaps.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\cmatpaintmaps.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\cmatqueuedrendercontext.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\cmatqueuedrendercontext.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\cmatqueuedrendercontext.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\cmatrendercontext.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\cmatrendercontext.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\cmatrendercontext.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\colorspace.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\colorspace.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\colorspace.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\composite_texture.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\composite_texture.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\composite_texture.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\ctexture.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\ctexture.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\ctexture.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\custom_material.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\custom_material.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\custom_material.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\common\debug_dll_check.cpp
Debug output file: F:\csgo_64\cstrike15_src\common\debug_dll_check.cpp
Release output file: F:\csgo_64\cstrike15_src\common\debug_dll_check.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\public\filesystem_helpers.cpp
Debug output file: F:\csgo_64\cstrike15_src\public\filesystem_helpers.cpp
Release output file: F:\csgo_64\cstrike15_src\public\filesystem_helpers.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\imagepacker.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\imagepacker.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\imagepacker.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\mat_stub.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\mat_stub.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\mat_stub.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\materialsystem_global.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\materialsystem_global.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\materialsystem_global.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\public\tier0\memoverride.cpp
Debug output file: F:\csgo_64\cstrike15_src\public\tier0\memoverride.cpp
Release output file: F:\csgo_64\cstrike15_src\public\tier0\memoverride.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\morph.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\morph.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\morph.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\occlusionquerymgr.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\occlusionquerymgr.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\occlusionquerymgr.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\pch_materialsystem.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\pch_materialsystem.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\pch_materialsystem.cpp
Containing unity file:
PCH file: pch_materialsystem.h
Builds PCH file: yes
Source file: F:\csgo_64\cstrike15_src\materialsystem\shadersystem.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\shadersystem.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\shadersystem.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\SubdMgr.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\SubdMgr.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\SubdMgr.cpp
Containing unity file:
PCH file:
Source file: F:\csgo_64\cstrike15_src\materialsystem\texturemanager.cpp
Debug output file: F:\csgo_64\cstrike15_src\materialsystem\texturemanager.cpp
Release output file: F:\csgo_64\cstrike15_src\materialsystem\texturemanager.cpp
Containing unity file:
PCH file:
@@ -0,0 +1,18 @@
//========= Copyright © 1996-2013, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "materialsystem/ivisualsdataprocessor.h"
#include "materialsystem/base_visuals_data_processor.h"
const char g_szMaterialParamNames[MATERIAL_PARAM_ID_COUNT][32] =
{
{ "$baseTexture" },
{ "$phongexponenttexture" },
{ "$bumpmap" },
{ "$anisodirtexture" },
{ "$masks1" }
};
+668
View File
@@ -0,0 +1,668 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#include "pch_materialsystem.h"
// NOTE: currently this file is marked as "exclude from build"
//#define _CHECK_MATERIALS_FOR_PROBLEMS 1
#ifdef _CHECK_MATERIALS_FOR_PROBLEMS
#include "vtf/vtf.h"
#include "tier1/utlbuffer.h"
#include "tier1/utlstring.h"
void CheckMateralsInDirectoryRecursive( const char *pRoot, const char *pDirectory );
#endif
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
#ifdef _CHECK_MATERIALS_FOR_PROBLEMS
//-----------------------------------------------------------------------------
// Does a texture have alpha?
//-----------------------------------------------------------------------------
static bool DoesTextureUseAlpha( const char *pTextureName, const char *pMaterialName )
{
if ( IsGameConsole() )
{
// not supporting
return false;
}
// Special textures start with '_'..
if ( pTextureName[0] == '_' )
return false;
// The texture name doubles as the relative file name
// It's assumed to have already been set by this point
// Compute the cache name
char pCacheFileName[MATERIAL_MAX_PATH];
Q_snprintf( pCacheFileName, sizeof( pCacheFileName ), "materials/%s.vtf", pTextureName );
CUtlBuffer buf;
FileHandle_t fileHandle = g_pFullFileSystem->Open( pCacheFileName, "rb" );
if ( fileHandle == FILESYSTEM_INVALID_HANDLE)
{
Warning( "Material \"%s\": can't open texture \"%s\"\n", pMaterialName, pCacheFileName );
return false;
}
// Check the .vtf for an alpha channel
IVTFTexture *pVTFTexture = CreateVTFTexture();
int nHeaderSize = VTFFileHeaderSize( VTF_MAJOR_VERSION );
buf.EnsureCapacity( nHeaderSize );
// read the header first.. it's faster!!
g_pFullFileSystem->Read( buf.Base(), nHeaderSize, fileHandle );
buf.SeekPut( CUtlBuffer::SEEK_HEAD, nHeaderSize );
// Unserialize the header
bool bUsesAlpha = false;
if (!pVTFTexture->Unserialize( buf, true ))
{
Warning( "Error reading material \"%s\"\n", pCacheFileName );
g_pFullFileSystem->Close(fileHandle);
}
else
{
if ( pVTFTexture->Flags() & (TEXTUREFLAGS_ONEBITALPHA | TEXTUREFLAGS_EIGHTBITALPHA) )
{
bUsesAlpha = true;
}
}
DestroyVTFTexture( pVTFTexture );
g_pFullFileSystem->Close( fileHandle );
return bUsesAlpha;
}
//-----------------------------------------------------------------------------
// Does a texture have alpha?
//-----------------------------------------------------------------------------
static bool DoesTextureUseNormal( const char *pTextureName, const char *pMaterialName, bool &bUsesAlpha, bool &bIsCompressed, int &nSizeInBytes )
{
nSizeInBytes = 0;
bUsesAlpha = false;
if ( IsGameConsole() )
{
// not supporting
return false;
}
// Special textures start with '_'..
if ( !pTextureName || ( pTextureName[0] == '_' ) || ( pTextureName[0] == 0 ) )
return false;
// The texture name doubles as the relative file name
// It's assumed to have already been set by this point
// Compute the cache name
char pCacheFileName[MATERIAL_MAX_PATH];
Q_snprintf( pCacheFileName, sizeof( pCacheFileName ), "materials/%s.vtf", pTextureName );
CUtlBuffer buf;
FileHandle_t fileHandle = g_pFullFileSystem->Open( pCacheFileName, "rb" );
if ( fileHandle == FILESYSTEM_INVALID_HANDLE)
{
// Warning( "Material \"%s\": can't open texture \"%s\"\n", pMaterialName, pCacheFileName );
return false;
}
// Check the .vtf for an alpha channel
IVTFTexture *pVTFTexture = CreateVTFTexture();
int nHeaderSize = VTFFileHeaderSize( VTF_MAJOR_VERSION );
buf.EnsureCapacity( nHeaderSize );
// read the header first.. it's faster!!
g_pFullFileSystem->Read( buf.Base(), nHeaderSize, fileHandle );
buf.SeekPut( CUtlBuffer::SEEK_HEAD, nHeaderSize );
// Unserialize the header
bool bUsesNormal = false;
if ( !pVTFTexture->Unserialize( buf, true ) )
{
Warning( "Error reading material \"%s\"\n", pCacheFileName );
}
else
{
if ( pVTFTexture->Flags() & TEXTUREFLAGS_NORMAL )
{
bUsesAlpha = false;
bUsesNormal = true;
bIsCompressed = ImageLoader::IsCompressed( pVTFTexture->Format() ) || ( pVTFTexture->Format() == IMAGE_FORMAT_A8 );
nSizeInBytes = pVTFTexture->ComputeTotalSize();
if ( pVTFTexture->Flags() & (TEXTUREFLAGS_ONEBITALPHA | TEXTUREFLAGS_EIGHTBITALPHA) )
{
bUsesAlpha = true;
}
}
}
DestroyVTFTexture( pVTFTexture );
g_pFullFileSystem->Close( fileHandle );
return bUsesNormal;
}
//-----------------------------------------------------------------------------
// Is this a real texture
//-----------------------------------------------------------------------------
static bool IsTexture( const char *pTextureName )
{
// Special textures start with '_'..
if ( pTextureName[0] == '_' )
return false;
// The texture name doubles as the relative file name
// It's assumed to have already been set by this point
// Compute the cache name
char pCacheFileName[MATERIAL_MAX_PATH];
Q_snprintf( pCacheFileName, sizeof( pCacheFileName ), "materials/%s.vtf", pTextureName );
FileHandle_t fileHandle = g_pFullFileSystem->Open( pCacheFileName, "rb" );
if ( fileHandle == FILESYSTEM_INVALID_HANDLE)
return false;
g_pFullFileSystem->Close( fileHandle );
return true;
}
//-----------------------------------------------------------------------------
// Scan material + all subsections for key
//-----------------------------------------------------------------------------
static float MaterialFloatKeyValue( KeyValues *pKeyValues, const char *pKeyName, float flDefault )
{
float flValue = pKeyValues->GetFloat( pKeyName, flDefault );
if ( flValue != flDefault )
return flValue;
for( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() )
{
float flValue = MaterialFloatKeyValue( pSubKey, pKeyName, flDefault );
if ( flValue != flDefault )
return flValue;
}
return flDefault;
}
int ParseVectorFromKeyValueString( KeyValues *pKeyValue, const char *pMaterialName, float vecVal[4] );
static bool AsVectorsEqual( int nDim1, float *pVector1, int nDim2, float *pVector2 )
{
if ( nDim1 != nDim2 )
return false;
for ( int i = 0; i < nDim1; ++i )
{
if ( fabs( pVector1[i] - pVector2[i] ) > 1e-3 )
return false;
}
return true;
}
static bool MaterialVectorKeyValue( KeyValues *pKeyValues, const char *pKeyName, int nDefaultDim, float *pDefault, int *pDim, float *pVector )
{
int nDim;
float retVal[4];
KeyValues *pValue = pKeyValues->FindKey( pKeyName );
if ( pValue )
{
switch( pValue->GetDataType() )
{
case KeyValues::TYPE_INT:
{
int nInt = pValue->GetInt();
for ( int i = 0; i < 4; ++i )
{
retVal[i] = nInt;
}
if ( !AsVectorsEqual( nDefaultDim, pDefault, nDefaultDim, retVal ) )
{
*pDim = nDefaultDim;
memcpy( pVector, retVal, nDefaultDim * sizeof(float) );
return true;
}
}
break;
case KeyValues::TYPE_FLOAT:
{
float flFloat = pValue->GetFloat();
for ( int i = 0; i < 4; ++i )
{
retVal[i] = flFloat;
}
if ( !AsVectorsEqual( nDefaultDim, pDefault, nDefaultDim, retVal ) )
{
*pDim = nDefaultDim;
memcpy( pVector, retVal, nDefaultDim * sizeof(float) );
return true;
}
}
break;
case KeyValues::TYPE_STRING:
{
nDim = ParseVectorFromKeyValueString( pValue, "", retVal );
if ( !AsVectorsEqual( nDefaultDim, pDefault, nDim, retVal ) )
{
*pDim = nDim;
memcpy( pVector, retVal, nDim * sizeof(float) );
return true;
}
}
break;
}
}
for( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() )
{
if ( MaterialVectorKeyValue( pSubKey, pKeyName, nDefaultDim, pDefault, &nDim, retVal ) )
{
*pDim = nDim;
memcpy( pVector, retVal, nDim * sizeof(float) );
return true;
}
}
*pDim = nDefaultDim;
memcpy( pVector, pDefault, nDefaultDim * sizeof(float) );
return false;
}
//-----------------------------------------------------------------------------
// Scan material + all subsections for key
//-----------------------------------------------------------------------------
static bool DoesMaterialHaveKey( KeyValues *pKeyValues, const char *pKeyName )
{
if ( pKeyValues->GetString( pKeyName, NULL ) != NULL )
return true;
for( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() )
{
if ( DoesMaterialHaveKey( pSubKey, pKeyName ) )
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// Scan all materials for errors
//-----------------------------------------------------------------------------
static int s_nNormalBytes;
static int s_nNormalCompressedBytes;
static int s_nNormalPalettizedBytes;
static int s_nNormalWithAlphaBytes;
static int s_nNormalWithAlphaCompressedBytes;
struct VTFInfo_t
{
CUtlString m_VTFName;
bool m_bFoundInVMT;
};
void CheckKeyValues( KeyValues *pKeyValues, CUtlVector<VTFInfo_t> &vtf )
{
for ( KeyValues *pSubKey = pKeyValues->GetFirstValue(); pSubKey; pSubKey = pSubKey->GetNextValue() )
{
if ( pSubKey->GetDataType() != KeyValues::TYPE_STRING )
continue;
if ( IsTexture( pSubKey->GetString() ) )
{
int nLen = Q_strlen( pSubKey->GetString() ) + 1;
char *pTemp = (char*)_alloca( nLen );
memcpy( pTemp, pSubKey->GetString(), nLen );
Q_FixSlashes( pTemp );
int nCount = vtf.Count();
for ( int i = 0; i < nCount; ++i )
{
if ( Q_stricmp( vtf[i].m_VTFName, pTemp ) )
continue;
vtf[i].m_bFoundInVMT = true;
break;
}
}
}
for ( KeyValues *pSubKey = pKeyValues->GetFirstTrueSubKey(); pSubKey; pSubKey = pSubKey->GetNextTrueSubKey() )
{
CheckKeyValues( pSubKey, vtf );
}
}
void CheckMaterial( KeyValues *pKeyValues, const char *pRoot, const char *pFileName, CUtlVector<VTFInfo_t> &vtf )
{
const char *pShaderName = pKeyValues->GetName();
/*
if ( Q_stristr( pShaderName, "Water" ) ||
Q_stristr( pShaderName, "Eyeball" ) ||
Q_stristr( pShaderName, "Shadow" ) ||
Q_stristr( pShaderName, "Refract" ) ||
Q_stristr( pShaderName, "Predator" ) ||
Q_stristr( pShaderName, "ParticleSphere" ) ||
Q_stristr( pShaderName, "DebugLuxels" ) ||
Q_stristr( pShaderName, "GooInGlass" ) ||
Q_stristr( pShaderName, "Modulate" ) ||
Q_stristr( pShaderName, "UnlitTwoTexture" ) ||
Q_stristr( pShaderName, "Cloud" ) ||
Q_stristr( pShaderName, "WorldVertexTransition" ) ||
Q_stristr( pShaderName, "DecalModulate" ) ||
Q_stristr( pShaderName, "DecalBaseTimesLightmapAlphaBlendSelfIllum" ) ||
Q_stristr( pShaderName, "Sprite" ) )
{
return;
}
// Check for alpha channels
const char *pBaseTextureName = pKeyValues->GetString( "$basetexture", NULL );
if ( pBaseTextureName != NULL )
{
if ( DoesTextureUseAlpha( pBaseTextureName, pFileName ) )
{
float flAlpha = MaterialFloatKeyValue( pKeyValues, "$alpha", 1.0f );
bool bHasVertexAlpha = DoesMaterialHaveKey( pKeyValues, "$vertexalpha" ); // Modulation always happens here whether we want it to or not
bool bHasAlphaTest = DoesMaterialHaveKey( pKeyValues, "$alphatest" );
bool bHasTranslucent = DoesMaterialHaveKey( pKeyValues, "$translucent" );
bool bHasSelfIllum = DoesMaterialHaveKey( pKeyValues, "$selfillum" );
bool bHasBaseAlphaEnvMapMask = DoesMaterialHaveKey( pKeyValues, "$basealphaenvmapmask" );
if ( (flAlpha == 1.0f) && !bHasVertexAlpha && !bHasAlphaTest && !bHasTranslucent && !bHasSelfIllum && !bHasBaseAlphaEnvMapMask )
{
Warning("Material \"%s\": BASETEXTURE \"%s\"\n", pFileName, pBaseTextureName );
}
}
}
*/
/*
// Check for bump, spec, and no normalmapalphaenvmapmask
const char *pBumpmapName = pKeyValues->GetString( "$bumpmap", NULL );
if ( pBumpmapName != NULL )
{
if ( DoesTextureUseAlpha( pBumpmapName, pFileName ) )
{
bool bHasEnvmap = DoesMaterialHaveKey( pKeyValues, "$envmap" );
bool bHasNormalMapAlphaEnvMapMask = DoesMaterialHaveKey( pKeyValues, "$normalmapalphaenvmapmask" );
if ( !bHasEnvmap || !bHasNormalMapAlphaEnvMapMask )
{
Warning("Material \"%s\": BUMPMAP \"%s\"\n", pFileName, pBumpmapName );
}
}
}
*/
/*
if ( !Q_stristr( pShaderName, "LightmappedGeneric" ) &&
!Q_stristr( pShaderName, "VertexLitGeneric" ) )
{
return;
}
if ( DoesMaterialHaveKey( pKeyValues, "$envmap" ) && DoesMaterialHaveKey( pKeyValues, "$bumpmap" ) )
{
int nDim;
float retVal[4];
float defaultVal[4] = { 1, 1, 1, 1 };
if ( MaterialVectorKeyValue( pKeyValues, "$envmaptint", 3, defaultVal, &nDim, retVal ) )
{
Warning("ENVMAP + ENVMAPTINT : Material \"%s\"\n", pFileName );
}
// else
// {
// Warning("ENVMAP only: Material \"%s\"\n", pFileName );
// }
}
*/
/*
if ( !Q_stristr( pShaderName, "Refract" ) )
{
return;
}
if ( !DoesMaterialHaveKey( pKeyValues, "$envmap" ) )
{
bool bUsesAlpha, bIsCompressed, bIsPalettized;
int nSizeInBytes;
if ( DoesTextureUseNormal( pKeyValues->GetString( "$normalmap" ),
pFileName, bUsesAlpha, bIsCompressed, bIsPalettized, nSizeInBytes ) )
{
if ( bIsCompressed )
{
Warning("Bad : Material compressed \"%s\"\n", pFileName );
}
else
{
Warning("Bad : Material \"%s\"\n", pFileName );
}
}
}
*/
/*
if ( !Q_stristr( pShaderName, "WorldTwoTextureBlend" ) )
{
return;
}
if ( DoesMaterialHaveKey( pKeyValues, "$envmap" ) ||
DoesMaterialHaveKey( pKeyValues, "$parallaxmap" ) ||
DoesMaterialHaveKey( pKeyValues, "$bumpmap" ) ||
DoesMaterialHaveKey( pKeyValues, "$vertexcolor" ) ||
DoesMaterialHaveKey( pKeyValues, "$basetexture2" )
)
{
Warning("Bad : Material \"%s\"\n", pFileName );
}
*/
for ( KeyValues *pSubKey = pKeyValues->GetFirstValue(); pSubKey; pSubKey = pSubKey->GetNextValue() )
{
// Msg( " Checking %s\n", pSubKey->GetString() );
if ( pSubKey->GetDataType() != KeyValues::TYPE_STRING )
continue;
bool bUsesAlpha, bIsCompressed;
int nSizeInBytes;
if ( DoesTextureUseNormal( pSubKey->GetString(), pFileName, bUsesAlpha, bIsCompressed, nSizeInBytes ) )
{
if ( bUsesAlpha )
{
if ( bIsCompressed )
{
s_nNormalWithAlphaCompressedBytes += nSizeInBytes;
}
else
{
s_nNormalWithAlphaBytes += nSizeInBytes;
Msg( "Normal texture w alpha uncompressed %s\n", pSubKey->GetString() );
}
}
else
{
if ( bIsCompressed )
{
s_nNormalCompressedBytes += nSizeInBytes;
}
else
{
s_nNormalBytes += nSizeInBytes;
}
}
}
}
/*
if ( !Q_stristr( pShaderName, "VertexLitGeneric" ) )
return;
if ( !DoesMaterialHaveKey( pKeyValues, "$envmap" ) && DoesMaterialHaveKey( pKeyValues, "$bumpmap" ) )
{
Warning("BUMPMAP + no ENVMAP : Material \"%s\"\n", pFileName );
}
*/
// CheckKeyValues( pKeyValues, vtf );
}
//-----------------------------------------------------------------------------
// Build list of all VTFs
//-----------------------------------------------------------------------------
void CheckVTFInDirectoryRecursive( const char *pRoot, const char *pDirectory, CUtlVector< VTFInfo_t > &vtf )
{
#define BUF_SIZE 1024
char buf[BUF_SIZE];
WIN32_FIND_DATA wfd;
HANDLE findHandle;
sprintf( buf, "%s/%s/*.vtf", pRoot, pDirectory );
findHandle = FindFirstFile( buf, &wfd );
if ( findHandle != INVALID_HANDLE_VALUE )
{
do
{
int i = vtf.AddToTail( );
char buf[MAX_PATH];
char buf2[MAX_PATH];
Q_snprintf( buf, MAX_PATH, "%s/%s", pDirectory, wfd.cFileName );
Q_FixSlashes( buf );
Q_StripExtension( buf, buf2, sizeof(buf2) );
Assert( !Q_strnicmp( buf2, "materials\\", 10 ) );
vtf[i].m_VTFName = &buf2[10];
vtf[i].m_bFoundInVMT = false;
} while ( FindNextFile ( findHandle, &wfd ) );
FindClose ( findHandle );
}
// do subdirectories
sprintf( buf, "%s/%s/*.*", pRoot, pDirectory );
findHandle = FindFirstFile( buf, &wfd );
if ( findHandle != INVALID_HANDLE_VALUE )
{
do
{
if( wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( ( strcmp( wfd.cFileName, ".." ) == 0 ) ||
( strcmp( wfd.cFileName, "." ) == 0 ) )
{
continue;
}
char buf[MAX_PATH];
Q_snprintf( buf, MAX_PATH, "%s/%s", pDirectory, wfd.cFileName );
CheckVTFInDirectoryRecursive( pRoot, buf, vtf );
}
} while ( FindNextFile ( findHandle, &wfd ) );
FindClose ( findHandle );
}
#undef BUF_SIZE
}
//-----------------------------------------------------------------------------
// Scan all materials for errors
//-----------------------------------------------------------------------------
void _CheckMateralsInDirectoryRecursive( const char *pRoot, const char *pDirectory, CUtlVector< VTFInfo_t > &vtf )
{
#define BUF_SIZE 1024
char buf[BUF_SIZE];
WIN32_FIND_DATA wfd;
HANDLE findHandle;
sprintf( buf, "%s/%s/*.vmt", pRoot, pDirectory );
findHandle = FindFirstFile( buf, &wfd );
if ( findHandle != INVALID_HANDLE_VALUE )
{
do
{
KeyValues * vmtKeyValues = new KeyValues("vmt");
char pFileName[MAX_PATH];
Q_snprintf( pFileName, sizeof( pFileName ), "%s/%s", pDirectory, wfd.cFileName );
if ( !vmtKeyValues->LoadFromFile( g_pFullFileSystem, pFileName, "GAME" ) )
{
Warning( "CheckMateralsInDirectoryRecursive: can't open \"%s\"\n", pFileName );
continue;
}
CheckMaterial( vmtKeyValues, pRoot, pFileName, vtf );
vmtKeyValues->deleteThis();
} while ( FindNextFile ( findHandle, &wfd ) );
FindClose ( findHandle );
}
// do subdirectories
sprintf( buf, "%s/%s/*.*", pRoot, pDirectory );
findHandle = FindFirstFile( buf, &wfd );
if ( findHandle != INVALID_HANDLE_VALUE )
{
do
{
if( wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
if( ( strcmp( wfd.cFileName, ".." ) == 0 ) ||
( strcmp( wfd.cFileName, "." ) == 0 ) )
{
continue;
}
char buf[MAX_PATH];
Q_snprintf( buf, MAX_PATH, "%s/%s", pDirectory, wfd.cFileName );
_CheckMateralsInDirectoryRecursive( pRoot, buf, vtf );
}
} while ( FindNextFile ( findHandle, &wfd ) );
FindClose ( findHandle );
}
// Msg( "Normal only %d/%d/%d Normal w alpha %d/%d\n", s_nNormalBytes, s_nNormalPalettizedBytes, s_nNormalCompressedBytes, s_nNormalWithAlphaBytes, s_nNormalWithAlphaCompressedBytes );
#undef BUF_SIZE
}
void CheckMateralsInDirectoryRecursive( const char *pRoot, const char *pDirectory )
{
CUtlVector< VTFInfo_t > vtfNames;
// CheckVTFInDirectoryRecursive( pRoot, pDirectory, vtfNames );
_CheckMateralsInDirectoryRecursive( pRoot, pDirectory, vtfNames );
/*
int nCount = vtfNames.Count();
for ( int i = 0; i < nCount; ++i )
{
if ( !vtfNames[i].m_bFoundInVMT )
{
Msg( "Unused VTF %s\n", vtfNames[i].m_VTFName );
}
}
*/
}
#endif // _CHECK_MATERIALS_FOR_PROBLEMS
File diff suppressed because it is too large. Load diff
+391
View File
@@ -0,0 +1,391 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include "cmaterial_queuefriendly.h"
#include "tier1/callqueue.h"
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
#define USE_QUEUED_MATERIAL_CALLS //uncomment to queue up material changing calls. Comment out to always use instant calls.
#ifdef USE_QUEUED_MATERIAL_CALLS
#define QUEUE_MATERIAL_CALL( FuncName, ... ) \
{ \
ICallQueue *pCallQueue = materials->GetRenderContext()->GetCallQueue(); \
if ( !pCallQueue ) \
{ \
m_pRealTimeVersion->FuncName( __VA_ARGS__ ); \
} \
else \
{ \
pCallQueue->QueueCall( m_pRealTimeVersion, &IMaterialInternal::FuncName, ##__VA_ARGS__ ); \
} \
}
#else
#define QUEUE_MATERIAL_CALL( FuncName, ... ) m_pRealTimeVersion->FuncName( __VA_ARGS__ );
#endif
const char *CMaterial_QueueFriendly::GetName() const
{
return m_pRealTimeVersion->GetName();
}
const char *CMaterial_QueueFriendly::GetTextureGroupName() const
{
return m_pRealTimeVersion->GetTextureGroupName();
}
PreviewImageRetVal_t CMaterial_QueueFriendly::GetPreviewImageProperties( int *width, int *height, ImageFormat *imageFormat, bool* isTranslucent ) const
{
return m_pRealTimeVersion->GetPreviewImageProperties( width, height, imageFormat, isTranslucent );
}
PreviewImageRetVal_t CMaterial_QueueFriendly::GetPreviewImage( unsigned char *data, int width, int height, ImageFormat imageFormat ) const
{
return m_pRealTimeVersion->GetPreviewImage( data, width, height, imageFormat );
}
int CMaterial_QueueFriendly::GetMappingWidth( )
{
return m_pRealTimeVersion->GetMappingWidth();
}
int CMaterial_QueueFriendly::GetMappingHeight( )
{
return m_pRealTimeVersion->GetMappingHeight();
}
int CMaterial_QueueFriendly::GetNumAnimationFrames( )
{
return m_pRealTimeVersion->GetNumAnimationFrames();
}
bool CMaterial_QueueFriendly::InMaterialPage( void )
{
return m_pRealTimeVersion->InMaterialPage();
}
void CMaterial_QueueFriendly::GetMaterialOffset( float *pOffset )
{
m_pRealTimeVersion->GetMaterialOffset( pOffset );
}
void CMaterial_QueueFriendly::GetMaterialScale( float *pScale )
{
m_pRealTimeVersion->GetMaterialScale( pScale );
}
IMaterial *CMaterial_QueueFriendly::GetMaterialPage( void )
{
return m_pRealTimeVersion->GetMaterialPage();
}
void CMaterial_QueueFriendly::IncrementReferenceCount( void )
{
m_pRealTimeVersion->IncrementReferenceCount();
}
int CMaterial_QueueFriendly::GetEnumerationID( void ) const
{
return m_pRealTimeVersion->GetEnumerationID();
}
bool CMaterial_QueueFriendly::HasProxy( void ) const
{
return m_pRealTimeVersion->HasProxy();
}
void CMaterial_QueueFriendly::GetReflectivity( Vector& reflect )
{
m_pRealTimeVersion->GetReflectivity( reflect );
}
bool CMaterial_QueueFriendly::GetPropertyFlag( MaterialPropertyTypes_t type )
{
return m_pRealTimeVersion->GetPropertyFlag( type );
}
bool CMaterial_QueueFriendly::IsTwoSided()
{
return m_pRealTimeVersion->IsTwoSided();
}
int CMaterial_QueueFriendly::ShaderParamCount() const
{
return m_pRealTimeVersion->ShaderParamCount();
}
bool CMaterial_QueueFriendly::IsErrorMaterial() const
{
return m_pRealTimeVersion->IsErrorMaterial();
}
bool CMaterial_QueueFriendly::IsSpriteCard()
{
return m_pRealTimeVersion->IsSpriteCard();
}
//TODO: Investigate if these are likely to change at all when setting vars/flags
bool CMaterial_QueueFriendly::IsAlphaTested()
{
return m_pRealTimeVersion->IsAlphaTested();
}
bool CMaterial_QueueFriendly::IsVertexLit()
{
return m_pRealTimeVersion->IsVertexLit();
}
VertexFormat_t CMaterial_QueueFriendly::GetVertexFormat() const
{
return m_pRealTimeVersion->GetVertexFormat();
}
bool CMaterial_QueueFriendly::UsesEnvCubemap( void )
{
return m_pRealTimeVersion->UsesEnvCubemap();
}
bool CMaterial_QueueFriendly::NeedsTangentSpace( void )
{
return m_pRealTimeVersion->NeedsTangentSpace();
}
bool CMaterial_QueueFriendly::NeedsSoftwareSkinning( void )
{
return m_pRealTimeVersion->NeedsSoftwareSkinning();
}
int CMaterial_QueueFriendly::GetNumPasses( void )
{
return m_pRealTimeVersion->GetNumPasses();
}
int CMaterial_QueueFriendly::GetTextureMemoryBytes( void )
{
return m_pRealTimeVersion->GetTextureMemoryBytes();
}
bool CMaterial_QueueFriendly::NeedsLightmapBlendAlpha( void )
{
return m_pRealTimeVersion->NeedsLightmapBlendAlpha();
}
bool CMaterial_QueueFriendly::NeedsSoftwareLighting( void )
{
return m_pRealTimeVersion->NeedsSoftwareLighting();
}
void CMaterial_QueueFriendly::GetLowResColorSample( float s, float t, float *color ) const
{
m_pRealTimeVersion->GetLowResColorSample( s, t, color );
}
IMaterialVar *CMaterial_QueueFriendly::FindVar( const char *varName, bool *found, bool complain )
{
//TODO: return a queue friendly variable that can be get/set
return m_pRealTimeVersion->FindVar( varName, found, complain );
}
IMaterialVar *CMaterial_QueueFriendly::FindVarFast( char const *pVarName, unsigned int *pToken )
{
//TODO: return a queue friendly variable that can be get/set
return m_pRealTimeVersion->FindVarFast( pVarName, pToken );
}
IMaterialVar **CMaterial_QueueFriendly::GetShaderParams( void )
{
//TODO: return queue friendly variables that can be get/set
return m_pRealTimeVersion->GetShaderParams();
}
void CMaterial_QueueFriendly::DecrementReferenceCount( void )
{
QUEUE_MATERIAL_CALL( DecrementReferenceCount );
}
void CMaterial_QueueFriendly::DeleteIfUnreferenced()
{
QUEUE_MATERIAL_CALL( DeleteIfUnreferenced );
}
void CMaterial_QueueFriendly::RecomputeStateSnapshots()
{
QUEUE_MATERIAL_CALL( RecomputeStateSnapshots );
}
bool CMaterial_QueueFriendly::IsTranslucent()
{
//TODO: need to base this as if the queued state is 100% up to date
return m_pRealTimeVersion->IsTranslucentInternal( m_fAlphaModulationOnQueueCompletion );
}
bool CMaterial_QueueFriendly::IsTranslucentUnderModulation( float fAlphaModulation ) const
{
return m_pRealTimeVersion->IsTranslucentUnderModulation( fAlphaModulation );
}
bool CMaterial_QueueFriendly::NeedsPowerOfTwoFrameBufferTexture( bool bCheckSpecificToThisFrame )
{
//bCheckSpecificToThisFrame scares me a bit.
return m_pRealTimeVersion->NeedsPowerOfTwoFrameBufferTexture( bCheckSpecificToThisFrame );
}
bool CMaterial_QueueFriendly::NeedsFullFrameBufferTexture( bool bCheckSpecificToThisFrame )
{
//bCheckSpecificToThisFrame scares me a bit.
return m_pRealTimeVersion->NeedsFullFrameBufferTexture( bCheckSpecificToThisFrame );
}
void CMaterial_QueueFriendly::AlphaModulate( float alpha )
{
QUEUE_MATERIAL_CALL( AlphaModulate, alpha );
m_fAlphaModulationOnQueueCompletion = alpha;
}
void CMaterial_QueueFriendly::ColorModulate( float r, float g, float b )
{
QUEUE_MATERIAL_CALL( ColorModulate, r, g, b );
m_vColorModulationOnQueueCompletion.Init( r, g, b );
}
void CMaterial_QueueFriendly::SetMaterialVarFlag( MaterialVarFlags_t flag, bool on )
{
QUEUE_MATERIAL_CALL( SetMaterialVarFlag, flag, on );
}
bool CMaterial_QueueFriendly::GetMaterialVarFlag( MaterialVarFlags_t flag ) const
{
//TODO: somehow mix both queued and real time states
return m_pRealTimeVersion->GetMaterialVarFlag( flag );
}
void CMaterial_QueueFriendly::SetShader( const char *pShaderName )
{
//TODO: queue it and investigate, seems like a grenade.
m_pRealTimeVersion->SetShader( pShaderName );
}
void CMaterial_QueueFriendly::SetShaderAndParams( KeyValues *pKeyValues )
{
//TODO: queue it and investigate, seems like a grenade.
m_pRealTimeVersion->SetShaderAndParams( pKeyValues );
}
const char *CMaterial_QueueFriendly::GetShaderName() const
{
//TODO: return as if the queue is up to date. Someone could have set the shader very recently
return m_pRealTimeVersion->GetShaderName();
}
void CMaterial_QueueFriendly::Refresh()
{
//TODO: Investigate, this one seems like a grenade.
m_pRealTimeVersion->Refresh();
//QUEUE_MATERIAL_CALL( Refresh );
}
void CMaterial_QueueFriendly::RefreshPreservingMaterialVars()
{
//TODO: Investigate, this one seems like a grenade.
m_pRealTimeVersion->RefreshPreservingMaterialVars();
//QUEUE_MATERIAL_CALL( RefreshPreservingMaterialVars );
}
float CMaterial_QueueFriendly::GetAlphaModulation()
{
#ifdef USE_QUEUED_MATERIAL_CALLS
return m_fAlphaModulationOnQueueCompletion;
#else
return m_pRealTimeVersion->GetAlphaModulation();
#endif
}
void CMaterial_QueueFriendly::GetColorModulation( float *r, float *g, float *b )
{
#ifdef USE_QUEUED_MATERIAL_CALLS
*r = m_vColorModulationOnQueueCompletion.x;
*g = m_vColorModulationOnQueueCompletion.y;
*b = m_vColorModulationOnQueueCompletion.z;
#else
m_pRealTimeVersion->GetColorModulation( r, g, b );
#endif
}
void CMaterial_QueueFriendly::CallBindProxy( void *proxyData, ICallQueue *pCallQueue )
{
//TODO: queue it? Investigate.
return m_pRealTimeVersion->CallBindProxy( proxyData, pCallQueue );
}
void CMaterial_QueueFriendly::PrecacheMappingDimensions()
{
return m_pRealTimeVersion->PrecacheMappingDimensions();
}
void CMaterial_QueueFriendly::FindRepresentativeTexture()
{
return m_pRealTimeVersion->FindRepresentativeTexture();
}
bool CMaterial_QueueFriendly::IsRealTimeVersion( void ) const
{
return false;
}
IMaterialInternal *CMaterial_QueueFriendly::GetRealTimeVersion( void )
{
return m_pRealTimeVersion;
}
IMaterialInternal *CMaterial_QueueFriendly::GetQueueFriendlyVersion( void )
{
return this;
}
void CMaterial_QueueFriendly::UpdateToRealTime( void )
{
m_fAlphaModulationOnQueueCompletion = m_pRealTimeVersion->GetAlphaModulation();
m_pRealTimeVersion->GetColorModulation( &m_vColorModulationOnQueueCompletion.x,
&m_vColorModulationOnQueueCompletion.y,
&m_vColorModulationOnQueueCompletion.z );
}
bool CMaterial_QueueFriendly::SetTempExcluded( bool bSet, int nExcludedDimensionLimit )
{
return m_pRealTimeVersion->SetTempExcluded( bSet, nExcludedDimensionLimit );
}
+162
View File
@@ -0,0 +1,162 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#ifndef CMATERIAL_QUEUEFRIENDLY_H
#define CMATERIAL_QUEUEFRIENDLY_H
#ifdef _WIN32
#pragma once
#endif
#include "imaterialinternal.h"
class CMaterial_QueueFriendly : public IMaterialInternal //wraps a CMaterial with queue friendly functions for game/engine code. materialsystem/shaderapi code should use CMaterial directly.
{
public:
virtual const char * GetName() const;
virtual const char * GetTextureGroupName() const;
virtual PreviewImageRetVal_t GetPreviewImageProperties( int *width, int *height, ImageFormat *imageFormat, bool* isTranslucent ) const;
virtual PreviewImageRetVal_t GetPreviewImage( unsigned char *data, int width, int height, ImageFormat imageFormat ) const;
virtual int GetMappingWidth( );
virtual int GetMappingHeight( );
virtual int GetNumAnimationFrames( );
virtual bool InMaterialPage( void );
virtual void GetMaterialOffset( float *pOffset );
virtual void GetMaterialScale( float *pScale );
virtual IMaterial *GetMaterialPage( void );
virtual void IncrementReferenceCount( void );
virtual int GetEnumerationID( void ) const;
virtual bool HasProxy( void ) const;
virtual void GetReflectivity( Vector& reflect );
virtual bool GetPropertyFlag( MaterialPropertyTypes_t type );
virtual bool IsTwoSided();
virtual int ShaderParamCount() const;
virtual bool IsErrorMaterial() const; //should probably return the realtime error material instead of this wrapper for it
virtual bool IsSpriteCard(); //lets just assume nobody changes the shader to spritecard and immediately asks if it's a spritecard
//TODO: Investigate if these are likely to change at all when setting vars/flags
virtual bool IsAlphaTested();
virtual bool IsVertexLit();
virtual VertexFormat_t GetVertexFormat() const;
virtual bool UsesEnvCubemap( void );
virtual bool NeedsTangentSpace( void );
virtual bool NeedsSoftwareSkinning( void );
virtual int GetNumPasses( void );
virtual int GetTextureMemoryBytes( void );
virtual bool NeedsLightmapBlendAlpha( void );
virtual bool NeedsSoftwareLighting( void );
//TODO: Investigate if this can change over the course of a frame.
virtual void GetLowResColorSample( float s, float t, float *color ) const;
//Functions that need to be queue friendly, the whole reason for this wrapper class.
virtual IMaterialVar * FindVar( const char *varName, bool *found, bool complain = true );
virtual IMaterialVar * FindVarFast( char const *pVarName, unsigned int *pToken );
virtual IMaterialVar **GetShaderParams( void );
virtual void DecrementReferenceCount( void );
virtual void DeleteIfUnreferenced();
virtual void RecomputeStateSnapshots();
virtual bool IsTranslucent();
virtual bool IsTranslucentUnderModulation( float fAlphaModulation ) const;
virtual bool NeedsPowerOfTwoFrameBufferTexture( bool bCheckSpecificToThisFrame = true );
virtual bool NeedsFullFrameBufferTexture( bool bCheckSpecificToThisFrame = true );
virtual void AlphaModulate( float alpha );
virtual void ColorModulate( float r, float g, float b );
virtual void SetMaterialVarFlag( MaterialVarFlags_t flag, bool on );
virtual bool GetMaterialVarFlag( MaterialVarFlags_t flag ) const;
virtual void SetShader( const char *pShaderName );
virtual void SetShaderAndParams( KeyValues *pKeyValues );
virtual const char * GetShaderName() const;
virtual void Refresh();
virtual void RefreshPreservingMaterialVars();
virtual float GetAlphaModulation();
virtual void GetColorModulation( float *r, float *g, float *b );
virtual void CallBindProxy( void *proxyData, ICallQueue *pCallQueue );
virtual void PrecacheMappingDimensions( );
virtual void FindRepresentativeTexture( void );
virtual bool WasReloadedFromWhitelist() { return m_pRealTimeVersion->WasReloadedFromWhitelist(); }
#define QUEUEFRIENDLY_USED_INTERNALLY_ASSERT AssertMsg( 0, "CMaterial_QueueFriendly used internally within materialsystem. Update the calling code to use a realtime CMaterial." )
//------------------------------------------------------------------------------
// IMaterialInternal interfaces. Internal systems should not be using this queue
// wrapper class at all. Switch to the real time pointer in the calling code.
//------------------------------------------------------------------------------
virtual int GetReferenceCount( ) const { return m_pRealTimeVersion->GetReferenceCount(); }
virtual void SetEnumerationID( int id ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->SetEnumerationID( id ); }
virtual void SetNeedsWhiteLightmap( bool val ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->SetNeedsWhiteLightmap( val ); }
virtual bool GetNeedsWhiteLightmap( ) const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->GetNeedsWhiteLightmap(); }
virtual void Uncache( bool bPreserveVars = false ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->Uncache( bPreserveVars ); }
virtual void Precache() { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->Precache(); }
// If provided, pKeyValues and pPatchKeyValues should come from LoadVMTFile()
virtual bool PrecacheVars( KeyValues *pKeyValues = NULL, KeyValues *pPatchKeyValues = NULL, CUtlVector<FileNameHandle_t> *pIncludes = NULL ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->PrecacheVars( pKeyValues, pPatchKeyValues, pIncludes ); }
virtual void ReloadTextures() { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->ReloadTextures(); }
virtual void SetMinLightmapPageID( int pageID ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->SetMinLightmapPageID( pageID ); }
virtual void SetMaxLightmapPageID( int pageID ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->SetMaxLightmapPageID( pageID ); }
virtual int GetMinLightmapPageID( ) const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->GetMinLightmapPageID(); }
virtual int GetMaxLightmapPageID( ) const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->GetMaxLightmapPageID(); }
virtual IShader *GetShader() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->GetShader(); }
virtual bool IsPrecached( ) const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->IsPrecached(); }
virtual bool IsPrecachedVars() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->IsPrecachedVars(); }
virtual void DrawMesh( VertexCompressionType_t vertexCompression, bool bIsAlphaModulating, bool bRenderingPreTessPatchMesh ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->DrawMesh( vertexCompression, bIsAlphaModulating, bRenderingPreTessPatchMesh ); }
virtual VertexFormat_t GetVertexUsage() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->GetVertexUsage(); }
virtual bool PerformDebugTrace() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->PerformDebugTrace(); }
virtual bool NoDebugOverride() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->NoDebugOverride(); }
virtual void ToggleSuppression() { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->ToggleSuppression(); }
virtual bool IsSuppressed() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->IsSuppressed(); }
virtual void ToggleDebugTrace() { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->ToggleDebugTrace(); }
virtual bool UseFog() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->UseFog(); }
virtual void AddMaterialVar( IMaterialVar *pMaterialVar ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->AddMaterialVar( pMaterialVar ); }
virtual ShaderRenderState_t *GetRenderState() { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->GetRenderState(); }
virtual bool IsManuallyCreated() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->IsManuallyCreated(); }
virtual bool NeedsFixedFunctionFlashlight() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->NeedsFixedFunctionFlashlight(); }
virtual bool IsUsingVertexID() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->IsUsingVertexID(); }
virtual void MarkAsPreloaded( bool bSet ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->MarkAsPreloaded( bSet ); }
virtual bool IsPreloaded() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->IsPreloaded(); }
virtual void ArtificialAddRef() { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->ArtificialAddRef(); }
virtual void ArtificialRelease() { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->ArtificialRelease(); }
virtual void ReportVarChanged( IMaterialVar *pVar ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; m_pRealTimeVersion->ReportVarChanged( pVar ); }
virtual uint32 GetChangeID() const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->GetChangeID(); }
virtual bool IsTranslucentInternal( float fAlphaModulation ) const { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->IsTranslucentInternal( fAlphaModulation ); }
virtual void DecideShouldReloadFromWhitelist( IFileList *pFileList ) { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->DecideShouldReloadFromWhitelist( pFileList ); }
virtual void ReloadFromWhitelistIfMarked() { QUEUEFRIENDLY_USED_INTERNALLY_ASSERT; return m_pRealTimeVersion->ReloadFromWhitelistIfMarked(); }
virtual bool IsRealTimeVersion( void ) const;
virtual IMaterialInternal *GetRealTimeVersion( void );
virtual IMaterialInternal *GetQueueFriendlyVersion( void );
void SetRealTimeVersion( IMaterialInternal *pRealTimeVersion ) { m_pRealTimeVersion = pRealTimeVersion; }
void UpdateToRealTime( void ); //update cached off variables using the real time version as a base.
virtual void CompactMaterialVars() {}
// The material system should be asking, and it should be working with the realtime version only.
virtual bool HasQueueFriendlyProxies() const { Assert( !"Unexpected call to HasQueueFriendlyProxies" ); return false; }
virtual bool SetTempExcluded( bool bSet, int nExcludedDimensionLimit );
protected:
IMaterialInternal *m_pRealTimeVersion; //the material we're wrapping with queued delays
private:
//some calls need to know what state the material would be in right now if the queue had completed.
float m_fAlphaModulationOnQueueCompletion;
Vector m_vColorModulationOnQueueCompletion;
};
#endif //#ifndef CMATERIAL_QUEUEFRIENDLY_H
+159
View File
@@ -0,0 +1,159 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#include "pch_materialsystem.h"
#ifndef _PS3
#define MATSYS_INTERNAL
#endif
#include "cmaterialdict.h"
#include "materialsystem_global.h"
#include "filesystem.h"
#include "imaterialinternal.h"
// NOTE: This must be the last file included!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// sort function
//-----------------------------------------------------------------------------
bool CMaterialDict::MaterialLessFunc( const MaterialLookup_t& src1,
const MaterialLookup_t& src2 )
{
// Always sort manually-created materials to the front
if ( src1.m_bManuallyCreated != src2.m_bManuallyCreated )
return src1.m_bManuallyCreated;
return src1.m_Name < src2.m_Name;
}
//-----------------------------------------------------------------------------
// sort function for missing materials
//-----------------------------------------------------------------------------
bool CMaterialDict::MissingMaterialLessFunc( const MissingMaterial_t& src1,
const MissingMaterial_t& src2 )
{
return src1.m_Name < src2.m_Name;
}
void CMaterialDict::Shutdown( )
{
// Clean up all materials..
RemoveAllMaterials();
// FIXME: Could dump list here...
m_MissingList.RemoveAll();
}
//-----------------------------------------------------------------------------
// Adds/removes the material to the list of all materials
//-----------------------------------------------------------------------------
void CMaterialDict::AddMaterialToMaterialList( IMaterialInternal *pMaterial )
{
MaterialLookup_t lookup;
lookup.m_pMaterial = pMaterial;
lookup.m_Name = pMaterial->GetName();
lookup.m_bManuallyCreated = pMaterial->IsManuallyCreated();
m_MaterialDict.Insert( lookup );
}
void CMaterialDict::RemoveMaterialFromMaterialList( IMaterialInternal *pMaterial )
{
// Gotta iterate over this manually; name-based lookup is bogus if there are two
// materials with the same name, which can happen for procedural materials
// First remove all the subrect materials, because they'll point at their material pages.
MaterialHandle_t i;
MaterialHandle_t iNext = InvalidMaterial();
for (i = FirstMaterial(); i != InvalidMaterial(); i = iNext )
{
iNext = NextMaterial(i);
if ( m_MaterialDict[i].m_pMaterial == pMaterial )
{
m_MaterialDict.RemoveAt( i );
break;
}
}
Assert( i != InvalidMaterial() );
#ifdef _DEBUG
for ( i = iNext; i != InvalidMaterial(); i = NextMaterial(i) )
{
Assert( m_MaterialDict[i].m_pMaterial != pMaterial );
}
#endif
}
//-----------------------------------------------------------------------------
// Adds, removes materials
//-----------------------------------------------------------------------------
IMaterialInternal* CMaterialDict::AddMaterial( char const* pName, const char *pTextureGroupName )
{
IMaterialInternal *pMaterial = IMaterialInternal::CreateMaterial( pName, pTextureGroupName );
Assert( pMaterial && pMaterial->IsRealTimeVersion() );
AddMaterialToMaterialList( pMaterial );
return pMaterial;
}
void CMaterialDict::RemoveMaterial( IMaterialInternal* pMaterial )
{
Assert( (pMaterial == NULL) || pMaterial->IsRealTimeVersion() );
RemoveMaterialFromMaterialList( pMaterial );
IMaterialInternal::DestroyMaterial( pMaterial );
}
IMaterialInternal *CMaterialDict::AddMaterialSubRect( const char *pName, const char *pTextureGroupName, KeyValues *pKeyValues, KeyValues *pPatchKeyValues )
{
IMaterialInternal *pMaterial = IMaterialInternal::CreateMaterialSubRect( pName, pTextureGroupName, pKeyValues, pPatchKeyValues, true );
Assert( pMaterial );
AddMaterialToMaterialList( pMaterial );
return pMaterial;
}
void CMaterialDict::RemoveMaterialSubRect( IMaterialInternal *pMaterial )
{
RemoveMaterialFromMaterialList( pMaterial );
IMaterialInternal::DestroyMaterialSubRect( pMaterial );
}
void CMaterialDict::RemoveMaterialFromMaterialList( MaterialHandle_t h )
{
m_MaterialDict.RemoveAt( h );
}
void CMaterialDict::RemoveAllMaterialsFromMaterialList()
{
m_MaterialDict.RemoveAll();
}
void CMaterialDict::RemoveAllMaterials()
{
// First remove all the subrect materials, because they'll point at their material pages.
MaterialHandle_t i, iNext;
for (i = FirstMaterial(); i != InvalidMaterial(); i = iNext )
{
iNext = NextMaterial(i);
IMaterialInternal *pMaterial = GetMaterialInternal( i );
if ( pMaterial->InMaterialPage() )
{
IMaterialInternal::DestroyMaterialSubRect( pMaterial );
RemoveMaterialFromMaterialList( i );
}
}
// Now get rid of the rest of the materials, including the pages.
for (i = FirstMaterial(); i != InvalidMaterial(); i = NextMaterial(i) )
{
IMaterialInternal::DestroyMaterial( GetMaterialInternal( i ) );
}
RemoveAllMaterialsFromMaterialList();
}
+181
View File
@@ -0,0 +1,181 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#ifndef CMATERIALDICT_H
#define CMATERIALDICT_H
#include "tier1/utlsymbol.h"
#include "tier1/utlrbtree.h"
#ifndef MATSYS_INTERNAL
#error "This file is private to the implementation of IMaterialSystem/IMaterialSystemInternal"
#endif
#if defined( _WIN32 )
#pragma once
#endif
//-----------------------------------------------------------------------------
class IMaterial;
class IMaterialInternal;
typedef unsigned short MaterialHandle_t;
//-----------------------------------------------------------------------------
// Dictionary of all known materials
//-----------------------------------------------------------------------------
class CMaterialDict
{
public:
CMaterialDict() :
m_MaterialDict( 0, 256, MaterialLessFunc ),
m_MissingList( 0, 32, MissingMaterialLessFunc )
{
}
void Shutdown();
int GetNumMaterials( void ) const;
IMaterial* GetMaterial( MaterialHandle_t h ) const;
IMaterialInternal * GetMaterialInternal( MaterialHandle_t idx ) const;
MaterialHandle_t FirstMaterial() const;
MaterialHandle_t NextMaterial( MaterialHandle_t h ) const;
MaterialHandle_t InvalidMaterial() const;
IMaterialInternal * FindMaterial( const char *pszName, bool bManuallyCreated ) const;
void AddMaterialToMaterialList( IMaterialInternal *pMaterial );
void RemoveMaterialFromMaterialList( IMaterialInternal *pMaterial );
void RemoveMaterial( IMaterialInternal *pMaterial );
void RemoveMaterialSubRect( IMaterialInternal *pMaterial );
IMaterialInternal* AddMaterial( const char* pName, const char *pTextureGroupName );
// pKeyValues and pPatchKeyValues should come from LoadVMTFile()
IMaterialInternal* AddMaterialSubRect( const char* pName, const char *pTextureGroupName, KeyValues *pKeyValues, KeyValues *pPatchKeyValues );
bool NoteMissing( const char *pszName );
bool IsMissing( const char *pszName );
protected: /*private:*/
void RemoveAllMaterials();
void RemoveAllMaterialsFromMaterialList();
void RemoveMaterialFromMaterialList( MaterialHandle_t h );
// Stores a dictionary of materials, searched by name
struct MaterialLookup_t
{
IMaterialInternal* m_pMaterial;
CUtlSymbol m_Name;
bool m_bManuallyCreated;
};
// Stores a dictionary of missing materials to cut down on redundant warning messages
// TODO: 1) Could add a counter
// 2) Could dump to file/console at exit for exact list of missing materials
struct MissingMaterial_t
{
CUtlSymbol m_Name;
};
static bool MaterialLessFunc( const MaterialLookup_t& src1,
const MaterialLookup_t& src2 );
static bool MissingMaterialLessFunc( const MissingMaterial_t& src1,
const MissingMaterial_t& src2 );
CUtlRBTree< MaterialLookup_t, MaterialHandle_t > m_MaterialDict;
CUtlRBTree< MissingMaterial_t, int > m_MissingList;
};
//-----------------------------------------------------------------------------
// Material iteration methods
//-----------------------------------------------------------------------------
inline MaterialHandle_t CMaterialDict::FirstMaterial() const
{
return m_MaterialDict.FirstInorder();
}
inline MaterialHandle_t CMaterialDict::NextMaterial( MaterialHandle_t h ) const
{
return m_MaterialDict.NextInorder(h);
}
inline int CMaterialDict::GetNumMaterials( ) const
{
return m_MaterialDict.Count();
}
//-----------------------------------------------------------------------------
// Invalid index handle....
//-----------------------------------------------------------------------------
inline MaterialHandle_t CMaterialDict::InvalidMaterial() const
{
return m_MaterialDict.InvalidIndex();
}
//-----------------------------------------------------------------------------
// Handle to material
//-----------------------------------------------------------------------------
inline IMaterial* CMaterialDict::GetMaterial( MaterialHandle_t idx ) const
{
return m_MaterialDict[idx].m_pMaterial;
}
inline IMaterialInternal* CMaterialDict::GetMaterialInternal( MaterialHandle_t idx ) const
{
Assert( (m_MaterialDict[idx].m_pMaterial == NULL) || m_MaterialDict[idx].m_pMaterial->IsRealTimeVersion() );
return m_MaterialDict[idx].m_pMaterial;
}
inline IMaterialInternal* CMaterialDict::FindMaterial( const char *pszName, bool bManuallyCreated ) const
{
MaterialLookup_t lookup;
lookup.m_Name = pszName;
lookup.m_bManuallyCreated = bManuallyCreated; // This causes the search to find only file-created materials
MaterialHandle_t h = m_MaterialDict.Find( lookup );
if ( h != m_MaterialDict.InvalidIndex() )
{
return m_MaterialDict[h].m_pMaterial;
}
return NULL;
}
inline bool CMaterialDict::IsMissing( const char *pszName )
{
MissingMaterial_t missing;
missing.m_Name = pszName;
if ( m_MissingList.Find( missing ) != m_MissingList.InvalidIndex() )
return true;
return false;
}
inline bool CMaterialDict::NoteMissing( const char *pszName )
{
MissingMaterial_t missing;
missing.m_Name = pszName;
if ( m_MissingList.Find( missing ) != m_MissingList.InvalidIndex() )
{
return false;
}
m_MissingList.Insert( missing );
return true;
}
//-----------------------------------------------------------------------------
#endif // CMATERIALDICT_H
File diff suppressed because it is too large. Load diff
+915
View File
@@ -0,0 +1,915 @@
//========== Copyright 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#ifndef CMATERIALSYSTEM_H
#define CMATERIALSYSTEM_H
#include "tier1/delegates.h"
#include "materialsystem_global.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/ishaderapi.h"
#include "imaterialinternal.h"
#include "imaterialsysteminternal.h"
#include "shaderapi/ishaderutil.h"
#include "materialsystem/deformations.h"
#include "cmaterialdict.h"
#include "cmatlightmaps.h"
#include "cmatpaintmaps.h"
#include "cmatrendercontext.h"
#include "cmatqueuedrendercontext.h"
#include "materialsystem_global.h"
#include "custom_material.h"
#include "composite_texture.h"
#ifndef MATSYS_INTERNAL
#error "This file is private to the implementation of IMaterialSystem/IMaterialSystemInternal"
#endif
#if defined( _WIN32 )
#pragma once
#endif
#ifdef _PS3
#include "tls_ps3.h"
inline IMatRenderContextInternal *& Ps3TlsMaterialSystemRenderContextFn() { void **ppv = &( GetTLSGlobals()->pMaterialSystemRenderContext ); return *( IMatRenderContextInternal ** ) ppv; }
#define Ps3TlsMaterialSystemRenderContext Ps3TlsMaterialSystemRenderContextFn()
#endif
//-----------------------------------------------------------------------------
class CJob;
struct DeferredUpdateLightmapInfo_t;
// typedefs to allow use of delegation macros
typedef int LightmapOffset_t[2];
//-----------------------------------------------------------------------------
extern CThreadFastMutex g_MatSysMutex;
enum AsyncTextureLoadError_t
{
ASYNCTEXTURE_LOADERROR_NONE = 0,
ASYNCTEXTURE_LOADERROR_FILEOPEN = -1,
ASYNCTEXTRUE_LOADERROR_READING = -2,
};
struct AsyncTextureLoad_t
{
AsyncTextureContext_t *m_pContext;
void *m_pData;
int m_nNumReadBytes;
AsyncTextureLoadError_t m_LoadError;
};
//-----------------------------------------------------------------------------
// The material system implementation
//-----------------------------------------------------------------------------
class CMaterialSystem : public CTier2AppSystem< IMaterialSystemInternal >, public IShaderUtil
{
typedef CTier2AppSystem< IMaterialSystemInternal > BaseClass;
public:
CMaterialSystem();
~CMaterialSystem();
//---------------------------------------------------------
// Initialization and shutdown
//---------------------------------------------------------
//
// IAppSystem
//
virtual bool Connect( CreateInterfaceFn factory );
virtual void Disconnect();
virtual void * QueryInterface( const char *pInterfaceName );
virtual InitReturnVal_t Init();
virtual void Shutdown();
virtual const AppSystemInfo_t * GetDependencies( ) { return NULL; }
virtual AppSystemTier_t GetTier() { return APP_SYSTEM_TIER2; }
virtual void Reconnect( CreateInterfaceFn factory, const char *pInterfaceName ) { BaseClass::Reconnect( factory, pInterfaceName ); }
CreateInterfaceFn Init( const char* pShaderDLL,
IMaterialProxyFactory* pMaterialProxyFactory,
CreateInterfaceFn fileSystemFactory,
CreateInterfaceFn cvarFactory );
// Call this to set an explicit shader version to use
// Must be called before Init().
void SetShaderAPI( const char *pShaderAPIDLL );
// Must be called before Init(), if you're going to call it at all...
void SetAdapter( int nAdapter, int nFlags );
void ModInit();
void ModShutdown();
private:
// Used to dynamically load and unload the shader api
CreateInterfaceFn CreateShaderAPI( const char* pShaderDLL );
void DestroyShaderAPI();
// Method to get at interfaces supported by the SHADDERAPI
void * QueryShaderAPI( const char *pInterfaceName );
// Initializes the color correction terms
void InitColorCorrection();
// force the thread mode to single threaded, synchronizes with render thread if running
void ForceSingleThreaded();
void ThreadRelease( void ); // Tell QMS to release GL
void ThreadAcquire( void ); // Tell QMS to acquire GL
public:
virtual void SetThreadMode( MaterialThreadMode_t nextThreadMode, int nServiceThread );
virtual MaterialThreadMode_t GetThreadMode(); // current thread mode
virtual bool IsRenderThreadSafe( );
virtual bool AllowThreading( bool bAllow, int nServiceThread );
virtual void ExecuteQueued();
virtual void OnDebugEvent( const char * pEvent = "" );
//---------------------------------------------------------
// Component accessors
//---------------------------------------------------------
const CMatLightmaps * GetLightmaps() const { return &m_Lightmaps; }
CMatLightmaps * GetLightmaps() { return &m_Lightmaps; }
const CMatPaintmaps * GetPaintmaps( void ) const { return &m_Paintmaps; }
CMatPaintmaps * GetPaintmaps( void ) { return &m_Paintmaps; }
IMatRenderContext * GetRenderContext();
IMatRenderContext * CreateRenderContext( MaterialContextType_t type );
IMatRenderContext * SetRenderContext( IMatRenderContext * );
#ifdef _PS3
const IMatRenderContextInternal * GetRenderContextInternal() const { IMatRenderContextInternal *pRenderContext = Ps3TlsMaterialSystemRenderContext; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
IMatRenderContextInternal * GetRenderContextInternal() { IMatRenderContextInternal *pRenderContext = Ps3TlsMaterialSystemRenderContext; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
#elif defined(_X360)
const IMatRenderContextInternal * GetRenderContextInternal() const { IMatRenderContextInternal *pRenderContext = m_pRenderContexts[(int)ThreadInMainThread()]; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
IMatRenderContextInternal * GetRenderContextInternal() { IMatRenderContextInternal *pRenderContext = m_pRenderContexts[(int)ThreadInMainThread()]; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
#else
const IMatRenderContextInternal * GetRenderContextInternal() const { IMatRenderContextInternal *pRenderContext = m_pRenderContext; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
IMatRenderContextInternal * GetRenderContextInternal() { IMatRenderContextInternal *pRenderContext = m_pRenderContext; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
#endif
const CMaterialDict * GetMaterialDict() const { return &m_MaterialDict; }
CMaterialDict * GetMaterialDict() { return &m_MaterialDict; }
virtual void ReloadFilesInList( IFileList *pFilesToReload );
public:
//---------------------------------------------------------
// Config management
//---------------------------------------------------------
// IMaterialSystem
virtual IMaterialSystemHardwareConfig * GetHardwareConfig( const char *pVersion, int *returnCode );
// Get the current config for this video card (as last set by control panel or the default if not)
virtual bool UpdateConfig( bool forceUpdate );
virtual bool OverrideConfig( const MaterialSystem_Config_t &config, bool bForceUpdate );
const MaterialSystem_Config_t & GetCurrentConfigForVideoCard() const;
// Gets *recommended* configuration information associated with the display card and dxsupport.
virtual bool GetRecommendedVideoConfig( KeyValues *pKeyValues );
virtual bool GetRecommendedConfigurationInfo( int nDXLevel, KeyValues * pKeyValues );
// IShaderUtil
MaterialSystem_Config_t & GetConfig();
private:
//---------------------------------
// This is called when the config changes
void GenerateConfigFromConfigKeyValues( MaterialSystem_Config_t *pConfig, bool bOverwriteCommandLineValues );
// Read/write config into convars
void ReadConfigFromConVars( MaterialSystem_Config_t *pConfig );
void WriteConfigIntoConVars( const MaterialSystem_Config_t &config );
public:
// -----------------------------------------------------------
// Device methods
// -----------------------------------------------------------
int GetDisplayAdapterCount() const;
int GetCurrentAdapter() const;
void GetDisplayAdapterInfo( int adapter, MaterialAdapterInfo_t& info ) const;
int GetModeCount( int adapter ) const;
void GetModeInfo( int adapter, int mode, MaterialVideoMode_t& info ) const;
void AddModeChangeCallBack( ModeChangeCallbackFunc_t func );
void RemoveModeChangeCallBack( ModeChangeCallbackFunc_t func );
// Returns the mode info for the current display device
void GetDisplayMode( MaterialVideoMode_t& info ) const;
bool SetMode( void* hwnd, const MaterialSystem_Config_t &config );
// Reports support for a given MSAA mode
bool SupportsMSAAMode( int nMSAAMode );
// Reports support for a given CSAA mode
bool SupportsCSAAMode( int nNumSamples, int nQualityLevel );
bool SupportsHDRMode( HDRType_t nHDRModede );
bool UsesSRGBCorrectBlending() const;
// Shadow depth bias factors
void SetShadowDepthBiasFactors( float fShadowSlopeScaleDepthBias, float fShadowDepthBias );
void FlipCulling( bool bFlipCulling );
const MaterialSystemHardwareIdentifier_t &GetVideoCardIdentifier() const;
// Use this to spew information about the 3D layer
void SpewDriverInfo() const;
DELEGATE_TO_OBJECT_2VC( GetBackBufferDimensions, int &, int &, g_pShaderDevice );
DELEGATE_TO_OBJECT_0C( ImageFormat, GetBackBufferFormat, g_pShaderDevice );
DELEGATE_TO_OBJECT_0C( const AspectRatioInfo_t &, GetAspectRatioInfo, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( PushDeformation, DeformationBase_t const *, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( PopDeformation, g_pShaderAPI );
DELEGATE_TO_OBJECT_0C(int, GetNumActiveDeformations, g_pShaderAPI );
// -----------------------------------------------------------
// Window methods
// -----------------------------------------------------------
// Creates/ destroys a child window
bool AddView( void* hwnd );
void RemoveView( void* hwnd );
// Sets the view
void SetView( void* hwnd );
// -----------------------------------------------------------
// Control flow
// -----------------------------------------------------------
void BeginFrame( float frameTime );
void EndFrame();
virtual bool IsInFrame( ) const;
void Flush( bool flushHardware = false );
void SwapBuffers();
uint32 GetCurrentFrameCount();
// Flushes managed textures from the texture cacher
void EvictManagedResources();
void ReleaseResources();
void ReacquireResources();
// Recomputes a state snapshot
void RecomputeAllStateSnapshots();
void NoteAnisotropicLevel( int currentLevel );
// -----------------------------------------------------------
// Device loss/restore
// -----------------------------------------------------------
// Installs a function to be called when we need to release vertex buffers
void AddReleaseFunc( MaterialBufferReleaseFunc_t func );
void RemoveReleaseFunc( MaterialBufferReleaseFunc_t func );
// Installs a function to be called when we need to restore vertex buffers
void AddRestoreFunc( MaterialBufferRestoreFunc_t func );
void RemoveRestoreFunc( MaterialBufferRestoreFunc_t func );
// Called by the shader API when it's just about to lose video memory
void ReleaseShaderObjects( int nChangeFlags );
void RestoreShaderObjects( CreateInterfaceFn shaderFactory, int nChangeFlags = 0 );
// Installs a function to be called when we need to delete objects at the end of the render frame
virtual void AddEndFrameCleanupFunc( EndFrameCleanupFunc_t func );
virtual void RemoveEndFrameCleanupFunc( EndFrameCleanupFunc_t func );
// Gets called when the level is shuts down, will call the registered callback
virtual void OnLevelShutdown();
// Installs a function to be called when the level is shuts down
virtual bool AddOnLevelShutdownFunc( OnLevelShutdownFunc_t func, void * pUserData );
virtual bool RemoveOnLevelShutdownFunc( OnLevelShutdownFunc_t func, void * pUserData );
// Installs a function to be called when we need to perform operation before next rendering context is started
virtual void AddEndFramePriorToNextContextFunc( EndFramePriorToNextContextFunc_t func );
virtual void RemoveEndFramePriorToNextContextFunc( EndFramePriorToNextContextFunc_t func );
virtual void OnLevelLoadingComplete();
// Release temporary HW memory...
void ResetTempHWMemory( bool bExitingLevel = false );
// For dealing with device lost in cases where SwapBuffers isn't called all the time (Hammer)
void HandleDeviceLost();
// -----------------------------------------------------------
// Shaders
// -----------------------------------------------------------
int ShaderCount() const;
int GetShaders( int nFirstShader, int nCount, IShader **ppShaderList ) const;
int ShaderFlagCount() const;
const char * ShaderFlagName( int nIndex ) const;
void GetShaderFallback( const char *pShaderName, char *pFallbackShader, int nFallbackLength );
// -----------------------------------------------------------
// Material proxies
// -----------------------------------------------------------
IMaterialProxyFactory* GetMaterialProxyFactory();
void SetMaterialProxyFactory( IMaterialProxyFactory* pFactory );
IClientMaterialSystem* GetClientMaterialSystemInterface();
// -----------------------------------------------------------
// Refresh the spinner on load screens
// -----------------------------------------------------------
void RefreshFrontBufferNonInteractive();
virtual uint32 GetFrameTimestamps( ApplicationPerformanceCountersInfo_t &apci, ApplicationInstantCountersInfo_t & aici );
bool CanDownloadTextures() const;
// -----------------------------------------------------------
// Editor mode
// -----------------------------------------------------------
bool InEditorMode() const;
// Used to enable editor materials. Must be called before Init.
void EnableEditorMaterials();
void EnableGBuffers( void );
// Can we use editor materials?
bool CanUseEditorMaterials( void ) const;
int GetConfigurationFlags( void ) const;
// -----------------------------------------------------------
// Stub mode mode
// -----------------------------------------------------------
void SetInStubMode( bool bInStubMode );
bool IsInStubMode();
//---------------------------------------------------------
// Image formats
//---------------------------------------------------------
ImageFormatInfo_t const& ImageFormatInfo( ImageFormat fmt) const;
int GetMemRequired( int width, int height, int depth, ImageFormat format, bool mipmap );
bool ConvertImageFormat( unsigned char *src, enum ImageFormat srcImageFormat,
unsigned char *dst, enum ImageFormat dstImageFormat,
int width, int height, int srcStride = 0, int dstStride = 0 );
//---------------------------------------------------------
// Debug support
//---------------------------------------------------------
void CreateDebugMaterials();
void CleanUpDebugMaterials();
void CleanUpErrorMaterial();
void DebugPrintUsedMaterials( const char *pSearchSubString, bool bVerbose );
void DebugPrintUsedTextures();
void ToggleSuppressMaterial( const char* pMaterialName );
void ToggleDebugMaterial( const char* pMaterialName );
//---------------------------------------------------------
// Misc features
//---------------------------------------------------------
//returns whether fast clipping is being used or not - needed to be exposed for better per-object clip behavior
bool UsingFastClipping();
int StencilBufferBits();
//---------------------------------------------------------
// Standard material and textures
//---------------------------------------------------------
void AllocateStandardTextures();
void ReleaseStandardTextures();
IMaterialInternal * GetDrawFlatMaterial() { return m_pDrawFlatMaterial; }
IMaterialInternal * GetBufferClearObeyStencil( int i ) { return m_pBufferClearObeyStencil[i]; }
IMaterialInternal * GetReloadZcullMaterial() { return m_pReloadZcullMaterial; }
IMaterialInternal * GetRenderTargetBlitMaterial() { return m_pRenderTargetBlitMaterial; }
ShaderAPITextureHandle_t GetFullbrightLightmapTextureHandle() const { return m_FullbrightLightmapTextureHandle; }
ShaderAPITextureHandle_t GetFullbrightBumpedLightmapTextureHandle() const { return m_FullbrightBumpedLightmapTextureHandle; }
ShaderAPITextureHandle_t GetBlackTextureHandle() const { return m_BlackTextureHandle; }
ShaderAPITextureHandle_t GetBlackAlphaZeroTextureHandle() const { return m_BlackAlphaZeroTextureHandle; }
ShaderAPITextureHandle_t GetFlatNormalTextureHandle() const { return m_FlatNormalTextureHandle; }
ShaderAPITextureHandle_t GetFlatSSBumpTextureHandle() const { return m_FlatSSBumpTextureHandle; }
ShaderAPITextureHandle_t GetGreyTextureHandle() const { return m_GreyTextureHandle; }
ShaderAPITextureHandle_t GetGreyAlphaZeroTextureHandle() const { return m_GreyAlphaZeroTextureHandle; }
ShaderAPITextureHandle_t GetWhiteTextureHandle() const { return m_WhiteTextureHandle; }
ShaderAPITextureHandle_t GetLinearToGammaTableTextureHandle() const { return m_LinearToGammaTableTextureHandle; }
ShaderAPITextureHandle_t GetLinearToGammaIdentityTableTextureHandle() const { return m_LinearToGammaIdentityTableTextureHandle; }
ShaderAPITextureHandle_t GetMaxDepthTextureHandle() const { return m_MaxDepthTextureHandle; }
//---------------------------------------------------------
// Material and texture management
//---------------------------------------------------------
void UncacheAllMaterials();
void UncacheUnusedMaterials( bool bRecomputeStateSnapshots );
void CacheUsedMaterials();
void ReloadTextures();
void ReloadMaterials( const char *pSubString = NULL );
// Create new materials
IMaterial * CreateMaterial( const char *pMaterialName, KeyValues *pVMTKeyValues );
IMaterial * FindMaterial( const char *materialName, const char *pTextureGroupName, bool complain = true, const char *pComplainPrefix = NULL );
virtual IMaterial * FindProceduralMaterial( const char *pMaterialName, const char *pTextureGroupName, KeyValues *pVMTKeyValues = NULL );
const char * GetForcedTextureLoadPathID() { return m_pForcedTextureLoadPathID; }
bool LoadKeyValuesFromVMTFile( KeyValues &vmtKeyValues, const char *pMaterialName, bool bUsesUNCFilename );
//---------------------------------
DELEGATE_TO_OBJECT_0C( MaterialHandle_t, FirstMaterial, &m_MaterialDict );
DELEGATE_TO_OBJECT_1C( MaterialHandle_t, NextMaterial, MaterialHandle_t, &m_MaterialDict );
DELEGATE_TO_OBJECT_0C( MaterialHandle_t, InvalidMaterial, &m_MaterialDict );
DELEGATE_TO_OBJECT_1C( IMaterial *, GetMaterial, MaterialHandle_t, &m_MaterialDict );
DELEGATE_TO_OBJECT_1C( IMaterialInternal *, GetMaterialInternal, MaterialHandle_t, &m_MaterialDict );
DELEGATE_TO_OBJECT_0C( int, GetNumMaterials, &m_MaterialDict );
DELEGATE_TO_OBJECT_1V( AddMaterialToMaterialList, IMaterialInternal *, &m_MaterialDict );
DELEGATE_TO_OBJECT_1V( RemoveMaterial, IMaterialInternal *, &m_MaterialDict );
DELEGATE_TO_OBJECT_1V( RemoveMaterialSubRect, IMaterialInternal *, &m_MaterialDict );
//---------------------------------
ITexture * FindTexture( const char* pTextureName, const char *pTextureGroupName, bool complain = true, int nAdditionalCreationFlags = 0 );
bool IsTextureLoaded( const char* pTextureName ) const;
bool GetTextureInformation( char const *szTextureName, MaterialTextureInfo_t &info ) const;
void AddTextureAlias( const char *pAlias, const char *pRealName );
void RemoveTextureAlias( const char *pAlias );
void SetExcludedTextures( const char *pScriptName, bool bUsingWeaponModelCache );
void UpdateExcludedTextures( void );
void ClearForceExcludes( void );
// Creates a procedural texture
ITexture * CreateProceduralTexture( const char *pTextureName,
const char *pTextureGroupName,
int w,
int h,
ImageFormat fmt,
int nFlags );
virtual ICustomMaterialManager *GetCustomMaterialManager();
virtual ICompositeTextureGenerator *GetCompositeTextureGenerator();
#if defined( _X360 )
// Create a texture for displaying gamerpics.
// This function allocates the texture in the correct gamerpic format, but it does not fill in the gamerpic data.
virtual ITexture * CreateGamerpicTexture( const char *pTextureName,
const char *pTextureGroupName,
int nFlags );
// Update the given texture with the player gamerpic for the local player at the given index.
// Note: this texture must be the correct size and format. Use CreateGamerpicTexture.
virtual bool UpdateLocalGamerpicTexture( ITexture *pTexture, DWORD userIndex );
// Update the given texture with a remote player's gamerpic.
// Note: this texture must be the correct size and format. Use CreateGamerpicTexture.
virtual bool UpdateRemoteGamerpicTexture( ITexture *pTexture, XUID xuid );
#endif // _X360
//
// Render targets
//
void BeginRenderTargetAllocation();
void EndRenderTargetAllocation(); // Simulate an Alt-Tab in here, which causes a release/restore of all resources
void FinishRenderTargetAllocation( void );
void ReEnableRenderTargetAllocation_IRealizeIfICallThisAllTexturesWillBeUnloadedAndLoadTimeWillSufferHorribly( void );
// Creates a texture for use as a render target
ITexture * CreateRenderTargetTexture( int w,
int h,
RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
ImageFormat format,
MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED );
ITexture * CreateNamedRenderTargetTextureEx( const char *pRTName, // Pass in NULL here for an unnamed render target.
int w,
int h,
RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
ImageFormat format,
MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
unsigned int textureFlags = TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
unsigned int renderTargetFlags = 0 );
ITexture * CreateNamedRenderTargetTexture( const char *pRTName,
int w,
int h,
RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
ImageFormat format,
MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
bool bClampTexCoords = true,
bool bAutoMipMap = false );
ITexture * CreateNamedRenderTargetTextureEx2( const char *pRTName, // Pass in NULL here for an unnamed render target.
int w,
int h,
RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
ImageFormat format,
MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
unsigned int textureFlags = TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
unsigned int renderTargetFlags = 0 );
ITexture * CreateNamedMultiRenderTargetTexture( const char *pRTName, // Pass in NULL here for an unnamed render target.
int w,
int h,
RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
ImageFormat format,
MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
unsigned int textureFlags = TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
unsigned int renderTargetFlags = 0 );
// -----------------------------------------------------------
bool OnDrawMesh( IMesh *pMesh, int firstIndex, int numIndices );
bool OnDrawMesh( IMesh *pMesh, CPrimList *pLists, int nLists );
bool OnDrawMeshModulated( IMesh *pMesh, const Vector4D &diffuseModulation, int firstIndex, int numIndices );
DELEGATE_TO_OBJECT_3( bool, OnSetFlexMesh, IMesh *, IMesh *, int, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_3( bool, OnSetColorMesh, IMesh *, IMesh *, int, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_2( bool, OnSetPrimitiveType, IMesh *, MaterialPrimitiveType_t, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_0V( SyncMatrices, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_1V( SyncMatrix, MaterialMatrixMode_t, GetRenderContextInternal() );
void OnThreadEvent( uint32 threadEvent );
DELEGATE_TO_OBJECT_1( ShaderAPITextureHandle_t, GetLightmapTexture, ShaderAPITextureHandle_t, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_1( ShaderAPITextureHandle_t, GetPaintmapTexture, ShaderAPITextureHandle_t, GetRenderContextInternal() );
// -----------------------------------------------------------
// Lightmaps delegates
// -----------------------------------------------------------
DELEGATE_TO_OBJECT_0V( BeginLightmapAllocation, &m_Lightmaps );
void EndLightmapAllocation()
{
GetLightmaps()->EndLightmapAllocation();
AllocateStandardTextures();
}
void CleanupLightmaps()
{
GetLightmaps()->CleanupLightmaps();
}
DELEGATE_TO_OBJECT_4( int, AllocateLightmap, int, int, LightmapOffset_t, IMaterial *, &m_Lightmaps );
DELEGATE_TO_OBJECT_1( int, AllocateWhiteLightmap, IMaterial *, &m_Lightmaps );
DELEGATE_TO_OBJECT_3( int, AllocateDynamicLightmap, LightmapOffset_t, int *, int, &m_Lightmaps );
void UpdateLightmap( int, LightmapOffset_t, LightmapOffset_t, float *, float *, float *, float * );
DELEGATE_TO_OBJECT_0( int, GetNumSortIDs, &m_Lightmaps );
DELEGATE_TO_OBJECT_1V( GetSortInfo, MaterialSystem_SortInfo_t *, &m_Lightmaps );
DELEGATE_TO_OBJECT_3VC( GetLightmapPageSize, int, int *, int *, &m_Lightmaps );
DELEGATE_TO_OBJECT_0V( ResetMaterialLightmapPageInfo, &m_Lightmaps );
DELEGATE_TO_OBJECT_0C( int, GetNumLightmapPages, &m_Lightmaps );
DELEGATE_TO_OBJECT_1C( int, GetLightmapWidth, int, &m_Lightmaps );
DELEGATE_TO_OBJECT_1C( int, GetLightmapHeight, int, &m_Lightmaps );
DELEGATE_TO_OBJECT_0V( BeginUpdateLightmaps, &m_Lightmaps );
DELEGATE_TO_OBJECT_0V( EndUpdateLightmaps, &m_Lightmaps );
// -----------------------------------------------------------
// Paint map delegates
// -----------------------------------------------------------
DELEGATE_TO_OBJECT_1( void, RegisterPaintmapDataManager, IPaintmapDataManager *, &m_Paintmaps );
DELEGATE_TO_OBJECT_0V( BeginUpdatePaintmaps, &m_Paintmaps );
DELEGATE_TO_OBJECT_0V( EndUpdatePaintmaps, &m_Paintmaps );
void UpdatePaintmap( int paintmap, BYTE* pPaintData, int numRects, Rect_t* pRects );
// -----------------------------------------------------------
// Stereo
// -----------------------------------------------------------
bool IsStereoSupported();
bool IsStereoActiveThisFrame() const;
void NVStereoUpdate();
bool m_bStereoBoolsInitialized;
bool m_bIsStereoSupported;
bool m_bIsStereoActiveThisFrame;
// -----------------------------------------------------------
// Render context delegates
// -----------------------------------------------------------
// IMaterialSystem
DELEGATE_TO_OBJECT_3V( ClearBuffers, bool, bool, bool, GetRenderContextInternal() );
// IMaterialSystemInternal
DELEGATE_TO_OBJECT_0( IMaterial *, GetCurrentMaterial, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_0( int, GetLightmapPage, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_0( ITexture *, GetLocalCubemap, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_1V( ForceDepthFuncEquals, bool, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_0( MaterialHeightClipMode_t, GetHeightClipMode, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_0C( bool, InFlashlightMode, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_0C( bool, IsRenderingPaint, GetRenderContextInternal() );
DELEGATE_TO_OBJECT_0C( bool, IsCascadedShadowMapping, GetRenderContextInternal() );
// IShaderUtil
DELEGATE_TO_OBJECT_3V( BindStandardTexture, Sampler_t, TextureBindFlags_t, StandardTextureId_t, &m_HardwareRenderContext );
DELEGATE_TO_OBJECT_1( ShaderAPITextureHandle_t, GetStandardTexture, StandardTextureId_t, &m_HardwareRenderContext );
DELEGATE_TO_OBJECT_2V( BindStandardVertexTexture, VertexTextureSampler_t, StandardTextureId_t, &m_HardwareRenderContext );
DELEGATE_TO_OBJECT_2V( GetLightmapDimensions, int *, int *, &m_HardwareRenderContext );
DELEGATE_TO_OBJECT_3V( GetStandardTextureDimensions, int *, int *, StandardTextureId_t, &m_HardwareRenderContext );
DELEGATE_TO_OBJECT_0( float, GetSubDHeight, &m_HardwareRenderContext );
DELEGATE_TO_OBJECT_0( MorphFormat_t, GetBoundMorphFormat, &m_HardwareRenderContext );
DELEGATE_TO_OBJECT_1( ITexture *, GetRenderTargetEx, int, &m_HardwareRenderContext );
DELEGATE_TO_OBJECT_7V( DrawClearBufferQuad, unsigned char, unsigned char, unsigned char, unsigned char, bool, bool, bool, &m_HardwareRenderContext );
#if defined( _PS3 )
DELEGATE_TO_OBJECT_0V( DrawReloadZcullQuad, &m_HardwareRenderContext );
#endif // _PS3
DELEGATE_TO_OBJECT_0C( int, MaxHWMorphBatchCount, g_pMorphMgr );
DELEGATE_TO_OBJECT_1V( GetCurrentColorCorrection, ShaderColorCorrectionInfo_t*, g_pColorCorrectionSystem );
virtual ShaderAPITextureHandle_t GetShaderAPITextureBindHandle( ITexture *pTexture, int nFrameVar, int nTextureChannel = 0 );
#if defined( _X360 )
void ListUsedMaterials();
HXUIFONT OpenTrueTypeFont( const char *pFontname, int tall, int style );
void CloseTrueTypeFont( HXUIFONT hFont );
bool GetTrueTypeFontMetrics( HXUIFONT hFont, wchar_t wchFirst, wchar_t wchLast, XUIFontMetrics *pFontMetrics, XUICharMetrics *pCharMetrics );
// Render a sequence of characters and extract the data into a buffer
// For each character, provide the width+height of the font texture subrect,
// an offset to apply when rendering the glyph, and an offset into a buffer to receive the RGBA data
bool GetTrueTypeGlyphs( HXUIFONT hFont, int numChars, wchar_t *pWch, int *pOffsetX, int *pOffsetY, int *pWidth, int *pHeight, unsigned char *pRGBA, int *pOffset );
void ReadBackBuffer( Rect_t *pSrcRect, Rect_t *pDstRect, unsigned char *pData, ImageFormat dstFormat, int nDstStride );
void PersistDisplay();
void *GetD3DDevice();
bool OwnGPUResources( bool bEnable );
#elif defined( _PS3 )
void ListUsedMaterials();
virtual HPS3FONT OpenTrueTypeFont( const char *pFontname, int tall, int style );
virtual void CloseTrueTypeFont( HPS3FONT hFont );
virtual bool GetTrueTypeFontMetrics( HPS3FONT hFont, int nFallbackTall, wchar_t wchFirst, wchar_t wchLast, CPS3FontMetrics *pFontMetrics, CPS3CharMetrics *pCharMetrics );
// Render a sequence of characters and extract the data into a buffer
// For each character, provide the width+height of the font texture subrect,
// an offset to apply when rendering the glyph, and an offset into a buffer to receive the RGBA data
virtual bool GetTrueTypeGlyphs( HPS3FONT hFont, int nFallbackTall, int numChars, wchar_t *pWch, int *pOffsetX, int *pOffsetY, int *pWidth, int *pHeight, unsigned char *pRGBA, int *pRGBAOffset );
virtual void TransmitScreenshotToVX();
virtual void CompactRsxLocalMemory( char const *szReason );
virtual void SetFlipPresentFrequency( int nNumVBlanks );
static void RunQMS(void* cmat, void* ptr)
{
((CMaterialSystem*)cmat)->ThreadExecuteQueuedContext((CMatQueuedRenderContext *)ptr);
}
#endif
virtual void SpinPresent( uint nFrames );
MaterialLock_t Lock();
void Unlock( MaterialLock_t );
CMatCallQueue * GetRenderCallQueue();
uint GetRenderThreadId() const { return m_nRenderThreadID; }
void UnbindMaterial( IMaterial *pMaterial );
virtual void CompactMemory();
// Get stats on GPU memory usage
virtual void GetGPUMemoryStats( GPUMemoryStats &stats );
bool IsLevelLoadingComplete() const;
void OnAsyncTextureDataComplete( AsyncTextureContext_t *pContext, void *pData, int nNumReadBytes, AsyncTextureLoadError_t loadError );
// -----------------------------------------------------------
private:
CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showmaterials", DebugPrintUsedMaterials, "Show materials.", 0 );
CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showmaterialsverbose", DebugPrintUsedMaterialsVerbose, "Show materials (verbose version).", 0 );
CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showtextures", DebugPrintUsedTextures, "Show used textures.", 0 );
CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_reloadallmaterials", ReloadAllMaterials, "Reloads all materials", FCVAR_CHEAT );
CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_reloadmaterial", ReloadMaterials, "Reloads a single material", FCVAR_CHEAT );
CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_reloadtextures", ReloadTextures, "Reloads all textures", FCVAR_CHEAT );
CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showaspectratioinfo", DebugPrintAspectRatioInfo, "Spew info about the hardware aspect ratio", FCVAR_DEVELOPMENTONLY );
#if defined( _X360 ) || defined(_PS3)
CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_material_list", ListUsedMaterials, "Show used textures.", 0 );
#endif
friend void* InstantiateMaterialSystemV76Interface();
friend CMaterialSystem *CMatLightmaps::GetMaterialSystem() const;
friend CMaterialSystem *CMatPaintmaps::GetMaterialSystem() const;
void ThreadExecuteQueuedContext( CMatQueuedRenderContext *pContext );
IThreadPool * CreateMatQueueThreadPool();
void DestroyMatQueueThreadPool();
#if defined( DX_TO_GL_ABSTRACTION ) && !defined( _GAMECONSOLE )
void DoStartupShaderPreloading( void );
#endif
void ServiceAsyncTextureLoads();
void ServiceEndFramePriorToNextContext();
// -----------------------------------------------------------
CMaterialDict m_MaterialDict;
CMatLightmaps m_Lightmaps;
CMatPaintmaps m_Paintmaps;
#if defined(_X360)
static IMatRenderContextInternal *CMaterialSystem::m_pRenderContexts[2];
#elif !defined(_PS3)
static CTHREADLOCALPTR(IMatRenderContextInternal) m_pRenderContext;
#endif
CMatRenderContext m_HardwareRenderContext;
CMatQueuedRenderContext m_QueuedRenderContexts[2];
int m_iCurQueuedContext;
MaterialThreadMode_t m_ThreadMode;
MaterialThreadMode_t m_IdealThreadMode;
int m_nServiceThread;
//---------------------------------
char * m_pShaderDLL;
CSysModule * m_ShaderHInst; // Used to dynamically load the shader DLL
CreateInterfaceFn m_ShaderAPIFactory;
int m_nAdapter;
int m_nAdapterFlags;
int m_nConfigurationFlags; // MATCONFIG_FLAGS_xxxx
ShaderDisplayMode_t m_nAdapterInfo;
//---------------------------------
IMaterialProxyFactory * m_pMaterialProxyFactory;
IClientMaterialSystem * m_pClientMaterialSystemInterface;
//---------------------------------
// Callback methods for releasing + restoring video memory
CUtlVector< MaterialBufferReleaseFunc_t > m_ReleaseFunc;
CUtlVector< MaterialBufferRestoreFunc_t > m_RestoreFunc;
CUtlVector< EndFrameCleanupFunc_t > m_EndFrameCleanupFunc;
class COnLevelShutdownFunc
{
public:
COnLevelShutdownFunc( OnLevelShutdownFunc_t func, void * pUserData )
:
m_Func(func),
m_pUserData(pUserData)
{
// Do nothing... Is there a CUtlPair class or something like that?
}
bool operator==(const COnLevelShutdownFunc & other) const
{
return ( (m_Func == other.m_Func) && (m_pUserData == other.m_pUserData) );
}
OnLevelShutdownFunc_t m_Func;
void * m_pUserData;
};
CUtlVector< COnLevelShutdownFunc > m_OnLevelShutdownFuncs;
CUtlVector< EndFramePriorToNextContextFunc_t > m_EndFramePriorToNextContextFunc;
//---------------------------------
bool m_bRequestedEditorMaterials;
bool m_bRequestedGBuffers;
//---------------------------------
// Store texids for various things
ShaderAPITextureHandle_t m_FullbrightLightmapTextureHandle;
ShaderAPITextureHandle_t m_FullbrightBumpedLightmapTextureHandle;
ShaderAPITextureHandle_t m_BlackTextureHandle;
ShaderAPITextureHandle_t m_BlackAlphaZeroTextureHandle;
ShaderAPITextureHandle_t m_FlatNormalTextureHandle;
ShaderAPITextureHandle_t m_FlatSSBumpTextureHandle;
ShaderAPITextureHandle_t m_GreyTextureHandle;
ShaderAPITextureHandle_t m_GreyAlphaZeroTextureHandle;
ShaderAPITextureHandle_t m_WhiteTextureHandle;
ShaderAPITextureHandle_t m_LinearToGammaTableTextureHandle; //linear to gamma srgb conversion lookup for the current hardware
ShaderAPITextureHandle_t m_LinearToGammaIdentityTableTextureHandle; //An identity lookup for when srgb writes are off
ShaderAPITextureHandle_t m_MaxDepthTextureHandle; //a 1x1 texture with maximum depth values.
// Have we allocated the standard lightmaps?
bool m_StandardTexturesAllocated;
// Do we need to restore mananged resources next time RestoreShaderObjects is called
bool m_bRestoreManangedResources;
// Deferred material reload ( so we don't call it when ALT-TABd
bool m_bDeferredMaterialReload;
char *m_pSubString; // allocated substring for deferred material reload
//---------------------------------
// Shared materials used for debugging....
//---------------------------------
enum BufferClearType_t //bClearColor + ( bClearAlpha << 1 ) + ( bClearDepth << 2 )
{
BUFFER_CLEAR_NONE,
BUFFER_CLEAR_COLOR,
BUFFER_CLEAR_ALPHA,
BUFFER_CLEAR_COLOR_AND_ALPHA,
BUFFER_CLEAR_DEPTH,
BUFFER_CLEAR_COLOR_AND_DEPTH,
BUFFER_CLEAR_ALPHA_AND_DEPTH,
BUFFER_CLEAR_COLOR_AND_ALPHA_AND_DEPTH,
BUFFER_CLEAR_TYPE_COUNT
};
IMaterialInternal * m_pBufferClearObeyStencil[BUFFER_CLEAR_TYPE_COUNT];
IMaterialInternal * m_pReloadZcullMaterial;
IMaterialInternal * m_pDrawFlatMaterial;
IMaterialInternal * m_pRenderTargetBlitMaterial;
IMaterialInternal * m_pBIKPreloadMaterial; // PORTAL2 - a dummy material which is used to ensure that the (~2 KB) bink shaders are always loaded
//---------------------------------
const char * m_pForcedTextureLoadPathID;
uint m_nRenderThreadID;
// nesting counter for render target allocation
int m_nAllocatingRenderTargets;
bool m_bDisableRenderTargetAllocationForever;
bool m_bInStubMode;
bool m_bGeneratedConfig;
bool m_bInFrame;
bool m_bForcedSingleThreaded;
bool m_bAllowQueuedRendering;
bool m_bThreadHasOwnership;
bool m_bLevelLoadingComplete;
CTSQueue< AsyncTextureLoad_t > m_QueuedAsyncTextureLoads;
AsyncTextureLoad_t m_AsyncTextureLoad;
AsyncTextureLoad_t * m_pActiveAsyncTextureLoad;
//---------------------------------
CCustomMaterialManager m_CustomMaterialManager;
CCompositeTextureGenerator m_CompositeTextureGenerator;
#ifdef DX_TO_GL_ABSTRACTION
uint m_ThreadOwnershipID;
#endif
#ifndef _PS3
CJob * m_pActiveAsyncJob;
#else
bool m_bQMSJobSubmitted;
#endif
CUtlVector<uint32> m_threadEvents;
IThreadPool * m_pMatQueueThreadPool;
#if defined(_PS3) // some PS3-specific font info (hey, it was either do this or have a pointer to a pimpl struct)
CUtlVector< HPS3FONT > m_vExtantFonts; // used to catch leaks -- can't store a vector of the CellFonts directly bc the handle is a pointer and can't store pointers into a vector
void InitializePS3Fonts();
enum { kPS3_DEFAULT_MAX_USER_FONTS = 256 };
public:
virtual bool PS3InitFontLibrary( unsigned fontFileCacheSizeInBytes, unsigned maxNumFonts );
virtual void PS3DumpFontLibrary();
virtual void *PS3GetFontLibPtr();
protected:
#else
inline void InitializePS3Fonts(){};
#endif
};
//-----------------------------------------------------------------------------
inline CMaterialSystem *CMatLightmaps::GetMaterialSystem() const
{
return GET_OUTER( CMaterialSystem, m_Lightmaps );
}
inline CMaterialSystem *CMatPaintmaps::GetMaterialSystem() const
{
return GET_OUTER( CMaterialSystem, m_Paintmaps );
}
//-----------------------------------------------------------------------------
#endif // CMATERIALSYSTEM_H
+799
View File
@@ -0,0 +1,799 @@
//===== Copyright (c) Valve Corporation, All rights reserved. ======//
//
// Purpose: PS3-specific font code that for historical reasons is hidden
// in the materialsystem.
//
//==================================================================//
#include "pch_materialsystem.h"
#ifndef _PS3
#define MATSYS_INTERNAL
#endif
#include "cmaterialsystem.h"
#include "colorspace.h"
#include "materialsystem/materialsystem_config.h"
#include "materialsystem/imaterialproxyfactory.h"
#include "IHardwareConfigInternal.h"
#include "shadersystem.h"
#include "texturemanager.h"
#include "shaderlib/ShaderDLL.h"
#include "tier1/callqueue.h"
#include "vstdlib/jobthread.h"
#include "cmatnullrendercontext.h"
#include "datacache/iresourceaccesscontrol.h"
#include "filesystem/IQueuedLoader.h"
#include "filesystem/IXboxInstaller.h"
#include "cdll_int.h"
#include <cell/sysmodule.h>
#include <cell/font.h>
#include <cell/fontft.h>
#include "../common/vgui_surfacelib/vguifont.h"
#ifdef _PS3
#include "ps3_pathinfo.h"
#endif
// NOTE: This must be the last file included!!!
#include "tier0/memdbgon.h"
static const CellFontLibrary *Fontlib();
// in case I make HPS3FONT something other than just a pointer
static inline CellFont *CellFontFromHandle( HPS3FONT &h )
{
return (CellFont *)h;
}
wchar_t g_wchFallbackGlyph = L'_';
static inline bool ShouldFallBackToSystemFontForWChar( wchar_t wch, int &nFontTallAdjustment )
{
if ( ( wch == 0x00AE /*(R)*/ ) || ( wch == 0x2122 /*(TM)*/ ) )
{
nFontTallAdjustment = 1;
return true;
}
return false;
}
#define TEXTURE_PAGE_HEIGHT 128 // copied from FontTextureCache.cpp, which for some reason hardcodes this. because there's multiple implementations
// of the font cache strewn throughout various libraries all linked into the vgui dll, I didn't feel safe changing
// it to just use larger textures.
class CFallbackFont: public CellFont
{
protected:
int m_nInitError;
int m_nTall;
CellFontHorizontalLayout m_hlayout;
public:
CFallbackFont(): m_nInitError(-1), m_nTall( -1 )
{
}
void Init()
{
if( m_nInitError == CELL_OK )
{
// already initialized
return ;
}
CellFontType fontType;
fontType.type = CELL_FONT_TYPE_GOTHIC_JAPANESE_CJK_LATIN_SET;
fontType.map = CELL_FONT_MAP_UNICODE;
m_nInitError = cellFontOpenFontset( Fontlib(), &fontType, this );
if( m_nInitError == CELL_OK )
{
Warning("Cannot open fallback font, error 0x%X\n", m_nInitError );
}
}
CellFontHorizontalLayout *GetHorizontalLayout()
{
return &m_hlayout;
}
int SetTall( int nTall )
{
if( m_nInitError != CELL_OK )
{
return m_nInitError;
}
if( nTall == m_nTall )
{
return CELL_OK;
}
float pointSize = nTall * 0.79f;
cellFontSetScalePixel( this, pointSize, pointSize );
// sometimes we ask for bigger fonts than the packer can handle. Also, because of accents etc, the font may poke out of the requested tall value.
// The packer is for some reason hardcoded to a maximum height of 128.
cellFontGetHorizontalLayout( this, &m_hlayout );
if ( m_hlayout.lineHeight + m_hlayout.effectHeight > TEXTURE_PAGE_HEIGHT )
{
Warning("FAILSAFE: Fallback Font at '%d' tall is actually %d pixels high, but max texture page is %d. Shrinking to ",
nTall, (int)(m_hlayout.lineHeight + m_hlayout.effectHeight), TEXTURE_PAGE_HEIGHT );
do
{
pointSize *= 0.9;
cellFontSetScalePixel( this, nTall, nTall );
cellFontGetHorizontalLayout( this, &m_hlayout );
}
while ( ( m_hlayout.lineHeight + m_hlayout.effectHeight > TEXTURE_PAGE_HEIGHT ) && ( pointSize >= 1 ) );
Warning( "%.2f\n", pointSize );
}
m_nTall = nTall;
return CELL_OK;
}
void Shutdown()
{
if( m_nInitError == CELL_OK )
{
int nError = cellFontCloseFont( this );
if( nError != CELL_OK )
{
Warning("Cannot close fallback font, error 0x%X\n", nError );
}
}
}
};
CFallbackFont g_fallbackFont;
void CMaterialSystem::InitializePS3Fonts()
{
m_vExtantFonts.EnsureCapacity(8);
}
class CTempFontHandle
{
public:
CMaterialSystem * m_pMaterialSystem;
MaterialLock_t m_hLock;
CellFont * m_pNewFont;
public:
CTempFontHandle( CMaterialSystem * pMaterialSystem):
m_pMaterialSystem( pMaterialSystem )
{
m_hLock = pMaterialSystem->Lock();
m_pNewFont = new CellFont;
}
CellFont* DetachFont()
{
CellFont * pFont = m_pNewFont;
m_pNewFont = NULL;
return pFont;
}
~CTempFontHandle()
{
if( m_pNewFont )
{
delete m_pNewFont;
}
m_pMaterialSystem->Unlock( m_hLock );
}
};
HPS3FONT CMaterialSystem::OpenTrueTypeFont( const char *pFontname, int tall, int style )
{
CTempFontHandle hTemp( this );
static int sUniquePositiveNumber = 0;
// need absolute disk path, look in resource then platform
char fontpath[MAX_PATH] = {0};
struct fontTable_t
{
const char *pFontName;
const char *pPath;
bool m_bRestrictiveLoadIntoMemory;
bool m_bAlwaysLoadIntoMemory;
};
int nCellError;
if( !V_stricmp( pFontname, "system" ) )
{
CellFontType fontType;
fontType.type = CELL_FONT_TYPE_GOTHIC_JAPANESE_CJK_LATIN_SET;
fontType.map = CELL_FONT_MAP_UNICODE;
nCellError = cellFontOpenFontset( Fontlib(), &fontType, hTemp.m_pNewFont );
}
else if( !V_stricmp( pFontname, "japanese cjk latin" ) )
{
CellFontType fontType;
fontType.type = CELL_FONT_TYPE_GOTHIC_JAPANESE_CJK_LATIN_SET;
fontType.map = CELL_FONT_MAP_UNICODE;
nCellError = cellFontOpenFontset( Fontlib(), &fontType, hTemp.m_pNewFont );
}
else
{
// explicit mapping required, dvd searching too expensive
static fontTable_t fontToFilename[] =
{
#include "shaderapidx9/fontremaptable.h"
};
// remap typeface to diskname
char const *pDiskname = NULL;
for ( int i=0; i<ARRAYSIZE( fontToFilename ); i++ )
{
if ( !V_stricmp( pFontname, fontToFilename[i].pFontName ) )
{
pDiskname = fontToFilename[i].pPath;
break;
}
}
if ( !pDiskname )
{
// not found
DevWarning( "PS3: True Type Font: '%s' unknown.\n", pFontname );
}
else
{
Q_snprintf( fontpath, ARRAYSIZE( fontpath ), "%s/%s", g_pPS3PathInfo->GameImagePath(), pDiskname );
}
// if we failed to find the font, substitute a system font
if ( fontpath[0] == 0 )
{
CellFontType fontType;
fontType.type = CELL_FONT_TYPE_GOTHIC_JAPANESE_CJK_LATIN_SET;
fontType.map = CELL_FONT_MAP_UNICODE;
nCellError = cellFontOpenFontset( Fontlib(), &fontType, hTemp.m_pNewFont );
}
else
{
nCellError = cellFontOpenFontFile(
Fontlib(),
reinterpret_cast<uint8_t *>(fontpath),
0,
++sUniquePositiveNumber,
hTemp.m_pNewFont );
}
}
CellFont *pNewFont = NULL;
if ( nCellError != CELL_FONT_OK )
{
Warning( "could not open font '%s': %x\n", pFontname, nCellError );
return false;
}
else
{
pNewFont = hTemp.DetachFont(); // do not release the font structure
m_vExtantFonts.AddToTail( pNewFont );
}
float pointSize = tall * 0.79f;
cellFontSetScalePixel( pNewFont, pointSize, pointSize );
// sometimes we ask for bigger fonts than the packer can handle. Also, because of accents etc, the font may poke out of the requested tall value.
// The packer is for some reason hardcoded to a maximum height of 128.
CellFontHorizontalLayout hlayout;
cellFontGetHorizontalLayout( pNewFont, &hlayout );
if ( hlayout.lineHeight + hlayout.effectHeight > TEXTURE_PAGE_HEIGHT )
{
Warning("FAILSAFE: %s at '%d' tall is actually %d pixels high, but max texture page is %d. Shrinking to ",
pFontname, tall, (int)(hlayout.lineHeight + hlayout.effectHeight), TEXTURE_PAGE_HEIGHT );
do
{
pointSize *= 0.9;
cellFontSetScalePixel( pNewFont, tall, tall );
cellFontGetHorizontalLayout( pNewFont, &hlayout );
}
while ( ( hlayout.lineHeight + hlayout.effectHeight > TEXTURE_PAGE_HEIGHT ) && (pointSize >= 1) );
Warning( "%.2f\n", pointSize );
}
/*
nCellError = cellFontGetHorizontalLayout( &m_sFont, &m_HorizontalLayout );
AssertMsg2( nCellError == CELL_OK, "Could not get horizontal layout for font %s (%x)\n", m_szName.String(), nCellError );
*/
/*
nCellError = cellFontGetVerticalLayout( &m_sFont, &m_VerticalLayout );
AssertMsg2( nCellError == CELL_OK, "Could not get vertical layout for font %s (%x)\n", m_szName.String(), nCellError );
*/
return pNewFont;
}
void CMaterialSystem::CloseTrueTypeFont( HPS3FONT hFont )
{
MaterialLock_t hLock = Lock();
// find the font in the vector
CellFont *pFont = CellFontFromHandle( hFont );
cellFontCloseFont( pFont );
if ( m_vExtantFonts.FindAndFastRemove( pFont ) )
{
delete pFont;
}
else
{
AssertMsg1( false, "Tried to remove a font %x which wasn't in the material system's library\n", hFont );
}
Unlock( hLock );
}
bool CMaterialSystem::GetTrueTypeFontMetrics( HPS3FONT hFont, int nFallbackTall, wchar_t wchFirst, wchar_t wchLast, CPS3FontMetrics * RESTRICT pFontMetrics, CPS3CharMetrics * RESTRICT pCharMetrics )
{
MaterialLock_t hLock = Lock();
int numChars = wchLast - wchFirst + 1;
V_memset( pCharMetrics, 0, numChars * sizeof( CPS3CharMetrics ) );
CellFont * RESTRICT pFont = CellFontFromHandle( hFont );
int nCellError = cellFontGetHorizontalLayout( pFont, pFontMetrics );
AssertMsg1( nCellError == CELL_OK, "Could not get horizontal layout for font (%x)\n", nCellError );
// we will still need to go and fill in the max width once we've got the data for all the characters
float fMaxWidth = 0;
for ( int i = 0; i < numChars; i++ )
{
int nMetricsError = CELL_FONT_ERROR_FATAL;
int nFallbackFontTallAdjustment = 0;
if ( !ShouldFallBackToSystemFontForWChar( wchFirst + i, nFallbackFontTallAdjustment ) )
{
nMetricsError = cellFontGetCharGlyphMetrics( pFont, wchFirst + i, pCharMetrics + i );
}
if( nMetricsError != CELL_OK )
{
// try the fallback font
int nFallbackError = g_fallbackFont.SetTall( nFallbackTall + nFallbackFontTallAdjustment );
if( nFallbackError == CELL_OK )
{
nMetricsError = cellFontGetCharGlyphMetrics( &g_fallbackFont, wchFirst + i, pCharMetrics + i );
}
}
if( nMetricsError != CELL_OK )
{
nMetricsError = cellFontGetCharGlyphMetrics( pFont, g_wchFallbackGlyph, pCharMetrics + i );
}
if ( nMetricsError == CELL_OK )
{
fMaxWidth = fmax( fMaxWidth, pCharMetrics[i].Horizontal.advance + 1 );
}
else
{
memset( pCharMetrics+i, 0, sizeof(*pCharMetrics) );
}
}
pFontMetrics->fMaxWidth = fMaxWidth;
Unlock( hLock );
return nCellError == CELL_OK;
}
// encapsulates the ps3 fontlib renderer class with a RAII interface
// so it binds/unbinds automatically
class CFontRendererRAII
{
public:
CFontRendererRAII( CellFont *pBoundFont );
~CFontRendererRAII();
bool IsValid() { return m_nInitSuccess == CELL_FONT_OK; }
protected:
CellFontRenderer m_Renderer;
CellFont *m_pFont;
int m_nInitSuccess;
};
CFontRendererRAII::CFontRendererRAII( CellFont *pBoundFont ) : m_pFont(NULL)
{
CellFontRendererConfig config;
CellFontRendererConfig_initialize( &config );
// proper setup here
m_nInitSuccess = cellFontCreateRenderer( Fontlib(), &config, &m_Renderer );
if ( m_nInitSuccess != CELL_FONT_OK )
{
return ; // we have failed. we are failures. the stench of failure hangs upon us.
}
// connect the renderer to the font
m_nInitSuccess = cellFontBindRenderer( pBoundFont, &m_Renderer );
if ( m_nInitSuccess != CELL_FONT_OK )
{
return ; // we have failed. we are failures. the stench of failure hangs upon us.
}
m_pFont = pBoundFont;
}
CFontRendererRAII::~CFontRendererRAII()
{
if ( m_pFont )
{
cellFontUnbindRenderer( m_pFont );
}
cellFontDestroyRenderer( &m_Renderer );
}
// OPTIMIZATION OPPORTUNITY:
// This can be made to run on the RSX instead of the PPU, if necessary.
bool CMaterialSystem::GetTrueTypeGlyphs( HPS3FONT hFont, int nFallbackTall, int numChars, wchar_t *pWch, int *pOffsetX, int *pOffsetY, int * RESTRICT pWidth, int * RESTRICT pHeight, unsigned char *pRGBA, int *pRGBAOffset )
{
VPROF( "CMaterialSystem::GetTrueTypeGlyphs" );
MaterialLock_t hLock = Lock();
// Figure out the size of surface/texture we need to allocate
int rtWidth = 0;
int rtHeight = 0;
for ( int i = 0; i < numChars; i++ )
{
//rtWidth += pWidth[i];
rtWidth = MAX( rtWidth, pWidth[i] );
rtHeight = MAX( rtHeight, pHeight[i] );
}
/*
// per resolve() restrictions
rtWidth = AlignValue( rtWidth, 32 );
rtHeight = AlignValue( rtHeight, 32 );
*/
if ( rtWidth == 0 || rtHeight == 0 )
{
AssertMsg2( false, "Tried to draw a %dx%d glyph! What are you trying to pull?!\n", rtWidth, rtHeight );
Unlock( hLock );
return false;
}
CellFont *pFont = CellFontFromHandle( hFont );
CFontRendererRAII renderer( pFont ), *pFallbackRenderer = NULL;
CellFontRenderSurface surface;
CellFontGlyphMetrics metrics;
CellFontImageTransInfo transInfo;
CellFontHorizontalLayout hlayoutSlowWeShouldMoveThisIntoTheFontClass;
cellFontRenderSurfaceInit( &surface, NULL, rtWidth, 1, rtWidth, rtHeight ); // the surface doesn't actually use the memory pointer (go figure)
cellFontRenderSurfaceSetScissor( &surface, 0, 0, rtWidth, rtHeight );
cellFontGetHorizontalLayout( pFont, &hlayoutSlowWeShouldMoveThisIntoTheFontClass );
const int baselineY = floor(hlayoutSlowWeShouldMoveThisIntoTheFontClass.baseLineY);
// struct XUIRect { int x, int y, int w, int h };
// Draw the characters, stepping across the texture
// int xCursor = 0;
unsigned int successfulWrites = 0;
for ( int i = 0; i < numChars; i++)
{
/*
// FIXME: the drawRect params don't make much sense (should use "(xCursor+pWidth[i]), pHeight[i]", but then some characters disappear!)
XUIRect drawRect = XUIRect( xCursor + pOffsetX[i], pOffsetY[i], rtWidth, rtHeight );
cellFontRenderSurfaceSetScissor( &surface, drawRect.x, drawRect.y, drawRect.w, drawRect.h );
wchar_t text[2] = { pWch[i], 0 };
XuiDrawText( m_hDC, text, XUI_FONT_STYLE_NORMAL|XUI_FONT_STYLE_SINGLE_LINE|XUI_FONT_STYLE_NO_WORDWRAP, 0, &drawRect );
xCursor += pWidth[i];
*/
// draw one glyph to the surface
int ps3suc = CELL_FONT_ERROR_FATAL;
int nFallbackFontTallAdjustment = 0;
if ( !ShouldFallBackToSystemFontForWChar( pWch[i], nFallbackFontTallAdjustment ) )
{
ps3suc = cellFontRenderCharGlyphImage( pFont, pWch[i], &surface, 0, 0, &metrics, &transInfo );
}
if ( ps3suc != CELL_OK )
{
if( CELL_OK == g_fallbackFont.SetTall( nFallbackTall + nFallbackFontTallAdjustment ) )
{
if( !pFallbackRenderer )
pFallbackRenderer = new CFontRendererRAII( &g_fallbackFont );
ps3suc = cellFontRenderCharGlyphImage( &g_fallbackFont, pWch[i], &surface, 0, 0, &metrics, &transInfo );
}
}
if( ps3suc != CELL_OK )
{
ps3suc = cellFontRenderCharGlyphImage( pFont, g_wchFallbackGlyph, &surface, 0, 0, &metrics, &transInfo );
}
if ( ps3suc == CELL_OK )
{
// blit the glyph to the bitmap
const int ibw = transInfo.imageWidthByte;
const int iBearingY = ceilf(metrics.Horizontal.bearingY); // start the conversion early to avoid a LHS
int destPitch = pWidth[i]*4; // distance between one row and the next IN BYTES
unsigned char *pLinear = pRGBA + pRGBAOffset[i];
// Clear out all pixels to black, since the source glyph size may not match the destination buffer size perfectly
memset( pLinear, 0, pHeight[i] * destPitch );
if ( transInfo.imageHeight==0 || transInfo.imageWidth==0 )
{
// this can happen for space or control characters
// just blank out the destination box
continue; // bail out and go to next character !
}
// work out the size of the region to copy -- which is the smaller of the source or destination buffer.
// in theory these two should be identical, but the PS3 OS tends to overallocate space slightly
// in its render surface, and sometimes the VGUI font code is expecting a blank column of pixels
// where the PS3 generates none.
// also we'll try to align the font glyph to the bottom of the destination rect, rather than
// the top.
int numLeftPadPixels = ( int )floorf( metrics.Horizontal.bearingX );
numLeftPadPixels = MAX( 0, numLeftPadPixels );
int iteratorMaxColumn = MIN( pWidth[i] - numLeftPadPixels, transInfo.imageWidth );
int iteratorMaxRow = MIN( pHeight[i], transInfo.imageHeight );
unsigned char *pLinearAligned = pLinear; // work out where to start writing into the image so that chars are aligned to bottom of rect
pLinearAligned = pLinear + MAX(0, baselineY-iBearingY)*destPitch;
// for ( int row = 0 ; row < transInfo.imageHeight ; ++row )
for ( int row = 0 ; row < iteratorMaxRow; ++row )
{
uint32 * pRowStart = reinterpret_cast<uint32 *>(pLinearAligned + (row*destPitch)); // we will write the RGBA one word at a time
for ( int col = 0 ; col < iteratorMaxColumn; ++col )
{
// white characters; only the alpha mask is copied from the rendered glyph
// exception: totally absent regions are marked as just black
uint8 a = transInfo.Image[ row * ibw + col ];
*(pRowStart + col + numLeftPadPixels) = a ? 0xFFFFFF00 | a : 0 ;
}
}
#if 0
if ( FILE *f = fopen( "/app_home/dbgfonts.txt", "a+" ) )
{
fprintf( f, "% 4d %C [%dx%d]\n",
pWch[i], pWch[i],
transInfo.imageWidth, transInfo.imageHeight
);
fprintf( f, " [%d]\n",
pWidth[i]
);
fprintf( f, " %0.5f %0.5f %0.5f\n",
metrics.Horizontal.bearingX, metrics.width, metrics.Horizontal.advance
);
for ( int row = 0; row < MAX( MAX( pHeight[i], ceilf( metrics.height ) ), transInfo.imageHeight ); ++ row )
{
for ( int col = 0; col < MAX( pWidth[i], ceilf( metrics.Horizontal.advance ) ); ++ col )
{
uint8 a = transInfo.Image[ row * ibw + col ];
fprintf( f, a ? ( (a>0x20) ? "X" : "*" ) : " " );
}
fprintf( f, "|\n" );
}
fprintf( f, "-----------------------------\n" );
fclose(f);
}
#endif
#if 0 // draw a line around the outer border for debugging
for ( int row = 0 ; row < pHeight[i]; ++row )
{
*(reinterpret_cast<uint32 *>(pLinear + (row*destPitch))+0) = 0xFFFFFFFF;
*(reinterpret_cast<uint32 *>(pLinear + (row*destPitch))+pWidth[i]-1) = 0xFFFFFFFF;
}
// top and bottom row
memset( pLinear, 0xFF, pWidth[i] * 4 );
memset( (pLinear + ((pHeight[i]-1)*destPitch)), 0xFF, pWidth[i] * 4 );
#endif
successfulWrites++;
}
else
{
AssertMsg2( false, "Couldn't draw u'%x', err %x\n", (unsigned int) *(pWch+i), ps3suc );
}
}
if( pFallbackRenderer )
delete pFallbackRenderer;
Unlock( hLock );
return successfulWrites > 0;
}
static int load_libfont_module()
{
int ret;
ret = cellSysmoduleLoadModule( CELL_SYSMODULE_FONT );
if ( ret == CELL_OK ) {
ret = cellSysmoduleLoadModule( CELL_SYSMODULE_FREETYPE_TT );
if ( ret == CELL_OK ) {
ret = cellSysmoduleLoadModule( CELL_SYSMODULE_FONTFT );
if ( ret == CELL_OK ) {
return CELL_OK; // Success
}
// Error handling as follows (Unload all loads)
cellSysmoduleUnloadModule( CELL_SYSMODULE_FREETYPE_TT );
}
cellSysmoduleUnloadModule( CELL_SYSMODULE_FONT );
}
return ret; // Error end
}
static void* fonts_malloc( void*obj, uint32_t size )
{
(void)obj;
return malloc( size );
}
static void fonts_free( void*obj, void*p )
{
(void)obj;
free( p );
}
static void* fonts_realloc( void*obj, void* p, uint32_t size )
{
(void)obj;
return realloc( p, size );
}
static void* fonts_calloc( void*obj, uint32_t numb, uint32_t blockSize )
{
(void)obj;
return calloc( numb, blockSize );
}
static int s_FontLibraryRefCount = 0;
static uint32 *s_FontFileCache = NULL;
static const CellFontLibrary *s_FontLibrary = NULL;
static CellFontEntry *s_UserFontEntries = NULL;
bool CMaterialSystem::PS3InitFontLibrary( unsigned fontFileCacheSizeInBytes, unsigned maxNumFonts )
{
if ( s_FontLibraryRefCount > 0 )
{
// don't need to load the font library, just add one to refcount
++s_FontLibraryRefCount;
return true;
}
else if ( s_FontLibraryRefCount < 0 )
{
Error( "Font library refcount is %d!\n", s_FontLibraryRefCount );
}
else
{
++s_FontLibraryRefCount;
}
VPROF("CMaterialSystem::PS3InitFontLibrary");
if ( s_FontFileCache )
{
Warning("Tried to init font library twice without intervening unload\n");
return false;
}
int ret;
if ( (ret=load_libfont_module()) != CELL_OK )
{
Warning("Could not load font library: %x\n", ret);
}
maxNumFonts = maxNumFonts ? maxNumFonts : 1;
if (s_FontFileCache)
{
Assert(false); // wasn't cleaned up?!
delete[] s_FontFileCache;
}
if (s_UserFontEntries)
{
Assert(false); // wasn't cleaned up?!
delete[] s_UserFontEntries;
}
s_FontFileCache = new uint32[fontFileCacheSizeInBytes >> 2];
s_UserFontEntries = new CellFontEntry[maxNumFonts];
CellFontConfig config;
config.FileCache.buffer = s_FontFileCache;
config.FileCache.size = fontFileCacheSizeInBytes;
config.userFontEntrys = s_UserFontEntries;
config.userFontEntryMax = maxNumFonts;
ret = cellFontInit(&config);
if ( ret == CELL_OK )
{
// can override malloc/free here:
CellFontLibraryConfigFT ftConfig;
CellFontLibraryConfigFT_initialize( &ftConfig );
ftConfig.MemoryIF.Object = NULL;
ftConfig.MemoryIF.Malloc = fonts_malloc;
ftConfig.MemoryIF.Free = fonts_free;
ftConfig.MemoryIF.Realloc = fonts_realloc;
ftConfig.MemoryIF.Calloc = fonts_calloc;
ret = cellFontInitLibraryFreeType( &ftConfig, &s_FontLibrary );
if ( ret == CELL_OK )
{
g_fallbackFont.Init( );
return true;
}
else
{
Warning( "cellFontInitLibraryFreeType failed, %x\n", ret );
return false;
}
}
else
{
Warning( "CellFontInit failed, %x\n", ret );
return false;
}
}
void *CMaterialSystem::PS3GetFontLibPtr()
{
return (void*)s_FontLibrary;
}
void CMaterialSystem::PS3DumpFontLibrary()
{
if ( s_FontLibraryRefCount <= 0 )
{
Warning("Font library refcount is %d during unload!\n", s_FontLibraryRefCount);
return;
}
else if ( s_FontLibrary == NULL )
{
Warning("\t!!!FAILSAFE!!!\nPS3 font library refcount %d but was somehow unloaded!\n", s_FontLibraryRefCount);
s_FontLibraryRefCount = 0;
}
else if ( --s_FontLibraryRefCount > 0 )
{ // refcount is still greater than one, don't need to unload
return;
}
// Warning( "Font library was dumped with %d fonts left open.\n", m_vExtantFonts.Count() );
if ( s_FontLibrary )
{
g_fallbackFont.Shutdown();
cellFontEndLibrary( s_FontLibrary );
cellFontEnd();
delete[] s_FontFileCache;
s_FontFileCache = NULL;
// handled by cellFontEndLibrary: // delete s_FontLibrary;
s_FontLibrary = NULL;
delete[] s_UserFontEntries;
s_UserFontEntries = NULL;
cellSysmoduleUnloadModule( CELL_SYSMODULE_FONTFT );
cellSysmoduleUnloadModule( CELL_SYSMODULE_FREETYPE_TT );
cellSysmoduleUnloadModule( CELL_SYSMODULE_FONT );
}
}
static const CellFontLibrary *Fontlib()
{
return s_FontLibrary;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+199
View File
@@ -0,0 +1,199 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#ifndef CMATERIALLIGHTMAPS_H
#define CMATERIALLIGHTMAPS_H
#include "tier1/utlvector.h"
#include "imagepacker.h"
#ifndef MATSYS_INTERNAL
#error "This file is private to the implementation of IMaterialSystem/IMaterialSystemInternal"
#endif
#if defined( _WIN32 )
#pragma once
#endif
//-----------------------------------------------------------------------------
class CMaterialSystem;
class IMatRenderContextInternal;
class CMaterialDict;
class IMaterial;
class IMaterialInternal;
class FloatBitMap_t;
typedef intp ShaderAPITextureHandle_t;
struct MaterialSystem_SortInfo_t;
typedef unsigned short MaterialHandle_t;
//-----------------------------------------------------------------------------
// Manager of material system lightmaps
//-----------------------------------------------------------------------------
const int COUNT_DYNAMIC_LIGHTMAP_PAGES = 1;
class CMatLightmaps
{
public:
CMatLightmaps();
void Shutdown( );
//------------------------------------------------------------
// Methods exposed in IMaterialSystem
//------------------------------------------------------------
void BeginLightmapAllocation( void );
void EndLightmapAllocation( void );
int AllocateLightmap( int width, int height,
int offsetIntoLightmapPage[2],
IMaterial *pMaterial );
int AllocateWhiteLightmap( IMaterial *pMaterial );
// NOTE: This returns a lightmap page ID, not a sortID like AllocateLightmap!!!!
int AllocateDynamicLightmap( int lightmapSize[2], int *pOutOffsetIntoPage, int frameID );
int GetNumSortIDs( void );
void GetSortInfo( MaterialSystem_SortInfo_t *sortInfoArray );
void UpdateLightmap( int lightmapPageID, int lightmapSize[2],
int offsetIntoLightmapPage[2],
float *pFloatImage, float *pFloatImageBump1,
float *pFloatImageBump2, float *pFloatImageBump3 );
void GetLightmapPageSize( int lightmapPageID, int *width, int *height ) const;
void ResetMaterialLightmapPageInfo( void );
//------------------------------------------------------------
// Methods exposed in IMaterialSystemInternal
//------------------------------------------------------------
int GetLightmapWidth( int lightmap ) const;
int GetLightmapHeight( int lightmap ) const;
//------------------------------------------------------------
// Methods used by other material system components
//------------------------------------------------------------
// Releases/restores lightmap pages
void ReleaseLightmapPages();
void RestoreLightmapPages();
void EnableLightmapFiltering( bool enabled );
int GetNumLightmapPages() const { return m_NumLightmapPages;}
ShaderAPITextureHandle_t GetLightmapPageTextureHandle( int lightmap ) { return m_LightmapPageTextureHandles[lightmap]; }
bool IsDynamicLightmap( int lightmap ) const { return (lightmap >= m_firstDynamicLightmap ) ? true : false; }
CMaterialSystem *GetMaterialSystem() const;
void BeginUpdateLightmaps();
void EndUpdateLightmaps();
void CleanupLightmaps();
private:
// Gets the maximum lightmap page size...
int GetMaxLightmapPageWidth() const;
int GetMaxLightmapPageHeight() const;
// Allocate lightmap textures in D3D
void AllocateLightmapTexture( int lightmap );
// Initializes lightmap bits
void InitLightmapBits( int lightmap );
// assumes m_LightmapPixelWriter is already set up - results written there
void BumpedLightmapBitsToPixelWriter_LDR( float* pFloatImage, float *pFloatImageBump1, float *pFloatImageBump2,
float *pFloatImageBump3, int pLightmapSize[2], int pOffsetIntoLightmapPage[2], FloatBitMap_t *pfmOut );
void BumpedLightmapBitsToPixelWriter_HDRF( float* pFloatImage, float *pFloatImageBump1, float *pFloatImageBump2,
float *pFloatImageBump3, int pLightmapSize[2], int pOffsetIntoLightmapPage[2], FloatBitMap_t *pfmOut );
void BumpedLightmapBitsToPixelWriter_HDRI( float* pFloatImage, float *pFloatImageBump1, float *pFloatImageBump2,
float *pFloatImageBump3, int pLightmapSize[2], int pOffsetIntoLightmapPage[2], FloatBitMap_t *pfmOut ) RESTRICT;
void LightmapBitsToPixelWriter_LDR( float* pFloatImage, int pLightmapSize[2], int pOffsetIntoLightmapPage[2], FloatBitMap_t *pfmOut );
void LightmapBitsToPixelWriter_HDRF( float* pFloatImage, int pLightmapSize[2], int pOffsetIntoLightmapPage[2], FloatBitMap_t *pfmOut );
void LightmapBitsToPixelWriter_HDRI( float* pFloatImage, int pLightmapSize[2], int pOffsetIntoLightmapPage[2], FloatBitMap_t *pfmOut );
// For computing sort info
void ComputeSortInfo( MaterialSystem_SortInfo_t* pInfo, int& sortId, bool alpha );
void ComputeWhiteLightmappedSortInfo( MaterialSystem_SortInfo_t* pInfo, int& sortId, bool alpha );
void EnumerateMaterials( void );
// Lock a lightmap for update.
bool LockLightmap( int lightmap );
//------------------------------------------------------------
// Accessor helpers
//------------------------------------------------------------
IMaterialInternal* GetCurrentMaterialInternal() const;
void SetCurrentMaterialInternal(IMaterialInternal* pCurrentMaterial);
IMaterialInternal* GetMaterialInternal( MaterialHandle_t idx ) const;
const IMatRenderContextInternal *GetRenderContextInternal() const;
IMatRenderContextInternal *GetRenderContextInternal();
const CMaterialDict *GetMaterialDict() const;
CMaterialDict *GetMaterialDict();
//------------------------------------------------------------
struct LightmapPageInfo_t
{
unsigned short m_Width;
unsigned short m_Height;
int m_Flags;
};
struct dynamiclightmap_t
{
void Init()
{
lightmapLocked = -1;
frameID = 0;
currentDynamicIndex = 0;
for ( int i = 0; i < COUNT_DYNAMIC_LIGHTMAP_PAGES; i++ )
{
lightmapLockFrame[i] = 0;
}
}
int lightmapLocked;
int frameID;
int currentDynamicIndex;
int lightmapLockFrame[COUNT_DYNAMIC_LIGHTMAP_PAGES];
CImagePacker imagePackers[COUNT_DYNAMIC_LIGHTMAP_PAGES];
};
CUtlVector<CImagePacker> m_ImagePackers;
int m_numSortIDs;
IMaterialInternal *m_currentWhiteLightmapMaterial;
LightmapPageInfo_t *m_pLightmapPages;
CUtlVector<ShaderAPITextureHandle_t> m_LightmapPageTextureHandles;
int m_NumLightmapPages;
int m_nUpdatingLightmapsStackDepth;
int m_firstDynamicLightmap;
CPixelWriter m_LightmapPixelWriter;
int m_nLockedLightmap; // -1 for nothing locked.
dynamiclightmap_t m_dynamic;
FloatBitMap_t **m_pLightmapDataPtrArray;
enum LightmapsState
{
STATE_DEFAULT, // Lightmaps in default state - all operations allowed
STATE_RELEASED // Lightmaps in released state - usually due to lost/released D3D device, D3D operations disallowed, Restore() call to follow
};
LightmapsState m_eLightmapsState;
};
//-----------------------------------------------------------------------------
#endif // CMATERIALLIGHTMAPS_H
+984
View File
@@ -0,0 +1,984 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#include "pch_materialsystem.h"
#include "cmatnullrendercontext.h"
#ifndef _PS3
#define MATSYS_INTERNAL
#endif
#include "cmatrendercontext.h"
#include "itextureinternal.h"
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
class CMatNullRenderContext : public CMatRenderContextBase
{
public:
CMatNullRenderContext()
: m_WidthBackBuffer( 0 ),
m_HeightBackBuffer( 0 )
{
}
virtual void InitializeFrom( CMatRenderContextBase *pInitialState )
{
CMatRenderContextBase::InitializeFrom( pInitialState );
g_pShaderAPI->GetBackBufferDimensions( m_WidthBackBuffer, m_HeightBackBuffer );
}
void BeginRender()
{
}
void EndRender()
{
}
void Flush(bool)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void GetRenderTargetDimensions(int &,int &) const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void DepthRange(float,float)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ClearBuffers(bool,bool,bool)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ReadPixels(int,int,int,int,unsigned char *,ImageFormat, ITexture *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ReadPixelsAsync(int,int,int,int,unsigned char *,ImageFormat, ITexture *, CThreadEvent *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ReadPixelsAsyncGetResult(int,int,int,int,unsigned char *,ImageFormat,CThreadEvent *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
virtual void SetLightingState( const MaterialLightingState_t &state )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetLights( int nCount, const LightDesc_t *pDesc )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetLightingOrigin( Vector vLightingOrigin )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetAmbientLightCube(Vector4D [])
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void CopyRenderTargetToTexture(ITexture *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetFrameBufferCopyTexture(ITexture *,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
ITexture *GetFrameBufferCopyTexture(int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return NULL;
}
void GetViewport( int& x, int& y, int& width, int& height ) const
{
// Verify valid top of RT stack
Assert ( m_RenderTargetStack.Count() > 0 );
// Grab the top of stack
const RenderTargetStackElement_t& element = m_RenderTargetStack.Top();
// If either dimension is negative, set to full bounds of current target
if ( (element.m_nViewW < 0) || (element.m_nViewH < 0) )
{
// Viewport origin at target origin
x = y = 0;
// If target is back buffer
if ( element.m_pRenderTargets[0] == NULL )
{
width = m_WidthBackBuffer;
height = m_HeightBackBuffer;
}
else // if target is texture
{
width = element.m_pRenderTargets[0]->GetActualWidth();
height = element.m_pRenderTargets[0]->GetActualHeight();
}
}
else // use the bounds from the stack directly
{
x = element.m_nViewX;
y = element.m_nViewY;
width = element.m_nViewW;
height = element.m_nViewH;
}
}
void BeginGeneratingCSMs()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void EndGeneratingCSMs()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void PerpareForCascadeDraw( int cascade, float fShadowSlopeScaleDepthBias, float fShadowDepthBias )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void CullMode(MaterialCullMode_t)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void FlipCullMode( void )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void FogMode(MaterialFogMode_t)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void FogStart(float)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void FogEnd(float)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetFogZ(float)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
MaterialFogMode_t GetFogMode()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return MATERIAL_FOG_NONE;
}
int GetCurrentNumBones( ) const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return 0;
}
void FogColor3f(float,float,float)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void FogColor3fv(const float *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void FogColor3ub(unsigned char,unsigned char,unsigned char)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void FogColor3ubv(const unsigned char *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void GetFogColor(unsigned char *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetNumBoneWeights(int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
IMesh *CreateStaticMesh(VertexFormat_t,const char *,IMaterial *,VertexStreamSpec_t *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return NULL;
}
void DestroyStaticMesh(IMesh *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
IMesh *GetDynamicMesh(bool,IMesh *,IMesh *,IMaterial *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return NULL;
}
virtual IMesh* GetDynamicMeshEx( VertexFormat_t, bool, IMesh*, IMesh*, IMaterial * )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return NULL;
}
int SelectionMode(bool)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return 0;
}
void SelectionBuffer(unsigned int *,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ClearSelectionNames()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void LoadSelectionName(int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void PushSelectionName(int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void PopSelectionName()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ClearColor3ub(unsigned char,unsigned char,unsigned char)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ClearColor4ub(unsigned char,unsigned char,unsigned char,unsigned char)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void OverrideDepthEnable( bool, bool, bool )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void OverrideAlphaWriteEnable( bool, bool )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void OverrideColorWriteEnable( bool, bool )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void DrawScreenSpaceQuad(IMaterial *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SyncToken(const char *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
OcclusionQueryObjectHandle_t CreateOcclusionQueryObject()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return NULL;
}
void DestroyOcclusionQueryObject(OcclusionQueryObjectHandle_t)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ResetOcclusionQueryObject( OcclusionQueryObjectHandle_t hOcclusionQuery )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void BeginOcclusionQueryDrawing(OcclusionQueryObjectHandle_t)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void EndOcclusionQueryDrawing(OcclusionQueryObjectHandle_t)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
int OcclusionQuery_GetNumPixelsRendered(OcclusionQueryObjectHandle_t)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return 1;
}
virtual void SetFlashlightMode(bool)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
virtual bool GetFlashlightMode( void ) const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return false;
}
virtual bool IsCullingEnabledForSinglePassFlashlight( void ) const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return false;
}
virtual void EnableCullingForSinglePassFlashlight( bool )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
virtual void SetRenderingPaint( bool bEnable )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetFlashlightState(const FlashlightState_t &,const VMatrix &)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
virtual bool IsCascadedShadowMapping() const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return false;
}
virtual void SetCascadedShadowMapping( bool bEnable )
{
bEnable;
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
virtual void SetCascadedShadowMappingState( const CascadedShadowMappingState_t &state, ITexture *pDepthTextureAtlas )
{
state, pDepthTextureAtlas;
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void PushScissorRect( const int nLeft, const int nTop, const int nRight, const int nBottom )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void PopScissorRect()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
virtual void PushDeformation( DeformationBase_t const *Deformation )
{
}
virtual void PopDeformation( )
{
}
virtual int GetNumActiveDeformations() const
{
return 0;
}
void EnableUserClipTransformOverride(bool)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void UserClipTransform(const VMatrix &)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
IMorph *CreateMorph(MorphFormat_t, const char *pDebugName)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return NULL;
}
void DestroyMorph(IMorph *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void BindMorph(IMorph *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetMorphTargetFactors(int,float *,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ReadPixelsAndStretch(Rect_t *,Rect_t *,unsigned char *,ImageFormat,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void GetWindowSize(int &,int &) const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void DrawScreenSpaceRectangle(IMaterial *,int,int,int,int,float,float,float,float,int,int,void*,int,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void LoadBoneMatrix(int,const matrix3x4_t &)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void BindLightmapTexture(ITexture *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void CopyRenderTargetToTextureEx(ITexture *,int,Rect_t *,Rect_t *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void CopyTextureToRenderTargetEx(int,ITexture *,Rect_t *,Rect_t *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetFloatRenderingParameter(int,float)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetIntRenderingParameter(int,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetTextureRenderingParameter( int, ITexture * )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetVectorRenderingParameter(int,const Vector &)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
virtual void SetStencilState( const ShaderStencilState_t & )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ClearStencilBufferRectangle(int,int,int,int,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void PushCustomClipPlane(const float *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void PopCustomClipPlane()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void GetMaxToRender(IMesh *,bool,int *,int *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
int GetMaxVerticesToRender(IMaterial *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return 0;
}
int GetMaxIndicesToRender()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return 0;
}
void DisableAllLocalLights()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
int CompareMaterialCombos(IMaterial *,IMaterial *,int,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return 0;
}
IMesh *GetFlexMesh()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return NULL;
}
void SetFlashlightStateEx(const FlashlightState_t &,const VMatrix &,ITexture *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
ITexture *GetLocalCubemap()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return NULL;
}
void ClearBuffersObeyStencil(bool,bool)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ClearBuffersObeyStencilEx( bool bClearColor, bool bClearAlpha, bool bClearDepth )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void PerformFullScreenStencilOperation( void )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
bool GetUserClipTransform(VMatrix &)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return true;
}
void GetFogDistances(float *,float *,float *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void BeginPIXEvent(unsigned long,const char *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void EndPIXEvent()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetPIXMarker(unsigned long,const char *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void BeginBatch(IMesh *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void BindBatch(IMesh *,IMaterial *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void DrawBatch(MaterialPrimitiveType_t, int,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void EndBatch()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetToneMappingScaleLinear(const Vector &)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
float GetFloatRenderingParameter(int) const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return 0;
}
int GetIntRenderingParameter(int) const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return 0;
}
ITexture *GetTextureRenderingParameter(int) const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return 0;
}
Vector GetVectorRenderingParameter(int) const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return Vector(0,0,0);
}
void SwapBuffers()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void ForceDepthFuncEquals(bool)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
bool InFlashlightMode() const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return true;
}
bool IsRenderingPaint() const
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return true;
}
void GetLightmapDimensions(int *,int *)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
MorphFormat_t GetBoundMorphFormat()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return 0;
}
void DrawClearBufferQuad(unsigned char,unsigned char,unsigned char,unsigned char,bool,bool,bool)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
#ifdef _PS3
virtual void DrawReloadZcullQuad()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
#endif // _PS3
bool OnDrawMesh(IMesh *,CPrimList *,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return true;
}
bool OnDrawMesh(IMesh *,int,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return true;
}
bool OnDrawMeshModulated(IMesh *, const Vector4D&, int,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return true;
}
bool OnSetFlexMesh(IMesh *,IMesh *,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return true;
}
bool OnSetColorMesh(IMesh *,IMesh *,int)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return true;
}
bool OnSetPrimitiveType(IMesh *,MaterialPrimitiveType_t)
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
return true;
}
void ForceHardwareSync()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void BeginFrame()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void EndFrame()
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void SetShadowDepthBiasFactors( float fSlopeScaleDepthBias, float fDepthBias )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void BindStandardTexture( Sampler_t, TextureBindFlags_t nBindFlags, StandardTextureId_t )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
void EvictManagedResources()
{
AssertMsg( 0, "EvictManagedResources only provides base features, not a stub (right now)" );
}
// ------------ New Vertex/Index Buffer interface ----------------------------
// Do we need support for bForceTempMesh and bSoftwareVertexShader?
// I don't think we use bSoftwareVertexShader anymore. .need to look into bForceTempMesh.
IVertexBuffer *CreateStaticVertexBuffer( VertexFormat_t fmt, int nVertexCount, const char *pBudgetGroup )
{
Assert( 0 );
return NULL;
}
IIndexBuffer *CreateStaticIndexBuffer( MaterialIndexFormat_t fmt, int nIndexCount, const char *pBudgetGroup )
{
Assert( 0 );
return NULL;
}
void DestroyVertexBuffer( IVertexBuffer * )
{
Assert( 0 );
}
void DestroyIndexBuffer( IIndexBuffer * )
{
Assert( 0 );
}
// Do we need to specify the stream here in the case of locking multiple dynamic VBs on different streams?
IVertexBuffer *GetDynamicVertexBuffer( int streamID, VertexFormat_t vertexFormat, bool bBufferedtrue )
{
Assert( 0 );
return NULL;
}
IIndexBuffer *GetDynamicIndexBuffer( )
{
Assert( 0 );
return NULL;
}
void BindVertexBuffer( int streamID, IVertexBuffer *pVertexBuffer, int nOffsetInBytes, int nFirstVertex, int nVertexCount, VertexFormat_t fmt, int nRepetitions1 )
{
Assert( 0 );
}
void BindIndexBuffer( IIndexBuffer *pIndexBuffer, int nOffsetInBytes )
{
Assert( 0 );
}
void Draw( MaterialPrimitiveType_t primitiveType, int firstIndex, int numIndices )
{
Assert( 0 );
}
virtual void BeginMorphAccumulation()
{
Assert( 0 );
}
virtual void EndMorphAccumulation()
{
Assert( 0 );
}
virtual void AccumulateMorph( IMorph* pMorph, int nMorphCount, const MorphWeight_t* pWeights )
{
Assert( 0 );
}
virtual bool GetMorphAccumulatorTexCoord( Vector2D *pTexCoord, IMorph *pMorph, int nVertex )
{
Assert(0);
pTexCoord->Init();
return false;
}
virtual int GetSubDBufferWidth()
{
Assert(0);
return 0;
}
virtual float* LockSubDBuffer( int nNumRows )
{
Assert(0);
return NULL;
}
virtual void UnlockSubDBuffer()
{
Assert(0);
}
virtual void SetFlexWeights( int nFirstWeight, int nCount, const MorphWeight_t* pWeights ) {}
virtual void FogMaxDensity( float flMaxDensity )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
virtual void DrawInstances( int nInstanceCount, const MeshInstanceData_t *pInstance )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
virtual void EnableColorCorrection( bool bEnable ) {}
virtual ColorCorrectionHandle_t AddLookup( const char *pName ) { return 0; }
virtual bool RemoveLookup( ColorCorrectionHandle_t handle ) { return true; }
virtual void LockLookup( ColorCorrectionHandle_t handle ) {}
virtual void LoadLookup( ColorCorrectionHandle_t handle, const char *pLookupName ) {}
virtual void UnlockLookup( ColorCorrectionHandle_t handle ) {}
virtual void SetLookupWeight( ColorCorrectionHandle_t handle, float flWeight ) {}
virtual void ResetLookupWeights( ) {}
virtual void SetResetable( ColorCorrectionHandle_t handle, bool bResetable ) {}
virtual void SetFullScreenDepthTextureValidityFlag( bool bIsValid ) {}
virtual void SetNonInteractiveLogoTexture( ITexture *pTexture, float flNormalizedX, float flNormalizedY, float flNormalizedW, float flNormalizedH ) {}
virtual void SetNonInteractivePacifierTexture( ITexture *pTexture, float flNormalizedX, float flNormalizedY, float flNormalizedSize ) {}
virtual void SetNonInteractiveTempFullscreenBuffer( ITexture *pTexture, MaterialNonInteractiveMode_t mode ) {}
virtual void EnableNonInteractiveMode( MaterialNonInteractiveMode_t mode ) {}
virtual void RefreshFrontBufferNonInteractive() {}
virtual void FlipCulling( bool bFlipCulling ) {}
#if defined( _X360 )
virtual void PushVertexShaderGPRAllocation( int iVertexShaderCount = 64 )
{
Assert( 0 );
}
virtual void PopVertexShaderGPRAllocation( void )
{
Assert( 0 );
}
virtual void FlushHiStencil()
{
Assert( 0 );
}
#endif
#if defined( _GAMECONSOLE )
virtual void BeginConsoleZPass( const WorldListIndicesInfo_t &indicesInfo )
{
Assert( 0 );
}
virtual void BeginConsoleZPass2( int nSlack )
{
Assert( 0 );
}
virtual void EndConsoleZPass()
{
Assert( 0 );
}
#endif
#if defined( _PS3 )
virtual void FlushTextureCache()
{
Assert( 0 );
}
#endif
virtual void AntiAliasingHint(int )
{
Assert( 0 );
}
virtual void EnableSinglePassFlashlightMode( bool bEnable )
{
Assert( 0 );
}
virtual bool SinglePassFlashlightModeEnabled( void ) const
{
Assert( 0 );
return false;
}
void UpdateGameTime( float )
{
AssertMsg( 0, "CMatNullRenderContext only provides base features, not a stub (right now)" );
}
#if defined( INCLUDE_SCALEFORM )
virtual void SetScaleformSlotViewport( int slot, int x, int y, int w, int h ) { Assert (0); }
virtual void RenderScaleformSlot( int slot ) { Assert (0); }
virtual void ForkRenderScaleformSlot( int slot ) { Assert (0); }
virtual void JoinRenderScaleformSlot( int slot ) { Assert (0); }
virtual void SetScaleformCursorViewport( int x, int y, int w, int h ) { Assert (0); }
virtual void RenderScaleformCursor() { Assert (0); }
virtual void AdvanceAndRenderScaleformSlot( int slot ) { Assert (0); }
virtual void AdvanceAndRenderScaleformCursor() { Assert (0); }
#endif
//--------------------------------------------------------
// debug logging - no-op in queued context
//--------------------------------------------------------
virtual void Printf( char *fmt, ... ) {};
virtual void PrintfVA( char *fmt, va_list vargs ){};
virtual float Knob( char *knobname, float *setvalue=NULL ) { return 0.0f; };
#if defined( DX_TO_GL_ABSTRACTION ) && !defined( _GAMECONSOLE )
void DoStartupShaderPreloading( void ) {};
#endif
virtual ColorCorrectionHandle_t FindLookup( const char *pName ) { return 0; }
int m_WidthBackBuffer, m_HeightBackBuffer;
};
CMatRenderContextBase *CreateNullRenderContext()
{
return new CMatNullRenderContext;
}
+18
View File
@@ -0,0 +1,18 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#ifndef CMATNULLRENDERCONTEXT_H
#define CMATNULLRENDERCONTEXT_H
#if defined( _WIN32 )
#pragma once
#endif
class CMatRenderContextBase;
CMatRenderContextBase *CreateNullRenderContext();
#endif // CMATNULLRENDERCONTEXT_H
+416
View File
@@ -0,0 +1,416 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#include "pch_materialsystem.h"
#ifndef _PS3
#define MATSYS_INTERNAL
#endif
#include "cmaterialsystem.h"
#include "IHardwareConfigInternal.h"
#include "cmatpaintmaps.h"
#include "cmatlightmaps.h"
#include "materialsystem_global.h"
#include "materialsystem/materialsystem_config.h"
#include "itextureinternal.h"
// src/public/
#include "game/shared/portal2/paint_enum.h"
static Color g_PaintColors[PAINT_POWER_TYPE_COUNT_PLUS_NO_POWER];
static void RegisterPaintColors()
{
#if defined ( PORTAL2 )
// These ConVar are defined in src/game/shared/portal/paint_color_manager.cpp
static ConVarRef speed_paint_color( "speed_paint_color" );
static ConVarRef bounce_paint_color( "bounce_paint_color" );
static ConVarRef reflect_paint_color( "reflect_paint_color" );
static ConVarRef portal_paint_color( "portal_paint_color" );
static ConVarRef erase_color( "erase_color" );
g_PaintColors[SPEED_POWER] = speed_paint_color.GetColor();
g_PaintColors[BOUNCE_POWER] = bounce_paint_color.GetColor();
g_PaintColors[PORTAL_POWER] = portal_paint_color.GetColor();
g_PaintColors[REFLECT_POWER] = reflect_paint_color.GetColor();
g_PaintColors[NO_POWER] = erase_color.GetColor();
#endif
}
static const BYTE NUM_ALPHA_BITS = 5;
static const BYTE PAINT_COLOR_BITS = 7 << NUM_ALPHA_BITS; // 224
static const BYTE PAINT_ALPHA_BITS = PAINT_COLOR_BITS ^ 0xFF; // 31
BYTE GetColorIndex( BYTE byte )
{
return ( PAINT_COLOR_BITS & byte ) >> NUM_ALPHA_BITS;
}
inline const Color &GetColor( BYTE byte )
{
BYTE colorIndex = GetColorIndex( byte );
return g_PaintColors[ colorIndex ];
}
inline float GetAlpha( BYTE byte )
{
double alpha = ( PAINT_ALPHA_BITS & byte ); // leave as double to postpone the frsp...
alpha /= PAINT_ALPHA_BITS;
alpha = clamp( alpha, 0.0, 1.0 );
return alpha; // ...to here
}
CMatPaintmaps::CMatPaintmaps( void )
{
m_pDataManager = NULL;
m_nUpdatingPaintmapsStackDepth = 0;
m_nLockedPaintmap = -1;
}
bool CMatPaintmaps::IsEnabled( void )
{
return (m_pDataManager != NULL);
}
void CMatPaintmaps::RegisterPaintmapDataManager( IPaintmapDataManager *pDataManager )
{
m_pDataManager = pDataManager;
RegisterPaintColors();
}
void CMatPaintmaps::BeginPaintTextureAllocation( int iPaintmapCount )
{
CleanupPaintmaps();
m_pDataManager->BeginPaintmapsDataAllocation( iPaintmapCount );
}
void CMatPaintmaps::EndPaintTextureAllocation( void )
{
//do we need to do anything?
}
void CMatPaintmaps::ReleasePaintmaps( void )
{
// clean up paint textures, leave the paint data alone
for( int i = 0; i < m_PaintmapTextureHandles.Count(); i++ )
{
g_pShaderAPI->DeleteTexture( m_PaintmapTextureHandles[i] );
}
m_PaintmapTextureHandles.RemoveAll();
}
void CMatPaintmaps::RestorePaintmaps( int nNumLightmaps )
{
Assert( m_PaintmapTextureHandles.Count() == 0 );
// reallocate + update paint textures
for ( int i=0; i<nNumLightmaps; ++i )
{
int width, height;
m_pDataManager->GetPaintmapSize( i, width, height );
AllocatePaintmapTexture( i, width, height );
}
m_pDataManager->OnRestorePaintmaps();
}
void CMatPaintmaps::CleanupPaintmaps( void )
{
for( int i = 0; i < m_PaintmapTextureHandles.Count(); i++ )
{
g_pShaderAPI->DeleteTexture( m_PaintmapTextureHandles[i] );
}
m_PaintmapTextureHandles.RemoveAll();
if( m_pDataManager )
{
m_pDataManager->DestroyPaintmapsData();
}
}
ShaderAPITextureHandle_t CMatPaintmaps::GetPaintmapPageTextureHandle( int paintmap )
{
//test new texture
if( paintmap >= 0 && paintmap < m_PaintmapTextureHandles.Count() )
{
return m_PaintmapTextureHandles[paintmap];
}
return INVALID_SHADERAPI_TEXTURE_HANDLE;
}
void CMatPaintmaps::BeginUpdatePaintmaps()
{
CMatCallQueue *pCallQueue = GetMaterialSystem()->GetRenderContextInternal()->GetCallQueueInternal();
if ( pCallQueue )
{
pCallQueue->QueueCall( this, &CMatPaintmaps::BeginUpdatePaintmaps );
return;
}
m_nUpdatingPaintmapsStackDepth++;
}
void CMatPaintmaps::FillRect( int paintmap, Rect_t* RESTRICT pRect, BYTE* RESTRICT pPaintData, Rect_t* RESTRICT pSubRect /*= NULL*/ ) RESTRICT
{
VPROF("CMatPaintmaps::FillRect");
int width, height;
m_pDataManager->GetPaintmapSize( paintmap, width, height );
// trap corrupted paint rect
// TODO: Server writing to and Client reading from rect list in paint.cpp in the engine is not threadsafe
if ( pRect->x < 0 || pRect->y < 0 || pRect->x >= width || pRect->y >= height ||
pRect->width < 0 || pRect->height < 0 || pRect->width > width || pRect->height > height ||
pRect->x + pRect->width > width || pRect->y + pRect->height > height )
{
DevWarning( "Corrupted paint rect\n" );
return;
}
int rectOffset[2] = { pRect->x, pRect->y };
if ( pSubRect )
{
rectOffset[0] -= pSubRect->x;
rectOffset[1] -= pSubRect->y;
}
int index;
for( int t = 0; t < pRect->height; ++t )
{
m_PaintmapPixelWriter.Seek( rectOffset[0], rectOffset[1] + t );
index = ( t + pRect->y ) * width;
for( int s = 0; s < pRect->width; ++s )
{
BYTE paintData = pPaintData[index + s + pRect->x];
const Color &color = GetColor( paintData );
float alpha = GetAlpha( paintData );
#ifndef _PS3
m_PaintmapPixelWriter.WritePixel( color.r(), color.g(), color.b(), alpha * 255 );
#else // is PS3
Assert( m_PaintmapPixelWriter.IsUsing16BitFloatFormat() );
m_PaintmapPixelWriter.WritePixelNoAdvance16F(
(float)color.r() / 255.0f,
(float)color.g() / 255.0f,
(float)color.b() / 255.0f,
alpha );
m_PaintmapPixelWriter.SkipPixels(1);
#endif
}
}
}
void CMatPaintmaps::UpdatePaintmap( int paintmap, BYTE* pPaintData, int numRects, Rect_t* pRects )
{
VPROF("CMatPaintmaps::UpdatePaintmap");
if ( paintmap >= GetMaterialSystem()->GetNumLightmapPages() || paintmap < 0 )
{
Error( "CMatPaintmaps::UpdatePaintmap paintmap=%d out of range\n", paintmap );
return;
}
bool bLockSubRect = pRects != NULL;
Rect_t rect;
if ( bLockSubRect )
{
int minX = 512;
int minY = 512;
int maxX = 0;
int maxY = 0;
// find min/max rect
for ( int i=0; i<numRects; ++i )
{
Rect_t* pCurrentRect = &pRects[i];
minX = MIN( pCurrentRect->x, minX );
minY = MIN( pCurrentRect->y, minY );
maxX = MAX( pCurrentRect->x + pCurrentRect->width, maxX );
maxY = MAX( pCurrentRect->y + pCurrentRect->height, maxY );
}
rect.x = minX;
rect.y = minY;
rect.width = maxX - minX;
rect.height = maxY - minY;
}
else
{
rect.x = rect.y = 0;
m_pDataManager->GetPaintmapSize( paintmap, rect.width, rect.height );
}
if ( bLockSubRect )
{
g_pShaderAPI->ModifyTexture( m_PaintmapTextureHandles[paintmap] );
if ( !g_pShaderAPI->TexLock( 0, 0, rect.x, rect.y, rect.width, rect.height, m_PaintmapPixelWriter ) )
{
Assert("Failed to lock paint texture!");
return;
}
}
else
{
if ( !LockPaintmap( paintmap ) )
{
Assert("Failed to lock paint texture!");
return;
}
}
// modify texture!
if ( pRects )
{
for ( int i=0; i<numRects; ++i )
{
FillRect( paintmap, &pRects[i], pPaintData, &rect );
}
}
else
{
FillRect( paintmap, &rect, pPaintData );
}
if ( bLockSubRect )
{
g_pShaderAPI->TexUnlock();
}
}
void CMatPaintmaps::EndUpdatePaintmaps()
{
CMatCallQueue *pCallQueue = GetMaterialSystem()->GetRenderContextInternal()->GetCallQueueInternal();
if ( pCallQueue )
{
pCallQueue->QueueCall( this, &CMatPaintmaps::EndUpdatePaintmaps );
return;
}
m_nUpdatingPaintmapsStackDepth--;
Assert( m_nUpdatingPaintmapsStackDepth >= 0 );
if( m_nUpdatingPaintmapsStackDepth <= 0 && m_nLockedPaintmap != -1 )
{
g_pShaderAPI->TexUnlock();
m_nLockedPaintmap = -1;
}
}
ConVar mat_dynamicPaintmaps( "mat_dynamicPaintmaps", "0", FCVAR_CHEAT );
void CMatPaintmaps::AllocatePaintmapTexture( int paintmap, int iWidth, int iHeight )
{
// allocate paint texture
int flags = 0;
bool bUseDynamicTextures = HardwareConfig()->PreferDynamicTextures() && mat_dynamicPaintmaps.GetBool();
if ( bUseDynamicTextures || IsPS3() ) // On PS3, we need the dynamic flag as a hint that we're going to update this texture incrementally in the future
{
flags |= TEXTURE_CREATE_DYNAMIC;
}
else
{
flags |= TEXTURE_CREATE_MANAGED;
}
//flags |= TEXTUREFLAGS_PROCEDURAL;
m_PaintmapTextureHandles.EnsureCount( paintmap + 1 );
char debugName[256];
Q_snprintf( debugName, sizeof( debugName ), "[paintmap %d]", paintmap );
ImageFormat imageFormat;
#if !defined( _X360 )
imageFormat = IMAGE_FORMAT_RGBA8888;
#else
imageFormat = IMAGE_FORMAT_LINEAR_RGBA8888;
#endif
#ifdef _PS3
// PS3 needs 16F textures...but the HDR_TYPE_FLOAT codepath has a lot of other baggage with it. Just lie here.
imageFormat = IMAGE_FORMAT_RGBA16161616F;
#endif // _PS3
m_PaintmapTextureHandles[paintmap] = g_pShaderAPI->CreateTexture(
iWidth, iHeight, 1,
imageFormat,
1, 1, flags, debugName, TEXTURE_GROUP_LIGHTMAP ); // don't mipmap Paintmaps
Assert( m_PaintmapTextureHandles[paintmap] != INVALID_SHADERAPI_TEXTURE_HANDLE );
// Load up the texture data
g_pShaderAPI->ModifyTexture( m_PaintmapTextureHandles[paintmap] );
g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
// Blat out the paintmap bits
InitPaintmapBits( paintmap );
}
void CMatPaintmaps::AllocatePaintmap( int paintmap, int iWidth, int iHeight )
{
if( !IsEnabled() )
return;
// allocate paint data
m_pDataManager->AllocatePaintmapData( paintmap, iWidth, iHeight );
// allocate paint texture
AllocatePaintmapTexture( paintmap, iWidth, iHeight );
}
void CMatPaintmaps::InitPaintmapBits( int paintmap )
{
CPixelWriter writer;
int width, height;
m_pDataManager->GetPaintmapSize( paintmap, width, height );
g_pShaderAPI->ModifyTexture( m_PaintmapTextureHandles[paintmap] );
if ( !g_pShaderAPI->TexLock( 0, 0, 0, 0, width, height, writer ) )
return;
// This always needs to be initialized fully to black
void *pBits = writer.GetPixelMemory();
memset( pBits, 0, width * height * writer.GetPixelSize() );
g_pShaderAPI->TexUnlock();
}
bool CMatPaintmaps::LockPaintmap( int paintmap )
{
if( m_nLockedPaintmap != -1 )
{
g_pShaderAPI->TexUnlock();
}
g_pShaderAPI->ModifyTexture( m_PaintmapTextureHandles[paintmap] );
int width, height;
m_pDataManager->GetPaintmapSize( paintmap, width, height );
if ( !g_pShaderAPI->TexLock( 0, 0, 0, 0, width, height, m_PaintmapPixelWriter ) )
{
Assert( 0 );
return false;
}
m_nLockedPaintmap = paintmap;
return true;
}
+75
View File
@@ -0,0 +1,75 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#ifndef CMATERIALPaintmapS_H
#define CMATERIALPaintmapS_H
#include "tier1/utlvector.h"
#include "materialsystem/MaterialSystemUtil.h"
#include "materialsystem/ipaintmapdatamanager.h"
#ifndef MATSYS_INTERNAL
#error "This file is private to the implementation of IMaterialSystem/IMaterialSystemInternal"
#endif
#if defined( _WIN32 )
#pragma once
#endif
class CMaterialSystem;
//-----------------------------------------------------------------------------
// Manager of material system Paintmaps
//-----------------------------------------------------------------------------
class CMatPaintmaps : public IPaintmapTextureManager
{
public:
CMatPaintmaps();
bool IsEnabled( void );
void RegisterPaintmapDataManager( IPaintmapDataManager *pDataManager );
void BeginPaintTextureAllocation( int iPaintmapCount );
void EndPaintTextureAllocation( void );
void AllocatePaintmap( int paintmap, int iWidth, int iHeight );
void ReleasePaintmaps( void );
void RestorePaintmaps( int nNumLightmaps );
void CleanupPaintmaps( void );
ShaderAPITextureHandle_t GetPaintmapPageTextureHandle( int paintmap );
CMaterialSystem *GetMaterialSystem() const;
// Derived from IPaintmapTextureManager
//------------------------------------------------
virtual void BeginUpdatePaintmaps();
virtual void UpdatePaintmap( int paintmap, BYTE* pPaintData, int numRects, Rect_t* pRects );
virtual void EndUpdatePaintmaps();
//------------------------------------------------
IPaintmapDataManager *m_pDataManager;
private:
void InitPaintmapBits( int paintmap );
bool LockPaintmap( int paintmap );
void FillRect( int paintmap, Rect_t* RESTRICT pRect, BYTE* RESTRICT pPaintData, Rect_t* RESTRICT pSubRect = NULL ) RESTRICT;
void AllocatePaintmapTexture( int paintmap, int iWidth, int iHeight );
CPixelWriter m_PaintmapPixelWriter;
CUtlVector<ShaderAPITextureHandle_t> m_PaintmapTextureHandles;
int m_nLockedPaintmap;
int m_nUpdatingPaintmapsStackDepth;
};
//-----------------------------------------------------------------------------
#endif // CMATERIALPaintmapS_H
File diff suppressed because it is too large. Load diff
+825
View File
@@ -0,0 +1,825 @@
//========== Copyright (c) 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#ifndef CMATQUEUEDRENDERCONTEXT_H
#define CMATQUEUEDRENDERCONTEXT_H
#include "imatrendercontextinternal.h"
#include "cmatrendercontext.h"
#include "tier1/callqueue.h"
#include "tier1/utlenvelope.h"
#include "tier1/memstack.h"
#include "mathlib/mathlib.h"
#include "tier0/memdbgon.h"
#if defined( _WIN32 )
#pragma once
#endif
#ifndef MATSYS_INTERNAL
#error "This file is private to the implementation of IMaterialSystem/IMaterialSystemInternal"
#endif
class CMaterialSystem;
class CMatQueuedMesh;
class CMatQueuedIndexBuffer;
class CPrimList;
//-----------------------------------------------------------------------------
#define DEFINE_QUEUED_CALL_0( FuncName, ClassName, pObject ) void FuncName() { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)())&ClassName::FuncName); }
#define DEFINE_QUEUED_CALL_1( FuncName, ArgType1, ClassName, pObject ) void FuncName( ArgType1 a1 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1))&ClassName::FuncName, a1 ); }
#define DEFINE_QUEUED_CALL_2( FuncName, ArgType1, ArgType2, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2))&ClassName::FuncName, a1, a2 ); }
#define DEFINE_QUEUED_CALL_3( FuncName, ArgType1, ArgType2, ArgType3, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3))&ClassName::FuncName, a1, a2, a3 ); }
#define DEFINE_QUEUED_CALL_4( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4))&ClassName::FuncName, a1, a2, a3, a4 ); }
#define DEFINE_QUEUED_CALL_5( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5))&ClassName::FuncName, a1, a2, a3, a4, a5 ); }
#define DEFINE_QUEUED_CALL_6( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6))&ClassName::FuncName, a1, a2, a3, a4, a5, a6 ); }
#define DEFINE_QUEUED_CALL_7( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7 ); }
#define DEFINE_QUEUED_CALL_8( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7, a8 ); }
#define DEFINE_QUEUED_CALL_9( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7, a8, a9 ); }
#define DEFINE_QUEUED_CALL_11( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9, ArgType10 a10, ArgType11 a11 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11 ); }
#define DEFINE_QUEUED_CALL_12( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9, ArgType10 a10, ArgType11 a11, ArgType12 a12 ) { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 ); }
#define DEFINE_QUEUED_CALL_0C( FuncName, ClassName, pObject ) void FuncName() const { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)() const)ClassName::FuncName); }
#define DEFINE_QUEUED_CALL_1C( FuncName, ArgType1, ClassName, pObject ) void FuncName( ArgType1 a1 ) const { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1) const)ClassName::FuncName, a1 ); }
#define DEFINE_QUEUED_CALL_2C( FuncName, ArgType1, ArgType2, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2 ) const { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2) const)ClassName::FuncName, a1, a2 ); }
#define DEFINE_QUEUED_CALL_3C( FuncName, ArgType1, ArgType2, ArgType3, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) const { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3) const)ClassName::FuncName, a1, a2, a3 ); }
#define DEFINE_QUEUED_CALL_4C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) const { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4) const)ClassName::FuncName, a1, a2, a3, a4 ); }
#define DEFINE_QUEUED_CALL_5C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) const { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5) const)ClassName::FuncName, a1, a2, a3, a4, a5 ); }
#define DEFINE_QUEUED_CALL_6C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) const { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6) const)ClassName::FuncName, a1, a2, a3, a4, a5, a6 ); }
#define DEFINE_QUEUED_CALL_7C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) const { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7) const)ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7 ); }
#define DEFINE_QUEUED_CALL_8C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) const { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8) const)ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7, a8 ); }
#define DEFINE_QUEUED_CALL_9C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) const { (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9) const)ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7, a8, a9 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_0( FuncName, ClassName, pObject ) void FuncName() { BaseClass::FuncName(); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)())&ClassName::FuncName ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_1( FuncName, ArgType1, ClassName, pObject ) void FuncName( ArgType1 a1 ) { BaseClass::FuncName( a1 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1))&ClassName::FuncName, a1 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_2( FuncName, ArgType1, ArgType2, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2 ) { BaseClass::FuncName( a1, a2 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2))&ClassName::FuncName, a1, a2 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_3( FuncName, ArgType1, ArgType2, ArgType3, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) { BaseClass::FuncName( a1, a2, a3 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3))&ClassName::FuncName, a1, a2, a3 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_4( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) { BaseClass::FuncName( a1, a2, a3, a4 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4))&ClassName::FuncName, a1, a2, a3, a4 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_5( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) { BaseClass::FuncName( a1, a2, a3, a4, a5 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5))&ClassName::FuncName, a1, a2, a3, a4, a5 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_6( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) { BaseClass::FuncName( a1, a2, a3, a4, a5, a6 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6))&ClassName::FuncName, a1, a2, a3, a4, a5, a6 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_7( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_8( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7, a8 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_9( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7, a8, a9 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_0C( FuncName, ClassName, pObject ) void FuncName() const { BaseClass::FuncName(); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)())&ClassName::FuncName ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_1C( FuncName, ArgType1, ClassName, pObject ) void FuncName( ArgType1 a1 ) const { BaseClass::FuncName( a1 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1))&ClassName::FuncName, a1 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_2C( FuncName, ArgType1, ArgType2, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2 ) const { BaseClass::FuncName( a1, a2 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2))&ClassName::FuncName, a1, a2 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_3C( FuncName, ArgType1, ArgType2, ArgType3, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3 ) const { BaseClass::FuncName( a1, a2, a3 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3))&ClassName::FuncName, a1, a2, a3 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_4C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4 ) const { BaseClass::FuncName( a1, a2, a3, a4 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4))&ClassName::FuncName, a1, a2, a3, a4 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_5C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5 ) const { BaseClass::FuncName( a1, a2, a3, a4, a5 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5))&ClassName::FuncName, a1, a2, a3, a4, a5 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_6C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6 ) const { BaseClass::FuncName( a1, a2, a3, a4, a5, a6 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6))&ClassName::FuncName, a1, a2, a3, a4, a5, a6 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_7C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7 ) const { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_8C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8 ) const { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7, a8 ); }
#define DEFINE_QUEUED_CALL_AFTER_BASE_9C( FuncName, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ClassName, pObject ) void FuncName( ArgType1 a1, ArgType2 a2, ArgType3 a3, ArgType4 a4, ArgType5 a5, ArgType6 a6, ArgType7 a7, ArgType8 a8, ArgType9 a9 ) const { BaseClass::FuncName( a1, a2, a3, a4, a5, a6, a7, a8, a9 ); (*(const_cast<CMatCallQueue *>(&m_queue))).QueueCall( pObject, (void (ClassName::*)(ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9))&ClassName::FuncName, a1, a2, a3, a4, a5, a6, a7, a8, a9 ); }
//-----------------------------------------------------------------------------
#define Unsupported( funcName ) ExecuteOnce( Msg( "CMatQueuedRenderContext: %s is unsupported\n", #funcName ) )
#define FATAL_QUEUE 1
#ifdef FATAL_QUEUE
#define CannotSupport() ExecuteOnce( Msg( "Called function that cannot be supported\n" ) ); ExecuteOnce( DebuggerBreakIfDebugging() )
#else
#define CannotSupport() ExecuteOnce( Msg( "Called function that cannot be supported\n" ) )
#endif
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
class CMatQueuedRenderContext : public CMatRenderContextBase
{
typedef CMatRenderContextBase BaseClass;
public:
CMatQueuedRenderContext()
: m_pHardwareContext( NULL ),
m_iRenderDepth( 0 ),
m_pQueuedMesh( NULL ),
m_WidthBackBuffer( 0 ),
m_HeightBackBuffer( 0 ),
m_FogMode( MATERIAL_FOG_NONE ),
m_flFogStart( 0 ),
m_flFogEnd( 0 ),
m_flFogZ( 0 ),
m_flFogMaxDensity( 1.0 )
{
memset( &m_FogColor, 0, sizeof(m_FogColor) );
}
void CycleDynamicBuffers( ); // For use in mat_queue_mode 1 only
void Init( CMaterialSystem *pMaterialSystem, CMatRenderContextBase *pHardwareContext );
void Shutdown();
void CompactMemory();
bool IsInitialized() const { return ( m_pHardwareContext != NULL ); }
void BeginQueue( CMatRenderContextBase *pInitialState = NULL );
void EndQueue( bool bCallQueued = false );
void BeginRender();
void EndRender();
void CallQueued( bool bTermAfterCall = false );
void FlushQueued();
ICallQueue * GetCallQueue();
CMatCallQueue * GetCallQueueInternal() { return &m_queue; }
DEFINE_QUEUED_CALL_0( EvictManagedResources, IShaderAPI, g_pShaderAPI );
bool OnDrawMesh( IMesh *pMesh, int firstIndex, int numIndices );
bool OnDrawMesh( IMesh *pMesh, CPrimList *pLists, int nLists );
bool OnDrawMeshModulated( IMesh *pMesh, const Vector4D &diffuseModulation, int firstIndex, int numIndices );
bool OnSetFlexMesh( IMesh *pStaticMesh, IMesh *pMesh, int nVertexOffsetInBytes );
bool OnSetColorMesh( IMesh *pStaticMesh, IMesh *pMesh, int nVertexOffsetInBytes );
bool OnSetPrimitiveType( IMesh *pMesh, MaterialPrimitiveType_t type );
DEFINE_QUEUED_CALL_1( Flush, bool, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( SwapBuffers, IMatRenderContextInternal, m_pHardwareContext );
void SetRenderTargetEx( int nRenderTargetID, ITexture *pTexture );
void GetRenderTargetDimensions( int &, int &) const;
void GetViewport( int& x, int& y, int& width, int& height ) const;
void Bind( IMaterial *, void * );
DEFINE_QUEUED_CALL_AFTER_BASE_1( BindLocalCubemap, ITexture *, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_AFTER_BASE_1( BindLightmapPage, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_2( DepthRange, float, float, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_3( ClearBuffers, bool, bool, bool, IMatRenderContext, m_pHardwareContext );
void ReadPixels( int x, int y, int width, int height, unsigned char *data, ImageFormat dstFormat, ITexture *pRenderTargetTexture = NULL );
void ReadPixelsAsync( int x, int y, int width, int height, unsigned char *data, ImageFormat dstFormat, ITexture *pRenderTargetTexture = NULL, CThreadEvent *pPixelsReadEvent = NULL );
void ReadPixelsAsyncGetResult( int x, int y, int width, int height, unsigned char *data, ImageFormat dstFormat, CThreadEvent *pGetResultEvent = NULL );
void SetLightingState( const MaterialLightingState_t &desc );
void SetLights( int nCount, const LightDesc_t *pLights );
void SetLightingOrigin( Vector vLightingOrigin );
void SetAmbientLightCube( LightCube_t cube );
DEFINE_QUEUED_CALL_1( CopyRenderTargetToTexture, ITexture *, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_AFTER_BASE_2( SetFrameBufferCopyTexture, ITexture *, int, IMatRenderContext, m_pHardwareContext );
// matrix api
void MatrixMode( MaterialMatrixMode_t);
void PushMatrix();
void PopMatrix();
void LoadMatrix( const VMatrix& matrix );
void LoadMatrix( const matrix3x4_t& matrix );
void MultMatrix( const VMatrix& matrix );
void MultMatrixLocal( const VMatrix& matrix );
void MultMatrix( const matrix3x4_t& matrix );
void MultMatrixLocal( const matrix3x4_t& matrix );
void LoadIdentity();
void Ortho( double, double, double, double, double, double);
void PerspectiveX( double, double, double, double);
void PerspectiveOffCenterX( double, double, double, double, double, double, double, double );
void PickMatrix( int, int, int, int);
void Rotate( float, float, float, float);
void Translate( float, float, float);
void Scale( float, float, float);
// end matrix api
void Viewport( int x, int y, int width, int height );
DEFINE_QUEUED_CALL_1( CullMode, MaterialCullMode_t, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( FlipCullMode, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( BeginGeneratingCSMs, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( EndGeneratingCSMs, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_3( PerpareForCascadeDraw, int, float, float, IMatRenderContext, m_pHardwareContext );
void FogMode( MaterialFogMode_t fogMode );
void FogStart( float fStart );
void FogEnd( float fEnd );
void SetFogZ( float fogZ );
MaterialFogMode_t GetFogMode( void );
void GetFogDistances( float *fStart, float *fEnd, float *fFogZ );
void FogMaxDensity( float flMaxDensity );
void FogColor3f( float r, float g, float b );
void FogColor3fv( float const* rgb );
void FogColor3ub( unsigned char r, unsigned char g, unsigned char b );
void FogColor3ubv( unsigned char const* rgb );
void GetFogColor( unsigned char *rgb );
int GetCurrentNumBones( ) const;
void SetNumBoneWeights( int nBoneCount );
DELEGATE_TO_OBJECT_4( IMesh *, CreateStaticMesh, VertexFormat_t, const char *, IMaterial *, VertexStreamSpec_t *, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( DestroyStaticMesh, IMesh *, IMatRenderContext, m_pHardwareContext );
IMesh * GetDynamicMesh(bool, IMesh *, IMesh *, IMaterial * );
IMesh* GetDynamicMeshEx( VertexFormat_t, bool, IMesh*, IMesh*, IMaterial* );
// ------------ New Vertex/Index Buffer interface ----------------------------
DELEGATE_TO_OBJECT_3( IVertexBuffer *, CreateStaticVertexBuffer, VertexFormat_t, int, const char *, m_pHardwareContext );
DELEGATE_TO_OBJECT_3( IIndexBuffer *, CreateStaticIndexBuffer, MaterialIndexFormat_t, int, const char *, m_pHardwareContext );
DELEGATE_TO_OBJECT_1V( DestroyVertexBuffer, IVertexBuffer *, m_pHardwareContext );
DELEGATE_TO_OBJECT_1V( DestroyIndexBuffer, IIndexBuffer *, m_pHardwareContext );
DELEGATE_TO_OBJECT_3( IVertexBuffer *, GetDynamicVertexBuffer, int, VertexFormat_t, bool, m_pHardwareContext );
IIndexBuffer * GetDynamicIndexBuffer( );
DELEGATE_TO_OBJECT_7V( BindVertexBuffer, int, IVertexBuffer *, int, int, int, VertexFormat_t, int, m_pHardwareContext );
DELEGATE_TO_OBJECT_2V( BindIndexBuffer, IIndexBuffer *, int, m_pHardwareContext );
DELEGATE_TO_OBJECT_3V( Draw, MaterialPrimitiveType_t, int, int, m_pHardwareContext );
// ------------ End ----------------------------
int SelectionMode( bool )
{
CannotSupport();
return 0;
}
void SelectionBuffer( unsigned int *, int )
{
CannotSupport();
}
DEFINE_QUEUED_CALL_0( ClearSelectionNames, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( LoadSelectionName, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( PushSelectionName, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( PopSelectionName, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_3( ClearColor3ub, unsigned char, unsigned char, unsigned char, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_4( ClearColor4ub, unsigned char, unsigned char, unsigned char, unsigned char, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_3( OverrideDepthEnable, bool, bool, bool, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_2( OverrideAlphaWriteEnable, bool, bool, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_2( OverrideColorWriteEnable, bool, bool, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( DrawScreenSpaceQuad, IMaterial *, IMatRenderContext, m_pHardwareContext );
void SyncToken( const char *p );
// Allocate and delete query objects.
OcclusionQueryObjectHandle_t CreateOcclusionQueryObject();
DEFINE_QUEUED_CALL_1( DestroyOcclusionQueryObject, OcclusionQueryObjectHandle_t, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( BeginOcclusionQueryDrawing, OcclusionQueryObjectHandle_t, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( EndOcclusionQueryDrawing, OcclusionQueryObjectHandle_t, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( ResetOcclusionQueryObject, OcclusionQueryObjectHandle_t, IMatRenderContext, m_pHardwareContext );
int OcclusionQuery_GetNumPixelsRendered( OcclusionQueryObjectHandle_t );
void SetFlashlightState( const FlashlightState_t &s, const VMatrix &m );
DEFINE_QUEUED_CALL_AFTER_BASE_1( SetHeightClipMode, MaterialHeightClipMode_t, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_AFTER_BASE_1( SetHeightClipZ, float, IMatRenderContext, m_pHardwareContext );
bool EnableClipping( bool bEnable );
DEFINE_QUEUED_CALL_1( EnableUserClipTransformOverride, bool, IMatRenderContext, m_pHardwareContext );
void UserClipTransform( const VMatrix &m );
IMorph *CreateMorph( MorphFormat_t format, const char *pDebugName )
{
CannotSupport();
return NULL;
}
DEFINE_QUEUED_CALL_1( DestroyMorph, IMorph *, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( BindMorph, IMorph *, IMatRenderContext, m_pHardwareContext );
void ReadPixelsAndStretch( Rect_t *pSrcRect, Rect_t *pDstRect, unsigned char *pBuffer, ImageFormat dstFormat, int nDstStride );
void GetWindowSize( int &width, int &height ) const;
void DrawScreenSpaceRectangle( IMaterial *pMaterial,
int destx, int desty,
int width, int height,
float src_texture_x0, float src_texture_y0, // which texel you want to appear at
// destx/y
float src_texture_x1, float src_texture_y1, // which texel you want to appear at
// destx+width-1, desty+height-1
int src_texture_width, int src_texture_height, // needed for fixup
void *pClientRenderable = NULL,
int nXDice = 1,
int nYDice = 1 );
void LoadBoneMatrix( int i, const matrix3x4_t &m );
DEFINE_QUEUED_CALL_AFTER_BASE_5( PushRenderTargetAndViewport, ITexture *, int, int, int, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_AFTER_BASE_6( PushRenderTargetAndViewport, ITexture *, ITexture *, int, int, int, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_AFTER_BASE_1( PushRenderTargetAndViewport, ITexture *, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_AFTER_BASE_0( PushRenderTargetAndViewport, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_AFTER_BASE_0( PopRenderTargetAndViewport, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( BindLightmapTexture, ITexture *, IMatRenderContext, m_pHardwareContext );
void CopyRenderTargetToTextureEx( ITexture *pTexture, int i, Rect_t *pSrc, Rect_t *pDst );
void CopyTextureToRenderTargetEx( int i, ITexture *pTexture, Rect_t *pSrc, Rect_t *pDst );
DEFINE_QUEUED_CALL_2( SetFloatRenderingParameter, int, float, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_2( SetIntRenderingParameter, int, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_2( SetTextureRenderingParameter, int, ITexture *, IMatRenderContext, m_pHardwareContext );
void SetVectorRenderingParameter( int i, const Vector &v )
{
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::SetVectorRenderingParameter, i, RefToVal( v ) );
}
float GetFloatRenderingParameter(int parm_number) const
{
CannotSupport();
return 0;
}
int GetIntRenderingParameter(int parm_number) const
{
CannotSupport();
return 0;
}
ITexture *GetTextureRenderingParameter(int parm_number) const
{
CannotSupport();
return 0;
}
Vector GetVectorRenderingParameter(int parm_number) const
{
CannotSupport();
return Vector(0,0,0);
}
virtual void SetStencilState( const ShaderStencilState_t &state )
{
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::SetStencilState, RefToVal( state ) );
}
DEFINE_QUEUED_CALL_5( ClearStencilBufferRectangle, int, int, int, int, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_2( SetShadowDepthBiasFactors, float, float, IMatRenderContext, m_pHardwareContext );
void PushCustomClipPlane( const float *p )
{
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::PushCustomClipPlane, m_queue.CopyArray( p, 4 ) );
}
DEFINE_QUEUED_CALL_0( PopCustomClipPlane, IMatRenderContext, m_pHardwareContext );
virtual void GetMaxToRender( IMesh *pMesh, bool bMaxUntilFlush, int *pMaxVerts, int *pMaxIndices );
virtual int GetMaxVerticesToRender( IMaterial *pMaterial );
virtual int GetMaxIndicesToRender( );
DEFINE_QUEUED_CALL_0( DisableAllLocalLights, IMatRenderContext, m_pHardwareContext );
int CompareMaterialCombos( IMaterial *pMaterial1, IMaterial *pMaterial2, int lightmapID1, int lightmapID2 )
{
CannotSupport();
return 0;
}
IMesh *GetFlexMesh();
void SetFlashlightStateEx( const FlashlightState_t &s, const VMatrix &m, ITexture *p )
{
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::SetFlashlightStateEx, RefToVal( s ), RefToVal( m ), p );
}
void PushScissorRect( const int nLeft, const int nTop, const int nRight, const int nBottom )
{
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::PushScissorRect, nLeft, nTop, nRight, nBottom );
}
void PopScissorRect( )
{
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::PopScissorRect );
}
virtual void DrawInstances( int nInstanceCount, const MeshInstanceData_t *pInstance );
virtual void PushDeformation( const DeformationBase_t *pDef )
{
CannotSupport();
}
void PopDeformation( )
{
CannotSupport();
}
int GetNumActiveDeformations( ) const
{
return 0;
}
ITexture *GetLocalCubemap()
{
return m_pLocalCubemapTexture;
}
DEFINE_QUEUED_CALL_2( ClearBuffersObeyStencil, bool, bool, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_3( ClearBuffersObeyStencilEx, bool, bool, bool, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( PerformFullScreenStencilOperation, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( SetRenderingPaint, bool, IMatRenderContext, m_pHardwareContext );
bool GetUserClipTransform( VMatrix &worldToView )
{
CannotSupport();
return false;
}
bool InFlashlightMode( void ) const
{
CannotSupport();
return false;
}
bool IsRenderingPaint() const
{
CannotSupport();
return false;
}
virtual void SetFlashlightMode( bool bEnable )
{
m_bFlashlightEnable = bEnable;
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::SetFlashlightMode, bEnable );
}
virtual bool GetFlashlightMode( void ) const { return m_bFlashlightEnable; }
virtual bool IsCullingEnabledForSinglePassFlashlight( void ) const { return m_bCullingEnabledForSinglePassFlashlight; }
virtual void EnableCullingForSinglePassFlashlight( bool bEnable )
{
m_bCullingEnabledForSinglePassFlashlight = bEnable;
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::EnableCullingForSinglePassFlashlight, bEnable );
}
virtual bool IsCascadedShadowMapping() const
{
CannotSupport();
return false;
}
virtual void SetCascadedShadowMapping( bool bEnable )
{
m_bCascadedShadowMappingEnabled = bEnable;
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::SetCascadedShadowMapping, bEnable );
}
virtual void SetCascadedShadowMappingState( const CascadedShadowMappingState_t &state, ITexture *pDepthTextureAtlas )
{
state, pDepthTextureAtlas;
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::SetCascadedShadowMappingState, RefToVal( state ), pDepthTextureAtlas );
}
void BeginPIXEvent( unsigned long color, const char *pszName )
{
#ifdef PROFILE
if ( IsX360() )
{
m_pHardwareContext->BeginPIXEvent( color, pszName );
}
#endif
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::BeginPIXEvent, color, m_queue.Copy( pszName ) );
}
void EndPIXEvent( )
{
#ifdef PROFILE
if ( IsX360() )
{
m_pHardwareContext->EndPIXEvent( );
}
#endif
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::EndPIXEvent );
}
void SetPIXMarker( unsigned long color, const char *pszName )
{
#ifdef PROFILE
if ( IsX360() )
{
m_pHardwareContext->SetPIXMarker( color, pszName );
}
#endif
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::SetPIXMarker, color, m_queue.Copy( pszName ) );
}
DEFINE_QUEUED_CALL_0( ForceHardwareSync, IMatRenderContextInternal, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( BeginFrame, IMatRenderContextInternal, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( EndFrame, IMatRenderContextInternal, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( BeginMorphAccumulation, IMatRenderContextInternal, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( EndMorphAccumulation, IMatRenderContextInternal, m_pHardwareContext );
virtual void AccumulateMorph( IMorph* pMorph, int nMorphCount, const MorphWeight_t* pWeights )
{
// FIXME: Must copy off the morph weights here. Not sure the pattern for this.
Assert( 0 );
}
virtual bool GetMorphAccumulatorTexCoord( Vector2D *pTexCoord, IMorph *pIMorph, int nVertex )
{
// FIXME: We must assign morph ids in the queued mode
// and pass the ids down to the morph mgr to get the texcoord
Assert(0);
pTexCoord->Init();
return false;
}
virtual void SetFlexWeights( int nFirstWeight, int nCount, const MorphWeight_t* pWeights )
{
Assert(0);
}
// Subdivision surface interface
virtual int GetSubDBufferWidth()
{
Assert( 0 );
return 0;
}
virtual float* LockSubDBuffer( int nNumRows )
{
Assert( 0 );
return NULL;
}
virtual void UnlockSubDBuffer()
{
Assert( 0 );
}
DEFINE_QUEUED_CALL_1( UpdateGameTime, float, IMatRenderContext, m_pHardwareContext );
//-------------------------------------------------------------------------
DEFINE_QUEUED_CALL_AFTER_BASE_1( SetCurrentMaterialInternal, IMaterialInternal *, IMatRenderContextInternal, m_pHardwareContext );
DEFINE_QUEUED_CALL_AFTER_BASE_1( SetCurrentProxy, void *, IMatRenderContextInternal, m_pHardwareContext );
int GetLightmapPage()
{
CannotSupport();
return 0;
}
void ForceDepthFuncEquals( bool )
{
CannotSupport();
}
void BindStandardTexture( Sampler_t, TextureBindFlags_t nBindFlags, StandardTextureId_t )
{
CannotSupport();
}
void GetLightmapDimensions( int *, int * )
{
CannotSupport();
}
MorphFormat_t GetBoundMorphFormat()
{
CannotSupport();
return (MorphFormat_t)0;
}
void DrawClearBufferQuad( unsigned char, unsigned char, unsigned char, unsigned char, bool, bool, bool )
{
CannotSupport();
}
#ifdef _PS3
void DrawReloadZcullQuad()
{
CannotSupport();
}
#endif // _PS3
void BeginBatch( IMesh* pIndices );
void BindBatch( IMesh* pVertices, IMaterial *pAutoBind = NULL );
void DrawBatch( MaterialPrimitiveType_t primType, int firstIndex, int numIndices );
void EndBatch();
// Color correction related methods..
// Client cannot call IColorCorrectionSystem directly because it is not thread-safe
// FIXME: Make IColorCorrectionSystem threadsafe?
virtual ColorCorrectionHandle_t AddLookup( const char *pName );
virtual void LockLookup( ColorCorrectionHandle_t handle );
virtual void LoadLookup( ColorCorrectionHandle_t handle, const char *pLookupName );
virtual void UnlockLookup( ColorCorrectionHandle_t handle );
virtual bool RemoveLookup( ColorCorrectionHandle_t handle );
DEFINE_QUEUED_CALL_1( EnableColorCorrection, bool, IColorCorrectionSystem, g_pColorCorrectionSystem );
DEFINE_QUEUED_CALL_0( ResetLookupWeights, IColorCorrectionSystem, g_pColorCorrectionSystem );
DEFINE_QUEUED_CALL_2( SetLookupWeight, ColorCorrectionHandle_t, float, IColorCorrectionSystem, g_pColorCorrectionSystem );
DEFINE_QUEUED_CALL_2( SetResetable, ColorCorrectionHandle_t, bool, IColorCorrectionSystem, g_pColorCorrectionSystem );
DEFINE_QUEUED_CALL_1( SetFullScreenDepthTextureValidityFlag, bool, IMatRenderContext, m_pHardwareContext );
void SetToneMappingScaleLinear( const Vector &scale )
{
m_LastSetToneMapScale = scale;
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::SetToneMappingScaleLinear, RefToVal( scale ) );
}
Vector GetToneMappingScaleLinear( void )
{
return m_LastSetToneMapScale;
}
#if defined( _GAMECONSOLE )
void BeginConsoleZPass( const WorldListIndicesInfo_t &indicesInfo )
{
uint nSpaceLeft = Indices().GetSize() - Indices().GetUsed();
if( nSpaceLeft >= indicesInfo.m_nTotalIndices )
{
// there's enough indices in the primary (non-spillover) index buffer that's resident in memory for 3 frames,
// and that's not a ring buffer. We don't need to worry about these indices being overwritten by anything due
// to ring buffer ending and restarting: there's another (spillover) ring buffer that does that
BeginConsoleZPass2( 0 );
}
else
{
// there's some spillover from the main dynamic index buffer; thus, we need to compute the spillover and defer the decision
// about whether we have enough space in spillover buffer to start z prepass for later
// in the very worst case, we'll waste ( indicesInfo.m_nMaxBatchIndices - 1 ) indices
// in the end of the main dynamic IB
BeginConsoleZPass2( indicesInfo.m_nTotalIndices - nSpaceLeft + indicesInfo.m_nMaxBatchIndices - 1 );
}
}
#endif
void DeferredBeginBatch( );
void DeferredDrawPrimList( IMesh *pMesh, CPrimList *pLists, int nLists );
void DeferredSetFlexMesh( IMesh *pStaticMesh, int nVertexOffsetInBytes );
#if defined( _X360 )
DEFINE_QUEUED_CALL_1( PushVertexShaderGPRAllocation, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( PopVertexShaderGPRAllocation, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( FlushHiStencil, IMatRenderContext, m_pHardwareContext );
#endif
#if defined( _GAMECONSOLE )
DEFINE_QUEUED_CALL_1( BeginConsoleZPass2, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( EndConsoleZPass, IMatRenderContext, m_pHardwareContext );
#endif
#if defined( _PS3 )
DEFINE_QUEUED_CALL_0( FlushTextureCache, IMatRenderContext, m_pHardwareContext );
#endif
DEFINE_QUEUED_CALL_1( AntiAliasingHint, int, IMatRenderContext, m_pHardwareContext );
// A special path used to tick the front buffer while loading on the 360
DEFINE_QUEUED_CALL_5( SetNonInteractiveLogoTexture, ITexture *, float, float, float, float, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_4( SetNonInteractivePacifierTexture, ITexture *, float, float, float, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_2( SetNonInteractiveTempFullscreenBuffer, ITexture *, MaterialNonInteractiveMode_t, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( EnableNonInteractiveMode, MaterialNonInteractiveMode_t, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( RefreshFrontBufferNonInteractive, IMatRenderContext, m_pHardwareContext );
DELEGATE_TO_OBJECT_1V( FlipCulling, bool, g_pShaderAPI );
// DEFINE_QUEUED_CALL_1( EnableSinglePassFlashlightMode, bool, IMatRenderContext, m_pHardwareContext );
virtual void EnableSinglePassFlashlightMode( bool bEnable )
{
m_bSinglePassFlashlightMode = bEnable;
m_queue.QueueCall( m_pHardwareContext, &IMatRenderContext::EnableSinglePassFlashlightMode, bEnable );
}
virtual bool SinglePassFlashlightModeEnabled( void ) const { return m_bSinglePassFlashlightMode; }
//--------------------------------------------------------
// Memory allocation calls for queued mesh, et. al.
//--------------------------------------------------------
byte *AllocVertices( int nVerts, int nVertexSize, bool *pUsingExternalMemory );
byte *AllocIndices( int nIndices, int nIndexSize, bool *pUsingExternalMemory );
byte *ReallocVertices( byte *pVerts, int nVertsOld, int nVertsNew, int nVertexSize, bool bExternalMemory );
byte *ReallocIndices( byte *pIndices, int nIndicesOld, int nIndicesNew, int nIndexSize, bool bExternalMemory );
void FreeVertices( byte *pVerts, int nVerts, int nVertexSize );
void FreeIndices( byte *pIndices, int nIndices, int nIndexSize );
//--------------------------------------------------------
// debug logging - no-op in queued context
//--------------------------------------------------------
virtual void Printf( char *fmt, ... ) {};
virtual void PrintfVA( char *fmt, va_list vargs ){};
virtual float Knob( char *knobname, float *setvalue=NULL ) { return 0.0f; };
#if defined( DX_TO_GL_ABSTRACTION ) && !defined( _GAMECONSOLE )
void DoStartupShaderPreloading( void ) {}
#endif
#if defined( INCLUDE_SCALEFORM )
//--------------------------------------------------------
// scaleform calls
//
// *** NOTE - THREAD SAFETY ***
// SFUI is not mutexed. If you add functions to this list check it is safe
// to call them in parallel with the main thread
//--------------------------------------------------------
DEFINE_QUEUED_CALL_5( SetScaleformSlotViewport, int, int, int, int, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( RenderScaleformSlot, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_4( SetScaleformCursorViewport, int, int, int, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_0( RenderScaleformCursor, IMatRenderContext, m_pHardwareContext );
// Unused on PC
DEFINE_QUEUED_CALL_1( ForkRenderScaleformSlot, int, IMatRenderContext, m_pHardwareContext );
DEFINE_QUEUED_CALL_1( JoinRenderScaleformSlot, int, IMatRenderContext, m_pHardwareContext );
void AdvanceAndRenderScaleformSlot( int slot )
{
// always run advance slot on the main thread
ScaleformUI()->AdvanceSlot( slot );
// renderSlot can be queued
RenderScaleformSlot( slot );
}
void AdvanceAndRenderScaleformCursor()
{
// always run advance slot on the main thread
ScaleformUI()->AdvanceCursor();
// renderSlot can be queued
RenderScaleformCursor();
}
#endif // INCLUDE_SCALEFORM
virtual ColorCorrectionHandle_t FindLookup( const char *pName );
private:
void QueueMatrixSync();
void DeferredDrawInstances( int nInstanceCount, const MeshInstanceData_t *pInstances );
#ifndef MS_NO_DYNAMIC_BUFFER_COPY
FORCEINLINE CMemoryStack &Vertices()
{
return m_Vertices;
}
FORCEINLINE CMemoryStack &Indices()
{
return m_Indices;
}
#else
FORCEINLINE CMemoryStack &Vertices()
{
return *m_pVertices;
}
FORCEINLINE CMemoryStack &Indices()
{
return *m_pIndices;
}
#endif
//friend class CMatQueuedMesh;
friend class CCallQueueExternal;
CMatCallQueue m_queue;
CMatQueuedMesh *m_pQueuedMesh;
CMatQueuedMesh *m_pQueuedFlexMesh;
CMatQueuedIndexBuffer *m_pQueuedIndexBuffer;
CMatRenderContextBase *m_pHardwareContext;
int m_iRenderDepth;
int m_WidthBackBuffer, m_HeightBackBuffer;
int m_nBoneCount;
MaterialFogMode_t m_FogMode;
float m_flFogStart;
float m_flFogEnd;
float m_flFogZ;
float m_flFogMaxDensity;
color24 m_FogColor;
CMemoryStack m_Vertices;
CMemoryStack m_Indices;
#ifdef MS_NO_DYNAMIC_BUFFER_COPY
#define RENDER_CONTEXT_STACKS 3
static CMemoryStack s_Vertices[RENDER_CONTEXT_STACKS];
static CMemoryStack s_Indices[RENDER_CONTEXT_STACKS];
static int s_nCurStack;
static bool s_bInitializedStacks;
private:
CMemoryStack *m_pVertices;
CMemoryStack *m_pIndices;
#endif
class CCallQueueExternal : public ICallQueue
{
void QueueFunctorInternal( CFunctor *pFunctor )
{
GET_OUTER( CMatQueuedRenderContext, m_CallQueueExternal )->m_queue.QueueFunctor( pFunctor );
pFunctor->Release();
}
};
CCallQueueExternal m_CallQueueExternal;
};
//-----------------------------------------------------------------------------
#include "tier0/memdbgoff.h"
#endif // CMATQUEUEDRENDERCONTEXT_H
File diff suppressed because it is too large. Load diff
+851
View File
@@ -0,0 +1,851 @@
//========== Copyright (c) 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#ifndef CMATERIALRENDERSTATE_H
#define CMATERIALRENDERSTATE_H
#if defined( _WIN32 )
#pragma once
#endif
#include "tier1/delegates.h"
#include "tier1/utlstack.h"
#include "bitvec.h"
#include "materialsystem_global.h"
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/ishaderapi.h"
#include "imaterialinternal.h"
#include "shadersystem.h"
#include "imorphinternal.h"
#include "isubdinternal.h"
#include "imatrendercontextinternal.h"
#include "occlusionquerymgr.h"
#include "materialsystem/MaterialSystemUtil.h"
#include "tier1/memstack.h"
#ifndef MATSYS_INTERNAL
#error "This file is private to the implementation of IMaterialSystem/IMaterialSystemInternal"
#endif
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class ITextureInternal;
class CMaterialSystem;
class CMatLightmaps;
class CMatPaintmaps;
typedef intp ShaderAPITextureHandle_t;
class IMorphMgrRenderContext;
class CMatCallQueue;
//-----------------------------------------------------------------------------
// Render targets
//-----------------------------------------------------------------------------
#if !defined( _X360 ) && !defined( _PS3 )
#define MAX_RENDER_TARGETS 4
#else
#define MAX_RENDER_TARGETS 1
#endif
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
class CMatRenderContextBase : public CRefCounted1<IMatRenderContextInternal>
{
public:
virtual void InitializeFrom( CMatRenderContextBase *pInitialState );
InitReturnVal_t Init();
void Shutdown();
void CompactMemory();
void SetFrameTime( float frameTime ) { m_FrameTime = frameTime; }
ICallQueue * GetCallQueue() { return NULL; }
CMatCallQueue * GetCallQueueInternal() { return NULL; }
ITexture * GetRenderTarget( void );
ITexture * GetRenderTargetEx( int nRenderTargetID );
IMaterialInternal* GetCurrentMaterialInternal() const { return m_pCurrentMaterial; }
virtual void SetCurrentMaterialInternal(IMaterialInternal* pCurrentMaterial) {
m_pCurrentMaterial = pCurrentMaterial;
Assert( (m_pCurrentMaterial == NULL) || ((IMaterialInternal *)m_pCurrentMaterial)->IsRealTimeVersion() );
}
IMaterial * GetCurrentMaterial() { return GetCurrentMaterialInternal(); }
virtual void * GetCurrentProxy() { return m_pCurrentProxyData; }
virtual void SetCurrentProxy( void *pProxyData ) { m_pCurrentProxyData = pProxyData; }
void Bind( IMaterial *material, void *proxyData = NULL );
void BindLightmapPage( int lightmapPageID );
void BindLocalCubemap( ITexture *pTexture );
// matrix api
void MatrixMode( MaterialMatrixMode_t);
void PushMatrix();
void PopMatrix();
void LoadMatrix( const VMatrix& matrix );
void LoadMatrix( const matrix3x4_t& matrix );
void MultMatrix( const VMatrix& matrix );
void MultMatrixLocal( const VMatrix& matrix );
void MultMatrix( const matrix3x4_t& matrix );
void MultMatrixLocal( const matrix3x4_t& matrix );
void GetMatrix( MaterialMatrixMode_t matrixMode, VMatrix *pMatrix );
void GetMatrix( MaterialMatrixMode_t matrixMode, matrix3x4_t *pMatrix );
void LoadIdentity();
void Ortho( double, double, double, double, double, double);
void PerspectiveX( double, double, double, double);
void PerspectiveOffCenterX( double, double, double, double, double, double, double, double );
void PickMatrix( int, int, int, int);
void Rotate( float, float, float, float);
void Translate( float, float, float);
void Scale( float, float, float);
// end matrix api
// Set the current texture that is a copy of the framebuffer.
void SetFrameBufferCopyTexture( ITexture *pTexture, int textureIndex );
ITexture * GetFrameBufferCopyTexture( int textureIndex );
void SetHeightClipMode( MaterialHeightClipMode_t mode );
MaterialHeightClipMode_t GetHeightClipMode( void );
void SetHeightClipZ( float z );
bool EnableClipping( bool bEnable );
void SetRenderTarget( ITexture *pTexture );
void SetRenderTargetEx( int nRenderTargetID, ITexture *pTexture );
void Viewport( int x, int y, int width, int height );
void PushRenderTargetAndViewport( );
void PushRenderTargetAndViewport( ITexture *pTexture );
void PushRenderTargetAndViewport( ITexture *pTexture, int nViewX, int nViewY, int nViewW, int nViewH );
void PushRenderTargetAndViewport( ITexture *pTexture, ITexture *pDepthTexture, int nViewX, int nViewY, int nViewW, int nViewH );
void PopRenderTargetAndViewport( void );
void SyncMatrices();
void SyncMatrix( MaterialMatrixMode_t );
const VMatrix & AccessCurrentMatrix() const { return m_pCurMatrixItem->matrix; }
ShaderAPITextureHandle_t GetLightmapTexture( int nLightmapPage );
ShaderAPITextureHandle_t GetPaintmapTexture( int nLightmapPage );
virtual void UpdateHeightClipUserClipPlane( void ) {}
virtual void ApplyCustomClipPlanes( void ) {}
float ComputePixelDiameterOfSphere( const Vector& origin, float flRadius );
float ComputePixelWidthOfSphere( const Vector& origin, float flRadius ); // FIXME: REMOVE THIS FUNCTION!
virtual void GetWorldSpaceCameraPosition( Vector *pCameraPos );
virtual void GetWorldSpaceCameraVectors( Vector *pVecForward, Vector *pVecRight, Vector *pVecUp );
Vector GetToneMappingScaleLinear();
// Inherited from IMaterialSystemInternal
int GetLightmapPage( void );
virtual void * LockRenderData( int nSizeInBytes );
virtual void UnlockRenderData( void *pData );
virtual void AddRefRenderData();
virtual void ReleaseRenderData();
virtual bool IsRenderData( const void *pData ) const;
void MarkRenderDataUnused( bool bFrameEnd );
int RenderDataSizeUsed() const;
// debugging
virtual void PrintfVA( char *fmt, va_list vargs );
virtual void Printf( char *fmt, ... );
virtual float Knob( char *knobname, float *setvalue = NULL );
protected:
enum MatrixStackFlags_t
{
MSF_DIRTY = ( 1 << 0 ),
MSF_IDENTITY = ( 1 << 1 ),
};
struct MatrixStackItem_t
{
VMatrix matrix;
unsigned flags;
};
struct RenderTargetStackElement_t
{
// The render target
ITexture *m_pRenderTargets[MAX_RENDER_TARGETS];
// Optional depth texture (used for shadow mapping)
ITexture *m_pDepthTexture;
// Viewport dimensions
int m_nViewX;
int m_nViewY;
int m_nViewW;
int m_nViewH;
};
struct ScissorRectStackElement_t
{
int nLeft;
int nTop;
int nRight;
int nBottom;
};
struct PlaneStackElement
{
float fValues[4];
bool bHack_IsHeightClipPlane; //used to hack in compatibility between the user clip planes and the existing height clip plane code
//I'm doing the hack this way to retain modder's flexibility to mess with clip plane ordering so that they can make special hacks on their side if necessary
PlaneStackElement( void ) : bHack_IsHeightClipPlane( false ) { };
};
protected:
CMatRenderContextBase( );
virtual void CommitRenderTargetAndViewport( void ) {}
void RecomputeViewState();
void RecomputeViewProjState();
void CurrentMatrixChanged();
virtual void OnRenderDataUnreferenced() {}
protected:
IMaterialInternal * m_pCurrentMaterial;
void* m_pCurrentProxyData;
// The lightmap page
int m_lightmapPageID;
ITextureInternal * m_pUserDefinedLightmap;
ITexture * m_pLocalCubemapTexture;
ITexture * m_pCurrentFrameBufferCopyTexture[MAX_FB_TEXTURES];
MaterialHeightClipMode_t m_HeightClipMode;
float m_HeightClipZ;
// The currently bound morph target
IMorphInternal * m_pBoundMorph;
IMorphMgrRenderContext *m_pMorphRenderContext;
// Intially a stack of 32 elements allocated, growing by 16 on overflows
CUtlStack< RenderTargetStackElement_t > m_RenderTargetStack;
// Intially a stack of 32 elements allocated, growing by 16 on overflows
CUtlStack< ScissorRectStackElement_t > m_ScissorRectStack;
MaterialMatrixMode_t m_MatrixMode;
MatrixStackItem_t * m_pCurMatrixItem;
CUtlStack<MatrixStackItem_t> m_MatrixStacks[NUM_MATRIX_MODES];
// View state
VMatrix m_viewProjMatrix;
Vector m_vecViewOrigin;
Vector m_vecViewForward;
Vector m_vecViewUp;
Vector m_vecViewRight;
float m_FrameTime;
Vector m_LastSetToneMapScale;
ShaderViewport_t m_Viewport;
CMaterialSystem * m_pMaterialSystem;
static CMemoryStack sm_RenderData[2];
static int sm_nRenderLockCount;
static int sm_nRenderStack;
static MemoryStackMark_t sm_nRenderCurrentAllocPoint;
static int sm_nInitializeCount;
bool m_bFlashlightEnable : 1;
bool m_bDirtyViewState : 1;
bool m_bDirtyViewProjState : 1;
bool m_bEnableClipping : 1;
bool m_bFullFrameDepthIsValid : 1;
bool m_bRenderingPaint : 1;
bool m_bCullingEnabledForSinglePassFlashlight : 1;
bool m_bSinglePassFlashlightMode : 1;
bool m_bCascadedShadowMappingEnabled : 1;
};
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
#if defined( _PS3 ) || defined( _OSX )
#define g_pShaderAPI ShaderAPI()
#endif
class CMatRenderContext : public CMatRenderContextBase
{
typedef CMatRenderContextBase BaseClass;
public:
CMatRenderContext();
InitReturnVal_t Init( CMaterialSystem *pMaterialSystem );
void Shutdown();
void BeginRender();
void EndRender();
void Flush( bool flushHardware = false );
void SwapBuffers();
void OnReleaseShaderObjects();
DELEGATE_TO_OBJECT_0V( EvictManagedResources, g_pShaderAPI );
// Set the current texture that is a copy of the framebuffer.
void SetFrameBufferCopyTexture( ITexture *pTexture, int textureIndex );
IMesh * CreateStaticMesh( VertexFormat_t vertexFormat, const char *pTextureBudgetGroup, IMaterial * pMaterial = NULL, VertexStreamSpec_t *pStreamSpec = NULL );
DELEGATE_TO_OBJECT_1V( DestroyStaticMesh, IMesh *, g_pShaderDevice );
IMesh * GetDynamicMesh( bool buffered, IMesh* pVertexOverride = 0, IMesh* pIndexOverride = 0, IMaterial *pAutoBind = 0 );
virtual IMesh* GetDynamicMeshEx( VertexFormat_t vertexFormat, bool bBuffered = true, IMesh* pVertexOverride = 0, IMesh* pIndexOverride = 0, IMaterial *pAutoBind = 0 );
DELEGATE_TO_OBJECT_0( IMesh *, GetFlexMesh, g_pShaderAPI );
// ------------ New Vertex/Index Buffer interface ----------------------------
IVertexBuffer *CreateStaticVertexBuffer( VertexFormat_t fmt, int nVertexCount, const char *pBudgetGroup )
{
return g_pShaderDevice->CreateVertexBuffer( SHADER_BUFFER_TYPE_STATIC, fmt, nVertexCount, pBudgetGroup );
}
IIndexBuffer *CreateStaticIndexBuffer( MaterialIndexFormat_t fmt, int nIndexCount, const char *pBudgetGroup )
{
return g_pShaderDevice->CreateIndexBuffer( SHADER_BUFFER_TYPE_STATIC, fmt, nIndexCount, pBudgetGroup );
}
DELEGATE_TO_OBJECT_1V( DestroyVertexBuffer, IVertexBuffer *, g_pShaderDevice );
DELEGATE_TO_OBJECT_1V( DestroyIndexBuffer, IIndexBuffer *, g_pShaderDevice );
DELEGATE_TO_OBJECT_3( IVertexBuffer *, GetDynamicVertexBuffer, int, VertexFormat_t, bool, g_pShaderDevice );
DELEGATE_TO_OBJECT_0( IIndexBuffer *, GetDynamicIndexBuffer, g_pShaderDevice );
DELEGATE_TO_OBJECT_7V( BindVertexBuffer, int, IVertexBuffer *, int, int, int, VertexFormat_t, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_2V( BindIndexBuffer, IIndexBuffer *, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_3V( Draw, MaterialPrimitiveType_t, int, int, g_pShaderAPI );
// ------------ End ----------------------------
void BindLocalCubemap( ITexture *pTexture );
ITexture * GetLocalCubemap( void );
void SetRenderTargetEx( int nRenderTargetID, ITexture *pTexture );
void GetRenderTargetDimensions( int &width, int &height) const;
// matrix api
void MatrixMode( MaterialMatrixMode_t);
void PushMatrix();
void PopMatrix();
void LoadMatrix( const VMatrix& matrix );
void LoadMatrix( const matrix3x4_t& matrix );
void MultMatrix( const VMatrix& matrix );
void MultMatrixLocal( const VMatrix& matrix );
void MultMatrix( const matrix3x4_t& matrix );
void MultMatrixLocal( const matrix3x4_t& matrix );
void GetMatrix( MaterialMatrixMode_t matrixMode, VMatrix *pMatrix );
void GetMatrix( MaterialMatrixMode_t matrixMode, matrix3x4_t *pMatrix );
void LoadIdentity();
void Ortho( double, double, double, double, double, double);
void PerspectiveX( double, double, double, double);
void PerspectiveOffCenterX( double, double, double, double, double, double, double, double );
void PickMatrix( int, int, int, int);
void Rotate( float, float, float, float);
void Translate( float, float, float);
void Scale( float, float, float);
// end matrix api
void SyncMatrices();
void SyncMatrix( MaterialMatrixMode_t );
bool TestMatrixSync( MaterialMatrixMode_t );
void ForceSyncMatrix( MaterialMatrixMode_t );
ShaderAPITextureHandle_t GetLightmapTexture( int nLightmapPage );
ShaderAPITextureHandle_t GetPaintmapTexture( int nLightmapPage );
// Allows us to override the depth buffer setting of a material
DELEGATE_TO_OBJECT_3V( OverrideDepthEnable, bool, bool, bool, g_pShaderAPI );
DELEGATE_TO_OBJECT_2V( OverrideAlphaWriteEnable, bool, bool, g_pShaderAPI );
DELEGATE_TO_OBJECT_2V( OverrideColorWriteEnable, bool, bool, g_pShaderAPI );
// FIXME: This is a hack required for NVidia/XBox, can they fix in drivers?
void DrawScreenSpaceQuad( IMaterial* pMaterial );
int CompareMaterialCombos( IMaterial *pMaterial1, IMaterial *pMaterial2, int lightMapID1, int lightMapID2 );
void Bind( IMaterial *material, void *proxyData = NULL );
void BindLightmapPage( int lightmapPageID );
void BindPaintTexture( ITexture *pTexture );
DELEGATE_TO_OBJECT_2V( SetLights, int, const LightDesc_t *, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( SetLightingOrigin, Vector, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( SetAmbientLightCube, LightCube_t, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( DisableAllLocalLights, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( SetLightingState, const MaterialLightingState_t&, g_pShaderAPI );
void CopyRenderTargetToTexture( ITexture *pTexture );
void ClearBuffers( bool bClearColor, bool bClearDepth, bool bClearStencil );
DELEGATE_TO_OBJECT_3V( ClearColor3ub, unsigned char, unsigned char, unsigned char, g_pShaderAPI );
DELEGATE_TO_OBJECT_4V( ClearColor4ub, unsigned char, unsigned char, unsigned char, unsigned char, g_pShaderAPI );
DELEGATE_TO_OBJECT_2V( ClearBuffersObeyStencil, bool, bool, g_pShaderAPI );
DELEGATE_TO_OBJECT_3V( ClearBuffersObeyStencilEx, bool, bool, bool, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( PerformFullScreenStencilOperation, g_pShaderAPI );
// read to a unsigned char rgb image.
DELEGATE_TO_OBJECT_6V( ReadPixels, int, int, int, int, unsigned char *, ImageFormat, g_pShaderAPI );
DELEGATE_TO_OBJECT_7V( ReadPixels, int, int, int, int, unsigned char *, ImageFormat, ITexture *, g_pShaderAPI );
DELEGATE_TO_OBJECT_6V( ReadPixelsAsync, int, int, int, int, unsigned char *, ImageFormat, g_pShaderAPI );
DELEGATE_TO_OBJECT_7V( ReadPixelsAsync, int, int, int, int, unsigned char *, ImageFormat, ITexture *, g_pShaderAPI );
DELEGATE_TO_OBJECT_8V( ReadPixelsAsync, int, int, int, int, unsigned char *, ImageFormat, ITexture *, CThreadEvent *, g_pShaderAPI );
DELEGATE_TO_OBJECT_6V( ReadPixelsAsyncGetResult, int, int, int, int, unsigned char *, ImageFormat, g_pShaderAPI );
DELEGATE_TO_OBJECT_7V( ReadPixelsAsyncGetResult, int, int, int, int, unsigned char *, ImageFormat, CThreadEvent *, g_pShaderAPI );
void ReadPixelsAndStretch( Rect_t *pSrcRect, Rect_t *pDstRect, unsigned char *pBuffer, ImageFormat dstFormat, int nDstStride ) { g_pShaderAPI->ReadPixels( pSrcRect, pDstRect, pBuffer, dstFormat, nDstStride ); }
// Gets/sets viewport
void Viewport( int x, int y, int width, int height );
void GetViewport( int& x, int& y, int& width, int& height ) const;
virtual void DepthRange( float zNear, float zFar );
// Selection mode methods
DELEGATE_TO_OBJECT_1( int, SelectionMode, bool, g_pShaderAPI );
DELEGATE_TO_OBJECT_2V( SelectionBuffer, unsigned int *, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( ClearSelectionNames, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( LoadSelectionName, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( PushSelectionName, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( PopSelectionName, g_pShaderAPI );
// Sets the cull mode
DELEGATE_TO_OBJECT_1V( CullMode, MaterialCullMode_t, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( FlipCullMode, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( BeginGeneratingCSMs, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( EndGeneratingCSMs, g_pShaderAPI );
DELEGATE_TO_OBJECT_3V( PerpareForCascadeDraw, int, float, float, g_pShaderAPI );
// Sets the number of bones for skinning
DELEGATE_TO_OBJECT_1V( SetNumBoneWeights, int, g_pShaderAPI );
void LoadBoneMatrix( int boneIndex, const matrix3x4_t& matrix );
DELEGATE_TO_OBJECT_3V( SetFlexWeights, int, int, const MorphWeight_t*, g_pShaderAPI );
// Fog-related methods
void FogMode( MaterialFogMode_t fogMode ) { g_pShaderAPI->SceneFogMode( fogMode ); }
DELEGATE_TO_OBJECT_1V( FogStart, float, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( FogEnd, float, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( SetFogZ, float, g_pShaderAPI );
void FogColor3f( float r, float g, float b );
void FogColor3fv( const float* rgb );
void FogColor3ub( unsigned char r, unsigned char g, unsigned char b ) { g_pShaderAPI->SceneFogColor3ub( r, g, b ); }
void FogColor3ubv( unsigned char const* rgb );
void FogMaxDensity( float flMaxDensity );
MaterialFogMode_t GetFogMode( void ) { return g_pShaderAPI->GetSceneFogMode(); }
void GetFogColor( unsigned char *rgb ) { g_pShaderAPI->GetSceneFogColor( rgb ); }
DELEGATE_TO_OBJECT_3V( GetFogDistances, float *, float *, float *, g_pShaderAPI );
int GetCurrentNumBones( ) const { return g_pShaderAPI->GetCurrentNumBones(); }
// Bind standard textures
void BindStandardTexture( Sampler_t sampler, TextureBindFlags_t nBindFlags, StandardTextureId_t id );
ShaderAPITextureHandle_t GetStandardTexture( StandardTextureId_t id );
virtual void BindStandardVertexTexture( VertexTextureSampler_t sampler, StandardTextureId_t id );
virtual void GetStandardTextureDimensions( int *pWidth, int *pHeight, StandardTextureId_t id );
virtual float GetSubDHeight();
// By default, the material system applies the VIEW and PROJECTION matrices to the user clip
// planes (which are specified in world space) to generate projection-space user clip planes
// Occasionally (for the particle system in hl2, for example), we want to override that
// behavior and explictly specify a ViewProj transform for user clip planes
DELEGATE_TO_OBJECT_1V( EnableUserClipTransformOverride, bool, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( UserClipTransform, const VMatrix &, g_pShaderAPI );
// Gets the window size
DELEGATE_TO_OBJECT_2VC( GetWindowSize, int &, int &, g_pShaderDevice );
// Methods related to occlusion query
OcclusionQueryObjectHandle_t CreateOcclusionQueryObject();
DELEGATE_TO_OBJECT_1V( DestroyOcclusionQueryObject, OcclusionQueryObjectHandle_t, g_pOcclusionQueryMgr );
DELEGATE_TO_OBJECT_1V( BeginOcclusionQueryDrawing, OcclusionQueryObjectHandle_t, g_pOcclusionQueryMgr );
DELEGATE_TO_OBJECT_1V( EndOcclusionQueryDrawing, OcclusionQueryObjectHandle_t, g_pOcclusionQueryMgr );
DELEGATE_TO_OBJECT_1V( ResetOcclusionQueryObject, OcclusionQueryObjectHandle_t, g_pOcclusionQueryMgr );
int OcclusionQuery_GetNumPixelsRendered( OcclusionQueryObjectHandle_t h );
bool InFlashlightMode() const;
bool IsRenderingPaint() const;
virtual void SetFlashlightMode( bool bEnable );
virtual void SetRenderingPaint( bool bEnable );
bool GetFlashlightMode( ) const;
virtual bool IsCascadedShadowMapping() const;
virtual void SetCascadedShadowMapping( bool bEnable );
virtual void SetCascadedShadowMappingState( const CascadedShadowMappingState_t &state, ITexture *pDepthTextureAtlas );
virtual bool IsCullingEnabledForSinglePassFlashlight() const;
virtual void EnableCullingForSinglePassFlashlight( bool bEnable );
void SetFlashlightState( const FlashlightState_t &state, const VMatrix &worldToTexture );
void SetFlashlightStateEx( const FlashlightState_t &state, const VMatrix &worldToTexture, ITexture *pFlashlightDepthTexture );
void PushScissorRect( const int nLeft, const int nTop, const int nRight, const int nBottom );
void PopScissorRect();
#if defined( _GAMECONSOLE )
void BeginConsoleZPass( const WorldListIndicesInfo_t &indicesInfo ){ BeginConsoleZPass2( indicesInfo.m_nTotalIndices ); }
#endif
// Creates/destroys morph data associated w/ a particular material
IMorph * CreateMorph( MorphFormat_t format, const char *pDebugName );
void DestroyMorph( IMorph *pMorph );
void BindMorph( IMorph *pMorph );
// Gets the bound morph's vertex format; returns 0 if no morph is bound
MorphFormat_t GetBoundMorphFormat();
void DrawScreenSpaceRectangle( IMaterial *pMaterial,
int destx, int desty,
int width, int height,
float src_texture_x0, float src_texture_y0, // which texel you want to appear at
// destx/y
float src_texture_x1, float src_texture_y1, // which texel you want to appear at
// destx+width-1, desty+height-1
int src_texture_width, int src_texture_height, // needed for fixup
void *pClientRenderable = NULL,
int nXDice = 1,
int nYDice = 1 );
// custom clip planes, beware that only the most recently pushed plane will actually be used in some hardware configurations
void PushCustomClipPlane( const float *fPlane );
void PopCustomClipPlane( void );
void ApplyCustomClipPlanes( void ); //updates the clip planes based on how many are supported by the hardware using the top of the stack first, at the end of the stack, the height clip plane will be evaluated
// Force writes only when z matches. . . useful for stenciling things out
// by rendering the desired Z values ahead of time.
DELEGATE_TO_OBJECT_1V( ForceDepthFuncEquals, bool, g_pShaderAPI );
// Two methods of building lightmap bits from floating point src data
// What are the lightmap dimensions?
void GetLightmapDimensions( int *w, int *h );
void DrawClearBufferQuad( unsigned char r, unsigned char g, unsigned char b, unsigned char a, bool bClearColor, bool bClearAlpha, bool bClearDepth );
#ifdef _PS3
void DrawReloadZcullQuad();
#endif // _PS3
void UpdateHeightClipUserClipPlane( void );
// Private routine called by render target stack push and pop routines to commit new top of stack to the device
void CommitRenderTargetAndViewport( void );
void SyncToken( const char *pToken );
void BindLightmapTexture( ITexture *pLightmapTexture );
void CopyRenderTargetToTextureEx( ITexture *pTexture, int nRenderTargetID, Rect_t *pSrcRect, Rect_t *pDstRect = NULL );
void CopyTextureToRenderTargetEx( int nRenderTargetID, ITexture *pTexture, Rect_t *pSrcRect, Rect_t *pDstRect = NULL );
DELEGATE_TO_OBJECT_2V( SetFloatRenderingParameter, int, float, g_pShaderAPI );
DELEGATE_TO_OBJECT_2V( SetIntRenderingParameter, int, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_2V( SetTextureRenderingParameter, int, ITexture *, g_pShaderAPI );
DELEGATE_TO_OBJECT_2V( SetVectorRenderingParameter, int, const Vector &, g_pShaderAPI );
DELEGATE_TO_OBJECT_1C( float, GetFloatRenderingParameter, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_1C( int, GetIntRenderingParameter, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_1C( ITexture *, GetTextureRenderingParameter, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_1C( Vector, GetVectorRenderingParameter, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_4V( GetMaxToRender, IMesh *, bool, int *, int *, g_pShaderAPI );
DELEGATE_TO_OBJECT_1( int, GetMaxVerticesToRender, IMaterial *, g_pShaderAPI );
DELEGATE_TO_OBJECT_0( int, GetMaxIndicesToRender, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( SetStencilState, const ShaderStencilState_t &, g_pShaderAPI );
DELEGATE_TO_OBJECT_5V( ClearStencilBufferRectangle, int, int, int, int, int, g_pShaderAPI );
// PIX support
DELEGATE_TO_OBJECT_2V( BeginPIXEvent, unsigned long, const char *, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( EndPIXEvent, g_pShaderAPI );
DELEGATE_TO_OBJECT_2V( SetPIXMarker, unsigned long, const char *, g_pShaderAPI );
DELEGATE_TO_OBJECT_2V( SetShadowDepthBiasFactors, float, float, g_pShaderAPI );
void BeginBatch( IMesh* pIndices );
void BindBatch( IMesh* pVertices, IMaterial *pAutoBind = NULL );
void DrawBatch( MaterialPrimitiveType_t primType, int firstIndex, int numIndices );
void EndBatch();
void SetToneMappingScaleLinear( const Vector &scale );
bool OnDrawMesh( IMesh *pMesh, int firstIndex, int numIndices );
bool OnDrawMesh( IMesh *pMesh, CPrimList *pLists, int nLists );
bool OnDrawMeshModulated( IMesh *pMesh, const Vector4D &diffuseModulation, int firstIndex, int numIndices );
bool OnSetFlexMesh( IMesh *pStaticMesh, IMesh *pMesh, int nVertexOffsetInBytes ) { return true; }
bool OnSetColorMesh( IMesh *pStaticMesh, IMesh *pMesh, int nVertexOffsetInBytes ) { return true; }
bool OnSetPrimitiveType( IMesh *pMesh, MaterialPrimitiveType_t type ) { return true; }
CMaterialSystem *GetMaterialSystem() const;
DELEGATE_TO_OBJECT_0V( ForceHardwareSync, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( BeginFrame, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( EndFrame, g_pShaderAPI );
virtual void BeginMorphAccumulation();
virtual void EndMorphAccumulation();
virtual void AccumulateMorph( IMorph* pMorph, int nMorphCount, const MorphWeight_t* pWeights );
virtual bool GetMorphAccumulatorTexCoord( Vector2D *pTexCoord, IMorph *pMorph, int nVertex );
// Subdivision surface interface
virtual int GetSubDBufferWidth();
virtual float *LockSubDBuffer( int nNumRows );
virtual void UnlockSubDBuffer();
DELEGATE_TO_OBJECT_1V( PushDeformation, const DeformationBase_t *, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( PopDeformation, g_pShaderAPI );
DELEGATE_TO_OBJECT_0C( int, GetNumActiveDeformations, g_pShaderAPI );
// Color correction related methods..
DELEGATE_TO_OBJECT_1V( EnableColorCorrection, bool, g_pColorCorrectionSystem );
DELEGATE_TO_OBJECT_1( ColorCorrectionHandle_t, AddLookup, const char *, g_pColorCorrectionSystem );
DELEGATE_TO_OBJECT_1( bool, RemoveLookup, ColorCorrectionHandle_t, g_pColorCorrectionSystem );
DELEGATE_TO_OBJECT_1V( LockLookup, ColorCorrectionHandle_t, g_pColorCorrectionSystem );
DELEGATE_TO_OBJECT_2V( LoadLookup, ColorCorrectionHandle_t, const char *, g_pColorCorrectionSystem );
DELEGATE_TO_OBJECT_1V( UnlockLookup, ColorCorrectionHandle_t, g_pColorCorrectionSystem );
DELEGATE_TO_OBJECT_2V( SetLookupWeight, ColorCorrectionHandle_t, float, g_pColorCorrectionSystem );
DELEGATE_TO_OBJECT_0V( ResetLookupWeights, g_pColorCorrectionSystem );
DELEGATE_TO_OBJECT_2V( SetResetable, ColorCorrectionHandle_t, bool, g_pColorCorrectionSystem );
virtual void SetFullScreenDepthTextureValidityFlag( bool bIsValid );
#if defined( _X360 )
DELEGATE_TO_OBJECT_1V( PushVertexShaderGPRAllocation, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( PopVertexShaderGPRAllocation, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( FlushHiStencil, g_pShaderAPI );
#endif
#if defined( _GAMECONSOLE )
DELEGATE_TO_OBJECT_1V( BeginConsoleZPass2, int, g_pShaderAPI );
DELEGATE_TO_OBJECT_0V( EndConsoleZPass, g_pShaderAPI );
#endif
#if defined( _PS3 )
DELEGATE_TO_OBJECT_0V( FlushTextureCache, g_pShaderAPI );
#endif
DELEGATE_TO_OBJECT_1V( AntiAliasingHint, int, g_pShaderAPI );
// A special path used to tick the front buffer while loading on the 360
virtual void SetNonInteractiveLogoTexture( ITexture *pTexture, float flNormalizedX, float flNormalizedY, float flNormalizedW, float flNormalizedH );
virtual void SetNonInteractivePacifierTexture( ITexture *pTexture, float flNormalizedX, float flNormalizedY, float flNormalizedSize );
virtual void SetNonInteractiveTempFullscreenBuffer( ITexture *pTexture, MaterialNonInteractiveMode_t mode );
virtual void EnableNonInteractiveMode( MaterialNonInteractiveMode_t mode );
virtual void RefreshFrontBufferNonInteractive();
DELEGATE_TO_OBJECT_1V( FlipCulling, bool, g_pShaderAPI );
// DELEGATE_TO_OBJECT_1V( EnableSinglePassFlashlightMode, bool, g_pShaderAPI );
virtual void EnableSinglePassFlashlightMode( bool bEnable );
virtual bool SinglePassFlashlightModeEnabled() const;
DELEGATE_TO_OBJECT_2V( DrawInstances, int, const MeshInstanceData_t *, g_pShaderAPI );
DELEGATE_TO_OBJECT_1V( UpdateGameTime, float, g_pShaderAPI );
//--------------------------------------------------------
// debug logging - no-op in queued context
//--------------------------------------------------------
virtual void Printf( char *fmt, ... );
virtual void PrintfVA( char *fmt, va_list vargs );;
virtual float Knob( char *knobname, float *setvalue=NULL );
#if defined( DX_TO_GL_ABSTRACTION ) && !defined( _GAMECONSOLE )
void DoStartupShaderPreloading( void );
#endif
//---------------------------------------------------------
#if defined( INCLUDE_SCALEFORM )
//--------------------------------------------------------
// scaleform interaction
//--------------------------------------------------------
void SetScaleformSlotViewport( int slot, int x, int y, int w, int h ) { ScaleformUI()->SetSlotViewport( slot, x, y, w, h ); }
void RenderScaleformSlot( int slot ) { ScaleformUI()->RenderSlot( slot ); }
void ForkRenderScaleformSlot( int slot ) { ScaleformUI()->ForkRenderSlot( slot ); }
void JoinRenderScaleformSlot( int slot ) { ScaleformUI()->JoinRenderSlot( slot ); }
void SetScaleformCursorViewport( int x, int y, int w, int h ) { ScaleformUI()->SetCursorViewport( x, y, w, h ); }
void RenderScaleformCursor( void ) { ScaleformUI()->RenderCursor(); }
void AdvanceAndRenderScaleformSlot( int slot ) { ScaleformUI()->AdvanceSlot( slot ); ScaleformUI()->RenderSlot( slot ); }
void AdvanceAndRenderScaleformCursor() { ScaleformUI()->AdvanceCursor(); ScaleformUI()->RenderCursor(); }
#endif // INCLUDE_SCALEFORM
DELEGATE_TO_OBJECT_1( ColorCorrectionHandle_t, FindLookup, const char *, g_pColorCorrectionSystem );
//---------------------------------------------------------
protected:
IMaterialInternal *GetMaterialInternal( MaterialHandle_t ) const;
IMaterialInternal *GetDrawFlatMaterial();
IMaterialInternal *GetRenderTargetBlitMaterial();
IMaterialInternal *GetBufferClearObeyStencil( int i );
IMaterialInternal *GetReloadZcullMaterial();
ShaderAPITextureHandle_t GetFullbrightLightmapTextureHandle() const;
ShaderAPITextureHandle_t GetFullbrightBumpedLightmapTextureHandle() const;
ShaderAPITextureHandle_t GetBlackTextureHandle() const;
ShaderAPITextureHandle_t GetBlackAlphaZeroTextureHandle() const;
ShaderAPITextureHandle_t GetFlatNormalTextureHandle() const;
ShaderAPITextureHandle_t GetFlatSSBumpTextureHandle() const;
ShaderAPITextureHandle_t GetGreyTextureHandle() const;
ShaderAPITextureHandle_t GetGreyAlphaZeroTextureHandle() const;
ShaderAPITextureHandle_t GetWhiteTextureHandle() const;
ShaderAPITextureHandle_t GetFrameBufferTextureHandle() const;
ShaderAPITextureHandle_t GetMaxDepthTextureHandle() const;
// Helper methods
void BindLightmap( Sampler_t stage, TextureBindFlags_t nBindFlags );
void BindBumpLightmap( Sampler_t stage, TextureBindFlags_t nBindFlags );
void BindFullbrightLightmap( Sampler_t stage, TextureBindFlags_t nBindFlags );
void BindBumpedFullbrightLightmap( Sampler_t stage, TextureBindFlags_t nBindFlags );
void BindPaintTexture( Sampler_t stage, TextureBindFlags_t nBindFlags );
virtual void OnRenderDataUnreferenced();
const CMatLightmaps *GetLightmaps() const;
CMatLightmaps *GetLightmaps();
const CMatPaintmaps *GetPaintmaps() const;
CMatPaintmaps *GetPaintmaps();
CUtlVector<PlaneStackElement> m_CustomClipPlanes; //implemented as a vector so we can remove in special ways
IMesh *m_pBatchIndices;
IMesh *m_pBatchMesh;
IIndexBuffer *m_pCurrentIndexBuffer;
CTextureReference m_pNonInteractiveTempFullscreenBuffer[MATERIAL_NON_INTERACTIVE_MODE_COUNT];
CTextureReference m_pNonInteractivePacifier;
CTextureReference m_pNonInteractiveLogo;
MaterialNonInteractiveMode_t m_NonInteractiveMode;
float m_flNormalizedX;
float m_flNormalizedY;
float m_flNormalizedSize;
float m_flLogoNormalizedX;
float m_flLogoNormalizedY;
float m_flLogoNormalizedW;
float m_flLogoNormalizedH;
};
//-----------------------------------------------------------------------------
inline void CMatRenderContext::LoadBoneMatrix( int boneIndex, const matrix3x4_t& matrix )
{
g_pShaderAPI->LoadBoneMatrix( boneIndex, matrix.Base() );
}
//-----------------------------------------------------------------------------
inline bool CMatRenderContext::InFlashlightMode() const
{
return m_bFlashlightEnable;
}
inline bool CMatRenderContext::IsRenderingPaint() const
{
return m_bRenderingPaint;
}
inline void CMatRenderContext::SetFlashlightState( const FlashlightState_t &state, const VMatrix &worldToTexture )
{
SetFlashlightStateEx( state, worldToTexture, NULL );
}
inline bool CMatRenderContext::IsCascadedShadowMapping() const
{
return m_bCascadedShadowMappingEnabled;
}
inline void CMatRenderContext::SetCascadedShadowMapping( bool bEnable )
{
m_bCascadedShadowMappingEnabled = bEnable;
}
inline float CMatRenderContextBase::ComputePixelWidthOfSphere( const Vector& vecOrigin, float flRadius )
{
return ComputePixelDiameterOfSphere( vecOrigin, flRadius ) * 2.0f;
}
inline void CMatRenderContext::FogColor3ubv( unsigned char const* rgb )
{
g_pShaderAPI->SceneFogColor3ub( rgb[0], rgb[1], rgb[2] );
}
inline void CMatRenderContext::FogMaxDensity( float flMaxDensity )
{
g_pShaderAPI->FogMaxDensity( flMaxDensity );
}
inline ITexture *CMatRenderContext::GetLocalCubemap( void )
{
return m_pLocalCubemapTexture;
}
inline void CMatRenderContextBase::SetRenderTarget( ITexture *pTexture_ )
{
SetRenderTargetEx( 0, pTexture_ );
}
//-----------------------------------------------------------------------------
// Gets the bound morph's vertex format; returns 0 if no morph is bound
//-----------------------------------------------------------------------------
inline MorphFormat_t CMatRenderContext::GetBoundMorphFormat()
{
return m_pBoundMorph ? m_pBoundMorph->GetMorphFormat() : 0;
}
//-----------------------------------------------------------------------------
// Use this to create static vertex and index buffers
//-----------------------------------------------------------------------------
inline IMesh* CMatRenderContext::CreateStaticMesh( VertexFormat_t vertexFormat, const char *pTextureBudgetGroup, IMaterial * pMaterial, VertexStreamSpec_t *pStreamSpec )
{
return g_pShaderDevice->CreateStaticMesh( vertexFormat, pTextureBudgetGroup, pMaterial, pStreamSpec );
}
inline void CMatRenderContext::SyncToken( const char *pToken )
{
#if !defined( _PS3 ) && !defined( _OSX )
if ( g_pShaderAPI )
#endif
{
g_pShaderAPI->SyncToken( pToken );
}
}
inline enum MaterialHeightClipMode_t CMatRenderContextBase::GetHeightClipMode( void )
{
return m_HeightClipMode;
}
inline int CMatRenderContextBase::GetLightmapPage( void )
{
return m_lightmapPageID;
}
inline CMaterialSystem *CMatRenderContext::GetMaterialSystem() const
{
return m_pMaterialSystem;
}
#if defined( _PS3 ) || defined( _OSX )
#undef g_pShaderAPI
#endif
//-----------------------------------------------------------------------------
#endif // CMATERIALRENDERSTATE_H
+212
View File
@@ -0,0 +1,212 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=====================================================================================//
#include <math.h>
#include "mathlib/bumpvects.h"
#include "colorspace.h"
#include "materialsystem_global.h"
#include "IHardwareConfigInternal.h"
#include "materialsystem/materialsystem_config.h"
// NOTE: This has to be the last file included
#include "tier0/memdbgon.h"
//static float texLightToLinear[256]; // texlight (0..255) to linear (0..4)
static float textureToLinear[256]; // texture (0..255) to linear (0..1)
static int linearToTexture[1024]; // linear (0..1) to texture (0..255)
static int linearToScreen[1024]; // linear (0..1) to gamma corrected vertex light (0..255)
float g_LinearToVertex[4096]; // linear (0..4) to screen corrected vertex space (0..1?)
static int linearToLightmap[4096]; // linear (0..4) to screen corrected texture value (0..255)
void ColorSpace::SetGamma( float screenGamma, float texGamma,
float overbright, bool allowCheats, bool linearFrameBuffer )
{
int i, inf;
float g1, g3;
float g;
float brightness = 0.0f; // This used to be configurable. . hardcode to 0.0
if( linearFrameBuffer )
{
screenGamma = 1.0f;
}
g = screenGamma;
// clamp values to prevent cheating in multiplayer
if( !allowCheats )
{
if (brightness > 2.0f)
brightness = 2.0f;
if (g < 1.8f)
g = 1.8f;
}
if (g > 3.0)
g = 3.0;
g = 1.0f / g;
g1 = texGamma * g;
// pow( textureColor, g1 ) converts from on-disk texture space to framebuffer space
if (brightness <= 0.0f)
{
g3 = 0.125;
}
else if (brightness > 1.0f)
{
g3 = 0.05f;
}
else
{
g3 = 0.125f - (brightness * brightness) * 0.075f;
}
for (i=0 ; i<1024 ; i++)
{
float f;
f = i / 1023.0f;
// scale up
if (brightness > 1.0f)
f = f * brightness;
// shift up
if (f <= g3)
f = (f / g3) * 0.125f;
else
f = 0.125f + ((f - g3) / (1.0f - g3)) * 0.875f;
// convert linear space to desired gamma space
inf = ( int )( 255 * pow ( f, g ) );
if (inf < 0)
inf = 0;
if (inf > 255)
inf = 255;
linearToScreen[i] = inf;
}
for (i=0 ; i<256 ; i++)
{
// convert from nonlinear texture space (0..255) to linear space (0..1)
textureToLinear[i] = ( float )pow( i / 255.0f, texGamma );
}
for (i=0 ; i<1024 ; i++)
{
// convert from linear space (0..1) to nonlinear texture space (0..255)
linearToTexture[i] = ( int )( pow( i / 1023.0f, 1.0f / texGamma ) * 255 );
}
#if 0
for (i=0 ; i<256 ; i++)
{
float f;
// convert from nonlinear lightmap space (0..255) to linear space (0..4)
f = ( float )( (i / 255.0f) * sqrt( 4 ) );
f = f * f;
texLightToLinear[i] = f;
}
#endif
float f, overbrightFactor;
// Can't do overbright without texcombine
// UNDONE: Add GAMMA ramp to rectify this
if ( !HardwareConfig() )
{
overbright = 1.0f;
}
if ( overbright == 2.0 )
{
overbrightFactor = 0.5;
}
else if ( overbright == 4.0 )
{
overbrightFactor = 0.25;
}
else
{
overbrightFactor = 1.0;
}
for (i=0 ; i<4096 ; i++)
{
// convert from linear 0..4 (x1024) to screen corrected vertex space (0..1?)
f = ( float )pow ( i/1024.0f, 1.0f / screenGamma );
g_LinearToVertex[i] = f * overbrightFactor;
if (g_LinearToVertex[i] > 1)
g_LinearToVertex[i] = 1;
linearToLightmap[i] = ( int )( f * 255 * overbrightFactor );
if (linearToLightmap[i] > 255)
linearToLightmap[i] = 255;
}
}
// convert texture to linear 0..1 value
float ColorSpace::TextureToLinear( int c )
{
if (c < 0)
return 0;
if (c > 255)
return 1.0f;
return textureToLinear[c];
}
// convert texture to linear 0..1 value
int ColorSpace::LinearToTexture( float f )
{
int i;
i = ( int )( f * 1023.0f ); // assume 0..1 range
if (i < 0)
i = 0;
if (i > 1023)
i = 1023;
return linearToTexture[i];
}
float ColorSpace::TexLightToLinear( int c, int exponent )
{
// return texLightToLinear[ c ];
// optimize me
return ( float )c * ( float )pow( 2.0f, exponent ) * ( 1.0f / 255.0f );
}
// converts 0..1 linear value to screen gamma (0..255)
int ColorSpace::LinearToScreenGamma( float f )
{
int i;
i = ( int )( f * 1023.0f ); // assume 0..1 range
if (i < 0)
i = 0;
if (i > 1023)
i = 1023;
return linearToScreen[i];
}
uint16 ColorSpace::LinearFloatToCorrectedShort( float in )
{
uint16 out;
in = MIN( in * 4096.0, 65535.0 );
out = (uint16) MAX( in, 0.0f );
return out;
}
+456
View File
@@ -0,0 +1,456 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#ifndef COLORSPACE_H
#define COLORSPACE_H
#ifdef _WIN32
#pragma once
#endif
#include "mathlib/mathlib.h"
#include "mathlib/ssemath.h"
#include "mathlib/bumpvects.h"
#include "tier0/dbg.h"
extern float g_LinearToVertex[4096]; // linear (0..4) to screen corrected vertex space (0..1?)
// FIXME!!! Get rid of this. . all of this should be in mathlib
namespace ColorSpace
{
void SetGamma( float screenGamma, float texGamma,
float overbright, bool allowCheats, bool linearFrameBuffer );
// convert texture to linear 0..1 value
float TextureToLinear( int c );
// convert texture to linear 0..1 value
int LinearToTexture( float f );
float TexLightToLinear( int c, int exponent );
// assume 0..4 range
void LinearToLightmap( unsigned char *pDstRGB, const float *pSrcRGB );
// assume 0..4 range
void LinearToBumpedLightmap( const float *linearColor, const float *linearBumpColor1,
const float *linearBumpColor2, const float *linearBumpColor3,
unsigned char *ret, unsigned char *retBump1,
unsigned char *retBump2, unsigned char *retBump3 );
//
void LinearToBumpedLightmapAlpha( const float *linearAlpha, const float *linearBumpAlpha1,
const float *linearBumpAlpha2, const float *linearBumpAlpha3,
unsigned char *ret, unsigned char *retBump1,
unsigned char *retBump2, unsigned char *retBump3 );
// converts 0..1 linear value to screen gamma (0..255)
int LinearToScreenGamma( float f );
FORCEINLINE void LinearToLightmap( unsigned char *pDstRGB, const float *pSrcRGB )
{
Vector tmpVect;
#if 1
int i, j;
for( j = 0; j < 3; j++ )
{
i = RoundFloatToInt( pSrcRGB[j] * 1024 ); // assume 0..4 range
if (i < 0)
{
i = 0;
}
if (i > 4091)
{
i = 4091;
}
tmpVect[j] = g_LinearToVertex[i];
}
#else
tmpVect[0] = LinearToVertexLight( pSrcRGB[0] );
tmpVect[1] = LinearToVertexLight( pSrcRGB[1] );
tmpVect[2] = LinearToVertexLight( pSrcRGB[2] );
#endif
ColorClamp( tmpVect );
pDstRGB[0] = RoundFloatToByte( tmpVect[0] * 255.0f );
pDstRGB[1] = RoundFloatToByte( tmpVect[1] * 255.0f );
pDstRGB[2] = RoundFloatToByte( tmpVect[2] * 255.0f );
}
// Clamp the three values for bumped lighting such that we trade off directionality for brightness.
FORCEINLINE void ColorClampBumped( Vector& color1, Vector& color2, Vector& color3 )
{
Vector maxs;
Vector *colors[3] = { &color1, &color2, &color3 };
maxs[0] = VectorMaximum( color1 );
maxs[1] = VectorMaximum( color2 );
maxs[2] = VectorMaximum( color3 );
// HACK! Clean this up, and add some else statements
#define CONDITION(a,b,c) do { if( maxs[a] >= maxs[b] && maxs[b] >= maxs[c] ) { order[0] = a; order[1] = b; order[2] = c; } } while( 0 )
int order[3];
CONDITION(0,1,2);
CONDITION(0,2,1);
CONDITION(1,0,2);
CONDITION(1,2,0);
CONDITION(2,0,1);
CONDITION(2,1,0);
int i;
for( i = 0; i < 3; i++ )
{
float max = VectorMaximum( *colors[order[i]] );
if( max <= 1.0f )
{
continue;
}
// This channel is too bright. . take half of the amount that we are over and
// add it to the other two channel.
float factorToRedist = ( max - 1.0f ) / max;
Vector colorToRedist = factorToRedist * *colors[order[i]];
*colors[order[i]] -= colorToRedist;
colorToRedist *= 0.5f;
*colors[order[(i+1)%3]] += colorToRedist;
*colors[order[(i+2)%3]] += colorToRedist;
}
ColorClamp( color1 );
ColorClamp( color2 );
ColorClamp( color3 );
if( color1[0] < 0.f ) color1[0] = 0.f;
if( color1[1] < 0.f ) color1[1] = 0.f;
if( color1[2] < 0.f ) color1[2] = 0.f;
if( color2[0] < 0.f ) color2[0] = 0.f;
if( color2[1] < 0.f ) color2[1] = 0.f;
if( color2[2] < 0.f ) color2[2] = 0.f;
if( color3[0] < 0.f ) color3[0] = 0.f;
if( color3[1] < 0.f ) color3[1] = 0.f;
if( color3[2] < 0.f ) color3[2] = 0.f;
}
FORCEINLINE void LinearToBumpedLightmap( const float *linearColor, const float *linearBumpColor1,
const float *linearBumpColor2, const float *linearBumpColor3,
unsigned char *ret, unsigned char *retBump1,
unsigned char *retBump2, unsigned char *retBump3 )
{
const Vector &linearBump1 = *( ( const Vector * )linearBumpColor1 );
const Vector &linearBump2 = *( ( const Vector * )linearBumpColor2 );
const Vector &linearBump3 = *( ( const Vector * )linearBumpColor3 );
Vector gammaGoal;
// gammaGoal is premultiplied by 1/overbright, which we want
gammaGoal[0] = LinearToVertexLight( linearColor[0] );
gammaGoal[1] = LinearToVertexLight( linearColor[1] );
gammaGoal[2] = LinearToVertexLight( linearColor[2] );
Vector bumpAverage = linearBump1;
bumpAverage += linearBump2;
bumpAverage += linearBump3;
bumpAverage *= ( 1.0f / 3.0f );
Vector correctionScale;
if( *( int * )&bumpAverage[0] != 0 && *( int * )&bumpAverage[1] != 0 && *( int * )&bumpAverage[2] != 0 )
{
// fast path when we know that we don't have to worry about divide by zero.
VectorDivide( gammaGoal, bumpAverage, correctionScale );
// correctionScale = gammaGoal / bumpSum;
}
else
{
correctionScale.Init( 0.0f, 0.0f, 0.0f );
if( bumpAverage[0] != 0.0f )
{
correctionScale[0] = gammaGoal[0] / bumpAverage[0];
}
if( bumpAverage[1] != 0.0f )
{
correctionScale[1] = gammaGoal[1] / bumpAverage[1];
}
if( bumpAverage[2] != 0.0f )
{
correctionScale[2] = gammaGoal[2] / bumpAverage[2];
}
}
Vector correctedBumpColor1;
Vector correctedBumpColor2;
Vector correctedBumpColor3;
VectorMultiply( linearBump1, correctionScale, correctedBumpColor1 );
VectorMultiply( linearBump2, correctionScale, correctedBumpColor2 );
VectorMultiply( linearBump3, correctionScale, correctedBumpColor3 );
Vector check = ( correctedBumpColor1 + correctedBumpColor2 + correctedBumpColor3 ) / 3.0f;
ColorClampBumped( correctedBumpColor1, correctedBumpColor2, correctedBumpColor3 );
ret[0] = RoundFloatToByte( gammaGoal[0] * 255.0f );
ret[1] = RoundFloatToByte( gammaGoal[1] * 255.0f );
ret[2] = RoundFloatToByte( gammaGoal[2] * 255.0f );
retBump1[0] = RoundFloatToByte( correctedBumpColor1[0] * 255.0f );
retBump1[1] = RoundFloatToByte( correctedBumpColor1[1] * 255.0f );
retBump1[2] = RoundFloatToByte( correctedBumpColor1[2] * 255.0f );
retBump2[0] = RoundFloatToByte( correctedBumpColor2[0] * 255.0f );
retBump2[1] = RoundFloatToByte( correctedBumpColor2[1] * 255.0f );
retBump2[2] = RoundFloatToByte( correctedBumpColor2[2] * 255.0f );
retBump3[0] = RoundFloatToByte( correctedBumpColor3[0] * 255.0f );
retBump3[1] = RoundFloatToByte( correctedBumpColor3[1] * 255.0f );
retBump3[2] = RoundFloatToByte( correctedBumpColor3[2] * 255.0f );
}
// For use with CSM correct blending output in alpha channel from vrad
// we can go out of 0..1 range if we normalize the bumped alpha data
// so we 'squash' the range to compensate.
// Note - We shouldn't be taking the simple average in the bump case when normalizing anyway
// (i.e. add together and multiply by 0.575 comments below).
// Keeping the averaging as is for consistency with RGB's, etc
FORCEINLINE void LinearToBumpedLightmapAlpha( const float *linearAlpha, const float *linearBumpAlpha1,
const float *linearBumpAlpha2, const float *linearBumpAlpha3,
unsigned char *ret, unsigned char *retBump1,
unsigned char *retBump2, unsigned char *retBump3 )
{
// divide by three to ensure we stay in a 0..1 range here, scale up result later (via scaling in CSM light color)
const float &linearUnbumped = *((const float *)linearAlpha) / 3.0f;
const float &linearBump1 = *((const float *)linearBumpAlpha1) / 3.0f;
const float &linearBump2 = *((const float *)linearBumpAlpha2) / 3.0f;
const float &linearBump3 = *((const float *)linearBumpAlpha3) / 3.0f;
float bumpAverage = linearBump1;
bumpAverage += linearBump2;
bumpAverage += linearBump3;
bumpAverage *= (1.0f / 3.0f);
float correctionScale;
if ( *(int *)&bumpAverage != 0 )
{
// fast path when we know that we don't have to worry about divide by zero.
correctionScale = linearUnbumped / bumpAverage;
}
else
{
correctionScale = 0.0f;
if ( bumpAverage != 0.0f )
{
correctionScale = linearUnbumped / bumpAverage;
}
}
float correctedBumpAlpha1;
float correctedBumpAlpha2;
float correctedBumpAlpha3;
correctedBumpAlpha1 = linearBump1 * correctionScale;
correctedBumpAlpha2 = linearBump2 * correctionScale;
correctedBumpAlpha3 = linearBump3 * correctionScale;
ret[0] = RoundFloatToByte( linearUnbumped * 255.0f );
retBump1[0] = RoundFloatToByte( correctedBumpAlpha1 * 255.0f );
retBump2[0] = RoundFloatToByte( correctedBumpAlpha2 * 255.0f );
retBump3[0] = RoundFloatToByte( correctedBumpAlpha3 * 255.0f );
}
uint16 LinearFloatToCorrectedShort( float in );
inline unsigned short LinearToUnsignedShort( float in, int nFractionalBits )
{
unsigned short out;
in = in * ( 1 << nFractionalBits );
in = MIN( in, 65535 );
out = ( unsigned short ) MAX( in, 0.0f );
return out;
}
inline void ClampToHDR( const Vector &in, unsigned short out[3] )
{
Vector tmp = in;
out[0] = LinearFloatToCorrectedShort( in.x );
out[1] = LinearFloatToCorrectedShort( in.y );
out[2] = LinearFloatToCorrectedShort( in.z );
}
// divide by 3 to ensure we stay in the same range as bumped alpha data
// this is important for overlays, since a bumped overlay on a non-bumped
// lightmap surface is still drawn with the bumped lightmap shader, with 3x the base lightmap
// and vice versa. If we're not consistent, we break the CSM blending
FORCEINLINE void LinearToLightmapAlpha( unsigned char *pDstA, const float srcA )
{
pDstA[0] = RoundFloatToByte( (srcA * 255.0f) / 3.0f );
}
FORCEINLINE void LinearToLightmapAlpha( int *pDstA, const float srcA )
{
pDstA[0] = LinearToUnsignedShort( srcA / 3.0f, 16 );
}
FORCEINLINE void LinearToLightmapAlpha( float *pA )
{
pA[0] = pA[0] / 3.0f;
}
FORCEINLINE void
LinearToBumpedLightmap( const float *linearColor, const float *linearBumpColor1,
const float *linearBumpColor2, const float *linearBumpColor3,
float *ret, float *retBump1,
float *retBump2, float *retBump3 )
{
const Vector &linearUnbumped = *( ( const Vector * )linearColor );
Vector linearBump1 = *( ( const Vector * )linearBumpColor1 );
Vector linearBump2 = *( ( const Vector * )linearBumpColor2 );
Vector linearBump3 = *( ( const Vector * )linearBumpColor3 );
// find a scale factor which makes the average of the 3 bumped mapped vectors match the
// straight up vector (if possible), so that flat bumpmapped areas match non-bumpmapped
// areas.
// Note: According to Alex, this code is completely wrong.
// Because the bump vectors constitute a orthonormal basis, one does not simply average
// them to get the straight-up result. In fact they are added together then multiplied
// by 0.575
Vector bumpAverage = linearBump1;
bumpAverage += linearBump2;
bumpAverage += linearBump3;
bumpAverage *= ( 1.0f / 3.0f );
Vector correctionScale;
if( *( int * )&bumpAverage[0] != 0 &&
*( int * )&bumpAverage[1] != 0 &&
*( int * )&bumpAverage[2] != 0 )
{
// fast path when we know that we don't have to worry about divide by zero.
VectorDivide( linearUnbumped, bumpAverage, correctionScale );
}
else
{
correctionScale.Init( 0.0f, 0.0f, 0.0f );
if( bumpAverage[0] != 0.0f )
{
correctionScale[0] = linearUnbumped[0] / bumpAverage[0];
}
if( bumpAverage[1] != 0.0f )
{
correctionScale[1] = linearUnbumped[1] / bumpAverage[1];
}
if( bumpAverage[2] != 0.0f )
{
correctionScale[2] = linearUnbumped[2] / bumpAverage[2];
}
}
linearBump1 *= correctionScale;
linearBump2 *= correctionScale;
linearBump3 *= correctionScale;
*((Vector *)ret) = linearUnbumped;
*((Vector *)retBump1) = linearBump1;
*((Vector *)retBump2) = linearBump2;
*((Vector *)retBump3) = linearBump3;
}
// For use with CSM correct blending output in alpha channel from vrad
// we can go out of 0..1 range if we normalize the bumped alpha data
// so we 'squash' the range to compensate.
// Note - We shouldn't be taking the simple average in the bump case when normalizing anyway
// (i.e. add together and multiply by 0.575 comments below).
// Keeping the averaging as is for consistency with RGB's, etc
FORCEINLINE void LinearToBumpedLightmapAlpha( const float *linearAlpha, const float *linearBumpAlpha1,
const float *linearBumpAlpha2, const float *linearBumpAlpha3,
float *ret, float *retBump1,
float *retBump2, float *retBump3 )
{
// divide by three to ensure we stay in a 0..1 range here, scale up result later (via scaling in CSM light color)
const float &linearUnbumped = *((const float *)linearAlpha) / 3.0f;
const float &linearBump1 = *((const float *)linearBumpAlpha1) / 3.0f;
const float &linearBump2 = *((const float *)linearBumpAlpha2) / 3.0f;
const float &linearBump3 = *((const float *)linearBumpAlpha3) / 3.0f;
float bumpAverage = linearBump1;
bumpAverage += linearBump2;
bumpAverage += linearBump3;
bumpAverage *= (1.0f / 3.0f);
float correctionScale;
if ( *(int *)&bumpAverage != 0 )
{
// fast path when we know that we don't have to worry about divide by zero.
correctionScale = linearUnbumped / bumpAverage;
}
else
{
correctionScale = 0.0f;
if ( bumpAverage != 0.0f )
{
correctionScale = linearUnbumped / bumpAverage;
}
}
float correctedBumpAlpha1;
float correctedBumpAlpha2;
float correctedBumpAlpha3;
correctedBumpAlpha1 = linearBump1 * correctionScale;
correctedBumpAlpha2 = linearBump2 * correctionScale;
correctedBumpAlpha3 = linearBump3 * correctionScale;
ret[0] = linearUnbumped;
retBump1[0] = correctedBumpAlpha1;
retBump2[0] = correctedBumpAlpha2;
retBump3[0] = correctedBumpAlpha3;
}
// The domain of the inputs is floats [0 .. 16.0f]
// the output range is also floats [0 .. 16.0f] (eg, compression to short does not happen)
FORCEINLINE void
LinearToBumpedLightmap( FLTX4 linearColor, FLTX4 linearBumpColor1,
FLTX4 linearBumpColor2, FLTX4 linearBumpColor3,
fltx4 &ret, fltx4 &retBump1, // I pray that with inlining
fltx4 &retBump2, fltx4 &retBump3 ) // these will be returned on registers
{
// preload 3.0f onto the returns so that we don't need to multiply the bumpAverage by it
// straight away (eg, reschedule this dependent op)
static const fltx4 vThree = { 3.0f, 3.0f, 3.0f, 0.0f };
fltx4 retValBump1 = MulSIMD( vThree, linearBumpColor1);
fltx4 retValBump2 = MulSIMD( vThree, linearBumpColor2);
fltx4 retValBump3 = MulSIMD( vThree, linearBumpColor3);
// find a scale factor which makes the average of the 3 bumped mapped vectors match the
// straight up vector (if possible), so that flat bumpmapped areas match non-bumpmapped
// areas.
fltx4 bumpAverage = AddSIMD(AddSIMD(linearBumpColor1, linearBumpColor2), linearBumpColor3); // actually average * 3
// find the zero terms so that we can quash their channels in the output
bi32x4 zeroTerms = CmpEqSIMD(bumpAverage, Four_Zeros);
fltx4 correctionScale = ReciprocalEstSIMD(bumpAverage); // each channel is now 1.0f / (average[x] * 3.0f)
// divide unbumped linear by the average to get the correction scale
correctionScale = MulSIMD( AndNotSIMD(zeroTerms, linearColor), // crush values that were zero in bumpAverage. (saves on dep latency)
correctionScale); // still has an extra 1/3 factor multiplied in
// multiply this against three to get the return values
ret = linearColor;
retBump1 = MulSIMD(retValBump1, correctionScale);
retBump2 = MulSIMD(retValBump2, correctionScale);
retBump3 = MulSIMD(retValBump3, correctionScale);
}
// input: floats [0 .. 16.0f]
// output: shorts [0 .. 65535]
FORCEINLINE void
LinearToBumpedLightmap( const float *linearColor, const float *linearBumpColor1,
const float *linearBumpColor2, const float *linearBumpColor3,
unsigned short *ret, unsigned short *retBump1,
unsigned short *retBump2, unsigned short *retBump3 )
{
Vector linearUnbumped, linearBump1, linearBump2, linearBump3;
LinearToBumpedLightmap( linearColor, linearBumpColor1, linearBumpColor2, linearBumpColor3, &linearUnbumped.x, &linearBump1.x, &linearBump2.x, &linearBump3.x );
ClampToHDR( linearUnbumped, ret );
ClampToHDR( linearBump1, retBump1 );
ClampToHDR( linearBump2, retBump2 );
ClampToHDR( linearBump3, retBump3 );
}
};
#endif // COLORSPACE_H
File diff suppressed because it is too large. Load diff
+235
View File
@@ -0,0 +1,235 @@
//========= Copyright © 1996-2013, Valve Corporation, All rights reserved. ============//
//
// Purpose: Provide custom texture generation (compositing)
//
// $NoKeywords: $
//=============================================================================//
#ifndef COMPOSITE_TEXTURE_H
#define COMPOSITE_TEXTURE_H
#include "materialsystem/MaterialSystemUtil.h"
#include "materialsystem/itexture.h"
#include "materialsystem/icompositetexturegenerator.h"
#include "utllinkedlist.h"
#include "utlbuffer.h"
class IVisualsDataProcessor;
class ITextureInternal;
//
// Render Targets for Custom Materials
//
class IMaterialSystem;
class IMaterialSystemHardwareConfig;
struct SCompositeTextureRTData_t
{
const char* pName;
int nSize;
bool bSRGB;
bool bAvailable; // true if the RT was created and can be used.
IVTFTexture *pScratch;
};
// this should match the s_compositeTextureRTData array in composite_texture.cpp
enum CompositeTextureRTSizes_t
{
#if !defined( PLATFORM_OSX )
COMPOSITE_TEXTURE_RT_2048,
#endif
COMPOSITE_TEXTURE_RT_1024,
COMPOSITE_TEXTURE_RT_512,
COMPOSITE_TEXTURE_RT_256,
COMPOSITE_TEXTURE_RT_128,
COMPOSITE_TEXTURE_RT_COUNT
};
//
// Texture Regenerator for Custom Materials
//
// This is where the compositing material is created and used to make the procedural textures
// used with custom materials. It also holds the result vtfs that are copied into the
// actual textures used for rendering.
//
enum CompositeTextureStages_t
{
COMPOSITE_TEXTURE_STATE_NOT_STARTED = 0,
COMPOSITE_TEXTURE_STATE_ASYNC_TEXTURE_LOAD,
COMPOSITE_TEXTURE_STATE_WAITING_FOR_ASYNC_TEXTURE_LOAD_FINISH,
COMPOSITE_TEXTURE_STATE_NEEDS_INIT,
COMPOSITE_TEXTURE_STATE_WAITING_FOR_RENDER_TO_RT,
COMPOSITE_TEXTURE_STATE_RENDERED_TO_RT,
COMPOSITE_TEXTURE_STATE_WAITING_FOR_READ_RT,
COMPOSITE_TEXTURE_STATE_REQUESTED_READ,
COMPOSITE_TEXTURE_STATE_WAITING_FOR_GETRESULT,
COMPOSITE_TEXTURE_STATE_REQUESTED_GETRESULT,
COMPOSITE_TEXTURE_STATE_COPY_TO_VTF_COMPLETE,
COMPOSITE_TEXTURE_STATE_WAITING_FOR_MATERIAL_CLEANUP,
COMPOSITE_TEXTURE_STATE_COMPLETE
};
#define NUM_PRELOAD_TEXTURES 20
class CCompositeTexture;
class CCompositeTextureResult : public ITextureRegenerator
{
public:
CCompositeTextureResult( CCompositeTexture *pOwner ) : m_pOwner( pOwner ), m_pTexture( NULL ) {}
virtual void RegenerateTextureBits( ITexture *pTexture, IVTFTexture *pVTFTexture, Rect_t *pRect );
virtual void Release();
CCompositeTexture *m_pOwner;
ITexture *m_pTexture;
};
class CCompositeTexture : public ICompositeTexture, public CRefCounted<>
{
public:
CCompositeTexture( const CUtlBuffer &compareBlob, KeyValues *pCompositingMaterialKeyValues, CompositeTextureSize_t size, CompositeTextureFormat_t format, int nMaterialParamNameId, bool bSRGB, bool bIgnorePicMip );
bool Init();
void Refresh()
{
m_nRegenerateStage = COMPOSITE_TEXTURE_STATE_NOT_STARTED;
m_bNeedsRegenerate = false;
m_bNeedsFinalize = true;
}
bool IsReady() const { return ( !NeedsFinalize() && GenerationComplete() ); }
bool GenerationComplete() const { return ( m_nRegenerateStage == COMPOSITE_TEXTURE_STATE_COMPLETE ); }
void Usage( int &nTextures, int &nBackingTextures );
bool NeedsAsyncTextureLoad() const { return m_nRegenerateStage == COMPOSITE_TEXTURE_STATE_ASYNC_TEXTURE_LOAD; }
void DoAsyncTextureLoad();
bool NeedsCompositingMaterial() const { return m_nRegenerateStage == COMPOSITE_TEXTURE_STATE_NEEDS_INIT; }
void CreateCompositingMaterial();
bool NeedsRender() const { return m_nRegenerateStage == COMPOSITE_TEXTURE_STATE_WAITING_FOR_RENDER_TO_RT; }
void RenderToRT();
bool HasRendered() const { return ( m_nRegenerateStage == COMPOSITE_TEXTURE_STATE_RENDERED_TO_RT ); }
void AdvanceToReadRT();
bool NeedsReadRT() const { return m_nRegenerateStage == COMPOSITE_TEXTURE_STATE_WAITING_FOR_READ_RT; }
void ReadRT();
bool NeedsGetResult() const { return m_nRegenerateStage == COMPOSITE_TEXTURE_STATE_WAITING_FOR_GETRESULT; }
void GetReadRTResult();
bool NeedsMaterialCleanup() const { return m_nRegenerateStage == COMPOSITE_TEXTURE_STATE_WAITING_FOR_MATERIAL_CLEANUP; }
void CleanupCompositingMaterial();
void GenerationStep();
bool NeedsRegenerate() const { return m_bNeedsRegenerate; }
void ForceRegenerate();
CompositeTextureFormat_t Format() const { return m_format; }
CompositeTextureSize_t Size() const { return m_size; }
int ActualSize() const { return m_nActualSize; }
int GetMaterialParamNameId() const { return m_nMaterialParamNameId; }
const char *GetName() { return m_szTextureName; }
bool NeedsFinalize() const { return m_bNeedsFinalize; }
void Finalize();
IVTFTexture *GetResultVTF() { return m_pResultVTF; }
bool ShouldRelease() { return ( ( GetRefCount() == 1 ) && IsReady() ); }
const CUtlBuffer &GetVisualsDataCompareBlob() { return m_compareBlob; }
void ReleaseResult() { m_ResultTexture.Release(); }
bool IsSRGB() const { return m_bSRGB; }
bool Compare( const SCompositeTextureInfo &textureInfo );
protected:
virtual ~CCompositeTexture();
void GenerateComposite();
void ReleasePreloadedTextures();
char m_szTextureName[ MAX_PATH ];
CompositeTextureSize_t m_size;
CompositeTextureFormat_t m_format; // DXT1 or DXT5 only
int m_nMaterialParamNameId; // the material parameter that this texture will fill/replace in the eventual Custom Material, also used to interact with the VisualsDataProcessor
bool m_bSRGB;
CompositeTextureStages_t m_nRegenerateStage;
CUtlBuffer m_compareBlob;
IVTFTexture *m_pResultVTF;
CCompositeTextureResult m_ResultTexture;
int m_nActualSize;
bool m_bNeedsRegenerate;
bool m_bNeedsFinalize;
IVTFTexture *m_pScratchVTF;
ITexture *m_pCustomMaterialRT;
KeyValues *m_pCompositingMaterialKeyValues;
IMaterial *m_pCompositingMaterial;
int m_nLastFrameCount;
CThreadEvent *m_pPixelsReadEvent;
bool m_bIgnorePicMip;
static int m_nTextureCount;
private:
CCompositeTexture( CCompositeTexture &);
ITextureInternal* m_pPreLoadTextures[ NUM_PRELOAD_TEXTURES ];
};
//
// Composite Texture Generator
//
// This is the class that the game talks to in order to make composite textures
// You need a IVisualsDataProcessor based class to feed this.
//
class CCompositeTextureGenerator : public ICompositeTextureGenerator
{
public:
CCompositeTextureGenerator( void );
virtual ~CCompositeTextureGenerator( void );
bool Init( void );
void Shutdown( void );
virtual bool Process( void );
virtual ICompositeTexture *GetCompositeTexture( IVisualsDataProcessor *pVisualsDataProcessor, int nMaterialParamNameId, CompositeTextureSize_t size, CompositeTextureFormat_t format, bool bSRGB, bool bIgnorePicMip = false , bool bAllowCreate = true );
virtual ICompositeTexture *GetCompositeTexture( const SCompositeTextureInfo &textureInfo, bool bIgnorePicMip = false , bool bAllowCreate = true );
virtual bool ForceRegenerate( ICompositeTexture *pTexture );
private:
CUtlVector< CCompositeTexture * > m_pCompositeTextures;
CUtlVector< CCompositeTexture * > m_pPendingCompositeTextures;
void DestroyTextures( void );
void GenerateThread(); // never call this directly, it's running as another thread
void CreateGenerateThread();
void DestroyGenerateThread();
CUtlLinkedList< CCompositeTexture * > m_pGenerateQueue;
CThreadFastMutex m_GenerateQueueMutex;
ThreadHandle_t m_hGenerateThread;
bool m_bGenerateThreadExit;
CTextureReference m_CompositeTextureManagerRTs[COMPOSITE_TEXTURE_RT_COUNT];
ITextureInternal* m_pGunGrimeTexture;
ITextureInternal* m_pPaintWearTexture;
};
#endif // COMPOSITE_TEXTURE_H
File diff suppressed because it is too large. Load diff
+446
View File
@@ -0,0 +1,446 @@
//========= Copyright © 1996-2013, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
//#include "cbase.h"
#include "custom_material.h"
#include "composite_texture.h"
#include "materialsystem/base_visuals_data_processor.h"
#include "materialsystem_global.h"
#include "keyvalues.h"
#include "tier0/vprof.h"
#ifndef DEDICATED
#include "filesystem.h"
#endif
//#define DEBUG_CUSTOMMATERIALS
int CCustomMaterial::m_nMaterialCount = 0;
//
// Material applied to the item to give it a custom look
//
CCustomMaterial::CCustomMaterial( KeyValues *pKeyValues )
: m_bValid( false )
, m_nModelMaterialIndex( -1 )
, m_szBaseMaterialName( NULL)
{
// we need to copy this, because the passed in one was allocated outside materialsystem.dll
m_pVMTKeyValues = ( pKeyValues != NULL ) ? pKeyValues->MakeCopy() : NULL;
}
CCustomMaterial::~CCustomMaterial()
{
Shutdown();
}
void CCustomMaterial::AddTexture( ICompositeTexture * pTextureInterface )
{
CCompositeTexture *pTexture = dynamic_cast< CCompositeTexture * >( pTextureInterface );
if ( pTexture )
{
m_pTextures.AddToTail( pTexture );
pTexture->AddRef();
}
}
ICompositeTexture *CCustomMaterial::GetTexture( int nIndex )
{
if ( nIndex >= 0 && nIndex < m_pTextures.Count() )
{
return m_pTextures[ nIndex ];
}
return NULL;
}
bool CCustomMaterial::CheckRegenerate( int nSize )
{
if ( m_pTextures.Count() > 0 )
{
return nSize != ( 2048 >> m_pTextures[ 0 ]->Size() );
}
return false;
}
void CCustomMaterial::SetBaseMaterialName( const char* szName )
{
Assert( !m_szBaseMaterialName );
m_szBaseMaterialName = strdup( szName );
}
void CCustomMaterial::Shutdown()
{
DestroyProceduralMaterial();
if ( m_pVMTKeyValues != NULL )
{
m_pVMTKeyValues->deleteThis();
m_pVMTKeyValues = NULL;
}
for ( int i = 0; i < m_pTextures.Count(); i++ )
{
if ( m_pTextures[ i ] )
{
m_pTextures[ i ]->Release();
m_pTextures[ i ] = NULL;
}
}
if ( m_szBaseMaterialName )
free( ( void * ) m_szBaseMaterialName );
m_pTextures.RemoveAll();
}
void CCustomMaterial::Usage( int& nTextures, int& nBackingTextures )
{
for ( int i = 0; i < m_pTextures.Count(); i++ )
{
m_pTextures[ i ]->Usage( nTextures, nBackingTextures );
}
}
bool CCustomMaterial::TexturesReady() const
{
if ( m_pTextures.Count() == 0 )
{
return false;
}
for ( int i = 0; i < m_pTextures.Count(); i++ )
{
if ( !m_pTextures[ i ]->IsReady() )
{
return false;
}
}
return true;
}
void CCustomMaterial::RegenerateTextures()
{
for ( int i = 0; i < m_pTextures.Count(); i++ )
{
m_pTextures[ i ]->ForceRegenerate();
}
}
bool CCustomMaterial::ShouldRelease()
{
return ( ( GetRefCount() == 1 ) && IsValid() );
}
bool CCustomMaterial::Compare( const CUtlVector< SCompositeTextureInfo > &vecTextures )
{
if ( m_pTextures.Count() == vecTextures.Count() )
{
FOR_EACH_VEC( m_pTextures, i )
{
if ( !m_pTextures[ i ]->Compare( vecTextures[ i ] ) )
{
return false;
}
}
return true;
}
return false;
}
void CCustomMaterial::Finalize()
{
char szUniqueMaterialName[ 256 ];
V_snprintf( szUniqueMaterialName, sizeof( szUniqueMaterialName ), "cs_custom_material_%i", m_nMaterialCount++ );
DestroyProceduralMaterial();
if ( m_pVMTKeyValues != NULL )
{
CreateProceduralMaterial( szUniqueMaterialName, m_pVMTKeyValues->MakeCopy() );
}
else
{
// Create default material key values
m_pVMTKeyValues = new KeyValues( "VertexLitGeneric" );
m_pVMTKeyValues->SetInt( "$phongalbedoboost", 45 );
m_pVMTKeyValues->SetInt( "$phong", 1 );
m_pVMTKeyValues->SetFloat( "$phongboost", 0.4 );
m_pVMTKeyValues->SetString( "$phongfresnelranges", "[.8 .8 1]" );
m_pVMTKeyValues->SetInt( "$basemapalphaphongmask", 1 );
m_pVMTKeyValues->SetString( "$envmap", "env_cubemap" );
m_pVMTKeyValues->SetInt( "$envmapfresnel", 1 );
m_pVMTKeyValues->SetString( "$envmapFresnelMinMaxExp", "[0 5 .4]" );
m_pVMTKeyValues->SetString( "$envmaptint", "[.02 .02 .02]" );
m_pVMTKeyValues->SetInt( "$phongalbedotint", 1 );
CreateProceduralMaterial( szUniqueMaterialName, m_pVMTKeyValues->MakeCopy() );
}
}
void CCustomMaterial::CreateProceduralMaterial( const char *pMaterialName, KeyValues *pVMTKeyValues )
{
// Replace parts of existing material key values
// loop over m_pTextures and set the material params
for ( int i = 0; i < m_pTextures.Count(); i++ )
{
pVMTKeyValues->SetString( g_szMaterialParamNames[ m_pTextures[ i ]->GetMaterialParamNameId() ], m_pTextures[ i ]->GetName() );
}
m_Material.Init( pMaterialName, pVMTKeyValues );
m_Material->Refresh();
}
void CCustomMaterial::DestroyProceduralMaterial()
{
m_Material.Shutdown( true );
}
//
// global custom material manager
// the game uses this to make/get a custom material
//
CCustomMaterialManager::CCustomMaterialManager()
{
#ifndef DEDICATED
m_pCustomMaterials.EnsureCapacity( 128 );
m_mapVMTKeyValues.SetLessFunc( StringLessThan );
#endif
}
CCustomMaterialManager::~CCustomMaterialManager()
{
}
// this is called at the end of each frame
bool ProcessDynamicCustomMaterialGenerator()
{
return MaterialSystem()->GetCustomMaterialManager()->Process();
}
bool CCustomMaterialManager::Init()
{
#ifndef DEDICATED
MaterialSystem()->AddEndFramePriorToNextContextFunc( ::ProcessDynamicCustomMaterialGenerator );
KeyValues *pVMTCache = new KeyValues( "VMTCache" );
if ( pVMTCache->LoadFromFile( g_pFullFileSystem, "resource/vmtcache.txt", "MOD" ) )
{
KeyValues *pValue = pVMTCache->GetFirstValue();
while ( pValue )
{
const char *pszVMTToCache = pValue->GetString();
if ( pszVMTToCache && pszVMTToCache[0] != 0 )
{
KeyValues *pVMTKeyValues = new KeyValues( "VertexLitGeneric" );
bool bVMTExists = pVMTKeyValues->LoadFromFile( g_pFullFileSystem , pszVMTToCache, "MOD" );
if ( bVMTExists )
{
m_mapVMTKeyValues.Insert( pszVMTToCache, pVMTKeyValues );
DevMsg( "CustomMaterialManager: Cached KeyValues %s.\n", pszVMTToCache );
}
else
{
DevMsg( "Failed to load VMT: %s\n", pszVMTToCache );
}
}
pValue = pValue->GetNextValue();
}
}
#endif
return true;
}
void CCustomMaterialManager::Shutdown()
{
#ifndef DEDICATED
MaterialSystem()->RemoveEndFramePriorToNextContextFunc( ::ProcessDynamicCustomMaterialGenerator );
FOR_EACH_MAP_FAST( m_mapVMTKeyValues, i )
{
m_mapVMTKeyValues[ i ]->deleteThis();
}
m_mapVMTKeyValues.Purge();
DestroyMaterials();
#endif
}
bool CCustomMaterialManager::GetVMTKeyValues( const char *pszVMTName, KeyValues **ppVMTKeyValues )
{
// lookup VMT KeyValues in container
int nIndex = m_mapVMTKeyValues.Find( pszVMTName );
if ( nIndex != m_mapVMTKeyValues.InvalidIndex() )
{
// need to return a copy here, since we don't want the caller to change our copy.
*ppVMTKeyValues = m_mapVMTKeyValues[ nIndex ]->MakeCopy();
return true;
}
return false;
}
// handles finalizing materials once all the textures are ready, swapping materials that are pending swap and ready, and cleans up materials that are no longer used
bool CCustomMaterialManager::Process()
{
//TM_ZONE( TELEMETRY_LEVEL0, TMZF_NONE, "%s", __FUNCTION__ );
for ( int i = 0; i < m_pCustomMaterials.Count(); ++i )
{
if ( m_pCustomMaterials[ i ] &&
m_pCustomMaterials[ i ]->TexturesReady() &&
!m_pCustomMaterials[ i ]->IsValid() )
{
m_pCustomMaterials[ i ]->Finalize();
m_pCustomMaterials[ i ]->SetValid( true );
#ifdef DEBUG_CUSTOMMATERIALS
DevMsg( "Finalized custom material: %s \n", m_pCustomMaterials[ i ]->GetMaterial() ? m_pCustomMaterials[ i ]->GetMaterial()->GetName() : "*unknown*" );
#endif
}
else if ( !m_pCustomMaterials[ i ]->TexturesReady() &&
m_pCustomMaterials[ i ]->IsValid() )
{
// this happens when textures regenerate because of mat_picmip changes
m_pCustomMaterials[ i ]->SetValid( false );
}
}
for ( int i = m_pCustomMaterials.Count() - 1; i >= 0; i-- )
{
if ( m_pCustomMaterials[ i ] )
{
// clean up materials that are no longer used (we are the only reference)
if ( m_pCustomMaterials[ i ]->ShouldRelease() )
{
#ifdef DEBUG_CUSTOMMATERIALS
DevMsg( "Releasing custom material: %s \n", m_pCustomMaterials[ i ]->GetMaterial()->GetName() );
#endif
m_pCustomMaterials[ i ]->Release();
m_pCustomMaterials[ i ] = NULL;
m_pCustomMaterials.Remove( i );
}
}
}
return false;
}
ICustomMaterial * CCustomMaterialManager::GetOrCreateCustomMaterial( KeyValues *pKeyValues, const CUtlVector< SCompositeTextureInfo > &vecTextureInfos, bool bIgnorePicMip /*= false */ )
{
#if defined( DEDICATED ) || defined( DISABLE_CUSTOM_MATERIAL_GENERATION )
return NULL;
#endif
TM_MESSAGE( TELEMETRY_LEVEL0, TMMF_ICON_NOTE | TMMF_SEVERITY_WARNING, "%s %d", __FUNCTION__, vecTextureInfos[0].m_size );
for ( int i = 0; i < m_pCustomMaterials.Count(); ++i )
{
CCustomMaterial *pMaterial = m_pCustomMaterials[ i ];
if ( pMaterial && pMaterial->Compare( vecTextureInfos ) )
{
return pMaterial;
}
}
CCustomMaterial *pMaterial = new CCustomMaterial( pKeyValues );
pMaterial->SetValid( false );
pMaterial->SetBaseMaterialName( vecTextureInfos[ 0 ].m_pVisualsDataProcessor->GetOriginalMaterialBaseName() );
FOR_EACH_VEC( vecTextureInfos, i )
{
ICompositeTexture *pTexture = g_pMaterialSystem->GetCompositeTextureGenerator()->GetCompositeTexture( vecTextureInfos[ i ] );
if ( pTexture )
{
pMaterial->AddTexture( pTexture );
}
else
{
AssertMsg( pTexture != NULL, "Unable to get/create composite texture for custom material!" );
pMaterial->Release();
return NULL;
}
}
m_pCustomMaterials.AddToTail( pMaterial );
#ifdef DEBUG_CUSTOMMATERIALS
DevMsg( "Created custom material for: %s \n", pVisualsDataProcessor->GetOriginalMaterialName() );
#endif
// The material may not be complete yet, but it will be completed over the next few frames via Process()
return pMaterial;
}
void CCustomMaterialManager::ReloadAllMaterials( const CCommand &args )
{
for ( int i = 0; i < m_pCustomMaterials.Count(); ++i )
{
CCustomMaterial *pMaterial = m_pCustomMaterials[ i ];
if ( pMaterial )
{
pMaterial->RegenerateTextures();
}
}
}
void CCustomMaterialManager::ReloadVmtCache( const CCommand &args )
{
}
int CCustomMaterialManager::DebugGetNumActiveCustomMaterials( )
{
int nActive = 0;
for ( int i = 0; i < m_pCustomMaterials.Count(); ++i )
{
CCustomMaterial *pMaterial = m_pCustomMaterials[ i ];
if ( pMaterial && pMaterial->IsValid() )
{
nActive++;
}
}
return nActive;
}
void CCustomMaterialManager::Usage( const CCommand &args )
{
int nTextures = 0;
int nBackingTextures = 0;
int nActive = 0;
for ( int i = 0; i < m_pCustomMaterials.Count(); ++i )
{
CCustomMaterial *pMaterial = m_pCustomMaterials[ i ];
if ( pMaterial && pMaterial->IsValid() )
{
int nBackingTexture = 0;
pMaterial->Usage( nTextures, nBackingTexture );
Msg( "%2d. %s, %d \n", i, pMaterial->GetMaterial() ? pMaterial->GetMaterial()->GetName() : "*pending*", nBackingTexture );
nBackingTextures += nBackingTexture;
nActive++;
}
}
Msg( "Custom Weapon Material Usage: Total: %d Active: %d Textures: %d BackingTextures: %d \n", m_pCustomMaterials.Count(), nActive, nTextures, nBackingTextures );
}
void CCustomMaterialManager::DestroyMaterials( void )
{
for ( int i = 0; i < m_pCustomMaterials.Count(); ++i )
{
if ( m_pCustomMaterials[ i ] )
{
m_pCustomMaterials[ i ]->Release();
m_pCustomMaterials[ i ] = NULL;
}
}
m_pCustomMaterials.RemoveAll();
}
+108
View File
@@ -0,0 +1,108 @@
//========= Copyright 1996-2012, Valve Corporation, All rights reserved. ============//
//
// Purpose: Provide custom texture generation (compositing) for use on weapons and clothing
//
// $NoKeywords: $
//=============================================================================//
#ifndef CUSTOM_MATERIAL_H
#define CUSTOM_MATERIAL_H
#include "materialsystem/MaterialSystemUtil.h"
#include "materialsystem/icustommaterial.h"
#include "materialsystem/icustommaterialmanager.h"
#include "convar.h"
#include "utlvector.h"
#include "utlmap.h"
//#define DISABLE_CUSTOM_MATERIAL_GENERATION
class IVisualsDataProcessor;
class IVisualsDataCompare;
class ICompositeTexture;
class CCompositeTexture;
class KeyValues;
//
// Custom Materials
//
// This handles making a material to contain composite textures,
// and it will be used during rendering of the model(s)
//
class CCustomMaterial : public ICustomMaterial
{
public:
CCustomMaterial( KeyValues *pKeyValues );
virtual ~CCustomMaterial();
// inherited from ICustomMaterial
// returns the actual end result material to be used for drawing the model
virtual IMaterial *GetMaterial() { return m_Material; } // the material reference converts itself into an IMaterial
virtual void AddTexture( ICompositeTexture *pTexture );
virtual ICompositeTexture *GetTexture( int nIndex );
virtual bool IsValid() const { return m_bValid; }
virtual bool CheckRegenerate( int nSize );
virtual const char* GetBaseMaterialName( void ) { return m_szBaseMaterialName; }
// ----
void SetBaseMaterialName( const char* szNmae );
void Shutdown();
void SetValid( bool bState ) { m_bValid = bState; }
void Usage( int& nTextures, int& nMaterials );
bool TexturesReady() const;
void RegenerateTextures();
bool ShouldRelease();
bool Compare( const CUtlVector< SCompositeTextureInfo > &vecTextures );
// actually creates the internal material that references the textures (which need to be finalized before calling this)
void Finalize();
private:
void CreateProceduralMaterial( const char *pMaterialName, KeyValues *pKeyValues );
void DestroyProceduralMaterial();
CMaterialReference m_Material;
CUtlVector< CCompositeTexture * > m_pTextures;
bool m_bValid;
int m_nModelMaterialIndex;
KeyValues *m_pVMTKeyValues;
const char *m_szBaseMaterialName;
static int m_nMaterialCount;
};
class CCustomMaterialManager : public ICustomMaterialManager
{
public:
CCustomMaterialManager();
virtual ~CCustomMaterialManager();
bool Init();
void Shutdown();
virtual bool Process();
virtual ICustomMaterial *GetOrCreateCustomMaterial( KeyValues *pKeyValues, const CUtlVector< SCompositeTextureInfo > &vecTextureInfos, bool bIgnorePicMip = false );
virtual int DebugGetNumActiveCustomMaterials();
virtual bool GetVMTKeyValues( const char *pszVMTName, KeyValues **ppVMTKeyValues );
private:
CON_COMMAND_MEMBER_F( CCustomMaterialManager, "mat_reloadallcustommaterials", ReloadAllMaterials, "Reloads all custom materials", FCVAR_CHEAT | FCVAR_CLIENTDLL );
CON_COMMAND_MEMBER_F( CCustomMaterialManager, "mat_custommaterialusage", Usage, "Show memory usage for custom weapon materials.", FCVAR_CLIENTDLL );
CON_COMMAND_MEMBER_F( CCustomMaterialManager, "mat_reloadvmtcache", ReloadVmtCache, "Reload vmts from vmtcache.txt.", FCVAR_CHEAT | FCVAR_CLIENTDLL | FCVAR_DEVELOPMENTONLY );
void DestroyMaterials();
CUtlVector< CCustomMaterial * > m_pCustomMaterials;
CUtlMap< const char *, KeyValues * > m_mapVMTKeyValues;
};
#endif // CUSTOM_MATERIAL_H
+105
View File
@@ -0,0 +1,105 @@
for( $i = 0; $i < 16; $i++ )
{
print "\#define SHADER_CLASS$i(name,help";
for( $j = 0; $j < $i; $j++ )
{
print ",p$j,p$j" . "type,p$j" . "default,p$j" . "help\\\n\t\t";
}
print ")\\\n";
print "\tstatic const char *s_HelpString = help;\\\n";
print "\tstatic const char *s_ParamNames[] = {";
if( $i == 0 )
{
print "NULL";
}
else
{
for( $j = 0; $j < $i; $j++ )
{
print "\\\n\t\t\"\$\" #p$j";
if( $j != $i - 1 )
{
print ",";
}
}
}
print "\\\n\t};\\\n";
print "\tstatic ShaderParamType_t s_ParamType[] = {";
if( $i == 0 )
{
print "SHADER_PARAM_TYPE_INTEGER";
}
else
{
for( $j = 0; $j < $i; $j++ )
{
print "\\\n\t\tp$j" . "type";
if( $j != $i - 1 )
{
print ",";
}
}
}
print "\\\n\t};\\\n";
print "\tstatic const char *s_ParamDefault[] = {";
if( $i == 0 )
{
print "\"\"";
}
else
{
for( $j = 0; $j < $i; $j++ )
{
print "\\\n\t\tp$j" . "default";
if( $j != $i - 1 )
{
print ",";
}
}
}
print "\\\n\t};\\\n";
print "\tstatic const char *s_ParamHelp[] = {";
if( $i == 0 )
{
print "\"\"";
}
else
{
for( $j = 0; $j < $i; $j++ )
{
print "\\\n\t\tp$j" . "help";
if( $j != $i - 1 )
{
print ",";
}
}
}
print "\\\n\t};\\\n";
print "\\\n\tenum {";
if( $i == 0 )
{
print "DUMMY_PARAM";
}
else
{
for( $j = 0; $j < $i; $j++ )
{
print "\\\n\t\tp$j";
if( $j == 0 )
{
print " = NUM_SHADER_MATERIAL_VARS";
}
if( $j != $i - 1 )
{
print ",";
}
}
}
print "\\\n\t};\\\n";
print "\tstatic const char *s_Name = #name;\\\n\tclass CShader_ ## name : public Shader_t\n\n";
}
+358
View File
@@ -0,0 +1,358 @@
//============ Copyright (c) Valve Corporation, All rights reserved. ============
//
// cglmbuffer.cpp
//
//===============================================================================
#include "glmgr/glmgr.h"
#include "glmgr/cglmbuffer.h"
// memdbgon -must- be the last include file in a .cpp file.
#include "tier0/memdbgon.h"
// void BindBufferARB(enum target, uint buffer);
// void DeleteBuffersARB(sizei n, const uint *buffers);
// void GenBuffersARB(sizei n, uint *buffers);
// boolean IsBufferARB(uint buffer);
//
// void BufferDataARB(enum target, sizeiptrARB size, const void *data,
// enum usage);
// void BufferSubDataARB(enum target, intptrARB offset, sizeiptrARB size,
// const void *data);
// void GetBufferSubDataARB(enum target, intptrARB offset,
// sizeiptrARB size, void *data);
//
// void *MapBufferARB(enum target, enum access);
// boolean UnmapBufferARB(enum target);
//
// void GetBufferParameterivARB(enum target, enum pname, int *params);
// void GetBufferPointervARB(enum target, enum pname, void **params);
//
//New Tokens
//
// Accepted by the <target> parameters of BindBufferARB, BufferDataARB,
// BufferSubDataARB, MapBufferARB, UnmapBufferARB,
// GetBufferSubDataARB, GetBufferParameterivARB, and
// GetBufferPointervARB:
//
// ARRAY_BUFFER_ARB 0x8892
// ELEMENT_ARRAY_BUFFER_ARB 0x8893
//
// Accepted by the <pname> parameter of GetBooleanv, GetIntegerv,
// GetFloatv, and GetDoublev:
//
// ARRAY_BUFFER_BINDING_ARB 0x8894
// ELEMENT_ARRAY_BUFFER_BINDING_ARB 0x8895
// VERTEX_ARRAY_BUFFER_BINDING_ARB 0x8896
// NORMAL_ARRAY_BUFFER_BINDING_ARB 0x8897
// COLOR_ARRAY_BUFFER_BINDING_ARB 0x8898
// INDEX_ARRAY_BUFFER_BINDING_ARB 0x8899
// TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB 0x889A
// EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB 0x889B
// SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB 0x889C
// FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB 0x889D
// WEIGHT_ARRAY_BUFFER_BINDING_ARB 0x889E
//
// Accepted by the <pname> parameter of GetVertexAttribivARB:
//
// VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB 0x889F
//
// Accepted by the <usage> parameter of BufferDataARB:
//
// STREAM_DRAW_ARB 0x88E0
// STREAM_READ_ARB 0x88E1
// STREAM_COPY_ARB 0x88E2
// STATIC_DRAW_ARB 0x88E4
// STATIC_READ_ARB 0x88E5
// STATIC_COPY_ARB 0x88E6
// DYNAMIC_DRAW_ARB 0x88E8
// DYNAMIC_READ_ARB 0x88E9
// DYNAMIC_COPY_ARB 0x88EA
//
// Accepted by the <access> parameter of MapBufferARB:
//
// READ_ONLY_ARB 0x88B8
// WRITE_ONLY_ARB 0x88B9
// READ_WRITE_ARB 0x88BA
//
// Accepted by the <pname> parameter of GetBufferParameterivARB:
//
// BUFFER_SIZE_ARB 0x8764
// BUFFER_USAGE_ARB 0x8765
// BUFFER_ACCESS_ARB 0x88BB
// BUFFER_MAPPED_ARB 0x88BC
//
// Accepted by the <pname> parameter of GetBufferPointervARB:
//
// BUFFER_MAP_POINTER_ARB 0x88BD
// http://www.opengl.org/registry/specs/ARB/pixel_buffer_object.txt
// Accepted by the <target> parameters of BindBuffer, BufferData,
// BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData,
// GetBufferParameteriv, and GetBufferPointerv:
// PIXEL_PACK_BUFFER_ARB 0x88EB
// PIXEL_UNPACK_BUFFER_ARB 0x88EC
// gl_bufmode: zero means we mark all vertex/index buffers static
// non zero means buffers are initially marked static..
// ->but can shift to dynamic upon first 'discard' (orphaning)
ConVar gl_bufmode( "gl_bufmode", "1" );
CGLMBuffer::CGLMBuffer( GLMContext *ctx, EGLMBufferType type, uint size, uint options )
{
m_ctx = ctx;
m_type = type;
switch(m_type)
{
case kGLMVertexBuffer: m_buffGLTarget = GL_ARRAY_BUFFER_ARB; break;
case kGLMIndexBuffer: m_buffGLTarget = GL_ELEMENT_ARRAY_BUFFER_ARB; break;
case kGLMUniformBuffer: m_buffGLTarget = GL_UNIFORM_BUFFER_EXT; break;
case kGLMPixelBuffer: m_buffGLTarget = GL_PIXEL_UNPACK_BUFFER_ARB; break;
default: Assert(!"Unknown buffer type" );
}
m_size = size;
m_bound = false;
m_mapped = false;
m_lastMappedAddress = NULL;
m_enableAsyncMap = false;
m_enableExplicitFlush = false;
m_dirtyMinOffset = m_dirtyMaxOffset = 0; // adjust/grow on lock, clear on unlock
m_ctx->CheckCurrent();
m_revision = rand();
// make a decision about pseudo mode
// this looked like it didn't help much or was actually slower, so leave it available but only as opt-in.
// a more clever implementation would be able to select pseudo buf storage for small batches only..
m_pseudo = (m_type==kGLMIndexBuffer) && (CommandLine()->FindParm("-gl_enable_pseudobufs"));
if (m_pseudo)
{
m_name = 0;
m_pseudoBuf = (char*)malloc( size );
m_ctx->BindBufferToCtx( m_type, NULL ); // exit with no buffer bound
}
else
{
glGenBuffersARB( 1, &m_name );
GLMCheckError();
m_ctx->BindBufferToCtx( m_type, this ); // causes glBindBufferARB
// buffers start out static, but if they get orphaned and gl_bufmode is non zero,
// then they will get flipped to dynamic.
GLenum hint = GL_STATIC_DRAW_ARB;
switch(m_type)
{
case kGLMVertexBuffer: hint = (options & GLMBufferOptionDynamic) ? GL_DYNAMIC_DRAW_ARB : GL_STATIC_DRAW_ARB; break;
case kGLMIndexBuffer: hint = (options & GLMBufferOptionDynamic) ? GL_DYNAMIC_DRAW_ARB : GL_STATIC_DRAW_ARB; break;
case kGLMUniformBuffer: hint = GL_DYNAMIC_DRAW_ARB; break; // "fwiw" - shrug
case kGLMPixelBuffer: hint = (options & GLMBufferOptionDynamic) ? GL_DYNAMIC_DRAW_ARB : GL_STATIC_DRAW_ARB; break;
default: Assert(!"Unknown buffer type" );
}
glBufferDataARB( m_buffGLTarget, m_size, NULL, hint ); // may ultimately need more hints to set the usage correctly (esp for streaming)
this->SetModes( true, true, true );
m_ctx->BindBufferToCtx( m_type, NULL ); // unbind me
}
}
CGLMBuffer::~CGLMBuffer( )
{
m_ctx->CheckCurrent();
if (m_pseudo)
{
free (m_pseudoBuf);
m_pseudoBuf = NULL;
}
else
{
glDeleteBuffersARB( 1, &m_name );
GLMCheckError();
}
m_ctx = NULL;
m_name = 0;
m_bound = 0;
m_lastMappedAddress = NULL;
}
void CGLMBuffer::SetModes ( bool asyncMap, bool explicitFlush, bool force )
{
// assumes buffer is bound. called by constructor and by Lock.
if (m_pseudo)
{
// ignore it...
}
else
{
if (force || (m_enableAsyncMap != asyncMap) )
{
// note the sense of the parameter, it's TRUE if you *want* serialization, so for async you turn it to false.
glBufferParameteriAPPLE( this->m_buffGLTarget, GL_BUFFER_SERIALIZED_MODIFY_APPLE, asyncMap==false );
m_enableAsyncMap = asyncMap;
}
if (force || (m_enableExplicitFlush != explicitFlush) )
{
// note the sense of the parameter, it's TRUE if you *want* auto-flush-on-unmap, so for explicit-flush, you turn it to false.
glBufferParameteriAPPLE( this->m_buffGLTarget, GL_BUFFER_FLUSHING_UNMAP_APPLE, explicitFlush==false );
m_enableExplicitFlush = explicitFlush;
}
}
}
void CGLMBuffer::FlushRange ( uint offset, uint size )
{
if (m_pseudo)
{
// nothing to do
}
else
{
// assumes buffer is bound.
glFlushMappedBufferRangeAPPLE(this->m_buffGLTarget, (GLintptr)offset, (GLsizeiptr)size);
}
}
ConVar gl_buffer_alignment_quantum ( "gl_buffer_alignment_quantum", "32" ); // the alignment we use pre-SLGU
ConVar gl_buffer_alignment_quantum_slgu( "gl_buffer_alignment_quantum_slgu", "2" ); // alignment used post-SLGU
void CGLMBuffer::Lock( GLMBuffLockParams *params, char **addressOut )
{
char *resultPtr = NULL;
Assert( !m_mapped);
m_ctx->CheckCurrent();
GLMCheckError();
if (params->m_offset >= m_size)
Debugger();
if (params->m_offset + params->m_size > m_size)
Debugger();
// bind (yes, even for pseudo - this binds name 0)
m_ctx->BindBufferToCtx( this->m_type, this );
if (m_pseudo)
{
// discard is a no-op
// async map modes are a no-op
// latch last mapped address (silly..)
m_lastMappedAddress = (float*)m_pseudoBuf;
// calc lock address
resultPtr = m_pseudoBuf + params->m_offset;
// dirty range is a no-op
}
else
{
// perform discard if requested
if (params->m_discard)
{
// observe gl_bufmode on any orphan event.
// if orphaned and bufmode is nonzero, flip it to dynamic.
GLenum hint = gl_bufmode.GetInt() ? GL_DYNAMIC_DRAW_ARB : GL_STATIC_DRAW_ARB;
glBufferDataARB( m_buffGLTarget, m_size, NULL, hint );
m_lastMappedAddress = NULL;
m_revision++; // revision grows on orphan event
}
// adjust async map option appropriately, leave explicit flush unchanged
this->SetModes( params->m_nonblocking, m_enableExplicitFlush );
// map
char *mapPtr = (char*)glMapBufferARB( this->m_buffGLTarget, GL_READ_WRITE_ARB );
if (!mapPtr)
{
Debugger();
}
if (m_lastMappedAddress)
{
// just check if it moved
Assert (m_lastMappedAddress == (float*)mapPtr);
}
m_lastMappedAddress = (float*)mapPtr;
// calculate offset location
resultPtr = mapPtr + params->m_offset;
// adjust dirty range
if (m_dirtyMinOffset != m_dirtyMaxOffset)
{
// grow range
m_dirtyMinOffset = MIN( m_dirtyMinOffset, params->m_offset );
m_dirtyMaxOffset = MIN( m_dirtyMaxOffset, params->m_offset+params->m_size );
}
else
{
// set range
m_dirtyMinOffset = params->m_offset;
m_dirtyMaxOffset = params->m_offset+params->m_size;
}
// pad and clamp dirty range to choice of boundary
uint quantum = (m_ctx->Caps().m_hasPerfPackage1) ? gl_buffer_alignment_quantum_slgu.GetInt() : gl_buffer_alignment_quantum.GetInt();
uint quantum_mask = quantum - 1;
m_dirtyMinOffset = m_dirtyMinOffset & (~quantum_mask);
m_dirtyMaxOffset = (m_dirtyMaxOffset + quantum_mask) & (~quantum_mask);
m_dirtyMaxOffset = MIN( m_dirtyMaxOffset, m_size );
}
m_mapped = true;
*addressOut = resultPtr;
}
void CGLMBuffer::Unlock( void )
{
m_ctx->CheckCurrent();
Assert (m_mapped);
if (m_pseudo)
{
// nothing to do actually
}
else
{
m_ctx->BindBufferToCtx( this->m_type, this );
// time to do explicit flush
if (m_enableExplicitFlush)
{
this->FlushRange( m_dirtyMinOffset, m_dirtyMaxOffset - m_dirtyMinOffset );
}
// clear dirty range no matter what
m_dirtyMinOffset = m_dirtyMaxOffset = 0; // adjust/grow on lock, clear on unlock
glUnmapBuffer( this->m_buffGLTarget );
}
m_mapped = false;
}
+355
View File
@@ -0,0 +1,355 @@
//============ Copyright (c) Valve Corporation, All rights reserved. ============
//
// cglmfbo.cpp
//
//===============================================================================
#include "glmgr/glmgr.h"
#include "glmgr/cglmfbo.h"
// #include "../shaderapidx9/dxabstract.h"
// memdbgon -must- be the last include file in a .cpp file.
#include "tier0/memdbgon.h"
CGLMFBO::CGLMFBO( GLMContext *ctx )
{
m_ctx = ctx;
m_ctx->CheckCurrent();
glGenFramebuffersEXT( 1, &m_name );
GLMCheckError();
memset( m_attach, 0, sizeof( m_attach ) );
m_sizeX = m_sizeY = 0;
}
CGLMFBO::~CGLMFBO( )
{
m_ctx->CheckCurrent();
// detach all known attached textures first... necessary ?
for( int index = 0; index < kAttCount; index++)
{
if (m_attach[ index ].m_tex)
{
TexDetach( (EGLMFBOAttachment)index );
GLMCheckError();
}
}
glDeleteFramebuffersEXT( 1, &m_name );
GLMCheckError();
m_name = 0;
m_ctx = NULL;
}
// the tex attach path should also select a specific slice of the texture...
// and we need a way to make renderbuffers..
static GLenum EncodeAttachmentFBO( EGLMFBOAttachment index )
{
if (index < kAttDepth)
{
return GL_COLOR_ATTACHMENT0_EXT + (int) index;
}
else
{
switch( index )
{
case kAttDepth:
return GL_DEPTH_ATTACHMENT_EXT;
break;
case kAttStencil:
return GL_STENCIL_ATTACHMENT_EXT;
break;
case kAttDepthStencil:
return GL_DEPTH_STENCIL_ATTACHMENT_EXT;
break;
default:
GLMStop(); // bad news
break;
}
}
}
void CGLMFBO::TexAttach( GLMFBOTexAttachParams *params, EGLMFBOAttachment attachIndex, GLenum fboBindPoint )
{
// force our parent context to be current
m_ctx->MakeCurrent();
// bind to context (will cause FBO object creation on first use)
m_ctx->BindFBOToCtx( this, fboBindPoint );
// it's either a plain 2D, a 2D face of a cube map, or a slice of a 3D.
CGLMTex *tex = params->m_tex;
// always detach what is currently there, if anything
this->TexDetach( attachIndex, fboBindPoint );
if (!tex)
{
// andif they pass NULL to us, then we are done.
return;
}
GLMTexLayout *layout = tex->m_layout;
GLenum target = tex->m_layout->m_key.m_texGLTarget;
GLenum attachIndexGL = EncodeAttachmentFBO( attachIndex );
switch( target )
{
case GL_TEXTURE_2D:
{
// we will attach the underlying RBO on a multisampled tex, iff the tex hasone, **and** we're not being asked to attach it to the read buffer.
// if we get a req to attach an MSAA tex to the read buffer, chances are it's BlitTex calling, andit has already resolved the tex, so in those
// cases you really do want to attach the texture and not the RBO to the FBO in question.
bool useRBO = false; // initial state
if (layout->m_key.m_texFlags & kGLMTexMultisampled)
{
// it is an MSAA tex
if (fboBindPoint == GL_READ_FRAMEBUFFER_EXT)
{
// I think you just want to read a resolved tex.
// But I will check that it is resolved first..
Assert( tex->m_rboDirty == false );
}
else
{
// you want to draw into it. You get the RBO bound instead of the tex.
useRBO = true;
}
}
if (useRBO)
{
// MSAA path - attach the RBO, not the texture, and mark the RBO dirty
if (attachIndexGL==GL_DEPTH_STENCIL_ATTACHMENT_EXT)
{
// you have to attach it both places...
// http://www.opengl.org/wiki/GL_EXT_framebuffer_object
// bind the RBO to the GL_RENDERBUFFER_EXT target
glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, tex->m_rboName );
GLMCheckError();
// attach the GL_RENDERBUFFER_EXT target to the depth and stencil attach points
glFramebufferRenderbufferEXT( fboBindPoint, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, tex->m_rboName);
GLMCheckError();
glFramebufferRenderbufferEXT( fboBindPoint, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, tex->m_rboName);
GLMCheckError();
// no need to leave the RBO hanging on
glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 );
GLMCheckError();
}
else
{
// color attachment (likely 0)
glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, tex->m_rboName );
GLMCheckError();
glFramebufferRenderbufferEXT( fboBindPoint, attachIndexGL, GL_RENDERBUFFER_EXT, tex->m_rboName);
GLMCheckError();
glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 );
GLMCheckError();
}
tex->m_rboDirty = true;
}
else
{
// regular path - attaching a texture2d
if (attachIndexGL==GL_DEPTH_STENCIL_ATTACHMENT_EXT)
{
// you have to attach it both places...
// http://www.opengl.org/wiki/GL_EXT_framebuffer_object
glFramebufferTexture2DEXT( fboBindPoint, GL_DEPTH_ATTACHMENT_EXT, target, tex->m_texName, params->m_mip );
GLMCheckError();
glFramebufferTexture2DEXT( fboBindPoint, GL_STENCIL_ATTACHMENT_EXT, target, tex->m_texName, params->m_mip );
GLMCheckError();
}
else
{
glFramebufferTexture2DEXT( fboBindPoint, attachIndexGL, target, tex->m_texName, params->m_mip );
GLMCheckError();
}
}
}
break;
case GL_TEXTURE_3D:
{
glFramebufferTexture3DEXT( fboBindPoint, attachIndexGL, target, tex->m_texName, params->m_mip, params->m_zslice );
GLMCheckError();
}
break;
case GL_TEXTURE_CUBE_MAP:
{
// adjust target to steer to the proper face of the cube map
target = GL_TEXTURE_CUBE_MAP_POSITIVE_X + params->m_face;
glFramebufferTexture2DEXT( fboBindPoint, attachIndexGL, target, tex->m_texName, params->m_mip );
GLMCheckError();
}
break;
}
// log the attached tex
m_attach[ attachIndex ] = *params;
// indicate that the tex has been bound to an RT
tex->m_rtAttachCount++;
}
void CGLMFBO::TexDetach( EGLMFBOAttachment attachIndex, GLenum fboBindPoint )
{
// force our parent context to be current
m_ctx->MakeCurrent();
// bind to context (will cause FBO object creation on first use)
m_ctx->BindFBOToCtx( this, fboBindPoint );
if (m_attach[ attachIndex ].m_tex)
{
CGLMTex *tex = m_attach[ attachIndex ].m_tex;
GLMTexLayout *layout = tex->m_layout;
GLenum target = tex->m_layout->m_key.m_texGLTarget;
GLenum attachIndexGL = EncodeAttachmentFBO( attachIndex );
switch( target )
{
case GL_TEXTURE_2D:
{
if (layout->m_key.m_texFlags & kGLMTexMultisampled)
{
// MSAA path - detach the RBO, not the texture
// (is this the right time to resolve? probably better to wait until someone tries to sample the texture)
glBindRenderbufferEXT( GL_RENDERBUFFER_EXT, 0 );
GLMCheckError();
if (attachIndexGL==GL_DEPTH_STENCIL_ATTACHMENT_EXT)
{
// detach the GL_RENDERBUFFER_EXT target at depth and stencil attach points
glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
GLMCheckError();
glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, 0);
GLMCheckError();
}
else
{
// color attachment (likely 0)
glFramebufferRenderbufferEXT( GL_FRAMEBUFFER_EXT, attachIndexGL, GL_RENDERBUFFER_EXT, 0);
GLMCheckError();
}
}
else
{
// plain tex detach
if (attachIndexGL==GL_DEPTH_STENCIL_ATTACHMENT_EXT)
{
// you have to detach it both places...
// http://www.opengl.org/wiki/GL_EXT_framebuffer_object
glFramebufferTexture2DEXT( fboBindPoint, GL_DEPTH_ATTACHMENT_EXT, 0,0,0 );
glFramebufferTexture2DEXT( fboBindPoint, GL_STENCIL_ATTACHMENT_EXT, 0,0,0 );
}
else
{
glFramebufferTexture2DEXT( fboBindPoint, attachIndexGL, 0, 0, 0 );
}
}
}
break;
case GL_TEXTURE_3D:
{
glFramebufferTexture3DEXT( fboBindPoint, attachIndexGL, 0, 0, 0, 0 );
GLMCheckError();
}
break;
case GL_TEXTURE_CUBE_MAP:
{
glFramebufferTexture2DEXT( fboBindPoint, attachIndexGL, 0, 0, 0 );
GLMCheckError();
}
break;
}
// un-log the attached tex
memset( &m_attach[ attachIndex ], 0, sizeof( m_attach[0] ) );
// drop the RT attach count
tex->m_rtAttachCount--;
}
else
{
//Debugger(); // odd, but not harmful - typ comes from D3D code passing NULL into SetRenderTarget
}
}
void CGLMFBO::TexScrub( CGLMTex *tex )
{
// see if it's attached anywhere
for( int attachIndex = 0; attachIndex < kAttCount; attachIndex++ )
{
if (m_attach[ attachIndex ].m_tex == tex)
{
// blammo
TexDetach( (EGLMFBOAttachment)attachIndex, GL_DRAW_FRAMEBUFFER_EXT );
}
}
}
bool CGLMFBO::IsReady( void )
{
bool result = false;
// ensure our parent context is current
m_ctx->CheckCurrent();
// bind to context (will cause FBO object creation on first use)
m_ctx->BindFBOToCtx( this );
GLenum status;
status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
switch(status)
{
case GL_FRAMEBUFFER_COMPLETE_EXT:
result = true;
break;
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
result = false;
Debugger();
/* choose different formats */
break;
default:
result = false;
Debugger();
/* programming error; will fail on all hardware */
break;
}
return result;
}
File diff suppressed because it is too large. Load diff
+413
View File
@@ -0,0 +1,413 @@
//============ Copyright (c) Valve Corporation, All rights reserved. ============
//
// cglmquery.cpp
//
//===============================================================================
#include "glmgr/glmgr.h"
#include "glmgr/cglmquery.h"
#include "../shaderapidx9/dxabstract.h"
#include <unistd.h>
// memdbgon -must- be the last include file in a .cpp file.
#include "tier0/memdbgon.h"
//===============================================================================
extern ConVar gl_errorcheckall;
extern ConVar gl_errorcheckqueries;
extern ConVar gl_errorchecknone;
// how many microseconds to wait after a failed query-available test
// presently on MTGL this doesn't happen, but it could change, keep this handy
ConVar gl_nullqueries( "gl_nullqueries", "0" );
GLenum GetQueryError( void )
{
if ( ( GLMDEBUG || (gl_errorcheckall.GetInt() != 0) || (gl_errorcheckqueries.GetInt() != 0) ) && (gl_errorchecknone.GetInt() == 0) )
{
return glGetError();
}
else
{
return (GLenum) 0; // whistle past graveyard
}
}
//===============================================================================
CGLMQuery::CGLMQuery( GLMContext *ctx, GLMQueryParams *params )
{
// make sure context is current
// get the type of query requested
// generate name(s) needed
// set initial state appropriately
ctx->MakeCurrent();
m_ctx = ctx;
m_params = *params;
m_name = 0;
m_started = m_stopped = m_done = false;
m_nullQuery = false;
// assume value of convar at start time
// does not change during individual query lifetime
// started null = stays null
// started live = stays live
switch(m_params.m_type)
{
case EOcclusion:
{
//make an occlusion query (and a fence to go with it)
glGenQueriesARB( 1, &m_name );
GLMPRINTF(("-A- CGLMQuery(OQ) created name %d", m_name));
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::CGLMQuery (OQ) saw %s error (%d) from glGenQueriesARB", decodedStr, errorcode );
m_name = 0;
}
}
break;
case EFence:
//make a fence - no aux fence needed
glGenFencesAPPLE(1, &m_name );
GLMPRINTF(("-A- CGLMQuery(fence) created name %d", m_name));
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::CGLMQuery (fence) saw %s error (%d) from glGenFencesAPPLE", decodedStr, errorcode );
m_name = 0;
}
break;
}
}
CGLMQuery::~CGLMQuery()
{
GLMPRINTF(("-A-> ~CGLMQuery"));
// make sure query has completed (might not be necessary)
// delete the name(s)
m_ctx->MakeCurrent();
switch(m_params.m_type)
{
case EOcclusion:
{
// do a finish occlusion query ?
GLMPRINTF(("-A- ~CGLMQuery(OQ) deleting name %d", m_name));
glDeleteQueries(1, &m_name );
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::~CGLMQuery (OQ) saw %s error (%d) from glDeleteQueries", decodedStr, errorcode );
}
}
break;
case EFence:
{
// do a finish fence ?
GLMPRINTF(("-A- ~CGLMQuery(fence) deleting name %d", m_name));
glDeleteFencesAPPLE(1, &m_name );
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::~CGLMQuery (fence) saw %s error (%d) from glDeleteFencesAPPLE", decodedStr, errorcode );
}
}
break;
}
m_name = 0;
GLMPRINTF(("-A-< ~CGLMQuery"));
}
void CGLMQuery::Start( void ) // "start counting"
{
m_ctx->MakeCurrent();
// on occlusion query:
// glBeginQueryARB on the OQ name. counting starts.
// on fence: glSetFence on m_name.
// note, fences finish themselves via command progress - OQ's do not.
Assert(!m_started);
Assert(!m_stopped);
Assert(!m_done);
m_nullQuery = (gl_nullqueries.GetInt() != 0); // latch value for remainder of query life
switch(m_params.m_type)
{
case EOcclusion:
{
if (m_nullQuery)
{
// do nothing..
}
else
{
glBeginQueryARB( GL_SAMPLES_PASSED_ARB, m_name );
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::Start(OQ) saw %s error (%d) from glBeginQueryARB (GL_SAMPLES_PASSED_ARB) name=%d", decodedStr, errorcode, m_name );
}
}
}
break;
case EFence:
glSetFenceAPPLE( m_name );
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::Start(fence) saw %s error (%d) from glSetFenceAPPLE name=%d", decodedStr, errorcode, m_name );
}
m_stopped = true; // caller should not call Stop on a fence, it self-stops
break;
}
m_started = true;
}
void CGLMQuery::Stop( void ) // "stop counting"
{
m_ctx->MakeCurrent();
Assert(m_started);
Assert(!m_stopped); // this will assert if you try to call Stop on a fence that is started
Assert(!m_done);
switch(m_params.m_type)
{
case EOcclusion:
{
if (m_nullQuery)
{
// do nothing..
}
else
{
glEndQueryARB( GL_SAMPLES_PASSED_ARB ); // we are only putting the request-to-stop-counting into the cmd stream.
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::Stop(OQ) saw %s error (%d) from glEndQueryARB( GL_SAMPLES_PASSED_ARB ) name=%d", decodedStr, errorcode, m_name );
}
}
}
break;
case EFence:
// nop - you don't "end" a fence, you just test it and/or finish it out in Complete
break;
}
m_stopped = true;
}
bool CGLMQuery::IsDone( void )
{
m_ctx->MakeCurrent();
Assert(m_started);
Assert(m_stopped);
if(!m_done) // you can ask more than once, but we only check until it comes back as done.
{
// on occlusion: glGetQueryObjectivARB - large cost on pre SLGU, cheap after
// on fence: glTestFenceAPPLE on the fence
switch(m_params.m_type)
{
case EOcclusion: // just test the fence that was set after the query begin
{
if (m_nullQuery)
{
// do almost nothing.. but claim work is complete
m_done = true;
}
else
{
// prepare to pay a big price on drivers prior to 10.6.4+SLGU
GLint available = 0;
glGetQueryObjectivARB(m_name, GL_QUERY_RESULT_AVAILABLE_ARB, &available );
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::IsDone saw %s error (%d) from glGetQueryObjectivARB(a2) name=%d", decodedStr, errorcode, m_name );
}
m_done = (available != 0);
}
}
break;
case EFence:
{
m_done = glTestFenceAPPLE( m_name );
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::IsDone saw %s error (%d) from glTestFenceAPPLE(b) name=%d", decodedStr, errorcode, m_name );
}
if (m_done)
{
glFinishFenceAPPLE( m_name ); // no set fence goes un-finished
errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::IsDone saw %s error (%d) from glFinishFenceAPPLE(b) name=%d", decodedStr, errorcode, m_name );
}
}
}
break;
}
}
return m_done;
}
void CGLMQuery::Complete( uint *result )
{
m_ctx->MakeCurrent();
uint resultval = 0;
GLint available = 0;
bool bogus_available = false;
// blocking call if not done
Assert(m_started);
Assert(m_stopped);
switch(m_params.m_type)
{
case EOcclusion:
{
if (m_nullQuery)
{
m_done = true;
resultval = 0; // we did say "null queries..."
}
else
{
// accept that the query is going to drain pipe in 10.6.4 and prior.
// check the error on the spot.
glGetQueryObjectivARB(m_name, GL_QUERY_RESULT_AVAILABLE_ARB, &available );
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::Complete saw %s error (%d) from glGetQueryObjectivARB GL_QUERY_RESULT_AVAILABLE_ARB name=%d", decodedStr, errorcode, m_name );
resultval=0;
}
else
{
if (!available)
{
// this does happen with some very modest frequency.
if (!m_ctx->Caps().m_hasPerfPackage1)
{
glFlush(); // ISTR some deadlock cases on pre-SLGU drivers if you didn't do this to kick the queue along..
}
}
glGetQueryObjectuivARB( m_name, GL_QUERY_RESULT_ARB, &resultval);
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::Complete saw %s error (%d) from glGetQueryObjectivARB GL_QUERY_RESULT_ARB name=%d", decodedStr, errorcode, m_name );
resultval=0;
}
else
{
// resultval is legit
}
}
m_done = true;
}
}
break;
case EFence:
{
if(!m_done)
{
glFinishFenceAPPLE( m_name );
GLenum errorcode = GetQueryError();
if (errorcode)
{
const char *decodedStr = GLMDecode( eGL_ERROR, errorcode );
printf( "\nCGLMQuery::Complete saw %s error (%d) from glFinishFenceAPPLE (EFence) name=%d", decodedStr, errorcode, m_name );
}
m_done = true; // for clarity or if they try to Complete twice
}
}
break;
}
Assert( m_done );
// reset state for re-use - i.e. you have to call Complete if you want to re-use the object
m_started = m_stopped = m_done = false;
if (result) // caller may pass NULL if not interested in result, for example to clear a fence
{
*result = resultval;
}
}
// accessors for the started/stopped state
bool CGLMQuery::IsStarted ( void )
{
return m_started;
}
bool CGLMQuery::IsStopped ( void )
{
return m_stopped;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+80
View File
@@ -0,0 +1,80 @@
//========= Copyright 1996-2009, Valve Corporation, All rights reserved. ============//
//
// Purpose: provide some call-out glue to ObjC from the C++ GLMgr code
//
// $Revision: $
// $NoKeywords: $
//=============================================================================//
#include <Cocoa/Cocoa.h>
#undef MIN
#undef MAX
#define DONT_DEFINE_BOOL // Don't define BOOL!
#include "tier0/threadtools.h"
#include "tier1/interface.h"
#include "tier1/strtools.h"
#include "tier1/utllinkedlist.h"
#include "glmgr/glmgr.h"
// ------------------------------------------------------------------------------------ //
// some glue to let GLMgr call into NS/ObjC classes.
// ------------------------------------------------------------------------------------ //
bool NewNSGLContext( unsigned long *attribs, PseudoNSGLContextPtr nsglShareCtx, PseudoNSGLContextPtr *nsglCtxOut, CGLContextObj *cglCtxOut )
{
NSAutoreleasePool *tempPool = [[NSAutoreleasePool alloc] init ];
NSOpenGLPixelFormat *pixFmt = NULL;
NSOpenGLContext *nsglCtx = NULL;
bool result = true; // optimism
if (result)
{
pixFmt = [[NSOpenGLPixelFormat alloc] initWithAttributes:(NSOpenGLPixelFormatAttribute*)attribs];
if (!pixFmt)
{
Debugger(); // bad news
result = false;
}
}
if (result)
{
nsglCtx = [[NSOpenGLContext alloc] initWithFormat: pixFmt shareContext: (NSOpenGLContext*) nsglShareCtx ];
if (!nsglCtx)
{
Debugger();
result = false;
}
}
if (result)
{
[nsglCtx makeCurrentContext];
*nsglCtxOut = nsglCtx;
*cglCtxOut = (CGLContextObj)[ (NSOpenGLContext*)nsglCtx CGLContextObj ];
}
else
{
*nsglCtxOut = NULL;
*cglCtxOut = NULL;
}
[tempPool release];
return result;
}
CGLContextObj GetCGLContextFromNSGL( PseudoNSGLContextPtr nsglCtx )
{
return (CGLContextObj)[ (NSOpenGLContext*)nsglCtx CGLContextObj];
}
void DelNSGLContext( PseudoNSGLContextPtr nsglCtx )
{
[ (NSOpenGLContext*)nsglCtx release ];
}
+104
View File
@@ -0,0 +1,104 @@
//============ Copyright (c) Valve Corporation, All rights reserved. ============
//
// glmgrext.h
// helper file for extension testing and runtime importing of entry points
//
//===============================================================================
#pragma once
#include <OpenGL/gl.h>
#include <OpenGL/glext.h>
#include <mach-o/dyld.h>
#include <stdlib.h>
#include <string.h>
#include "glmgr/glmgr.h"
PFNglColorMaskIndexedEXT pfnglColorMaskIndexedEXT;
PFNglEnableIndexedEXT pfnglEnableIndexedEXT;
PFNglDisableIndexedEXT pfnglDisableIndexedEXT;
PFNglGetFramebufferAttachmentParameteriv pfnglGetFramebufferAttachmentParameteriv;
PFNglUniformBufferEXT pfnglUniformBufferEXT;
void * NSGLGetProcAddress (const char *name)
{
NSSymbol symbol;
char *symbolName = (char *)malloc (strlen (name) + 2);
strcpy(symbolName + 1, name);
symbolName[0] = '_';
symbol = NULL;
if (NSIsSymbolNameDefined (symbolName))
symbol = NSLookupAndBindSymbol (symbolName);
free (symbolName);
return symbol ? NSAddressOfSymbol (symbol) : NULL;
}
void GLMSetupExtensions( void )
{
pfnglColorMaskIndexedEXT = (PFNglColorMaskIndexedEXT) NSGLGetProcAddress( "glColorMaskIndexedEXT" );
pfnglEnableIndexedEXT = (PFNglEnableIndexedEXT) NSGLGetProcAddress( "glEnableIndexedEXT" );
pfnglDisableIndexedEXT = (PFNglDisableIndexedEXT) NSGLGetProcAddress( "glDisableIndexedEXT" );
pfnglGetFramebufferAttachmentParameteriv = (PFNglGetFramebufferAttachmentParameteriv) NSGLGetProcAddress( "glGetFramebufferAttachmentParameteriv" );
pfnglUniformBufferEXT = (PFNglUniformBufferEXT) NSGLGetProcAddress( "glUniformBufferEXT" );
}
/*
#define INSTANTIATE_GL_IMPORTS
#include "glmgr/glmgr.h" // will include glmgrext.h
#undef INSTANTIATE_GL_IMPORTS
// helper class for looking up function names
// see http://andrewtolbert.com/svn/personal/OpenGLSuperBible/shared/gltools.cpp
// also http://developer.apple.com/mac/library/DOCUMENTATION/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/opengl_entrypts/opengl_entrypts.html
class CFunctionImporter
{
public:
CFBundleRef m_bundle;
CFunctionImporter( CFStringRef bundleID ) // for example CFSTR("com.apple.OpenGL")
{
m_bundle = CFBundleGetBundleWithIdentifier( bundleID );
if ( m_bundle )
CFRetain( m_bundle );
}
~CFunctionImporter()
{
if( m_bundle )
{
CFRelease(m_bundle);
m_bundle = NULL;
}
}
void *FindFunctionByName(CFStringRef name) // ex CFSTR("glColorMaskedIndexedEXT")
{
void *result = NULL;
if (m_bundle)
{
result = CFBundleGetFunctionPointerForName(m_bundle, name);
}
return result;
}
};
void GLMSetupExtensions( void )
{
CFunctionImporter importer( CFSTR("com.apple.OpenGL") );
#define DO_IMPORT(name) name = (name##FuncPtr)importer.FindFunctionByName( CFSTR(#name) );
#ifndef GL_EXT_draw_buffers2
// FIXME we're not checking for the extension string yet, we're just grabbing func ptrs
DO_IMPORT(glColorMaskIndexedEXT);
DO_IMPORT(glEnableIndexedEXT);
DO_IMPORT(glDisableIndexedEXT);
#endif
}
*/
+26
View File
@@ -0,0 +1,26 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#ifndef IFONT_H
#define IFONT_H
#include "platform.h"
// font interface
class IFont
{
public:
virtual void RenderToBuffer(int ch, int offsetx, int width, int height, unsigned char *pBuffer) = 0;
virtual bool GetCharABCWidth(int ch, int &a, int &b, int &c) = 0;
virtual int GetMaxHeight() = 0;
virtual int GetMaxWidth() = 0;
virtual int GetAscent() = 0;
};
#endif
+169
View File
@@ -0,0 +1,169 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=====================================================================================//
#include "imagepacker.h"
#include "materialsystem_global.h"
#include "IHardwareConfigInternal.h"
// NOTE: This has to be the last file included
#include "tier0/memdbgon.h"
float CImagePacker::GetEfficiency( void )
{
return ( float )m_AreaUsed / ( float )( m_MaxLightmapWidth * CeilPow2( m_MinimumHeight ) );
}
bool CImagePacker::Reset( int nSortId, int maxLightmapWidth, int maxLightmapHeight )
{
int i;
Assert( maxLightmapWidth <= MAX_MAX_LIGHTMAP_WIDTH );
m_MaxLightmapWidth = maxLightmapWidth;
m_MaxLightmapHeight = maxLightmapHeight;
m_MaxBlockWidth = maxLightmapWidth + 1;
m_MaxBlockHeight = maxLightmapHeight + 1;
m_nSortID = nSortId;
m_AreaUsed = 0;
m_MinimumHeight = -1;
for( i = 0; i < m_MaxLightmapWidth; i++ )
{
m_pLightmapWavefront[i] = -1;
}
return true;
}
inline int CImagePacker::GetMaxYIndex( int firstX, int width )
{
int maxY = -1;
int maxYIndex = 0;
for( int x = firstX; x < firstX + width; ++x )
{
// NOTE: Want the equals here since we'll never be able to fit
// in between the multiple instances of maxY
if( m_pLightmapWavefront[x] >= maxY )
{
maxY = m_pLightmapWavefront[x];
maxYIndex = x;
}
}
return maxYIndex;
}
//#define ADD_ONE_TEXEL_BORDER
bool CImagePacker::AddBlock( int width, int height,
int *returnX, int *returnY )
{
#ifdef ADD_ONE_TEXEL_BORDER
width += 2;
height += 2;
width = clamp( width, m_MaxLightmapWidth );
height = clamp( height, m_MaxLightmapHeight );
#endif
// If we've already determined that a block this big couldn't fit
// then blow off checking again...
if ( ( width >= m_MaxBlockWidth ) && ( height >= m_MaxBlockHeight ) )
return false;
int bestX = -1;
int maxYIdx;
int outerX = 0;
int outerMinY = m_MaxLightmapHeight;
int lastX = m_MaxLightmapWidth - width;
int lastMaxYVal = -2;
while (outerX <= lastX)
{
// Skip all tiles that have the last Y value, these
// aren't going to change our min Y value
if (m_pLightmapWavefront[outerX] == lastMaxYVal)
{
++outerX;
continue;
}
maxYIdx = GetMaxYIndex( outerX, width );
lastMaxYVal = m_pLightmapWavefront[maxYIdx];
if (outerMinY > lastMaxYVal)
{
outerMinY = lastMaxYVal;
bestX = outerX;
// Early out for the first row...
// if (outerMinY == -1)
// break;
}
outerX = maxYIdx + 1;
}
if( bestX == -1 )
{
// If we failed to add it, remember the block size that failed
// *only if both dimensions are smaller*!!
// Just because a 1x10 block failed, doesn't mean a 10x1 block will fail
if ( ( width <= m_MaxBlockWidth ) && ( height <= m_MaxBlockHeight ) )
{
m_MaxBlockWidth = width;
m_MaxBlockHeight = height;
}
return false;
}
// Set the return positions for the block.
*returnX = bestX;
*returnY = outerMinY + 1;
// Check if it actually fit height-wise.
// hack
// if( *returnY + height > maxLightmapHeight )
if( *returnY + height >= m_MaxLightmapHeight - 1 )
{
if ( ( width <= m_MaxBlockWidth ) && ( height <= m_MaxBlockHeight ) )
{
m_MaxBlockWidth = width;
m_MaxBlockHeight = height;
}
return false;
}
// It fit!
// Keep up with the smallest possible size for the image so far.
if( *returnY + height > m_MinimumHeight )
m_MinimumHeight = *returnY + height;
// Update the wavefront info.
int x;
for( x = bestX; x < bestX + width; x++ )
{
m_pLightmapWavefront[x] = outerMinY + height;
}
// AddBlockToLightmapImage( *returnX, *returnY, width, height );
m_AreaUsed += width * height;
#ifdef ADD_ONE_TEXEL_BORDER
*returnX++;
*returnY++;
#endif
return true;
}
void CImagePacker::GetMinimumDimensions( int *pReturnWidth, int *pReturnHeight )
{
*pReturnWidth = CeilPow2( m_MaxLightmapWidth );
*pReturnHeight = CeilPow2( m_MinimumHeight );
int aspect = *pReturnWidth / *pReturnHeight;
if (aspect > HardwareConfig()->MaxTextureAspectRatio())
{
*pReturnHeight = *pReturnWidth / HardwareConfig()->MaxTextureAspectRatio();
}
}
+69
View File
@@ -0,0 +1,69 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#ifndef IMAGEPACKER_H
#define IMAGEPACKER_H
#ifdef _WIN32
#pragma once
#endif
#include "utlvector.h"
#include "utlrbtree.h"
#define MAX_MAX_LIGHTMAP_WIDTH 2048
//-----------------------------------------------------------------------------
// This packs a single lightmap
//-----------------------------------------------------------------------------
class CImagePacker
{
public:
bool Reset( int nSortId, int maxLightmapWidth, int maxLightmapHeight );
bool AddBlock( int width, int height,
int *returnX, int *returnY );
void GetMinimumDimensions( int *returnWidth, int *returnHeight );
float GetEfficiency( void );
int GetSortId() const;
void IncrementSortId();
protected:
int GetMaxYIndex( int firstX, int width );
int m_MaxLightmapWidth;
int m_MaxLightmapHeight;
int m_pLightmapWavefront[MAX_MAX_LIGHTMAP_WIDTH];
int m_AreaUsed;
int m_MinimumHeight;
// For optimization purposes:
// These store the width + height of the first image
// that was unable to be stored in this image
int m_MaxBlockWidth;
int m_MaxBlockHeight;
int m_nSortID;
};
//-----------------------------------------------------------------------------
// Inline methods
//-----------------------------------------------------------------------------
inline int CImagePacker::GetSortId() const
{
return m_nSortID;
}
inline void CImagePacker::IncrementSortId()
{
++m_nSortID;
}
#endif // IMAGEPACKER_H
+186
View File
@@ -0,0 +1,186 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#ifndef IMATERIALINTERNAL_H
#define IMATERIALINTERNAL_H
#ifdef _WIN32
#pragma once
#endif
// identifier was truncated to '255' characters in the debug information
#pragma warning(disable: 4786)
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/imaterial.h"
#include "shaderapi/ishaderapi.h"
#include "filesystem.h"
//-----------------------------------------------------------------------------
// forward declarations
//-----------------------------------------------------------------------------
enum MaterialPrimitiveType_t;
class IShader;
class IMesh;
class IVertexBuffer;
class IIndexBuffer;
struct Shader_VertexArrayData_t;
struct ShaderRenderState_t;
class KeyValues;
class CBasePerMaterialContextData;
struct tokencache_t
{
unsigned short symbol;
unsigned char varIndex;
unsigned char cached : 1;
unsigned char subrect : 1;
};
//-----------------------------------------------------------------------------
// Interface for materials used only within the material system
//-----------------------------------------------------------------------------
abstract_class IMaterialInternal : public IMaterial
{
public:
// class factory methods
static IMaterialInternal* CreateMaterial( char const* pMaterialName, const char *pTextureGroupName, KeyValues *pKeyValues = NULL );
static void DestroyMaterial( IMaterialInternal* pMaterial );
// If supplied, pKeyValues and pPatchKeyValues should come from LoadVMTFile()
static IMaterialInternal* CreateMaterialSubRect( char const* pMaterialName, const char *pTextureGroupName,
KeyValues *pKeyValues = NULL, KeyValues *pPatchKeyValues = NULL, bool bAssumeCreateFromFile = false );
static void DestroyMaterialSubRect( IMaterialInternal* pMaterial );
// refcount
virtual int GetReferenceCount( ) const = 0;
// enumeration id
virtual void SetEnumerationID( int id ) = 0;
// White lightmap methods
virtual void SetNeedsWhiteLightmap( bool val ) = 0;
virtual bool GetNeedsWhiteLightmap( ) const = 0;
// load/unload
virtual void Uncache( bool bPreserveVars = false ) = 0;
virtual void Precache() = 0;
// If supplied, pKeyValues and pPatchKeyValues should come from LoadVMTFile()
virtual bool PrecacheVars( KeyValues *pKeyValues = NULL, KeyValues *pPatchKeyValues = NULL, CUtlVector<FileNameHandle_t> *pIncludes = NULL ) = 0;
// reload all textures used by this materals
virtual void ReloadTextures() = 0;
// lightmap pages associated with this material
virtual void SetMinLightmapPageID( int pageID ) = 0;
virtual void SetMaxLightmapPageID( int pageID ) = 0;;
virtual int GetMinLightmapPageID( ) const = 0;
virtual int GetMaxLightmapPageID( ) const = 0;
virtual IShader *GetShader() const = 0;
virtual IMaterialVar** GetVars() { return NULL; }
// Can we use it?
virtual bool IsPrecached( ) const = 0;
virtual bool IsPrecachedVars() const = 0;
// main draw method
virtual CBasePerMaterialContextData **GetContextData( int modulationFlags ) { return NULL; }
virtual StateSnapshot_t GetSnapshotId( int modulation, int renderPass ) { return (StateSnapshot_t)-1; }
virtual unsigned char* GetInstanceCommandBuffer( int modulation ) { return NULL; }
virtual void DrawMesh( VertexCompressionType_t vertexCompression, bool bIsAlphaModulating, bool bUsingPreTessPatches ) = 0;
// Gets the vertex format
virtual VertexFormat_t GetVertexFormat() const = 0;
virtual VertexFormat_t GetVertexUsage() const = 0;
// Performs a debug trace on this material
virtual bool PerformDebugTrace() const = 0;
// Can we override this material in debug?
virtual bool NoDebugOverride() const = 0;
// Should we draw?
virtual void ToggleSuppression() = 0;
// Are we suppressed?
virtual bool IsSuppressed() const = 0;
// Should we debug?
virtual void ToggleDebugTrace() = 0;
// Do we use fog?
virtual bool UseFog() const = 0;
// Adds a material variable to the material
virtual void AddMaterialVar( IMaterialVar *pMaterialVar ) = 0;
// Gets the renderstate
virtual ShaderRenderState_t *GetRenderState() = 0;
// Was this manually created (not read from a file?)
virtual bool IsManuallyCreated() const = 0;
virtual bool NeedsFixedFunctionFlashlight() const = 0;
virtual bool IsUsingVertexID() const = 0;
// Identifies a material mounted through the preload path
virtual void MarkAsPreloaded( bool bSet ) = 0;
virtual bool IsPreloaded() const = 0;
// Conditonally increments the refcount
virtual void ArtificialAddRef( void ) = 0;
virtual void ArtificialRelease( void ) = 0;
virtual void ReportVarChanged( IMaterialVar *pVar ) = 0;
virtual uint32 GetChangeID() const = 0;
virtual uint32 GetChangeTimestamp() const { return 0; }
virtual bool IsTranslucentInternal( float fAlphaModulation ) const = 0;
//Is this the queue friendly or realtime version of the material?
virtual bool IsRealTimeVersion( void ) const = 0;
virtual void ClearContextData( void )
{
}
//easy swapping between the queue friendly and realtime versions of the material
virtual IMaterialInternal *GetRealTimeVersion( void ) = 0;
virtual IMaterialInternal *GetQueueFriendlyVersion( void ) = 0;
virtual void PrecacheMappingDimensions( void ) = 0;
virtual void FindRepresentativeTexture( void ) = 0;
// These are used when a new whitelist is passed in. First materials to be reloaded are flagged, then they are reloaded.
virtual void DecideShouldReloadFromWhitelist( IFileList *pFileList ) = 0;
virtual void ReloadFromWhitelistIfMarked() = 0;
virtual void CompactMaterialVars() = 0;
// Are any of the proxies attached to this material callable from the queued thread?
virtual bool HasQueueFriendlyProxies() const = 0;
};
extern void InsertKeyValues( KeyValues& dst, KeyValues& src, bool bCheckForExistence );
extern void WriteKeyValuesToFile( const char *pFileName, KeyValues& keyValues );
extern void ExpandPatchFile( KeyValues& keyValues, KeyValues &patchKeyValues );
// patchKeyValues accumulates keys applied by VMT patch files (this is necessary to make $fallbackmaterial
// work properly - the patch keys need to be reapplied when the fallback VMT is loaded). It may contain
// previously accumulated patch keys on entry, and may contain more encountered patch keys on exit.
extern bool LoadVMTFile( KeyValues &vmtKeyValues, KeyValues &patchKeyValues, const char *pMaterialName, bool bUsesUNCFilename, CUtlVector<FileNameHandle_t> *pIncludes );
extern void CompactMaterialVars( IMaterialVar **ppMaterialVars, int nVars );
extern void CompactMaterialVarHeap();
#endif // IMATERIALINTERNAL_H
+272
View File
@@ -0,0 +1,272 @@
//========= Copyright (c) 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#ifndef IMATERIALSYSTEMINTERNAL_H
#define IMATERIALSYSTEMINTERNAL_H
#ifdef _WIN32
#pragma once
#endif
#include "materialsystem/imaterialsystem.h"
#include "tier1/callqueue.h"
#include "tier1/memstack.h"
#include "tier1/fmtstr.h"
#include "tier0/vprof_telemetry.h"
#include "tier0/perfstats.h"
class IMaterialInternal;
//-----------------------------------------------------------------------------
// Special call queue that knows (a) single threaded access, and (b) all
// functions called after last function added
//-----------------------------------------------------------------------------
class CMatCallQueue
{
public:
CMatCallQueue()
{
static int nStackCount = 0;
CFmtStr stackName( "CMatCallQueue.m_Allocator[%d]", nStackCount++ );
#ifdef DEDICATED
m_Allocator.Init( (const char *)stackName, 2*1024, 0, 0, 4 );
#else
m_Allocator.Init( (const char *)stackName, ( IsGameConsole() || IsPlatformPosix() ) ? 2*1024*1024 : 8*1024*1024, 64*1024, 256*1024, 4 );
#endif
m_FunctorFactory.SetAllocator( &m_Allocator );
m_pHead = m_pTail = NULL;
}
size_t GetMemoryUsed()
{
return m_Allocator.GetUsed();
}
int Count()
{
int i = 0;
Elem_t *pCurrent = m_pHead;
while ( pCurrent )
{
i++;
pCurrent = pCurrent->pNext;
}
return i;
}
template <typename T>
T &Copy( T &item )
{
T *pCopy = (T *)m_Allocator.Alloc( sizeof(T) );
memcpy( pCopy, &item, sizeof(T) );
return *pCopy;
}
template <typename T>
T *CopyArray( T *p, int n )
{
T *pCopy = (T *)m_Allocator.Alloc( sizeof(T) * n );
memcpy( (void *)pCopy, p, sizeof(T) * n );
return pCopy;
}
template <const char *>
const char *Copy( const char *psz )
{
int len = V_strlen( psz );
char *pCopy = (char *)m_Allocator.Alloc( len + 1 );
memcpy( pCopy, psz, len + 1 );
return pCopy;
}
void CallQueued()
{
TM_ZONE_PLOT( TELEMETRY_LEVEL1, "RenderThread", TELEMETRY_ZONE_PLOT_SLOT_2 );
PERF_STATS_BLOCK( "RenderThread", PERF_STATS_SLOT_RENDERTHREAD );
if ( !m_pHead )
{
return;
}
CFunctor *pFunctor;
Elem_t *pCurrent = m_pHead;
while ( pCurrent )
{
pFunctor = pCurrent->GetFunctor();
#ifdef _DEBUG
if ( pFunctor->m_nUserID == m_nBreakSerialNumber)
{
m_nBreakSerialNumber = (unsigned)-1;
}
#endif
if ( pCurrent->pNext )
{
PREFETCH360( pCurrent->pNext, 0 );
PREFETCH360( pCurrent->pNext, 128 );
}
(*pFunctor)();
pFunctor->~CFunctor(); // no need to ref count, we're alone here...
pCurrent = pCurrent->pNext;
}
#ifdef DEBUG_MATCALLQUEUE
static int prevHigh = 0;
if ( m_Allocator.GetUsed() > prevHigh )
{
Msg( "***%d\n", m_Allocator.GetUsed() );
prevHigh = m_Allocator.GetUsed();
}
#endif
m_Allocator.FreeAll( false );
m_pHead = m_pTail = NULL;
}
void QueueFunctor( CFunctor *pFunctor )
{
Assert( pFunctor );
m_Allocator.Alloc( sizeof(Elem_t) );
QueueFunctorInternal( m_FunctorFactory.CreateRefCountingFunctor( pFunctor, &CFunctor::operator() ) );
}
void Flush()
{
if ( !m_pHead )
{
return;
}
CFunctor *pFunctor;
Elem_t *pCurrent = m_pHead;
while ( pCurrent )
{
pFunctor = pCurrent->GetFunctor();
pFunctor->Release();
pCurrent = pCurrent->pNext;
}
m_Allocator.FreeAll( false );
m_pHead = m_pTail = NULL;
}
#define DEFINE_MATCALLQUEUE_NONMEMBER_QUEUE_CALL(N) \
template <typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N FUNC_TEMPLATE_ARG_PARAMS_##N> \
void QueueCall(FUNCTION_RETTYPE (*pfnProxied)( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \
{ \
m_Allocator.Alloc( sizeof(Elem_t) ); \
QueueFunctorInternal( m_FunctorFactory.CreateFunctor( pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N ) ); \
}
//-------------------------------------
#define DEFINE_MATCALLQUEUE_MEMBER_QUEUE_CALL(N) \
template <typename OBJECT_TYPE_PTR, typename FUNCTION_CLASS, typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N FUNC_TEMPLATE_ARG_PARAMS_##N> \
void QueueCall(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) FUNC_ARG_FORMAL_PARAMS_##N ) \
{ \
m_Allocator.Alloc( sizeof(Elem_t) ); \
QueueFunctorInternal( m_FunctorFactory.CreateFunctor( pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N ) ); \
}
//-------------------------------------
#define DEFINE_MATCALLQUEUE_CONST_MEMBER_QUEUE_CALL(N) \
template <typename OBJECT_TYPE_PTR, typename FUNCTION_CLASS, typename FUNCTION_RETTYPE FUNC_TEMPLATE_FUNC_PARAMS_##N FUNC_TEMPLATE_ARG_PARAMS_##N> \
void QueueCall(OBJECT_TYPE_PTR pObject, FUNCTION_RETTYPE ( FUNCTION_CLASS::*pfnProxied )( FUNC_BASE_TEMPLATE_FUNC_PARAMS_##N ) const FUNC_ARG_FORMAL_PARAMS_##N ) \
{ \
m_Allocator.Alloc( sizeof(Elem_t) ); \
QueueFunctorInternal( m_FunctorFactory.CreateFunctor( pObject, pfnProxied FUNC_FUNCTOR_CALL_ARGS_##N ) ); \
}
//-------------------------------------
FUNC_GENERATE_ALL( DEFINE_MATCALLQUEUE_NONMEMBER_QUEUE_CALL );
FUNC_GENERATE_ALL( DEFINE_MATCALLQUEUE_MEMBER_QUEUE_CALL );
FUNC_GENERATE_ALL( DEFINE_MATCALLQUEUE_CONST_MEMBER_QUEUE_CALL );
private:
void QueueFunctorInternal( CFunctor *pFunctor )
{
#ifdef _DEBUG
pFunctor->m_nUserID = m_nCurSerialNumber++;
#endif
MEM_ALLOC_CREDIT_( "CMatCallQueue.m_Allocator" );
// Caller is expected to have preallocated Elem_t entry immediately prior to functor
Elem_t *pNew = ((Elem_t *)pFunctor) - 1;
if ( m_pTail )
{
m_pTail->pNext = pNew;
m_pTail = pNew;
}
else
{
m_pHead = m_pTail = pNew;
}
pNew->pNext = NULL;
}
struct Elem_t
{
Elem_t *pNext;
CFunctor *GetFunctor() { return (CFunctor *)(this + 1 ); }
};
Elem_t *m_pHead;
Elem_t *m_pTail;
CMemoryStack m_Allocator;
CCustomizedFunctorFactory<CMemoryStack, CRefCounted1<CFunctor, CRefCountServiceDestruct< CRefST > > > m_FunctorFactory;
unsigned m_nCurSerialNumber;
unsigned m_nBreakSerialNumber;
};
#define MATCONFIG_FLAGS_SUPPORT_EDITOR ( 1 << 0 )
#define MATCONFIG_FLAGS_SUPPORT_GBUFFER ( 1 << 1 )
//-----------------------------------------------------------------------------
// Additional interfaces used internally to the library
//-----------------------------------------------------------------------------
abstract_class IMaterialSystemInternal : public IMaterialSystem
{
public:
// Returns the current material
virtual IMaterial* GetCurrentMaterial() = 0;
virtual int GetLightmapPage( void ) = 0;
// Gets the maximum lightmap page size...
virtual int GetLightmapWidth( int lightmap ) const = 0;
virtual int GetLightmapHeight( int lightmap ) const = 0;
virtual ITexture *GetLocalCubemap( void ) = 0;
// virtual bool RenderZOnlyWithHeightClipEnabled( void ) = 0;
virtual void ForceDepthFuncEquals( bool bEnable ) = 0;
virtual enum MaterialHeightClipMode_t GetHeightClipMode( void ) = 0;
// FIXME: Remove? Here for debugging shaders in CShaderSystem
virtual void AddMaterialToMaterialList( IMaterialInternal *pMaterial ) = 0;
virtual void RemoveMaterial( IMaterialInternal *pMaterial ) = 0;
virtual void RemoveMaterialSubRect( IMaterialInternal *pMaterial ) = 0;
virtual bool InFlashlightMode() const = 0;
virtual bool IsCascadedShadowMapping() const = 0;
// Can we use editor materials?
virtual bool CanUseEditorMaterials() const = 0;
virtual int GetConfigurationFlags( void ) const = 0;
virtual const char *GetForcedTextureLoadPathID() = 0;
virtual CMatCallQueue *GetRenderCallQueue() = 0;
virtual void UnbindMaterial( IMaterial *pMaterial ) = 0;
virtual uint GetRenderThreadId() const = 0 ;
};
#endif // IMATERIALSYSTEMINTERNAL_H
@@ -0,0 +1,81 @@
//========== Copyright (c) 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//===============================================================================
#ifndef IMATRENDERCONTEXTINTERNAL_H
#define IMATRENDERCONTEXTINTERNAL_H
#if defined( _WIN32 )
#pragma once
#endif
// typedefs to allow use of delegation macros
typedef Vector4D LightCube_t[6];
abstract_class IMatRenderContextInternal : public IMatRenderContext
{
// For now, stuck implementing these until IMaterialSystem is reworked
bool Connect(CreateInterfaceFn) { return true; }
void Disconnect(void) {}
void *QueryInterface(const char *pszInterface) { return NULL; }
InitReturnVal_t Init(void) { return INIT_OK; }
void Shutdown(void) {}
public:
virtual float GetFloatRenderingParameter(int parm_number) const = 0;
virtual int GetIntRenderingParameter(int parm_number) const = 0;
virtual ITexture *GetTextureRenderingParameter(int parm_number) const = 0;
virtual Vector GetVectorRenderingParameter(int parm_number) const = 0;
virtual void SwapBuffers() = 0;
virtual void SetCurrentMaterialInternal(IMaterialInternal* pCurrentMaterial) = 0;
virtual IMaterialInternal* GetCurrentMaterialInternal() const = 0;
virtual int GetLightmapPage() = 0;
virtual void ForceDepthFuncEquals( bool) = 0;
virtual bool InFlashlightMode() const = 0;
virtual bool IsCascadedShadowMapping() const = 0;
virtual void BindStandardTexture( Sampler_t, TextureBindFlags_t nBindFlags, StandardTextureId_t ) = 0;
virtual void GetLightmapDimensions( int *, int *) = 0;
virtual MorphFormat_t GetBoundMorphFormat() = 0;
virtual ITexture *GetRenderTargetEx( int ) = 0;
virtual void DrawClearBufferQuad( unsigned char, unsigned char, unsigned char, unsigned char, bool, bool, bool ) = 0;
#ifdef _PS3
virtual void DrawReloadZcullQuad() = 0;
#endif // _PS3
virtual bool OnDrawMesh( IMesh *pMesh, int firstIndex, int numIndices ) = 0;
virtual bool OnDrawMesh( IMesh *pMesh, CPrimList *pLists, int nLists ) = 0;
virtual bool OnDrawMeshModulated( IMesh *pMesh, const Vector4D &diffuseModulation, int firstIndex, int numIndices ) = 0;
virtual bool OnSetFlexMesh( IMesh *pStaticMesh, IMesh *pMesh, int nVertexOffsetInBytes ) = 0;
virtual bool OnSetColorMesh( IMesh *pStaticMesh, IMesh *pMesh, int nVertexOffsetInBytes ) = 0;
virtual bool OnSetPrimitiveType( IMesh *pMesh, MaterialPrimitiveType_t type ) = 0;
virtual void SyncMatrices() = 0;
virtual void SyncMatrix( MaterialMatrixMode_t ) = 0;
virtual void ForceHardwareSync() = 0;
virtual void BeginFrame() = 0;
virtual void EndFrame() = 0;
virtual void SetFrameTime( float frameTime ) = 0;
virtual void SetCurrentProxy( void *pProxy ) = 0;
virtual void MarkRenderDataUnused( bool bBeginFrame ) = 0;
virtual CMatCallQueue *GetCallQueueInternal() = 0;
virtual void EvictManagedResources() = 0;
virtual ShaderAPITextureHandle_t GetLightmapTexture( int nLightmapPage ) = 0;
virtual bool IsRenderingPaint() const = 0;
virtual ShaderAPITextureHandle_t GetPaintmapTexture( int nLightmapPage ) = 0;
#if defined( DX_TO_GL_ABSTRACTION ) && !defined( _GAMECONSOLE )
virtual void DoStartupShaderPreloading( void ) = 0;
#endif
};
#endif // IMATRENDERCONTEXTINTERNAL_H
+91
View File
@@ -0,0 +1,91 @@
//====== Copyright © 1996-2004, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#ifndef IMORPHINTERNAL_H
#define IMORPHINTERNAL_H
#ifdef _WIN32
#pragma once
#endif
#include "materialsystem/imorph.h"
#include "shaderapi/shareddefs.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class ITextureInternal;
//-----------------------------------------------------------------------------
// Render context for morphs
//-----------------------------------------------------------------------------
abstract_class IMorphMgrRenderContext
{
public:
};
//-----------------------------------------------------------------------------
//
// Morph data class
//
//-----------------------------------------------------------------------------
abstract_class IMorphInternal : public IMorph
{
public:
virtual void Init( MorphFormat_t format, const char *pDebugName ) = 0;
virtual bool Bind( IMorphMgrRenderContext *pRenderContext ) = 0;
virtual MorphFormat_t GetMorphFormat() const = 0;
};
//-----------------------------------------------------------------------------
// Morph manager class
//-----------------------------------------------------------------------------
abstract_class IMorphMgr
{
public:
// Allocate,free scratch textures + materials
virtual bool ShouldAllocateScratchTextures() = 0;
virtual void AllocateScratchTextures() = 0;
virtual void FreeScratchTextures() = 0;
virtual void AllocateMaterials() = 0;
virtual void FreeMaterials() = 0;
// Returns the morph accumulator scratch texture
virtual ITextureInternal *MorphAccumulator() = 0;
virtual ITextureInternal *MorphWeights() = 0;
// Class factory
virtual IMorphInternal *CreateMorph() = 0;
virtual void DestroyMorph( IMorphInternal *pMorphData ) = 0;
// Max morphs between Begin/End
virtual int MaxHWMorphBatchCount() const = 0;
// Begin, end morph accumulation phase
virtual void BeginMorphAccumulation( IMorphMgrRenderContext *pRenderContext ) = 0;
virtual void EndMorphAccumulation( IMorphMgrRenderContext *pRenderContext ) = 0;
// Accumulate a morph
virtual void AccumulateMorph( IMorphMgrRenderContext *pRenderContext, IMorph* pMorph, int nMorphCount, const MorphWeight_t* pWeights ) = 0;
// Advances frame count (for debugging)
virtual void AdvanceFrame() = 0;
// Returns the location of a particular vertex in the morph accumulator
virtual bool GetMorphAccumulatorTexCoord( IMorphMgrRenderContext *pRenderContext, Vector2D *pTexCoord, IMorph *pMorph, int nVertex ) = 0;
// Allocate, free morph mgr render context data.
virtual IMorphMgrRenderContext *AllocateRenderContext() = 0;
virtual void FreeRenderContext( IMorphMgrRenderContext *pRenderContext ) = 0;
};
extern IMorphMgr *g_pMorphMgr;
#endif // IMORPHINTERNAL_H
+48
View File
@@ -0,0 +1,48 @@
//====== Copyright © 1996-2008, Valve Corporation, All rights reserved. =======
//
// Purpose:
//
//=============================================================================
#ifndef ISUBDINTERNAL_H
#define ISUBDINTERNAL_H
#ifdef _WIN32
#pragma once
#endif
#include "shaderapi/shareddefs.h"
#include "itextureinternal.h"
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class ITextureInternal;
//-----------------------------------------------------------------------------
// Subdivision surface manager class
//-----------------------------------------------------------------------------
abstract_class ISubDMgr
{
public:
virtual bool ShouldAllocateTextures() = 0; //
virtual void AllocateTextures() = 0; // Allocate & free textures
virtual void FreeTextures() = 0; //
virtual void ReleaseResources() = 0;
virtual void ReacquireResources() = 0;
virtual int GetWidth() = 0;
virtual int GetHeight() = 0;
virtual int GetOffsetGeometry() = 0;
virtual int GetOffsetTangents() = 0;
virtual float* Lock( int nNumRows ) = 0;
virtual void Unlock() = 0;
virtual ShaderAPITextureHandle_t SubDTexture() = 0; // Return the subd position texture
};
extern ISubDMgr *g_pSubDMgr;
#endif // ISUBDINTERNAL_H
+176
View File
@@ -0,0 +1,176 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#ifndef ITEXTUREINTERNAL_H
#define ITEXTUREINTERNAL_H
#ifdef _WIN32
#pragma once
#endif
#include "materialsystem/itexture.h"
#include "shaderapi/ishaderapi.h"
class Vector;
enum Sampler_t;
class IFileList;
enum RenderTargetType_t
{
NO_RENDER_TARGET = 0,
// GR - using shared depth buffer
RENDER_TARGET = 1,
// GR - using own depth buffer
RENDER_TARGET_WITH_DEPTH = 2,
// GR - no depth buffer
RENDER_TARGET_NO_DEPTH = 3,
// only cares about depth buffer
RENDER_TARGET_ONLY_DEPTH = 4,
};
abstract_class ITextureInternal : public ITexture
{
public:
virtual void Bind( Sampler_t sampler, TextureBindFlags_t nBindFlags ) = 0;
virtual void Bind( Sampler_t sampler1, TextureBindFlags_t nBindFlags, int nFrame, Sampler_t sampler2 = SHADER_SAMPLER_INVALID ) = 0;
virtual void GetReflectivity( Vector& reflectivity ) = 0;
// Set this as the render target, return false for failure
virtual bool SetRenderTarget( int nRenderTargetID ) = 0;
// Releases the texture's hw memory
virtual void Release() = 0;
// Called before Download() on restore. Gives render targets a change to change whether or
// not they force themselves to have a separate depth buffer due to AA.
virtual void OnRestore() = 0;
// Resets the texture's filtering and clamping mode
virtual void SetFilteringAndClampingMode() = 0;
// Used by tools.... loads up the non-fallback information about the texture
virtual void Precache() = 0;
// Stretch blit the framebuffer into this texture.
virtual void CopyFrameBufferToMe( int nRenderTargetID = 0, Rect_t *pSrcRect = NULL, Rect_t *pDstRect = NULL ) = 0;
virtual void CopyMeToFrameBuffer( int nRenderTargetID = 0, Rect_t *pSrcRect = NULL, Rect_t *pDstRect = NULL ) = 0;
virtual ITexture *GetEmbeddedTexture( int nIndex ) = 0;
// Get the shaderapi texture handle associated w/ a particular frame
virtual ShaderAPITextureHandle_t GetTextureHandle( int nFrame, int nTextureChannel =0 ) = 0;
virtual ~ITextureInternal()
{
}
virtual ImageFormat GetImageFormat() const = 0;
// Creates a new texture
static ITextureInternal *CreateFileTexture( const char *pFileName, const char *pTextureGroupName );
static ITextureInternal *CreateProceduralTexture(
const char *pTextureName,
const char *pTextureGroupName,
int w,
int h,
int d,
ImageFormat fmt,
int nFlags );
static ITextureInternal *CreateRenderTarget(
const char *pRTName, // NULL for an auto-generated name.
int w,
int h,
RenderTargetSizeMode_t sizeMode,
ImageFormat fmt,
RenderTargetType_t type,
unsigned int textureFlags,
unsigned int renderTargetFlags,
bool bMultipleTargets );
static void ChangeRenderTarget(
ITextureInternal *pTexture,
int w,
int h,
RenderTargetSizeMode_t sizeMode,
ImageFormat fmt,
RenderTargetType_t type,
unsigned int textureFlags,
unsigned int renderTargetFlags );
static ITextureInternal *CreateReferenceTextureFromHandle(
const char *pTextureName,
const char *pTextureGroupName,
ShaderAPITextureHandle_t hTexture );
static void Destroy( ITextureInternal *pTexture );
// Set this as the render target, return false for failure
virtual bool SetRenderTarget( int nRenderTargetID, ITexture* pDepthTexture ) = 0;
// Bind this to a vertex texture sampler
virtual void BindVertexTexture( VertexTextureSampler_t sampler, int frameNum = 0 ) = 0;
virtual void MarkAsPreloaded( bool bSet ) = 0;
virtual bool IsPreloaded() const = 0;
virtual void MarkAsExcluded( bool bSet, int nDimensionsLimit, bool bMarkAsTrumpedExclude = false ) = 0;
virtual bool UpdateExcludedState() = 0;
virtual bool IsTempRenderTarget( void ) const = 0;
// Reload any files the texture is responsible for.
virtual void ReloadFilesInList( IFileList *pFilesToReload ) = 0;
virtual bool IsMultiRenderTarget( void ) = 0;
#ifdef _PS3
virtual void Ps3gcmRawBufferAlias( char const *pRTName ) = 0;
#endif
virtual bool MarkAsTempExcluded( bool bSet, int nExcludedDimensionLimit ) = 0;
virtual bool IsForceExcluded() const = 0;
virtual bool ClearForceExclusion() = 0;
virtual bool IsAsyncDone() const = 0;
};
inline bool IsTextureInternalEnvCubemap( const ITextureInternal *pTexture )
{
return ( pTexture == ( ITextureInternal * )-1 );
}
//-----------------------------------------------------------------------------
// Ensures that caller provided names are consistent to the dictionary
//-----------------------------------------------------------------------------
inline char *NormalizeTextureName( const char *pName, char *pOutName, int nOutNameSize )
{
// hdr textures have an ldr version and need to resolve correctly
int nLen = Q_strlen( pName ) + 1;
if ( nLen <= 5 || Q_stricmp( pName + nLen - 5, ".hdr" ) )
{
// strip any non .hdr extension
Q_StripExtension( pName, pOutName, nOutNameSize );
}
else
{
// keep .hdr extension
Q_strncpy( pOutName, pName, nOutNameSize );
}
Q_strlower( pOutName );
Q_FixSlashes( pOutName, '/' );
return pOutName;
}
#endif // ITEXTUREINTERNAL_H
File diff suppressed because it is too large. Load diff
+328
View File
@@ -0,0 +1,328 @@
//-----------------------------------------------------------------------------
// MATERIALSYSTEM.VPC
//
// Project Script
//-----------------------------------------------------------------------------
$macro SRCDIR ".."
$Macro SHADERAPIDX9DIR "shaderapidx9"
$Macro SHADERLIBDIR "shaderlib"
$Macro STDSHADERSDIR "stdshaders"
$Macro OUTBINDIR "$SRCDIR\..\game\bin"
$include "$SRCDIR\vpc_scripts\source_dll_base.vpc"
$IgnoreRedundancyWarning "ON"
//-----------------------------------------------------------------------------
$CustomBuildStep "fp"
{
$CommandLine "$(SCE_PS3_ROOT)\host-win32\Cg\bin\sce-cgc -quiet -profile sce_fp_rsx -o &quot;$(InputName).fpo&quot; &quot;$(InputPath)&quot;&#x0D;&#x0A;$(SCE_PS3_ROOT)\host-win32\ppu\bin\ppu-lv2-objcopy -I binary -O elf64-powerpc-celloslv2 -B powerpc &quot;$(InputName).fpo&quot; &quot;$(IntDir)\$(InputName).fp.ppu.o&quot;"
$Description "Fragment Program $(InputFileName) produces $(InputName).fpo produces $(InputName).fp.ppu.o"
$Outputs "$(IntDir)\$(InputName).fp.ppu.o"
}
$CustomBuildStep "vp"
{
$CommandLine "$(SCE_PS3_ROOT)\host-win32\Cg\bin\sce-cgc -quiet -profile sce_vp_rsx -o &quot;$(InputName).vpo&quot; &quot;$(InputPath)&quot;&#x0D;&#x0A;$(SCE_PS3_ROOT)\host-win32\ppu\bin\ppu-lv2-objcopy -I binary -O elf64-powerpc-celloslv2 -B powerpc &quot;$(InputName).vpo&quot; &quot;$(IntDir)\$(InputName).vp.ppu.o&quot;"
$Description "Vertex Program $(InputFileName) produces $(InputName).vpo produces $(InputName).vp.ppu.o"
$Outputs "$(IntDir)\$(InputName).vp.ppu.o"
}
$Configuration
{
$Compiler
{
$AdditionalIncludeDirectories "$BASE;$SRCDIR\materialsystem"
$AdditionalIncludeDirectories "$BASE;$SRCDIR\dx9sdk\Include" [$WINDOWS && !$GL]
$AdditionalIncludeDirectories "$BASE;$(XEDK)\include\xbox" [$X360]
$PreprocessorDefinitions "$BASE;DEFINE_MATERIALSYSTEM_INTERFACE;MATERIALSYSTEM_EXPORTS;PROTECTED_THINGS_ENABLE;INCLUDE_SCALEFORM"
$PreprocessorDefinitions "$BASE;VERSION_SAFE_STEAM_API_INTERFACES"
$PreprocessorDefinitions "$BASE;USE_ACTUAL_DX" [ ( $WINDOWS || $X360 ) && !$GL ]
$PreprocessorDefinitions "$BASE;GL_GLEXT_PROTOTYPES;DX_TO_GL_ABSTRACTION" [$GL]
$PreprocessorDefinitions "$BASE;strncpy=use_Q_strncpy_instead;_snprintf=use_Q_snprintf_instead" [!$POSIX]
$PreprocessorDefinitions "$BASE;ALLOW_TEXT_MODE=1" [$CSTRIKE_TRUNK_BUILD||$CSTRIKE_STAGING_BUILD]
$EnableC++Exceptions "Yes (/EHsc)"
$Create/UsePCHThroughFile "pch_materialsystem.h"
}
$Linker
{
$AdditionalLibraryDirectories "$BASE;$SRCDIR\dx9sdk\lib" [$WINDOWS && !$GL]
$AdditionalDependencies "$BASE winmm.lib Ws2_32.lib imm32.lib oleaut32.lib" [$WINDOWS]
$AdditionalDependencies "$BASE dxguid.lib d3d9.lib" [$WINDOWS && !$GL]
$AdditionalLibraryDirectories "$BASE;$(XEDK)\lib\xbox" [$X360]
$AdditionalDependencies "$BASE libgfx.lib libjpeg.lib zlib.lib libpng.lib" [$X360]
}
$PreLinkEvent [$PS3]
{
$CommandLine "call .\$(IntDir)\xy16icf32.vp.bat" "\n" \
"call .\$(IntDir)\cxformgauraud.fp.bat" "\n" \
"call .\$(IntDir)\cxformgauraudnoaddalpha.fp.bat" "\n" \
"call .\$(IntDir)\cxformgauraudtexture.fp.bat" "\n" \
"call .\$(IntDir)\glyph.vp.bat" "\n" \
"call .\$(IntDir)\noninteractiveshader.fp.bat" "\n" \
"call .\$(IntDir)\noninteractiveshader.vp.bat" "\n" \
"call .\$(IntDir)\noninteractiveshaderstartup.fp.bat" "\n" \
"call .\$(IntDir)\noninteractiveshaderstartuppass2.fp.bat" "\n" \
"call .\$(IntDir)\solidcolor.fp.bat" "\n" \
"call .\$(IntDir)\strip.vp.bat" "\n" \
"call .\$(IntDir)\texttexturealpha.fp.bat" "\n" \
"call .\$(IntDir)\xy16ic32.vp.bat"
}
// Since other shader modules are conglomerated here,
// need to set project settings for those modules too:
$Compiler [$PS3 || $OSXALL]
{
$AdditionalIncludeDirectories "$BASE;..\"
// shaderapidx9
$PreprocessorDefinitions "$BASE;SHADERAPIDX9;SHADER_DLL_EXPORT;"
// shaderlib
$PreprocessorDefinitions "$BASE;FAST_MATERIALVAR_ACCESS;"
// stdshader
$AdditionalIncludeDirectories "$BASE;$SRCDIR\materialsystem\stdshaders\fxctmp9_ps3" [$PS3]
$AdditionalIncludeDirectories "$BASE;$SRCDIR\materialsystem\stdshaders\fxctmp9;$SRCDIR\materialsystem\stdshaders\vshtmp9" [$OSXALL]
$PreprocessorDefinitions "$BASE;STDSHADER_DX9_DLL_EXPORT;FAST_MATERIALVAR_ACCESS"
// all internal headers access
$PreprocessorDefinitions "$BASE;MATSYS_INTERNAL" [$PS3]
// platform override
$PreprocessorDefinitions "$BASE;PLATFORM_OVERRIDE_MATERIALSYSTEM"
}
$SNCCompiler [$PS3]
{
$ForceIncludes "platform_override.h"
}
$Linker [$PS3]
{
$AdditionalDependencies "$BASE libgfx.a libjpeg.a libpng.a libz.a libnet_stub.a libnetctl_stub.a librtc_stub.a"
$AdditionalDependencies "$BASE libfont_stub.a libfontFT_stub.a libfreetypeTT_stub.a"
$AdditionalDependencies "$BASE libgcm_sys_stub.a libgcm_cmdasm.a libsysutil_stub.a libresc_stub.a libspurs_stub.a $SCE_PPU_LIBROOT\libio_stub.a libedgepost.a"
$AdditionalDependencies "$BASE libgem_stub.a"
}
}
$Configuration "Debug"
{
$Compiler [$PS3]
{
// $PreprocessorDefinitions "$BASE;CELL_GCM_DEBUG"
}
$Linker [$WINDOWS]
{
$AdditionalDependencies "$BASE"
$AdditionalDependencies "$BASE d3dx9d.lib" [!$GL]
}
$Linker [$X360]
{
$AdditionalDependencies "$BASE d3dx9d.lib xonlined.lib"
}
$Linker [$PS3]
{
// use libgcm_cmddbg.a to validate parameters
$AdditionalDependencies "$BASE libgcm_cmd.a"
}
}
$Configuration "Release"
{
$Linker [$WINDOWS]
{
$AdditionalDependencies "$BASE"
$AdditionalDependencies "$BASE d3dx9.lib" [!$GL]
}
$Linker [$X360]
{
$AdditionalDependencies "$BASE d3dx9.lib xonline.lib"
}
$Linker [$PS3]
{
$AdditionalDependencies "$BASE libgcm_cmd.a"
}
}
$Configuration
{
$Linker [$OSXALL]
{
$SystemFrameworks "Carbon;OpenGL;Quartz;Cocoa;IOKit"
$SystemLibraries "iconv;z"
}
}
///////////////////////////////////////////////
//
// PS3 conglomerates all shader modules here
//
$include "shaderapidx9/shaderapidx9_inc.vpc" [$PS3 || $OSXALL]
$include "shaderlib/shaderlib_inc.vpc" [$PS3 || $OSXALL]
$include "stdshaders/stdshader_dx9_inc.vpc" [$PS3 || $OSXALL]
//
//
///////////////////////////////////////////////
$Project "materialsystem"
{
$Folder "Source Files"
{
$File "CColorCorrection.cpp"
$File "cmaterial.cpp"
$File "cmaterial_queuefriendly.cpp"
$File "CMaterialSubRect.cpp"
$File "cmaterialvar.cpp"
$File "cmatnullrendercontext.cpp"
$File "colorspace.cpp"
$File "ctexture.cpp"
$File "$SRCDIR\public\filesystem_helpers.cpp"
$File "imagepacker.cpp"
$File "mat_stub.cpp"
$File "materialsystem_global.cpp"
$File "morph.cpp"
$File "SubdMgr.cpp" [ !$X360 && !$PS3 ]
$File "occlusionquerymgr.cpp"
$File "shadersystem.cpp"
$File "texturemanager.cpp"
$File "cmaterialsystem_ps3fonts.cpp" [$PS3]
$File "composite_texture.cpp"
$File "custom_material.cpp"
$File "base_visuals_data_processor.cpp"
$File "pch_materialsystem.cpp" [!$PS3]
{
$Configuration
{
$Compiler [!$LINUX && !$OSXALL]
{
$Create/UsePrecompiledHeader "Create Precompiled Header (/Yc)"
}
}
}
$File "cmaterialdict.cpp" \
"cmaterialsystem.cpp" \
"cmatlightmaps.cpp" \
"cmatpaintmaps.cpp" \
"cmatrendercontext.cpp" \
"cmatqueuedrendercontext.cpp"
}
$Folder "Public Header Files"
{
$File "$SRCDIR\public\tier0\basetypes.h"
$File "$SRCDIR\public\mathlib\bumpvects.h"
$File "$SRCDIR\public\const.h"
$File "$SRCDIR\public\tier1\convar.h"
$File "$SRCDIR\public\crtmemdebug.h"
$File "$SRCDIR\common\cstringhash.h"
$File "$SRCDIR\public\filesystem.h"
$File "$SRCDIR\public\appframework\iappsystem.h"
$File "$SRCDIR\public\materialsystem\IColorCorrection.h"
$File "$SRCDIR\public\materialsystem\imaterial.h"
$File "$SRCDIR\public\materialsystem\imaterialproxy.h"
$File "$SRCDIR\public\materialsystem\imaterialproxyfactory.h"
$File "$SRCDIR\public\materialsystem\imaterialsystem.h"
$File "$SRCDIR\public\materialsystem\imaterialsystemhardwareconfig.h"
$File "$SRCDIR\public\materialsystem\imaterialsystemstub.h"
$File "$SRCDIR\public\materialsystem\imaterialvar.h"
$File "$SRCDIR\public\materialsystem\imesh.h"
$File "$SRCDIR\public\materialsystem\imorph.h"
$File "$SRCDIR\public\materialsystem\ipaintmapdatamanager.h"
$File "$SRCDIR\public\tier1\interface.h"
$File "$SRCDIR\public\materialsystem\IShader.h"
$File "$SRCDIR\public\materialsystem\ishaderapi.h"
$File "$SRCDIR\public\materialsystem\itexture.h"
$File "$SRCDIR\public\materialsystem\ivisualsdataprocessor.h"
$File "$SRCDIR\public\materialsystem\icustommaterial.h"
$File "$SRCDIR\public\materialsystem\custommaterialowner.h"
$File "$SRCDIR\public\materialsystem\icompositetexture.h"
$File "$SRCDIR\public\materialsystem\icustommaterialmanager.h"
$File "$SRCDIR\public\materialsystem\icompositetexturegenerator.h"
$File "$SRCDIR\public\tier1\keyvalues.h"
$File "$SRCDIR\public\materialsystem\materialsystem_config.h"
$File "$SRCDIR\public\mathlib\mathlib.h"
$File "$SRCDIR\public\tier1\mempool.h"
$File "$SRCDIR\public\pixelwriter.h"
$File "$SRCDIR\public\tier0\platform_override.h" [$PS3]
$File "$SRCDIR\public\renderparm.h"
$File "$SRCDIR\public\tier1\strtools.h"
$File "$SRCDIR\public\tier1\utlbuffer.h"
$File "$SRCDIR\public\tier1\utlmemory.h"
$File "$SRCDIR\public\tier1\utlrbtree.h"
$File "$SRCDIR\public\tier1\utlsymbol.h"
$File "$SRCDIR\public\tier1\utlvector.h"
$File "$SRCDIR\public\mathlib\vector.h"
$File "$SRCDIR\public\mathlib\vector2d.h"
$File "$SRCDIR\public\mathlib\vector4d.h"
$File "$SRCDIR\public\mathlib\vmatrix.h"
$File "$SRCDIR\public\mathlib\vplane.h"
$File "$SRCDIR\public\vstdlib\vstdlib.h"
$File "$SRCDIR\public\vtf\vtf.h"
$File "$SRCDIR\public\materialsystem\base_visuals_data_processor.h"
}
$Folder "Header Files"
{
$File "cmaterial_queuefriendly.h"
$File "cmaterialdict.h"
$File "cmaterialsystem.h"
$File "cmatlightmaps.h"
$File "cmatnullrendercontext.h"
$File "cmatpaintmaps.h"
$File "cmatqueuedrendercontext.h"
$File "cmatrendercontext.h"
$File "colorspace.h"
$File "IHardwareConfigInternal.h"
$File "imagepacker.h"
$File "imaterialinternal.h"
$File "imaterialsysteminternal.h"
$File "imatrendercontextinternal.h"
$File "imorphinternal.h"
$File "isubdinternal.h"
$File "itextureinternal.h"
$File "materialsystem_global.h"
$File "occlusionquerymgr.h"
$File "shader_dll_verify.h" [$WINDOWS]
$File "shadersystem.h"
$File "texturemanager.h"
$File "shadersystem_ps3nonvirt.inl" [$PS3]
$File "shaderutil_ps3nonvirt.h" [$PS3]
$File "shaderutil_ps3nonvirt.inl" [$PS3]
$File "composite_texture.h"
$File "custom_material.h"
}
$Folder "Noninteractive Shaders" [$PS3]
{
$File "$SHADERAPIDX9DIR\..\ps3gcm\noninteractiveshader.fp"
$File "$SHADERAPIDX9DIR\..\ps3gcm\noninteractiveshader.vp"
$File "$SHADERAPIDX9DIR\..\ps3gcm\noninteractiveshaderstartup.fp"
$File "$SHADERAPIDX9DIR\..\ps3gcm\noninteractiveshaderstartuppass2.fp"
}
$Folder "Link Libraries"
{
$Lib "bitmap"
$Lib "mathlib"
$Lib "shaderlib"[!$PS3 && !$OSXALL]
$Lib "tier2"
$Lib "tier3"
$Lib "vtf"
$Lib "videocfg" [$OSXALL]
$ImplibExternal steam_api [ ( $WIN32 || $POSIX || $PS3 ) && !$NO_STEAM ]
$ImplibExternal steam_api64 [ $WIN64 && !$NO_STEAM ]
$Implib togl [!$IS_LIB_PROJECT && $GL && !$DEDICATED]
}
}
@@ -0,0 +1,13 @@
"vpc_cache"
{
"CacheVersion" "1"
"win32"
{
"CRCFile" "materialsystem.vcxproj.vpc_crc"
"OutputFiles"
{
"0" "materialsystem.vcxproj"
"1" "materialsystem.vcxproj.filters"
}
}
}
+45
View File
@@ -0,0 +1,45 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=====================================================================================//
#include "icvar.h"
#include "convar.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// ------------------------------------------------------------------------------------------- //
// ConVar stuff.
// ------------------------------------------------------------------------------------------- //
class CMaterialSystemConVarAccessor : public IConCommandBaseAccessor
{
public:
virtual bool RegisterConCommandBase( ConCommandBase *pCommand )
{
// Link to engine's list instead
g_pCVar->RegisterConCommand( pCommand );
char const *pValue = g_pCVar->GetCommandLineValue( pCommand->GetName() );
if( pValue && !pCommand->IsCommand() )
{
( ( ConVar * )pCommand )->SetValue( pValue );
}
return true;
}
};
//EAPS3 : Make static.
static CMaterialSystemConVarAccessor g_ConVarAccessor;
void InitMaterialSystemLibCVars( CreateInterfaceFn cvarFactory )
{
if ( g_pCVar )
{
ConVar_Register( 0, &g_ConVarAccessor );
}
}
+31
View File
@@ -0,0 +1,31 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=====================================================================================//
#include "materialsystem_global.h"
#include "shaderapi/ishaderapi.h"
#include "shadersystem.h"
#ifndef _PS3
#include <malloc.h>
#endif
#include "filesystem.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
int g_FrameNum;
#ifndef SHADERAPI_GLOBAL_H
IShaderAPI *g_pShaderAPI = 0;
IShaderDeviceMgr* g_pShaderDeviceMgr = 0;
IShaderDevice *g_pShaderDevice = 0;
IShaderShadow* g_pShaderShadow = 0;
#endif
IClientMaterialSystem *g_pClientMaterialSystem = 0;
#if defined( INCLUDE_SCALEFORM )
IScaleformUI* g_pScaleformUI = 0;
#endif
+140
View File
@@ -0,0 +1,140 @@
//========= Copyright 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Header: $
// $NoKeywords: $
//
//=============================================================================//
#ifndef MATERIALSYSTEM_GLOBAL_H
#define MATERIALSYSTEM_GLOBAL_H
#ifdef _WIN32
#pragma once
#endif
#include "imaterialsysteminternal.h"
#include "tier0/dbg.h"
#include "tier2/tier2.h"
#if defined( _PS3 ) || defined( _OSX )
#include "shaderapidx9/shaderapidx8.h"
#include "shaderapidx9/shaderdevicedx8.h"
#include "shaderapidx9/hardwareconfig.h"
#include "shaderapidx9/shaderapidx8_global.h"
#include "shaderapidx9/shadershadowdx8.h"
#endif
#if defined( INCLUDE_SCALEFORM )
#include "scaleformui/scaleformui.h"
#endif
//-----------------------------------------------------------------------------
// Forward declarations
//-----------------------------------------------------------------------------
class ITextureInternal;
class IShaderAPI;
class IHardwareConfigInternal;
class IShaderUtil;
class IShaderShadow;
class IShaderDeviceMgr;
class IShaderDevice;
class IShaderSystemInternal;
class IMaterialInternal;
class IColorCorrectionSystem;
class IMaterialVar;
class IClientMaterialSystem;
//-----------------------------------------------------------------------------
// Constants used by the system
//-----------------------------------------------------------------------------
#define MATERIAL_MAX_PATH 256
// GR - limits for blured image (HDR stuff)
#define MAX_BLUR_IMAGE_WIDTH 256
#define MAX_BLUR_IMAGE_HEIGHT 192
#define CLAMP_BLUR_IMAGE_WIDTH( _w ) ( ( _w < MAX_BLUR_IMAGE_WIDTH ) ? _w : MAX_BLUR_IMAGE_WIDTH )
#define CLAMP_BLUR_IMAGE_HEIGHT( _h ) ( ( _h < MAX_BLUR_IMAGE_HEIGHT ) ? _h : MAX_BLUR_IMAGE_HEIGHT )
//-----------------------------------------------------------------------------
// Global structures
//-----------------------------------------------------------------------------
extern MaterialSystem_Config_t g_config;
extern uint32 g_nDebugVarsSignature;
//extern MaterialSystem_ErrorFunc_t Error;
//extern MaterialSystem_WarningFunc_t Warning;
extern int g_FrameNum;
#ifndef SHADERAPI_GLOBAL_H
extern IShaderAPI* g_pShaderAPI;
extern IShaderDeviceMgr* g_pShaderDeviceMgr;
extern IShaderDevice* g_pShaderDevice;
extern IShaderShadow* g_pShaderShadow;
#endif
extern IClientMaterialSystem *g_pClientMaterialSystem;
extern IMaterialInternal *g_pErrorMaterial;
IShaderSystemInternal* ShaderSystem();
inline IShaderSystemInternal* ShaderSystem()
{
extern IShaderSystemInternal *g_pShaderSystem;
return g_pShaderSystem;
}
#ifdef _PS3
#include "shaderapidx9/hardwareconfig_ps3nonvirt.h"
#elif !defined( _OSX )
inline IHardwareConfigInternal *HardwareConfig()
{
extern IHardwareConfigInternal* g_pHWConfig;
return g_pHWConfig;
}
#endif
#if defined( INCLUDE_SCALEFORM )
inline IScaleformUI* ScaleformUI()
{
extern IScaleformUI* g_pScaleformUI;
return g_pScaleformUI;
}
#endif
//-----------------------------------------------------------------------------
// Accessor to get at the material system
//-----------------------------------------------------------------------------
inline IMaterialSystemInternal* MaterialSystem()
{
extern IMaterialSystemInternal *g_pInternalMaterialSystem;
return g_pInternalMaterialSystem;
}
#ifndef SHADERAPI_GLOBAL_H
inline IShaderUtil* ShaderUtil()
{
extern IShaderUtil *g_pShaderUtil;
return g_pShaderUtil;
}
#endif
extern IColorCorrectionSystem *g_pColorCorrectionSystem;
inline IColorCorrectionSystem *ColorCorrectionSystem()
{
return g_pColorCorrectionSystem;
}
//-----------------------------------------------------------------------------
// Global methods related to material vars
//-----------------------------------------------------------------------------
void EnableThreadedMaterialVarAccess( bool bEnable, IMaterialVar **ppParams, int nVarCount );
#endif // MATERIALSYSTEM_GLOBAL_H
File diff suppressed because it is too large. Load diff
+261
View File
@@ -0,0 +1,261 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#include "pch_materialsystem.h"
#ifndef _PS3
#define MATSYS_INTERNAL
#endif
#include "occlusionquerymgr.h"
#include "imaterialsysteminternal.h"
#include "imatrendercontextinternal.h"
// NOTE: This must be the last file included!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Singleton
//-----------------------------------------------------------------------------
static COcclusionQueryMgr s_OcclusionQueryMgr;
COcclusionQueryMgr *g_pOcclusionQueryMgr = &s_OcclusionQueryMgr;
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
COcclusionQueryMgr::COcclusionQueryMgr()
{
m_nFrameCount = 0;
}
//-----------------------------------------------------------------------------
// Allocate and delete query objects.
//-----------------------------------------------------------------------------
OcclusionQueryObjectHandle_t COcclusionQueryMgr::CreateOcclusionQueryObject( )
{
m_Mutex.Lock();
OcclusionQueryObjectHandle_t h = (OcclusionQueryObjectHandle_t)m_OcclusionQueryObjects.AddToTail();
m_Mutex.Unlock();
return h;
}
void COcclusionQueryMgr::OnCreateOcclusionQueryObject( OcclusionQueryObjectHandle_t h )
{
for ( int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++)
{
m_OcclusionQueryObjects[(intp)h].m_QueryHandle[i] = g_pShaderAPI->CreateOcclusionQueryObject( );
}
}
// Flushes an outstanding query
// HEY - Be very careful using this method - it causes a full pipeline flush/stall!
void COcclusionQueryMgr::FlushQuery( OcclusionQueryObjectHandle_t hOcclusionQuery, int nIndex )
{
// Flush out any previous queries
intp h = (intp)hOcclusionQuery;
if ( m_OcclusionQueryObjects[h].m_bHasBeenIssued[nIndex] )
{
ShaderAPIOcclusionQuery_t hQuery = m_OcclusionQueryObjects[h].m_QueryHandle[nIndex];
while ( OCCLUSION_QUERY_RESULT_PENDING == g_pShaderAPI->OcclusionQuery_GetNumPixelsRendered( hQuery, true ) )
continue;
}
}
void COcclusionQueryMgr::DestroyOcclusionQueryObject( OcclusionQueryObjectHandle_t hOcclusionQuery )
{
intp h = (intp)hOcclusionQuery;
Assert( m_OcclusionQueryObjects.IsValidIndex( h ) );
if ( m_OcclusionQueryObjects.IsValidIndex( h ) )
{
for ( int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++)
{
if ( m_OcclusionQueryObjects[h].m_QueryHandle[i] != INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE )
{
g_pShaderAPI->DestroyOcclusionQueryObject( m_OcclusionQueryObjects[h].m_QueryHandle[i] );
}
}
m_Mutex.Lock();
m_OcclusionQueryObjects.Remove( h );
m_Mutex.Unlock();
}
}
//-----------------------------------------------------------------------------
// Advance frame
//-----------------------------------------------------------------------------
void COcclusionQueryMgr::AdvanceFrame()
{
++m_nFrameCount;
}
//-----------------------------------------------------------------------------
// Alt-tab support
// NOTE: This doesn't queue anything up
//-----------------------------------------------------------------------------
void COcclusionQueryMgr::AllocOcclusionQueryObjects( void )
{
FOR_EACH_LL( m_OcclusionQueryObjects, iterator )
{
for ( int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++)
{
m_OcclusionQueryObjects[iterator].m_QueryHandle[i] = g_pShaderAPI->CreateOcclusionQueryObject();
m_OcclusionQueryObjects[iterator].m_bHasBeenIssued[i] = false; // any in-flight queries are never returning
}
}
}
void COcclusionQueryMgr::FreeOcclusionQueryObjects( void )
{
FOR_EACH_LL( m_OcclusionQueryObjects, iterator )
{
for ( int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++)
{
if ( m_OcclusionQueryObjects[iterator].m_QueryHandle[i] != INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE )
{
g_pShaderAPI->DestroyOcclusionQueryObject( m_OcclusionQueryObjects[iterator].m_QueryHandle[i] );
m_OcclusionQueryObjects[iterator].m_QueryHandle[i] = INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE;
m_OcclusionQueryObjects[iterator].m_bHasBeenIssued[i] = false;
}
}
}
}
//-----------------------------------------------------------------------------
// Used to make the handle think it's never had a successful query before
//-----------------------------------------------------------------------------
void COcclusionQueryMgr::ResetOcclusionQueryObject( OcclusionQueryObjectHandle_t hOcclusionQuery )
{
intp h = (intp)hOcclusionQuery;
Assert( m_OcclusionQueryObjects.IsValidIndex( h ) );
if ( m_OcclusionQueryObjects.IsValidIndex( h ) )
{
// Forget we've issued any previous queries - there's no need to flush them.
for ( int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++)
{
m_OcclusionQueryObjects[h].m_bHasBeenIssued[i] = false;
}
m_OcclusionQueryObjects[h].m_LastResult = -1;
m_OcclusionQueryObjects[h].m_nFrameIssued = -1;
}
}
//-----------------------------------------------------------------------------
// Bracket drawing with begin and end so that we can get counts next frame.
//-----------------------------------------------------------------------------
void COcclusionQueryMgr::BeginOcclusionQueryDrawing( OcclusionQueryObjectHandle_t hOcclusionQuery )
{
intp h = (intp)hOcclusionQuery;
Assert( m_OcclusionQueryObjects.IsValidIndex( h ) );
if ( m_OcclusionQueryObjects.IsValidIndex( h ) )
{
int nCurrent = m_OcclusionQueryObjects[h].m_nCurrentIssue;
ShaderAPIOcclusionQuery_t hQuery = m_OcclusionQueryObjects[h].m_QueryHandle[nCurrent];
if ( hQuery != INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE )
{
// If it's been issued, but we haven't gotten a result when we polled last time,
// try polling one last time, since we can't poll again after we issue again.
if ( m_OcclusionQueryObjects[h].m_bHasBeenIssued[nCurrent] )
{
int nPixels = g_pShaderAPI->OcclusionQuery_GetNumPixelsRendered( hQuery, false );
if ( ( nPixels == OCCLUSION_QUERY_RESULT_PENDING ) && ( m_OcclusionQueryObjects[h].m_nFrameIssued == m_nFrameCount ) )
{
static int s_nWarnCount = 0;
if ( s_nWarnCount++ < 5 )
{
DevWarning( "blocking issue in occlusion queries! Grab brian!\n" );
}
}
while( !OCCLUSION_QUERY_FINISHED( nPixels ) )
{
// We're going to reuse this query, so issue a flush to force the query results to come back.
nPixels = g_pShaderAPI->OcclusionQuery_GetNumPixelsRendered( hQuery, true );
}
if ( nPixels >= 0 )
{
m_OcclusionQueryObjects[h].m_LastResult = nPixels;
}
m_OcclusionQueryObjects[h].m_bHasBeenIssued[nCurrent] = false;
}
g_pShaderAPI->BeginOcclusionQueryDrawing( hQuery );
}
}
}
void COcclusionQueryMgr::EndOcclusionQueryDrawing( OcclusionQueryObjectHandle_t hOcclusionQuery )
{
intp h = (intp)hOcclusionQuery;
Assert( m_OcclusionQueryObjects.IsValidIndex( h ) );
if ( m_OcclusionQueryObjects.IsValidIndex( h ) )
{
int nCurrent = m_OcclusionQueryObjects[h].m_nCurrentIssue;
ShaderAPIOcclusionQuery_t hQuery = m_OcclusionQueryObjects[h].m_QueryHandle[nCurrent];
if ( hQuery != INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE )
{
g_pShaderAPI->EndOcclusionQueryDrawing( hQuery );
m_OcclusionQueryObjects[h].m_bHasBeenIssued[nCurrent] = true;
m_OcclusionQueryObjects[h].m_nFrameIssued = m_nFrameCount;
nCurrent = (nCurrent+1) % COUNT_OCCLUSION_QUERY_STACK;
m_OcclusionQueryObjects[h].m_nCurrentIssue = nCurrent;
}
}
}
//-----------------------------------------------------------------------------
// Get the number of pixels rendered between begin and end on an earlier frame.
// Calling this in the same frame is a huge perf hit!
//-----------------------------------------------------------------------------
void COcclusionQueryMgr::OcclusionQuery_IssueNumPixelsRenderedQuery( OcclusionQueryObjectHandle_t hOcclusionQuery )
{
intp h = (intp)hOcclusionQuery;
Assert( m_OcclusionQueryObjects.IsValidIndex( h ) );
if ( m_OcclusionQueryObjects.IsValidIndex( h ) )
{
for( int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++ )
{
int nIndex = ( m_OcclusionQueryObjects[h].m_nCurrentIssue + i ) % COUNT_OCCLUSION_QUERY_STACK;
ShaderAPIOcclusionQuery_t hQuery = m_OcclusionQueryObjects[h].m_QueryHandle[nIndex];
if ( hQuery != INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE && m_OcclusionQueryObjects[h].m_bHasBeenIssued[nIndex] )
{
int nPixels = g_pShaderAPI->OcclusionQuery_GetNumPixelsRendered( hQuery );
if ( nPixels == OCCLUSION_QUERY_RESULT_ERROR )
{
// In GL mode, it's possible for queries to fail (say when mat_queue_mode is toggled). In this case, just clear m_bHasBeenIssued and forget we ever issued this query.
m_OcclusionQueryObjects[h].m_bHasBeenIssued[nIndex] = false;
}
else if ( nPixels >= 0 )
{
m_OcclusionQueryObjects[h].m_LastResult = nPixels;
m_OcclusionQueryObjects[h].m_bHasBeenIssued[nIndex] = false;
}
}
}
}
}
int COcclusionQueryMgr::OcclusionQuery_GetNumPixelsRendered( OcclusionQueryObjectHandle_t h, bool bDoQuery )
{
if ( bDoQuery )
{
OcclusionQuery_IssueNumPixelsRenderedQuery( h );
}
int nPixels = m_OcclusionQueryObjects[(intp)h].m_LastResult;
return nPixels;
}
+106
View File
@@ -0,0 +1,106 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#ifndef OCCLUSIONQUERY_H
#define OCCLUSIONQUERY_H
#include "tier1/utlsymbol.h"
#include "tier1/utlrbtree.h"
#ifndef MATSYS_INTERNAL
#error "This file is private to the implementation of IMaterialSystem/IMaterialSystemInternal"
#endif
#if defined( _WIN32 )
#pragma once
#endif
#include "tier1/utllinkedlist.h"
#include "shaderapi/ishaderapi.h"
class IMatRenderContextInternal;
// because the GPU/driver can buffer frames we need to allow several queries to be in flight.
// The game wants to reiusse the queries every frame so we buffer them here to avoid
// having to block waiting for a query to be available for reissue.
#define COUNT_OCCLUSION_QUERY_STACK 4
//-----------------------------------------------------------------------------
// Dictionary of all known materials
//-----------------------------------------------------------------------------
class COcclusionQueryMgr
{
public:
COcclusionQueryMgr();
// Allocate and delete query objects.
OcclusionQueryObjectHandle_t CreateOcclusionQueryObject( );
void OnCreateOcclusionQueryObject( OcclusionQueryObjectHandle_t h );
void DestroyOcclusionQueryObject( OcclusionQueryObjectHandle_t h );
// Bracket drawing with begin and end so that we can get counts next frame.
void BeginOcclusionQueryDrawing( OcclusionQueryObjectHandle_t h );
void EndOcclusionQueryDrawing( OcclusionQueryObjectHandle_t h );
// Used to make the handle think it's never had a successful query before
void ResetOcclusionQueryObject( OcclusionQueryObjectHandle_t );
// Get the number of pixels rendered between begin and end on an earlier frame.
// Calling this in the same frame is a huge perf hit!
int OcclusionQuery_GetNumPixelsRendered( OcclusionQueryObjectHandle_t h, bool bDoQuery );
void OcclusionQuery_IssueNumPixelsRenderedQuery( OcclusionQueryObjectHandle_t h );
// Internal stuff for occlusion query
void AllocOcclusionQueryObjects( void );
void FreeOcclusionQueryObjects( void );
// Advance frame
void AdvanceFrame();
private:
//-----------------------------------------------------------------------------
// Occlusion query objects
//-----------------------------------------------------------------------------
struct OcclusionQueryObject_t
{
ShaderAPIOcclusionQuery_t m_QueryHandle[COUNT_OCCLUSION_QUERY_STACK];
int m_LastResult;
int m_nFrameIssued;
int m_nCurrentIssue;
bool m_bHasBeenIssued[COUNT_OCCLUSION_QUERY_STACK];
OcclusionQueryObject_t(void)
{
for ( int i = 0; i < COUNT_OCCLUSION_QUERY_STACK; i++ )
{
m_QueryHandle[i] = INVALID_SHADERAPI_OCCLUSION_QUERY_HANDLE;
m_bHasBeenIssued[i] = false;
}
m_LastResult = -1;
m_nFrameIssued = -1;
m_nCurrentIssue = 0;
}
};
// Flushes an outstanding query
void FlushQuery( OcclusionQueryObjectHandle_t hOcclusionQuery, int nIndex );
// Occlusion query objects
CUtlFixedLinkedList<OcclusionQueryObject_t> m_OcclusionQueryObjects;
CThreadFastMutex m_Mutex;
int m_nFrameCount;
};
//-----------------------------------------------------------------------------
// Singleton
//-----------------------------------------------------------------------------
extern COcclusionQueryMgr *g_pOcclusionQueryMgr;
#endif // OCCLUSIONQUERY_H
+7
View File
@@ -0,0 +1,7 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#include "pch_materialsystem.h"
+60
View File
@@ -0,0 +1,60 @@
//========== Copyright © 2005, Valve Corporation, All rights reserved. ========
//
// Purpose:
//
//=============================================================================
#ifndef PCH_MATERIALSYSTEM_H
#define PCH_MATERIALSYSTEM_H
#if defined( _WIN32 )
#pragma once
#endif
#if defined( _WIN32 ) && !defined( _X360 )
#define WIN32_LEAN_AND_MEAN 1
#include "windows.h"
#endif
#if defined( _PS3 )
#include <stdlib.h>
#else //_PS3
#include <malloc.h>
#endif //_PS3
#include <string.h>
#include "crtmemdebug.h"
#include "tier0/platform.h"
#include "tier0/dbg.h"
#include "tier0/fasttimer.h"
#include "tier0/vprof.h"
#include "tier1/tier1.h"
#include "tier1/utlstack.h"
#include "tier1/generichash.h"
#include "tier1/utlsymbol.h"
#include "tier1/utlrbtree.h"
#include "tier1/strtools.h"
#include "tier0/icommandline.h"
#include "mathlib/vmatrix.h"
#include "icvar.h"
#include "keyvalues.h"
#include "convar.h"
#include "tier2/tier2.h"
#include "bitmap/imageformat.h"
#include "bitmap/tgawriter.h"
#include "bitmap/tgaloader.h"
#include "datacache/idatacache.h"
#include "filesystem.h"
#include "pixelwriter.h"
#include "materialsystem_global.h"
#include "materialsystem/imaterialvar.h"
#include "materialsystem/imesh.h"
#include "materialsystem/IColorCorrection.h"
#include "imaterialinternal.h"
#include "imaterialsysteminternal.h"
#endif // PCH_MATERIALSYSTEM_H
+76
View File
@@ -0,0 +1,76 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
// SPU Profiling
//
//==================================================================================================
#ifndef INCLUDED_CELLMGR_SPU_PROFILE_H
#define INCLUDED_CELLMGR_SPU_PROFILE_H
//--------------------------------------------------------------------------------------------------
// Headers
//--------------------------------------------------------------------------------------------------
#include <stdint.h>
//--------------------------------------------------------------------------------------------------
// Defines
//--------------------------------------------------------------------------------------------------
// Uncomment to enabled profiling
//#define ENABLE_SPU_PROFILE
//--------------------------------------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------------------------------------
const int NUM_BOOKMARKS_IN_EVENT = 6;
//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------
/*
* Insert a marker that is displayed in Tuner
*/
void insert_bookmark( uint32_t bookmark );
/*
* 400 cycles delay per bookmark when emitting bookmarks on multiple SPUs
*/
void bookmark_delay( int NumBookmarks );
/*
* Inserting 6 SPU bookmarks, which will
* be identified by Tuner as a start event
*/
void raw_spu_prof_start( int iLevel, uint16_t lsa );
/*
* Inserting 6 SPU bookmarks, which will
* be identified by Tuner as a stop event
*/
void raw_spu_prof_stop( uint16_t lsa );
/*
*Profiling macros
*/
#ifdef ENABLE_SPU_PROFILE
#define BEGIN_PROFILE(level) raw_spu_prof_start(level, 0)
#define END_PROFILE(level) raw_spu_prof_stop(level)
#define BEGIN_BOOKMARK(colour) insert_bookmark( colour )
#define END_BOOKMARK(colour)
#else
#define BEGIN_PROFILE(level)
#define END_PROFILE(level)
#define BEGIN_BOOKMARK(colour)
#define END_BOOKMARK(colour)
#endif
#endif // INCLUDED_CELLMGR_SPU_PROFILE_H
+76
View File
@@ -0,0 +1,76 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
//
//
//==================================================================================================
//--------------------------------------------------------------------------------------------------
// Headers
//--------------------------------------------------------------------------------------------------
#include "Profile.h"
#include <spu_intrinsics.h>
//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------
/*
* Insert a marker that is displayed in Tuner
*/
void insert_bookmark( uint32_t bookmark )
{
__asm__ volatile ("wrch $69, %0" :: "r" (bookmark));
// Must wait for 16 cycles
__asm__ volatile ("nop;nop;nop;nop;nop;nop;nop;nop");
__asm__ volatile ("nop;nop;nop;nop;nop;nop;nop;nop");
}
void bookmark_delay( int NumBookmarks )
{
// 400 cycles per bookmark when emitting bookmarks on both SPUs
for ( int i=0; i<NumBookmarks*400/8; i++)
{
__asm__ volatile ("nop;nop;nop;nop;nop;nop;nop;nop");
}
}
/*
* Inserting 6 SPU bookmarks, which will
* be identified by Tuner as a start event
*/
void raw_spu_prof_start( int iLevel, uint16_t lsa )
{
typedef union { char c4[4]; uint16_t u16[2]; uint32_t u32; } Module_u;
static Module_u s_mu = { { 't', 'e', 's', 't' } };
insert_bookmark( 0xffaa ); // start marker 1
insert_bookmark( s_mu.u16[0] ); // name
insert_bookmark( s_mu.u16[1] ); // name
insert_bookmark( iLevel ); // level
insert_bookmark( lsa >> 2 ); // LSA is shifted by 2 as per the SPURS spec.
insert_bookmark( 0xffab ); // start marker 2
bookmark_delay( NUM_BOOKMARKS_IN_EVENT );
}
/*
* Inserting 6 SPU bookmarks, which will
* be identified by Tuner as a stop event
*/
void raw_spu_prof_stop( uint16_t lsa )
{
typedef union { uint16_t u16[4]; uint64_t u64; } GUID_u;
GUID_u guid;
qword insn = si_roti(*(qword*)(0x80 + lsa), 7);
qword pattern = (qword)(vec_uchar16){0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13};
guid.u64 = si_to_ullong(si_shufb(insn, insn, pattern));
insert_bookmark( 0xffac ); // start marker 1
insert_bookmark( guid.u16[0] ); // guid
insert_bookmark( guid.u16[1] ); // guid
insert_bookmark( guid.u16[2] ); // guid
insert_bookmark( guid.u16[3] ); // guid
insert_bookmark( 0xffad ); // start marker 2
bookmark_delay( NUM_BOOKMARKS_IN_EVENT );
}
+98
View File
@@ -0,0 +1,98 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
//
//
//==================================================================================================
#ifndef INCLUDED_SPUMGR_DMA_H
#define INCLUDED_SPUMGR_DMA_H
//--------------------------------------------------------------------------------------------------
// Headers
//--------------------------------------------------------------------------------------------------
#include <stdint.h>
#ifdef SPU
//#include <Stdshader_spu/Inc/debug_spu.h> // MH
#else
#include <debug/inc/debug.h>
#endif
//--------------------------------------------------------------------------------------------------
// Defines
//--------------------------------------------------------------------------------------------------
#define SPUMGR_IS_ALIGNED(val, align) (((val) & ((align) - 1)) == 0)
#define SPUMGR_ALIGN_UP(val, align) (((val) + ((align)-1)) & ~((align) - 1))
#define SPUMGR_ALIGN_DOWN(val, align) ((val) & ~((align) - 1))
#define SPUMGR_MSG_MEMCPY 0x000000ff
#define Assert(val) // MH
//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------
struct MemCpyHeader
{
uint32_t src;
uint32_t dst;
uint32_t size;
uint32_t blocking;
uint8_t cacheLine[16];
};
//--------------------------------------------------------------------------------------------------
// Classes
//--------------------------------------------------------------------------------------------------
struct DMAList
{
uint32_t stallAndNotify :1;
uint32_t reserved :16;
uint32_t size :15;
uint32_t ea;
};
//--------------------------------------------------------------------------------------------------
// DmaCheckAlignment
// Checks restrictions specified in SpuMgr::DmaGet
//--------------------------------------------------------------------------------------------------
int DmaCheckAlignment(uint32_t src, uint32_t dest, uint32_t size);
//--------------------------------------------------------------------------------------------------
//SetupDmaListEntry
//
// Note that this function increments input ptr by number of entries added,
// which will be > 1 if size > 16K
//--------------------------------------------------------------------------------------------------
inline void SetupDmaListEntry(uint32_t stall, uint32_t ea, uint32_t size, DMAList **pDmaList)
{
// check alignment; don't pass in NULL for dest
if (!DmaCheckAlignment(ea, 0x10, size))
{
Assert(0);
}
Assert((size & 0xF) == 0); // for lists input sizes must be multiple of 16 bytes
while (size)
{
uint32_t dmaSize = 0x4000;
dmaSize = size < dmaSize? size: dmaSize;
(*pDmaList)->stallAndNotify = stall;
(*pDmaList)->size = dmaSize;
(*pDmaList)->ea = ea;
size -= dmaSize;
ea += dmaSize;
(*pDmaList)++;
}
}
#endif // INCLUDED_SPUMGR_DMA_H
+628
View File
@@ -0,0 +1,628 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
//
//
//==================================================================================================
//--------------------------------------------------------------------------------------------------
// Headers
//--------------------------------------------------------------------------------------------------
#include "sys/memory.h"
#include "sysutil/sysutil_sysparam.h"
#include "cell/sysmodule.h"
#include "tier0/platform.h"
#include "tier0/dbg.h"
#include "tier1/utlbuffer.h"
#include <sys/timer.h>
#include <sys/spu_image.h>
#include <stdio.h>
#include <stdlib.h>
#include <cell/cell_fs.h>
#include <cell/atomic.h>
#include <string.h>
#include "ps3_pathinfo.h"
#include <cell/spurs/control.h>
#include "SpuMgr_ppu.h"
#include "memdbgon.h"
typedef uint32_t uint32;
#define ASSERT Assert
//--------------------------------------------------------------------------------------------------
// Defines
//--------------------------------------------------------------------------------------------------
// Spu Mailbox Status Register
// Described in CBE architecture chapter 8.6.3 SPU Mailbox Status Register (SPU_Mbox_Stat)
#define SPU_IN_MBOX_COUNT_SHIFT (8)
#define SPU_IN_MBOX_COUNT (0xFF << SPU_IN_MBOX_COUNT_SHIFT)
#define SPU_OUT_MBOX_COUNT (0xFF)
#define SPU_OUT_INTR_MBOX_COUNT_SHIFT (16)
#define SPU_OUT_INTR_MBOX_COUNT (0xFF << SPU_OUT_INTR_MBOX_COUNT_SHIFT)
//--------------------------------------------------------------------------------------------------
// Globals
//--------------------------------------------------------------------------------------------------
// SPU manager instance
SpuMgr gSpuMgr;
//--------------------------------------------------------------------------------------------------
// DmaCheckAlignment
// Checks restrictions specified in SpuMgr::DmaGet
//--------------------------------------------------------------------------------------------------
int DmaCheckAlignment(uint32_t src, uint32_t dest, uint32_t size)
{
#if !defined( _CERT )
uint32_t align = size;
bool error = false;
if (size >= 16 && ((size & 0xf) == 0))
{
align = 16;
}
else if (size == 8 || size == 4 || size == 2 || size == 1)
{
error = ((src & 0xF) != (dest & 0xF));
}
else
{
error = true; // bad size
}
return (!error && src && dest &&
SPUMGR_IS_ALIGNED(src, align) &&
SPUMGR_IS_ALIGNED(dest, align));
#else //!_CERT
return 1;
#endif //!_CERT
}
//--------------------------------------------------------------------------------------------------
// Internal functions
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// handle_syscall
//
// interrupt handler to handle SPU interrupts
// see Handle SPU Interrupts Lv2-Uders_manual_e P34
//--------------------------------------------------------------------------------------------------
void handle_syscall (uint64_t arg)
{
sys_raw_spu_t id = arg;
uint64_t stat;
int ret;
#ifndef _CERT
g_snRawSPULockHandler();
#endif
// Create a tag to handle class 2 interrupt, SPU halts fall in
// this category
ret = sys_raw_spu_get_int_stat(id, 2, &stat);
if (ret)
{
#ifndef _CERT
g_snRawSPUUnlockHandler();
#endif
sys_interrupt_thread_eoi();
}
//
// SPU Stop-and-Signal Instruction Trap
// This interrupt occurs when the SPU executes a stop-and-signal
// instruction.
//
if (stat & INTR_STOP_MASK) //stop
{
//We've hit a stop, so what kind of value is it?
uint32_t signalVal = GetStopSignal( id );
switch ( signalVal )
{
case 0x3:
// it was a stop that is in the SPU code to signal to the PPU
// do any processing for the user defined stop here
// if we do not restart the SPU then we need to call g_snRawSPUNotifySPUStopped(id)
// to inform the debugger that SPU has stopped
//restart the SPU
sys_raw_spu_mmio_write( id, SPU_RunCntl, 0x1 );
break;
default:
#ifndef _CERT
g_snRawSPUNotifySPUStopped(id);
#endif
break;
}
}
else if (stat & INTR_HALT_MASK) // halt
{
#ifndef _CERT
g_snRawSPUNotifySPUStopped(id);
#endif
}
// Other class 2 interrupts could be handled here
// ...
//
// Must reset interrupt status bit of those not handled.
//
ret = sys_raw_spu_set_int_stat(id, 2, stat);
if (ret)
{
#ifndef _CERT
g_snRawSPUUnlockHandler();
#endif
sys_interrupt_thread_eoi();
}
//
// End of interrupt
//
#ifndef _CERT
g_snRawSPUUnlockHandler();
#endif
sys_interrupt_thread_eoi();
}
int CreateDefaultInterruptHandler(SpuTaskHandle *pTask)
{
int res = 0;
//
// Create a SPU interrupt handler thread, an interrupt tag,
// and associate it with the thread
//
// create thread
if (sys_ppu_thread_create(&pTask->m_ppuThread, handle_syscall,
0, INTR_HANDLER_THREAD_PRIORITY, INTR_HANDLER_THREAD_STACK_SIZE,
SYS_PPU_THREAD_CREATE_INTERRUPT, "Interrupt PPU Thread"))
{
res = 1;
goto xit;
}
// create interrupt tag for handling class 2 interrupts from this spu
if (sys_raw_spu_create_interrupt_tag(pTask->m_spuId, 2, SYS_HW_THREAD_ANY, &pTask->m_intrTag))
{
res = 1;
goto xit;
}
// associate interrupt tag with thread
if (sys_interrupt_thread_establish(&pTask->m_interruptThread, pTask->m_intrTag,
pTask->m_ppuThread, pTask->m_spuId))
{
res = 1;
goto xit;
}
// Set interrupt mask - enable Halt, Stop-and-Signal interrupts
if (sys_raw_spu_set_int_mask(pTask->m_spuId, 2, INTR_STOP_MASK | INTR_HALT_MASK))
{
res = 1;
goto xit;
}
xit:
return res;
}
//--------------------------------------------------------------------------------------------------
// Class Methods
//--------------------------------------------------------------------------------------------------
int SpuMgr::Init(int numRawSpu)
{
// Need at least 2 SPUs for SPURS instances
ASSERT(numRawSpu < 5);
// Run SPURS on all SPUs that are not in raw mode
// Creating two SPURS instances. One with a thread group of 5 - numRawSpu threads and one
// with a thread group of 1 thread.
// The instance with a single thread is designed to be singled out as the preemption victim
// when the OS needs to use an SPU. We ensure this by giving it a lower priority than the
// dedicated SPURS instance.
// Init dedicated SPUs SPURS instance
// CellSpursAttribute attr;
// int32 ret = cellSpursAttributeInitialize(&attr, 5 - numRawSpu, 99, 2, false);
// ASSERT(ret == CELL_OK);
// ret = cellSpursAttributeEnableSpuPrintfIfAvailable(&attr);
// ASSERT(ret == CELL_OK);
// ret = cellSpursAttributeSetNamePrefix(&attr, "gameSpusSpurs", std::strlen("gameSpusSpurs"));
// ASSERT(ret == CELL_OK);
// ret = cellSpursInitializeWithAttribute2(&m_exclusiveSpusSpurs, &attr);
// ASSERT(ret == CELL_OK);
// Init pre-emption SPU SPURS instance
// ret = cellSpursAttributeInitialize(&attr, 1, 100, 2, false);
// ASSERT(ret == CELL_OK);
// ret = cellSpursAttributeEnableSpuPrintfIfAvailable(&attr);
// ASSERT(ret == CELL_OK);
// ret = cellSpursAttributeSetNamePrefix(&attr, "sharedSpuSpurs", std::strlen("sharedSpuSpurs"));
// ASSERT(ret == CELL_OK);
// ret = cellSpursInitializeWithAttribute2(&m_preemptedSpuSpurs, &attr);
// ASSERT(ret == CELL_OK);
int res = 0;
// set up members
m_numSpus = 0;
// Initialize SPUs
if (sys_spu_initialize(6, numRawSpu) != SUCCEEDED)
{
res = 1;
goto xit;
}
// Create raw spus
for (; m_numSpus < (uint32)numRawSpu; m_numSpus++)
{
if (sys_raw_spu_create(&m_spuIds[m_numSpus], NULL) != SUCCEEDED)
{
Error("Unable to create saw spu\n");
res = 1;
goto xit;
}
#ifndef _CERT
g_snRawSPUNotifyCreation(m_spuIds[m_numSpus]);
#endif
m_spuInUse[m_numSpus] = 0;
}
xit:
return res;
}
void SpuMgr::Term()
{
uint32 spu;
// destroy raw spus
for (spu = 0; spu < m_numSpus; spu++)
{
sys_raw_spu_destroy(m_spuIds[spu]);
}
// destroy the SPURS instances
// int ret;
// ret = cellSpursfinalize(&m_exclusiveSpusSpurs);
// ASSERT(ret == CELL_OK);
//
// ret = cellSpursfinalize(&m_preemptedSpuSpurs);
// ASSERT(ret == CELL_OK);
m_numSpus = 0;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
uint32_t spumgr_mmio_read(uint32_t spu, uint32_t regoffset)
{
uint64_t addr = get_reg_addr(spu,regoffset);
addr &= 0xffffffffUL;
volatile uint32_t * pAddr = (uint32_t*) addr;
return *pAddr;
}
void spumgr_mmio_write(int spu, int regoffset, uint32_t value)
{
uint64_t addr = get_reg_addr(spu,regoffset);
addr &= 0xffffffffUL;
volatile uint32_t * pAddr = (uint32_t*) addr;
*pAddr = value;
}
//--------------------------------------------------------------------------------------------------
// Create Spu task from file based image
//--------------------------------------------------------------------------------------------------
static char modPath[MAX_PATH];
int SpuMgr::CreateSpuTask(const char *path, SpuTaskHandle *pTask,
CreateSPUTaskCallback *pfnCallback /* = NULL */)
{
int res = 0;
int ret;
uint32 spu;
register uint32 spuid;
uint32 entry;
FILE* fp;
void* pSpuProg = NULL;
sys_spu_image_t img;
pTask->m_spuId = -1;
pTask->m_ppuThread = NULL;
pTask->m_intrTag = NULL;
pTask->m_interruptThread = NULL;
// find free raw spu
for (spu = 0; spu < m_numSpus; spu++)
{
if (!m_spuInUse[spu])
{
break;
}
}
// check we found free spu
if (spu == m_numSpus)
{
res = 1;
goto xit;
}
// Loading an SPU program to the Raw SPU.
//if (sys_raw_spu_load(m_spuIds[spu], path, &entry) != SUCCEEDED)
sprintf(modPath, "%s/%s", g_pPS3PathInfo->PrxPath(), path);
path = modPath;
if(strstr(path,".self"))
{
ret = sys_spu_image_open(&img, path);
if(ret != CELL_OK)
{
// (Running on Main Thread)
Error("Failed to open SPU program: %s\n", path);
}
}
else
{
// Allocate mem for SPU prog
CellFsStat stat;
cellFsStat(path,&stat);
pSpuProg = memalign(4096,((uint32)stat.st_size + 0x7f)&0xffffff80);
fp = fopen(path, "rb");
fread(pSpuProg, 1, stat.st_size, fp );
fclose(fp);
ret = sys_spu_image_import(&img, pSpuProg, SYS_SPU_IMAGE_PROTECT);
if (ret != CELL_OK)
{
res = 1;
goto xit;
}
}
ret = sys_raw_spu_image_load(m_spuIds[spu], &img);
spuid = m_spuIds[spu];
if (ret == CELL_OK)
{
// successfully loaded - mark spu as used and fill in o/p
m_spuInUse[spu] = 1;
pTask->m_spuId = spuid;
}
else
{
res = 1;
goto xit;
}
//Free PPU resources used to load image
if(pSpuProg)
{
free(pSpuProg);
}
sys_spu_image_close(&img);
entry = sys_raw_spu_mmio_read((uint32_t)spuid, (uint32_t)SPU_NPC);
#ifndef _CERT
g_snRawSPUNotifyElfLoad(spuid, entry, path);
#endif
// call callback or create default interrupt handler
if (!pfnCallback)
{
res = CreateDefaultInterruptHandler(pTask);
}
else
{
res = pfnCallback(pTask);
}
if (res)
{
goto xit;
}
// Run the Raw SPU
#ifndef _CERT
g_snRawSPUNotifySPUStarted(m_spuIds[spu]);
#endif
sys_raw_spu_mmio_write(spuid, SPU_NPC, entry);
sys_raw_spu_mmio_write(spuid, SPU_RunCntl, 0x1);
__asm("eieio");
// Once the SPU has started, write a mailbox with the effective address of the
// SPU lock.
WriteMailbox( pTask, (uint32) &pTask->m_lock );
WriteMailbox( pTask, (uint32) &pTask->m_memcpyLock );
xit:
if(res)
{
// Error("Error: CreateSpuTask error attempting to load and run %s on SPU\n", path);
}
return res;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void SpuMgr::DestroySpuTask(SpuTaskHandle *pTask)
{
if (pTask->m_spuId != -1)
{
// Stop the Raw spu
#ifndef _CERT
g_snRawSPUNotifySPUStopped(pTask->m_spuId);
#endif
sys_raw_spu_mmio_write(pTask->m_spuId, SPU_RunCntl, 0x0);
__asm("eieio");
// Cleanup interrupt handling mechanism
if (pTask->m_interruptThread)
{
sys_interrupt_thread_disestablish(pTask->m_interruptThread); // also kills the thread
}
if (pTask->m_intrTag)
{
sys_interrupt_tag_destroy(pTask->m_intrTag);
}
}
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
int SpuMgr::WriteMailbox(SpuTaskHandle *pTask, uint32 val, bool bBlocking /* =true */)
{
uint32 mboxAvailable;
do
{
// Check the SPU Mailbox Status Register
mboxAvailable = sys_raw_spu_mmio_read(pTask->m_spuId, SPU_MBox_Status) & SPU_IN_MBOX_COUNT;
} while (bBlocking && !mboxAvailable);
if (mboxAvailable)
sys_raw_spu_mmio_write(pTask->m_spuId, SPU_In_MBox, (std::uint32_t)val);
return !mboxAvailable;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
int SpuMgr::ReadMailbox(SpuTaskHandle *pTask, uint32 *pVal, bool bBlocking /* = true */)
{
uint32 mailAvailable;
do
{
// Check the SPU Mailbox Status Register
mailAvailable = sys_raw_spu_mmio_read(pTask->m_spuId, SPU_MBox_Status) & SPU_OUT_MBOX_COUNT;
} while (bBlocking && !mailAvailable);
if (mailAvailable)
{
// Read the SPU Outbound Mailbox Register
*pVal = sys_raw_spu_mmio_read(pTask->m_spuId, SPU_Out_MBox);
}
return !mailAvailable;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
int SpuMgr::ReadIntrMailbox(SpuTaskHandle *pTask, uint32 *pVal, bool bBlocking /* = true */)
{
uint32 mailAvailable;
do
{
// Check the SPU Mailbox Status Register
mailAvailable = sys_raw_spu_mmio_read(pTask->m_spuId, SPU_MBox_Status) & SPU_OUT_INTR_MBOX_COUNT;
} while (bBlocking && !mailAvailable);
if (mailAvailable)
{
// Read the SPU Outbound Mailbox Register
sys_raw_spu_read_puint_mb(pTask->m_spuId, pVal);
}
return !mailAvailable;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
bool SpuMgr::Lock( SpuTaskHandle *pTask )
{
return cellAtomicCompareAndSwap32( &pTask->m_lock, 0, 1 ) == 0;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void SpuMgr::Unlock( SpuTaskHandle *pTask )
{
cellAtomicCompareAndSwap32( &pTask->m_lock, 1, 0 );
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
bool SpuMgr::MemcpyLock( SpuTaskHandle *pTask )
{
return cellAtomicCompareAndSwap32( &pTask->m_memcpyLock, 0, 1 ) == 0;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void SpuMgr::MemcpyUnlock( SpuTaskHandle *pTask )
{
cellAtomicCompareAndSwap32( &pTask->m_memcpyLock, 1, 0 );
}
+238
View File
@@ -0,0 +1,238 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
// Raw SPU management
//
//==================================================================================================
#ifndef INCLUDED_SPUMGR_PPU_H
#define INCLUDED_SPUMGR_PPU_H
//--------------------------------------------------------------------------------------------------
// Headers
//--------------------------------------------------------------------------------------------------
#include <sys/spu_initialize.h>
#include <sys/raw_spu.h>
#include <sys/spu_utility.h>
#include <sys/ppu_thread.h>
#include <sys/interrupt.h>
#include <sys/raw_spu.h>
#include <sys/sys_time.h>
#include <cell/spurs.h>
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
extern "C"
{
extern void (*g_snRawSPULockHandler) (void);
extern void (*g_snRawSPUUnlockHandler) (void);
extern void (*g_snRawSPUNotifyCreation) (unsigned int uID);
extern void (*g_snRawSPUNotifyDestruction) (unsigned int uID);
extern void (*g_snRawSPUNotifyElfLoad) (unsigned int uID, unsigned int uEntry, const char *pFileName);
extern void (*g_snRawSPUNotifyElfLoadNoWait) (unsigned int uID, unsigned int uEntry, const char *pFileName);
extern void (*g_snRawSPUNotifyElfLoadAbs) (unsigned int uID, unsigned int uEntry, const char *pFileName);
extern void (*g_snRawSPUNotifyElfLoadAbsNoWait) (unsigned int uID, unsigned int uEntry, const char *pFileName);
extern void (*g_snRawSPUNotifySPUStopped) (unsigned int uID);
extern void (*g_snRawSPUNotifySPUStarted) (unsigned int uID);
};
//--------------------------------------------------------------------------------------------------
// Fwd refs
//--------------------------------------------------------------------------------------------------
class CellSpurs2;
class SpuTaskHandle;
//--------------------------------------------------------------------------------------------------
// Defines
//--------------------------------------------------------------------------------------------------
#define MAX_RAW_SPUS 5
// Class 2 Interrupt Status Register (INT_Stat_class2)
// Described in CBE architecture v10 on page 259
#define INTR_PPU_MB_SHIFT 0
#define INTR_STOP_SHIFT 1
#define INTR_HALT_SHIFT 2
#define INTR_DMA_SHIFT 3
#define INTR_SPU_MB_SHIFT 4
#define INTR_PPU_MB_MASK (0x1 << INTR_PPU_MB_SHIFT)
#define INTR_STOP_MASK (0x1 << INTR_STOP_SHIFT)
#define INTR_HALT_MASK (0x1 << INTR_HALT_SHIFT)
#define INTR_DMA_MASK (0x1 << INTR_DMA_SHIFT)
#define INTR_SPU_MB_MASK (0x1 << INTR_SPU_MB_SHIFT)
// thread priority for interrupt handler threads
#define INTR_HANDLER_THREAD_PRIORITY 200
#define INTR_HANDLER_THREAD_STACK_SIZE 0x4000
#define SPUMGR_IS_ALIGNED(val, align) (((val) & ((align) - 1)) == 0)
#define SPUMGR_ALIGN_UP(val, align) (((val) + ((align)-1)) & ~((align) - 1))
#define SPUMGR_ALIGN_DOWN(val, align) ((val) & ~((align) - 1))
//--------------------------------------------------------------------------------------------------
// Overide sys_raw_spu_mmio_read / write, since they draw out another bug in SNC :(
//--------------------------------------------------------------------------------------------------
#define sys_raw_spu_mmio_read(spu, regoffset) spumgr_mmio_read(spu, regoffset)
extern uint32_t spumgr_mmio_read(uint32_t spu, uint32_t regoffset);
#define sys_raw_spu_mmio_write(spu, regoffset, value) spumgr_mmio_write(spu, regoffset, value)
extern void spumgr_mmio_write(int id, int offset, uint32_t value);
//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------
typedef int CreateSPUTaskCallback(SpuTaskHandle *pTask);
// SpuStatusRegister
// Described in CBE architecture v10 on page 87
typedef union SpuStatusRegister
{
struct
{
uint32_t m_sc : 16;
uint32_t m_reserved2 : 5;
uint32_t m_isolateExitStatus : 1;
uint32_t m_isolateLoadStatus : 1;
uint32_t m_reserved1 : 1;
uint32_t m_isolationStatus : 1;
uint32_t m_illegalChannelInstructionDetected : 1;
uint32_t m_invalidInstructionDetected : 1;
uint32_t m_singleStepStatus : 1;
uint32_t m_waitStatus : 1;
uint32_t m_haltStatus : 1;
uint32_t m_programStopAndSignalStatus : 1;
uint32_t m_runStatus : 1;
};
uint32_t m_val;
} SpuStatusRegister;
//--------------------------------------------------------------------------------------------------
// Classes
//--------------------------------------------------------------------------------------------------
class SpuTaskHandle
{
public:
sys_raw_spu_t m_spuId;
sys_ppu_thread_t m_ppuThread;
sys_interrupt_tag_t m_intrTag;
sys_interrupt_thread_handle_t m_interruptThread;
uint32_t m_lock;
uint32_t m_memcpyLock;
};
//--------------------------------------------------------------------------------------------------
// SpuMgr
//
// Provides functionality for running raw spu tasks. For this purpose it creates
// and manages a raw spu pool
//
// Currently we assume a simple setup where app loads an elf on to a raw spu,
// after which the spu starts running the elf and continues to do so thereafter.
// The ppu->spu and spu->ppu communication is explicitly handled by the app
// and the spu program using SpuMgr methods
//
// Currently all DMA transfer is supposed to be initiated by the SPUs which is
// why SpuMgr does not provide any DMA functionality
//--------------------------------------------------------------------------------------------------
class SpuMgr
{
public:
// Init/Term
int Init(int numRawSpu);
void Term();
// Create/Destroy tasks
int CreateSpuTask(const char *path, SpuTaskHandle *pTask, CreateSPUTaskCallback *pfnCallback = NULL);
void DestroySpuTask(SpuTaskHandle *pTask);
//
// Helper functions to communicate with the SPU
// As we build more functionality into the SPU mgr it is
// possible that we will need to expose less of
// these low-level functions
//
//
// Mailbox functions
//
//
// The SPU Inbound Mailbox is a 4-level FIFO structure for communication from the
// PPU to SPU, and can hold up to four 32-bit messages.
// If there are already four messages in the mailbox the last message will be
// overwritten...but we can check for a full mailbox and prevent this
int WriteMailbox(SpuTaskHandle *pTask, uint32_t val, bool bBlocking = true);
// The SPU Outbound Mailbox can hold one 32-bit message for SPU-to-PPU communication.
int ReadMailbox(SpuTaskHandle *pTask, uint32_t *pVal, bool bBlocking = true);
// The SPU Outbound Interrupt Mailbox can hold one 32-bit message for SPU-to-PPU communication.
int ReadIntrMailbox(SpuTaskHandle *pTask, uint32_t *pVal, bool bBlocking = true);
//
// Access to local store - note that this involves MMIO which will be slow
// so need to use DMA instead for any significant data transfer. This
// mechanism may be useful for writing some small amount of data such
// as some constants etc into LS
//
int WriteLS(SpuTaskHandle *pTask, uint32_t lsOffset, void *pData, uint32_t size);
int ReadLS(SpuTaskHandle *pTask, uint32_t lsOffset, void *pData, uint32_t size);
bool Lock( SpuTaskHandle *pTask );
void Unlock( SpuTaskHandle *pTask );
bool MemcpyLock( SpuTaskHandle *pTask );
void MemcpyUnlock( SpuTaskHandle *pTask );
// CellSpurs2 m_exclusiveSpusSpurs; // SPURS instance running on SPUs used exclusively by the application
// CellSpurs2 m_preemptedSpuSpurs; // SPURS instance running on an SPU shared with the OS (may be preempted by it occasionally)
private:
uint32_t m_numSpus;
uint32_t m_spuInUse[MAX_RAW_SPUS];
sys_raw_spu_t m_spuIds[MAX_RAW_SPUS];
int ReadMailboxChannel(SpuTaskHandle *pTask, uint32_t *pVal,
uint32_t countMask, uint32_t channel, bool bBlocking = true);
};
//--------------------------------------------------------------------------------------------------
// Externs
//--------------------------------------------------------------------------------------------------
extern SpuMgr gSpuMgr;
//--------------------------------------------------------------------------------------------------
// DmaCheckAlignment
// Checks restrictions specified in SpuMgr::DmaGet
//--------------------------------------------------------------------------------------------------
int DmaCheckAlignment(uint32_t src, uint32_t dest, uint32_t size);
//--------------------------------------------------------------------------------------------------
// GetStopSignal
//--------------------------------------------------------------------------------------------------
inline uint32_t GetStopSignal( sys_raw_spu_t idSpu )
{
SpuStatusRegister status;
status.m_val = sys_raw_spu_mmio_read(idSpu, SPU_Status);
uint32_t stopSignal = status.m_sc;
return stopSignal;
}
#endif // INCLUDED_SPUMGR_PPU_H
+485
View File
@@ -0,0 +1,485 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
//
//
//==================================================================================================
//--------------------------------------------------------------------------------------------------
// Headers
//--------------------------------------------------------------------------------------------------
#include "SpuMgr_spu.h"
#include <cell/atomic.h>
#ifndef _CERT
#include <libsn_spu.h>
#endif
#include <stdlib.h>
#include <string.h>
//--------------------------------------------------------------------------------------------------
// Globals
//--------------------------------------------------------------------------------------------------
// singleton instance
SpuMgr gSpuMgr __attribute__((aligned(128)));
unsigned char gUnalignedMem[16] __attribute__((aligned(16)));
MemCpyHeader gMemCpyHeader __attribute__((aligned(16)));
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void SPU_memcpy( void *pBuf1, void *pBuf2 )
{
uint32_t header;
gSpuMgr.ReadMailbox( &header );
gSpuMgr.MemcpyLock();
gSpuMgr.DmaGetUNSAFE( &gMemCpyHeader, header, sizeof( MemCpyHeader ), 0 );
gSpuMgr.DmaDone( 0x1 );
DEBUG_ERROR( ( gMemCpyHeader.src & 0xf ) == 0 );
uint32_t sizeAligned;
uint32_t sizeAlignedDown;
uint32_t dstAlignedDown;
uint32_t offset;
memcpy( gUnalignedMem, gMemCpyHeader.cacheLine, 16 );
while ( gMemCpyHeader.size > 8192 )
{
sizeAligned = 8192;
dstAlignedDown = SPUMGR_ALIGN_DOWN( gMemCpyHeader.dst, 16 );
offset = gMemCpyHeader.dst - dstAlignedDown;
gSpuMgr.DmaGetUNSAFE( pBuf1, gMemCpyHeader.src, sizeAligned, 0 );
gSpuMgr.DmaDone( 0x1 );
if ( offset )
{
memcpy( pBuf2, gUnalignedMem, offset );
}
memcpy( (void *) ( (uint32_t) pBuf2 + offset ), pBuf1, sizeAligned );
gSpuMgr.DmaSync();
gSpuMgr.DmaPut( dstAlignedDown, pBuf2, SPUMGR_ALIGN_UP( sizeAligned + offset, 16 ), 0 );
gSpuMgr.DmaDone( 0x1 );
sizeAlignedDown = SPUMGR_ALIGN_DOWN( sizeAligned + offset, 16 );
memcpy( gUnalignedMem, (void *) ( (uint32_t) pBuf2 + sizeAlignedDown ), 16 );
gMemCpyHeader.size -= sizeAligned;
gMemCpyHeader.dst += 8192;
gMemCpyHeader.src += 8192;
}
sizeAligned = SPUMGR_ALIGN_UP( gMemCpyHeader.size, 16 );
dstAlignedDown = SPUMGR_ALIGN_DOWN( gMemCpyHeader.dst, 16 );
offset = gMemCpyHeader.dst - dstAlignedDown;
gSpuMgr.DmaGetUNSAFE( pBuf1, gMemCpyHeader.src, sizeAligned, 0 );
gSpuMgr.DmaDone( 0x1 );
if ( offset )
{
memcpy( pBuf2, gUnalignedMem, offset );
}
memcpy( (void *) ( (uint32_t) pBuf2 + offset ), pBuf1, gMemCpyHeader.size );
sizeAligned = SPUMGR_ALIGN_UP( gMemCpyHeader.size + offset, 16 );
gSpuMgr.DmaSync();
gSpuMgr.DmaPut( dstAlignedDown, pBuf2, sizeAligned, 0 );
gSpuMgr.DmaDone( 0x1 );
if ( gMemCpyHeader.blocking )
{
gSpuMgr.WriteMailbox( 0 );
}
gSpuMgr.MemcpyUnlock();
}
//--------------------------------------------------------------------------------------------------
// DmaCheckAlignment
//
// Checks restrictions specified in SpuMgr::DmaGet
//--------------------------------------------------------------------------------------------------
int DmaCheckAlignment(uint32_t src, uint32_t dest, uint32_t size)
{
#if !defined( _CERT )
uint32_t align = size;
bool error = false;
if (size >= 16 && ((size & 0xf) == 0))
{
align = 16;
}
else if (size == 8 || size == 4 || size == 2 || size == 1)
{
error = ((src & 0xF) != (dest & 0xF));
}
else
{
error = true; // bad size
}
return (!error && src && dest &&
SPUMGR_IS_ALIGNED(src, align) &&
SPUMGR_IS_ALIGNED(dest, align));
#else //!FINAL
return 1;
#endif //!FINAL
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
int SpuMgr::Init()
{
// Start the decrementer since it is possible
// that it has not been started by default
const unsigned int kEventDec = 0x20;
// Disable the decrementer event.
unsigned int maskEvents = spu_readch(SPU_RdEventStatMask);
spu_writech(SPU_WrEventMask, maskEvents & ~kEventDec);
// Acknowledge any pending events and stop the decrementer.
spu_writech(SPU_WrEventAck, kEventDec);
// Write the decrementer value to start the decrementer.
unsigned int decValue = spu_readch(SPU_RdDec);
spu_writech(SPU_WrDec, decValue);
// Enable events.
spu_writech(SPU_WrEventMask, maskEvents | kEventDec);
// Reset byte count
ResetBytesTransferred();
// reset malloc count
m_mallocCount = 0;
// Read the effective address of the SPU locks.
ReadMailbox( &m_lockEA );
ReadMailbox( &m_memcpyLockEA );
return 0;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
void SpuMgr::Term()
{
}
//--------------------------------------------------------------------------------------------------
// SpuMgr::DmaGet
//
// DmaGet - alignment and size checking
// DmaGetUNSAFE - no alignment or size checking (but will assert in debug)
// _DmaGet - handles badly aligned dma's, should be a private member really (doesn't handle small dma's)
//
// DMA restrictions
// An MFC supports naturally aligned DMA transfer sizes of 1, 2, 4,
// 8, and 16 bytes and multiples of 16 bytes
// Furthermore, if size is 1, 2, 4, or 8 bytes then lower 4 bits
// of LS and EA must match
//
// Note:
// Peak performance is achieved for transfers in which both the EA and
// the LSA are 128-byte aligned and the size of the transfer is a multiple
// of 128 bytes.
//--------------------------------------------------------------------------------------------------
void SpuMgr::DmaGetUNSAFE(void *ls, uint32_t ea, uint32_t size, uint32_t tagId)
{
DEBUG_ERROR( ea < 0xd0000000 );
DEBUG_ERROR( ea );
DEBUG_ERROR(DmaCheckAlignment((uint32_t)ls, ea, size));
// do the dma
while (size)
{
uint32_t dmaSize = 0x4000;
dmaSize = (size < dmaSize)? size: dmaSize;
size -= dmaSize;
// kick off dma
spu_mfcdma64( (void*)ls, 0, ea, dmaSize, tagId, MFC_GET_CMD);
m_numDMATransfers++;
ls = (void*)((uint32_t)ls + dmaSize);
ea += dmaSize;
}
// add up bytes transferred
m_bytesRequested += size;
m_bytesTransferred += size;
}
//--------------------------------------------------------------------------------------------------
// SpuMgr::_DmaGet
//
// Internal function - do not call this directly
//--------------------------------------------------------------------------------------------------
void SpuMgr::_DmaGet(void *ls, uint32_t ea, uint32_t size, uint32_t tagId)
{
uint32_t unaligned = false;
uint32_t eaAligned = (uint32_t)ea;
uint32_t sizeAligned = size;
uint32_t lsAligned = (uint32_t)ls;
uint32_t sizeOffset = 0;
char *pTempBuff = NULL;
// check if src is unaligned
if (eaAligned & 0xF)
{
eaAligned = eaAligned & ~0xF; // round down
sizeOffset = ea - eaAligned;
sizeAligned += sizeOffset;
unaligned = true;
}
// check if size is unaligned
if (sizeAligned & 0xF)
{
sizeAligned = (sizeAligned + 0xF) & ~0xF; // round up
unaligned = true;
}
// if we have adjusted the size, or if ls is unaligned,
// we need to alloc temp buffer
if (unaligned || (lsAligned & 0xF))
{
pTempBuff = (char*)MemAlign(0x10, sizeAligned);
lsAligned = (uint32_t)pTempBuff;
unaligned = true;
}
// add up bytes transferred, for informational purposes
m_bytesRequested += size;
m_bytesTransferred += sizeAligned;
// do the dma
while (sizeAligned)
{
uint32_t dmaSize = 0x4000;
dmaSize = (sizeAligned < dmaSize)? sizeAligned: dmaSize;
sizeAligned -= dmaSize;
// kick off dma
spu_mfcdma64( (void*)lsAligned, 0, eaAligned, dmaSize, tagId, MFC_GET_CMD);
m_numDMATransfers++;
lsAligned += dmaSize;
eaAligned += dmaSize;
}
if (unaligned)
{
// block for now till dma done because we do the memcpy right here
DmaDone(1 << tagId);
// copy data over
memcpy(ls, pTempBuff + sizeOffset, size);
// free temp buff
Free(pTempBuff);
}
}
//--------------------------------------------------------------------------------------------------
// SpuMgr::DmaGetSAFE
//
// DMA restrictions (look at SpuMgr::DmaGetUNSAFE in this file) are
// handled transparently by this function
//--------------------------------------------------------------------------------------------------
void SpuMgr::DmaGetSAFE(void *ls, uint32_t ea, uint32_t size, uint32_t tagId)
{
DEBUG_ERROR( ea );
if( size < 0x10 )
{
// lowest 4 bits of address have to match regardless, &
// size can only be 1, 2, 4 or 8 B
if( size==0x1 || size==0x2 || size==0x4 || size==0x8 )
{
if( ((uint32_t)ls&0xF == ea&0xF) )
{
DmaGetUNSAFE(ls,ea,size,tagId);
}
else
{
// small get not aligned within a 16B block
_DmaGet(ls,ea,size,tagId);
}
}
else
{
// if < 16B can only get 1,2,4 or 8B
_DmaGet(ls,ea,size,tagId);
}
}
else
{
if( (!(size & 0xF)) && // has to be multiple of 16B, &
(((uint32_t)ls&0xF)==0) && // ea and ls have to be 16B aligned
((ea&0xF)==0) )
{
// alignment is okay just dma
DmaGetUNSAFE(ls,ea,size,tagId);
}
else
{
_DmaGet(ls,ea,size,tagId);
}
}
}
//--------------------------------------------------------------------------------------------------
// SpuMgr::DmaPut
//--------------------------------------------------------------------------------------------------
void SpuMgr::DmaPut(uint32_t ea, void *ls, uint32_t size, uint32_t tagId)
{
DEBUG_ERROR( (ea!=0) && (ea<0xd0000000) ); // valid ea
DEBUG_ERROR( (uint32_t)ls < 0x40000 ); // valid ls
DEBUG_ERROR(DmaCheckAlignment((uint32_t)ls, ea, size));
// do the dma
while (size)
{
uint32_t dmaSize = 0x4000;
dmaSize = (size < dmaSize)? size: dmaSize;
size -= dmaSize;
// initiate dma to ppu
spu_mfcdma64( ls, 0, ea, dmaSize, tagId, MFC_PUT_CMD);
ls = (void*)((uint32_t)ls + dmaSize);
ea += dmaSize;
}
}
//--------------------------------------------------------------------------------------------------
// SpuMgr::DmaSmallPut
//--------------------------------------------------------------------------------------------------
void SpuMgr::DmaSmallPut(uint32_t ea, void *ls, uint32_t size, uint32_t tagId)
{
DEBUG_ERROR( (ea!=0) && (ea<0xd0000000) ); // valid ea
DEBUG_ERROR( (uint32_t)ls < 0x40000 ); // valid ls
DEBUG_ERROR(DmaCheckAlignment((uint32_t)ls, ea, size));
uint32_t dmaSize = 1;
if ((size % 8) == 0)
{
dmaSize = 8;
}
else if ((size % 4) == 0)
{
dmaSize = 4;
}
else if ((size % 2) == 0)
{
dmaSize = 2;
}
while (size)
{
size -= dmaSize;
// initiate dma to ppu
spu_mfcdma64( ls, 0, ea, dmaSize, tagId, MFC_PUT_CMD);
ls = (void*)((uint32_t)ls + dmaSize);
ea += dmaSize;
}
}
//--------------------------------------------------------------------------------------------------
// SpuMgr::DmaGetlist
//
// Gather data scattered around main mem, MFC will run through the list, and place the elements (based on ea address and size)
// contiguously in ls.
//
// NOTE: if an individual list element size is <16B, the data will still be dma'd but the proceeding element will be placed
// on the next 16B boundary. So it is possible to get lots of small elements, but you will be left with gaps in ls.
//
// ls - ls address of where items will be placed (contiguously)
// lsList - ls address of actual list
// sizeList - size of list in bytes (each list element is 8B (sizeof(DMAList)), so sizeList should be number of list elements // sizeof(DMAList))
// tagId - works the same way as regular DMA's
//
// Alignment and Size Restrictions:
// -ls and lsList must be 8B aligned
// -size must be a multiple of 8B (sizeof(DMAList))
// -no more than 2048 list elements
//
// light error checking right now
//--------------------------------------------------------------------------------------------------
void SpuMgr::DmaGetList(void *ls, DMAList *pLS_List, uint32_t sizeList, uint32_t tagId)
{
DEBUG_ERROR( ((uint32_t)pLS_List&0x7) == 0 ); // ls address must be 8B aligned
DEBUG_ERROR( ((uint32_t)ls&0x7) == 0 ); // ea so aligned also, due to offset within 16B alignment restrictions
DEBUG_ERROR( (sizeList&0x7) == 0 ); // list size is a multiple of 8B
DEBUG_ERROR( sizeList<(2048*sizeof(DMAList))); // no more than 2048 list elements
// initiate dma list
spu_mfcdma64( ls, 0, (uint32_t)pLS_List, sizeList, tagId, MFC_GETL_CMD );
}
//--------------------------------------------------------------------------------------------------
// SpuMgr::DmaGPutlist
//
// Scatter data held contiguously in ls, to main mem
//
// ls - ls address of where items exist (contiguously) to be scattered back to main mem
// lsList - ls address of actual list
// sizeList - size of list in bytes (each list element is 8B (sizeof(DMAList)), so sizeList should be number of list elements * sizeof(DMAList))
// tagId - works the same way as regular DMA's
//
// Alignment and Size Restrictions:
// ls and lsList must be 8B aligned, size must be a multiple of 8B (sizeof(DMAList))
//
// light error checking right now
//--------------------------------------------------------------------------------------------------
void SpuMgr::DmaPutList(void *ls, DMAList* pLS_List, uint32_t sizeList, uint32_t tagId)
{
DEBUG_ERROR( ((uint32_t)pLS_List&0x7) == 0 ); // ls address must be 8B aligned
DEBUG_ERROR( ((uint32_t)ls&0x7) == 0 ); // ea so aligned also, due to offset within 16B alignment restrictions
DEBUG_ERROR( (sizeList&0x7) == 0 ); // list size is a multiple of 8B
DEBUG_ERROR( sizeList<(2048*sizeof(DMAList))); // no more than 2048 list elements
// initiate dma list
spu_mfcdma64( ls, 0, (uint32_t)pLS_List, sizeList, tagId, MFC_PUTL_CMD );
}
+473
View File
@@ -0,0 +1,473 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
//
//
//==================================================================================================
#ifndef INCLUDED_SPUMGR_SPU_H
#define INCLUDED_SPUMGR_SPU_H
//--------------------------------------------------------------------------------------------------
// Headers
//--------------------------------------------------------------------------------------------------
#include <stdint.h>
#include <string.h>
#include <spu_intrinsics.h>
#include <spu_mfcio.h>
#include <stdlib.h>
#include <cell/atomic.h>
#include "SpuMgr_dma.h"
#include <libsn_spu.h>
//--------------------------------------------------------------------------------------------------
// Defines
//--------------------------------------------------------------------------------------------------
#define DEBUG_ASSERT(val) Assert(val)
#define DEBUG_ERROR(val) Assert(val)
#define Msg(...)
#define Error(...)
#define DebuggerBreak() snPause()
#include <sys/integertypes.h>
//Short aliases
typedef int8_t s8;
typedef uint8_t u8;
typedef int16_t s16;
typedef uint16_t u16;
typedef int32_t s32;
typedef uint32_t u32;
typedef uint32_t u64[2];
typedef float f32;
typedef double f64;
typedef int BOOL;
typedef s8 int8;
typedef u8 uint8;
typedef s16 int16;
typedef u16 uint16;
typedef s32 int32;
typedef u32 uint32;
typedef u64 uint64;
typedef unsigned int uintp;
typedef unsigned int uint;
typedef vector float fltx4 ;
#define INT_MAX 0x7fffffff
#define DECL_ALIGN(x) __attribute__( ( aligned( x ) ) )
#define ALIGN16 DECL_ALIGN(16)
#define ALIGN16_POST
#define ALIGN128 DECL_ALIGN(128)
#define ALIGN128_POST
template <typename T>
inline T AlignValue( T val, uintp alignment )
{
return ( T )( ( ( uintp )val + alignment - 1 ) & ~( alignment - 1 ) );
}
#define ALIGN_VALUE( val, alignment ) ( ( val + alignment - 1 ) & ~( alignment - 1 ) )
inline bool IsPowerOfTwo( uint x )
{
return ( x & ( x - 1 ) ) == 0;
}
#define FORCEINLINE inline /* __attribute__ ((always_inline)) */
#define IsPlatformPS3() 1
#define IsPlatformPS3_PPU() 0
#define IsPlatformPS3_SPU() 1
#define IsPlatformX360() 0
#define IsPlatformOSX() 0
#define RESTRICT
#define V_memset __builtin_memset
#define V_memcpy memcpy
void SPU_memcpy( void *pBuf1, void *pBuf2 );
#define MemAlloc_AllocAligned(size, align) gSpuMgr.MemAlign(align, size)
#define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0]))
#define MIN( a, b ) ( ( ( a ) < ( b ) ) ? ( a ) : ( b ) )
#define MAX( a, b ) ( ( ( a ) > ( b ) ) ? ( a ) : ( b ) )
//--------------------------------------------------------------------------------------------------
// Task handle
//--------------------------------------------------------------------------------------------------
class SpuTaskHandle
{
public:
uint32_t m_spuId;
uint64_t m_ppuThread;
uint32_t m_intrTag;
uint32_t m_interruptThread;
uint32_t m_lock;
uint32_t m_memcpyLock;
};
//--------------------------------------------------------------------------------------------------
// SpuMgr
//--------------------------------------------------------------------------------------------------
class SpuMgr
{
public:
// Init/Term
int Init();
void Term();
// MFC Atomic Update functionality
// Currently provides functionality to read/write up to
// one cache line (128 bytes) of main mem
inline void MFCAGet(void *ls, uint32_t ea, uint32_t size);
inline void MFCAPut(void *ls, uint32_t ea, uint32_t size);
//
// DMA functionality
//
// tagId is a value between 0 and 31 that can be used to group
// dma requests together
void DmaGetSAFE(void *ls, uint32_t ea, uint32_t size, uint32_t tagId);
void DmaGetUNSAFE(void *ls, uint32_t ea, uint32_t size, uint32_t tagId);
void DmaPut(uint32_t ea, void *ls, uint32_t size, uint32_t tagId);
void DmaSmallPut(uint32_t ea, void *ls, uint32_t size, uint32_t tagId);
void DmaGetList(void *ls, DMAList *pLS_List, uint32_t sizeList, uint32_t tagId);
void DmaPutList(void *ls, DMAList* pLS_List, uint32_t sizeList, uint32_t tagId);
inline int DmaDone(uint32_t dmaTagMask, bool bBlocking = true);
// DmaSync
// All earlier store instructions are forced to complete
// before proceeding. This function ensures that all stores to
// to local storage are visible to the MFC or PPU.
inline void DmaSync()
{
__asm("dsync");
}
//
// Mailbox functions - see SpuMgr_ppu.h for a descrition of mailboxes
//
int WriteMailbox(uint32_t val, bool bBlocking = true);
int WriteIntrMailbox(uint32_t val, bool bBlocking = true);
int WriteMailboxChannel(uint32_t val, uint32_t channel, bool bBlocking /* = true */);
int ReadMailbox(uint32_t *pVal, bool bBlocking = true);
bool Lock();
void Unlock();
bool MemcpyLock();
void MemcpyUnlock();
// Decrementer access, for time stamps
inline uint32_t ReadDecr(void);
// mem mgr
void *Malloc( uint32_t size )
{
m_mallocCount++;
void *ptr = malloc( size );
DEBUG_ASSERT( ptr );
return ptr;
}
void *MemAlignUNSAFE(uint32_t boundary, uint32_t size )
{
m_mallocCount++;
void *ptr = memalign( boundary, size );
return ptr;
}
void *MemAlign( uint32_t boundary, uint32_t size )
{
void *ptr = MemAlignUNSAFE(boundary, size);
DEBUG_ERROR( ptr );
return ptr;
}
void Free( void *pData )
{
m_mallocCount--;
free( pData );
}
uint32_t GetMallocCount()
{
return m_mallocCount;
}
// counters to help us keep track of how much data we are moving
inline void ResetBytesTransferred()
{
m_bytesRequested = 0;
m_bytesTransferred = 0;
m_numDMATransfers = 0;
}
// Private data and member functions
void _DmaGet(void *ls, uint32_t ea, uint32_t size, uint32_t tagId);
uint32_t m_lock[32] __attribute__ ((aligned(128)));
uint32_t m_lockEA;
uint32_t m_memcpyLock[32] __attribute__ ((aligned(128)));
uint32_t m_memcpyLockTest;// __attribute__ ((aligned(128)));
uint32_t m_memcpyLockEA;
uint32_t m_bytesRequested;
uint32_t m_bytesTransferred;
uint32_t m_numDMATransfers;
uint32_t m_mallocCount;
uint8_t m_MFCACacheLine[128] __attribute__ ((aligned(128)));
};
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline void SpuMgr::MFCAGet(void *ls, uint32_t ea, uint32_t size)
{
// get start of cache line
uint32_t eaAligned = SPUMGR_ALIGN_DOWN(ea, 0x80);
// get offset to given ea
uint32_t eaOffset = ea - eaAligned;
// check size to read
DEBUG_ASSERT(size + eaOffset <= 0x80);
// read cache line
spu_mfcdma64(&m_MFCACacheLine[0], 0, eaAligned, 128, 0, MFC_GETLLAR_CMD);
// wait for completion - this is a blocking read
spu_readch(MFC_RdAtomicStat);
// copy out data
memcpy(ls, &m_MFCACacheLine[eaOffset], size);
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline void SpuMgr::MFCAPut(void *ls, uint32_t ea, uint32_t size)
{
// get start of cache line
uint32_t eaAligned = SPUMGR_ALIGN_DOWN(ea, 0x80);
// get offset to given ea
uint32_t eaOffset = ea - eaAligned;
// check size to write
DEBUG_ASSERT(size + eaOffset <= 0x80);
// atmoic update - read cache line and reserve it, update it,
// conditionally write it back until write succeeds
// if write succeeds then spu_readch(MFC_RdAtomicStat) returns 0
do
{
// read cache line
spu_mfcdma64(&m_MFCACacheLine[0], 0, eaAligned, 128, 0, MFC_GETLLAR_CMD);
// wait for completion - this is a blocking read
spu_readch(MFC_RdAtomicStat);
spu_dsync();
// update cache line
memcpy(&m_MFCACacheLine[eaOffset], ls, size);
// dsync to make sure it's commited to LS
spu_dsync();
// write it back
spu_mfcdma64(&m_MFCACacheLine[0], 0, eaAligned, 128, 0, MFC_PUTLLC_CMD);
} while (__builtin_expect(spu_readch(MFC_RdAtomicStat), 0));
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline int SpuMgr::DmaDone(uint32_t dmaTagMask, bool bBlocking /*=true*/)
{
// From Cell Broadband Engine Architecture V1.0 Chapter 9.3.1 "Procedures for Determining the Status of Tag Groups"
//
// For polling for the completion of an MFC command or for the completion of a group of MFC commands, the
// basic procedure is as follows:
// 1. Clear any pending tag status update requests by:
// • Writing a ‘0’ to the MFC Write Tag Status Update Request Channel (see page 116)
// • Reading the channel count associated with the MFC Write Tag Status Update Request Channel (see
// page 116), until a value of ‘1’ is returned
// • Reading the MFC Read Tag-Group Status Channel (see page 117) and discarding the tag status
// data.
// 2. Enable the tag groups of interest by writing the MFC Write Tag-Group Query Mask Channel (see page
// 114) with the appropriate mask data (only needed if a new tag-group mask is required).
// 3. Request an immediate tag status update by writing the MFC Write Tag Status Update Request Channel
// (see page 116) with a value of ‘0’.
// 4. Perform a read of the MFC Read Tag-Group Status Channel (see page 117). The data returned is the
// current status of each tag group with the tag-group mask applied.
// 5. Repeat steps 3 and 4 until the tag group or the tag groups of interest are complete.
//
// Note
// MFC Write Tag Status Update Request Channel = MFC_WrTagUpdate
// MFC Read Tag-Group Status Channel = MFC_RdTagStat
// MFC Write Tag-Group Query Mask Channel = MFC_WrTagMask
// Here we go...
// 1. Clear any pending tag status update requests
spu_writech(MFC_WrTagUpdate, 0);
do {} while (spu_readchcnt(MFC_WrTagUpdate) == 0);
spu_readch(MFC_RdTagStat);
// 2. Enable the tag groups of interest
spu_writech(MFC_WrTagMask, dmaTagMask);
uint32_t dmaDone = 0;
do
{
// 3. Request an immediate tag status update
spu_writech(MFC_WrTagUpdate, 0);
// 4. Perform a read of the MFC Read Tag-Group Status Channel
uint32_t tagGroupStat = spu_readch(MFC_RdTagStat);
dmaDone = (tagGroupStat == dmaTagMask);
} while (bBlocking && !dmaDone);
return !dmaDone;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline int SpuMgr::WriteMailbox(uint32_t val, bool bBlocking /* = true */)
{
uint32_t mboxAvailable;
do
{
mboxAvailable = spu_readchcnt(SPU_WrOutMbox);
} while (bBlocking && !mboxAvailable);
if (mboxAvailable)
{
spu_writech(SPU_WrOutMbox, val);
}
return !mboxAvailable;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline int SpuMgr::WriteIntrMailbox(uint32_t val, bool bBlocking /* = true */)
{
uint32_t mboxAvailable;
do
{
mboxAvailable = spu_readchcnt(SPU_WrOutIntrMbox);
} while (bBlocking && !mboxAvailable);
if (mboxAvailable)
{
spu_writech(SPU_WrOutIntrMbox, val);
}
return !mboxAvailable;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline int SpuMgr::ReadMailbox(uint32_t *pVal, bool bBlocking /* = true */)
{
uint32_t mailAvailable;
do
{
mailAvailable = spu_readchcnt(SPU_RdInMbox);
} while (bBlocking && !mailAvailable);
if (mailAvailable)
*pVal = spu_readch(SPU_RdInMbox);
return !mailAvailable;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline uint32_t SpuMgr::ReadDecr(void)
{
return spu_readch(SPU_RdDec);
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline bool SpuMgr::Lock()
{
return cellAtomicCompareAndSwap32( m_lock, m_lockEA, 0, 1 ) == 0;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline void SpuMgr::Unlock()
{
cellAtomicCompareAndSwap32( m_lock, m_lockEA, 1, 0 );
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline bool SpuMgr::MemcpyLock()
{
return cellAtomicCompareAndSwap32( m_memcpyLock, m_memcpyLockEA, 0, 1 ) == 0;
}
//--------------------------------------------------------------------------------------------------
//
//--------------------------------------------------------------------------------------------------
inline void SpuMgr::MemcpyUnlock()
{
cellAtomicCompareAndSwap32( m_memcpyLock, m_memcpyLockEA, 1, 0 );
}
//--------------------------------------------------------------------------------------------------
// Externs
//--------------------------------------------------------------------------------------------------
extern SpuMgr gSpuMgr;
#endif // INCLUDED_SPUMGR_SPU_H
+32
View File
@@ -0,0 +1,32 @@
//================ Copyright (c) 1996-2009 Valve Corporation. All Rights Reserved. =================
#include "cgutils.h"
#include "tier0/dbg.h"
struct DatatypeRec_t
{
CGtype type;
CGparameterclass parameterClass;
};
static DatatypeRec_t s_datatypeClassname[] = {
#define CG_DATATYPE_MACRO(name, compiler_name, enum_name, base_enum, nrows, ncols,classname) \
{ enum_name, classname },
#include <Cg/cg_datatypes.h>
#undef CG_DATATYPE_MACRO
};
CGparameterclass vcgGetTypeClass( CGtype type )
{
if( type <= CG_TYPE_START_ENUM || type > CG_TYPE_START_ENUM + sizeof( s_datatypeClassname ) / sizeof( s_datatypeClassname[0] ) )
{
return CG_PARAMETERCLASS_UNKNOWN;
}
else
{
DatatypeRec_t & rec = s_datatypeClassname[type - CG_TYPE_START_ENUM - 1];
Assert( rec.type == type );
return rec.parameterClass;
}
}
View File
Whitespace-only changes.
File diff suppressed because it is too large. Load diff
+565
View File
@@ -0,0 +1,565 @@
//================ Copyright (c) 1996-2009 Valve Corporation. All Rights Reserved. =================
//
// LibGcm implementation of DX
//
//==================================================================================================
#ifndef DXABSTRACT_H
#define DXABSTRACT_H
#include "tier0/platform.h"
#include "tier0/memalloc.h"
#include "utlvector.h"
#include <cell/gcm.h>
#include <cell/gcm/gcm_method_data.h>
#include <cell/gcm/gcm_methods.h>
#include <sysutil/sysutil_sysparam.h>
#include "gcmconfig.h"
#include "dxabstract_def.h"
#include "gcmtexture.h"
#include "gcmlabels.h"
#define GCM_ALLOW_TIMESTAMPS 1
#ifdef _CERT
#define Debugger() ((void)0)
#else
#define Debugger() DebuggerBreak()
#endif
#define PS3GCM_ARTIFICIAL_TEXTURE_HANDLE_INDEX_BACKBUFFER 0
#define PS3GCM_ARTIFICIAL_TEXTURE_HANDLE_INDEX_DEPTHBUFFER 1
//--------------------------------------------------------------------------------------------------
// Interfaces
//--------------------------------------------------------------------------------------------------
struct IDirect3DResource9 : public IUnknown
{
IDirect3DDevice9 *m_device; // parent device
D3DRESOURCETYPE m_restype;
DWORD SetPriority(DWORD PriorityNew);
};
// for the moment, a "D3D surface" is modeled as a GLM tex, a face, and a mip.
struct IDirect3DSurface9 : public IDirect3DResource9
{
// no Create method, these are filled in by the various create surface methods.
HRESULT LockRect(D3DLOCKED_RECT* pLockedRect,CONST RECT* pRect,DWORD Flags);
HRESULT UnlockRect();
HRESULT GetDesc(D3DSURFACE_DESC *pDesc);
// only invoke this on depth/stencil surfaces please...
// axed HRESULT ResetDepthStencilSurfaceSize( int Width, int Height );
D3DSURFACE_DESC m_desc; // Layout must be the same as IDirect3DBaseTexture9!
CPs3gcmTexture *m_tex;
int m_face;
int m_mip;
bool m_bOwnsTexture;
~IDirect3DSurface9() { if ( m_bOwnsTexture && m_tex ) m_tex->Release(); }
};
struct IDirect3DBaseTexture9 : public IDirect3DResource9 // "A Texture.."
{
D3DSURFACE_DESC m_descZero; // desc of top level.
CPs3gcmTexture *m_tex; // this object owns data
D3DRESOURCETYPE GetType();
DWORD GetLevelCount();
HRESULT GetLevelDesc(UINT Level,D3DSURFACE_DESC *pDesc);
~IDirect3DBaseTexture9() { if ( m_tex ) m_tex->Release(); }
};
struct IDirect3DTexture9 : public IDirect3DBaseTexture9 // "Texture 2D"
{
//CUtlVector< IDirect3DSurface9* > m_surfs;
IDirect3DSurface9 *m_surfZero; // surf of top level. YUK!!
HRESULT LockRect(UINT Level,D3DLOCKED_RECT* pLockedRect,CONST RECT* pRect,DWORD Flags);
HRESULT UnlockRect(UINT Level);
HRESULT GetSurfaceLevel(UINT Level,IDirect3DSurface9** ppSurfaceLevel);
~IDirect3DTexture9() { if ( m_surfZero ) m_surfZero->Release(); }
};
struct IDirect3DCubeTexture9 : public IDirect3DBaseTexture9 // "Texture Cube Map"
{
IDirect3DSurface9 *m_surfZero[6]; // surfs of top level. YUK!!
HRESULT GetCubeMapSurface(D3DCUBEMAP_FACES FaceType,UINT Level,IDirect3DSurface9** ppCubeMapSurface);
HRESULT GetLevelDesc(UINT Level,D3DSURFACE_DESC *pDesc);
~IDirect3DCubeTexture9() { for ( int j = 0; j < 6; ++ j ) if ( m_surfZero[j] ) m_surfZero[j]->Release(); }
};
struct IDirect3DVolumeTexture9 : public IDirect3DBaseTexture9 // "Texture 3D"
{
IDirect3DSurface9 *m_surfZero; // surf of top level. YUK!!
D3DVOLUME_DESC m_volDescZero; // volume desc top level
HRESULT LockBox(UINT Level,D3DLOCKED_BOX* pLockedVolume,CONST D3DBOX* pBox,DWORD Flags);
HRESULT UnlockBox(UINT Level);
HRESULT GetLevelDesc( UINT level, D3DVOLUME_DESC *pDesc );
~IDirect3DVolumeTexture9() { if ( m_surfZero ) m_surfZero->Release(); }
};
struct IDirect3D9 : public IUnknown
{
public:
UINT GetAdapterCount(); //cheese: returns 1
HRESULT GetDeviceCaps (UINT Adapter,D3DDEVTYPE DeviceType,D3DCAPS9* pCaps);
HRESULT GetAdapterIdentifier (UINT Adapter,DWORD Flags,D3DADAPTER_IDENTIFIER9* pIdentifier);
HRESULT CheckDeviceFormat (UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT AdapterFormat,DWORD Usage,D3DRESOURCETYPE RType,D3DFORMAT CheckFormat);
UINT GetAdapterModeCount (UINT Adapter,D3DFORMAT Format);
HRESULT EnumAdapterModes (UINT Adapter,D3DFORMAT Format,UINT Mode,D3DDISPLAYMODE* pMode);
HRESULT CheckDeviceType (UINT Adapter,D3DDEVTYPE DevType,D3DFORMAT AdapterFormat,D3DFORMAT BackBufferFormat,BOOL bWindowed);
HRESULT GetAdapterDisplayMode (UINT Adapter,D3DDISPLAYMODE* pMode);
HRESULT CheckDepthStencilMatch (UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT AdapterFormat,D3DFORMAT RenderTargetFormat,D3DFORMAT DepthStencilFormat);
HRESULT CheckDeviceMultiSampleType (UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT SurfaceFormat,BOOL Windowed,D3DMULTISAMPLE_TYPE MultiSampleType,DWORD* pQualityLevels);
HRESULT CreateDevice (UINT Adapter,D3DDEVTYPE DeviceType,VD3DHWND hFocusWindow,DWORD BehaviorFlags,D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DDevice9** ppReturnedDeviceInterface);
};
struct IDirect3DSwapChain9 : public IUnknown
{
};
struct IDirect3DQuery9 : public IUnknown
{
public:
D3DQUERYTYPE m_type; // D3DQUERYTYPE_OCCLUSION or D3DQUERYTYPE_EVENT
uint32 m_queryIdx;
enum Flags_t
{
kQueryValueMask = 0x0000FFFF, // Mask for query value index
kQueryFinished = 0x80000000, // Query is completed
kQueryUninitialized = 0xFFFFFFFF, // Query hasn't started
};
struct QueryGlobalStateOcclusion_t
{
enum { kMaxQueries = GCM_REPORT_QUERY_LAST + 1 - GCM_REPORT_QUERY_FIRST, kGcmQueryBase = GCM_REPORT_QUERY_FIRST };
CellGcmReportData volatile *m_Values[kMaxQueries];
uint32 m_queryIdx;
uint32 PrepareForQuery();
};
static QueryGlobalStateOcclusion_t s_GlobalStateOcclusion;
struct QueryGlobalStateFence_t
{
enum { kMaxQueries = GCM_LABEL_QUERY_LAST + 1 - GCM_LABEL_QUERY_FIRST, kGcmLabelBase = GCM_LABEL_QUERY_FIRST };
uint32 volatile *m_Values[kMaxQueries];
uint32 m_queryIdx;
uint32 PrepareForQuery();
};
static QueryGlobalStateFence_t s_GlobalStateFence;
HRESULT Issue(DWORD dwIssueFlags);
HRESULT GetData(void* pData,DWORD dwSize,DWORD dwGetDataFlags);
};
struct IDirect3DGcmBufferBase : public IUnknown
{
public:
CPs3gcmBuffer *m_pBuffer;
HRESULT Lock(UINT OffsetToLock,UINT SizeToLock,void** ppbData,DWORD Flags);
HRESULT Unlock();
~IDirect3DGcmBufferBase() { if ( m_pBuffer ) m_pBuffer->Release(); }
};
struct IDirect3DVertexBuffer9 : public IDirect3DGcmBufferBase
{
public:
D3DVERTEXBUFFER_DESC m_vtxDesc; // to satisfy GetDesc
};
struct IDirect3DIndexBuffer9 : public IDirect3DGcmBufferBase
{
public:
D3DINDEXBUFFER_DESC m_idxDesc; // to satisfy GetDesc
HRESULT GetDesc(D3DINDEXBUFFER_DESC *pDesc);
};
struct IDirect3DGcmProgramBase : public IUnknown
{
public:
CgBinaryProgram *m_pProgram;
inline CGprogram GetCgProgram() const { return reinterpret_cast< CGprogram >( m_pProgram ); }
inline void * GetProgramUCode() const { return (((char*)m_pProgram) + m_pProgram->ucode); }
~IDirect3DGcmProgramBase() { if ( m_pProgram ) free( m_pProgram ); }
};
// define this to find out how many times we reuse the same shader during a frame
//#define DEBUG_GCM_VERTEX_SHADER_USAGE
struct IDirect3DVertexShader9 : public IDirect3DGcmProgramBase
{
public:
VertexShader9Data_t m_data;
//uint32 m_nIoOffsetStart; // the start of subroutine (IO Offset on RSX) that sets this vertex program
~IDirect3DVertexShader9();
};
struct IDirect3DPixelShader9 : public CAlignedNewDelete< 16, IUnknown >
{
public:
PixelShader9Data_t m_data;
public:
//inline CgBinaryFragmentProgram *GetFragmentProgram() const { return (CgBinaryFragmentProgram *)(((char*)m_pProgram) + m_pProgram->program); }
//void ValidateAssumptions( const char * pShaderName );
IDirect3DPixelShader9( CgBinaryProgram* prog );
~IDirect3DPixelShader9();
#ifdef _DEBUG
CgBinaryProgram *m_pCgProg;
#endif
};
struct ID3DXMatrixStack : public IUnknown
{
public:
CUtlVector<D3DMATRIX> m_stack;
int m_stackTop; // top of stack is at the highest index, this is that index. push increases, pop decreases.
HRESULT Create( void );
D3DXMATRIX* GetTop();
void Push();
void Pop();
void LoadIdentity();
void LoadMatrix( const D3DXMATRIX *pMat );
void MultMatrix( const D3DXMATRIX *pMat );
void MultMatrixLocal( const D3DXMATRIX *pMat );
HRESULT ScaleLocal(FLOAT x, FLOAT y, FLOAT z);
// Left multiply the current matrix with the computed rotation
// matrix, counterclockwise about the given axis with the given angle.
// (rotation is about the local origin of the object)
HRESULT RotateAxisLocal(CONST D3DXVECTOR3* pV, FLOAT Angle);
// Left multiply the current matrix with the computed translation
// matrix. (transformation is about the local origin of the object)
HRESULT TranslateLocal(FLOAT x, FLOAT y, FLOAT z);
};
typedef ID3DXMatrixStack* LPD3DXMATRIXSTACK;
struct IDirect3DDevice9Params
{
UINT m_adapter;
D3DDEVTYPE m_deviceType;
VD3DHWND m_focusWindow;
DWORD m_behaviorFlags;
D3DPRESENT_PARAMETERS m_presentationParameters;
};
struct D3DIndexDesc
{
IDirect3DIndexBuffer9 *m_idxBuffer;
};
struct IDirect3DDevice9 : public IUnknown
{
// members
IDirect3DDevice9Params m_params; // mirror of the creation inputs
// D3D flavor stuff
IDirect3DSurface9 *m_rtSurfaces[16]; // current color RT (Render Target) surfaces. [0] is initially == m_defaultColorSurface
IDirect3DSurface9 *m_dsSurface; // current Depth Stencil Render Target surface. can be changed!
IDirect3DSurface9 *m_defaultColorSurface; // default color surface.
IDirect3DSurface9 *m_defaultDepthStencilSurface; // queried by GetDepthStencilSurface.
IDirect3DVertexDeclaration9 *m_vertDecl; // Set by SetVertexDeclaration...
//D3DStreamDesc *m_pVertexStreamSources; // Set by SetStreamSource..
D3DIndexDesc m_indices; // Set by SetIndices..
IDirect3DVertexShader9 *m_vertexShader; // Set by SetVertexShader...
IDirect3DPixelShader9 *m_pixelShader; // Set by SetPixelShader...
#ifdef _DEBUG
uint m_nDrawIndexedPrimitives;
#endif
enum AntiAliasingStatusEnum_t
{
AA_STATUS_NORMAL,
AA_STATUS_PREV_FRAME, // drawing into previous frame, aliased
AA_STATUS_DEFERRED // drawing into deferred queue
};
// this is used to draw UI into already-mlaa'd-surface (to avoid AA'ing the UI)
// when this is on, the default surface to draw should be previous flip surface
AntiAliasingStatusEnum_t m_nAntiAliasingStatus;
// is in logical zpass? logical zpass may have wider scope than spuGcm.zPass, because logical zpass does not abort for any reason. It begins and ends with API calls. Used to balance Perf Marker Push/Pop
bool m_isZPass; //
bool m_isDeferredDrawQueueSurfaceSet;
// methods
// Create call invoked from IDirect3D9
HRESULT Create( IDirect3DDevice9Params *params );
//
// Basics
//
HRESULT Reset(D3DPRESENT_PARAMETERS* pPresentationParameters);
HRESULT SetViewport(CONST D3DVIEWPORT9* pViewport);
HRESULT BeginScene();
HRESULT Clear(DWORD Count,CONST D3DRECT* pRects,DWORD Flags,D3DCOLOR Color,float Z,DWORD Stencil);
HRESULT EndScene();
HRESULT Present(CONST RECT* pSourceRect,CONST RECT* pDestRect,VD3DHWND hDestWindowOverride,CONST RGNDATA* pDirtyRegion);
// textures
HRESULT CreateTexture(UINT Width,UINT Height,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DTexture9** ppTexture,VD3DHANDLE* pSharedHandle);
HRESULT CreateCubeTexture(UINT EdgeLength,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DCubeTexture9** ppCubeTexture,VD3DHANDLE* pSharedHandle);
HRESULT CreateVolumeTexture(UINT Width,UINT Height,UINT Depth,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DVolumeTexture9** ppVolumeTexture,VD3DHANDLE* pSharedHandle);
HRESULT SetTexture(DWORD Stage,IDirect3DBaseTexture9* pTexture);
HRESULT GetTexture(DWORD Stage,IDirect3DBaseTexture9** ppTexture);
// render targets, color and depthstencil, surfaces, blit
HRESULT CreateRenderTarget(UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Lockable,IDirect3DSurface9** ppSurface,VD3DHANDLE* pSharedHandle);
HRESULT SetRenderTarget(DWORD RenderTargetIndex,IDirect3DSurface9* pRenderTarget);
HRESULT GetRenderTarget(DWORD RenderTargetIndex,IDirect3DSurface9** ppRenderTarget);
HRESULT CreateOffscreenPlainSurface(UINT Width,UINT Height,D3DFORMAT Format,D3DPOOL Pool,IDirect3DSurface9** ppSurface,VD3DHANDLE* pSharedHandle);
HRESULT CreateDepthStencilSurface(UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Discard,IDirect3DSurface9** ppSurface,VD3DHANDLE* pSharedHandle);
HRESULT SetDepthStencilSurface(IDirect3DSurface9* pNewZStencil);
HRESULT GetDepthStencilSurface(IDirect3DSurface9** ppZStencilSurface);
HRESULT GetRenderTargetData(IDirect3DSurface9* pRenderTarget,IDirect3DSurface9* pDestSurface); // ? is anyone using this ?
HRESULT GetFrontBufferData(UINT iSwapChain,IDirect3DSurface9* pDestSurface);
HRESULT StretchRect(IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestSurface,CONST RECT* pDestRect,D3DTEXTUREFILTERTYPE Filter);
// pixel shaders
HRESULT CreatePixelShader(CONST DWORD* pFunction,IDirect3DPixelShader9** ppShader, const char *pShaderName = NULL, char *debugLabel = NULL);
HRESULT SetPixelShader(IDirect3DPixelShader9* pShader);
HRESULT SetPixelShaderConstantF(UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount);
HRESULT SetPixelShaderConstantB(UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount);
HRESULT SetPixelShaderConstantI(UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount);
// vertex shaders
HRESULT CreateVertexShader(CONST DWORD* pFunction,IDirect3DVertexShader9** ppShader, char *debugLabel = NULL);
HRESULT SetVertexShader(IDirect3DVertexShader9* pShader);
HRESULT SetVertexShaderConstantF(UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount);
HRESULT SetVertexShaderConstantB(UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount);
HRESULT SetVertexShaderConstantI(UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount);
// vertex buffers
HRESULT CreateVertexDeclaration(CONST D3DVERTEXELEMENT9* pVertexElements,IDirect3DVertexDeclaration9** ppDecl);
HRESULT SetVertexDeclaration(IDirect3DVertexDeclaration9* pDecl);
HRESULT SetFVF(DWORD FVF); // we might not be using these ?
HRESULT GetFVF(DWORD* pFVF);
HRESULT CreateVertexBuffer(UINT Length,DWORD Usage,DWORD FVF,D3DPOOL Pool,IDirect3DVertexBuffer9** ppVertexBuffer,VD3DHANDLE* pSharedHandle);
HRESULT SetStreamSource(UINT StreamNumber,IDirect3DVertexBuffer9* pStreamData,UINT OffsetInBytes,UINT Stride);
HRESULT SetRawHardwareDataStreams( IDirect3DVertexBuffer9** ppRawHardwareDataStreams );
// index buffers
HRESULT CreateIndexBuffer(UINT Length,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DIndexBuffer9** ppIndexBuffer,VD3DHANDLE* pSharedHandle);
HRESULT SetIndices(IDirect3DIndexBuffer9* pIndexData);
// State management.
HRESULT SetRenderState(D3DRENDERSTATETYPE State,DWORD Value);
HRESULT SetSamplerState(DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD Value);
// Draw.
HRESULT ValidateDrawPrimitiveStreams( D3DPRIMITIVETYPE Type, UINT baseVertexIndex, UINT MinVertexIndex, UINT NumVertices, UINT startIndex, UINT primCount ); // validate streams
HRESULT DrawPrimitive(D3DPRIMITIVETYPE PrimitiveType,UINT StartVertex,UINT PrimitiveCount);
void DrawPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType,UINT PrimitiveCount,CONST void *pVertexStreamZeroData,UINT VertexStreamZeroStride);
HRESULT DrawIndexedPrimitive(D3DPRIMITIVETYPE PrimitiveType,INT BaseVertexIndex,UINT MinVertexIndex,UINT NumVertices,UINT startIndex,UINT primCount);
HRESULT DrawIndexedPrimitiveUP(D3DPRIMITIVETYPE PrimitiveType,UINT MinVertexIndex,UINT NumVertices,UINT PrimitiveCount,CONST void* pIndexData,D3DFORMAT IndexDataFormat,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride);
// misc
BOOL ShowCursor(BOOL bShow);
HRESULT ValidateDevice(DWORD* pNumPasses);
HRESULT SetMaterial(CONST D3DMATERIAL9* pMaterial);
HRESULT LightEnable(DWORD Index,BOOL Enable);
HRESULT SetScissorRect(CONST RECT* pRect);
HRESULT CreateQuery(D3DQUERYTYPE Type,IDirect3DQuery9** ppQuery);
HRESULT GetDeviceCaps(D3DCAPS9* pCaps);
HRESULT TestCooperativeLevel();
HRESULT EvictManagedResources();
HRESULT SetLight(DWORD Index,CONST D3DLIGHT9*);
void SetGammaRamp(UINT iSwapChain,DWORD Flags,CONST D3DGAMMARAMP* pRamp);
// Talk to JasonM about this one. It's tricky in GL.
HRESULT SetClipPlane(DWORD Index,CONST float* pPlane);
ULONG __stdcall Release();
// Xbox ZPass analogue
void BeginZPass( DWORD Flags );
void SetPredication( DWORD PredicationMask );
HRESULT EndZPass();
// void ReloadZcullMemory( int nStencilRef );
void StartRenderingIntoPreviousFramebuffer();
void AntiAliasingHint( int nHint );
//
//
// **** FIXED FUNCTION STUFF - None of this stuff needs support in GL.
//
//
HRESULT SetTransform(D3DTRANSFORMSTATETYPE State,CONST D3DMATRIX* pMatrix);
HRESULT SetTextureStageState(DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD Value);
#ifdef _PS3
void GetGPUMemoryStats( GPUMemoryStats &stats ) { return ::GetGPUMemoryStats( stats ); }
void FlushVertexCache();
void FlushTextureCache();
// Allocate storage for a texture's bits (if D3DUSAGE_TEXTURE_NOD3DMEMORY was used to defer allocation on creation)
bool AllocateTextureStorage( IDirect3DBaseTexture9 *pTexture );
protected:
// Flushing changes to GL
void SetVertexStreamSource( uint i, IDirect3DVertexBuffer9* pStreamData,UINT OffsetInBytes,UINT Stride );
void Ps3Helper_ResetSurfaceToKnownDefaultState();
void Ps3Helper_UpdateSurface( int idx );
friend void DxDeviceForceUpdateRenderTarget( );
#endif
};
struct ID3DXInclude
{
virtual HRESULT Open(D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) = 0;
virtual HRESULT Close(LPCVOID pData) = 0;
};
typedef ID3DXInclude* LPD3DXINCLUDE;
struct ID3DXBuffer : public IUnknown
{
void* GetBufferPointer();
DWORD GetBufferSize();
};
typedef ID3DXBuffer* LPD3DXBUFFER;
class ID3DXConstantTable : public IUnknown
{
};
typedef ID3DXConstantTable* LPD3DXCONSTANTTABLE;
// ------------------------------------------------------------------------------------------------------------------------------ //
// D3DX stuff.
// ------------------------------------------------------------------------------------------------------------------------------ //
const char* D3DXGetPixelShaderProfile( IDirect3DDevice9 *pDevice );
D3DXMATRIX* D3DXMatrixMultiply( D3DXMATRIX *pOut, CONST D3DXMATRIX *pM1, CONST D3DXMATRIX *pM2 );
D3DXVECTOR3* D3DXVec3TransformCoord( D3DXVECTOR3 *pOut, CONST D3DXVECTOR3 *pV, CONST D3DXMATRIX *pM );
HRESULT D3DXCreateMatrixStack( DWORD Flags, LPD3DXMATRIXSTACK* ppStack);
void D3DXMatrixIdentity( D3DXMATRIX * );
D3DXINLINE D3DXVECTOR3* D3DXVec3Subtract( D3DXVECTOR3 *pOut, CONST D3DXVECTOR3 *pV1, CONST D3DXVECTOR3 *pV2 )
{
pOut->x = pV1->x - pV2->x;
pOut->y = pV1->y - pV2->y;
pOut->z = pV1->z - pV2->z;
return pOut;
}
D3DXINLINE D3DXVECTOR3* D3DXVec3Cross( D3DXVECTOR3 *pOut, CONST D3DXVECTOR3 *pV1, CONST D3DXVECTOR3 *pV2 )
{
D3DXVECTOR3 v;
v.x = pV1->y * pV2->z - pV1->z * pV2->y;
v.y = pV1->z * pV2->x - pV1->x * pV2->z;
v.z = pV1->x * pV2->y - pV1->y * pV2->x;
*pOut = v;
return pOut;
}
D3DXINLINE FLOAT D3DXVec3Dot( CONST D3DXVECTOR3 *pV1, CONST D3DXVECTOR3 *pV2 )
{
return pV1->x * pV2->x + pV1->y * pV2->y + pV1->z * pV2->z;
}
D3DXMATRIX* D3DXMatrixInverse( D3DXMATRIX *pOut, FLOAT *pDeterminant, CONST D3DXMATRIX *pM );
D3DXMATRIX* D3DXMatrixTranspose( D3DXMATRIX *pOut, CONST D3DXMATRIX *pM );
D3DXPLANE* D3DXPlaneNormalize( D3DXPLANE *pOut, CONST D3DXPLANE *pP);
D3DXVECTOR4* D3DXVec4Transform( D3DXVECTOR4 *pOut, CONST D3DXVECTOR4 *pV, CONST D3DXMATRIX *pM );
D3DXVECTOR4* D3DXVec4Normalize( D3DXVECTOR4 *pOut, CONST D3DXVECTOR4 *pV );
D3DXMATRIX* D3DXMatrixTranslation( D3DXMATRIX *pOut, FLOAT x, FLOAT y, FLOAT z );
// Build an ortho projection matrix. (right-handed)
D3DXMATRIX* D3DXMatrixOrthoOffCenterRH( D3DXMATRIX *pOut, FLOAT l, FLOAT r, FLOAT b, FLOAT t, FLOAT zn,FLOAT zf );
D3DXMATRIX* D3DXMatrixPerspectiveRH( D3DXMATRIX *pOut, FLOAT w, FLOAT h, FLOAT zn, FLOAT zf );
D3DXMATRIX* D3DXMatrixPerspectiveOffCenterRH( D3DXMATRIX *pOut, FLOAT l, FLOAT r, FLOAT b, FLOAT t, FLOAT zn, FLOAT zf );
// Transform a plane by a matrix. The vector (a,b,c) must be normal.
// M should be the inverse transpose of the transformation desired.
D3DXPLANE* D3DXPlaneTransform( D3DXPLANE *pOut, CONST D3DXPLANE *pP, CONST D3DXMATRIX *pM );
IDirect3D9 *Direct3DCreate9(UINT SDKVersion);
void D3DPERF_SetOptions( DWORD dwOptions );
HRESULT D3DXCompileShader(
LPCSTR pSrcData,
UINT SrcDataLen,
CONST D3DXMACRO* pDefines,
LPD3DXINCLUDE pInclude,
LPCSTR pFunctionName,
LPCSTR pProfile,
DWORD Flags,
LPD3DXBUFFER* ppShader,
LPD3DXBUFFER* ppErrorMsgs,
LPD3DXCONSTANTTABLE* ppConstantTable);
// fake D3D usage constant for SRGB tex creation
#define D3DUSAGE_TEXTURE_SRGB (0x80000000L)
// fake D3D usage constant for deferred tex bits allocation
#define D3DUSAGE_TEXTURE_NOD3DMEMORY (0x40000000L)
extern bool g_bDxMicroProfile;
#endif // DXABSTRACT_H
File diff suppressed because it is too large. Load diff
+611
View File
@@ -0,0 +1,611 @@
//========= Copyright © Valve Corporation, All rights reserved. ====//
#include "tier0/platform.h"
#ifdef _PS3
#include "dxabstract.h"
#include <sys/memory.h>
#include "ps3/spugcm_shared.h"
#include "fpcpatcher_spu.h"
#include "cg/cg.h"
#include "cg/cgBinary.h"
#include "vjobs_interface.h"
#include "tier0/hardware_clock_fast.h"
#include "vjobs/fpcpatch_shared.h"
#include "vjobs/root.h"
#include "ps3/vjobutils.h"
#include "tier0/microprofiler.h"
#include "ps3/ps3_gcm_config.h"
#include "spugcm.h"
enum
{
PROFILE_SCE_VP_RSX = 7003,
PROFILE_SCE_FP_RSX = 7004
};
#define GCM_MUST_SUCCEED( FUNC, ... ) do { int nError = FUNC(__VA_ARGS__); if( nError != CELL_OK ) { Error( "Error 0x%X in " #FUNC ", %s:%d\n", nError, __FILE__, __LINE__ ); } } while( 0 )
DEFINE_LOGGING_CHANNEL_NO_TAGS( LOG_VJOBS, "VJOBS" );
CFragmentProgramConstantPatcher_SPU g_pixelShaderPatcher; // Patches pixel shader constants
CMicroProfiler g_mpBindProgram, g_mpFpcPatch2;
// debug only
CFragmentProgramConstantPatcher_SPU::CFragmentProgramConstantPatcher_SPU()
{
m_pBuffer = m_pBufferEnd = NULL;
m_nIoOffsetDelta = 0; // m_pBuffer + m_nIoOffsetDelta == IO offset usable by RSX
m_pPutFragmentProgram = NULL;
#ifdef DEBUG_FPC_PATCHER
m_bSync = ( CommandLine()->FindParm( "-fpcpsync" ) != 0 );
#endif
}
void CFragmentProgramConstantPatcher_SPU::InitLocal( void *pBuffer, uint nSize )
{
m_nFpcPatchCounter = 0;
m_nFpcPatchCounterOfLastSyncJob = 0;
//cellGcmSetDebugOutputLevel( CELL_GCM_DEBUG_LEVEL2 );
const uint nOverfetchGuard = 1024; // RSX front end prefetches up to 4k, but 1k is ( should be ) enough to avoid overfetch crashes
const uint nStateBufferQwords = 1 << 12; // make space for at least 8 full batches of constants...
uint nPatchStateBufferSize = ( sizeof( job_fpcpatch::FpcPatchState_t ) + sizeof( fltx4 ) * nStateBufferQwords );
uint32 nBufferIoOffset;
m_bFpcPatchOnPpu = ( 0 != CommandLine()->FindParm( "-fpcpatchonppu" ) );
#ifdef DEBUG_FPC_PATCHER
m_bTestAlwaysStateSync = ( 0 != CommandLine()->FindParm( "-fpcpstatesync" ) );
#endif
m_bEnableSPU = true;
m_nFpcPatchSyncMask = 0;
// use this passed buffer (probably from local memory) for the patched stuff
m_pBuffer = ( uint32* ) pBuffer;
m_pBufferEnd = ( uint32* ) ( uintp( pBuffer ) + nSize );
m_nBufferLocation = CELL_GCM_LOCATION_LOCAL;
m_isBufferPassedIn = true;
m_state.Init( ( job_fpcpatch::FpcPatchState_t* )MemAlloc_AllocAligned( nPatchStateBufferSize, 128 ), nStateBufferQwords );
GCM_MUST_SUCCEED( cellGcmAddressToOffset, m_pBuffer, &nBufferIoOffset );
#ifdef DBGFLAG_ASSERT
uint32 nBufferIoOffsetCheck;
GCM_MUST_SUCCEED( cellGcmAddressToOffset, m_pBuffer, &nBufferIoOffsetCheck );
Assert( nBufferIoOffsetCheck == nBufferIoOffset );
Assert( !( nBufferIoOffsetCheck & 0x7F ) );
for( uint nOffset = 0; nOffset < nSize; nOffset += 128 )
{
GCM_MUST_SUCCEED( cellGcmAddressToOffset, ((uint8*)m_pBuffer) + nOffset, &nBufferIoOffsetCheck );
Assert( nBufferIoOffsetCheck == nBufferIoOffset + nOffset );
}
#endif
m_nIoOffsetDelta = nBufferIoOffset - uintp( m_pBuffer );
#ifdef DEBUG_FPC_PATCHER
m_pSyncState = ( fltx4* ) MemAlloc_AllocAligned( sizeof( fltx4 ) * job_fpcpatch::MAX_VIRTUAL_CONST_COUNT, 16 );
V_memset( m_pSyncState, 0xCD, sizeof( fltx4 ) * job_fpcpatch::MAX_VIRTUAL_CONST_COUNT );
V_memset( m_state.m_pSharedState->m_reg, 0xCD, sizeof( fltx4 ) * job_fpcpatch::MAX_VIRTUAL_CONST_COUNT );
#endif
ResetPut();
//cellGcmSetDebugOutputLevel( CELL_GCM_DEBUG_LEVEL0 );
}
void CFragmentProgramConstantPatcher_SPU::Shutdown()
{
}
void CFragmentProgramConstantPatcher_SPU::ResetPut()
{
m_pPutFragmentProgram = m_pBufferEnd; // reserved word for the count of constants to set
}
CFragmentProgramConstantPatcher_SPU::~CFragmentProgramConstantPatcher_SPU()
{
if( m_isBufferPassedIn )
{
MemAlloc_FreeAligned( m_state.m_pSharedState );
}
else
{
sys_memory_free( ( sys_addr_t )m_pBuffer );
}
#ifdef DEBUG_FPC_PATCHER
MemAlloc_FreeAligned( m_pSyncState );
#endif
}
void CFragmentProgramConstantPatcher_SPU::BeginScene()
{
m_nFpcPatchCounterAtBeginScene = m_nFpcPatchCounter;
// we shouldn't have in-flight SPU jobs by now.. should we?
Assert( uint( g_spuGcmShared.m_nFpcpStartRangesAfterLastSync - m_state.m_pSharedState->m_nStartRanges ) <= m_state.m_pSharedState->m_nBufferMask + 1 );
}
void CFragmentProgramConstantPatcher_SPU::EndScene()
{
#if ENABLE_MICRO_PROFILER > 0
uint nPatchCounter = m_nFpcPatchCounter - m_nFpcPatchCounterAtBeginScene;
extern bool g_bDxMicroProfile;
if( g_bDxMicroProfile && nPatchCounter )
{
g_mpBindProgram.PrintAndReset( "[BindProgram] " );
g_mpFpcPatch2 .PrintAndReset( "[FpcPatch2] " );
}
#endif
}
job_fpcpatch2::FpHeader_t g_nullFpHeader = {0,0,0,0};
// semantics should match cgGLSetFragmentRegisterBlock()
void CFragmentProgramConstantPatcher_SPU::SetFragmentRegisterBlock( uint nStartRegister, uint nVector4fCount, const float * pConstantData )
{
#ifndef _CERT
if ( nStartRegister >= job_fpcpatch::MAX_VIRTUAL_CONST_COUNT || nStartRegister + nVector4fCount > job_fpcpatch::MAX_VIRTUAL_CONST_COUNT )
Error( "Invalid Fragment Register Block Range %u..%u\n", nStartRegister, nStartRegister + nVector4fCount );
#endif
#ifdef DEBUG_FPC_PATCHER
if( m_bSync )
{
fltx4 reg[job_fpcpatch::MAX_VIRTUAL_CONST_COUNT];
m_state.GetSyncState( reg );
Assert( !V_memcmp( m_pSyncState, reg, sizeof( fltx4 ) * job_fpcpatch::MAX_VIRTUAL_CONST_COUNT ) );
}
uint nEnd = m_state.m_nEndOfJournalIdx;
#endif
// we have 4 DMA elements ( 2..6 ) to fit the constant buffer; the 1st element may have to be as small as 16 bytes.
// this leaves the max constant buffer size 4 * 16kb + 16 bytes
const uint nMaxUploadRangeBeforeStateSync = ( 32 * 1024 ) / sizeof( fltx4 );
uint numUploadRangeQwords = m_state.m_nEndOfJournalIdx - g_spuGcmShared.m_nFpcpStartRangesAfterLastSync;
///////////////////////////////////////////////////////////////////////////
//
// PREPATCH MUST BE DONE IN (CTXFLUSH OR) DRAW JOB FROM NOW ON!!! g_spuGcmShared.m_nFpcpStartRangesAfterLastSync IS SYNCHRONOUS AND CORRECT THERE
//
//////////////////////////////////////////////////////////////////////////
/*
bool bPrePatch = nVector4fCount + 1 + numUploadRangeQwords > nMaxUploadRangeBeforeStateSync;
if( bPrePatch )
{
// force state sync now
if( g_spuGcmShared.m_enableStallWarnings )
{
Warning( "PPU-SPU Wait for RSX. SetFragmentRegisterBlock: Forced to set state on PPU, %u vectors, %u qwords in history. This is slow fallback path.\n", nVector4fCount, numUploadRangeQwords );
}
FpcPatch2( &g_nullFpHeader, sizeof( g_nullFpHeader ), NULL, NULL );
}
*/
if( uint nAttempts = m_state.AddRange( nStartRegister, nVector4fCount, pConstantData ) )
{
if( g_spuGcmShared.m_enableStallWarnings )
{
Warning( "PPU-SPU Wait for RSX. SetFragmentRegisterBlock: Stall, %d spins. Waiting for more memory; %d qwords, %d jobs buffered up\n", nAttempts, m_state.m_nEndOfJournalIdx - m_state.m_pSharedState->m_nStartRanges, g_spuGcmShared.m_nFpcPatchCounter - m_state.m_pSharedState->m_nThisStatePatchCounter );
}
}
#ifdef DEBUG_FPC_PATCHER
if( m_bTestAlwaysStateSync && !bPrePatch )
{
FpcPatch2( &g_nullFpHeader, sizeof( g_nullFpHeader ), NULL, NULL );
}
V_memcpy( m_pSyncState + nStartRegister, pConstantData, nVector4fCount * sizeof( fltx4 ) );
if( m_bSync )
{
fltx4 reg[job_fpcpatch::MAX_VIRTUAL_CONST_COUNT];
m_state.GetSyncState( reg );
Assert( !V_memcmp( m_pSyncState, reg, sizeof( fltx4 ) * job_fpcpatch::MAX_VIRTUAL_CONST_COUNT ) );
}
#endif
}
//volatile int g_nDebugStage = 0;
//
// Match the semantics of cgGLBindProgram()
// There are 2 formats of fragment shaders, see SDK docs "2. 2 Cg Compiler Options" and
// in Cg Compiler User's Guide:
// "7. 2 NV Binary Shader Format (VPO and FPO)"
// "7. 4 Cgb File Format Specification"
//
void CFragmentProgramConstantPatcher_SPU::BindProgram( const struct IDirect3DPixelShader9 * psh )
{
MICRO_PROFILE( g_mpBindProgram );
const job_fpcpatch2::FpHeader_t * prog = psh->m_data.m_eaFp;
uint32 nFragmentProgramOffset = uintp( m_pPutFragmentProgram ) + m_nIoOffsetDelta;
g_spuGcmShared.m_fpcpRing.UnlockRsxMemoryForSpu();
m_pPutFragmentProgram = ( uint32* )g_spuGcmShared.m_fpcpRing.LockRsxMemoryForSpu( &g_spuGcmShared.m_fpcpJobChain, prog->m_nUcodeSize );
nFragmentProgramOffset = uintp( m_pPutFragmentProgram ) - uintp( g_ps3gcmGlobalState.m_pLocalBaseAddress );
if( !IsCert() && nFragmentProgramOffset >= g_ps3gcmGlobalState.m_nLocalSize )
{
Error( "Fragment program Ucode buffer offset 0x%X is at unexpected address not in local memory\n", nFragmentProgramOffset );
}
if ( !IsCert() && ( m_pPutFragmentProgram < m_pBuffer || m_pPutFragmentProgram >= m_pBufferEnd ) )
{
Error( "Fragment Program UCode buffer overflow.\n" );
}
#ifdef DEBUG_FPC_PATCHER
if( m_bSync )
{
fltx4 reg[job_fpcpatch::MAX_VIRTUAL_CONST_COUNT];
m_state.GetSyncState( reg );
Assert( !V_memcmp( m_pSyncState, reg, sizeof( fltx4 ) * job_fpcpatch::MAX_VIRTUAL_CONST_COUNT ) );
}
#endif
uint nTexControls = prog->m_nTexControls;
// set jump to self
GCM_CTX_RESERVE( 7 + 2 * nTexControls );
uint32 * pJts = NULL;
FpcPatch2( prog, psh->m_data.m_nFpDmaSize, m_pPutFragmentProgram, pJts );
CELL_GCM_METHOD_SET_SHADER_CONTROL( GCM_CTX->current, prog->m_nShaderControl0 ); // +2
CELL_GCM_METHOD_SET_SHADER_PROGRAM( GCM_CTX->current, m_nBufferLocation + 1, ( nFragmentProgramOffset & 0x1fffffff ) ); // +2
CELL_GCM_METHOD_SET_VERTEX_ATTRIB_OUTPUT_MASK( GCM_CTX->current, psh->m_data.m_attributeInputMask | 0x20 ); // +2
V_memcpy( GCM_CTX->current, prog->GetTexControls(), nTexControls * sizeof( uint32 ) * 2 );
GCM_CTX->current += 2 * nTexControls;
#ifdef DEBUG_FPC_PATCHER
if( m_bSync )
{
g_ps3gcmGlobalState.CmdBufferFlush( CPs3gcmGlobalState::kFlushForcefully );
while ( *( volatile uint32* )pJts )
{
sys_timer_usleep( 50 );// wait for nop
}
#ifdef DEBUG_FPC_PATCHER
{
fltx4 reg[job_fpcpatch::MAX_VIRTUAL_CONST_COUNT];
m_state.GetSyncState( reg );
Assert( !V_memcmp( m_pSyncState, reg, sizeof( fltx4 ) * job_fpcpatch::MAX_VIRTUAL_CONST_COUNT ) );
}
ValidatePatchedProgram( psh->m_pCgProg, m_pPutFragmentProgram );
uint32 nFragmentProgramOffsetCheck;
GCM_MUST_SUCCEED( cellGcmAddressToOffset, m_pPutFragmentProgram, &nFragmentProgramOffsetCheck );
Assert( nFragmentProgramOffsetCheck == nFragmentProgramOffset );
#endif
g_ps3gcmGlobalState.CmdBufferFinish();
}
#endif
m_nFpcPatchCounter++;
}
uint g_nFpcPatch2JobExtraFlags = 0; // set this to 2 and SPU will break
static int s_nFpcPatch2Calls = 0;
void CFragmentProgramConstantPatcher_SPU::FpcPatch2( const job_fpcpatch2::FpHeader_t * prog, uint nFpDmaSize, void *pPatchedProgram, uint32 * pJts )
{
MICRO_PROFILE( g_mpFpcPatch2 );
#ifdef VJOBS_ON_SPURS
VjobChain3 &jobChain = g_spuGcm.m_jobSink;
uint32 nUCodeSize = prog->m_nUcodeSize;
CellSpursJob128 * pJob = g_spuGcm.m_jobPool128.Alloc( *g_spuGcm.m_pRoot->m_pFpcPatch2 );
Assert( pJob->header.sizeDmaList == 0 && pJob->header.sizeInOrInOut == 0 ); // the default MUST always be 1
pJob->header.useInOutBuffer = 1;
CDmaListConstructor dmaConstructor( pJob->workArea.dmaList );
dmaConstructor.AddInputDma( nFpDmaSize, prog );
dmaConstructor.AddInputDma( sizeof( *m_state.m_pSharedState ), ( void* )m_state.m_pSharedState );
// the g_spuGcmShared.m_nFpcpStartRangesAfterLastSync runs ahead of m_state.m_pSharedState->m_nStartRanges , because it's a PREDICTED
// start of range. It'll be absolutely in-sync with m_state.m_pSharedState->m_nStartRanges if we run SPUs synchronously
#ifdef DBGFLAG_ASSERT
uint nSharedStateStartRanges = m_state.m_pSharedState->m_nStartRanges;
#endif
// NOTE: if the asserts below fire, it may be due to invalid value in nSharedStateStartRanges because SPU DMAs stuff right down to m_state.m_pSharedState and it's changing while this code executes
Assert( uint( m_state.m_nEndOfJournalIdx - nSharedStateStartRanges ) <= m_state.m_pSharedState->m_nBufferMask + 1 );
Assert( uint( g_spuGcmShared.m_nFpcpStartRangesAfterLastSync - nSharedStateStartRanges ) <= uint( m_state.m_nEndOfJournalIdx - nSharedStateStartRanges ) );
uint nStartOfJournal = /*nSharedStateStartRanges*/g_spuGcmShared.m_nFpcpStartRangesAfterLastSync, nBufferMask = m_state.m_pSharedState->m_nBufferMask;
// we have 4 DMA elements ( 2..6 ) to fit the constant buffer; the 1st element may have to be as small as 16 bytes.
// this leaves the max constant buffer size 4 * 16kb + 16 bytes
const uint numRangeQwords = ( m_state.m_nEndOfJournalIdx - nStartOfJournal );
Assert( numRangeQwords <= nBufferMask + 1 );
if ( numRangeQwords != 0 )
{
uint nEndOfSpan0 = ( nStartOfJournal + nBufferMask + 1 ) & ~nBufferMask;
if ( ( signed int )( nEndOfSpan0 - m_state.m_nEndOfJournalIdx ) >= 0 )
{
//numRangeQwords = ( m_state.m_nEndOfJournalIdx - nStartOfJournal );
dmaConstructor.AddInputDmaLarge( ( numRangeQwords ) * sizeof( fltx4 ), m_state.m_pSharedState->GetBufferStart() + ( nStartOfJournal & nBufferMask ) );
}
else
{
//numRangeQwords = nFirstRange + nSecondRange ;
dmaConstructor.AddInputDmaLarge( ( nEndOfSpan0 - nStartOfJournal ) * sizeof( fltx4 ), m_state.m_pSharedState->GetBufferStart() + ( nStartOfJournal & nBufferMask ) );
dmaConstructor.AddInputDmaLarge( ( m_state.m_nEndOfJournalIdx - nEndOfSpan0 ) * sizeof( fltx4 ), m_state.m_pSharedState->GetBufferStart() );
}
}
else
{
dmaConstructor.AddSizeInOrInOut( 16 ); // we need at least 16 bytes in the ranges area for temporary storage
}
dmaConstructor.FinishIoBuffer( &pJob->header );
if( pJob->header.sizeDmaList > 7 * sizeof( uint64 ) )
{
Error( "FpcPatch2: DMA list size out of range (%d). job_fpcpatch2 parameters won't fit. numRangeQwords = %d\n", pJob->header.sizeDmaList, numRangeQwords );
}
// IMPORTANT: make it always synchronous , in case we don't have the target to patch. The only reason for this job to exist is to make it synchronous
// Also, if the range is large, still make it synchronous, to avoid subsequent jobs doing a lot of computations in vein
uint nAsync = !pPatchedProgram || numRangeQwords >= 1024 ? 0 : ( ( m_nFpcPatchCounter ) & m_nFpcPatchSyncMask ) ;
dmaConstructor[7][0] = m_nFpcPatchCounterOfLastSyncJob;
dmaConstructor[7][1] = m_nFpcPatchCounter;
dmaConstructor[8][0] = ( uint32 ) pPatchedProgram;
dmaConstructor[8][1] = uintp( pJts ); // the SPU->RSX dma element; may be NULL
dmaConstructor[9][0] = m_state.m_nEndOfJournalIdx;
dmaConstructor[9][1] = ( uint32 ) nStartOfJournal;
if( !IsCert() )
{
pJob->header.jobType |= CELL_SPURS_JOB_TYPE_MEMORY_CHECK;
}
dmaConstructor[8][0] |= g_nFpcPatch2JobExtraFlags;
if ( !nAsync )
{
dmaConstructor[8][0] |= job_fpcpatch::FLAG_PUT_STATE;
m_nFpcPatchCounterOfLastSyncJob = m_nFpcPatchCounter;
pJob->header.jobType |= CELL_SPURS_JOB_TYPE_STALL_SUCCESSOR;
g_spuGcmShared.m_nFpcpStartRangesAfterLastSync = m_state.m_nEndOfJournalIdx;
}
#ifdef DBGFLAG_ASSERT
int nError = cellSpursCheckJob( ( const CellSpursJob256* )pJob, sizeof( *pJob ), 256 );
static int s_nJobErrors = 0;
if( CELL_OK != nError )
{
++s_nJobErrors;
}
#endif
if ( !nAsync )
{
jobChain.PushSyncJobSync( CELL_SPURS_JOB_COMMAND_JOB( pJob ) );
}
else
{
jobChain.Push( CELL_SPURS_JOB_COMMAND_JOB( pJob ) );
}
#ifdef DEBUG_FPC_PATCHER
if( m_bSync )
{
if( pJts )
{
volatile uint32 * pJts2 = pJts;
while( *pJts2 )
continue;
}
volatile uint64_t * pEaJob = &pJob->header.eaBinary;
while( * pEaJob )
continue;
}
#endif
s_nFpcPatch2Calls++;
#endif
}
#ifdef DEBUG_FPC_PATCHER
extern void PatchUcodeConstSwap( uint32 * pDestination, const uint32 * pSource, int nLength );
extern uint fspatchGetLength( CGtype nType );
uint32 g_nConstLengthCounter[5] = { 0, 0, 0, 0, 0 };
void CFragmentProgramConstantPatcher_SPU::ValidatePatchedProgram( const CgBinaryProgram * prog, void * pPatchedUcode )
{
Assert( prog->profile == PROFILE_SCE_FP_RSX && prog->binaryFormatRevision == CG_BINARY_FORMAT_REVISION );
uint32 nUCodeSize = prog->ucodeSize;
void * pUcode = stackalloc( nUCodeSize );
void * pSourceUcode = ( ( uint8* ) prog ) + prog->ucode;
V_memcpy( pUcode, ( ( uint8* ) prog ) + prog->ucode, nUCodeSize );
CgBinaryParameter * pParameters = ( CgBinaryParameter * )( uintp( prog ) + prog->parameterArray ) ;
uint32 * pPatchDestination = NULL;
Assert( cellGcmCgGetCountParameter( ( CGprogram ) prog ) == prog->parameterCount );
for ( int nPar = 0; nPar < prog->parameterCount; ++nPar )
{
CgBinaryParameter * pPar = pParameters + nPar;
Assert( pPar == ( CgBinaryParameter * ) cellGcmCgGetIndexParameter( ( CGprogram ) prog, nPar ) );
#ifdef DBGFLAG_ASSERT
const char * pLeafName = ( const char * )( uintp( prog ) + pPar->name );
( void )pLeafName;
uint32 * pDefault = pPar->defaultValue ? ( uint32* )( uintp( prog ) + pPar->defaultValue ) : NULL ;
#endif
if ( pPar->embeddedConst )
{
Assert( pPar->res == CG_C && pPar->var == CG_UNIFORM ); // this MUST be a uniform constant.. at least I think that's the only kind we need to patch
const CgBinaryEmbeddedConstant * pEmbedded = ( const CgBinaryEmbeddedConstant* )( uintp( prog ) + pPar->embeddedConst );
int nLength = fspatchGetLength( pPar->type );
g_nConstLengthCounter[nLength] ++;
for ( uint nEm = 0; nEm < pEmbedded->ucodeCount; ++ nEm )
{
uint ucodeOffset = pEmbedded->ucodeOffset[nEm]; // is this the offset from prog structure start?
Assert( ucodeOffset < nUCodeSize - 4 );
#ifdef DBGFLAG_ASSERT
Assert( cellGcmCgGetEmbeddedConstantOffset( ( CGprogram ) prog, ( CGparameter ) pPar, nEm ) == ucodeOffset );
const float * pDefaultCheck = cellGcmCgGetParameterValues( ( CGprogram ) prog, ( CGparameter ) pPar );
Assert( pDefault == ( uint32* ) pDefaultCheck );
uint32 * pUcodeEmConst = ( uint32* )( uintp( pSourceUcode ) + ucodeOffset );
Assert( !pDefault || !V_memcmp( pDefault, pUcodeEmConst, nLength * 4 ) );
#endif
pPatchDestination = ( uint32* )( uintp( pUcode ) + ucodeOffset );
uint32 * pPatchedCheck = ( uint32* )( uintp( pPatchedUcode ) + ucodeOffset );
PatchUcodeConstSwap( pPatchDestination, ( uint32* ) & ( m_pSyncState[pPar->resIndex] ), nLength );
Assert( !V_memcmp( pPatchDestination, pPatchedCheck, nLength * 4 ) );
}
}
}
Assert( !V_memcmp( pPatchedUcode, pUcode, nUCodeSize ) );
}
#endif
void FpcPatchState::Init( job_fpcpatch::FpcPatchState_t * pSharedState, uint32 nBufferQwords )
{
#ifdef _DEBUG
//m_nRangesAdded = 0;
#endif
pSharedState->m_nBufferMask = m_nBufferMask = nBufferQwords - 1;
pSharedState->m_nStartRanges = m_nEndOfJournalIdx = IsCert() ? 0 : nBufferQwords - 128;
pSharedState->m_eaThis = m_pSharedState = pSharedState;
pSharedState->m_nThisStatePatchCounter = 0;
pSharedState->m_nDebuggerBreak = 0;
}
void FpcPatchState::GetSyncState( fltx4 * pRegisters )
{
V_memcpy( pRegisters, m_pSharedState->m_reg, job_fpcpatch:: MAX_VIRTUAL_CONST_COUNT * sizeof( fltx4 ) );
for( uint nJournalIdx = m_pSharedState->m_nStartRanges; nJournalIdx < m_nEndOfJournalIdx ; )
{
job_fpcpatch:: ConstRangeHeader_t & range = ((job_fpcpatch::ConstRangeHeader_t*)m_pSharedState->GetBufferStart())[ nJournalIdx & m_pSharedState->m_nBufferMask ];
nJournalIdx++;
for( uint nConstIdx = 0 ; nConstIdx < range.m_u32.m_nCount; ++nConstIdx, ++nJournalIdx )
{
pRegisters[ range.m_u32.m_nStart + nConstIdx ] = m_pSharedState->GetBufferStart()[nJournalIdx & m_pSharedState->m_nBufferMask ];
}
}
}
/*
void FpcPatchState::Reset()
{
m_nEndOfJournalIdx = 0;
m_pSharedState->m_nStartRanges = 0;
}
*/
#ifdef _DEBUG
static int s_nDebugRangeAdd = -1, s_nDebugSetConst = -1;
#endif
uint FpcPatchState::AddRange( uint32 nStart, uint32 nCount, const float * pData )
{
#ifndef _CERT
if( nStart + nCount > job_fpcpatch::MAX_VIRTUAL_CONST_COUNT )
{
Error( "AddRange(%d..%d) out of range <%d\n", nStart, nCount, int( job_fpcpatch::MAX_VIRTUAL_CONST_COUNT ) );
}
#endif
#ifdef _DEBUG
//Assert( s_nDebugRangeAdd != m_nRangesAdded );
if( int( s_nDebugSetConst - nStart ) >= 0 && int( s_nDebugSetConst - nStart ) < int( nCount ) )
{
fltx4 flDebugRegister = LoadUnalignedSIMD( pData + 4 * int( s_nDebugSetConst - nStart ) );
DebuggerBreak();
}
//++m_nRangesAdded;
#endif
// spin-wait, then V_memcpy range
COMPILE_TIME_ASSERT( sizeof( job_fpcpatch::ConstRangeHeader_t ) == 16 );
const uint nSpins = 0x1FF;
Assert( !( nSpins & ( nSpins + 1 ) ) );
//
// We need space for nCount + 1 QWords (1 Qword for the ConstRangeHeader_t)
// And we need m_nEndOfJournalIdx != m_nStartRanges to distinguish between
// the all-empty and all-full buffers
//
uint nAttempts = 0;
for ( ; ; ++nAttempts )
{
uint32 nStartRanges = m_pSharedState->m_nStartRanges;
Assert( uint32( m_nEndOfJournalIdx - nStartRanges ) <= m_nBufferMask + 1 );
// compute the new end - start; is it running further than buffer size away?
if ( ( m_nEndOfJournalIdx + nCount - ( nStartRanges + m_nBufferMask + 1 ) ) & 0x80000000 )
{ // no, the comparison is negative, therefore it's safe to fill it in
break;
}
// if ( ( nAttempts & nSpins ) == nSpins )
{
// the caller prints warning about this stall.
sys_timer_usleep( 60 ); // TODO: proper spinwait; proper OS syncronization
if( nAttempts == ( 1000000 / 60 ) )
{
// waiting for a second already ...
Warning(
"***************************************************************************************************************\n"
"* SPU hang in FpcPatchState::AddRange(). Please send this log (including a couple of screens above) to Sergiy *\n"
);
Msg( "AddRange(%d,%d,%p), ", nStart, nCount, pData );
Msg( "SharedState @%p {start=0x%X&0x%X,patch=%X,job=%X},", m_pSharedState, m_pSharedState->m_nStartRanges, m_pSharedState->m_nBufferMask, m_pSharedState->m_nThisStatePatchCounter, m_pSharedState->m_eaThisStateJobDescriptor );
Msg( "FpcpState @%p {end=0x%X},", this, this->m_nEndOfJournalIdx );
Msg( "SpuGcmShared trace {0x%X,0x%X,0x%X}\n", g_spuGcmShared.m_nFpcPatchCounterOfLastSyncJob, g_spuGcmShared.m_nFpcPatchCounter, g_spuGcmShared.m_nFpcpStartRangesAfterLastSync );
Msg( "RSX put=%X, get=%X sysring{put=%X,end=%X}\n", g_spuGcmShared.m_eaGcmControlRegister->put, g_spuGcmShared.m_eaGcmControlRegister->get,
g_spuGcmShared.m_sysring.m_nPut, g_spuGcmShared.m_sysring.m_nEnd );
Msg( "last JTS ret guard patched @%X, ", *cellGcmGetLabelAddress( GCM_LABEL_DEBUG_FPCP_RING ) );
Msg( "ringRsx[%d]:", g_spuGcmShared.m_fpcpRing.m_ringRsx.Count() );
for( int i = 0; i < g_spuGcmShared.m_fpcpRing.m_ringRsx.Count(); ++i )
{
RsxSpuDoubleRing::Segment_t & segment = g_spuGcmShared.m_fpcpRing.m_ringRsx[i];
Msg(" {%X,%p,%s}", segment.m_eaBase, segment.m_pSpuJts, *(segment.m_pSpuJts) == CELL_SPURS_JOB_COMMAND_LWSYNC ? "LWSYNC" : *(segment.m_pSpuJts) == CELL_SPURS_JOB_COMMAND_JTS ? "JTS" : "ERROR" );
}
Msg( "\nringSpu[%d]:", g_spuGcmShared.m_fpcpRing.m_ringSpu.Count() );
for( int i = 0; i < g_spuGcmShared.m_fpcpRing.m_ringSpu.Count(); ++i )
{
RsxSpuDoubleRing::Segment_t & segment = g_spuGcmShared.m_fpcpRing.m_ringSpu[i];
Msg(" {%X,%p,%s}", segment.m_eaBase, segment.m_pSpuJts, *(segment.m_pSpuJts) == CELL_SPURS_JOB_COMMAND_LWSYNC ? "LWSYNC" : *(segment.m_pSpuJts) == CELL_SPURS_JOB_COMMAND_JTS ? "JTS" : "ERROR" );
}
Msg( "***************************************************************************************************************\n" );
}
}
}
// we have enough free buffer to insert stuff
job_fpcpatch::ConstRangeHeader_t *hdr = (job_fpcpatch::ConstRangeHeader_t *)AddInternalPtr();
hdr->m_u32.m_nStart = nStart;
hdr->m_u32.m_nCount = nCount;
// add constants block
AddInternalBlock( pData, nCount );
return nAttempts;
}
#endif
+123
View File
@@ -0,0 +1,123 @@
//========= Copyright © Valve Corporation, All rights reserved. ====//
//
// Fragment Program Constant Patcher: an SPU implementation, V0
//
#ifndef PS3_SHADER_CONSTANT_PATCH_SPU_HDR
#define PS3_SHADER_CONSTANT_PATCH_SPU_HDR
#ifdef _PS3
#include "vjobs/fpcpatch_shared.h"
#include <cg/cg.h>
#include <cg/cgBinary.h>
#ifdef _DEBUG
//#define DEBUG_FPC_PATCHER
#endif
class FpcPatchState
{
public:
job_fpcpatch::FpcPatchState_t * m_pSharedState;
uint32 m_nEndOfJournalIdx; // this is PPU-side variable only, written by PPU only
fltx4 * GetBufferStart(){ return m_pSharedState->GetBufferStart() ; } // the buffer start address
uint32 m_nBufferMask; // the number of Qwords in the buffer
//#ifdef _DEBUG
//int m_nRangesAdded;
//#endif
public:
FpcPatchState(){m_pSharedState = NULL;}
void Init( job_fpcpatch::FpcPatchState_t * pSharedState, uint32 nBufferQwords );
void Reset();
uint AddRange( uint32 nStart, uint32 nCount, const float * pData );
void GetSyncState( fltx4 * pRegisters );
protected:
fltx4 * AddInternalPtr()
{
fltx4 * pOut = GetBufferStart() + ( m_nEndOfJournalIdx & m_nBufferMask );
m_nEndOfJournalIdx++;
return pOut;
}
void AddInternal( const fltx4 f4 )
{
*AddInternalPtr() = f4;
}
inline void AddInternalBlock( const void *pBlock, const uint32 numFltx4s )
{
// Fit the first portion until the end of the buffer, second portion at start
uint32 const nCurrentIdx = ( m_nEndOfJournalIdx & m_nBufferMask ); // the start index to copy to
uint32 const numFltx4sUntilEnd = ( -nCurrentIdx ) & m_nBufferMask; // number of fltx4's from the nCurrentIdx to the end of the current buffer ring
uint32 const numFirstCopy = MIN( numFltx4sUntilEnd, numFltx4s ); // number of fltx4's to copy first
memcpy( GetBufferStart() + nCurrentIdx, pBlock, numFirstCopy * sizeof( fltx4 ) );
memcpy( GetBufferStart(), ( ( fltx4* ) pBlock ) + numFirstCopy, ( numFltx4s - numFirstCopy ) * sizeof( fltx4 ) );
m_nEndOfJournalIdx += numFltx4s;
}
};
struct IDirect3DPixelShader9 ;
class CFragmentProgramConstantPatcher_SPU
{
public:
CFragmentProgramConstantPatcher_SPU();
~CFragmentProgramConstantPatcher_SPU();
void InitLocal( void *pBuffer, uint nSize );
void Shutdown();
// semantics should match cgGLSetFragmentRegisterBlock()
void SetFragmentRegisterBlock( uint StartRegister, uint Vector4fCount, const float* pConstantData );
// semantics of cgGLBindProgram( pPixelShader->m_pixProgram->m_CGprogram )
void BindProgram( const CgBinaryProgram *prog );
void BindProgram( const struct IDirect3DPixelShader9 * prog );
void BeginScene();
void EndScene();
//job_fpcpatch::FpcPatchState_t * GetSharedState(){return m_state.m_pSharedState; }
uint GetStateEndOfJournalIdx() { return m_state.m_nEndOfJournalIdx; }
uint GetJournalCapacity() const { return m_state.m_nBufferMask + 1; }
int GetJournalSpaceUsedSince( uint nMarker )const{ return int( m_state.m_nEndOfJournalIdx - nMarker ); }
int GetJournalSpaceLeftSince( uint nMarker )const{ return int( ( m_state.m_nBufferMask + 1 ) - ( m_state.m_nEndOfJournalIdx - nMarker ) ); }
protected:
void ResetPut();
void * FpcPatch( const struct CgBinaryProgram * prog, void * pFragmentProgramDestination, uint32 * pJts );
void FpcPatch2( const job_fpcpatch2::FpHeader_t * psh, uint nFpDmaSize, void *pPatchedProgram, uint32 * pJts );
protected:
friend class CSpuGcm;
FpcPatchState m_state;
uint32* m_pBuffer, *m_pBufferEnd;
int m_nIoOffsetDelta; // m_pBuffer + m_nIoOffsetDelta == IO offset usable by RSX
uint32 * m_pPutFragmentProgram;
uint m_nFpcPatchCounterAtBeginScene; // used for timing
uint m_nFpcPatchCounterOfLastSyncJob;
uint m_nBufferLocation;// CELL_GCM_LOCATION_MAIN
uint m_nFpcPatchCounter, m_nFpcPatchSyncMask;
//uint m_nStartRangesAfterLastSync; // this is the index used to upload only the useful constants to SPU
bool m_isBufferPassedIn;
bool m_bFpcPatchOnPpu, m_bEnableSPU;
#ifdef DEBUG_FPC_PATCHER
void ValidatePatchedProgram( const CgBinaryProgram *prog, void * pPatchedUcode );
fltx4 *m_pSyncState;
bool m_bTestAlwaysStateSync;
bool m_bSync; // don't use JTS, but just patch synchronously (may be more stable with GPAD)
#endif
};
extern CFragmentProgramConstantPatcher_SPU g_pixelShaderPatcher; // Patches pixel shader constants
#endif
#endif
+202
View File
@@ -0,0 +1,202 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
// Configure gcm be inline, unsfae etc....
// Inlcude (spu or ppu) after cell headers
//
//==================================================================================================
#ifndef INCLUDED_GCMCONFIG_H
#define INCLUDED_GCMCONFIG_H
// Comment in one GCMCONFIG defn as required
//#define GCMCONFIG(x) x##Inline
#define GCMCONFIG(x) x##UnsafeInline
//#define GCMCONFIG(x) x
#define GCM_FUNC( GCM_FUNCTION, ...) GCM_FUNCTION ( gpGcmContext, ##__VA_ARGS__ )
#define cellGcmSetReferenceCommand GCMCONFIG(cellGcmSetReferenceCommand)
#define cellGcmSetJumpCommand GCMCONFIG(cellGcmSetJumpCommand)
#define cellGcmSetCallCommand GCMCONFIG(cellGcmSetCallCommand)
#define cellGcmSetReturnCommand GCMCONFIG(cellGcmSetReturnCommand)
#define cellGcmSetAntiAliasingControl GCMCONFIG(cellGcmSetAntiAliasingControl)
#define cellGcmSetWaitLabel GCMCONFIG(cellGcmSetWaitLabel)
#define cellGcmSetWriteCommandLabel GCMCONFIG(cellGcmSetWriteCommandLabel)
#define cellGcmSetWriteBackEndLabel GCMCONFIG(cellGcmSetWriteBackEndLabel)
#define cellGcmSetWriteTextureLabel GCMCONFIG(cellGcmSetWriteTextureLabel)
#define cellGcmSetTimeStamp GCMCONFIG(cellGcmSetTimeStamp)
#define cellGcmSetInvalidateZcull GCMCONFIG(cellGcmSetInvalidateZcull)
#define cellGcmSetAlphaFunc GCMCONFIG(cellGcmSetAlphaFunc)
#define cellGcmSetBlendColor GCMCONFIG(cellGcmSetBlendColor)
#define cellGcmSetBlendEquation GCMCONFIG(cellGcmSetBlendEquation)
#define cellGcmSetBlendFunc GCMCONFIG(cellGcmSetBlendFunc)
#define cellGcmSetClearSurface GCMCONFIG(cellGcmSetClearSurface)
#define cellGcmSetClearColor GCMCONFIG(cellGcmSetClearColor)
#define cellGcmSetClearDepthStencil GCMCONFIG(cellGcmSetClearDepthStencil)
#define cellGcmSetColorMask GCMCONFIG(cellGcmSetColorMask)
#define cellGcmSetColorMaskMrt GCMCONFIG(cellGcmSetColorMaskMrt)
#define cellGcmSetCullFace GCMCONFIG(cellGcmSetCullFace)
#define cellGcmSetDepthBounds GCMCONFIG(cellGcmSetDepthBounds)
#define cellGcmSetDepthFunc GCMCONFIG(cellGcmSetDepthFunc)
#define cellGcmSetDepthMask GCMCONFIG(cellGcmSetDepthMask)
#define cellGcmSetFrontFace GCMCONFIG(cellGcmSetFrontFace)
#define cellGcmSetLineWidth GCMCONFIG(cellGcmSetLineWidth)
#define cellGcmSetLineSmoothEnable GCMCONFIG(cellGcmSetLineSmoothEnable)
#define cellGcmSetLineStippleEnable GCMCONFIG(cellGcmSetLineStippleEnable)
#define cellGcmSetLineStipplePattern GCMCONFIG(cellGcmSetLineStipplePattern)
#define cellGcmSetLogicOp GCMCONFIG(cellGcmSetLogicOp)
#define cellGcmSetPointSize GCMCONFIG(cellGcmSetPointSize)
#define cellGcmSetPolygonOffset GCMCONFIG(cellGcmSetPolygonOffset)
#define cellGcmSetPolySmoothEnable GCMCONFIG(cellGcmSetPolySmoothEnable)
#define cellGcmSetPolygonStippleEnable GCMCONFIG(cellGcmSetPolygonStippleEnable)
#define cellGcmSetPolygonStipplePattern GCMCONFIG(cellGcmSetPolygonStipplePattern)
#define cellGcmSetFrontPolygonMode GCMCONFIG(cellGcmSetFrontPolygonMode)
#define cellGcmSetBackPolygonMode GCMCONFIG(cellGcmSetBackPolygonMode)
#define cellGcmSetScissor GCMCONFIG(cellGcmSetScissor)
#define cellGcmSetShadeMode GCMCONFIG(cellGcmSetShadeMode)
#define cellGcmSetTwoSideLightEnable GCMCONFIG(cellGcmSetTwoSideLightEnable)
#define cellGcmSetStencilFunc GCMCONFIG(cellGcmSetStencilFunc)
#define cellGcmSetBackStencilFunc GCMCONFIG(cellGcmSetBackStencilFunc)
#define cellGcmSetStencilMask GCMCONFIG(cellGcmSetStencilMask)
#define cellGcmSetBackStencilMask GCMCONFIG(cellGcmSetBackStencilMask)
#define cellGcmSetStencilOp GCMCONFIG(cellGcmSetStencilOp)
#define cellGcmSetBackStencilOp GCMCONFIG(cellGcmSetBackStencilOp)
#define cellGcmSetZMinMaxControl GCMCONFIG(cellGcmSetZMinMaxControl)
#define cellGcmSetAlphaTestEnable GCMCONFIG(cellGcmSetAlphaTestEnable)
#define cellGcmSetBlendEnable GCMCONFIG(cellGcmSetBlendEnable)
#define cellGcmSetBlendEnableMrt GCMCONFIG(cellGcmSetBlendEnableMrt)
#define cellGcmSetLogicOpEnable GCMCONFIG(cellGcmSetLogicOpEnable)
#define cellGcmSetCullFaceEnable GCMCONFIG(cellGcmSetCullFaceEnable)
#define cellGcmSetDepthBoundsTestEnable GCMCONFIG(cellGcmSetDepthBoundsTestEnable)
#define cellGcmSetDepthTestEnable GCMCONFIG(cellGcmSetDepthTestEnable)
#define cellGcmSetDitherEnable GCMCONFIG(cellGcmSetDitherEnable)
#define cellGcmSetStencilTestEnable GCMCONFIG(cellGcmSetStencilTestEnable)
#define cellGcmSetTwoSidedStencilTestEnable GCMCONFIG(cellGcmSetTwoSidedStencilTestEnable)
#define cellGcmSetPolygonOffsetFillEnable GCMCONFIG(cellGcmSetPolygonOffsetFillEnable)
#define cellGcmSetRestartIndexEnable GCMCONFIG(cellGcmSetRestartIndexEnable)
#define cellGcmSetPointSpriteControl GCMCONFIG(cellGcmSetPointSpriteControl)
#define cellGcmSetInvalidateTextureCache GCMCONFIG(cellGcmSetInvalidateTextureCache)
#define cellGcmSetTextureBorderColor GCMCONFIG(cellGcmSetTextureBorderColor)
#define cellGcmSetTextureControl GCMCONFIG(cellGcmSetTextureControl)
#define cellGcmSetTextureOptimization GCMCONFIG(cellGcmSetTextureOptimization)
#define cellGcmSetCylindricalWrap GCMCONFIG(cellGcmSetCylindricalWrap)
#define cellGcmSetInvalidateVertexCache GCMCONFIG(cellGcmSetInvalidateVertexCache)
#define cellGcmSetRestartIndex GCMCONFIG(cellGcmSetRestartIndex)
#define cellGcmSetVertexData4f GCMCONFIG(cellGcmSetVertexData4f)
#define cellGcmSetFrequencyDividerOperation GCMCONFIG(cellGcmSetFrequencyDividerOperation)
#define cellGcmSetTransformBranchBits GCMCONFIG(cellGcmSetTransformBranchBits)
#define cellGcmSetVertexAttribInputMask GCMCONFIG(cellGcmSetVertexAttribInputMask)
#define cellGcmSetFragmentProgramGammaEnable GCMCONFIG(cellGcmSetFragmentProgramGammaEnable)
#define cellGcmSetRenderEnable GCMCONFIG(cellGcmSetRenderEnable)
#define cellGcmSetZpassPixelCountEnable GCMCONFIG(cellGcmSetZpassPixelCountEnable)
#define cellGcmSetClearReport GCMCONFIG(cellGcmSetClearReport)
#define cellGcmSetReport GCMCONFIG(cellGcmSetReport)
#define cellGcmSetZcullStatsEnable GCMCONFIG(cellGcmSetZcullStatsEnable)
#define cellGcmSetZcullControl GCMCONFIG(cellGcmSetZcullControl)
#define cellGcmSetZcullLimit GCMCONFIG(cellGcmSetZcullLimit)
#define cellGcmSetScullControl GCMCONFIG(cellGcmSetScullControl)
#define cellGcmSetVertexTextureAddress GCMCONFIG(cellGcmSetVertexTextureAddress)
#define cellGcmSetVertexTextureFilter GCMCONFIG(cellGcmSetVertexTextureFilter)
#define cellGcmSetVertexTextureControl GCMCONFIG(cellGcmSetVertexTextureControl)
#define cellGcmSetVertexTextureBorderColor GCMCONFIG(cellGcmSetVertexTextureBorderColor)
#define cellGcmSetPerfMonTrigger GCMCONFIG(cellGcmSetPerfMonTrigger)
#define cellGcmSetFogMode GCMCONFIG(cellGcmSetFogMode)
#define cellGcmSetFogParams GCMCONFIG(cellGcmSetFogParams)
#define cellGcmSetTransferLocation GCMCONFIG(cellGcmSetTransferLocation)
#define cellGcmSetDepthFormat GCMCONFIG(cellGcmSetDepthFormat)
#define cellGcmSetBlendOptimization GCMCONFIG(cellGcmSetBlendOptimization)
#define cellGcmSetPolygonOffsetLineEnable GCMCONFIG(cellGcmSetPolygonOffsetLineEnable)
#define cellGcmSetVertexAttribOutputMask GCMCONFIG(cellGcmSetVertexAttribOutputMask)
#define cellGcmSetTextureRemap GCMCONFIG(cellGcmSetTextureRemap)
#define cellGcmSetVertexProgramStartSlot GCMCONFIG(cellGcmSetVertexProgramStartSlot)
#define cellGcmSetVertexProgramRegisterCount GCMCONFIG(cellGcmSetVertexProgramRegisterCount)
#define cellGcmSetTransferDataMode GCMCONFIG(cellGcmSetTransferDataMode)
#define cellGcmSetDrawBegin GCMCONFIG(cellGcmSetDrawBegin)
#define cellGcmSetDrawEnd GCMCONFIG(cellGcmSetDrawEnd)
#define cellGcmSetVertexDataArrayFormat GCMCONFIG(cellGcmSetVertexDataArrayFormat)
#define cellGcmSetVertexDataArrayOffset GCMCONFIG(cellGcmSetVertexDataArrayOffset)
#define cellGcmSetUpdateFragmentProgramParameterLocation GCMCONFIG(cellGcmSetUpdateFragmentProgramParameterLocation)
#define cellGcmSetVertexDataBase GCMCONFIG(cellGcmSetVertexDataBase)
#define cellGcmSetFragmentProgramOffset GCMCONFIG(cellGcmSetFragmentProgramOffset)
#define cellGcmSetFragmentProgramControl GCMCONFIG(cellGcmSetFragmentProgramControl)
#define cellGcmSetClearZcullSurface GCMCONFIG(cellGcmSetClearZcullSurface)
#define cellGcmSetZcullEnable GCMCONFIG(cellGcmSetZcullEnable)
#define cellGcmSetUserCommand GCMCONFIG(cellGcmSetUserCommand)
#define cellGcmSetReportLocation GCMCONFIG(cellGcmSetReportLocation)
#define cellGcmSetNotifyIndex GCMCONFIG(cellGcmSetNotifyIndex)
#define cellGcmSetNotify GCMCONFIG(cellGcmSetNotify)
#define cellGcmSetTextureFilter GCMCONFIG(cellGcmSetTextureFilter)
#define cellGcmSetTextureAddress GCMCONFIG(cellGcmSetTextureAddress)
#define cellGcmSetUserClipPlaneControl GCMCONFIG(cellGcmSetUserClipPlaneControl)
#define cellGcmSetAnisoSpread GCMCONFIG(cellGcmSetAnisoSpread)
#define cellGcmSetNopCommand GCMCONFIG(cellGcmSetNopCommand)
#define cellGcmSetSkipNop GCMCONFIG(cellGcmSetSkipNop)
#define cellGcmReserveMethodSize GCMCONFIG(cellGcmReserveMethodSize)
#define cellGcmSetWriteBackEndLabelForConditional GCMCONFIG(cellGcmSetWriteBackEndLabelForConditional)
#define cellGcmSetWriteTextureLabelForConditional GCMCONFIG(cellGcmSetWriteTextureLabelForConditional)
#define cellGcmSetVertexProgram GCMCONFIG(cellGcmSetVertexProgram)
#define cellGcmSetFragmentProgramLoadLocation GCMCONFIG(cellGcmSetFragmentProgramLoadLocation)
#define cellGcmSetVertexProgramLoad GCMCONFIG(cellGcmSetVertexProgramLoad)
#define cellGcmSetVertexProgramLoadSlot GCMCONFIG(cellGcmSetVertexProgramLoadSlot)
#define cellGcmSetVertexProgramConstants GCMCONFIG(cellGcmSetVertexProgramConstants)
#define cellGcmSetVertexProgramParameterBlock GCMCONFIG(cellGcmSetVertexProgramParameterBlock)
#define cellGcmSetVertexDataArray GCMCONFIG(cellGcmSetVertexDataArray)
#define cellGcmSetTextureBorder GCMCONFIG(cellGcmSetTextureBorder)
#define cellGcmSetWaitFlip GCMCONFIG(cellGcmSetWaitFlip)
#define cellGcmSetFragmentProgramParameterPointer GCMCONFIG(cellGcmSetFragmentProgramParameterPointer)
#define cellGcmSetFragmentProgramParameter GCMCONFIG(cellGcmSetFragmentProgramParameter)
#define cellGcmSetFragmentProgram GCMCONFIG(cellGcmSetFragmentProgram)
#define cellGcmSetVertexProgramParameter GCMCONFIG(cellGcmSetVertexProgramParameter)
#define cellGcmSetFragmentProgramLoad GCMCONFIG(cellGcmSetFragmentProgramLoad)
#define cellGcmSetUpdateFragmentProgramParameter GCMCONFIG(cellGcmSetUpdateFragmentProgramParameter)
#define cellGcmSetTextureFilterSigned GCMCONFIG(cellGcmSetTextureFilterSigned)
#define cellGcmSetClipMinMax GCMCONFIG(cellGcmSetClipMinMax)
#define cellGcmSetViewport GCMCONFIG(cellGcmSetViewport)
#define cellGcmSetTextureAddressAnisoBiasRemap GCMCONFIG(cellGcmSetTextureAddressAnisoBiasRemap)
#define cellGcmSetTextureAddressAnisoBias GCMCONFIG(cellGcmSetTextureAddressAnisoBias)
#define cellGcmSetTexture GCMCONFIG(cellGcmSetTexture)
#define cellGcmSetVertexTexture GCMCONFIG(cellGcmSetVertexTexture)
#define cellGcmSetSurface GCMCONFIG(cellGcmSetSurface)
#define cellGcmSetSurfaceWindow GCMCONFIG(cellGcmSetSurfaceWindow)
#define cellGcmSetInlineTransfer GCMCONFIG(cellGcmSetInlineTransfer)
#define cellGcmInlineTransfer GCMCONFIG(cellGcmInlineTransfer)
#define cellGcmSetTransferImage GCMCONFIG(cellGcmSetTransferImage)
#define cellGcmTransferData GCMCONFIG(cellGcmTransferData)
#define cellGcmSetTransferData GCMCONFIG(cellGcmSetTransferData)
#define cellGcmSetConvertSwizzleFormat GCMCONFIG(cellGcmSetConvertSwizzleFormat)
#define cellGcmSetInlineTransferPointer GCMCONFIG(cellGcmSetInlineTransferPointer)
#define cellGcmSetTransferDataFormat GCMCONFIG(cellGcmSetTransferDataFormat)
#define cellGcmSetTransferDataOffset GCMCONFIG(cellGcmSetTransferDataOffset)
#define cellGcmSetTransferScaleMode GCMCONFIG(cellGcmSetTransferScaleMode)
#define cellGcmSetTransferScaleSurface GCMCONFIG(cellGcmSetTransferScaleSurface)
#define cellGcmSetTransferScaleSwizzle GCMCONFIG(cellGcmSetTransferScaleSwizzle)
#define cellGcmSetTransferReportData GCMCONFIG(cellGcmSetTransferReportData)
#define cellGcmSetDrawArrays GCMCONFIG(cellGcmSetDrawArrays)
#define cellGcmSetDrawIndexArray GCMCONFIG(cellGcmSetDrawIndexArray)
#define cellGcmSetDrawInlineArray GCMCONFIG(cellGcmSetDrawInlineArray)
#define cellGcmSetDrawInlineIndexArray32 GCMCONFIG(cellGcmSetDrawInlineIndexArray32)
#define cellGcmSetDrawInlineIndexArray16 GCMCONFIG(cellGcmSetDrawInlineIndexArray16)
#define cellGcmSetDrawInlineArrayPointer GCMCONFIG(cellGcmSetDrawInlineArrayPointer)
#define cellGcmSetVertexProgramConstantsPointer GCMCONFIG(cellGcmSetVertexProgramConstantsPointer)
#define cellGcmSetDrawInlineIndexArray32Pointer GCMCONFIG(cellGcmSetDrawInlineIndexArray32Pointer)
#define cellGcmSetDrawInlineIndexArray16Pointer GCMCONFIG(cellGcmSetDrawInlineIndexArray16Pointer)
#define cellGcmSetVertexProgramParameterBlockPointer GCMCONFIG(cellGcmSetVertexProgramParameterBlockPointer)
#define cellGcmSetWaitForIdle GCMCONFIG(cellGcmSetWaitForIdle)
#define cellGcmSetVertexData3f GCMCONFIG(cellGcmSetVertexData3f)
#define cellGcmSetVertexData2f GCMCONFIG(cellGcmSetVertexData2f)
#define cellGcmSetVertexData1f GCMCONFIG(cellGcmSetVertexData1f)
#define cellGcmSetVertexData4s GCMCONFIG(cellGcmSetVertexData4s)
#define cellGcmSetVertexDataScaled4s GCMCONFIG(cellGcmSetVertexDataScaled4s)
#define cellGcmSetVertexData2s GCMCONFIG(cellGcmSetVertexData2s)
#define cellGcmSetVertexData4ub GCMCONFIG(cellGcmSetVertexData4ub)
#define cellGcmSetTextureControlAlphaKill GCMCONFIG(cellGcmSetTextureControlAlphaKill)
#define cellGcmSetNoParanoidTextureFetches GCMCONFIG(cellGcmSetNoParanoidTextureFetches)
#define cellGcmSetInlineTransferAlignedPointer GCMCONFIG(cellGcmSetInlineTransferAlignedPointer)
#define cellGcmSetVertexProgramConstantsAlignedPointer GCMCONFIG(cellGcmSetVertexProgramConstantsAlignedPointer)
#define cellGcmSetVertexProgramParameterBlockAlignedPointer GCMCONFIG(cellGcmSetVertexProgramParameterBlockAlignedPointer)
#define cellGcmSetDrawInlineArrayAlignedPointer GCMCONFIG(cellGcmSetDrawInlineArrayAlignedPointer)
#define cellGcmSetDrawInlineIndexArray32AlignedPointer GCMCONFIG(cellGcmSetDrawInlineIndexArray32AlignedPointer)
#define cellGcmSetDrawInlineIndexArray16AlignedPointer GCMCONFIG(cellGcmSetDrawInlineIndexArray16AlignedPointer)
#endif // INCLUDED_GCMCONFIG_H
+273
View File
@@ -0,0 +1,273 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
//
//
//==================================================================================================
//--------------------------------------------------------------------------------------------------
// Inlcudes
//--------------------------------------------------------------------------------------------------
#include <libsn_spu.h>
#include "SpuMgr_spu.h"
#include "gcmdraw_spu.h"
#include "gcmdrawstate.h"
#include "gcmstate.h"
//--------------------------------------------------------------------------------------------------
// Globals
//--------------------------------------------------------------------------------------------------
ALIGN16 VertexShader9Data_t gVertexShaderData ALIGN16_POST;
ALIGN16 PixelShader9Data_t gPixelShaderData ALIGN16_POST;
ALIGN16 CellGcmContextData gGcmContext ALIGN16_POST ALIGN16_POST;
ALIGN16 CPs3gcmGlobalState g_ps3gcmGlobalState ALIGN16_POST ;
ALIGN16 CPs3gcmTextureLayout::Format_t g_ps3texFormats[PS3_TEX_MAX_FORMAT_COUNT] ALIGN16_POST;
ALIGN16 IDirect3DVertexDeclaration9 gDecl ALIGN16_POST;
ALIGN16 CellGcmContextData* gpGcmContext = &gGcmContext ALIGN16_POST;
ALIGN16 uint8 gFp[0x2000] ALIGN16_POST;
ALIGN16 uint8 gVp[0x2000] ALIGN16_POST;
ALIGN16 CPs3gcmTextureLayout gaLayout[D3D_MAX_TEXTURES] ALIGN16_POST;
ALIGN16 uint8 gaECB[3][0x1000];
ALIGN16 CPs3gcmLocalMemoryBlock gLmBlock ALIGN16_POST;
int gEA;
//--------------------------------------------------------------------------------------------------
// Routine to DMA in texture Layouts
//--------------------------------------------------------------------------------------------------
void GetTextureLayouts()
{
// Loop and DMA in texture layouts
for (uint32 lp = 0; lp < ARRAYSIZE(gaLayout); lp++)
{
uintp ea = gpGcmDrawState->m_textures[lp].m_eaLayout;
gEA = ea;
if (ea) gSpuMgr.DmaGetSAFE( &gaLayout[lp], ea, sizeof(CPs3gcmTextureLayout), SPU_DMAGET_TAG );
}
gSpuMgr.DmaDone( SPU_DMAGET_TAG_WAIT );
}
//--------------------------------------------------------------------------------------------------
// main()
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// Protocol
//
// Simplest possible for starters :
// PPU sends SPU Mbx the last part of the drawcall to perform.
// SPU performs it and DMAs down the data. When it's complete it send the PPUMbx the length of the drawcall
// PPU prepares next packet which waits on PPUMbx completion before sending another.
//
// Relies on PPU calling cellGcmReserveMethodSize with 16k, so that the SPU can go ahead and DMA back the
// draw..
//--------------------------------------------------------------------------------------------------
int main(void)
{
gSpuMgr.Init();
// Initialise SPUs drawstate class
uint32 eaGcmDrawState;
gpGcmDrawState->Init();
uint8* pData = gpGcmDrawState->m_pData;
// Initialise context
gGcmContext.begin = (uint32*)MemAlloc_AllocAligned(GCM_DS_FIFOPERDRAW * GCM_NUMDRAWCALLS_SPU, 128);
gGcmContext.end = gGcmContext.begin + (GCM_DS_FIFOPERDRAW * GCM_NUMDRAWCALLS_SPU)/4;
gGcmContext.callback = NULL;
// Pull in globalstate
volatile uint32 eagGlobalState;
gSpuMgr.ReadMailbox( (uint32_t *) &eagGlobalState );
gSpuMgr.DmaGetUNSAFE( &g_ps3gcmGlobalState, eagGlobalState, SPUMGR_ALIGN_UP( sizeof(g_ps3gcmGlobalState), 16 ), SPU_DMAGET_TAG );
gSpuMgr.DmaDone( SPU_DMAGET_TAG_WAIT );
while(1)
{
uint32 startidx, count, loop;
gSpuMgr.ReadMailbox( (uint32_t *) &startidx );
count = startidx >>16;
startidx &= 0xFFFF;
gpGcmContext->current = gpGcmContext->begin;
// Loop over the drawstates
for (loop = 0; loop < count; loop++)
{
uint32 idx = (startidx +loop) % GCM_DRAWSTATE_MAX;
eaGcmDrawState = g_ps3gcmGlobalState.m_eaDrawStates + (idx*sizeof(CGcmDrawState));
// Read drawstate
gSpuMgr.DmaGetUNSAFE( gpGcmDrawState, eaGcmDrawState, SPUMGR_ALIGN_UP( DRAWSTATE_SIZEOFDMA, 16 ), SPU_DMAGET_TAG );
gSpuMgr.DmaDone( SPU_DMAGET_TAG_WAIT );
// Read Fixed Data
gSpuMgr.DmaGetUNSAFE( &gFixedData[0], uintp(gpGcmDrawState->m_pFixed), SPUMGR_ALIGN_UP(sizeof(gFixedData[0]), 16), SPU_DMAGET_TAG );
gSpuMgr.DmaDone( SPU_DMAGET_TAG_WAIT );
gpGcmDrawState->m_pFixed = &gFixedData[0];
// Read Packed Data
uint32* pParam = gpGcmDrawState->m_param;
if (gpGcmDrawState->m_cmd & 0x80000000) snPause();
gpGcmDrawState->m_cmd &= 0x7fffffff;
uint32 packSize = gpGcmDrawState->m_pDataCursor - gpGcmDrawState->m_pData;
gSpuMgr.DmaGetUNSAFE( pData, uintp(gpGcmDrawState->m_pData), SPUMGR_ALIGN_UP( packSize, 16 ), SPU_DMAGET_TAG );
gpGcmDrawState->m_pData = pData;
gpGcmDrawState->m_pDataCursor = pData + packSize;
// DMA in any ECBs we will need...
for ( uint32 lp = 0; lp < 3; lp++ )
{
if (gpGcmDrawState->m_aECB[lp])
{
gSpuMgr.DmaGetSAFE( gaECB[lp], uintp(gpGcmDrawState->m_aECB[lp]), gpGcmDrawState->m_aSizeECB[lp], SPU_DMAGET_TAG );
gpGcmDrawState->m_aECB[lp] = gaECB[lp];
}
}
gSpuMgr.DmaDone( SPU_DMAGET_TAG_WAIT );
// Read Pixel Shader and Vertex Shader
if ( (gpGcmDrawState->m_cmd != CmdCommitStates) && (gpGcmDrawState->m_cmd != CmdEndFrame ))
{
if(gpGcmDrawState->m_pVertexShaderData)
{
gSpuMgr.DmaGetUNSAFE( &gVertexShaderData, uintp(gpGcmDrawState->m_pVertexShaderData), SPUMGR_ALIGN_UP( sizeof(gVertexShaderData), 16 ), SPU_DMAGET_TAG );
gpGcmDrawState->m_pVertexShaderData = &gVertexShaderData;
gSpuMgr.DmaDone( SPU_DMAGET_TAG_WAIT );
// FPHeader, UCode, patches etc...
uintp ea = uintp(gVertexShaderData.m_pVertexShaderCmdBuffer);
gSpuMgr.DmaGetUNSAFE( &gVp, ea, SPUMGR_ALIGN_UP((gVertexShaderData.m_nVertexShaderCmdBufferWords*4),16), SPU_DMAGET_TAG );
gVertexShaderData.m_pVertexShaderCmdBuffer = (uint32*)gVp;
}
if(gpGcmDrawState->m_pPixelShaderData)
{
// PS Data
gSpuMgr.DmaGetUNSAFE( &gPixelShaderData, uintp(gpGcmDrawState->m_pPixelShaderData), SPUMGR_ALIGN_UP( sizeof(gPixelShaderData), 16 ), SPU_DMAGET_TAG );
gpGcmDrawState->m_pPixelShaderData = &gPixelShaderData;
gSpuMgr.DmaDone( SPU_DMAGET_TAG_WAIT );
// FPHeader, UCode, patches etc...
uintp ea = uintp(gPixelShaderData.m_eaFp);
gSpuMgr.DmaGetUNSAFE( &gFp, ea, SPUMGR_ALIGN_UP(gPixelShaderData.m_nTotalSize,16), SPU_DMAGET_TAG );
gPixelShaderData.m_eaFp = (FpHeader_t*)gFp;
}
// Decl
gSpuMgr.DmaGetUNSAFE( &gDecl, uintp(pParam[0]), SPUMGR_ALIGN_UP( sizeof(gDecl), 16 ), SPU_DMAGET_TAG );
// Texture Fomrats
gSpuMgr.DmaGetUNSAFE( &g_ps3texFormats, uintp(pParam[4]), SPUMGR_ALIGN_UP( sizeof(g_ps3texFormats), 16 ), SPU_DMAGET_TAG );
gSpuMgr.DmaDone( SPU_DMAGET_TAG_WAIT );
}
// Process command
switch(gpGcmDrawState->m_cmd)
{
case CmdCommitStates:
case CmdEndFrame:
gpGcmDrawState->CommitStates();
break;
case CmdDrawPrim:
gpGcmDrawState->CommitAll(&gDecl, pParam[1]);
// Draw
GCM_FUNC( cellGcmSetDrawIndexArray,
pParam[2], pParam[5],
CELL_GCM_DRAW_INDEX_ARRAY_TYPE_16, CELL_GCM_LOCATION_LOCAL,
pParam[3] );
break;
case CmdDrawPrimUP:
{
D3DStreamDesc &dsd = g_dxGcmVertexStreamSources[0];
dsd.m_offset = 0;
dsd.m_stride = pParam[2];
dsd.m_vtxBuffer = ( IDirect3DVertexBuffer9 * )( uintp )1; // invalid pointer, but non-NULL to signal it's a real vertex buffer;
dsd.m_nLocalBufferOffset = 0;
gpGcmDrawState->CommitAll(&gDecl, 0);
GCM_FUNC(cellGcmSetCallCommand, pParam[1]);
}
break;
}
} // End Loop over drawstates
// DMA out packet
// first fill context to a 16B boundary
while (uintp(gpGcmContext->current) & 0xf)
{
*gpGcmContext->current = 0;
gpGcmContext->current++;
}
// Send to fifo
uint32 bytesUsed = (uint8*)gpGcmContext->current - (uint8*)gpGcmContext->begin;
gSpuMgr.DmaSync();
gSpuMgr.DmaPut(gpGcmDrawState->m_eaOutputFIFO, (void*)gpGcmContext->begin,
bytesUsed, SPU_DMAPUT_TAG);
gSpuMgr.DmaDone(SPU_DMAPUT_TAG_WAIT);
// Send to SPU mailbox
gSpuMgr.WriteMailbox(gpGcmDrawState->m_eaOutputFIFO + bytesUsed);
}
}
+33
View File
@@ -0,0 +1,33 @@
#ifndef INCLUDED_GCMDRAW_SPU_H
#define INCLUDED_GCMDRAW_SPU_H
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
//
//
//==================================================================================================
//--------------------------------------------------------------------------------------------------
// Headers
//--------------------------------------------------------------------------------------------------
#ifdef SPU
#include "SpuMgr_spu.h"
#else
#include "tier0/platform.h"
#include "tier0/dbg.h"
#include "cell\gcm.h"
#include "SpuMgr_ppu.h"
#endif
//--------------------------------------------------------------------------------------------------
// Defines for the DMA tags
//--------------------------------------------------------------------------------------------------
#define SPU_DMAGET_TAG 0
#define SPU_DMAGET_TAG_WAIT ( 1 << SPU_DMAGET_TAG )
#define SPU_DMAPUT_TAG 1
#define SPU_DMAPUT_TAG_WAIT ( 1 << SPU_DMAPUT_TAG )
#endif // INCLUDED_GCMDRAW_SPU_H
+708
View File
@@ -0,0 +1,708 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
// Per draw call gcm state
//
//==================================================================================================
#define PPU_DRAW 0
#ifndef SPU
#define CELL_GCM_MEMCPY memcpy // PPU SNC has no such intrinsic
#endif
#ifndef SPU
#include "sys/memory.h"
#include "sysutil/sysutil_sysparam.h"
#include "cell/sysmodule.h"
#include "tier0/platform.h"
#include "tier0/dbg.h"
#include "tier1/utlbuffer.h"
#include "cell/gcm.h"
#include "gcmconfig.h"
#include "ps3gcmmemory.h"
#include "gcmstate.h"
#include "gcmlabels.h"
#include "gcmdrawstate.h"
#include "ps3/ps3_helpers.h"
#include <materialsystem/imaterialsystem.h>
#include <vprof.h>
#include "tier0/memdbgon.h"
#else
#include "spumgr_spu.h"
#include "gcmdrawstate.h"
#endif
//--------------------------------------------------------------------------------------------------
// Globals
//--------------------------------------------------------------------------------------------------
ALIGN128 CGcmDrawState gGcmDrawState[GCM_DRAWSTATE_MAX] ALIGN128_POST;
CGcmDrawState* gpGcmDrawState = &gGcmDrawState[0];
int g_bZcullAuto = 1;
int g_nZcullDefault = 100;
int g_nZcullMoveForward = 100;
int g_nZcullPushBack = 100;
SetVertexDataArrayCache_t g_cacheSetVertexDataArray[ D3D_MAX_STREAMS ];
vec_float4 g_aFPConst[GCM_DS_MAXFPCONST] = {0,};
vec_float4 g_aVPConst[GCM_DS_MAXVPCONST] = {0,};
D3DStreamDesc g_dxGcmVertexStreamSources[D3D_MAX_STREAMS];
uint32 g_UPHigh = 0;
uint32 g_UPFrame;
#ifndef SPU
ALIGN16 uint8 g_aDynECB[GCM_DS_MAXDYNECB] ALIGN16_POST; // Ring buffer of dynamic cmds
uint32 g_nDynECBIdx = 0;
#endif
#ifndef SPU
ALIGN128 CGcmDrawState::FixedData gFixedData[GCM_DRAWSTATE_MAX] ALIGN128_POST;
#else
ALIGN128 CGcmDrawState::FixedData gFixedData[1] ALIGN128_POST;
#endif
#ifndef SPU
ALIGN128 uint8 gPackData[GCM_DRAWSTATE_MAX][GCM_DS_MAXDATAPERDRAWCALL] ALIGN128_POST;
#else
ALIGN128 uint8 gPackData[1][GCM_DS_MAXDATAPERDRAWCALL] ALIGN128_POST;
#endif
//--------------------------------------------------------------------------------------------------
// DX lookups etc..
//--------------------------------------------------------------------------------------------------
// THese tables are auto-generated in dxabstract.cpp, UnpackD3DRSITable()
// They provide renderstate classes and their default values....
uint8 g_d3drs_defvalue_indices[D3DRS_VALUE_LIMIT] =
{ 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0300 | 1, 0300 | 2, 0100 | 3, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0300 | 1, 0300 | 0, 0100 | 4, 0000 | 0, 0000 | 0, 0300 | 1, 0300 | 1, 0000 | 0, 0300 | 2, 0300 | 1, 0300 | 0, 0300 | 5, 0100 | 0, 0300 | 1, 0300 | 0, 0100 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0300 | 0, 0300 | 0, 0300 | 0, 0300 | 6, 0300 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0300 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0300 | 0, 0300 | 4, 0300 | 4, 0300 | 4, 0300 | 7, 0300 | 0, 0300 | 8, 0300 | 8, 0100 | 8, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0000 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0200 | 4, 0000 | 0, 0000 | 0, 0100 | 0, 0300 | 0, 0100 | 4, 0100 | 4, 0100 | 0, 0000 | 0, 0100 | 0, 0100 | 3, 0100 | 0, 0100 | 0, 0000 | 0, 0000 | 0, 0100 | 0, 0300 | 0, 0000 | 0, 0100 | 6, 0100 | 6, 0100 | 0, 0100 | 0, 0100 | 6, 0100 | 0, 0100 | 0, 0300 | 4, 0300 | 8, 0100 | 0, 0000 | 0, 0100 | 0, 0100 | 9, 0100 | 0, 0300 | 4, 0000 | 0, 0100 | 0, 0300 | 4, 0100 | 2, 0100 | 4, 0300 | 0, 0300 | 0, 0100 | 0, 0000 | 0, 0100 | 6, 0100 | 6, 0100 | 0, 0100 | 0, 0100 | 6, 0100 | 0, 0100 | 0, 0300 | 0, 0300 | 4, 0300 | 4, 0300 | 4, 0300 | 7, 0300 | 10, 0300 | 10, 0300 | 10, 0100 | 8, 0300 | 0, 0300 | 0, 0000 | 0, 0000 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 0, 0100 | 3, 0100 | 4, 0100 | 4};
uint32 g_d3drs_defvalues[11] =
{ 0x0, 0x31415926, 0x3, 0x2, 0x1, 0x7, 0x3F800000, 0x8, 0xFFFFFFFF, 0x42800000, 0xF };
uint16 dxtogl_blendop[7] =
{
/*invalid*/CELL_GCM_FUNC_ADD,
CELL_GCM_FUNC_ADD,
CELL_GCM_FUNC_SUBTRACT,
CELL_GCM_FUNC_REVERSE_SUBTRACT,
CELL_GCM_MIN,
CELL_GCM_MAX,
/*invalid*/CELL_GCM_FUNC_ADD,
};
uint32 dxtogl_stencilmode[10] =
{
/*invalid*/ CELL_GCM_KEEP,
/*D3DSTENCILOP_KEEP*/ CELL_GCM_KEEP,
/*D3DSTENCILOP_ZERO*/ CELL_GCM_ZERO,
/*D3DSTENCILOP_REPLACE*/ CELL_GCM_REPLACE,
/*D3DSTENCILOP_INCRSAT*/ CELL_GCM_INCR,
/*D3DSTENCILOP_DECRSAT*/ CELL_GCM_DECR,
/*D3DSTENCILOP_INVERT*/ CELL_GCM_INVERT,
/*D3DSTENCILOP_INCR*/ CELL_GCM_INCR_WRAP,
/*D3DSTENCILOP_DECR*/ CELL_GCM_DECR_WRAP,
/*invalid*/ CELL_GCM_KEEP,
};
// addressing modes
// 1 D3DTADDRESS_WRAP Tile the texture at every integer junction.
// D3DTADDRESS_MIRROR Similar to D3DTADDRESS_WRAP, except that the texture is flipped at every integer junction.
// 3 D3DTADDRESS_CLAMP Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively.
// 4 D3DTADDRESS_BORDER Texture coordinates outside the range [0.0, 1.0] are set to the border color.
// D3DTADDRESS_MIRRORONCE Similar to D3DTADDRESS_MIRROR and D3DTADDRESS_CLAMP.
// Takes the absolute value of the texture coordinate (thus, mirroring around 0),
// and then clamps to the maximum value. The most common usage is for volume textures,
// where support for the full D3DTADDRESS_MIRRORONCE texture-addressing mode is not
// necessary, but the data is symmetric around the one axis.
uint8 dxtogl_addressMode[6] =
{
CELL_GCM_TEXTURE_WRAP, // no zero entry
CELL_GCM_TEXTURE_WRAP, // from D3DTADDRESS_WRAP
CELL_GCM_TEXTURE_MIRROR, // from D3DTADDRESS_MIRROR
CELL_GCM_TEXTURE_CLAMP_TO_EDGE, // from D3DTADDRESS_CLAMP
CELL_GCM_TEXTURE_BORDER, // from D3DTADDRESS_BORDER
CELL_GCM_TEXTURE_MIRROR_ONCE_BORDER, // no D3DTADDRESS_MIRRORONCE support
};
uint8 dxtogl_anisoIndexHalf[32] = // indexed by [ dxsamp->maxAniso / 2 ]
{
CELL_GCM_TEXTURE_MAX_ANISO_1, // 0-1
CELL_GCM_TEXTURE_MAX_ANISO_2, // 2-3
CELL_GCM_TEXTURE_MAX_ANISO_4, // 4-5
CELL_GCM_TEXTURE_MAX_ANISO_6, // 6-7
CELL_GCM_TEXTURE_MAX_ANISO_8, // 8-9
CELL_GCM_TEXTURE_MAX_ANISO_10, // 10-11
CELL_GCM_TEXTURE_MAX_ANISO_12, // 12-13
CELL_GCM_TEXTURE_MAX_ANISO_16, // 14-15
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 16
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 18
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 20
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 22
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 24
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 26
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 28
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 30
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 32
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 34
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 36
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 38
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 40
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 42
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 44
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 46
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 48
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 50
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 52
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 54
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 56
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 58
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 60
CELL_GCM_TEXTURE_MAX_ANISO_16, // ... rest >= 62
};
uint8 dxtogl_minFilter[4][4] = // indexed by _D3DTEXTUREFILTERTYPE on both axes: [row is min filter][col is mip filter].
{
/* mip filter ---------------> D3DTEXF_NONE D3DTEXF_POINT D3DTEXF_LINEAR (D3DTEXF_ANISOTROPIC not applicable to mip filter) */
/* min = D3DTEXF_NONE */ { CELL_GCM_TEXTURE_NEAREST, CELL_GCM_TEXTURE_NEAREST_NEAREST, CELL_GCM_TEXTURE_NEAREST_LINEAR, CELL_GCM_TEXTURE_NEAREST }, // D3DTEXF_NONE we just treat like POINT
/* min = D3DTEXF_POINT */ { CELL_GCM_TEXTURE_NEAREST, CELL_GCM_TEXTURE_NEAREST_NEAREST, CELL_GCM_TEXTURE_NEAREST_LINEAR, CELL_GCM_TEXTURE_NEAREST },
/* min = D3DTEXF_LINEAR */ { CELL_GCM_TEXTURE_LINEAR, CELL_GCM_TEXTURE_LINEAR_NEAREST, CELL_GCM_TEXTURE_LINEAR_LINEAR, CELL_GCM_TEXTURE_NEAREST },
/* min = D3DTEXF_ANISOTROPIC */ { CELL_GCM_TEXTURE_LINEAR, CELL_GCM_TEXTURE_LINEAR_NEAREST, CELL_GCM_TEXTURE_LINEAR_LINEAR, CELL_GCM_TEXTURE_NEAREST }, // no diff from prior row, set maxAniso to effect the sampling
};
uint8 dxtogl_magFilter[4] = // indexed by _D3DTEXTUREFILTERTYPE
{
CELL_GCM_TEXTURE_NEAREST, // D3DTEXF_NONE not applicable to mag filter but we handle it like POINT (mat_showmiplevels hits this)
CELL_GCM_TEXTURE_NEAREST, // D3DTEXF_POINT
CELL_GCM_TEXTURE_LINEAR, // D3DTEXF_LINEAR
CELL_GCM_TEXTURE_LINEAR, // D3DTEXF_ANISOTROPIC (aniso will be driven by setting maxAniso, not by a GL filter mode)
};
//--------------------------------------------------------------------------------------------------
// Send to SPU
//--------------------------------------------------------------------------------------------------
#ifndef SPU
int gSpuJobIssued = 0;
uint32 gSpuStartIdx = 0;
uint32 gSpuCount = 0;
//--------------------------------------------------------------------------------------------------
// SPU DRAW CODE
//--------------------------------------------------------------------------------------------------
#if !PPU_DRAW
void CGcmDrawState::SendToSpu()
{
SpuTaskHandle *pTask = &g_ps3gcmGlobalState.m_spuHandle;
// Get this drawcall indx and the next
uint32 idx = gpGcmDrawState - gGcmDrawState;
uint32 nextidx = (idx + 1) % GCM_DRAWSTATE_MAX;
gSpuCount ++;
// Move gpGcmDrawState to the next set of Data
CGcmDrawState* pPrevDrawState = gpGcmDrawState;
gpGcmDrawState = &gGcmDrawState[nextidx];
gpGcmDrawState->m_shaderVxConstants = pPrevDrawState->m_shaderVxConstants;
gpGcmDrawState->m_pPixelShaderData = pPrevDrawState->m_pPixelShaderData;
gpGcmDrawState->m_pVertexShaderData = pPrevDrawState->m_pVertexShaderData;
gpGcmDrawState->m_nBackBufferSize[0] = pPrevDrawState->m_nBackBufferSize[0];
gpGcmDrawState->m_nBackBufferSize[1] = pPrevDrawState->m_nBackBufferSize[1];
gpGcmDrawState->m_pDataCursor = gpGcmDrawState->m_pData;
gpGcmDrawState->m_dirtySamplersMask = 0;
gpGcmDrawState->m_dirtyCachesMask = 0;
gpGcmDrawState->m_dirtyStatesMask = 0;
gpGcmDrawState->m_nFreeLabel = 0;
memset(gpGcmDrawState->m_pFixed->m_aSamplerIdx, 0xff, sizeof(m_pFixed->m_aSamplerIdx));
gpGcmDrawState->m_pFixed->m_nSampler = 0;
gpGcmDrawState->m_pFixed->m_nInstanced = 0;
gpGcmDrawState->m_nNumECB = 0;
memset(gpGcmDrawState->m_aECB, 0, sizeof(m_aECB));
if ( (gSpuCount < 4) && (m_cmd != CmdEndFrame) ) return;
// Send the state(s) to the SPU
// Wait on previous drawcall
if (gSpuJobIssued)
{
uint32 fifoPosn;
gSpuMgr.ReadMailbox(pTask, &fifoPosn);
gpGcmContext->current = (uint32*)fifoPosn;
}
// Makesure we have 16K at least, per drawcall (we issue 4 calls at a time)
cellGcmReserveMethodSizeInline(gpGcmContext, (GCM_DS_FIFOPERDRAW*GCM_NUMDRAWCALLS_SPU)/4); // 16K per draw call, /4 because api takes wordcount
// Makesure FIFO is on a 16B boundary
while (uintp(gpGcmContext->current) & 0xf)
{
*gpGcmContext->current = 0;
gpGcmContext->current++;
}
// Build count and startidx parameter to send to SPU
uint32 mailboxparam = (gSpuCount<<16) | gSpuStartIdx;
//Send this drawstate
m_eaOutputFIFO = (uint32)gpGcmContext->current;
__asm ( "eieio" );
gSpuMgr.WriteMailbox(pTask, mailboxparam);
gSpuJobIssued = 1;
// If it's an endframe, wait for result now
// comment out this if to always wait for the dma to come back
if (m_cmd == CmdEndFrame)
{
uint32 fifoPosn;
gSpuMgr.ReadMailbox(pTask, &fifoPosn);
gpGcmContext->current = (uint32*)fifoPosn;
gSpuJobIssued = 0;
}
gSpuStartIdx = nextidx;
gSpuCount = 0;
}
#else // PPU_DRAW.....
//--------------------------------------------------------------------------------------------------
// Draw on PPU
//--------------------------------------------------------------------------------------------------
void CGcmDrawState::SendToSpu()
{
// Makesure we have 16K at least
cellGcmReserveMethodSizeInline(gpGcmContext, GCM_DS_FIFOPERDRAW/4); // 16K per draw call
// Makesure FIFO is on a 16B boundary
while (uintp(gpGcmContext->current) & 0xf)
{
*gpGcmContext->current = 0;
gpGcmContext->current++;
}
// Process cmd on PPU
switch (m_cmd)
{
case CmdCommitStates:
case CmdEndFrame:
if (m_nFreeLabel) UnpackSetWriteBackEndLabel(GCM_LABEL_MEMORY_FREE, m_nFreeLabel);
if ( m_dirtyStatesMask & kDirtyResetRsx) UnpackResetRsxState();
if (m_dirtyStatesMask & kDirtyZeroAllPSConsts) ZeroFPConsts();
if (m_dirtyStatesMask & kDirtyZeroAllVSConsts) ZeroVPConsts();
UnpackData(); // Pulls out pixel shader consts and sets vertex shader consts
CommitRenderStates();
break;
case CmdDrawPrim:
{
gpGcmDrawState->CommitAll((IDirect3DVertexDeclaration9 *)m_param[0], m_param[1]);
// Draw
GCM_FUNC( cellGcmSetDrawIndexArray,
m_param[2], m_param[5],
CELL_GCM_DRAW_INDEX_ARRAY_TYPE_16, CELL_GCM_LOCATION_LOCAL,
m_param[3] );
}
break;
case CmdDrawPrimUP:
{
D3DStreamDesc &dsd = g_dxGcmVertexStreamSources[0];
dsd.m_offset = 0;
dsd.m_stride = m_param[2];
dsd.m_vtxBuffer = ( IDirect3DVertexBuffer9 * )( uintp )1; // invalid pointer, but non-NULL to signal it's a real vertex buffer;
dsd.m_nLocalBufferOffset = 0;
gpGcmDrawState->CommitAll((IDirect3DVertexDeclaration9 *)m_param[0], 0);
GCM_FUNC(cellGcmSetCallCommand, m_param[1]);
}
break;
}
// Flip to the other set of Data
if (gpGcmDrawState->m_pData == gPackData1)
{
gpGcmDrawState->m_pData = gPackData2;
gpGcmDrawState->m_pFixed = &gFixedData2;
}
else
{
gpGcmDrawState->m_pData = gPackData1;
gpGcmDrawState->m_pFixed = &gFixedData1;
}
gpGcmDrawState->m_pDataCursor = gpGcmDrawState->m_pData;
m_dirtySamplersMask = 0;
m_dirtyCachesMask = 0;
m_dirtyStatesMask = 0;
m_nFreeLabel = 0;
memset(m_pFixed->m_aSamplerIdx, 0xff, sizeof(m_pFixed->m_aSamplerIdx));
m_pFixed->m_nSampler = 0;
m_pFixed->m_nInstanced = 0;
m_nNumECB = 0;
memset(m_aECB, 0, sizeof(m_aECB));
}
#endif // ndef SPU
#endif
//--------------------------------------------------------------------------------------------------
// test func to try to find corrupted ECBs
//--------------------------------------------------------------------------------------------------
void CGcmDrawState::TestCommandBuffer( uint8 *pCmdBuf )
{
uint8* pStart = pCmdBuf;
uint8 *pReturnStack[20];
uint8 **pSP = &pReturnStack[ARRAYSIZE(pReturnStack)];
uint8 *pLastCmd;
for(;;)
{
uint8 *pCmd=pCmdBuf;
int nCmd = GetData<int>( pCmdBuf );
if (nCmd > CBCMD_SET_VERTEX_SHADER_NEARZFARZ_STATE) DebuggerBreak();
switch( nCmd )
{
case CBCMD_END:
{
if ( pSP == &pReturnStack[ARRAYSIZE(pReturnStack)] )
return;
else
{
// pop pc
pCmdBuf = *( pSP ++ );
break;
}
}
case CBCMD_JUMP:
pCmdBuf = GetData<uint8 *>( pCmdBuf + sizeof( int ) );
break;
case CBCMD_JSR:
{
Assert( pSP > &(pReturnStack[0] ) );
// *(--pSP ) = pCmdBuf + sizeof( int ) + sizeof( uint8 *);
// pCmdBuf = GetData<uint8 *>( pCmdBuf + sizeof( int ) );
TestCommandBuffer( GetData<uint8 *>( pCmdBuf + sizeof( int ) ) );
pCmdBuf = pCmdBuf + sizeof( int ) + sizeof( uint8 *);
break;
}
case CBCMD_SET_PIXEL_SHADER_FLOAT_CONST:
{
int nStartConst = GetData<int>( pCmdBuf + sizeof( int ) );
int nNumConsts = GetData<int>( pCmdBuf + 2 * sizeof( int ) );
pCmdBuf += nNumConsts * 4 * sizeof( float ) + 3 * sizeof( int );
break;
}
case CBCMD_SETPIXELSHADERFOGPARAMS:
{
Error("Pixel Shader Fog params not supported\n");
break;
}
case CBCMD_STORE_EYE_POS_IN_PSCONST:
{
pCmdBuf += 2 * sizeof( int ) + sizeof( float );
break;
}
case CBCMD_SET_DEPTH_FEATHERING_CONST:
{
// int nConst = GetData<int>( pCmdBuf + sizeof( int ) );
// float fDepthBlendScale = GetData<float>( pCmdBuf + 2 * sizeof( int ) );
pCmdBuf += 2 * sizeof( int ) + sizeof( float );
// SetDepthFeatheringPixelShaderConstant( nConst, fDepthBlendScale );
break;
}
case CBCMD_SET_VERTEX_SHADER_FLOAT_CONST:
{
int nStartConst = GetData<int>( pCmdBuf + sizeof( int ) );
int nNumConsts = GetData<int>( pCmdBuf + 2 * sizeof( int ) );
float const *pValues = reinterpret_cast< float const *> ( pCmdBuf + 3 * sizeof( int ) );
pCmdBuf += nNumConsts * 4 * sizeof( float ) + 3 * sizeof( int );
break;
}
case CBCMD_BIND_PS3_TEXTURE:
{
CPs3BindTexture_t tex = GetData<CPs3BindTexture_t> (pCmdBuf + sizeof( int ));
if (tex.m_pLmBlock->Offset() & 0x7e) DebuggerBreak();
pCmdBuf += sizeof(int) + sizeof(tex);
break;
}
case CBCMD_BIND_PS3_STANDARD_TEXTURE:
{
CPs3BindTexture_t tex = GetData<CPs3BindTexture_t> (pCmdBuf + sizeof( int ));
if (m_pFixed->m_nInstanced)
{
uint32 nBindFlags = tex.m_nBindFlags;
uint32 nSampler = tex.m_sampler;
switch (tex.m_boundStd)
{
case TEXTURE_LOCAL_ENV_CUBEMAP:
if (m_pFixed->m_nInstanced & GCM_DS_INST_ENVMAP) tex = m_pFixed->m_instanceEnvCubemap;
break;
case TEXTURE_LIGHTMAP:
if (m_pFixed->m_nInstanced & GCM_DS_INST_LIGHTMAP) tex = m_pFixed->m_instanceLightmap;
break;
case TEXTURE_PAINT:
if (m_pFixed->m_nInstanced & GCM_DS_INST_PAINTMAP) tex = m_pFixed->m_instancePaintmap;
break;
}
tex.m_nBindFlags = nBindFlags;
tex.m_sampler = nSampler;
}
// Test texture
if (tex.m_pLmBlock->Offset() & 0x7e) DebuggerBreak();
pCmdBuf += sizeof(int) + sizeof(tex);
break;
}
case CBCMD_PS3TEX:
{
pCmdBuf += sizeof(int) + (CBCMD_MAX_PS3TEX*sizeof(int));
break;
}
case CBCMD_LENGTH:
{
pCmdBuf += sizeof(int) *2 ;
break;
}
case CBCMD_SET_PSHINDEX:
{
// int nIdx = GetData<int>( pCmdBuf + sizeof( int ) );
// ShaderManager()->SetPixelShaderIndex( nIdx );
// pCmdBuf += 2 * sizeof( int );
Error("PSHINDEX Not Supported\n");
break;
}
case CBCMD_SET_VSHINDEX:
{
// int nIdx = GetData<int>( pCmdBuf + sizeof( int ) );
// ShaderManager()->SetVertexShaderIndex( nIdx );
pCmdBuf += 2 * sizeof( int );
Error("VSHINDEX Not Supported\n");
break;
}
case CBCMD_SET_VERTEX_SHADER_FLASHLIGHT_STATE:
{
// int nStartConst = GetData<int>( pCmdBuf + sizeof( int ) );
// SetVertexShaderConstantInternal( nStartConst, m_FlashlightWorldToTexture.Base(), 4, false );
// pCmdBuf += 2 * sizeof( int );
// Error("Flashlight unsupported\n");
pCmdBuf += 2 * sizeof( int );
break;
}
case CBCMD_SET_VERTEX_SHADER_NEARZFARZ_STATE:
{
Error("SetVertexShaderNearAndFarZ NOt SUPPORTED\n");
// int nStartConst = GetData<int>( pCmdBuf + sizeof( int ) );
//
// VMatrix m;
//
// m = m_MaterialProjectionMatrix;
//
// // GetMatrix( MATERIAL_PROJECTION, m.m[0] );
//
// // m[2][2] = F/(N-F) (flip sign if RH)
// // m[3][2] = NF/(N-F)
//
// float vNearFar[4];
//
// float N = m[3][2] / m[2][2];
// float F = (m[3][2]*N) / (N + m[3][2]);
//
// vNearFar[0] = N;
// vNearFar[1] = F;
//
// SetVertexShaderConstantInternal( nStartConst, vNearFar, 1, false );
pCmdBuf += 2 * sizeof( int );
break;
}
case CBCMD_SET_PIXEL_SHADER_FLASHLIGHT_STATE:
{
// int nLightSampler = GetData<int>( pCmdBuf + sizeof( int ) );
// int nDepthSampler = GetData<int>( pCmdBuf + 2 * sizeof( int ) );
// int nShadowNoiseSampler = GetData<int>( pCmdBuf + 3 * sizeof( int ) );
// int nColorConst = GetData<int>( pCmdBuf + 4 * sizeof( int ) );
// int nAttenConst = GetData<int>( pCmdBuf + 5 * sizeof( int ) );
// int nOriginConst = GetData<int>( pCmdBuf + 6 * sizeof( int ) );
// int nDepthTweakConst = GetData<int>( pCmdBuf + 7 * sizeof( int ) );
// int nScreenScaleConst = GetData<int>( pCmdBuf + 8 * sizeof( int ) );
// int nWorldToTextureConstant = GetData<int>( pCmdBuf + 9 * sizeof( int ) );
// bool bFlashlightNoLambert = GetData<int>( pCmdBuf + 10 * sizeof( int ) ) != 0;
// bool bSinglePassFlashlight = GetData<int>( pCmdBuf + 11 * sizeof( int ) ) != 0;
// pCmdBuf += 12 * sizeof( int );
//
// ShaderAPITextureHandle_t hTexture = g_pShaderUtil->GetShaderAPITextureBindHandle( m_FlashlightState.m_pSpotlightTexture, m_FlashlightState.m_nSpotlightTextureFrame, 0 );
// BindTexture( (Sampler_t)nLightSampler, TEXTURE_BINDFLAGS_SRGBREAD, hTexture ); // !!!BUG!!!srgb or not?
//
// SetPixelShaderConstantInternal( nAttenConst, m_pFlashlightAtten, 1, false );
// SetPixelShaderConstantInternal( nOriginConst, m_pFlashlightPos, 1, false );
//
// m_pFlashlightColor[3] = bFlashlightNoLambert ? 2.0f : 0.0f; // This will be added to N.L before saturate to force a 1.0 N.L term
//
// // DX10 hardware and single pass flashlight require a hack scalar since the flashlight is added in linear space
// float flashlightColor[4] = { m_pFlashlightColor[0], m_pFlashlightColor[1], m_pFlashlightColor[2], m_pFlashlightColor[3] };
// if ( ( g_pHardwareConfig->UsesSRGBCorrectBlending() ) || ( bSinglePassFlashlight ) )
// {
// // Magic number that works well on the 360 and NVIDIA 8800
// flashlightColor[0] *= 2.5f;
// flashlightColor[1] *= 2.5f;
// flashlightColor[2] *= 2.5f;
// }
//
// SetPixelShaderConstantInternal( nColorConst, flashlightColor, 1, false );
//
// if ( nWorldToTextureConstant >= 0 )
// {
// SetPixelShaderConstantInternal( nWorldToTextureConstant, m_FlashlightWorldToTexture.Base(), 4, false );
// }
//
// BindStandardTexture( (Sampler_t)nShadowNoiseSampler, TEXTURE_BINDFLAGS_NONE, TEXTURE_SHADOW_NOISE_2D );
// if( m_pFlashlightDepthTexture && m_FlashlightState.m_bEnableShadows && ShaderUtil()->GetConfig().ShadowDepthTexture() )
// {
// ShaderAPITextureHandle_t hDepthTexture = g_pShaderUtil->GetShaderAPITextureBindHandle( m_pFlashlightDepthTexture, 0, 0 );
// BindTexture( (Sampler_t)nDepthSampler, TEXTURE_BINDFLAGS_SHADOWDEPTH, hDepthTexture );
//
// SetPixelShaderConstantInternal( nDepthTweakConst, m_pFlashlightTweaks, 1, false );
//
// // Dimensions of screen, used for screen-space noise map sampling
// float vScreenScale[4] = {1280.0f / 32.0f, 720.0f / 32.0f, 0, 0};
// int nWidth, nHeight;
// BaseClass::GetBackBufferDimensions( nWidth, nHeight );
//
// int nTexWidth, nTexHeight;
// GetStandardTextureDimensions( &nTexWidth, &nTexHeight, TEXTURE_SHADOW_NOISE_2D );
//
// vScreenScale[0] = (float) nWidth / nTexWidth;
// vScreenScale[1] = (float) nHeight / nTexHeight;
// vScreenScale[2] = 1.0f / m_FlashlightState.m_flShadowMapResolution;
// vScreenScale[3] = 2.0f / m_FlashlightState.m_flShadowMapResolution;
// SetPixelShaderConstantInternal( nScreenScaleConst, vScreenScale, 1, false );
// }
// else
// {
// BindStandardTexture( (Sampler_t)nDepthSampler, TEXTURE_BINDFLAGS_NONE, TEXTURE_WHITE );
// }
// Error("Flashlight unsupported\n");
pCmdBuf += 12 * sizeof( int );
break;
}
case CBCMD_SET_PIXEL_SHADER_UBERLIGHT_STATE:
{
// int iEdge0Const = GetData<int>( pCmdBuf + sizeof( int ) );
// int iEdge1Const = GetData<int>( pCmdBuf + 2 * sizeof( int ) );
// int iEdgeOOWConst = GetData<int>( pCmdBuf + 3 * sizeof( int ) );
// int iShearRoundConst = GetData<int>( pCmdBuf + 4 * sizeof( int ) );
// int iAABBConst = GetData<int>( pCmdBuf + 5 * sizeof( int ) );
// int iWorldToLightConst = GetData<int>( pCmdBuf + 6 * sizeof( int ) );
pCmdBuf += 7 * sizeof( int );
//
// SetPixelShaderConstantInternal( iEdge0Const, m_UberlightRenderState.m_vSmoothEdge0.Base(), 1, false );
// SetPixelShaderConstantInternal( iEdge1Const, m_UberlightRenderState.m_vSmoothEdge1.Base(), 1, false );
// SetPixelShaderConstantInternal( iEdgeOOWConst, m_UberlightRenderState.m_vSmoothOneOverW.Base(), 1, false );
// SetPixelShaderConstantInternal( iShearRoundConst, m_UberlightRenderState.m_vShearRound.Base(), 1, false );
// SetPixelShaderConstantInternal( iAABBConst, m_UberlightRenderState.m_vaAbB.Base(), 1, false );
// SetPixelShaderConstantInternal( iWorldToLightConst, m_UberlightRenderState.m_WorldToLight.Base(), 4, false );
Error("Uberlight state unsupported\n");
break;
}
#ifndef NDEBUG
default:
Assert(0);
break;
#endif
}
pLastCmd = pCmd;
}
}
File diff suppressed because it is too large. Load diff
+56
View File
@@ -0,0 +1,56 @@
//================ Copyright (c) 1996-2010 Valve Corporation. All Rights Reserved. =================
#ifndef PS3GCMFUNC_H
#define PS3GCMFUNC_H
// this is the buffer that all PPU GCM functions assume is the normal command buffer,
// but it is not in IO-mapped memory and it's the SPU that picks up and submits it to RSX.
// it's a level of indirection necessary to interleave SPU and PPU calls to GCM
#define GCM_CTX gCellGcmCurrentContext
#if GCM_CTX_UNSAFE_MODE
#error "This mode is not supported any more. Use SPU draw mode."
#endif
extern int32_t SpuGcmCommandBufferReserveCallback( struct CellGcmContextData *context, uint32_t nCount );
#define GCM_CTX_RESERVE( WORDS ) SpuGcmCommandBufferReserveCallback( GCM_CTX, WORDS )
#define GCM_FUNC_NOINLINE( GCM_FUNCTION, ...) GCM_FUNCTION( GCM_CTX, ##__VA_ARGS__ )
#ifdef _CERT
#define GCM_PERF_RANGE( NAME )
#define GCM_PERF_PUSH_MARKER( NAME )
#define GCM_PERF_POP_MARKER( )
#define GCM_PERF_MARKER( NAME )
#else
class CGcmPerfAutoRange
{
public:
CGcmPerfAutoRange( const char * pName ){ GCM_FUNC_NOINLINE( cellGcmSetPerfMonPushMarker, pName ); }
~CGcmPerfAutoRange( ){ GCM_FUNC_NOINLINE( cellGcmSetPerfMonPopMarker ); }
};
#define GCM_PERF_RANGE( NAME ) CGcmPerfAutoRange _gcmAutoRange( NAME )
#define GCM_PERF_PUSH_MARKER( NAME ) GCM_FUNC_NOINLINE( cellGcmSetPerfMonPushMarker, NAME )
#define GCM_PERF_POP_MARKER( ) GCM_FUNC_NOINLINE( cellGcmSetPerfMonPopMarker )
#define GCM_PERF_MARKER( NAME ) GCM_FUNC_NOINLINE( cellGcmSetPerfMonMarker, ( NAME ) )
#endif
#define GCM_FUNC( GCM_FUNCTION, ...) \
{ \
uint nReserveWords = GCM_FUNCTION ## MeasureSizeInline( 0, ##__VA_ARGS__ ); \
GCM_CTX_RESERVE( nReserveWords ); \
GCM_FUNCTION ## UnsafeInline( GCM_CTX, ##__VA_ARGS__ ); \
}
extern void SpuGcmCommandBufferFlush();
#define GCM_CTX_FLUSH_CHECKPOINT() void SpuGcmCommandBufferFlush()
#define cellGcmFlush must_use_____g_ps3gcmGlobalState_CmdBufferFlush
#endif
+36
View File
@@ -0,0 +1,36 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
// Labels etc..
//
//==================================================================================================
#ifndef INCLUDED_GCMLABELS_H
#define INCLUDED_GCMLABELS_H
enum GcmLabelEnum_t
{
GCM_LABEL_QUERY_FIRST = 64, // GCM reserves the first 64 labels, do not use them
GCM_LABEL_QUERY_LAST = GCM_LABEL_QUERY_FIRST + 99, // the last query label, inclusive
GCM_LABEL_FPPATCH_RING_SEG = 252,
GCM_LABEL_CALL_CMD_RING_SEG = 253, // Ring command buffer for DrawPrimUP and similar
GCM_LABEL_FLIP_CONTROL = 254,
GCM_LABEL_MEMORY_FREE = 255 // 255 is the very last possible index of a label
};
enum GcmReportEnum_t
{
// Used for occlusion queries
GCM_REPORT_QUERY_FIRST = 0,
GCM_REPORT_QUERY_LAST = GCM_REPORT_QUERY_FIRST + 512,
// Used for RSX perf monitoring ... Four timestamps. Start and finish of this frame. Start and finish of previous frame
GCM_REPORT_TIMESTAMP_FRAME_FIRST,
GCM_REPORT_TIMESTAMP_FRAME_LAST = GCM_REPORT_TIMESTAMP_FRAME_FIRST + 3,
// Used for Zcull stats
GCM_REPORT_ZCULL_STATS_0,
GCM_REPORT_ZCULL_STATS_1,
};
#endif // INCLUDED_GCMLABELS_H
+848
View File
@@ -0,0 +1,848 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
// Gcm renderer state and util functions
//
//==================================================================================================
#ifndef SPU
#define CELL_GCM_MEMCPY memcpy // PPU SNC has no such intrinsic
#endif
#include "sys/memory.h"
#include "sysutil/sysutil_sysparam.h"
#include "cell/sysmodule.h"
#include "tier0/platform.h"
#include "tier0/dbg.h"
#include "tier1/utlbuffer.h"
#include "cell/gcm.h"
#include "gcmconfig.h"
#include "ps3gcmmemory.h"
#include "gcmstate.h"
#include "gcmlabels.h"
#include "gcmdrawstate.h"
#include "ps3/ps3_helpers.h"
#include <cell/gem.h> // PS3 move controller lib
#include "inputsystem/iinputsystem.h"
#include "memdbgon.h"
//--------------------------------------------------------------------------------------------------
// Golobals, GCM context, flip control init proto
//--------------------------------------------------------------------------------------------------
ALIGN128 CPs3gcmGlobalState g_ps3gcmGlobalState ALIGN128_POST;
ALIGN16 CellGcmContextData gGcmContext ALIGN16_POST;
CellGcmContextData* gpGcmContext;
CellGcmContextData gCallContext;
CellGcmContextData* gpCallContext = &gCallContext;
static void Gcm_InitFlipControl(void);
static volatile uint32_t *s_label_call_cmd_ring_seg; // pointer to the call cmd label
volatile uint32_t *g_label_fppatch_ring_seg; // Fp pacth label
//--------------------------------------------------------------------------------------------------
// Empty Ps
//--------------------------------------------------------------------------------------------------
uint8 g_dataShaderPsEmpty[] = {
0x00, 0x00, 0x1B, 0x5C, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB0, 0x00, 0x00, 0x00, 0x01
, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x80
, 0x00, 0x00, 0x04, 0x18, 0x00, 0x00, 0x0A, 0xC5, 0x00, 0x00, 0x10, 0x05, 0xFF, 0xFF, 0xFF, 0xFF
, 0x00, 0x00, 0x00, 0x56, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50
, 0x00, 0x00, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00
, 0x43, 0x4F, 0x4C, 0x4F, 0x52, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF
, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
, 0x1E, 0x7E, 0x7E, 0x00, 0xC8, 0x00, 0x1C, 0x9D, 0xC8, 0x00, 0x00, 0x01, 0xC8, 0x00, 0x00, 0x01
, 0x1E, 0x01, 0x01, 0x00, 0x28, 0x02, 0x1C, 0x9C, 0xC8, 0x00, 0x00, 0x01, 0xC8, 0x00, 0x00, 0x01
, 0x00, 0x00, 0x3F, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
//--------------------------------------------------------------------------------------------------
// Global GCM state class
//
// Global state, command buffers, RSX draw display buffers etc etc
//--------------------------------------------------------------------------------------------------
int32 CPs3gcmGlobalState::Init()
{
MEM_ALLOC_CREDIT_( "GCM INIT" );
Msg(">>>> Sizeof(CGcmDrawStateDma) %d \n", DRAWSTATE_SIZEOFDMA);
Msg(">>>> Sizeof(CGcmDrawState) %d \n", sizeof(CGcmDrawState));
// Create Raw SPU task for renderer acceleration
gSpuMgr.Init(1);
gSpuMgr.CreateSpuTask("rawspu_gcmdraw_spu.self", &m_spuHandle);
// Default to 60Hz
m_flipMode = 30;
// Video : display res, video buffer, gamma, RGB colour range
if( int nError= InitVideo() )
return nError;
// Alloc IO memory, Set address, size of main memory pool for RSX
CreateIoBuffers();
// Init GCM : Map IO memory, Create command buffers
if( int nError = InitGcm() )
return nError;
// Retrieve RSX local memory config
CellGcmConfig rsxConfig;
cellGcmGetConfiguration( &rsxConfig );
m_pLocalBaseAddress = rsxConfig.localAddress;
m_nLocalSize = rsxConfig.localSize;
cellGcmAddressToOffset( m_pLocalBaseAddress, &m_nLocalBaseOffset );
Assert( m_nLocalBaseOffset == 0 );
// Init local memory mgr
Ps3gcmLocalMemoryAllocator_Init();
// Create display buffers etc..
CreateRsxBuffers();
// Create Empty PS
m_pShaderPsEmpty = reinterpret_cast< CgBinaryProgram * >( g_dataShaderPsEmpty );
m_pShaderPsEmptyBuffer.Alloc( kAllocPs3GcmShader, m_pShaderPsEmpty->ucodeSize );
V_memcpy( m_pShaderPsEmptyBuffer.DataInLocalMemory(), ( (char*)m_pShaderPsEmpty ) + m_pShaderPsEmpty->ucode, m_pShaderPsEmpty->ucodeSize );
CgBinaryFragmentProgram *pCgFragmentProgram = ( CgBinaryFragmentProgram * )( uintp( m_pShaderPsEmpty ) + m_pShaderPsEmpty->program );
m_nPsEmptyAttributeInputMask = pCgFragmentProgram->attributeInputMask;
uint registerCount = pCgFragmentProgram->registerCount;
// NOTE: actual register count can be modified by specifying an artificial e.g. PS3REGCOUNT48 static combo to force it to 48
Assert( registerCount <= 48 );
if (registerCount < 2)
{
// register count must be [2, 48]
registerCount = 2;
}
uint8_t controlTxp = CELL_GCM_FALSE;
uint32 shCtrl0 = ( CELL_GCM_COMMAND_CAST( controlTxp ) << CELL_GCM_SHIFT_SET_SHADER_CONTROL_CONTROL_TXP )
& CELL_GCM_MASK_SET_SHADER_CONTROL_CONTROL_TXP;
shCtrl0 |= ( 1<<10 ) | ( registerCount << 24 );
shCtrl0 |= pCgFragmentProgram->depthReplace ? 0xE : 0x0;
shCtrl0 |= pCgFragmentProgram->outputFromH0 ? 0x00 : 0x40;
shCtrl0 |= pCgFragmentProgram->pixelKill ? 0x80 : 0x00;
m_nPsEmptyShaderControl0 = shCtrl0;
// Init glip control
m_fastFlip = 0;
Gcm_InitFlipControl();
// Address of draw states
m_eaDrawStates = uintp(gGcmDrawState);
// Give SPU program this class
gSpuMgr.WriteMailbox(&m_spuHandle, uintp(this));
return CELL_OK;
}
void CPs3gcmGlobalState::CreateIoBuffers()
{
m_nIoSize = GCM_IOSIZE;
if ((m_nIoSize & 0xFFFFF) != 0) // MB aligned
{
Error("No MB alignment %x\n\n", m_nIoSize);
}
// Try to allocate main memory that will be mapped to IO address space
// Actually mapped in in GcmInit, once gcm is going
sys_addr_t pIoAddress = NULL;
int nError = sys_memory_allocate( m_nIoSize, SYS_MEMORY_PAGE_SIZE_1M, &pIoAddress );
if ( CELL_OK != nError )
{
Error( "sys_memory_allocate failed to allocate %d bytes (err: %d)\n", m_nIoSize, nError );
}
m_pIoAddress = (void *)pIoAddress;
Msg( "======== GCM IO memory allocated @0x%p size = %d MB ========\n", m_pIoAddress, m_nIoSize / 1024 / 1024 );
// Call command buffer
m_pCallCmdBuffer = (void*)(uintp(pIoAddress) + GCM_DEFCMDBUFFSIZE);
// RSX main memory pool buffer
m_nRsxMainMemoryPoolBufferSize = GCM_MAINPOOLSIZE;
m_pRsxMainMemoryPoolBuffer = (void*)(uintp(pIoAddress) + GCM_DEFCMDBUFFSIZE + GCM_CALLCMDBUFFSIZE);
// Patch buffers
m_pPatchBuff = (uint8*)m_pRsxMainMemoryPoolBuffer + GCM_MAINPOOLSIZE;
}
int CPs3gcmGlobalState::InitGcm()
{
int32 result = cellGcmInit( GCM_DEFCMDBUFFSIZE, m_nIoSize, m_pIoAddress );
if ( result < CELL_OK )
return result;
gGcmContext = *gCellGcmCurrentContext;
gpGcmContext = &gGcmContext;
gpGcmContext->callback = CmdBufferFull;
// Set the flip mode etc...
// Get the offset delta
cellGcmAddressToOffset( m_pIoAddress, &m_nIoOffsetDelta );
m_nIoOffsetDelta -= uintp( m_pIoAddress );
// Setup call cmd buffer
m_nCallCmdBufferoffset = uintp(m_pCallCmdBuffer) + m_nIoOffsetDelta;
m_nCallWritePos = 0;
m_nCallReadSegment = 0;
s_label_call_cmd_ring_seg = cellGcmGetLabelAddress(GCM_LABEL_CALL_CMD_RING_SEG);
*s_label_call_cmd_ring_seg = 0;
// Setup Patch Buffers
m_nPatchIdx = 0;
m_nPatchReadSeg = 0;
g_label_fppatch_ring_seg = cellGcmGetLabelAddress(GCM_LABEL_FPPATCH_RING_SEG);
*g_label_fppatch_ring_seg = 0;
return CELL_OK;
}
int CPs3gcmGlobalState::InitVideo()
{
//////////////////////////////////////////////////////////////////////////
//
// Initialize m_display
//
CellVideoOutState videoOutState;
int result = cellVideoOutGetState( CELL_VIDEO_OUT_PRIMARY, 0, &videoOutState);
if ( result < CELL_OK )
return result;
CellVideoOutResolution resolution;
result = cellVideoOutGetResolution( videoOutState.displayMode.resolutionId, &resolution );
if ( result < CELL_OK )
return result;
// Always output scanout in system m_display resolution
m_nRenderSize[0] = resolution.width;
m_nRenderSize[1] = resolution.height;
// Handle special case: 1080p will be upsampled from 720p
if ( resolution.height >= 720 && CommandLine()->FindParm( "-480p" ) )
{
m_nRenderSize[0] = 640;
m_nRenderSize[1] = 480;
videoOutState.displayMode.resolutionId = CELL_VIDEO_OUT_RESOLUTION_480;
}
else if ( resolution.height >= 1080 && !CommandLine()->FindParm( "-1080p" ) )
{
m_nRenderSize[0] = 1280;
m_nRenderSize[1] = 720;
videoOutState.displayMode.resolutionId = CELL_VIDEO_OUT_RESOLUTION_720;
}
//////////////////////////////////////////////////////////////////////////
//
// Set video output
//
CellVideoOutConfiguration videocfg;
memset( &videocfg, 0, sizeof(videocfg) );
videocfg.resolutionId = videoOutState.displayMode.resolutionId;
videocfg.format = CELL_VIDEO_OUT_BUFFER_COLOR_FORMAT_X8R8G8B8;
videocfg.pitch = cellGcmGetTiledPitchSize( m_nRenderSize[0] * 4 );
m_nSurfaceRenderPitch = videocfg.pitch;
// Configure video output
result = cellVideoOutConfigure( CELL_VIDEO_OUT_PRIMARY, &videocfg, NULL, 0 );
if ( result < CELL_OK )
return result;
// Get the new video output
result = cellVideoOutGetState( CELL_VIDEO_OUT_PRIMARY, 0, &videoOutState );
if ( result < CELL_OK )
return result;
m_flRenderAspect = ( videoOutState.displayMode.aspect == CELL_VIDEO_OUT_ASPECT_4_3 ) ? ( 4.0f/3.0f ) : ( 16.0f / 9.0f );
// Set the gamma to deal with TV's having a darker gamma than computer monitors
result = cellSysmoduleLoadModule( CELL_SYSMODULE_AVCONF_EXT );
if ( result == CELL_OK )
{
cellVideoOutSetGamma( CELL_VIDEO_OUT_PRIMARY, 2.2f / 2.5f );
}
else
{
Warning( "***** ERROR calling cellSysmoduleLoadModule( CELL_SYSMODULE_AVCONF_EXT )! Gamma not set!\n" );
return result;
}
// Output video color settings
CellVideoOutDeviceInfo info;
cellVideoOutGetDeviceInfo( CELL_VIDEO_OUT_PRIMARY, 0, &info );
if ( info.rgbOutputRange == CELL_VIDEO_OUT_RGB_OUTPUT_RANGE_LIMITED )
{
DevMsg( "***** Video Out - Limited Range (16-235) - Gamma=%d *****\n", info.colorInfo.gamma );
}
else
{
DevMsg( "***** Video Out - Full Range (0-255) - Gamma=%d *****\n", info.colorInfo.gamma );
}
return CELL_OK;
}
void CPs3gcmGlobalState::CreateRsxBuffers()
{
//////////////////////////////////////////////////////////////////////////
//
// Create automatic display objects
//
if( m_nSurfaceRenderPitch != cellGcmGetTiledPitchSize( m_nRenderSize[0] * 4 ) )
{
Error("Pre-computed surface render pitch %u != %u = cellGcmGetTiledPitchSize( %u * 4 ) ", m_nSurfaceRenderPitch, cellGcmGetTiledPitchSize( m_nRenderSize[0] * 4 ), m_nRenderSize[0] );
}
m_display.surfaceFlipIdx = 0;
// Color buffers
for ( int k = 0; k < ARRAYSIZE( m_display.surfaceColor ); ++ k )
{
uint32 nRenderSize32bpp = GetRenderSurfaceBytes(); // 32-line vertical alignment required in local memory
m_display.surfaceColor[k].Alloc( kAllocPs3gcmColorBufferFB, nRenderSize32bpp );
cellGcmSetDisplayBuffer( k, m_display.surfaceColor[k].Offset(), m_nSurfaceRenderPitch, m_nRenderSize[0], m_nRenderSize[1] );
}
// Depth buffer
{
uint32 zcullSize[2] = { AlignValue( m_nRenderSize[0], 64 ), AlignValue( m_nRenderSize[1], 64 ) };
uint32 nDepthPitch = cellGcmGetTiledPitchSize( zcullSize[0] * 4 );
uint32 uDepthBufferSize32bpp = nDepthPitch * zcullSize[1];
uDepthBufferSize32bpp = AlignValue( uDepthBufferSize32bpp, PS3GCMALLOCATIONALIGN( kAllocPs3gcmDepthBuffer ) );
m_display.surfaceDepth.Alloc( kAllocPs3gcmDepthBuffer, uDepthBufferSize32bpp );
uint32 uiZcullIndex = m_display.surfaceDepth.ZcullMemoryIndex();
cellGcmBindZcull( uiZcullIndex,
m_display.surfaceDepth.Offset(),
zcullSize[0], zcullSize[1],
m_display.surfaceDepth.ZcullMemoryStart(),
CELL_GCM_ZCULL_Z24S8,
CELL_GCM_SURFACE_CENTER_1,
CELL_GCM_ZCULL_LESS,
CELL_GCM_ZCULL_LONES,
CELL_GCM_SCULL_SFUNC_ALWAYS,
0, 0 // sRef, sMask
);
uint32 uiTileIndex = m_display.surfaceDepth.TiledMemoryIndex();
cellGcmSetTileInfo( uiTileIndex, CELL_GCM_LOCATION_LOCAL, m_display.surfaceDepth.Offset(),
uDepthBufferSize32bpp, m_nSurfaceRenderPitch, CELL_GCM_COMPMODE_Z32_SEPSTENCIL_REGULAR,
m_display.surfaceDepth.TiledMemoryTagAreaBase(), // The area base + size/0x10000 will be allocated as the tag area.
3 ); // Default depth buffer on bank 3
cellGcmBindTile( uiTileIndex );
}
}
void CPs3gcmGlobalState::Shutdown()
{
gpGcmDrawState->EndFrame();
gpGcmDrawState->CmdBufferFinish();
cellGcmSetFlipHandler(NULL);
cellGcmSetVBlankHandler(NULL);
cellSysmoduleUnloadModule( CELL_SYSMODULE_AVCONF_EXT );
}
//--------------------------------------------------------------------------------------------------
// DawPrimUp code...
//--------------------------------------------------------------------------------------------------
uint32 CPs3gcmGlobalState::DrawPrimitiveUP(D3DPRIMITIVETYPE nPrimitiveType,UINT nPrimitiveCount,
CONST void *pVertexStreamZeroData, UINT nVertexStreamZeroStride )
{
// First Determine size required for this call
uint32 size = 0;
uint32 nIndexCount = GetGcmCount( nPrimitiveType, nPrimitiveCount );
uint32 nDataWords = ( nVertexStreamZeroStride * nIndexCount + 3 ) / sizeof( uint32 );
size = cellGcmSetWriteTextureLabelMeasureSize(size, GCM_LABEL_CALL_CMD_RING_SEG, 0 );
size = cellGcmSetInvalidateVertexCacheMeasureSize(size);
size = cellGcmSetDrawInlineArrayMeasureSize(size, GetGcmMode( nPrimitiveType ), nDataWords, pVertexStreamZeroData );
size = cellGcmSetReturnCommandMeasureSize(size);
size *=4;
// Check there is no space in the current segment
uint32 endPos, nextSeg, readSeg, writeSeg;
endPos = m_nCallWritePos + size;
writeSeg = m_nCallWritePos/GCM_CALLCMDSEGSIZE;
if ((endPos/GCM_CALLCMDSEGSIZE) != writeSeg)
{
// Move to the next segment
uint32 nextSeg = (writeSeg + 1) % (GCM_CALLCMDBUFFSIZE / GCM_CALLCMDSEGSIZE);
// Wait for RSX to not be in this segment
readSeg = m_nCallReadSegment;
if(nextSeg == readSeg) readSeg = *s_label_call_cmd_ring_seg;
gpGcmDrawState->CmdBufferFlush();
uint32 spins = 0;
while(nextSeg == readSeg)
{
spins++;
sys_timer_usleep(60);
readSeg = *s_label_call_cmd_ring_seg;
}
//if (spins > 1) Msg("Spins %d\n", spins);
// Move to next segmend abnd record new readSeg
m_nCallWritePos = (nextSeg * GCM_CALLCMDSEGSIZE);
writeSeg = nextSeg;
m_nCallReadSegment = readSeg;
// Msg("new Segment 0x%x\n", m_nCallWritePos);
}
uint32 ret = m_nCallWritePos + uintp(m_pCallCmdBuffer);
// Write Data
// Setup a context to do so
CellGcmContextData context;
context.begin = (uint32*)m_pCallCmdBuffer;
context.current = (uint32*)((uint8*)m_pCallCmdBuffer + m_nCallWritePos);
context.end = (uint32*)((uint8*)m_pCallCmdBuffer + GCM_CALLCMDBUFFSIZE);
context.callback = 0;
cellGcmSetWriteTextureLabelUnsafeInline(&context, GCM_LABEL_CALL_CMD_RING_SEG, writeSeg );
cellGcmSetInvalidateVertexCacheUnsafeInline(&context);
cellGcmSetDrawInlineArrayUnsafeInline(&context, GetGcmMode( nPrimitiveType ), nDataWords, pVertexStreamZeroData );
cellGcmSetReturnCommandUnsafeInline(&context);
// Update pointers
m_nCallWritePos += size;
return ret;
}
//--------------------------------------------------------------------------------------------------
// Command Buffer callback
//--------------------------------------------------------------------------------------------------
#define SEGSIZE 0x40000
#define SEGMASK 0x3FFFF
int32 CPs3gcmGlobalState::CmdBufferFull(struct CellGcmContextData * pGcmContext, uint32_t size)
{
// move to next SEGSIZE, and then wrap to start
// Determine where the next buffer will be
uint32 nIoAddress = (uint32)g_ps3gcmGlobalState.m_pIoAddress;
uint32 nextBufferStart = ((uint32)pGcmContext->begin + SEGSIZE) & (~SEGMASK);
nextBufferStart -= nIoAddress;
nextBufferStart &= (GCM_DEFCMDBUFFSIZE-1);
nextBufferStart = nextBufferStart ? (nextBufferStart + nIoAddress) : (SEGSIZE + nIoAddress);
// Flush RSX to this point
cellGcmFlushUnsafeInline(pGcmContext);
// put jump command to beginning of next buffer
uint32 nextBufferOffset = nextBufferStart - nIoAddress;
uint32 nextBufferEndOffset = ((nextBufferOffset + SEGSIZE) & (~SEGMASK)) - 4;
cellGcmSetJumpCommandUnsafeInline(pGcmContext, nextBufferStart - nIoAddress );
// get put/get/ref register address
volatile CellGcmControl* control = cellGcmGetControlRegister();
int count = 500000;
// wait for RSX to finish all commands in next buffer (it's a ring buffer)
volatile uint32_t get = (volatile uint32_t)control->get;
while( (get < 0x1000 ) || ( (get >= nextBufferOffset) && (get < nextBufferEndOffset) ) )
{
sys_timer_usleep( 30 );
get = (volatile uint32_t)control->get;
// count--;
// if (count < 1)
// {
// Msg("\n*****>>>> CmdBufferFull : get 0x%x : nextBufferOffset 0x%x : nextBufferEndOffset 0x%x\n", get, nextBufferOffset, nextBufferEndOffset );
// count = 1;
// }
}
// Set Command buffer context struct
pGcmContext->begin = (uint32*)nextBufferStart;
pGcmContext->end = (uint32*)(nextBufferEndOffset + nIoAddress);
pGcmContext->current = (uint32*)nextBufferStart;
return CELL_OK;
}
//--------------------------------------------------------------------------------------------------
// Flip Control
//
// Summary :
//
// Label used to cap the framerate. ie label to ensure flips no faster than 1 (60hz) or 2 (30Hz) vblanks.
// PPU blocks if previous flip not complete, so can't run too far ahead
// vblanks and flips noted by callbacks
//--------------------------------------------------------------------------------------------------
enum {
LABEL_FLIP_CONTROL_READY=1, // when label-before-flip is released
LABEL_FLIP_CONTROL_WAIT, // when label-before-flip is not released
/*
label_flip_control:
LABEL_FLIP_CONTROL_WAIT
=> (when releasing flip by ppu) => LABEL_FLIP_CONTROL_READY,
=> (when flip is finished by rsx) => LABEL_FLIP_CONTROL_WAIT,
*/
FLIP_STATE_V1=1,
FLIP_STATE_FLIP_RELEASED,
FLIP_STATE_FLIPPED,
/*
flip_status sequence (30fps or slower):
FLIP_STATE_FLIPPED
(at vblank callback) => FLIP_STATE_V1
(at vblank callback) =<release flip>=> FLIP_STATE_FLIP_RELEASED
(at flip callback) => FLIP_STATE_FLIPPED
*/
/*
flip_status sequence (60fps or slower):
FLIP_STATE_FLIPPED
(at vblank callback) =<release flip>=> FLIP_STATE_FLIP_RELEASED
(at flip callback) => FLIP_STATE_FLIPPED
*/
};
static volatile uint32_t *s_label_flip_control; // pointer to the flip control label
static int s_flip_status=FLIP_STATE_FLIPPED; // status variable to control flip
//--------------------------------------------------------------------------------------------------
static bool Gcm_ReleaseFlip(void)
{
if (*s_label_flip_control==LABEL_FLIP_CONTROL_READY) {
/* just in case rsx is running very slow somehow */
/* and flip_control label is not updated even after the real flip */
return false;
}
*s_label_flip_control=LABEL_FLIP_CONTROL_READY;
return true;
}
void updateCursorPosition(const int pixelX, const int pixelY)
{
cellGcmSetCursorPosition(pixelX, pixelY);
int32_t result = cellGcmUpdateCursor();
if( result == CELL_GCM_ERROR_FAILURE)
{
// [dkorus] this case happens until we initialize the cursor
//Msg(" hardware cursor error: cellGcmInitCursor() has not been called\n");
}
else if( result == CELL_GCM_ERROR_INVALID_VALUE )
{
Msg(" hardware cursor error: cursor bitmap is not correctly set\n");
}
}
void enableCursor()
{
if (cellGcmSetCursorEnable() != CELL_OK )
{
Msg( "Hardware Cursor Error: trouble with enable\n" );
}
if ( cellGcmUpdateCursor() != CELL_OK )
{
Msg( "Hardware Cursor Error: trouble with update\n" );
}
}
static void Gcm_VblankCallbackFunction(const uint32_t head)
{
// unused arg
(void)head;
int pixelX, pixelY;
if ( g_pInputSystem )
{
bool cursorEnabled = g_pInputSystem->GetPS3CursorPos( pixelX, pixelY );
if( cursorEnabled )
{
updateCursorPosition(pixelX,pixelY);
}
}
switch (s_flip_status){
case FLIP_STATE_FLIPPED:
if (g_ps3gcmGlobalState.m_flipMode == 30){
s_flip_status=FLIP_STATE_V1;
} else if (g_ps3gcmGlobalState.m_flipMode == 60){
if (Gcm_ReleaseFlip()){
s_flip_status=FLIP_STATE_FLIP_RELEASED;
}
}
break;
case FLIP_STATE_V1:
if (Gcm_ReleaseFlip()){
s_flip_status=FLIP_STATE_FLIP_RELEASED;
}
break;
case FLIP_STATE_FLIP_RELEASED:
break;
default:
assert(0);
}
}
static void Gcm_FlipCallbackFunction(const uint32_t head)
{
(void)head;
switch (s_flip_status){
case FLIP_STATE_FLIP_RELEASED:
s_flip_status=FLIP_STATE_FLIPPED;
break;
default:
break;
}
}
// initialize flip control state machine
static void Gcm_InitFlipControl(void)
{
cellGcmSetFlipMode( CELL_GCM_DISPLAY_HSYNC );
g_ps3gcmGlobalState.m_frameNo = 0;
g_ps3gcmGlobalState.m_finishIdx = 0;
s_label_flip_control=cellGcmGetLabelAddress(GCM_LABEL_FLIP_CONTROL);
*s_label_flip_control=LABEL_FLIP_CONTROL_WAIT;
cellGcmSetFlipHandler(Gcm_FlipCallbackFunction);
cellGcmSetVBlankHandler(Gcm_VblankCallbackFunction);
}
//--------------------------------------------------------------------------------------------------
// Beginscene, endscene and flip
//--------------------------------------------------------------------------------------------------
uint32 gCmdBufferHighWater = 0;
uint32 gCmdBufferStart = 0;
void CPs3gcmGlobalState::BeginScene()
{
gCmdBufferStart = (uint32)gpGcmContext->current;
gpGcmDrawState->BeginScene();
}
void CPs3gcmGlobalState::EndScene()
{
if ( (uint32)gpGcmContext->current > gCmdBufferStart )
{
uint32 bytes = (uint32)gpGcmContext->current - gCmdBufferStart;
if (bytes > gCmdBufferHighWater ) gCmdBufferHighWater = bytes;
}
gpGcmDrawState->EndScene();
}
float g_fliptime = 0;
void CPs3gcmGlobalState::SetFastFlip(bool onoff)
{
m_fastFlip = onoff;
g_fliptime = Plat_FloatTime();
}
extern void OnFrameTimestampAvailableRsx( float ms );
void CPs3gcmGlobalState::Flip()
{
cellSysutilCheckCallback();
if(m_fastFlip)
{
Gcm_ReleaseFlip();
float time = Plat_FloatTime();
if ( (time - g_fliptime) > 0.05) goto fullflip;
// Just end the frame, no point in flipping here...
gpGcmDrawState->EndFrame();
GCM_FUNC( cellGcmFlush );
goto newframe;
}
fullflip:
int idx, startIdx, endIdx;
//--------------------------------------------------------------------------------------------------
// Ensure any buffered state, copies etc... goes to GPU
//--------------------------------------------------------------------------------------------------
gpGcmDrawState->EndFrame();
//--------------------------------------------------------------------------------------------------
// Wait for previous frame Flip
//--------------------------------------------------------------------------------------------------
while (cellGcmGetFlipStatus()!=0){
g_pGcmSharedData->CheckForAudioRequest();
g_pGcmSharedData->CheckForServerRequest();
sys_timer_usleep(300);
}
// Insert end of gpu timestamp
idx = m_frameNo&1;
endIdx = GCM_REPORT_TIMESTAMP_FRAME_FIRST + (idx*2) + 1;
GCM_FUNC( cellGcmSetTimeStamp, endIdx );
//--------------------------------------------------------------------------------------------------
// If requested, lets defrag VRAM
//--------------------------------------------------------------------------------------------------
if (g_pGcmSharedData->m_bDeFrag)
{
g_pGcmSharedData->m_bDeFrag = 0;
extern void Ps3gcmLocalMemoryAllocator_CompactWithReason( char const *szReason );
Ps3gcmLocalMemoryAllocator_CompactWithReason( "End of Round" );
}
//--------------------------------------------------------------------------------------------------
// Get Timestamps
//--------------------------------------------------------------------------------------------------
if (m_frameNo)
{
idx = ((m_frameNo-1) & 1);
startIdx = GCM_REPORT_TIMESTAMP_FRAME_FIRST + (idx*2);
endIdx = startIdx+1;
uint64 uiStartTimestamp = cellGcmGetTimeStamp( startIdx );
uint64 uiEndTimestamp = cellGcmGetTimeStamp( endIdx );
uint64 uiRsxTimeInNanoSeconds = uiEndTimestamp - uiStartTimestamp;
OnFrameTimestampAvailableRsx( uiRsxTimeInNanoSeconds / 1000000.0f );
}
//--------------------------------------------------------------------------------------------------
// Insert new flip command and flush gpu
//--------------------------------------------------------------------------------------------------
// reset FlipStatus = 1
cellGcmResetFlipStatus();
// queue Flip command
GCM_FUNC( cellGcmSetFlipWithWaitLabel, m_display.surfaceFlipIdx, GCM_LABEL_FLIP_CONTROL, LABEL_FLIP_CONTROL_READY);
m_display.Flip();
GCM_FUNC( cellGcmSetWriteCommandLabel, GCM_LABEL_FLIP_CONTROL, LABEL_FLIP_CONTROL_WAIT);
GCM_FUNC( cellGcmSetWaitFlip );
GCM_FUNC( cellGcmFlush );
extern void Ps3gcmLocalMemoryAllocator_Reclaim();
Ps3gcmLocalMemoryAllocator_Reclaim();
//--------------------------------------------------------------------------------------------------
// Start a new frame
//--------------------------------------------------------------------------------------------------
newframe:
m_frameNo ++;
// Insert start of gpu timestamp
idx = m_frameNo&1;
startIdx = GCM_REPORT_TIMESTAMP_FRAME_FIRST + (idx*2);
GCM_FUNC( cellGcmSetTimeStamp, startIdx );
// Put RSX into known state for start of frame
gpGcmDrawState->ResetRsxState();
// Moved from DX present()
GCM_FUNC( cellGcmSetInvalidateVertexCache );
}
//--------------------------------------------------------------------------------------------------
// Buffer management
//--------------------------------------------------------------------------------------------------
CPs3gcmBuffer * CPs3gcmBuffer::New( uint32 uiSize, CPs3gcmAllocationType_t uType )
{
CPs3gcmBuffer * p = new CPs3gcmBuffer;
p->m_lmBlock.Alloc( uType, uiSize );
return p;
}
void CPs3gcmBuffer::Release()
{
// Wait for RSX to finish using the buffer memory
// and free it later
m_lmBlock.Free();
delete this;
}
+272
View File
@@ -0,0 +1,272 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
// Gcm renderer state and util functions
//
//==================================================================================================
#ifndef INCLUDED_GCMSTATE_H
#define INCLUDED_GCMSTATE_H
#ifndef SPU
#include "tier0/platform.h"
#include "tier0/dbg.h"
#include "cell\gcm.h"
#include "gcmconfig.h"
#include "ps3gcmmemory.h"
#include "dxabstract_def.h"
#include "spumgr_ppu.h"
#else
#include "spumgr_spu.h"
#endif
//--------------------------------------------------------------------------------------------------
// Misc
//--------------------------------------------------------------------------------------------------
template <typename T>
inline T Min( T a, T b )
{
return a < b ? a : b;
}
template <typename T>
inline T Max( T a, T b )
{
return a > b ? a : b;
}
template <typename T>
inline void Swap( T& a , T & b )
{
T c = a; a = b; b = c;
}
//--------------------------------------------------------------------------------------------------
// Literals
//--------------------------------------------------------------------------------------------------
// IO Memory (page isze is 1MB, so make these add up to 1MB
#define GCM_MAINPOOLSIZE (0 * 0x100000) // IO memory for main pool
#define GCM_DEFCMDBUFFSIZE (1 * 0x200000) // Default command buff (must be pow 2)
#define GCM_CALLCMDBUFFSIZE (2 * 0x10000) // 256 K of cmd buffer to call to
// Used for DrawprimUP
#define GCM_CALLCMDSEGSIZE 0x8000 // 32K segmentation
#define GCM_PATCHBUFFSIZE ((2 * 0x100000) - GCM_CALLCMDBUFFSIZE)
#define GCM_PATCHSEGSIZE 0x8000
#define GCM_IOSIZE (GCM_MAINPOOLSIZE + GCM_DEFCMDBUFFSIZE + GCM_CALLCMDBUFFSIZE + GCM_PATCHBUFFSIZE)
//--------------------------------------------------------------------------------------------------
// Display Structure
//--------------------------------------------------------------------------------------------------
struct CPs3gcmDisplay
{
uint32 surfaceFlipIdx; // which scanout color buffer will be presented with flip
enum EnumConst_t { SURFACE_COUNT = 2 };
CPs3gcmLocalMemoryBlockSystemGlobal surfaceColor[SURFACE_COUNT]; // scanout color buffers for double-buffering
// (need one more to avoid overwriting old buffer)
CPs3gcmLocalMemoryBlockSystemGlobal surfaceDepth; // depth buffer
void Flip()
{
surfaceFlipIdx = NextSurfaceIndex();
}
uint NextSurfaceIndex( int nFrame = 1 )const
{
return ( surfaceFlipIdx + nFrame ) % SURFACE_COUNT;
}
uint PrevSurfaceIndex( int nFrame )const
{
int nResult = int( surfaceFlipIdx + 1000000 * SURFACE_COUNT - nFrame ) % int( SURFACE_COUNT );
Assert( uint( nResult ) < SURFACE_COUNT ); // if this is negative, it means we did ( ( something ) mod 2 ) mod 3, which makes no sense in this context
return uint( nResult );
}
};
//--------------------------------------------------------------------------------------------------
// Global GCM state class
//--------------------------------------------------------------------------------------------------
struct CPs3gcmGlobalState
{
//--------------------------------------------------------------------------------------------------
// Memory
// RSX Local, plus one block of memory mapped into RSX (IO mem)
// Main memory pool is within the IO mem and is used for textures until it fills...
//--------------------------------------------------------------------------------------------------
// RSX local memory
void * m_pLocalBaseAddress; // RSX Local Memory Base Address
uint32 m_nLocalBaseOffset; // cellGcmAddressToOffset( m_pLocalBaseAddress )
uint32 m_nLocalSize; // RSX Local Memory Size
// IO memory mapped into RSX
void * m_pIoAddress; // RSX IO buffer, base address
uint32 m_nIoSize; // RSX IO total size [including CMD buffer]
uint32 m_nIoOffsetDelta; // add this to EA to get Io Offset
// Call Cmd Buffer
void* m_pCallCmdBuffer;
uint32 m_nCallCmdBufferoffset;
uint32 m_nCallWritePos; // Current posn (offset)
uint32 m_nCallReadSegment;
// main memory pool buffer
void * m_pRsxMainMemoryPoolBuffer;
uint32 m_nRsxMainMemoryPoolBufferSize;
// Pointer to the draw states
uint32 m_eaDrawStates;
//--------------------------------------------------------------------------------------------------
// SPU Task
//--------------------------------------------------------------------------------------------------
SpuTaskHandle m_spuHandle;
//--------------------------------------------------------------------------------------------------
// Patched Shaders
//--------------------------------------------------------------------------------------------------
uint8* m_pPatchBuff;
uint32 m_nPatchIdx; // Write index for this frames patch buffer
uint32 m_nPatchReadSeg;
//--------------------------------------------------------------------------------------------------
// Empty pixel shader
//--------------------------------------------------------------------------------------------------
CPs3gcmLocalMemoryBlock m_pShaderPsEmptyBuffer;
CgBinaryProgram *m_pShaderPsEmpty; // empty pixel shader
uint32 m_nPsEmptyShaderControl0;
uint32 m_nPsEmptyAttributeInputMask;
//--------------------------------------------------------------------------------------------------
// Flip data
//--------------------------------------------------------------------------------------------------
uint32 m_flipMode; // Holds 30 or 60
uint32 m_frameNo;
uint32 m_finishIdx;
bool m_fastFlip;
//--------------------------------------------------------------------------------------------------
// Display
//--------------------------------------------------------------------------------------------------
// Display size, aspect, pitch
uint16 m_nRenderSize[2]; // with & height of the render buffer
float m_flRenderAspect; // aspect ratio of the output device
uint32 m_nSurfaceRenderPitch;
CPs3gcmDisplay m_display;
//--------------------------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------------------------
public:
int32 Init();
void Shutdown();
void BeginScene();
void EndScene();
void Flip();
void SetFastFlip(bool onoff);
static int32_t CmdBufferFull(struct CellGcmContextData * pGcmContext, uint32_t size);
// DrawPrimUP puts a drawprimup call into the call buffer, with a label and RET.
// It's called from the gcmdrawstate which then sends a drawcall packet to the SPU
uint32 DrawPrimitiveUP(D3DPRIMITIVETYPE nPrimitiveType,UINT nPrimitiveCount,
CONST void *pVertexStreamZeroData, UINT nVertexStreamZeroStride );
// GetRenderSurfaceBytes Note:
// Height alignment must be 32 for tiled surfaces on RSX
// 128 for Edge Post MLAA
// 64 for Edge Post MLAA with EDGE_POST_MLAA_MODE_TRANSPOSE_64 flag set
inline uint GetRenderSurfaceBytes( uint nHeightAlignment = 32 ) const ;
private:
int InitGcm();
int InitVideo();
void CreateRsxBuffers(); // Display buffers and defaut allocated RTs etc..
void CreateIoBuffers(); // Allocs IO memory (mapped in Initgcm)
};
//--------------------------------------------------------------------------------------------------
// Inlines
//--------------------------------------------------------------------------------------------------
inline uint CPs3gcmGlobalState::GetRenderSurfaceBytes( uint nHeightAlignment) const
{
return m_nSurfaceRenderPitch * AlignValue( m_nRenderSize[1], nHeightAlignment );
}
//--------------------------------------------------------------------------------------------------
// Extern Globals
//--------------------------------------------------------------------------------------------------
extern CellGcmContextData gGcmContext;
extern CellGcmContextData* gpGcmContext;
extern CPs3gcmGlobalState g_ps3gcmGlobalState;
extern CellGcmContextData gCallContext;
extern CellGcmContextData* gpCallContext;
//--------------------------------------------------------------------------------------------------
// Memory block funcs that need access to g_ps3gcmGlobalState
//--------------------------------------------------------------------------------------------------
#ifndef SPU
inline char * CPs3gcmLocalMemoryBlock::DataInLocalMemory() const
{
Assert( IsLocalMemory() );
return
( m_nLocalMemoryOffset - g_ps3gcmGlobalState.m_nLocalBaseOffset ) +
( char * ) g_ps3gcmGlobalState.m_pLocalBaseAddress;
}
inline char * CPs3gcmLocalMemoryBlock::DataInMainMemory() const
{
Assert( !IsLocalMemory() && IsRsxMappedMemory() );
return
m_nLocalMemoryOffset +
( ( char * ) g_ps3gcmGlobalState.m_pIoAddress );
}
inline char * CPs3gcmLocalMemoryBlock::DataInMallocMemory() const
{
Assert( !IsLocalMemory() && !IsRsxMappedMemory() );
return ( char * ) m_nLocalMemoryOffset;
}
inline char * CPs3gcmLocalMemoryBlock::DataInAnyMemory() const
{
switch ( PS3GCMALLOCATIONPOOL( m_uType ) )
{
default: return DataInLocalMemory();
case kGcmAllocPoolMainMemory: return DataInMainMemory();
case kGcmAllocPoolMallocMemory: return DataInMallocMemory();
}
}
#endif
#endif // INCLUDED_GCMSTATE_H
+515
View File
@@ -0,0 +1,515 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
//
//
//==================================================================================================
#include "tier0/platform.h"
#include "tier0/dbg.h"
#include "tier1/strtools.h"
#include "tier1/utlbuffer.h"
#include "utlmap.h"
#include "ps3gcmmemory.h"
#include "gcmstate.h"
#include "bitmap/imageformat_declarations.h"
#include "gcmtexture.h"
#include "memdbgon.h"
#ifdef _CERT
#define Debugger() ((void)0)
#else
#define Debugger() DebuggerBreak()
#endif
//--------------------------------------------------------------------------------------------------
// Texture Layouts
//--------------------------------------------------------------------------------------------------
#ifdef _CERT
#define GLMTEX_FMT_DESC( x )
#else
#define GLMTEX_FMT_DESC( x ) x ,
#endif
#define CELL_GCM_REMAP_MODE_OIO(order, inputARGB, outputARGB) \
(((order)<<16)|((inputARGB))|((outputARGB)<<8))
#define REMAPO( x ) CELL_GCM_TEXTURE_REMAP_ORDER_X##x##XY
#define REMAP4(a,r,g,b) (((a)<<0)|((r)<<2)|((g)<<4)|((b)<<6))
#define REMAP_ARGB REMAP4( CELL_GCM_TEXTURE_REMAP_FROM_A, CELL_GCM_TEXTURE_REMAP_FROM_R, CELL_GCM_TEXTURE_REMAP_FROM_G, CELL_GCM_TEXTURE_REMAP_FROM_B )
#define REMAP_4 REMAP4( CELL_GCM_TEXTURE_REMAP_REMAP, CELL_GCM_TEXTURE_REMAP_REMAP, CELL_GCM_TEXTURE_REMAP_REMAP, CELL_GCM_TEXTURE_REMAP_REMAP )
#define REMAP_13 REMAP4( CELL_GCM_TEXTURE_REMAP_ONE, CELL_GCM_TEXTURE_REMAP_REMAP, CELL_GCM_TEXTURE_REMAP_REMAP, CELL_GCM_TEXTURE_REMAP_REMAP )
#define REMAP_4X(x) REMAP4( x, x, x, x )
#define REMAP_13X(y, x) REMAP4( y, x, x, x )
#define REMAP_ALL_DEFAULT CELL_GCM_REMAP_MODE_OIO( REMAPO(Y), REMAP_ARGB, REMAP_4 )
#define REMAP_ALL_DEFAULT_X CELL_GCM_REMAP_MODE_OIO( REMAPO(X), REMAP_ARGB, REMAP_4 )
#define CAP( x ) CPs3gcmTextureLayout::Format_t::kCap##x
CPs3gcmTextureLayout::Format_t g_ps3texFormats[PS3_TEX_MAX_FORMAT_COUNT] =
{
// summ-name d3d-format
// gcmRemap
// gcmFormat
// gcmPitchPer4X gcmFlags
{ GLMTEX_FMT_DESC("_D16") D3DFMT_D16,
REMAP_ALL_DEFAULT,
8,
CELL_GCM_TEXTURE_DEPTH16,
0 },
{ GLMTEX_FMT_DESC("_D24X8") D3DFMT_D24X8,
REMAP_ALL_DEFAULT,
16,
CELL_GCM_TEXTURE_DEPTH24_D8,
0 },
{ GLMTEX_FMT_DESC("_D24S8") D3DFMT_D24S8,
REMAP_ALL_DEFAULT,
16,
CELL_GCM_TEXTURE_DEPTH24_D8,
0 },
{ GLMTEX_FMT_DESC("_A8R8G8B8") D3DFMT_A8R8G8B8,
REMAP_ALL_DEFAULT,
16,
CELL_GCM_TEXTURE_A8R8G8B8,
CAP(SRGB) },
{ GLMTEX_FMT_DESC("_X8R8G8B8") D3DFMT_X8R8G8B8,
REMAP_ALL_DEFAULT,
16,
CELL_GCM_TEXTURE_A8R8G8B8,
CAP(SRGB) },
{ GLMTEX_FMT_DESC("_X1R5G5B5") D3DFMT_X1R5G5B5,
CELL_GCM_REMAP_MODE_OIO( REMAPO(X), REMAP_ARGB, REMAP_13 ),
8,
CELL_GCM_TEXTURE_R5G6B5,
0 },
{ GLMTEX_FMT_DESC("_A1R5G5B5") D3DFMT_A1R5G5B5,
REMAP_ALL_DEFAULT_X,
8,
CELL_GCM_TEXTURE_A1R5G5B5,
0 },
{ GLMTEX_FMT_DESC("_L8") D3DFMT_L8,
CELL_GCM_REMAP_MODE_OIO( REMAPO(Y), REMAP_4X(CELL_GCM_TEXTURE_REMAP_FROM_B), REMAP_13 ),
4,
CELL_GCM_TEXTURE_B8,
0 },
{ GLMTEX_FMT_DESC("_A8L8") D3DFMT_A8L8,
CELL_GCM_REMAP_MODE_OIO( REMAPO(Y), REMAP_13X( CELL_GCM_TEXTURE_REMAP_FROM_G, CELL_GCM_TEXTURE_REMAP_FROM_B), REMAP_4 ),
8,
CELL_GCM_TEXTURE_G8B8,
0 },
{ GLMTEX_FMT_DESC("_DXT1") D3DFMT_DXT1,
CELL_GCM_REMAP_MODE_OIO( REMAPO(Y), REMAP_ARGB, REMAP_13 ),
8,
CELL_GCM_TEXTURE_COMPRESSED_DXT1,
CAP(SRGB) | CAP(4xBlocks) },
{ GLMTEX_FMT_DESC("_DXT3") D3DFMT_DXT3,
REMAP_ALL_DEFAULT,
16,
CELL_GCM_TEXTURE_COMPRESSED_DXT23,
CAP(SRGB) | CAP(4xBlocks) },
{ GLMTEX_FMT_DESC("_DXT5") D3DFMT_DXT5,
REMAP_ALL_DEFAULT,
16,
CELL_GCM_TEXTURE_COMPRESSED_DXT45,
CAP(SRGB) | CAP(4xBlocks) },
{ GLMTEX_FMT_DESC("_A16B16G16R16F") D3DFMT_A16B16G16R16F,
REMAP_ALL_DEFAULT_X,
32,
CELL_GCM_TEXTURE_W16_Z16_Y16_X16_FLOAT,
0 },
{ GLMTEX_FMT_DESC("_A16B16G16R16") D3DFMT_A16B16G16R16,
REMAP_ALL_DEFAULT_X,
64,
CELL_GCM_TEXTURE_W32_Z32_Y32_X32_FLOAT,
0 },
{ GLMTEX_FMT_DESC("_A32B32G32R32F") D3DFMT_A32B32G32R32F,
REMAP_ALL_DEFAULT_X,
64,
CELL_GCM_TEXTURE_W32_Z32_Y32_X32_FLOAT,
0 },
{ GLMTEX_FMT_DESC("_R8G8B8") D3DFMT_R8G8B8,
CELL_GCM_REMAP_MODE_OIO( REMAPO(Y),
REMAP4( CELL_GCM_TEXTURE_REMAP_FROM_B, CELL_GCM_TEXTURE_REMAP_FROM_A, CELL_GCM_TEXTURE_REMAP_FROM_R, CELL_GCM_TEXTURE_REMAP_FROM_G ),
REMAP_13 ),
16,
CELL_GCM_TEXTURE_A8R8G8B8,
CAP(SRGB) },
{ GLMTEX_FMT_DESC("_A8") D3DFMT_A8,
CELL_GCM_REMAP_MODE_OIO( REMAPO(Y),
REMAP4( CELL_GCM_TEXTURE_REMAP_FROM_B, CELL_GCM_TEXTURE_REMAP_FROM_R, CELL_GCM_TEXTURE_REMAP_FROM_B, CELL_GCM_TEXTURE_REMAP_FROM_B ),
REMAP_13X( CELL_GCM_TEXTURE_REMAP_REMAP, CELL_GCM_TEXTURE_REMAP_ZERO ) ),
4,
CELL_GCM_TEXTURE_B8,
0 },
{ GLMTEX_FMT_DESC("_R5G6B5") D3DFMT_R5G6B5,
CELL_GCM_REMAP_MODE_OIO( REMAPO(Y),
REMAP4( CELL_GCM_TEXTURE_REMAP_FROM_B, CELL_GCM_TEXTURE_REMAP_FROM_A, CELL_GCM_TEXTURE_REMAP_FROM_R, CELL_GCM_TEXTURE_REMAP_FROM_G ),
REMAP_13 ),
16,
CELL_GCM_TEXTURE_A8R8G8B8,
CAP(SRGB) },
{ GLMTEX_FMT_DESC("_Q8W8V8U8") D3DFMT_Q8W8V8U8,
REMAP_ALL_DEFAULT,
16,
CELL_GCM_TEXTURE_A8R8G8B8,
CAP(SRGB) },
};
uint g_nPs3texFormatCount = PS3_TEX_CANONICAL_FORMAT_COUNT;
#undef CAP
#undef GLMTEX_FMT_DESC
static bool Ps3texLayoutLessFunc( CPs3gcmTextureLayout::Key_t const &a, CPs3gcmTextureLayout::Key_t const &b )
{
return ( memcmp( &a, &b, sizeof( CPs3gcmTextureLayout::Key_t ) ) < 0 );
}
static CUtlMap< CPs3gcmTextureLayout::Key_t, CPs3gcmTextureLayout const * > s_ps3texLayouts( Ps3texLayoutLessFunc );
CPs3gcmTextureLayout const * CPs3gcmTextureLayout::New( Key_t const &k )
{
// look up 'key' in the map and see if it's a hit, if so, bump the refcount and return
// if not, generate a completed layout based on the key, add to map, set refcount to 1, return that
unsigned short index = s_ps3texLayouts.Find( k );
if ( index != s_ps3texLayouts.InvalidIndex() )
{
CPs3gcmTextureLayout const *layout = s_ps3texLayouts[ index ];
++ layout->m_refCount;
return layout;
}
// Need to generate complete information about the texture layout
uint8 nMips = ( k.m_texFlags & kfMip ) ? k.m_nActualMipCount : 1;
uint8 nFaces = ( k.m_texFlags & kfTypeCubeMap ) ? 6 : 1;
uint32 nSlices = nMips * nFaces;
// Allocate layout memory
size_t numLayoutBytes = sizeof( CPs3gcmTextureLayout ) + nSlices * sizeof( Slice_t );
CPs3gcmTextureLayout *layout = ( CPs3gcmTextureLayout * ) MemAlloc_AllocAligned( numLayoutBytes, 16 );
memset( layout, 0, numLayoutBytes );
memcpy( &layout->m_key, &k, sizeof( Key_t ) );
layout->m_refCount = 1;
// Find the format descriptor
for ( int j = 0; j < PS3_TEX_CANONICAL_FORMAT_COUNT; ++ j )
{
if ( g_ps3texFormats[j].m_d3dFormat == k.m_texFormat )
{
layout->m_nFormat = j;
break;
}
Assert( j != PS3_TEX_CANONICAL_FORMAT_COUNT - 1 );
}
layout->m_mipCount = nMips;
//
// Slices
//
bool bSwizzled = layout->IsSwizzled();
size_t fmtPitch = layout->GetFormatPtr()->m_gcmPitchPer4X;
size_t fmtPitchBlock = ( layout->GetFormatPtr()->m_gcmCaps & CPs3gcmTextureLayout::Format_t::kCap4xBlocks ) ? 16 : 4;
size_t numDataBytes = 0;
Slice_t *pSlice = &layout->m_slices[0];
for ( int face = 0; face < nFaces; ++ face )
{
// For cubemaps every next face in swizzled addressing
// must be aligned on 128-byte boundary
if ( bSwizzled )
{
numDataBytes = ( numDataBytes + 127 ) & ~127;
}
for ( int mip = 0; mip < nMips; ++ mip, ++ pSlice )
{
for ( int j = 0; j < ARRAYSIZE( k.m_size ); ++ j )
{
pSlice->m_size[j] = k.m_size[j] >> mip;
pSlice->m_size[j] = MAX( pSlice->m_size[j], 1 );
}
pSlice->m_storageOffset = numDataBytes;
size_t numTexels;
// For linear layout textures every mip row must be padded to the
// width of the original highest level mip so that the pitch was
// the same for every mip
if ( bSwizzled )
numTexels = ( pSlice->m_size[0] * pSlice->m_size[1] * pSlice->m_size[2] );
else
numTexels = ( k.m_size[0] * pSlice->m_size[1] * pSlice->m_size[2] );
size_t numBytes = ( numTexels * fmtPitch ) / fmtPitchBlock;
if ( layout->GetFormatPtr()->m_gcmCaps & CPs3gcmTextureLayout::Format_t::kCap4xBlocks )
{
// Ensure the size of the smallest mipmap levels of DXT1/3/5 textures (the 1x1 and 2x2 mips) is accurately computed.
numBytes = MAX( numBytes, fmtPitch );
}
pSlice->m_storageSize = MAX( numBytes, 1 );
numDataBytes += pSlice->m_storageSize;
}
}
// Make the total size 128-byte aligned
// Realistically it is required only for depth textures
numDataBytes = ( numDataBytes + 127 ) & ~127;
//
// Tiled and ZCull memory adjustments
//
layout->m_gcmAllocType = GCM_MAINPOOLSIZE ? kAllocPs3gcmTextureData0 : kAllocPs3gcmTextureData;
if ( layout->IsTiledMemory() )
{
if( g_nPs3texFormatCount >= PS3_TEX_MAX_FORMAT_COUNT )
{
Error("Modified ps3 format array overflow. Increase PS3_TEX_MAX_FORMAT_COUNT appropriately and recompile\n");
}
Format_t *pModifiedFormat = &g_ps3texFormats[g_nPs3texFormatCount];
V_memcpy( pModifiedFormat, layout->GetFormatPtr(), sizeof( Format_t ) );
layout->m_nFormat = g_nPs3texFormatCount;
g_nPs3texFormatCount ++;
if ( k.m_texFlags & kfTypeDepthStencil )
{
//
// Tiled Zcull Surface
//
uint32 zcullSize[2] = { AlignValue( k.m_size[0], 64 ), AlignValue( k.m_size[1], 64 ) };
uint32 nDepthPitch;
if ( k.m_texFormat == D3DFMT_D16 )
nDepthPitch = cellGcmGetTiledPitchSize( zcullSize[0] * 2 );
else
nDepthPitch = cellGcmGetTiledPitchSize( zcullSize[0] * 4 );
pModifiedFormat->m_gcmPitchPer4X = nDepthPitch;
uint32 uDepthBufferSize32bpp = nDepthPitch * zcullSize[1];
uDepthBufferSize32bpp = AlignValue( uDepthBufferSize32bpp, PS3GCMALLOCATIONALIGN( kAllocPs3gcmDepthBuffer ) );
Assert( uDepthBufferSize32bpp >= numDataBytes );
numDataBytes = uDepthBufferSize32bpp;
layout->m_gcmAllocType = kAllocPs3gcmDepthBuffer;
}
else
{
//
// Tiled Color Surface
//
uint32 nTiledPitch = cellGcmGetTiledPitchSize( k.m_size[0] * layout->GetFormatPtr()->m_gcmPitchPer4X / 4 );
pModifiedFormat->m_gcmPitchPer4X = nTiledPitch;
// We Don't allocate any 512x512 RTs (they are used only when in PAL576i which can use the FB mem pool)
/*if ( k.m_size[0] == 512 && k.m_size[1] == 512 && k.m_size[2] == 1 )
layout->m_gcmAllocType = kAllocPs3gcmColorBuffer512;
else*/
if ( k.m_size[0] == g_ps3gcmGlobalState.m_nRenderSize[0] && k.m_size[1] == g_ps3gcmGlobalState.m_nRenderSize[1] && k.m_size[2] == 1 )
layout->m_gcmAllocType = kAllocPs3gcmColorBufferFB;
else if ( k.m_size[0] == g_ps3gcmGlobalState.m_nRenderSize[0]/4 && k.m_size[1] == g_ps3gcmGlobalState.m_nRenderSize[1]/4 && k.m_size[2] == 1 )
layout->m_gcmAllocType = kAllocPs3gcmColorBufferFBQ;
else
layout->m_gcmAllocType = kAllocPs3gcmColorBufferMisc;
uint32 uRenderSize = nTiledPitch * AlignValue( k.m_size[1], 32 ); // 32-line vertical alignment required in local memory
if ( layout->m_gcmAllocType == kAllocPs3gcmColorBufferMisc )
uRenderSize = AlignValue( uRenderSize, PS3GCMALLOCATIONALIGN( kAllocPs3gcmColorBufferMisc ) );
Assert( uRenderSize >= numDataBytes );
numDataBytes = uRenderSize;
}
}
layout->m_storageTotalSize = numDataBytes;
//
// Finished creating the layout information
//
#ifndef _CERT
// generate summary
// "target, format, +/- mips, base size"
char scratch[1024];
char *targetname = targetname = "2D ";
if ( layout->IsVolumeTex() )
targetname = "3D ";
if ( layout->IsCubeMap() )
targetname = "CUBE";
sprintf( scratch, "[%s %s %dx%dx%d mips=%d slices=%d flags=%02X%s]",
targetname,
layout->GetFormatPtr()->m_formatSummary,
layout->m_key.m_size[0], layout->m_key.m_size[1], layout->m_key.m_size[2],
nMips,
nSlices,
layout->m_key.m_texFlags,
(layout->m_key.m_texFlags & kfSrgbEnabled) ? " SRGB" : ""
);
layout->m_layoutSummary = strdup( scratch );
#endif
// then insert into map. disregard returned index.
s_ps3texLayouts.Insert( k, layout );
return layout;
}
void CPs3gcmTextureLayout::Release() const
{
-- m_refCount;
// keep the layout in the map for easy access
Assert( m_refCount >= 0 );
}
//////////////////////////////////////////////////////////////////////////
//
// Texture management
//
CPs3gcmTexture * CPs3gcmTexture::New( CPs3gcmTextureLayout::Key_t const &key )
{
//
// Allocate a new layout for the texture
//
CPs3gcmTextureLayout const *pLayout = CPs3gcmTextureLayout::New( key );
if ( !pLayout )
{
Debugger();
return NULL;
}
CPs3gcmTexture *tex = (CPs3gcmTexture *)MemAlloc_AllocAligned( sizeof( CPs3gcmTexture ), 16 );
memset( tex, 0, sizeof( CPs3gcmTexture ) ); // NOTE: This clears the CPs3gcmLocalMemoryBlock
tex->m_layout = pLayout;
CPs3gcmAllocationType_t uAllocationType = pLayout->m_gcmAllocType;
if ( key.m_texFlags & CPs3gcmTextureLayout::kfNoD3DMemory )
{
if ( ( uAllocationType == kAllocPs3gcmDepthBuffer ) || ( uAllocationType == kAllocPs3gcmColorBufferMisc ) )
{
Assert( 0 );
Warning( "ERROR: (CPs3gcmTexture::New) depth/colour buffers should not be marked with kfNoD3DMemory!\n" );
}
else
{
// Early-out, storage will be allocated later (via IDirect3DDevice9::AllocateTextureStorage)
return tex;
}
}
tex->Allocate();
return tex;
}
void CPs3gcmTexture::Release()
{
// Wait for RSX to finish using the texture memory
// and free it later
if ( m_lmBlock.Size() )
{
m_lmBlock.Free();
}
m_layout->Release();
MemAlloc_FreeAligned( this );
}
bool CPs3gcmTexture::Allocate()
{
if ( m_lmBlock.Size() )
{
// Already allocated!
Assert( 0 );
Warning( "ERROR: CPs3gcmTexture::Allocate called twice!\n" );
return true;
}
CPs3gcmAllocationType_t uAllocationType = m_layout->m_gcmAllocType;
const CPs3gcmTextureLayout::Key_t & key = m_layout->m_key;
// if kAllocPs3gcmTextureData0 (main memory) fails try kAllocPs3gcmTextureData
if (!m_lmBlock.Alloc( uAllocationType, m_layout->m_storageTotalSize ) )
{
if (m_layout->m_gcmAllocType == kAllocPs3gcmTextureData0)
{
m_layout->m_gcmAllocType = kAllocPs3gcmTextureData;
CPs3gcmAllocationType_t uAllocationType = m_layout->m_gcmAllocType;
m_lmBlock.Alloc( uAllocationType, m_layout->m_storageTotalSize );
}
}
if ( m_layout->IsTiledMemory() )
{
if ( uAllocationType == kAllocPs3gcmDepthBuffer )
{
bool bIs16BitDepth = ( m_layout->GetFormatPtr()->m_gcmFormat == CELL_GCM_TEXTURE_DEPTH16 ) || ( m_layout->m_nFormat == CELL_GCM_TEXTURE_DEPTH16_FLOAT );
uint32 zcullSize[2] = { AlignValue( key.m_size[0], 64 ), AlignValue( key.m_size[1], 64 ) };
uint32 uiZcullIndex = m_lmBlock.ZcullMemoryIndex();
cellGcmBindZcull( uiZcullIndex,
m_lmBlock.Offset(),
zcullSize[0], zcullSize[1],
m_lmBlock.ZcullMemoryStart(),
bIs16BitDepth ? CELL_GCM_ZCULL_Z16 : CELL_GCM_ZCULL_Z24S8,
CELL_GCM_SURFACE_CENTER_1,
CELL_GCM_ZCULL_LESS,
CELL_GCM_ZCULL_LONES,
CELL_GCM_SCULL_SFUNC_ALWAYS,
0, 0 // sRef, sMask
);
uint32 uiTileIndex = m_lmBlock.TiledMemoryIndex();
cellGcmSetTileInfo( uiTileIndex, CELL_GCM_LOCATION_LOCAL, m_lmBlock.Offset(),
m_layout->m_storageTotalSize, m_layout->DefaultPitch(), bIs16BitDepth ? CELL_GCM_COMPMODE_DISABLED : CELL_GCM_COMPMODE_Z32_SEPSTENCIL_REGULAR,
m_lmBlock.TiledMemoryTagAreaBase(), // The area base + size/0x10000 will be allocated as the tag area.
1 ); // Misc depth buffers on bank 1
cellGcmBindTile( uiTileIndex );
}
else if ( uAllocationType == kAllocPs3gcmColorBufferMisc )
{
uint32 uiTileIndex = m_lmBlock.TiledMemoryIndex();
cellGcmSetTileInfo( uiTileIndex, CELL_GCM_LOCATION_LOCAL, m_lmBlock.Offset(),
m_layout->m_storageTotalSize, m_layout->DefaultPitch(), CELL_GCM_COMPMODE_DISABLED,
m_lmBlock.TiledMemoryTagAreaBase(), // The area base + size/0x10000 will be allocated as the tag area.
1 ); // Tile misc color buffers on bank 1
cellGcmBindTile( uiTileIndex );
}
}
#ifdef _DEBUG
memset( Data(), 0, m_layout->m_storageTotalSize ); // initialize texture data to BLACK in DEBUG
#endif
return true;
}
+250
View File
@@ -0,0 +1,250 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
// Texture Layout, CPs3gcmTexture, and CPs3gcmTextureData_t
//
//==================================================================================================
#ifndef INCLUDED_GCMTEXTURE_H
#define INCLUDED_GCMTEXTURE_H
#include "ps3/ps3_platform.h"
#include "ps3gcmmemory.h"
#include "gcmstate.h"
//--------------------------------------------------------------------------------------------------
// Literals
//--------------------------------------------------------------------------------------------------
#define PS3_TEX_MAX_FORMAT_COUNT 48
#define PS3_TEX_CANONICAL_FORMAT_COUNT 19
//--------------------------------------------------------------------------------------------------
// Texture layout, texture etc..
//--------------------------------------------------------------------------------------------------
struct ALIGN16 CPs3gcmTextureLayout
{
#ifndef _CERT
char *m_layoutSummary; // for debug visibility
#endif
// format mapping description
struct ALIGN16 Format_t
{
#ifndef _CERT
char *m_formatSummary; // for debug visibility
#endif
enum GcmCaps_t
{
kCapSRGB = (1<<0), // GCM can sample it as SRGB
kCap4xBlocks = (1<<1), // Pitch is referring to 4 texel blocks and not single texel blocks (DXT)
};
D3DFORMAT m_d3dFormat; // what D3D knows it as; see public/bitmap/imageformat.h
uint32 m_gcmRemap; // GCM remap mask
uint16 m_gcmPitchPer4X; // GCM pitch multiplier per every 4 pixels of width
uint8 m_gcmFormat; // GCM format
uint8 m_gcmCaps; // GCM caps of this texture
}
ALIGN16_POST;
// const inputs used for hashing
struct Key_t
{
D3DFORMAT m_texFormat; // D3D texel format
uint16 m_size[3]; // dimensions of the base mip
uint8 m_texFlags; // mipped, autogen mips, render target, ... ?
uint8 m_nActualMipCount; // Actual number of mips; on console builds, we typically drop the smallest (highest index)
// mips to save space (they waste a lot of space for page-alignment reasons)
// high-bit 0x80 indicates cubemap
};
// layout flags
enum Flags_t
{
kfDynamicNoSwizzle = (1<<0), // Indicates whether this texture needs to keep a backing store for incremental updates.
// (On PS3 this will prevent texture from being swizzled to allow CPU writes at subrect offsets)
kfMip = (1<<1),
kfMipAuto = (1<<2),
kfTypeRenderable = (1<<3),
kfTypeDepthStencil = (1<<4),
kfTypeCubeMap = (1<<5),
kfSrgbEnabled = (1<<6),
kfNoD3DMemory = (1<<7), // Allocation of storage for the bits has been deferred (call IDirect3DDevice9::AllocateTextureStorage to do the allocation)
// -!!--!!- DO NOT ADD MORE FLAGS -!!--!!- (m_texFlags is only 8 bits)
};
// slice information
struct Slice_t
{
uint32 m_storageOffset; //where in the storage slab does this slice live
uint32 m_storageSize; //how much storage does this slice occupy
uint16 m_size[3]; //texel dimensions of this slice
};
//
// Structure definition
//
Key_t m_key; // key of the layout
int32 mutable m_refCount; // refcount
uint32 m_storageTotalSize; // size of storage slab required
uint16 m_nFormat; // format specific info; index in g_ps3texFormats table
uint8 m_mipCount; // derived by starting at base size and working down towards 1x1
CPs3gcmAllocationType_t mutable m_gcmAllocType; // type of GCM allocation to determine pool/alignment/etc.
#ifndef SPU
// slice array
Slice_t m_slices[0]; // dynamically allocated 2-d array [faces][mips]
public:
inline int SlicePitch( int iSlice ) const;
inline int DefaultPitch() const;
inline const Format_t * GetFormatPtr()const;
#endif
public:
inline bool IsSwizzled() const { return !( m_key.m_texFlags & ( kfDynamicNoSwizzle | kfTypeRenderable ) ) && IsPowerOfTwo( m_key.m_size[0] ) && IsPowerOfTwo( m_key.m_size[1] ) && IsPowerOfTwo( m_key.m_size[2] ); }
inline bool IsCubeMap() const { return !!(m_key.m_texFlags & kfTypeCubeMap); }
inline bool IsVolumeTex() const { return !!(m_key.m_size[2] > 1); }
inline bool IsTiledMemory() const { return (m_key.m_texFlags & ( kfTypeRenderable | kfDynamicNoSwizzle )) == kfTypeRenderable; }
inline int FaceCount() const { return ( !IsCubeMap() ) ? 1 : 6; }
inline int MipCount() const { return ( m_key.m_texFlags & kfMip ) ? m_key.m_nActualMipCount : 1; }
inline int SlicePitch2( int iSlice, const Slice_t* pSlices, const Format_t *pTexFormats ) const{ return !IsTiledMemory() ? ( ( IsSwizzled() ? pSlices[iSlice].m_size[0] : m_key.m_size[0] ) * pTexFormats[m_nFormat].m_gcmPitchPer4X / 4 ) : pTexFormats[m_nFormat].m_gcmPitchPer4X; }
inline int DefaultPitch2( const Format_t *pTexFormats ) const { return !IsTiledMemory() ? m_key.m_size[0] * pTexFormats[m_nFormat].m_gcmPitchPer4X / 4 : pTexFormats[m_nFormat].m_gcmPitchPer4X; }
inline int SliceIndex( int face, int mip ) const { return mip + ( face * MipCount() ); }
public:
#ifndef SPU
static CPs3gcmTextureLayout const * New( Key_t const &k );
void Release() const;
#endif
}
ALIGN16_POST;
extern CPs3gcmTextureLayout::Format_t g_ps3texFormats[PS3_TEX_MAX_FORMAT_COUNT];
extern uint g_nPs3texFormatCount;
#ifndef SPU
// convenience functions on PPU that use implicit tables always accessible on PPU
inline int CPs3gcmTextureLayout::SlicePitch( int iSlice ) const
{
return SlicePitch2( iSlice, &m_slices[0], g_ps3texFormats );
}
inline int CPs3gcmTextureLayout::DefaultPitch() const
{
return DefaultPitch2( g_ps3texFormats );
}
inline const CPs3gcmTextureLayout::Format_t * CPs3gcmTextureLayout::GetFormatPtr()const
{
return &g_ps3texFormats[ m_nFormat ];
}
#endif
struct ALIGN16 CPs3gcmTexture
{
CPs3gcmTextureLayout const *m_layout; // this structure persists. see CPs3gcmTextureLayout::Release( it asserts if refcount goes down to zero )
ALIGN16 CPs3gcmLocalMemoryBlock m_lmBlock ALIGN16_POST; // this structure has the Offset, and the texture bits at that offset persist until all Draw calls are made that use it
inline uint32 Offset()const { Assert( m_lmBlock.Size() ); return m_lmBlock.Offset(); }
#ifndef SPU
inline char * Data() { Assert( m_lmBlock.Size() ); return m_lmBlock.DataInAnyMemory(); }
#endif
public:
#ifndef SPU
static CPs3gcmTexture * New( CPs3gcmTextureLayout::Key_t const &key );
void Release();
bool Allocate();
#endif
}
ALIGN16_POST;
struct CPs3gcmTextureData_t
{
// CPs3gcmTextureLayout const *m_eaLayout
uint32 m_eaLayout; // this structure persists. see CPs3gcmTextureLayout::Release( it asserts if refcount goes down to zero )
uint32 m_nLocalOffset; // the offset of the texture bits
void Assign( const CPs3gcmTexture * pThat )
{
if( pThat )
{
m_eaLayout = ( uint32 )pThat->m_layout;
m_nLocalOffset = pThat->Offset();
Assert( m_eaLayout ? !( 15 & ( uintp( m_eaLayout ) | m_nLocalOffset ) ) && m_nLocalOffset : !m_nLocalOffset );
}
else
{
Reset();
}
}
inline uint32 Offset()const { return m_nLocalOffset; }
void Reset()
{
m_eaLayout = 0;
m_nLocalOffset = 0;
}
bool IsNull()const
{
return !NotNull();
}
bool NotNull()const
{
// either both are null, or none is null
Assert( ( m_eaLayout == 0 ) == ( m_nLocalOffset == 0 ) );
return m_eaLayout != 0;
}
operator bool() const { return NotNull(); }
};
//
// CPs3BindTexture_t : Everything we need to bind a texture
//
// This is what the SPU needs to bind the texture
struct CPs3BindTexture_t
{
uint8 m_sampler;
uint8 m_nBindFlags;
uint8 m_UWrap;
uint8 m_VWrap;
uint8 m_WWrap;
uint8 m_minFilter;
uint8 m_magFilter;
uint8 m_mipFilter;
uint32 m_nLayout;
CPs3gcmLocalMemoryBlock *m_pLmBlock;
int m_boundStd;
int m_hTexture;
};
// This is what we store when asked to bind a texture
// When the cmd buffer is executed, at this time we lookup
// the remaining fields and pack some CPs3BindTexture_t to actually use on the SPU
struct CPs3BindParams_t
{
uint16 m_nBindTexIndex;
uint8 m_sampler;
uint8 m_nBindFlags;
int m_boundStd;
int m_hTexture;
};
#endif // INCLUDED_GCMTEXTURE_H
@@ -0,0 +1,12 @@
//===== Copyright (c) 1996-2008, Valve Corporation, All rights reserved. ======//
struct PS_IN
{
float2 TexCoord : TEXCOORD;
};
sampler detail : register( s0 );
float4 main( PS_IN In ) : COLOR
{
return tex2D( detail, In.TexCoord );
}
@@ -0,0 +1,23 @@
//===== Copyright (c) 1996-2008, Valve Corporation, All rights reserved. ======//
float4x4 matWVP : register(c0);
struct VS_IN
{
float4 ObjPos : POSITION;
float2 TexCoord : TEXCOORD;
};
struct VS_OUT
{
float4 ProjPos : POSITION;
float2 TexCoord : TEXCOORD;
};
VS_OUT main( VS_IN In )
{
VS_OUT Out;
Out.ProjPos = mul( In.ObjPos, matWVP );
Out.TexCoord = In.TexCoord;
return Out;
}
@@ -0,0 +1,13 @@
//===== Copyright (c) 1996-2008, Valve Corporation, All rights reserved. ======//
struct PS_IN
{
float2 TexCoord : TEXCOORD;
};
sampler detail : register( s0 );
float4 main( PS_IN In ) : COLOR
{
return tex2D( detail, In.TexCoord );
}
@@ -0,0 +1,54 @@
//===== Copyright (c) 1996-2008, Valve Corporation, All rights reserved. ======//
struct PS_IN
{
float2 TexCoord : TEXCOORD;
};
float SrgbGammaToLinear( float flSrgbGammaValue )
{
float x = saturate( flSrgbGammaValue );
return ( x <= 0.04045f ) ? ( x / 12.92f ) : ( pow( ( x + 0.055f ) / 1.055f, 2.4f ) );
}
float X360LinearToGamma( float flLinearValue )
{
float fl360GammaValue;
flLinearValue = saturate( flLinearValue );
if ( flLinearValue < ( 128.0f / 1023.0f ) )
{
if ( flLinearValue < ( 64.0f / 1023.0f ) )
{
fl360GammaValue = flLinearValue * ( 1023.0f * ( 1.0f / 255.0f ) );
}
else
{
fl360GammaValue = flLinearValue * ( ( 1023.0f / 2.0f ) * ( 1.0f / 255.0f ) ) + ( 32.0f / 255.0f );
}
}
else
{
if ( flLinearValue < ( 512.0f / 1023.0f ) )
{
fl360GammaValue = flLinearValue * ( ( 1023.0f / 4.0f ) * ( 1.0f / 255.0f ) ) + ( 64.0f / 255.0f );
}
else
{
fl360GammaValue = flLinearValue * ( ( 1023.0f /8.0f ) * ( 1.0f / 255.0f ) ) + ( 128.0f /255.0f );
if ( fl360GammaValue > 1.0f )
{
fl360GammaValue = 1.0f;
}
}
}
fl360GammaValue = saturate( fl360GammaValue );
return fl360GammaValue;
}
sampler detail : register( s0 );
float4 main( PS_IN In ) : COLOR
{
float4 vTextureColor = tex2D( detail, In.TexCoord );
return vTextureColor;
};
@@ -0,0 +1,941 @@
//========== Copyright © 2010, Valve Corporation, All rights reserved. ========
#include "dxabstract.h"
#include "ps3gcmstate.h"
#include "utlmap.h"
#include "ps3/ps3gcmlabels.h"
#include "sys/tty.h"
#include "convar.h"
//#include "vjobs/spudrawqueue_shared.h"
#include "spugcm.h"
#include "memdbgon.h"
PLATFORM_OVERRIDE_MEM_ALLOC_INTERNAL_PS3_IMPL
//////////////////////////////////////////////////////////////////////////
#if 1 // #ifndef _CERT
#define TRACK_ALLOC_STATS 1
#endif
#ifdef GCMLOCALMEMORYBLOCKDEBUG
ConVar r_ps3_gcmnocompact( "r_ps3_gcmnocompact", "0" );
ConVar r_ps3_gcmlowcompact( "r_ps3_gcmlowcompact", "0" );
#endif
static CThreadFastMutex s_AllocMutex;
static int32 s_uiGcmLocalMemoryAllocatorMutexLockCount;
struct CGcmLocalMemoryAllocatorMutexLockCounter_t
{
CGcmLocalMemoryAllocatorMutexLockCounter_t() { Assert( s_uiGcmLocalMemoryAllocatorMutexLockCount >= 0 ); ++ s_uiGcmLocalMemoryAllocatorMutexLockCount; }
~CGcmLocalMemoryAllocatorMutexLockCounter_t() { Assert( s_uiGcmLocalMemoryAllocatorMutexLockCount > 0 ); -- s_uiGcmLocalMemoryAllocatorMutexLockCount; }
};
#define PS3ALLOCMTX AUTO_LOCK( s_AllocMutex ); CGcmLocalMemoryAllocatorMutexLockCounter_t aLockCounter;
bool IsItSafeToRefreshFrontBufferNonInteractivePs3()
{
// NOTE: only main thread can refresh front buffer
if ( !ThreadInMainThread() )
return false;
AUTO_LOCK( s_AllocMutex );
Assert( s_uiGcmLocalMemoryAllocatorMutexLockCount >= 0 );
return s_uiGcmLocalMemoryAllocatorMutexLockCount <= 0;
}
struct CPs3gcmLocalMemoryBlockMutable : public CPs3gcmLocalMemoryBlock
{
inline uint32 & MutableOffset() { return m_nLocalMemoryOffset; }
inline uint32 & MutableSize() { return m_uiSize; }
inline CPs3gcmAllocationType_t & MutableType() { return m_uType; }
inline uint32 & MutableIndex() { return m_uiIndex; }
};
#ifdef GCMLOCALMEMORYBLOCKDEBUG
static const uint64 g_GcmLocalMemoryBlockDebugCookieAllocated = 0xA110CA7EDA110CA7ull;
static const uint64 g_GcmLocalMemoryBlockDebugCookieFree = 0xFEEFEEFEEFEEFEEFllu;
#endif
struct CPs3gcmLocalMemoryAllocator
{
//////////////////////////////////////////////////////////////////////////
//
// Allocated memory tracking
//
uint32 m_nOffsetMin; // RSX Local Memory allocated by Initialization that will never be released
uint32 m_nOffsetMax; // Ceiling of allocatable RSX Local Memory (because the top portion is reserved for zcull/etc.), top portion managed separately
uint32 m_nOffsetUnallocated; // RSX Local Memory offset of not yet allocated memory (between Min and Max)
CUtlVector< CPs3gcmLocalMemoryBlockMutable * > m_arrAllocations; // Sorted array of all allocations
//////////////////////////////////////////////////////////////////////////
//
// Free blocks tracking
//
struct LocalMemoryAllocation_t
{
CPs3gcmLocalMemoryBlockMutable m_block;
uint32 m_uiFenceNumber;
LocalMemoryAllocation_t *m_pNext;
};
LocalMemoryAllocation_t *m_pPendingFreeBlock;
LocalMemoryAllocation_t *m_pFreeBlock;
static uint32 sm_uiFenceNumber;
uint32 m_uiFenceLastKnown;
static uint32 volatile *sm_puiFenceLocation;
//////////////////////////////////////////////////////////////////////////
//
// Implementation
//
inline bool Alloc( CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock );
inline void Free( CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock );
inline uint32 Reclaim( bool bForce = false );
inline void Compact();
// Helper methods
inline LocalMemoryAllocation_t * FindFreeBlock( uint32 uiAlignBytes, uint32 uiSize );
inline bool IsFenceCompleted( uint32 uiCurrentFenceValue, uint32 uiCheckStoredFenceValue );
inline void TrackAllocStats( CPs3gcmAllocationType_t uAllocType, int nDelta );
#ifdef GCMLOCALMEMORYBLOCKDEBUG
inline void ValidateAllBlocks();
#endif
}
g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolCount];
uint32 CPs3gcmLocalMemoryAllocator::sm_uiFenceNumber;
uint32 volatile * CPs3gcmLocalMemoryAllocator::sm_puiFenceLocation;
// RSX memory usage stats tracking:
static GPUMemoryStats g_RsxMemoryStats;
struct GPUMemoryStats_Pool
{
int nDefaultPoolSize;
int nDefaultPoolUsed;
int nRTPoolUsed;
int nDynamicPoolUsed;
int nMainMemUsed;
int nUnknownPoolUsed;
};
GPUMemoryStats_Pool g_RsxMemoryStats_Pool;
static inline uint32 Ps3gcmHelper_ComputeTiledAreaMemorySize( uint32 nCount, uint32 w, uint32 h, uint32 bpp )
{
uint32 nTilePitch = cellGcmGetTiledPitchSize( w * bpp );
uint32 uiSize = nTilePitch * AlignValue( h, 32 );
uiSize *= nCount;
uiSize = AlignValue( uiSize, PS3GCMALLOCATIONALIGN( kAllocPs3gcmColorBufferMisc ) );
return uiSize;
}
void Ps3gcmLocalMemoryAllocator_Init()
{
PS3ALLOCMTX
if ( !CPs3gcmLocalMemoryAllocator::sm_puiFenceLocation )
{
CPs3gcmLocalMemoryAllocator::sm_puiFenceLocation = cellGcmGetLabelAddress( GCM_LABEL_MEMORY_FREE );
*CPs3gcmLocalMemoryAllocator::sm_puiFenceLocation = 0;
}
// Pool boundaries
uint32 uiGcmAllocBegin = g_ps3gcmGlobalState.m_nLocalBaseOffset;
uint32 uiGcmAllocEnd = uiGcmAllocBegin + g_ps3gcmGlobalState.m_nLocalSize;
// Memory should be allocated for large frame buffers
uint32 uiMemorySizeBuffer[2] = { MAX( 1280, g_ps3gcmGlobalState.m_nRenderSize[0] ), MAX( 720, g_ps3gcmGlobalState.m_nRenderSize[1] ) };
uint32 uiFactor[2] = { uiMemorySizeBuffer[0]*uiMemorySizeBuffer[1], 1280*720 };
// Configuration of pool memory (can be #ifdef'd for every game)
static const uint32 s_PoolMemoryLayout[/*kGcmAllocPoolCount*/] =
{
#if defined( CSTRIKE15 )
// mhansen - We had to adjust the memory values a bit for cstrike15 to get a map to load
// PS3_BUILDFIX - We need to revisit this to determine the proper size later on
// mdonofrio - render target allocations revisited for PS3
// potential to save some more (~12Mb) from TiledColourFB (only need two really.
// wait for other rendering optimisation/rework to be finished first before attempting.
/*kGcmAllocPoolDefault = */ 0,
/*kGcmAllocPoolDynamicNewPath = */ 5 * 1024 * 1024, // 5 MB
/*kGcmAllocPoolDynamic = */ 11 * 1024 * 1024, // 11 MB
/*kGcmAllocPoolTiledColorFB = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 2 + CPs3gcmDisplay::SURFACE_COUNT, uiMemorySizeBuffer[0], uiMemorySizeBuffer[1], 4 ), // 3 buffers allocated in CreateRSXBuffers + 2 _rt_fullFrameFB - can probably get this down to 2 if we 1. don't use MLAA and 2. we clean up the post-pro rendering to use the front buffer as a textureand 3. tidy up aliasing for rt_fullframeFB and rt_fullFrameFB1
/*kGcmAllocPoolTiledColorFBQ = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 2, uiMemorySizeBuffer[0]/4, uiMemorySizeBuffer[1]/4, 4 ), // fits 2 1/4 size framebuffer textures
/*kGcmAllocPoolTiledColor512 = */ 0,
/*kGcmAllocPoolTiledColorMisc = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 1, 640, 640, 4 ) + Ps3gcmHelper_ComputeTiledAreaMemorySize( 2, 1024, 512, 4) + Ps3gcmHelper_ComputeTiledAreaMemorySize(1, 32, 32, 4), // // 1x 1/2 size smoke/fog buffer, 2xWater(1024x512x32bpp), EyeGlint(32x32x32bpp), *Monitor(256x256x32bpp), *RTTFlashlightShadows(864x864x8bpp) - * we don't need these for CS15
/*kGcmAllocPoolTiledD24S8 = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 2, uiMemorySizeBuffer[0], uiMemorySizeBuffer[1], 4 ), // only 2 depth buffer targets required (current and saved off), + reserve space for 1/2 size depth buffer for smoke/fog
/*kGcmAllocPoolMainMemory = */ 0, // configured based on mapped IO memory
/*kGcmAllocPoolMallocMemory = */ 0, // using malloc
#else
/*kGcmAllocPoolDefault = */ 0,
/*kGcmAllocPoolDynamicNewPath = */ 5 * 1024 * 1024, // 5 MB
/*kGcmAllocPoolDynamic = */ 10 * 1024 * 1024, // 10 MB
/*kGcmAllocPoolTiledColorFB = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 2 * CPs3gcmDisplay::SURFACE_COUNT, uiMemorySizeBuffer[0], uiMemorySizeBuffer[1], 4 ), // fits 6 of full framebuffer textures
/*kGcmAllocPoolTiledColorFBQ = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 4, uiMemorySizeBuffer[0]/4, uiMemorySizeBuffer[1]/4, 4 ), // fits 4 quarters of framebuffer textures
/*kGcmAllocPoolTiledColor512 = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 2, 512, 512, 4 ), // fits 2 512x512 RGBA textures
/*kGcmAllocPoolTiledColorMisc = */ 5 * 1024 * 1024, // 5 MB
/*kGcmAllocPoolTiledD24S8 = */ uint64( 15 * 1024 * 1024 ) * uiFactor[0]/uiFactor[1], // 15 MB
/*kGcmAllocPoolMainMemory = */ 0, // configured based on mapped IO memory
/*kGcmAllocPoolMallocMemory = */ 0, // using malloc
#endif
};
COMPILE_TIME_ASSERT( ARRAYSIZE( s_PoolMemoryLayout ) == ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ) );
for ( int j = ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ); j -- > 0; )
{
const uint32 uiSize = AlignValue( s_PoolMemoryLayout[j], 1024 * 1024 ); // Align it on 1 MB boundaries, all our pools are large
g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMax = uiGcmAllocEnd;
uiGcmAllocEnd -= uiSize;
g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMin =
g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetUnallocated = uiGcmAllocEnd;
}
// Default pool setup (rest of local memory)
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ].m_nOffsetMax = uiGcmAllocEnd;
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ].m_nOffsetMin =
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ].m_nOffsetUnallocated = uiGcmAllocBegin;
// Main memory mapped pool
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ].m_nOffsetMin =
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ].m_nOffsetUnallocated = uint32( g_ps3gcmGlobalState.m_pRsxMainMemoryPoolBuffer ) + g_ps3gcmGlobalState.m_nIoOffsetDelta;
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ].m_nOffsetMax = g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ].m_nOffsetMin + g_ps3gcmGlobalState.m_nRsxMainMemoryPoolBufferSize;
// Store initial capacity for memory stats tracking:
g_RsxMemoryStats.nGPUMemSize = g_ps3gcmGlobalState.m_nLocalSize;
g_RsxMemoryStats_Pool.nDefaultPoolSize = g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ].m_nOffsetMin;
//
// Setup preset tiled regions
//
{
CPs3gcmAllocationPool_t ePool = kGcmAllocPoolTiledColorFB;
uint8 uiBank = 0; // bank 0..3
uint32 nRenderPitch = cellGcmGetTiledPitchSize( g_ps3gcmGlobalState.m_nRenderSize[0] * 4 );
uint8 uiTileIndex = ePool - kGcmAllocPoolTiledColorFB;
cellGcmSetTileInfo( uiTileIndex, CELL_GCM_LOCATION_LOCAL,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
nRenderPitch, CELL_GCM_COMPMODE_DISABLED,
( g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolTiledColorFB ].m_nOffsetMin ) / 0x10000, // The area base + size/0x10000 will be allocated as the tag area.
uiBank );
cellGcmBindTile( uiTileIndex );
}
{
CPs3gcmAllocationPool_t ePool = kGcmAllocPoolTiledColorFBQ;
uint8 uiBank = 1; // bank 0..3
uint32 nRenderPitch = cellGcmGetTiledPitchSize( g_ps3gcmGlobalState.m_nRenderSize[0] * 4 / 4 );
uint8 uiTileIndex = ePool - kGcmAllocPoolTiledColorFB;
cellGcmSetTileInfo( uiTileIndex, CELL_GCM_LOCATION_LOCAL,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
nRenderPitch, CELL_GCM_COMPMODE_DISABLED,
( g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolTiledColorFB ].m_nOffsetMin ) / 0x10000, // The area base + size/0x10000 will be allocated as the tag area.
uiBank );
cellGcmBindTile( uiTileIndex );
}
{
CPs3gcmAllocationPool_t ePool = kGcmAllocPoolTiledColor512;
uint8 uiBank = 2; // bank 0..3
uint32 nRenderPitch = cellGcmGetTiledPitchSize( 512 * 4 );
uint8 uiTileIndex = ePool - kGcmAllocPoolTiledColorFB;
cellGcmSetTileInfo( uiTileIndex, CELL_GCM_LOCATION_LOCAL,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
nRenderPitch, CELL_GCM_COMPMODE_DISABLED,
( g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolTiledColorFB ].m_nOffsetMin ) / 0x10000, // The area base + size/0x10000 will be allocated as the tag area.
uiBank );
cellGcmBindTile( uiTileIndex );
}
#ifndef _CERT
static const char * s_PoolMemoryNames[] =
{
/*kGcmAllocPoolDefault = */ "Default Pool",
/*kGcmAllocPoolDynamicNewPath = */ "Dynamic New ",
/*kGcmAllocPoolDynamic = */ "Dynamic IBVB",
/*kGcmAllocPoolTiledColorFB = */ "FullFrameRTs",
/*kGcmAllocPoolTiledColorFBQ = */ "1/4Frame RTs",
/*kGcmAllocPoolTiledColor512 = */ "512x512 RTs ",
/*kGcmAllocPoolTiledColorMisc = */ "All Misc RTs",
/*kGcmAllocPoolTiledD24S8 = */ "DepthStencil",
/*kGcmAllocPoolMainMemory = */ "Main Memory ",
/*kGcmAllocPoolMallocMemory = */ "MallocMemory",
};
COMPILE_TIME_ASSERT( ARRAYSIZE( s_PoolMemoryNames ) == ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ) );
Msg( "RSX Local Memory layout:\n" );
for ( int j = 0; j < ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ); ++ j )
{
Msg( " %s 0x%08X - 0x%08X [ %9.3f MB ]\n",
s_PoolMemoryNames[j],
g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMin,
g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMax,
(g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMin) / 1024.f / 1024.f );
}
Msg( "Total size: %d MB\n", g_ps3gcmGlobalState.m_nLocalSize / 1024 / 1024 );
#endif
}
void Ps3gcmLocalMemoryAllocator_Reclaim()
{
PS3ALLOCMTX
for ( int k = 0; k < ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ); ++ k )
g_ps3gcmLocalMemoryAllocator[ k ].Reclaim();
}
void Ps3gcmLocalMemoryAllocator_Compact()
{
#define PS3GCMCOMPACTPROFILE 0
#if PS3GCMCOMPACTPROFILE
float flTimeStart = Plat_FloatTime();
uint32 uiFree = g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated;
#endif
// Let RSX wait for final flip
GCM_FUNC( cellGcmSetWaitFlip );
// Let PPU wait for all RSX commands done (include waitFlip)
g_ps3gcmGlobalState.CmdBufferFinish();
#if PS3GCMCOMPACTPROFILE
float flTimeWait = Plat_FloatTime() - flTimeStart;
#endif
{
PS3ALLOCMTX
for ( int k = 0; k < ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ); ++ k )
{
g_ps3gcmLocalMemoryAllocator[ k ].Compact();
}
}
#if PS3GCMCOMPACTPROFILE
float flTimePrepareTransfer = Plat_FloatTime() - flTimeStart;
#endif
// Wait for all RSX memory to be transferred
g_ps3gcmGlobalState.CmdBufferFinish();
#if PS3GCMCOMPACTPROFILE
float flTimeDone = Plat_FloatTime() - flTimeStart;
char chBuffer[64];
Q_snprintf( chBuffer, ARRAYSIZE( chBuffer ), "COMPACT: %0.3f / %0.3f / %0.3f sec\n",
flTimeWait, flTimePrepareTransfer, flTimeDone );
uint32 dummy;
sys_tty_write( SYS_TTYP6, chBuffer, Q_strlen( chBuffer ), &dummy );
Q_snprintf( chBuffer, ARRAYSIZE( chBuffer ), "COMPACT: %0.3f -> %0.3f MB (%0.3f MB free)\n",
uiFree / 1024.f / 1024.f, g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated / 1024.f / 1024.f,
(g_ps3gcmLocalMemoryAllocator[0].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated) / 1024.f / 1024.f );
sys_tty_write( SYS_TTYP6, chBuffer, Q_strlen( chBuffer ), &dummy );
#endif
}
void Ps3gcmLocalMemoryAllocator_CompactWithReason( char const *szReason )
{
double flTimeCompactStart = Plat_FloatTime();
DevMsg( "====== GCM LOCAL MEMORY COMPACT : %s =====\n", szReason );
uint32 uiFreeMemoryBeforeCompact = g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated;
DevMsg( "RSX Local Memory Free: %0.3f MB; compacting...\n", (g_ps3gcmLocalMemoryAllocator[0].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated) / 1024.f / 1024.f );
Ps3gcmLocalMemoryAllocator_Compact();
DevMsg( "RSX Local Memory Compacted %0.3f MB in %0.3f sec\n",
(uiFreeMemoryBeforeCompact - g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated) / 1024.f / 1024.f,
Plat_FloatTime() - flTimeCompactStart );
DevMsg( "RSX Local Memory Free: %0.3f MB\n", (g_ps3gcmLocalMemoryAllocator[0].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated) / 1024.f / 1024.f );
}
bool CPs3gcmLocalMemoryBlock::Alloc()
{
PS3ALLOCMTX
return g_ps3gcmLocalMemoryAllocator[PS3GCMALLOCATIONPOOL(m_uType)].Alloc( reinterpret_cast< CPs3gcmLocalMemoryBlockMutable * >( this ) );
}
void CPs3gcmLocalMemoryBlock::Free()
{
PS3ALLOCMTX
g_ps3gcmLocalMemoryAllocator[PS3GCMALLOCATIONPOOL(m_uType)].Free( reinterpret_cast< CPs3gcmLocalMemoryBlockMutable * >( this ) );
}
//////////////////////////////////////////////////////////////////////////
//
// Private implementation of PS3 local memory allocator
//
inline bool CPs3gcmLocalMemoryAllocator::Alloc( CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock )
{
TrackAllocStats( pBlock->MutableType(), pBlock->MutableSize() );
uint32 uAlignBytes = PS3GCMALLOCATIONALIGN( pBlock->MutableType() );
Assert( IsPowerOfTwo( uAlignBytes ) );
double flAllocatorStallTime = 0.0f;
bool bCompactPerformed = true;
#ifdef GCMLOCALMEMORYBLOCKDEBUG
bCompactPerformed = !r_ps3_gcmlowcompact.GetBool();
#endif
retry_allocation:
// Try to find a free block
if ( LocalMemoryAllocation_t *pFreeBlock = FindFreeBlock( uAlignBytes, pBlock->MutableSize() ) )
{
pBlock->MutableOffset() = pFreeBlock->m_block.MutableOffset();
pBlock->MutableIndex() = pFreeBlock->m_block.MutableIndex();
#ifdef GCMLOCALMEMORYBLOCKDEBUG
if ( m_arrAllocations[ pBlock->MutableIndex() ] != &pFreeBlock->m_block )
Error( "<vitaliy> GCM Local Memory Allocator Error (attempt to reuse invalid free block)!" );
#endif
m_arrAllocations[ pBlock->MutableIndex() ] = reinterpret_cast< CPs3gcmLocalMemoryBlockMutable * >( pBlock );
delete pFreeBlock;
}
else if ( this != &g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMallocMemory ] )
{
// Allocate new block
uint32 uiOldUnallocatedEdge = m_nOffsetUnallocated;
uint32 uiFreeBlock = ( m_nOffsetUnallocated + uAlignBytes - 1 ) & ~( uAlignBytes - 1 );
// Check if there's enough space in this pool for the requested block
if ( uiFreeBlock + pBlock->MutableSize() > m_nOffsetMax )
{
// There's not enough space in this pool
if ( m_pPendingFreeBlock )
{
// There are pending free blocks, we just need to wait for
// RSX to finish rendering using them
if ( !flAllocatorStallTime )
{
flAllocatorStallTime = Plat_FloatTime();
g_ps3gcmGlobalState.CmdBufferFlush( CPs3gcmGlobalState::kFlushForcefully );
}
while ( Reclaim() < pBlock->MutableSize() && m_pPendingFreeBlock )
{
ThreadSleep( 1 );
}
goto retry_allocation;
}
else if ( !bCompactPerformed )
{
// Let PPU wait for all RSX commands done
g_ps3gcmGlobalState.CmdBufferFinish();
uint32 uiFragmentedFreeSpace = m_nOffsetMax - m_nOffsetUnallocated;
for ( LocalMemoryAllocation_t *pFreeFragment = m_pFreeBlock; pFreeFragment; pFreeFragment = pFreeFragment->m_pNext )
uiFragmentedFreeSpace += pFreeFragment->m_block.MutableSize();
Warning(
"**************** GCM LOCAL MEMORY LOW *****************\n"
"<vitaliy> GCM Local Memory Allocator#%d pool compacting!\n"
" Requested allocation %u bytes.\n"
" Pool capacity %u bytes.\n"
" Free fragmented space %u bytes.\n"
" Unallocated %u bytes.\n"
" Used %u bytes.\n",
this - g_ps3gcmLocalMemoryAllocator,
( uint32 ) pBlock->MutableSize(),
m_nOffsetMax - m_nOffsetMin,
uiFragmentedFreeSpace,
m_nOffsetMax - m_nOffsetUnallocated,
m_nOffsetUnallocated - m_nOffsetMin
);
Compact();
Warning( " ---> Compacted pool#%d has %u unallocated bytes.\n",
this - g_ps3gcmLocalMemoryAllocator,
m_nOffsetMax - m_nOffsetUnallocated );
bCompactPerformed = true;
// Wait for all RSX memory to be transferred
g_ps3gcmGlobalState.CmdBufferFinish();
goto retry_allocation;
}
else
{
// Main memory pool returns failure so caller can try local pool.
if (this == &g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ]) return false;
uint32 uiFragmentedFreeSpace = m_nOffsetMax - m_nOffsetUnallocated;
for ( LocalMemoryAllocation_t *pFreeFragment = m_pFreeBlock; pFreeFragment; pFreeFragment = pFreeFragment->m_pNext )
uiFragmentedFreeSpace += pFreeFragment->m_block.MutableSize();
Error(
"********* OUT OF GCM LOCAL MEMORY ********************\n"
"<vitaliy> GCM Local Memory Allocator#%d pool exhausted!\n"
" Failed allocation %u bytes.\n"
" Pool capacity %u bytes.\n"
" Free fragmented space %u bytes.\n"
" Unallocated %u bytes.\n"
" Used %u bytes.\n",
this - g_ps3gcmLocalMemoryAllocator,
( uint32 ) pBlock->MutableSize(),
m_nOffsetMax - m_nOffsetMin,
uiFragmentedFreeSpace,
m_nOffsetMax - m_nOffsetUnallocated,
m_nOffsetUnallocated - m_nOffsetMin
);
}
}
// update the pointer to "unallocated" realm
m_nOffsetUnallocated = uiFreeBlock + pBlock->MutableSize();
// this is the last allocation so far
pBlock->MutableIndex() = m_arrAllocations.AddToTail( reinterpret_cast< CPs3gcmLocalMemoryBlockMutable * >( pBlock ) );
pBlock->MutableOffset() = uiFreeBlock;
}
else
{
MEM_ALLOC_CREDIT_( "GCM Malloc Pool" );
void *pvMallocMemory = MemAlloc_AllocAligned( pBlock->MutableSize(), uAlignBytes );
pBlock->MutableOffset() = (uint32) pvMallocMemory;
pBlock->MutableIndex() = ~0;
}
if ( flAllocatorStallTime )
g_ps3gcmGlobalState.m_flAllocatorStallTimeWaitingRSX += Plat_FloatTime() - flAllocatorStallTime;
#ifdef GCMLOCALMEMORYBLOCKDEBUG
// PS3 doesn't allow more than 8 zcull regions (index 0..7)
if ( g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledD24S8].m_arrAllocations.Count() > 8 )
Error( "PS3 number of zcull regions exceeded!\n" );
// PS3 doesn't allow more than 15 tiles regions (index 0..14)
if ( g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledD24S8].m_arrAllocations.Count() +
g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorMisc].m_arrAllocations.Count() +
( kGcmAllocPoolTiledColorMisc - kGcmAllocPoolTiledColorFB )
> 15 )
Error( "PS3 number of tiled regions exceeded!\n" );
pBlock->m_dbgGuardCookie = g_GcmLocalMemoryBlockDebugCookieAllocated;
#endif
return true;
}
inline void CPs3gcmLocalMemoryAllocator::Free( CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock )
{
#ifdef GCMLOCALMEMORYBLOCKDEBUG
if ( !pBlock ||
pBlock->m_dbgGuardCookie != g_GcmLocalMemoryBlockDebugCookieAllocated ||
( ( pBlock->MutableIndex() != ~0 ) && ( m_arrAllocations[ pBlock->MutableIndex() ] != pBlock ) ) )
{
//DebuggerBreak();
Error( "<vitaliy> Attempt to free not allocated GCM local memory block!" );
}
pBlock->m_dbgGuardCookie = g_GcmLocalMemoryBlockDebugCookieFree;
#endif
LocalMemoryAllocation_t *pDealloc = new LocalMemoryAllocation_t;
pDealloc->m_block = *pBlock;
pDealloc->m_uiFenceNumber = ++ sm_uiFenceNumber;
pDealloc->m_pNext = m_pPendingFreeBlock;
GCM_FUNC( cellGcmSetWriteBackEndLabel, GCM_LABEL_MEMORY_FREE, sm_uiFenceNumber );
m_pPendingFreeBlock = pDealloc;
TrackAllocStats( pBlock->MutableType(), - pBlock->MutableSize() );
if ( pBlock->MutableIndex() != ~0 )
{
#ifdef GCMLOCALMEMORYBLOCKDEBUG
if ( m_arrAllocations[ pBlock->MutableIndex() ] != pBlock )
Error( "<vitaliy> GCM Local Memory Allocator Error (freeing block that is not properly registered)!" );
#endif
m_arrAllocations[ pBlock->MutableIndex() ] = &pDealloc->m_block;
}
#ifdef GCMLOCALMEMORYBLOCKDEBUG
pBlock->MutableOffset() = ~0;
pBlock->MutableIndex() = ~0;
#endif
}
inline bool CPs3gcmLocalMemoryAllocator::IsFenceCompleted( uint32 uiCurrentFenceValue, uint32 uiCheckStoredFenceValue )
{
#if GCM_ALLOW_NULL_FLIPS
extern bool g_ps3_nullflips;
if ( g_ps3_nullflips )
return true;
#endif
// Needs to handle the counter wrapping around
return ( ( uiCurrentFenceValue - m_uiFenceLastKnown ) >= ( uiCheckStoredFenceValue - m_uiFenceLastKnown ) );
}
inline uint32 CPs3gcmLocalMemoryAllocator::Reclaim( bool bForce )
{
uint32 uiLargestBlockSizeReclaimed = 0;
uint32 uiCurrentFenceValue = *sm_puiFenceLocation;
// Walk pending free blocks and see if they are no longer
// in use by RSX:
LocalMemoryAllocation_t **p = &m_pPendingFreeBlock;
if ( !bForce ) while ( (*p) && !IsFenceCompleted( uiCurrentFenceValue, (*p)->m_uiFenceNumber ) )
p = &( (*p)->m_pNext );
// Now p is pointing to the chain of free blocks
// chain that has been completed (due to the nature of
// pushing new deallocation at the head of the pending
// list)
if ( *p )
{
LocalMemoryAllocation_t *pCompletedChain = *p;
*p = NULL; // Terminate the chain
// Handle the special case of malloc reclaim - free all memory
if ( this == &g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMallocMemory ] )
{
MEM_ALLOC_CREDIT_( "GCM Malloc Pool" );
for ( LocalMemoryAllocation_t *pActualFree = pCompletedChain; pActualFree; )
{
MemAlloc_FreeAligned( pActualFree->m_block.DataInMallocMemory() );
LocalMemoryAllocation_t *pDelete = pActualFree;
pActualFree = pActualFree->m_pNext;
delete pDelete;
}
pCompletedChain = NULL;
}
// Relink the completed pending chain into
// the free blocks chain
LocalMemoryAllocation_t **ppFree = &m_pFreeBlock;
while ( *ppFree )
ppFree = &( (*ppFree)->m_pNext );
*ppFree = pCompletedChain;
// Recompute actual free sizes of the completed chain
// Actual free size is the delta between block offset and next block offset
// When there's no next block then its delta between block offset and unallocated edge
for ( LocalMemoryAllocation_t *pActualFree = pCompletedChain; pActualFree; pActualFree = pActualFree->m_pNext )
{
uint32 uiIdx = pActualFree->m_block.MutableIndex() + 1;
uint32 uiNextOffset = m_nOffsetUnallocated;
if ( uiIdx < m_arrAllocations.Count() )
{
CPs3gcmLocalMemoryBlockMutable * RESTRICT pNextBlock = m_arrAllocations[ uiIdx ];
uiNextOffset = pNextBlock->Offset();
}
uint32 uiActualBlockSize = uiNextOffset - pActualFree->m_block.Offset();
pActualFree->m_block.MutableSize() = uiActualBlockSize;
uiLargestBlockSizeReclaimed = MAX( uiLargestBlockSizeReclaimed, uiActualBlockSize );
}
}
// Remember the last known fence value
m_uiFenceLastKnown = uiCurrentFenceValue;
#ifdef GCMLOCALMEMORYBLOCKDEBUG
ValidateAllBlocks();
#endif
return uiLargestBlockSizeReclaimed;
}
inline CPs3gcmLocalMemoryAllocator::LocalMemoryAllocation_t * CPs3gcmLocalMemoryAllocator::FindFreeBlock( uint32 uiAlignBytes, uint32 uiSize )
{
LocalMemoryAllocation_t **ppBest = NULL;
uint32 uiSizeMax = uiSize * 11/10; // we don't want to inflate requested size by > 10%
for ( LocalMemoryAllocation_t **p = &m_pFreeBlock;
(*p);
p = &( (*p)->m_pNext ) )
{
if ( (*p)->m_block.MutableSize() >= uiSize && (*p)->m_block.MutableSize() <= uiSizeMax &&
!( (*p)->m_block.Offset() & ( uiAlignBytes - 1 ) ) )
{
if ( !ppBest || ( (*p)->m_block.MutableSize() <= (*ppBest)->m_block.MutableSize() ) )
{
ppBest = p;
}
}
}
if ( ppBest )
{
LocalMemoryAllocation_t *pFree = (*ppBest);
(*ppBest) = pFree->m_pNext;
pFree->m_pNext = NULL;
return pFree;
}
return NULL;
}
inline bool TrackAllocStats_Pool( CPs3gcmAllocationType_t uAllocType, int nDelta )
{
CPs3gcmAllocationPool_t pool = PS3GCMALLOCATIONPOOL( uAllocType );
int *stat = &g_RsxMemoryStats_Pool.nUnknownPoolUsed;
bool bInRSXMem = true;
switch( pool )
{
case kGcmAllocPoolDefault:
stat = &g_RsxMemoryStats_Pool.nDefaultPoolUsed;
break;
case kGcmAllocPoolDynamicNewPath:
case kGcmAllocPoolDynamic:
stat = &g_RsxMemoryStats_Pool.nDynamicPoolUsed;
break;
case kGcmAllocPoolTiledColorFB:
case kGcmAllocPoolTiledColorFBQ:
case kGcmAllocPoolTiledColor512:
case kGcmAllocPoolTiledColorMisc:
case kGcmAllocPoolTiledD24S8:
stat = &g_RsxMemoryStats_Pool.nRTPoolUsed;
break;
case kGcmAllocPoolMainMemory: // Unused, unless PS3GCM_VBIB_IN_IO_MEMORY set to 1
case kGcmAllocPoolMallocMemory:
stat = &g_RsxMemoryStats_Pool.nMainMemUsed;
bInRSXMem = false; // In main memory!
break;
}
*stat += nDelta;
Assert( 0 <= (int)*stat );
// Report free memory only from the default pool (the other pools are pre-sized to fixed limits, and all
// geom/textures go into the default pool, so that's where content-driven variation/failures will occur)
g_RsxMemoryStats.nGPUMemFree = g_RsxMemoryStats_Pool.nDefaultPoolSize - g_RsxMemoryStats_Pool.nDefaultPoolUsed;
return bInRSXMem;
}
inline void CPs3gcmLocalMemoryAllocator::TrackAllocStats( CPs3gcmAllocationType_t uAllocType, int nDelta )
{
#if TRACK_ALLOC_STATS
// Early-out for allocations not in RSX memory:
if ( !TrackAllocStats_Pool( uAllocType, nDelta ) )
return;
unsigned int *stat = &g_RsxMemoryStats.nUnknown;
switch( uAllocType )
{
case kAllocPs3gcmColorBufferMisc:
case kAllocPs3gcmColorBufferFB:
case kAllocPs3gcmColorBufferFBQ:
case kAllocPs3gcmColorBuffer512:
case kAllocPs3gcmDepthBuffer:
stat = &g_RsxMemoryStats.nRTSize;
break;
case kAllocPs3gcmTextureData:
case kAllocPs3gcmTextureData0:
stat = &g_RsxMemoryStats.nTextureSize;
break;
case kAllocPs3GcmVertexBuffer:
stat = &g_RsxMemoryStats.nVBSize;
break;
case kAllocPs3GcmIndexBuffer:
stat = &g_RsxMemoryStats.nIBSize;
break;
case kAllocPs3GcmShader:
case kAllocPs3GcmEdgeGeomBuffer:
case kAllocPs3GcmVertexBufferDynamic:
case kAllocPs3GcmIndexBufferDynamic:
case kAllocPs3GcmDynamicBufferPool:
case kAllocPs3GcmVertexBufferDma:
case kAllocPs3GcmIndexBufferDma:
// Treat these as misc unless they become big/variable
break;
}
*stat += nDelta;
Assert( 0 <= (int)*stat );
#endif // TRACK_ALLOC_STATS
}
#ifdef GCMLOCALMEMORYBLOCKDEBUG
#define VALIDATECONDITION( x ) if( !( x ) ) { Error( "<vitaliy> GCM Local Memory Allocation block %p index %d is corrupt [line %d]!\n", pBlock, k, __LINE__ ); }
inline void CPs3gcmLocalMemoryAllocator::ValidateAllBlocks()
{
// Traverse the allocated list and validate debug guards and patch-back indices
CUtlVector< uint32 > arrFreeBlocksIdx;
uint32 uiLastAllocatedOffset = m_nOffsetMin;
for ( int k = 0, kEnd = m_arrAllocations.Count(); k < kEnd; ++ k )
{
CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock = m_arrAllocations[k];
VALIDATECONDITION( pBlock );
VALIDATECONDITION( pBlock->m_dbgGuardCookie == g_GcmLocalMemoryBlockDebugCookieAllocated || pBlock->m_dbgGuardCookie == g_GcmLocalMemoryBlockDebugCookieFree );
VALIDATECONDITION( pBlock->MutableIndex() < m_arrAllocations.Count() );
VALIDATECONDITION( pBlock->MutableIndex() == k );
VALIDATECONDITION( m_arrAllocations[ pBlock->MutableIndex() ] == pBlock );
VALIDATECONDITION( pBlock->Offset() >= uiLastAllocatedOffset );
uiLastAllocatedOffset = pBlock->Offset() + pBlock->MutableSize();
VALIDATECONDITION( uiLastAllocatedOffset <= m_nOffsetMax );
if ( pBlock->m_dbgGuardCookie == g_GcmLocalMemoryBlockDebugCookieFree )
arrFreeBlocksIdx.AddToTail( k );
}
// Traverse free lists and validate
LocalMemoryAllocation_t * arrFree[] = { m_pPendingFreeBlock, m_pFreeBlock };
for ( int j = 0; j < ARRAYSIZE( arrFree ); ++ j )
for ( LocalMemoryAllocation_t *p = arrFree[j]; p; p = p->m_pNext )
{
int k = j;
CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock = &p->m_block;
VALIDATECONDITION( pBlock );
VALIDATECONDITION( pBlock->m_dbgGuardCookie == g_GcmLocalMemoryBlockDebugCookieFree );
k = pBlock->MutableIndex();
if ( pBlock->MutableIndex() != ~0 )
{
VALIDATECONDITION( pBlock->MutableIndex() < m_arrAllocations.Count() );
VALIDATECONDITION( m_arrAllocations[ pBlock->MutableIndex() ] == pBlock );
VALIDATECONDITION( arrFreeBlocksIdx.FindAndFastRemove( pBlock->MutableIndex() ) );
}
}
int k = 0;
void *pBlock = 0;
VALIDATECONDITION( !arrFreeBlocksIdx.Count() );
}
#endif
inline void CPs3gcmLocalMemoryAllocator::Compact()
{
GCM_PERF_PUSH_MARKER( "LocalMemory:Compact" );
#ifdef GCMLOCALMEMORYBLOCKDEBUG
ValidateAllBlocks();
if ( r_ps3_gcmnocompact.GetBool() )
return;
#endif
// Reclaim all memory (NOTE: all pending blocks must be reclaimed since both RSX and PPU have stopped rendering!)
Reclaim();
#ifdef GCMLOCALMEMORYBLOCKDEBUG
if ( m_pPendingFreeBlock )
Warning( "GCM Local Memory Allocator Compact forces pending free blocks to be reclaimed.\n" );
ValidateAllBlocks();
#endif
if ( m_pPendingFreeBlock )
Reclaim( true );
#ifdef GCMLOCALMEMORYBLOCKDEBUG
if ( m_pPendingFreeBlock )
Error( "<vitaliy> GCM Local Memory Allocator Compact requires RSX and PPU rendering to be paused! (pending free blocks have not been reclaimed)\n" );
ValidateAllBlocks();
#endif
// Walk the free blocks chain and patch-back NULL pointers into allocation tracking system
while ( m_pFreeBlock )
{
LocalMemoryAllocation_t *p = m_pFreeBlock;
m_pFreeBlock = p->m_pNext;
m_arrAllocations[ p->m_block.MutableIndex() ] = NULL;
delete p;
}
Assert( !m_pFreeBlock && !m_pPendingFreeBlock );
// These are elements requiring reallocation
uint32 uiCount = m_arrAllocations.Count();
CPs3gcmLocalMemoryBlockMutable **pReallocationBlocks = m_arrAllocations.Base();
// Here "correct" implementation would be to copy off m_arrAllocations vector onto stack for iteration,
// RemoveAll from m_arrAllocations vector and allocate all blocks again.
// We will cheat since we know that we will allocate same number of elements and directly write zero
// into m_arrAllocations m_Size member, then we will still be able to use the memory of the vector
// for reading blocks requiring compact reallocation, and AddToTail will still fill the vector with
// correct data.
struct AllocatorCompactVectorCheat : public CUtlVector< CPs3gcmLocalMemoryBlockMutable * > { inline void ResetCountPreservingMemoryContents() { m_Size = 0; } };
( ( AllocatorCompactVectorCheat * ) ( char * ) &m_arrAllocations )->ResetCountPreservingMemoryContents();
m_nOffsetUnallocated = m_nOffsetMin;
// Prepare RSX for data buffer transfers in local memory
uint nTransferMode = ( ( this - &g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ] ) < kGcmAllocPoolMainMemory ) ? CELL_GCM_TRANSFER_LOCAL_TO_LOCAL : CELL_GCM_TRANSFER_MAIN_TO_MAIN;
Assert( nTransferMode < 4 );
GCM_FUNC( cellGcmSetTransferDataMode, nTransferMode ); // unnecessary if we do this on SPU
Assert( !g_spuGcm.IsDeferredDrawQueue() );
// Reallocate all blocks
for ( ; uiCount; -- uiCount, ++ pReallocationBlocks )
{
CPs3gcmLocalMemoryBlockMutable *pBlock = *pReallocationBlocks;
if ( !pBlock )
continue;
uint32 nOldOffset = pBlock->Offset();
TrackAllocStats( pBlock->MutableType(), - pBlock->MutableSize() );
Alloc( pBlock );
if ( nOldOffset == pBlock->Offset() )
continue;
// Have RSX transfer blocks data. RSX may hang if there's WriteLabel between the Format and Offset commands,
// so reserve space for both of them up front
SpuDrawTransfer_t * pTransfer = g_spuGcm.GetDrawQueue()->AllocWithHeader<SpuDrawTransfer_t>( SPUDRAWQUEUE_TRANSFER_METHOD | nTransferMode );
pTransfer->m_nLineSize = pBlock->MutableSize();
pTransfer->m_nOldOffset = nOldOffset;
pTransfer->m_nNewOffset = pBlock->Offset();
}
#ifdef GCMLOCALMEMORYBLOCKDEBUG
ValidateAllBlocks();
#endif
GCM_PERF_MARKER( "Compact:Complete" );
}
//////////////////////////////////////////////////////////////////////////
//
// Computation of tiled memory
//
uint32 CPs3gcmLocalMemoryBlock::TiledMemoryTagAreaBase() const
{
CPs3gcmAllocationPool_t ePool = PS3GCMALLOCATIONPOOL(m_uType);
if ( ePool == kGcmAllocPoolTiledColorMisc ) // Misc color tiles are placed at the front of tag area after preset pools
return ( Offset() - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFB].m_nOffsetMin ) / 0x10000;
if ( ePool == kGcmAllocPoolTiledD24S8 ) // Depth tiles are placed in the end of tag area (0-0x7FF is offset range)
return 0x800 - ( Offset() - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledD24S8].m_nOffsetMin + m_uiSize ) / 0x10000;
if ( ePool == kGcmAllocPoolTiledColorFB ) // FB color tiles go first
return ( g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFB].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFB].m_nOffsetMin ) / 0x10000;
if ( ePool == kGcmAllocPoolTiledColorFBQ ) // FBQ color tiles go next
return ( g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFBQ].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFB].m_nOffsetMin ) / 0x10000;
if ( ePool == kGcmAllocPoolTiledColor512 ) // 512 color tiles go next
return ( g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColor512].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFB].m_nOffsetMin ) / 0x10000;
#ifdef GCMLOCALMEMORYBLOCKDEBUG
Error( "<vitaliy> Cannot compute tiled memory tag base from a non-tiled-pool allocation!\n" );
#endif
return ~0;
}
uint32 CPs3gcmLocalMemoryBlock::TiledMemoryIndex() const
{
CPs3gcmAllocationPool_t ePool = PS3GCMALLOCATIONPOOL(m_uType);
if ( ePool == kGcmAllocPoolTiledColorMisc ) // Color tiles are placed in the front
return m_uiIndex + kGcmAllocPoolTiledColorMisc - kGcmAllocPoolTiledColorFB;
if ( ePool == kGcmAllocPoolTiledD24S8 ) // Depth tiles are placed as last tiles
return 14 - m_uiIndex;
return ePool - kGcmAllocPoolTiledColorFB;
}
uint32 CPs3gcmLocalMemoryBlock::ZcullMemoryIndex() const
{
CPs3gcmAllocationPool_t ePool = PS3GCMALLOCATIONPOOL(m_uType);
if ( ePool == kGcmAllocPoolTiledD24S8 ) // Depth tiles are the only zcull tiles
return m_uiIndex;
#ifdef GCMLOCALMEMORYBLOCKDEBUG
Error( "<vitaliy> Cannot compute zcull index from a non-zcull allocation!\n" );
#endif
return ~0;
}
uint32 CPs3gcmLocalMemoryBlock::ZcullMemoryStart() const
{
CPs3gcmAllocationPool_t ePool = PS3GCMALLOCATIONPOOL(m_uType);
if ( ePool == kGcmAllocPoolTiledD24S8 ) // Depth tiles are the only zcull tiles
return ( Offset() - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledD24S8].m_nOffsetMin ) / 4; // 1 byte per pixel, D24S8 is 4 bytes per pixel, implicitly 4096 aligned because offset is 64Kb aligned
#ifdef GCMLOCALMEMORYBLOCKDEBUG
Error( "<vitaliy> Cannot compute zcull memory start from a non-zcull allocation!\n" );
#endif
return ~0;
}
//////////////////////////////////////////////////////////////////////////
//
// Allow shaderapi to query GPU memory stats:
//
void GetGPUMemoryStats( GPUMemoryStats &stats )
{
stats = g_RsxMemoryStats;
}
+995
View File
@@ -0,0 +1,995 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
// GCM memory allocation mgmt
//
//==================================================================================================
#include "utlmap.h"
#include "sys/tty.h"
#include "convar.h"
#include "ps3gcmmemory.h"
#include "gcmlabels.h"
#include "gcmstate.h"
#include "gcmdrawstate.h"
#include "memdbgon.h"
PLATFORM_OVERRIDE_MEM_ALLOC_INTERNAL_PS3_IMPL
#define HARDWARE_CURSOR_SIZE (64*64*4)
//--------------------------------------------------------------------------------------------------
// GCM memory allocators
//--------------------------------------------------------------------------------------------------
#if 1 // #ifndef _CERT
#define TRACK_ALLOC_STATS 1
#endif
#ifdef GCMLOCALMEMORYBLOCKDEBUG
ConVar r_ps3_gcmnocompact( "r_ps3_gcmnocompact", "0" );
ConVar r_ps3_gcmlowcompact( "r_ps3_gcmlowcompact", "1" );
#endif
static CThreadFastMutex s_AllocMutex;
static int32 s_uiGcmLocalMemoryAllocatorMutexLockCount;
struct CGcmLocalMemoryAllocatorMutexLockCounter_t
{
CGcmLocalMemoryAllocatorMutexLockCounter_t() { Assert( s_uiGcmLocalMemoryAllocatorMutexLockCount >= 0 ); ++ s_uiGcmLocalMemoryAllocatorMutexLockCount; }
~CGcmLocalMemoryAllocatorMutexLockCounter_t() { Assert( s_uiGcmLocalMemoryAllocatorMutexLockCount > 0 ); -- s_uiGcmLocalMemoryAllocatorMutexLockCount; }
};
#define PS3ALLOCMTX AUTO_LOCK( s_AllocMutex ); CGcmLocalMemoryAllocatorMutexLockCounter_t aLockCounter;
bool IsItSafeToRefreshFrontBufferNonInteractivePs3()
{
// NOTE: only main thread can refresh front buffer
if ( !ThreadInMainThread() )
return false;
AUTO_LOCK( s_AllocMutex );
Assert( s_uiGcmLocalMemoryAllocatorMutexLockCount >= 0 );
return s_uiGcmLocalMemoryAllocatorMutexLockCount <= 0;
}
struct CPs3gcmLocalMemoryBlockMutable : public CPs3gcmLocalMemoryBlock
{
inline uint32 & MutableOffset() { return m_nLocalMemoryOffset; }
inline uint32 & MutableSize() { return m_uiSize; }
inline CPs3gcmAllocationType_t & MutableType() { return m_uType; }
inline uint32 & MutableIndex() { return m_uiIndex; }
};
#ifdef GCMLOCALMEMORYBLOCKDEBUG
static const uint64 g_GcmLocalMemoryBlockDebugCookieAllocated = 0xA110CA7EDA110CA7ull;
static const uint64 g_GcmLocalMemoryBlockDebugCookieFree = 0xFEEFEEFEEFEEFEEFllu;
#endif
struct CPs3gcmLocalMemoryAllocator
{
//////////////////////////////////////////////////////////////////////////
//
// Allocated memory tracking
//
uint32 m_nOffsetMin; // RSX Local Memory allocated by Initialization that will never be released
uint32 m_nOffsetMax; // Ceiling of allocatable RSX Local Memory (because the top portion is reserved for zcull/etc.), top portion managed separately
uint32 m_nOffsetUnallocated; // RSX Local Memory offset of not yet allocated memory (between Min and Max)
CUtlVector< CPs3gcmLocalMemoryBlockMutable * > m_arrAllocations; // Sorted array of all allocations
//////////////////////////////////////////////////////////////////////////
//
// Free blocks tracking
//
struct LocalMemoryAllocation_t
{
CPs3gcmLocalMemoryBlockMutable m_block;
uint32 m_uiFenceNumber;
LocalMemoryAllocation_t *m_pNext;
};
LocalMemoryAllocation_t *m_pPendingFreeBlock;
LocalMemoryAllocation_t *m_pFreeBlock;
static uint32 sm_uiFenceNumber;
uint32 m_uiFenceLastKnown;
static uint32 volatile *sm_puiFenceLocation;
//////////////////////////////////////////////////////////////////////////
//
// Implementation
//
inline bool Alloc( CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock );
inline void Free( CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock );
inline uint32 Reclaim( bool bForce = false );
inline void Compact();
// Helper methods
inline LocalMemoryAllocation_t * FindFreeBlock( uint32 uiAlignBytes, uint32 uiSize );
inline bool IsFenceCompleted( uint32 uiCurrentFenceValue, uint32 uiCheckStoredFenceValue );
inline void TrackAllocStats( CPs3gcmAllocationType_t uAllocType, int nDelta );
#ifdef GCMLOCALMEMORYBLOCKDEBUG
inline void ValidateAllBlocks();
#endif
}
g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolCount];
uint32 CPs3gcmLocalMemoryAllocator::sm_uiFenceNumber = 1;
uint32 volatile * CPs3gcmLocalMemoryAllocator::sm_puiFenceLocation;
// RSX memory usage stats tracking:
static GPUMemoryStats g_RsxMemoryStats;
struct GPUMemoryStats_Pool
{
int nDefaultPoolSize;
int nDefaultPoolUsed;
int nRTPoolUsed;
int nDynamicPoolUsed;
int nMainMemUsed;
int nUnknownPoolUsed;
};
GPUMemoryStats_Pool g_RsxMemoryStats_Pool;
static inline uint32 Ps3gcmHelper_ComputeTiledAreaMemorySize( uint32 nCount, uint32 w, uint32 h, uint32 bpp )
{
uint32 nTilePitch = cellGcmGetTiledPitchSize( w * bpp );
uint32 uiSize = nTilePitch * AlignValue( h, 32 );
uiSize *= nCount;
uiSize = AlignValue( uiSize, PS3GCMALLOCATIONALIGN( kAllocPs3gcmColorBufferMisc ) );
return uiSize;
}
void Ps3gcmLocalMemoryAllocator_Init()
{
PS3ALLOCMTX
if ( !CPs3gcmLocalMemoryAllocator::sm_puiFenceLocation )
{
CPs3gcmLocalMemoryAllocator::sm_puiFenceLocation = cellGcmGetLabelAddress( GCM_LABEL_MEMORY_FREE );
*CPs3gcmLocalMemoryAllocator::sm_puiFenceLocation = 0;
}
// Pool boundaries
uint32 uiGcmAllocBegin = g_ps3gcmGlobalState.m_nLocalBaseOffset;
uint32 uiGcmAllocEnd = uiGcmAllocBegin + g_ps3gcmGlobalState.m_nLocalSize;
// Memory should be allocated for large frame buffers
uint32 uiMemorySizeBuffer[2] = { MAX( 1280, g_ps3gcmGlobalState.m_nRenderSize[0] ), MAX( 720, g_ps3gcmGlobalState.m_nRenderSize[1] ) };
uint32 uiFactor[2] = { uiMemorySizeBuffer[0]*uiMemorySizeBuffer[1], 1280*720 };
// Configuration of pool memory (can be #ifdef'd for every game)
static const uint32 s_PoolMemoryLayout[/*kGcmAllocPoolCount*/] =
{
#if defined( CSTRIKE15 )
// mhansen - We had to adjust the memory values a bit for cstrike15 to get a map to load
// PS3_BUILDFIX - We need to revisit this to determine the proper size later on
/*kGcmAllocPoolDefault = */ 0,
/*kGcmAllocPoolDynamicNewPath = */ 6 * 1024 * 1024, // 5 MB
/*kGcmAllocPoolDynamic = */ 11 * 1024 * 1024, // 11 MB
/*kGcmAllocPoolTiledColorFB = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 2 + CPs3gcmDisplay::SURFACE_COUNT, uiMemorySizeBuffer[0], uiMemorySizeBuffer[1], 4 ),
// 2 buffers allocated in CreateRSXBuffers + 2 _rt_fullFrameFB - can probably get this down if...
// 1. we clean up the post-pro rendering to use the front buffer as a textureand
// 2. tidy up aliasing for rt_fullframeFB and rt_fullFrameFB1
/*kGcmAllocPoolTiledColorFBQ = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 2, uiMemorySizeBuffer[0]/4, uiMemorySizeBuffer[1]/4, 4 ), // fits 2 1/4 size framebuffer textures
/*kGcmAllocPoolTiledColor512 = */ 0,
/*kGcmAllocPoolTiledColorMisc = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 1, 640, 640, 4 ) // RTT shadows ?
+ Ps3gcmHelper_ComputeTiledAreaMemorySize( 2, 1024, 512, 4) // Water
+ Ps3gcmHelper_ComputeTiledAreaMemorySize(1, 32, 32, 4), // Eye Glint
/*kGcmAllocPoolTiledD24S8 = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 1, 640*2, 640*2, 2)
+ Ps3gcmHelper_ComputeTiledAreaMemorySize(1, 640, 640, 2) // CSM and Flashlight
+ Ps3gcmHelper_ComputeTiledAreaMemorySize( 1, uiMemorySizeBuffer[0], uiMemorySizeBuffer[1], 4 ), // Main depth buffer
/*kGcmAllocPoolMainMemory = */ 0, // configured based on mapped IO memory
/*kGcmAllocPoolMallocMemory = */ 0, // using malloc
#else
/*kGcmAllocPoolDefault = */ 0,
/*kGcmAllocPoolDynamicNewPath = */ 5 * 1024 * 1024, // 5 MB
/*kGcmAllocPoolDynamic = */ 10 * 1024 * 1024, // 10 MB
/*kGcmAllocPoolTiledColorFB = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 2 * CPs3gcmDisplay::SURFACE_COUNT, uiMemorySizeBuffer[0], uiMemorySizeBuffer[1], 4 ), // fits 6 of full framebuffer textures
/*kGcmAllocPoolTiledColorFBQ = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 4, uiMemorySizeBuffer[0]/4, uiMemorySizeBuffer[1]/4, 4 ), // fits 4 quarters of framebuffer textures
/*kGcmAllocPoolTiledColor512 = */ Ps3gcmHelper_ComputeTiledAreaMemorySize( 2, 512, 512, 4 ), // fits 2 512x512 RGBA textures
/*kGcmAllocPoolTiledColorMisc = */ 5 * 1024 * 1024, // 5 MB
/*kGcmAllocPoolTiledD24S8 = */ uint64( 15 * 1024 * 1024 ) * uiFactor[0]/uiFactor[1], // 15 MB
/*kGcmAllocPoolMainMemory = */ 0, // configured based on mapped IO memory
/*kGcmAllocPoolMallocMemory = */ 0, // using malloc
#endif
};
COMPILE_TIME_ASSERT( ARRAYSIZE( s_PoolMemoryLayout ) == ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ) );
for ( int j = ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ); j -- > 0; )
{
const uint32 uiSize = AlignValue( s_PoolMemoryLayout[j], 1024 * 1024 ); // Align it on 1 MB boundaries, all our pools are large
g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMax = uiGcmAllocEnd;
uiGcmAllocEnd -= uiSize;
g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMin =
g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetUnallocated = uiGcmAllocEnd;
}
// Default pool setup (rest of local memory)
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ].m_nOffsetMax = uiGcmAllocEnd;
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ].m_nOffsetMin =
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ].m_nOffsetUnallocated = uiGcmAllocBegin + HARDWARE_CURSOR_SIZE;
// Main memory mapped pool
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ].m_nOffsetMin =
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ].m_nOffsetUnallocated = uint32( g_ps3gcmGlobalState.m_pRsxMainMemoryPoolBuffer ) + g_ps3gcmGlobalState.m_nIoOffsetDelta;
g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ].m_nOffsetMax = g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ].m_nOffsetMin + g_ps3gcmGlobalState.m_nRsxMainMemoryPoolBufferSize;
// Store initial capacity for memory stats tracking:
g_RsxMemoryStats.nGPUMemSize = g_ps3gcmGlobalState.m_nLocalSize;
g_RsxMemoryStats_Pool.nDefaultPoolSize = g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ].m_nOffsetMin;
//
// Setup preset tiled regions
//
{
CPs3gcmAllocationPool_t ePool = kGcmAllocPoolTiledColorFB;
uint8 uiBank = 0; // bank 0..3
uint32 nRenderPitch = cellGcmGetTiledPitchSize( g_ps3gcmGlobalState.m_nRenderSize[0] * 4 );
uint8 uiTileIndex = ePool - kGcmAllocPoolTiledColorFB;
cellGcmSetTileInfo( uiTileIndex, CELL_GCM_LOCATION_LOCAL,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
nRenderPitch, CELL_GCM_COMPMODE_DISABLED,
( g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolTiledColorFB ].m_nOffsetMin ) / 0x10000, // The area base + size/0x10000 will be allocated as the tag area.
uiBank );
cellGcmBindTile( uiTileIndex );
}
{
CPs3gcmAllocationPool_t ePool = kGcmAllocPoolTiledColorFBQ;
uint8 uiBank = 1; // bank 0..3
uint32 nRenderPitch = cellGcmGetTiledPitchSize( g_ps3gcmGlobalState.m_nRenderSize[0] * 4 / 4 );
uint8 uiTileIndex = ePool - kGcmAllocPoolTiledColorFB;
cellGcmSetTileInfo( uiTileIndex, CELL_GCM_LOCATION_LOCAL,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
nRenderPitch, CELL_GCM_COMPMODE_DISABLED,
( g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolTiledColorFB ].m_nOffsetMin ) / 0x10000, // The area base + size/0x10000 will be allocated as the tag area.
uiBank );
cellGcmBindTile( uiTileIndex );
}
{
CPs3gcmAllocationPool_t ePool = kGcmAllocPoolTiledColor512;
uint8 uiBank = 2; // bank 0..3
uint32 nRenderPitch = cellGcmGetTiledPitchSize( 512 * 4 );
uint8 uiTileIndex = ePool - kGcmAllocPoolTiledColorFB;
cellGcmSetTileInfo( uiTileIndex, CELL_GCM_LOCATION_LOCAL,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin,
nRenderPitch, CELL_GCM_COMPMODE_DISABLED,
( g_ps3gcmLocalMemoryAllocator[ ePool ].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolTiledColorFB ].m_nOffsetMin ) / 0x10000, // The area base + size/0x10000 will be allocated as the tag area.
uiBank );
cellGcmBindTile( uiTileIndex );
}
#ifndef _CERT
static const char * s_PoolMemoryNames[] =
{
/*kGcmAllocPoolDefault = */ "Default Pool",
/*kGcmAllocPoolDynamicNewPath = */ "Dynamic New ",
/*kGcmAllocPoolDynamic = */ "Dynamic IBVB",
/*kGcmAllocPoolTiledColorFB = */ "FullFrameRTs",
/*kGcmAllocPoolTiledColorFBQ = */ "1/4Frame RTs",
/*kGcmAllocPoolTiledColor512 = */ "512x512 RTs ",
/*kGcmAllocPoolTiledColorMisc = */ "All Misc RTs",
/*kGcmAllocPoolTiledD24S8 = */ "DepthStencil",
/*kGcmAllocPoolMainMemory = */ "Main Memory ",
/*kGcmAllocPoolMallocMemory = */ "MallocMemory",
};
COMPILE_TIME_ASSERT( ARRAYSIZE( s_PoolMemoryNames ) == ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ) );
Msg( "RSX Local Memory layout:\n" );
for ( int j = 0; j < ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ); ++ j )
{
Msg( " %s 0x%08X - 0x%08X [ %9.3f MB ]\n",
s_PoolMemoryNames[j],
g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMin,
g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMax,
(g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[ j ].m_nOffsetMin) / 1024.f / 1024.f );
}
Msg( "Total size: %d MB\n", g_ps3gcmGlobalState.m_nLocalSize / 1024 / 1024 );
#endif
}
void Ps3gcmLocalMemoryAllocator_Reclaim()
{
PS3ALLOCMTX
for ( int k = 0; k < ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ); ++ k )
g_ps3gcmLocalMemoryAllocator[ k ].Reclaim();
}
void Ps3gcmLocalMemoryAllocator_Compact()
{
PS3ALLOCMTX
#define PS3GCMCOMPACTPROFILE 0
#if PS3GCMCOMPACTPROFILE
float flTimeStart = Plat_FloatTime();
uint32 uiFree = g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated;
#endif
// Let PPU wait for all RSX commands done (include waitFlip)
// Flush GPU right up to current point - Endframe call does this...
gpGcmDrawState->EndFrame();
gpGcmDrawState->CmdBufferFinish();
#if PS3GCMCOMPACTPROFILE
float flTimeWait = Plat_FloatTime() - flTimeStart;
#endif
{
// Locking out memory mgmt for the whole of the compact before this
// PS3ALLOCMTX
for ( int k = 0; k < ARRAYSIZE( g_ps3gcmLocalMemoryAllocator ); ++ k )
{
g_ps3gcmLocalMemoryAllocator[ k ].Compact();
}
}
#if PS3GCMCOMPACTPROFILE
float flTimePrepareTransfer = Plat_FloatTime() - flTimeStart;
#endif
// Wait for all RSX memory to be transferred
gpGcmDrawState->EndFrame();
gpGcmDrawState->CmdBufferFinish();
#if PS3GCMCOMPACTPROFILE
float flTimeDone = Plat_FloatTime() - flTimeStart;
char chBuffer[64];
Q_snprintf( chBuffer, ARRAYSIZE( chBuffer ), "COMPACT: %0.3f / %0.3f / %0.3f sec\n",
flTimeWait, flTimePrepareTransfer, flTimeDone );
uint32 dummy;
sys_tty_write( SYS_TTYP6, chBuffer, Q_strlen( chBuffer ), &dummy );
Q_snprintf( chBuffer, ARRAYSIZE( chBuffer ), "COMPACT: %0.3f -> %0.3f MB (%0.3f MB free)\n",
uiFree / 1024.f / 1024.f, g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated / 1024.f / 1024.f,
(g_ps3gcmLocalMemoryAllocator[0].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated) / 1024.f / 1024.f );
sys_tty_write( SYS_TTYP6, chBuffer, Q_strlen( chBuffer ), &dummy );
#endif
}
void Ps3gcmLocalMemoryAllocator_CompactWithReason( char const *szReason )
{
double flTimeCompactStart = Plat_FloatTime();
DevMsg( "====== GCM LOCAL MEMORY COMPACT : %s =====\n", szReason );
uint32 uiFreeMemoryBeforeCompact = g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated;
DevMsg( "RSX Local Memory Free: %0.3f MB; compacting...\n", (g_ps3gcmLocalMemoryAllocator[0].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated) / 1024.f / 1024.f );
Ps3gcmLocalMemoryAllocator_Compact();
DevMsg( "RSX Local Memory Compacted %0.3f MB in %0.3f sec\n",
(uiFreeMemoryBeforeCompact - g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated) / 1024.f / 1024.f,
Plat_FloatTime() - flTimeCompactStart );
DevMsg( "RSX Local Memory Free: %0.3f MB\n", (g_ps3gcmLocalMemoryAllocator[0].m_nOffsetMax - g_ps3gcmLocalMemoryAllocator[0].m_nOffsetUnallocated) / 1024.f / 1024.f );
}
bool CPs3gcmLocalMemoryBlock::Alloc()
{
PS3ALLOCMTX
return g_ps3gcmLocalMemoryAllocator[PS3GCMALLOCATIONPOOL(m_uType)].Alloc( reinterpret_cast< CPs3gcmLocalMemoryBlockMutable * >( this ) );
}
void CPs3gcmLocalMemoryBlock::Free()
{
PS3ALLOCMTX
g_ps3gcmLocalMemoryAllocator[PS3GCMALLOCATIONPOOL(m_uType)].Free( reinterpret_cast< CPs3gcmLocalMemoryBlockMutable * >( this ) );
}
//////////////////////////////////////////////////////////////////////////
//
// Private implementation of PS3 local memory allocator
//
inline bool CPs3gcmLocalMemoryAllocator::Alloc( CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock )
{
TrackAllocStats( pBlock->MutableType(), pBlock->MutableSize() );
uint32 uAlignBytes = PS3GCMALLOCATIONALIGN( pBlock->MutableType() );
Assert( IsPowerOfTwo( uAlignBytes ) );
double flAllocatorStallTime = 0.0f;
bool bCompactPerformed = false;
#ifdef GCMLOCALMEMORYBLOCKDEBUG
bCompactPerformed = !r_ps3_gcmlowcompact.GetBool();
#endif
retry_allocation:
// Try to find a free block
if ( LocalMemoryAllocation_t *pFreeBlock = FindFreeBlock( uAlignBytes, pBlock->MutableSize() ) )
{
pBlock->MutableOffset() = pFreeBlock->m_block.MutableOffset();
pBlock->MutableIndex() = pFreeBlock->m_block.MutableIndex();
#ifdef GCMLOCALMEMORYBLOCKDEBUG
if ( m_arrAllocations[ pBlock->MutableIndex() ] != &pFreeBlock->m_block )
Error( "<vitaliy> GCM Local Memory Allocator Error (attempt to reuse invalid free block)!" );
#endif
m_arrAllocations[ pBlock->MutableIndex() ] = reinterpret_cast< CPs3gcmLocalMemoryBlockMutable * >( pBlock );
delete pFreeBlock;
}
else if ( this != &g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMallocMemory ] )
{
// Allocate new block
uint32 uiOldUnallocatedEdge = m_nOffsetUnallocated;
uint32 uiFreeBlock = ( m_nOffsetUnallocated + uAlignBytes - 1 ) & ~( uAlignBytes - 1 );
// Check if there's enough space in this pool for the requested block
if ( uiFreeBlock + pBlock->MutableSize() > m_nOffsetMax )
{
// There's not enough space in this pool
if ( m_pPendingFreeBlock )
{
// There are pending free blocks, we just need to wait for
// RSX to finish rendering using them
if ( !flAllocatorStallTime )
{
flAllocatorStallTime = Plat_FloatTime();
// Flush GPU right up to current point - Endframe call does this...
gpGcmDrawState->EndFrame();
gpGcmDrawState->CmdBufferFlush();
}
while ( Reclaim() < pBlock->MutableSize() && m_pPendingFreeBlock )
{
ThreadSleep( 1 );
}
goto retry_allocation;
}
else if ( !bCompactPerformed )
{
if (this == &g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ]) return false;
// Let PPU wait for all RSX commands done
gpGcmDrawState->EndFrame();
gpGcmDrawState->CmdBufferFinish();
uint32 uiFragmentedFreeSpace = m_nOffsetMax - m_nOffsetUnallocated;
for ( LocalMemoryAllocation_t *pFreeFragment = m_pFreeBlock; pFreeFragment; pFreeFragment = pFreeFragment->m_pNext )
uiFragmentedFreeSpace += pFreeFragment->m_block.MutableSize();
Warning(
"**************** GCM LOCAL MEMORY LOW *****************\n"
"<vitaliy> GCM Local Memory Allocator#%d pool compacting!\n"
" Requested allocation %u bytes.\n"
" Pool capacity %u bytes.\n"
" Free fragmented space %u bytes.\n"
" Unallocated %u bytes.\n"
" Used %u bytes.\n",
this - g_ps3gcmLocalMemoryAllocator,
( uint32 ) pBlock->MutableSize(),
m_nOffsetMax - m_nOffsetMin,
uiFragmentedFreeSpace,
m_nOffsetMax - m_nOffsetUnallocated,
m_nOffsetUnallocated - m_nOffsetMin
);
Compact();
Warning( " ---> Compacted pool#%d has %u unallocated bytes.\n",
this - g_ps3gcmLocalMemoryAllocator,
m_nOffsetMax - m_nOffsetUnallocated );
bCompactPerformed = true;
// Wait for all RSX memory to be transferred
gpGcmDrawState->EndFrame();
gpGcmDrawState->CmdBufferFinish();
goto retry_allocation;
}
else
{
// Main memory pool returns failure so caller can try local pool.
if (this == &g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMainMemory ]) return false;
uint32 uiFragmentedFreeSpace = m_nOffsetMax - m_nOffsetUnallocated;
for ( LocalMemoryAllocation_t *pFreeFragment = m_pFreeBlock; pFreeFragment; pFreeFragment = pFreeFragment->m_pNext )
uiFragmentedFreeSpace += pFreeFragment->m_block.MutableSize();
Error(
"********* OUT OF GCM LOCAL MEMORY ********************\n"
"<vitaliy> GCM Local Memory Allocator#%d pool exhausted!\n"
" Failed allocation %u bytes.\n"
" Pool capacity %u bytes.\n"
" Free fragmented space %u bytes.\n"
" Unallocated %u bytes.\n"
" Used %u bytes.\n",
this - g_ps3gcmLocalMemoryAllocator,
( uint32 ) pBlock->MutableSize(),
m_nOffsetMax - m_nOffsetMin,
uiFragmentedFreeSpace,
m_nOffsetMax - m_nOffsetUnallocated,
m_nOffsetUnallocated - m_nOffsetMin
);
}
}
// update the pointer to "unallocated" realm
m_nOffsetUnallocated = uiFreeBlock + pBlock->MutableSize();
// this is the last allocation so far
pBlock->MutableIndex() = m_arrAllocations.AddToTail( reinterpret_cast< CPs3gcmLocalMemoryBlockMutable * >( pBlock ) );
pBlock->MutableOffset() = uiFreeBlock;
}
else
{
MEM_ALLOC_CREDIT_( "GCM Malloc Pool" );
void *pvMallocMemory = MemAlloc_AllocAligned( pBlock->MutableSize(), uAlignBytes );
pBlock->MutableOffset() = (uint32) pvMallocMemory;
pBlock->MutableIndex() = ~0;
}
// 7LTODO if ( flAllocatorStallTime )
// g_ps3gcmGlobalState.m_flAllocatorStallTimeWaitingRSX += Plat_FloatTime() - flAllocatorStallTime;
#ifdef GCMLOCALMEMORYBLOCKDEBUG
// PS3 doesn't allow more than 8 zcull regions (index 0..7)
if ( g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledD24S8].m_arrAllocations.Count() > 8 )
Error( "PS3 number of zcull regions exceeded!\n" );
// PS3 doesn't allow more than 15 tiles regions (index 0..14)
if ( g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledD24S8].m_arrAllocations.Count() +
g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorMisc].m_arrAllocations.Count() +
( kGcmAllocPoolTiledColorMisc - kGcmAllocPoolTiledColorFB )
> 15 )
Error( "PS3 number of tiled regions exceeded!\n" );
pBlock->m_dbgGuardCookie = g_GcmLocalMemoryBlockDebugCookieAllocated;
#endif
return true;
}
inline void CPs3gcmLocalMemoryAllocator::Free( CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock )
{
#ifdef GCMLOCALMEMORYBLOCKDEBUG
if ( !pBlock ||
pBlock->m_dbgGuardCookie != g_GcmLocalMemoryBlockDebugCookieAllocated ||
( ( pBlock->MutableIndex() != ~0 ) && ( m_arrAllocations[ pBlock->MutableIndex() ] != pBlock ) ) )
{
//DebuggerBreak();
Error( "<vitaliy> Attempt to free not allocated GCM local memory block!" );
}
pBlock->m_dbgGuardCookie = g_GcmLocalMemoryBlockDebugCookieFree;
#endif
LocalMemoryAllocation_t *pDealloc = new LocalMemoryAllocation_t;
pDealloc->m_block = *pBlock;
pDealloc->m_uiFenceNumber = sm_uiFenceNumber;
sm_uiFenceNumber ++;
if(!sm_uiFenceNumber)sm_uiFenceNumber = 1;
pDealloc->m_pNext = m_pPendingFreeBlock;
gpGcmDrawState->SetWriteBackEndLabel(GCM_LABEL_MEMORY_FREE, sm_uiFenceNumber);
m_pPendingFreeBlock = pDealloc;
TrackAllocStats( pBlock->MutableType(), - pBlock->MutableSize() );
if ( pBlock->MutableIndex() != ~0 )
{
#ifdef GCMLOCALMEMORYBLOCKDEBUG
if ( m_arrAllocations[ pBlock->MutableIndex() ] != pBlock )
Error( "<vitaliy> GCM Local Memory Allocator Error (freeing block that is not properly registered)!" );
#endif
m_arrAllocations[ pBlock->MutableIndex() ] = &pDealloc->m_block;
}
#ifdef GCMLOCALMEMORYBLOCKDEBUG
pBlock->MutableOffset() = ~0;
pBlock->MutableIndex() = ~0;
#endif
}
inline bool CPs3gcmLocalMemoryAllocator::IsFenceCompleted( uint32 uiCurrentFenceValue, uint32 uiCheckStoredFenceValue )
{
#if GCM_ALLOW_NULL_FLIPS
extern bool g_ps3_nullflips;
if ( g_ps3_nullflips )
return true;
#endif
// Needs to handle the counter wrapping around
return ( ( uiCurrentFenceValue - m_uiFenceLastKnown ) >= ( uiCheckStoredFenceValue - m_uiFenceLastKnown ) );
}
inline uint32 CPs3gcmLocalMemoryAllocator::Reclaim( bool bForce )
{
uint32 uiLargestBlockSizeReclaimed = 0;
uint32 uiCurrentFenceValue = *sm_puiFenceLocation;
// Walk pending free blocks and see if they are no longer
// in use by RSX:
LocalMemoryAllocation_t **p = &m_pPendingFreeBlock;
if ( !bForce ) while ( (*p) && !IsFenceCompleted( uiCurrentFenceValue, (*p)->m_uiFenceNumber ) )
p = &( (*p)->m_pNext );
// Now p is pointing to the chain of free blocks
// chain that has been completed (due to the nature of
// pushing new deallocation at the head of the pending
// list)
if ( *p )
{
LocalMemoryAllocation_t *pCompletedChain = *p;
*p = NULL; // Terminate the chain
// Handle the special case of malloc reclaim - free all memory
if ( this == &g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolMallocMemory ] )
{
MEM_ALLOC_CREDIT_( "GCM Malloc Pool" );
for ( LocalMemoryAllocation_t *pActualFree = pCompletedChain; pActualFree; )
{
MemAlloc_FreeAligned( pActualFree->m_block.DataInMallocMemory() );
LocalMemoryAllocation_t *pDelete = pActualFree;
pActualFree = pActualFree->m_pNext;
delete pDelete;
}
pCompletedChain = NULL;
}
// Relink the completed pending chain into
// the free blocks chain
LocalMemoryAllocation_t **ppFree = &m_pFreeBlock;
while ( *ppFree )
ppFree = &( (*ppFree)->m_pNext );
*ppFree = pCompletedChain;
// Recompute actual free sizes of the completed chain
// Actual free size is the delta between block offset and next block offset
// When there's no next block then its delta between block offset and unallocated edge
for ( LocalMemoryAllocation_t *pActualFree = pCompletedChain; pActualFree; pActualFree = pActualFree->m_pNext )
{
uint32 uiIdx = pActualFree->m_block.MutableIndex() + 1;
uint32 uiNextOffset = m_nOffsetUnallocated;
if ( uiIdx < m_arrAllocations.Count() )
{
CPs3gcmLocalMemoryBlockMutable * RESTRICT pNextBlock = m_arrAllocations[ uiIdx ];
uiNextOffset = pNextBlock->Offset();
}
uint32 uiActualBlockSize = uiNextOffset - pActualFree->m_block.Offset();
pActualFree->m_block.MutableSize() = uiActualBlockSize;
uiLargestBlockSizeReclaimed = MAX( uiLargestBlockSizeReclaimed, uiActualBlockSize );
}
}
// Remember the last known fence value
m_uiFenceLastKnown = uiCurrentFenceValue;
#ifdef GCMLOCALMEMORYBLOCKDEBUG
ValidateAllBlocks();
#endif
return uiLargestBlockSizeReclaimed;
}
inline CPs3gcmLocalMemoryAllocator::LocalMemoryAllocation_t * CPs3gcmLocalMemoryAllocator::FindFreeBlock( uint32 uiAlignBytes, uint32 uiSize )
{
LocalMemoryAllocation_t **ppBest = NULL;
uint32 uiSizeMax = uiSize * 11/10; // we don't want to inflate requested size by > 10%
for ( LocalMemoryAllocation_t **p = &m_pFreeBlock;
(*p);
p = &( (*p)->m_pNext ) )
{
if ( (*p)->m_block.MutableSize() >= uiSize && (*p)->m_block.MutableSize() <= uiSizeMax &&
!( (*p)->m_block.Offset() & ( uiAlignBytes - 1 ) ) )
{
if ( !ppBest || ( (*p)->m_block.MutableSize() <= (*ppBest)->m_block.MutableSize() ) )
{
ppBest = p;
}
}
}
if ( ppBest )
{
LocalMemoryAllocation_t *pFree = (*ppBest);
(*ppBest) = pFree->m_pNext;
pFree->m_pNext = NULL;
return pFree;
}
return NULL;
}
inline bool TrackAllocStats_Pool( CPs3gcmAllocationType_t uAllocType, int nDelta )
{
CPs3gcmAllocationPool_t pool = PS3GCMALLOCATIONPOOL( uAllocType );
int *stat = &g_RsxMemoryStats_Pool.nUnknownPoolUsed;
bool bInRSXMem = true;
switch( pool )
{
case kGcmAllocPoolDefault:
stat = &g_RsxMemoryStats_Pool.nDefaultPoolUsed;
break;
case kGcmAllocPoolDynamicNewPath:
case kGcmAllocPoolDynamic:
stat = &g_RsxMemoryStats_Pool.nDynamicPoolUsed;
break;
case kGcmAllocPoolTiledColorFB:
case kGcmAllocPoolTiledColorFBQ:
case kGcmAllocPoolTiledColor512:
case kGcmAllocPoolTiledColorMisc:
case kGcmAllocPoolTiledD24S8:
stat = &g_RsxMemoryStats_Pool.nRTPoolUsed;
break;
case kGcmAllocPoolMainMemory: // Unused, unless PS3GCM_VBIB_IN_IO_MEMORY set to 1
case kGcmAllocPoolMallocMemory:
stat = &g_RsxMemoryStats_Pool.nMainMemUsed;
bInRSXMem = false; // In main memory!
break;
}
*stat += nDelta;
Assert( 0 <= (int)*stat );
// Report free memory only from the default pool (the other pools are pre-sized to fixed limits, and all
// geom/textures go into the default pool, so that's where content-driven variation/failures will occur)
g_RsxMemoryStats.nGPUMemFree = g_RsxMemoryStats_Pool.nDefaultPoolSize - g_RsxMemoryStats_Pool.nDefaultPoolUsed;
return bInRSXMem;
}
inline void CPs3gcmLocalMemoryAllocator::TrackAllocStats( CPs3gcmAllocationType_t uAllocType, int nDelta )
{
#if TRACK_ALLOC_STATS
// Early-out for allocations not in RSX memory:
if ( !TrackAllocStats_Pool( uAllocType, nDelta ) )
return;
unsigned int *stat = &g_RsxMemoryStats.nUnknown;
switch( uAllocType )
{
case kAllocPs3gcmColorBufferMisc:
case kAllocPs3gcmColorBufferFB:
case kAllocPs3gcmColorBufferFBQ:
case kAllocPs3gcmColorBuffer512:
case kAllocPs3gcmDepthBuffer:
stat = &g_RsxMemoryStats.nRTSize;
break;
case kAllocPs3gcmTextureData:
case kAllocPs3gcmTextureData0:
stat = &g_RsxMemoryStats.nTextureSize;
break;
case kAllocPs3GcmVertexBuffer:
stat = &g_RsxMemoryStats.nVBSize;
break;
case kAllocPs3GcmIndexBuffer:
stat = &g_RsxMemoryStats.nIBSize;
break;
case kAllocPs3GcmShader:
case kAllocPs3GcmEdgeGeomBuffer:
case kAllocPs3GcmVertexBufferDynamic:
case kAllocPs3GcmIndexBufferDynamic:
case kAllocPs3GcmDynamicBufferPool:
case kAllocPs3GcmVertexBufferDma:
case kAllocPs3GcmIndexBufferDma:
// Treat these as misc unless they become big/variable
break;
}
*stat += nDelta;
Assert( 0 <= (int)*stat );
#endif // TRACK_ALLOC_STATS
}
#ifdef GCMLOCALMEMORYBLOCKDEBUG
#define VALIDATECONDITION( x ) if( !( x ) ) { Error( "<vitaliy> GCM Local Memory Allocation block %p index %d is corrupt [line %d]!\n", pBlock, k, __LINE__ ); }
inline void CPs3gcmLocalMemoryAllocator::ValidateAllBlocks()
{
// Traverse the allocated list and validate debug guards and patch-back indices
CUtlVector< uint32 > arrFreeBlocksIdx;
uint32 uiLastAllocatedOffset = m_nOffsetMin;
for ( int k = 0, kEnd = m_arrAllocations.Count(); k < kEnd; ++ k )
{
CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock = m_arrAllocations[k];
VALIDATECONDITION( pBlock );
VALIDATECONDITION( pBlock->m_dbgGuardCookie == g_GcmLocalMemoryBlockDebugCookieAllocated || pBlock->m_dbgGuardCookie == g_GcmLocalMemoryBlockDebugCookieFree );
VALIDATECONDITION( pBlock->MutableIndex() < m_arrAllocations.Count() );
VALIDATECONDITION( pBlock->MutableIndex() == k );
VALIDATECONDITION( m_arrAllocations[ pBlock->MutableIndex() ] == pBlock );
VALIDATECONDITION( pBlock->Offset() >= uiLastAllocatedOffset );
uiLastAllocatedOffset = pBlock->Offset() + pBlock->MutableSize();
VALIDATECONDITION( uiLastAllocatedOffset <= m_nOffsetMax );
if ( pBlock->m_dbgGuardCookie == g_GcmLocalMemoryBlockDebugCookieFree )
arrFreeBlocksIdx.AddToTail( k );
}
// Traverse free lists and validate
LocalMemoryAllocation_t * arrFree[] = { m_pPendingFreeBlock, m_pFreeBlock };
for ( int j = 0; j < ARRAYSIZE( arrFree ); ++ j )
for ( LocalMemoryAllocation_t *p = arrFree[j]; p; p = p->m_pNext )
{
int k = j;
CPs3gcmLocalMemoryBlockMutable * RESTRICT pBlock = &p->m_block;
VALIDATECONDITION( pBlock );
VALIDATECONDITION( pBlock->m_dbgGuardCookie == g_GcmLocalMemoryBlockDebugCookieFree );
k = pBlock->MutableIndex();
if ( pBlock->MutableIndex() != ~0 )
{
VALIDATECONDITION( pBlock->MutableIndex() < m_arrAllocations.Count() );
VALIDATECONDITION( m_arrAllocations[ pBlock->MutableIndex() ] == pBlock );
VALIDATECONDITION( arrFreeBlocksIdx.FindAndFastRemove( pBlock->MutableIndex() ) );
}
}
int k = 0;
void *pBlock = 0;
VALIDATECONDITION( !arrFreeBlocksIdx.Count() );
}
#endif
inline void CPs3gcmLocalMemoryAllocator::Compact()
{
#ifdef GCMLOCALMEMORYBLOCKDEBUG
ValidateAllBlocks();
if ( r_ps3_gcmnocompact.GetBool() )
return;
#endif
// Reclaim all memory (NOTE: all pending blocks must be reclaimed since both RSX and PPU have stopped rendering!)
Reclaim();
#ifdef GCMLOCALMEMORYBLOCKDEBUG
if ( m_pPendingFreeBlock )
Warning( "GCM Local Memory Allocator Compact forces pending free blocks to be reclaimed.\n" );
ValidateAllBlocks();
#endif
if ( m_pPendingFreeBlock )
Reclaim( true );
#ifdef GCMLOCALMEMORYBLOCKDEBUG
if ( m_pPendingFreeBlock )
Error( "<vitaliy> GCM Local Memory Allocator Compact requires RSX and PPU rendering to be paused! (pending free blocks have not been reclaimed)\n" );
ValidateAllBlocks();
#endif
// Walk the free blocks chain and patch-back NULL pointers into allocation tracking system
while ( m_pFreeBlock )
{
LocalMemoryAllocation_t *p = m_pFreeBlock;
m_pFreeBlock = p->m_pNext;
m_arrAllocations[ p->m_block.MutableIndex() ] = NULL;
delete p;
}
Assert( !m_pFreeBlock && !m_pPendingFreeBlock );
// These are elements requiring reallocation
uint32 uiCount = m_arrAllocations.Count();
CPs3gcmLocalMemoryBlockMutable **pReallocationBlocks = m_arrAllocations.Base();
// Here "correct" implementation would be to copy off m_arrAllocations vector onto stack for iteration,
// RemoveAll from m_arrAllocations vector and allocate all blocks again.
// We will cheat since we know that we will allocate same number of elements and directly write zero
// into m_arrAllocations m_Size member, then we will still be able to use the memory of the vector
// for reading blocks requiring compact reallocation, and AddToTail will still fill the vector with
// correct data.
struct AllocatorCompactVectorCheat : public CUtlVector< CPs3gcmLocalMemoryBlockMutable * > { inline void ResetCountPreservingMemoryContents() { m_Size = 0; } };
( ( AllocatorCompactVectorCheat * ) ( char * ) &m_arrAllocations )->ResetCountPreservingMemoryContents();
m_nOffsetUnallocated = m_nOffsetMin;
// Prepare RSX for data buffer transfers in local memory
uint nTransferMode = ( ( this - &g_ps3gcmLocalMemoryAllocator[ kGcmAllocPoolDefault ] ) < kGcmAllocPoolMainMemory ) ? CELL_GCM_TRANSFER_LOCAL_TO_LOCAL : CELL_GCM_TRANSFER_MAIN_TO_MAIN;
Assert( nTransferMode < 4 );
// Reallocate all blocks
for ( ; uiCount; -- uiCount, ++ pReallocationBlocks )
{
CPs3gcmLocalMemoryBlockMutable *pBlock = *pReallocationBlocks;
if ( !pBlock )
continue;
uint32 nOldOffset = pBlock->Offset();
char* pOldAddress = pBlock->DataInAnyMemory();
TrackAllocStats( pBlock->MutableType(), - pBlock->MutableSize() );
Alloc( pBlock );
if ( nOldOffset == pBlock->Offset() )
continue;
// Have RSX transfer blocks data. RSX may hang if there's WriteLabel between the Format and Offset commands,
// so reserve space for both of them up front
// SpuDrawTransfer_t * pTransfer = g_spuGcm.GetDrawQueue()->AllocWithHeader<SpuDrawTransfer_t>( SPUDRAWQUEUE_TRANSFER_METHOD | nTransferMode );
// pTransfer->m_nLineSize = pBlock->MutableSize();
// pTransfer->m_nOldOffset = nOldOffset;
// pTransfer->m_nNewOffset = pBlock->Offset();
// 7LTODO
uint32 uiLineSize = pBlock->MutableSize();
uint32 uiLineOffset = 0;
const uint nMaxTransferSize = 0x3FFFFF;
cellGcmReserveMethodSizeInline(gpGcmContext, 0x4000/4);
GCM_FUNC( cellGcmSetTransferDataMode, nTransferMode );
int i = 1;
do
{
uint32 uiTransferSize = Min<uint32>( uiLineSize, nMaxTransferSize );
GCM_FUNC( cellGcmSetTransferDataFormat, 0, 0, uiTransferSize, 1, 1, 1 );
GCM_FUNC( cellGcmSetTransferDataOffset, pBlock->Offset() + uiLineOffset, nOldOffset + uiLineOffset );
uiLineSize -= uiTransferSize;
uiLineOffset += uiTransferSize;
i++;
}
while ( uiLineSize > 0 );
// V_memmove(pBlock->DataInAnyMemory(), pOldAddress, pBlock->MutableSize() );
}
#ifdef GCMLOCALMEMORYBLOCKDEBUG
ValidateAllBlocks();
#endif
}
//////////////////////////////////////////////////////////////////////////
//
// Computation of tiled memory
//
uint32 CPs3gcmLocalMemoryBlock::TiledMemoryTagAreaBase() const
{
CPs3gcmAllocationPool_t ePool = PS3GCMALLOCATIONPOOL(m_uType);
if ( ePool == kGcmAllocPoolTiledColorMisc ) // Misc color tiles are placed at the front of tag area after preset pools
return ( Offset() - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFB].m_nOffsetMin ) / 0x10000;
if ( ePool == kGcmAllocPoolTiledD24S8 ) // Depth tiles are placed in the end of tag area (0-0x7FF is offset range)
return 0x800 - ( Offset() - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledD24S8].m_nOffsetMin + m_uiSize ) / 0x10000;
if ( ePool == kGcmAllocPoolTiledColorFB ) // FB color tiles go first
return ( g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFB].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFB].m_nOffsetMin ) / 0x10000;
if ( ePool == kGcmAllocPoolTiledColorFBQ ) // FBQ color tiles go next
return ( g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFBQ].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFB].m_nOffsetMin ) / 0x10000;
if ( ePool == kGcmAllocPoolTiledColor512 ) // 512 color tiles go next
return ( g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColor512].m_nOffsetMin - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledColorFB].m_nOffsetMin ) / 0x10000;
#ifdef GCMLOCALMEMORYBLOCKDEBUG
Error( "<vitaliy> Cannot compute tiled memory tag base from a non-tiled-pool allocation!\n" );
#endif
return ~0;
}
uint32 CPs3gcmLocalMemoryBlock::TiledMemoryIndex() const
{
CPs3gcmAllocationPool_t ePool = PS3GCMALLOCATIONPOOL(m_uType);
if ( ePool == kGcmAllocPoolTiledColorMisc ) // Color tiles are placed in the front
return m_uiIndex + kGcmAllocPoolTiledColorMisc - kGcmAllocPoolTiledColorFB;
if ( ePool == kGcmAllocPoolTiledD24S8 ) // Depth tiles are placed as last tiles
return 14 - m_uiIndex;
return ePool - kGcmAllocPoolTiledColorFB;
}
uint32 CPs3gcmLocalMemoryBlock::ZcullMemoryIndex() const
{
CPs3gcmAllocationPool_t ePool = PS3GCMALLOCATIONPOOL(m_uType);
if ( ePool == kGcmAllocPoolTiledD24S8 ) // Depth tiles are the only zcull tiles
return m_uiIndex;
#ifdef GCMLOCALMEMORYBLOCKDEBUG
Error( "<vitaliy> Cannot compute zcull index from a non-zcull allocation!\n" );
#endif
return ~0;
}
uint32 CPs3gcmLocalMemoryBlock::ZcullMemoryStart() const
{
CPs3gcmAllocationPool_t ePool = PS3GCMALLOCATIONPOOL(m_uType);
if ( ePool == kGcmAllocPoolTiledD24S8 ) // Depth tiles are the only zcull tiles
return ( Offset() - g_ps3gcmLocalMemoryAllocator[kGcmAllocPoolTiledD24S8].m_nOffsetMin ) / 4; // 1 byte per pixel, D24S8 is 4 bytes per pixel, implicitly 4096 aligned because offset is 64Kb aligned
#ifdef GCMLOCALMEMORYBLOCKDEBUG
Error( "<vitaliy> Cannot compute zcull memory start from a non-zcull allocation!\n" );
#endif
return ~0;
}
//////////////////////////////////////////////////////////////////////////
//
// Allow shaderapi to query GPU memory stats:
//
void GetGPUMemoryStats( GPUMemoryStats &stats )
{
stats = g_RsxMemoryStats;
}
+167
View File
@@ -0,0 +1,167 @@
//================ Copyright (c) Valve Corporation. All Rights Reserved. ===========================
//
// Local memory manager
//
//==================================================================================================
#ifndef INCLUDED_PS3GCMMEMORY_H
#define INCLUDED_PS3GCMMEMORY_H
#ifndef SPU
#include "tier1/strtools.h"
#include "shaderapi/gpumemorystats.h"
#include "cell/gcm.h"
#include "gcmconfig.h"
#else
#endif
//--------------------------------------------------------------------------------------------------
// Externals
//--------------------------------------------------------------------------------------------------
#ifndef SPU
extern void GetGPUMemoryStats( GPUMemoryStats &stats );
extern void Ps3gcmLocalMemoryAllocator_Init();
#endif
//--------------------------------------------------------------------------------------------------
// Memory Pools, Types and LocalMemoryBlock
//--------------------------------------------------------------------------------------------------
enum CPs3gcmAllocationPool_t
{
kGcmAllocPoolDefault,
kGcmAllocPoolDynamicNewPath,
kGcmAllocPoolDynamic,
kGcmAllocPoolTiledColorFB, // Frame-buffer tiled color memory (should be first preset tiled region)
kGcmAllocPoolTiledColorFBQ, // Quarter-frame-buffer tiled color memory
kGcmAllocPoolTiledColor512, // 512x512 tiled color memory
kGcmAllocPoolTiledColorMisc, // Last tiled color region
kGcmAllocPoolTiledD24S8,
kGcmAllocPoolMainMemory, // Pool in the main RSX-mapped IO memory
kGcmAllocPoolMallocMemory, // Pool in malloc-backed non-RSX-mapped memory
kGcmAllocPoolCount
};
#define PS3GCMALLOCATIONPOOL( uType ) ( (CPs3gcmAllocationPool_t)( ( ((uint32)(uType)) >> 28 ) & 0xF ) )
#define PS3GCMALLOCATIONALIGN( uType ) ( ((uint32)(uType)) & 0xFFFFFF )
#define PS3GCMALLOCATIONTYPE( uAlign, ePool, iType ) (((uint32)(uAlign))&0xFFFFFF) | ( (((uint32)(iType))&0xF) << 24 ) | ( (((uint32)(ePool))&0xF) << 28 )
enum CPs3gcmAllocationType_t
{
// Default pool
kAllocPs3gcmTextureData0 = PS3GCMALLOCATIONTYPE( 128, kGcmAllocPoolMainMemory, 0 ),
kAllocPs3gcmTextureData = PS3GCMALLOCATIONTYPE( 128, kGcmAllocPoolDefault, 1 ),
kAllocPs3GcmVertexBuffer = PS3GCMALLOCATIONTYPE( 32, kGcmAllocPoolDefault, 2 ),
kAllocPs3GcmIndexBuffer = PS3GCMALLOCATIONTYPE( 32, kGcmAllocPoolDefault, 3 ),
kAllocPs3GcmShader = PS3GCMALLOCATIONTYPE( 128, kGcmAllocPoolDefault, 4 ),
kAllocPs3GcmEdgeGeomBuffer = PS3GCMALLOCATIONTYPE( 128, kGcmAllocPoolDefault, 5 ),
// Dynamic pool
kAllocPs3GcmVertexBufferDynamic = PS3GCMALLOCATIONTYPE( 32, kGcmAllocPoolDynamic, 1 ),
kAllocPs3GcmIndexBufferDynamic = PS3GCMALLOCATIONTYPE( 32, kGcmAllocPoolDynamic, 2 ),
kAllocPs3GcmDynamicBufferPool = PS3GCMALLOCATIONTYPE( 32, kGcmAllocPoolDynamicNewPath, 1 ),
// Malloc memory pool
kAllocPs3GcmVertexBufferDma = PS3GCMALLOCATIONTYPE( 32, kGcmAllocPoolMallocMemory, 1 ),
kAllocPs3GcmIndexBufferDma = PS3GCMALLOCATIONTYPE( 32, kGcmAllocPoolMallocMemory, 2 ),
// Tiled pools
kAllocPs3gcmColorBufferFB = PS3GCMALLOCATIONTYPE( 64, kGcmAllocPoolTiledColorFB, 1 ),
kAllocPs3gcmColorBufferFBQ = PS3GCMALLOCATIONTYPE( 64, kGcmAllocPoolTiledColorFBQ, 1 ),
kAllocPs3gcmColorBuffer512 = PS3GCMALLOCATIONTYPE( 64, kGcmAllocPoolTiledColor512, 1 ),
kAllocPs3gcmColorBufferMisc = PS3GCMALLOCATIONTYPE( 64*1024, kGcmAllocPoolTiledColorMisc,1 ),
kAllocPs3gcmDepthBuffer = PS3GCMALLOCATIONTYPE( 64*1024, kGcmAllocPoolTiledD24S8, 1 ),
};
struct CPs3gcmLocalMemoryBlockSystemGlobal;
struct ALIGN16 CPs3gcmLocalMemoryBlock
{
public:
CPs3gcmLocalMemoryBlock() {}
#if 0
#define GCMLOCALMEMORYBLOCKDEBUG
uint64 m_dbgGuardCookie; // Debug cookie used to guard when calling code let block go out of scope without freeing it
#endif
protected:
uint32 m_nLocalMemoryOffset; // Offset in RSX local memory
uint32 m_uiSize; // Actual allocation size, might be larger than requested allocation size
CPs3gcmAllocationType_t m_uType; // Allocation type with required alignment
uint32 m_uiIndex; // Index of the allocation in allocation tracking system
bool Alloc(); // Internal implementation of Local Memory Allocator
// Prevent copying (since patch-back mechanism needs to access the allocated blocks)
CPs3gcmLocalMemoryBlock( CPs3gcmLocalMemoryBlock const &x ) { V_memcpy( this, &x, sizeof( CPs3gcmLocalMemoryBlock ) ); }
CPs3gcmLocalMemoryBlock& operator =( CPs3gcmLocalMemoryBlock const &x ) { V_memcpy( this, &x, sizeof( CPs3gcmLocalMemoryBlock ) ); return *this; }
public:
inline void Assign( CPs3gcmLocalMemoryBlockSystemGlobal const &x ) { V_memcpy( this, &x, sizeof( CPs3gcmLocalMemoryBlock ) ); }
inline bool Alloc( CPs3gcmAllocationType_t uType, uint32 uiSize ) { m_uType = uType; m_uiSize = uiSize; return Alloc(); }
inline void AttachToExternalMemory( CPs3gcmAllocationType_t uType, uint32 nOffset, uint32 uiSize ) { m_uType = uType; m_uiSize = uiSize; m_nLocalMemoryOffset = nOffset; m_uiIndex = ~0; }
void Free();
void FreeAndAllocNew() { Free(); Alloc(); }
inline uint32 Offset() const { return m_nLocalMemoryOffset; }
inline uint32 Size() const { return m_uiSize; }
inline bool IsLocalMemory() const { return PS3GCMALLOCATIONPOOL( m_uType ) < kGcmAllocPoolMainMemory; }
inline bool IsRsxMappedMemory() const { return PS3GCMALLOCATIONPOOL( m_uType ) < kGcmAllocPoolMallocMemory; }
inline uint8 GcmMemoryLocation() const { return IsLocalMemory() ? CELL_GCM_LOCATION_LOCAL : CELL_GCM_LOCATION_MAIN; }
#ifndef SPU
char * DataInLocalMemory() const;
char * DataInMainMemory() const;
char * DataInMallocMemory() const;
char * DataInAnyMemory() const;
#endif
// Tiled memory access
uint32 TiledMemoryTagAreaBase() const;
uint32 TiledMemoryIndex() const;
// Zcull memory access
uint32 ZcullMemoryIndex() const;
uint32 ZcullMemoryStart() const;
} ALIGN16_POST;
struct CPs3gcmLocalMemoryBlockSystemGlobal : public CPs3gcmLocalMemoryBlock
{
public:
CPs3gcmLocalMemoryBlockSystemGlobal() {}
private:
// Prevent copying (since patch-back mechanism needs to access the allocated blocks)
CPs3gcmLocalMemoryBlockSystemGlobal( CPs3gcmLocalMemoryBlock const &x );
CPs3gcmLocalMemoryBlockSystemGlobal& operator =( CPs3gcmLocalMemoryBlockSystemGlobal const &x );
};
//--------------------------------------------------------------------------------------------------
// Buffer (used by IB and VBs)
//--------------------------------------------------------------------------------------------------
struct CPs3gcmBuffer
{
CPs3gcmLocalMemoryBlock m_lmBlock;
public:
inline uint32 Offset() { return m_lmBlock.Offset(); }
public:
#ifndef SPU
static CPs3gcmBuffer * New( uint32 uiSize, CPs3gcmAllocationType_t uType );
void Release();
#endif
};
#endif // INCLUDED_PS3GCMMEMORY_H
File diff suppressed because it is too large. Load diff
+205
View File
@@ -0,0 +1,205 @@
//========== Copyright © 2010, Valve Corporation, All rights reserved. ========
// Global GCM-related state
//
#ifndef _PS3GCMSTATE_H_INC_
#define _PS3GCMSTATE_H_INC_
#include "ps3/ps3gcmmemory.h"
#include <cell/gcm.h>
#include "bitmap/imageformat.h"
#include "ps3/ps3_gcm_shared.h"
class CPs3gcmGlobalState
{
public:
void * m_pIoAddress; // RSX IO buffer, base address
uint32 m_nIoSize; // RSX IO total size [including CMD buffer]
uint32 m_nIoSizeNotPreallocated; // the io total size that wasn't pre-allocated in initialization
uint32 m_nCmdSize; // RSX CMD buffer total size [including first reserved 4K]
uint32 const volatile *m_pCurrentCmdBufferSegmentRSX; // Begin offset of current CMD buffer segment being processed by RSX
#if GCM_CTX_UNSAFE_MODE
uint32 *m_pCurrentCmdBufferUnflushedBeginRSX; // Marks beginning of not yet flushed RSX buffer
#endif
void * m_pLocalBaseAddress; // RSX Local Memory Base Address
uint32 m_nLocalBaseOffset; // cellGcmAddressToOffset( m_pLocalBaseAddress )
uint32 m_nLocalSize; // RSX Local Memory Size
uint16 m_nRenderSize[2]; // with & height of the render buffer
float m_flRenderAspect; // aspect ratio of the output device
uint32 m_nIoOffsetDelta; // add this to EA to get Io Offset
uint32 m_nSurfaceRenderPitch;
// this is used to allocate permanent cmd buffers; to be cleared when level reloads, hopefully won't need anything more complicated than that
// but if we do, we can make a page-chain-based (page from 128 bytes) allocator with reference count per page
// NOTE: the buffer MUST have 1KB padding in the end to prevent overfetch RSX crash!
CellGcmContextData m_cmdBufferPermContext;
// vertex and index data buffer
void * m_pRsxDataTransferBuffer;
uint32 m_nRsxDataTransferBufferSize;
// main memory pool buffer
void * m_pRsxMainMemoryPoolBuffer;
uint32 m_nRsxMainMemoryPoolBufferSize;
// special texture to support debug stripes
CPs3gcmLocalMemoryBlock m_debugStripeImageBuffer;
uint32 m_nCmdBufferRefCount; // how many buffers are referenced?
CPs3gcmDisplay m_display; // m_display objects that are created automatically
CPs3gcmLocalMemoryBlock m_pShaderPsEmptyBuffer;
CgBinaryProgram *m_pShaderPsEmpty; // empty pixel shader
uint32 m_nIoLocalOffsetEmptyFragmentProgramSetupRoutine;
uint32 m_nFlushCounter;
float m_flAllocatorStallTimeWaitingRSX; // how long allocator ended up waiting for RSX
public:
int32 Init();
void Shutdown();
void DrawDebugStripe( uint nScreenX, uint nScreenY, uint nStripeY, uint nStripeWidth, uint nStripeHeight, int nNext = 0 );
// pre-allocate memory before command buffer is allocated
void * IoMemoryPrealloc( uint nAlign, uint nSize );
void * IoSlackAlloc( uint nAlign, uint nSize );
void IoSlackFree( void * eaMemory );
bool IsIoMemory( void * eaMemory );
uintp CmdBufferToIoOffset( void *pCmdBuffer );
CellGcmContextData* CmdBufferAlloc( );
void CmdBufferFreeOffset( uint32 );
enum CmdBufferFlushType_t
{
kFlushForcefully,
kFlushEndFrame
};
void CmdBufferFlush( CmdBufferFlushType_t eFlushType );
void CmdBufferFinish();
void CmdBufferReservationCallback( struct CellGcmContextData *context );
uint32 GetRsxControlNextReferenceValue();
// Note:
// Height alignment must be 32 for tiled surfaces on RSX
// 128 for Edge Post MLAA
// 64 for Edge Post MLAA with EDGE_POST_MLAA_MODE_TRANSPOSE_64 flag set
uint GetRenderSurfaceBytes( uint nHeightAlignment = 32 ) const { return m_nSurfaceRenderPitch * AlignValue( m_nRenderSize[1], nHeightAlignment ); }
protected:
void CreateDebugStripeTextureBuffer();
void CreateEmptyPixelShader();
void CreateRsxBuffers();
void CreateIoBuffers();
int InitVideo();
int InitGcm();
};
inline uintp CPs3gcmGlobalState::CmdBufferToIoOffset( void * pCmdBuffer )
{
uintp nIoOffset = uintp( pCmdBuffer ) + m_nIoOffsetDelta;
Assert( ( uintp( pCmdBuffer ) >= uintp( m_cmdBufferPermContext.begin ) && uintp( pCmdBuffer ) < uintp( m_cmdBufferPermContext.end ) ) // can be a perm context buffer
|| ( nIoOffset >= 4096 && nIoOffset <= m_nCmdSize ) ); // or it can be the main cmd buffer (SYSring)
return nIoOffset;
}
inline CellGcmContextData* CPs3gcmGlobalState::CmdBufferAlloc( )
{
m_nCmdBufferRefCount++;
return &m_cmdBufferPermContext;
}
inline void CPs3gcmGlobalState::CmdBufferFreeOffset( uint32 )
{
if( !--m_nCmdBufferRefCount )
{
m_cmdBufferPermContext.current = m_cmdBufferPermContext.begin;
}
}
extern CPs3gcmGlobalState g_ps3gcmGlobalState;
//////////////////////////////////////////////////////////////////////////
//
// inline implementations of PPU-only stuff
//
inline char * CPs3gcmLocalMemoryBlock::DataInLocalMemory() const
{
Assert( IsLocalMemory() );
return
( m_nLocalMemoryOffset - g_ps3gcmGlobalState.m_nLocalBaseOffset ) +
( char * ) g_ps3gcmGlobalState.m_pLocalBaseAddress;
}
inline char * CPs3gcmLocalMemoryBlock::DataInMainMemory() const
{
Assert( !IsLocalMemory() && IsRsxMappedMemory() );
return
m_nLocalMemoryOffset +
( ( char * ) g_ps3gcmGlobalState.m_pIoAddress );
}
inline char * CPs3gcmLocalMemoryBlock::DataInMallocMemory() const
{
Assert( !IsLocalMemory() && !IsRsxMappedMemory() );
return ( char * ) m_nLocalMemoryOffset;
}
inline char * CPs3gcmLocalMemoryBlock::DataInAnyMemory() const
{
switch ( PS3GCMALLOCATIONPOOL( m_uType ) )
{
default: return DataInLocalMemory();
case kGcmAllocPoolMainMemory: return DataInMainMemory();
case kGcmAllocPoolMallocMemory: return DataInMallocMemory();
}
}
// Allow shaderapi to query GPU memory stats:
extern void GetGPUMemoryStats( GPUMemoryStats &stats );
class CmdSubBuffer: public CellGcmContextData
{
public:
static int32_t DoNothing( struct CellGcmContextData *pContext, uint32_t nWords )
{
Error( "CmdSubBuffer callback @%p: trying to allocate %u words\n", pContext, nWords );
return CELL_ERROR_ERROR_FLAG;
}
CmdSubBuffer( uint32 * pBuffer, uint nAllocateWords )
{
this->current = this->begin = pBuffer;
this->end = this->begin + nAllocateWords;
this->callback = DoNothing;
}
~CmdSubBuffer()
{
Assert( this->current == this->end );
}
};
extern uint32 CalculateMemorySizeFromCmdLineParam( char const *pCmdParamName, uint32 nDefaultValue, uint32 nMinValue = 0 );
inline bool CPs3gcmGlobalState::IsIoMemory( void * eaMemory )
{
return uintp( eaMemory ) >= uintp( m_pIoAddress ) && uintp( eaMemory ) <= uintp( m_pIoAddress ) + m_nIoSize;
}
#endif // _PS3GCMSTATE_H_INC_
+650
View File
@@ -0,0 +1,650 @@
// Copyright © 2010, Valve Corporation, All rights reserved. ========
#include "tier0/platform.h"
#include "tier0/dbg.h"
#include "tier1/convar.h"
#include "ps3/ps3gcmlabels.h"
#include "ps3gcmstate.h"
#include "spugcm.h"
#include "rsxflip.h"
CFlipHandler g_flipHandler;
ConVar r_drop_user_commands( "r_drop_user_commands", "0" );
ConVar r_ps3_mlaa( "r_ps3_mlaa", "1" ); //
ConVar r_ps3_vblank_miss_threshold( "r_ps3_vblank_miss_threshold", "0.08", FCVAR_DEVELOPMENTONLY, "How much % of vsync time is allowed after vblank for frames that missed vsync to tear and flip immediately" );
#if GCM_ALLOW_TIMESTAMPS
int32 g_ps3_timestampBeginIdx = GCM_REPORT_TIMESTAMP_FRAME_FIRST;
#endif
#if 0 // defined(_DEBUG)
char ALIGN16 g_flipLog[256][32] ALIGN16_POST;
uint g_flipLogIdx = 0;
#define FLIP_LOG(MSG,...) \
{ \
uint nLogIdx = cellAtomicIncr32( &g_flipLogIdx ) & ( ARRAYSIZE( g_flipLog ) - 1 ); \
int nCount = V_snprintf( g_flipLog[nLogIdx], sizeof( g_flipLog[nLogIdx] ), MSG, ##__VA_ARGS__ ); \
int zeroSize = sizeof( g_flipLog[0] ) - 4 - nCount; \
V_memset( g_flipLog[nLogIdx] + nCount, 0, zeroSize ); \
*(uint32*)( g_flipLog[nLogIdx] + sizeof( g_flipLog[0] ) - 4 ) = __mftb(); \
}
#define ENABLE_FLIP_LOG 1
#define FlipAssert( X ) do{if(!(X))DebuggerBreak();}while(false)
uint g_flipUserCommands[1024][2];
#else
#define FLIP_LOG(MSG,...)
#define FlipAssert( X )
#define ENABLE_FLIP_LOG 0
#endif
void CEdgePostWorkload::Kick( void * dst, uint nSetLabel )
{
if( !m_isInitialized )
return;
extern ConVar r_ps3_mlaa;
FLIP_LOG("mlaa %d,mode=%Xh,label=%d", nSetLabel, g_flipHandler.m_nMlaaFlagsThisFrame, *m_mlaaContext.rsxLabelAddress );
edgePostMlaaWait( &m_mlaaContext );
FlipAssert( vec_all_eq( *g_spuGcm.m_pMlaaBufferCookie, g_vuSpuGcmCookie ) );
//FLIP_LOG("mlaa init %d", nSetLabel );
edgePostInitializeWorkload( &m_workload, m_stages, STAGE_COUNT );
bool isMlaaRelativeEdgeDetection = true;
uint8
nMlaaThresholdBase (0x0a), // from Edge sample: these are pretty good threshold values, but you might find better ones...
nMlaaThresholdFactor(0x59),
nMlaaAbsoluteThreshold(0x20);
uint nWidth = g_ps3gcmGlobalState.m_nRenderSize[0], nHeight = g_ps3gcmGlobalState.m_nRenderSize[1];
FlipAssert( nWidth <= 1280 && nWidth >= 640 && nHeight <= 720 && nHeight >= 480 );
//FLIP_LOG("mlaa prep %d", nSetLabel );
edgePostMlaaPrepareWithRelativeThreshold( &m_mlaaContext, g_spuGcm.m_pMlaaBuffer, IsResultInMainMemory()? g_spuGcm.m_pMlaaBufferOut : dst,
nWidth, nHeight,
g_ps3gcmGlobalState.m_nSurfaceRenderPitch,
isMlaaRelativeEdgeDetection?nMlaaThresholdBase:nMlaaAbsoluteThreshold,
isMlaaRelativeEdgeDetection?nMlaaThresholdFactor:0,
g_flipHandler.m_nMlaaFlagsThisFrame,
nSetLabel );
//FLIP_LOG("mlaa kick %d", nSetLabel );
edgePostMlaaKickTasks( &m_mlaaContext );
FLIP_LOG("mlaa kicked %d,label=%d", nSetLabel, *m_mlaaContext.rsxLabelAddress );
FlipAssert( vec_all_eq( *g_spuGcm.m_pMlaaBufferCookie, g_vuSpuGcmCookie ) );
}
void RsxInterruptFifo::Init()
{
m_nGet = m_nPut = 0;
}
uint RsxInterruptFifo::Queue( uint8 nCause, uint8 nSurfaceFlipIdx )
{
Event_t event;
event.m_nCause = nCause;
event.m_nSurfaceFlipIdx = nSurfaceFlipIdx;
return Queue( event );
}
uint RsxInterruptFifo::Queue( const Event_t &event )
{
while( ( m_nPut - m_nGet ) >= MAX_EVENT_COUNT - 1 )
{
sys_timer_usleep( 100 ); // this should NEVER happen
}
#if ENABLE_FLIP_LOG
switch( event.m_nCause )
{
case GCM_USERCMD_POSTPROCESS:
FLIP_LOG( "queue:post %d", event.m_nSurfaceFlipIdx );
break;
case GCM_USERCMD_FLIPREADY:
FLIP_LOG( "queue:flip %d sys%d", event.m_nSurfaceFlipIdx, g_flipHandler.m_nSystemFlipId[ event.m_nSurfaceFlipIdx ] );
break;
default:
FLIP_LOG("Unknown event %d", event.m_nCause );
break;
}
#endif
m_queue[ m_nPut & ( MAX_EVENT_COUNT - 1 ) ] = event;
return ++m_nPut; // Should be atomic if there are multiple event producer threads
}
uint RsxInterruptFifo::GetPutMarker()const
{
return m_nPut;
}
int RsxInterruptFifo::HasEvents( uint nMarker )
{
uint nGet = m_nGet;
Assert( int( nMarker - nGet ) >= 0 );
return int( nMarker - nGet );
}
RsxInterruptFifo::Event_t & RsxInterruptFifo::PeekEvent()
{
uint nGet = m_nGet;
Assert( nGet != m_nPut );
return m_queue[ nGet & ( MAX_EVENT_COUNT - 1 ) ];
}
const RsxInterruptFifo::Event_t RsxInterruptFifo::DequeueEvent( )
{
Event_t event = PeekEvent();
m_nGet++; // should be atomic if there's more than one consumer
return event;
}
void RsxInterruptFifo::QueueRsxInterrupt()
{
uint32 *pReplace = NULL;
#if ENABLE_FLIP_LOG
//FLIP_LOG( "q%X", m_nPut );
g_flipUserCommands[ m_nPut & ( ARRAYSIZE( g_flipUserCommands ) - 1 ) ][ 0 ] = m_nPut;
pReplace = &g_flipUserCommands[ m_nPut & ( ARRAYSIZE( g_flipUserCommands ) - 1 ) ][ 1 ];
*pReplace = uint32( gCellGcmCurrentContext->current );
#endif
/*
if( IsCert() // don't deliberately drop anything in CERT
|| 0 == r_drop_user_commands.GetInt() // don't drop anything if drop==0
|| ( ( rand() % 100 ) >= r_drop_user_commands.GetInt() ) // drop 1% means in 99% of cases we still want to SetUserCommand
)
GCM_FUNC( cellGcmSetUserCommand, m_nPut );
GCM_FUNC( cellGcmSetWriteTextureLabel, GCM_LABEL_LAST_INTERRUPT_GET, m_nPut );
*/
// directly putting it to SPUGCM queue instead of routing it through GCM_FUNC
g_spuGcm.GetDrawQueue()->Push3( SPUDRAWQUEUE_QUEUE_RSX_INTERRUPT_METHOD | GCM_LABEL_LAST_INTERRUPT_GET, m_nPut, ( uintp )pReplace );
}
void CFlipHandler::Init()
{
m_interruptFifo.Init();
/*
V_memset( m_nDebugStates, 0, sizeof( m_nDebugStates ) );
m_nDebugStates[RENDERING_SURFACE] = -1;
*/
m_nFlipSurfaceIdx = 0;
m_nFlipSurfaceCount = 0;
m_nVblankCounter = 100; // how many vblanks since the last flip?
m_bEdgePostResultAlreadyInLocalMemory = false;
m_nMlaaFlagsThisFrame = 0; // disable MLAA before the first BeginScene() is called
m_nMlaaFlagMaskNextFrame = ~0u;
for( int i = 0; i < ARRAYSIZE( m_surfaceEdgePost ) ; ++i ) // initially, the post processing of surfaces is disabled
m_surfaceEdgePost[i] = 0;
// simulated initial state: we just flipped to surface 1, then 2, thus leaving surface 1 (then 0) available to render into
// event[1] may not be set for MLAA mode because in order to start rendering into surface 0 (which we're rendering into), we "waited" for event 1
for ( int j = 2; j < ARRAYSIZE( m_evFlipReady ); ++ j )
m_evFlipReady[j].Set();
//m_nLastFlippedSurfaceIdx = CPs3gcmDisplay::SURFACE_COUNT - 1 ;
m_pLastInterruptGet = cellGcmGetLabelAddress( GCM_LABEL_LAST_INTERRUPT_GET );
*m_pLastInterruptGet = 0;
cellGcmSetVBlankHandler( INTERRUPT_VBlankHandler );
cellGcmSetUserHandler( INTERRUPT_UserHandler );
}
void CFlipHandler::Shutdown()
{
cellGcmSetVBlankHandler( NULL );
cellGcmSetUserHandler( NULL );
}
//////////////////////////////////////////////////////////////////////////
// 1. draw PS/3 system menus into the surface
// 2. queue a reliable "flip ready" event for GCM interrupt thread to process and flip surface to this
//
void CFlipHandler::QmsPrepareFlipSubmit( GcmUserCommandEnum_t nEvent, uint surfaceFlipIdx )
{
uint32 nSystemFlipId = GCM_FUNC_NOINLINE( cellGcmSetPrepareFlip, surfaceFlipIdx );
m_nSystemFlipId[surfaceFlipIdx] = nSystemFlipId;
Assert( !m_evFlipReady[ surfaceFlipIdx ].Check() );
m_interruptFifo.Queue( nEvent, surfaceFlipIdx );
}
ConVar r_ps3_mlaa_pulse( "r_ps3_mlaa_pulse", "0" );
enum EdgePostFlags_t {
EDGE_POST_MLAA_FLAG_MASK = ( EDGE_POST_MLAA_MODE_ENABLED | EDGE_POST_MLAA_MODE_SHOW_EDGES | EDGE_POST_MLAA_MODE_SINGLE_SPU_TRANSPOSE | EDGE_POST_MLAA_MODE_TRANSPOSE_64 )
};
void CFlipHandler::BeginScene()
{
#if GCM_ALLOW_TIMESTAMPS
if ( g_ps3_timestampBeginIdx >= 0 )
{
GCM_FUNC( cellGcmSetTimeStamp, g_ps3_timestampBeginIdx );
g_ps3_timestampBeginIdx = -1;
}
#endif
m_nMlaaFlagsThisFrame = r_ps3_mlaa.GetInt() & EDGE_POST_MLAA_FLAG_MASK;
if( int nPulse = r_ps3_mlaa_pulse.GetInt() )
{
if( 1 & ( g_spuGcm.m_nFrame / nPulse ) )
{
m_nMlaaFlagsThisFrame = 0; // disable for 16 frames = 1/2 second
}
}
m_nMlaaFlagsThisFrame &= m_nMlaaFlagMaskNextFrame;
//m_nMlaaFlagMaskNextFrame = (uint)-1;
}
void CFlipHandler::TransferMlaaResultIfNecessary( uint nSurfacePrevFlipIdx )
{
if( m_bEdgePostResultAlreadyInLocalMemory )
return;
if( g_edgePostWorkload.ShouldUseLabelForSynchronization() )
{
GCM_FUNC( cellGcmSetWaitLabel, GCM_LABEL_EDGEPOSTMLAA, nSurfacePrevFlipIdx );
}
else
{
// wait for SPU to finish post-processing previous surface
uint32 *pPrevJts = &g_spuGcm.m_pEdgePostRsxLock[ nSurfacePrevFlipIdx ];
if( *pPrevJts != CELL_GCM_RETURN() )
{
GCM_FUNC( cellGcmSetCallCommand, uintp( pPrevJts ) + g_spuGcmShared.m_nIoOffsetDelta );
}
}
//
// NOTE: we can start post-processing before SetPrepareFlip, it only makes sense since we don't always use interrupt to do so
// if we ever do proper synchronization with SPU workload, we should kick Edge Post here, before SetPrepareFlip
//
if( g_edgePostWorkload.IsResultInMainMemory() )
{
CPs3gcmLocalMemoryBlockSystemGlobal & prevSurfaceColor = g_ps3gcmGlobalState.m_display.surfaceColor[nSurfacePrevFlipIdx];
GCM_FUNC( cellGcmSetTransferImage, CELL_GCM_TRANSFER_MAIN_TO_LOCAL,
prevSurfaceColor.Offset(), g_ps3gcmGlobalState.m_nSurfaceRenderPitch, 0, 0,
uintp( g_spuGcm.m_pMlaaBufferOut ) + g_ps3gcmGlobalState.m_nIoOffsetDelta, g_ps3gcmGlobalState.m_nSurfaceRenderPitch, 0, 0,
g_ps3gcmGlobalState.m_nRenderSize[0], g_ps3gcmGlobalState.m_nRenderSize[1],
4 );
}
m_bEdgePostResultAlreadyInLocalMemory = true;
}
bool CFlipHandler::QmsAdviceBeforeDrawPrevFramebuffer()
{
uint nSurfacePrevFlipIdx = g_ps3gcmGlobalState.m_display.PrevSurfaceIndex( 1 );
uint8 prevPostProcessed = m_surfaceEdgePost[nSurfacePrevFlipIdx];
if( prevPostProcessed ) // did previous surface need post-processing?
{
// we'd actually be free to start MLAA here instead of in Flip, for the cost of one more RSX->PPU interrupt
// but we don't do that because we only may do so when the LAST player draws, and we don't know if this post processing
// that will now start is related to the LAST player
// we don't need to do that until flip if we're using deferred queue
// although if we're using deferred queue and we run out of space there, we stop using it, replay it and start defer-render into previous frame
TransferMlaaResultIfNecessary( nSurfacePrevFlipIdx );
// do the post-processing on this frame, in the mean time render into previous frame
return true;
}
return false; // there's no need to switch surfaces now
}
void CFlipHandler::Flip()
{
#if GCM_ALLOW_TIMESTAMPS
OnFrameTimestampAvailableMST( 1.0f );
#endif
extern ConVar mat_vsync;
m_bVSync = mat_vsync.GetBool();
g_ps3gcmGlobalState.CmdBufferFlush( CPs3gcmGlobalState::kFlushForcefully );
g_spuGcm.GetDrawQueue()->Push1( SPUDRAWQUEUE_FRAMEEVENT_METHOD | SDQFE_END_FRAME );
uint surfaceFlipIdx = g_ps3gcmGlobalState.m_display.surfaceFlipIdx, nSurfaceNextFlipIdx = g_ps3gcmGlobalState.m_display.NextSurfaceIndex( 1 ), nSurfaceAfterNextFlipIdx = g_ps3gcmGlobalState.m_display.NextSurfaceIndex( 2 ), nSurfacePrevFlipIdx = g_ps3gcmGlobalState.m_display.PrevSurfaceIndex( 1 );
/*
uint nScreenWidth = g_ps3gcmGlobalState.m_nRenderSize[0];
uint nScreenY = 40;
g_ps3gcmGlobalState.DrawDebugStripe( nScreenWidth * surfaceFlipIdx / 3, nScreenY, 0, nScreenWidth / 3, 4 );
g_ps3gcmGlobalState.DrawDebugStripe( ( g_spuGcm.m_nFrame & 0xF ) * ( nScreenWidth / 16 ), 34, 0, ( nScreenWidth / 16 ) * ( 1 + m_nFlipSurfaceCount ), 1 );
*/
// let interrupt know we're ready to post-process the new frame, and we wanna flip the previous frame
//g_ps3gcmGlobalState.CmdBufferFinish();
uint32 * pThisJts = g_spuGcm.m_pEdgePostRsxLock + surfaceFlipIdx; // may be NULL + idx
Assert( !g_spuGcm.m_pEdgePostRsxLock || *pThisJts == CELL_GCM_RETURN() );
uint8 prevPostProcessed = m_surfaceEdgePost[nSurfacePrevFlipIdx];
uint8 thisPostProcess = g_spuGcm.m_pMlaaBuffer ? ( uint8 ) ( m_nMlaaFlagsThisFrame & EDGE_POST_MLAA_FLAG_MASK ): 0 ;
if( prevPostProcessed ) // did previous surface need post-processing?
{
TransferMlaaResultIfNecessary( nSurfacePrevFlipIdx );
//if( g_spuGcm.m_bUseDeferredDrawQueue )
{
// now is the time to execute all the deferred commands, if there are any
// NOTE: this will often do nothing , because current frame would've flushed previous frame deferred commands already
// right before starting writing its own
g_spuGcm.ExecuteDeferredDrawQueue( 1 );
}
//g_ps3gcmGlobalState.DrawDebugStripe( nScreenWidth * surfaceFlipIdx / 3, 44, surfaceFlipIdx, nScreenWidth / 3, 2, -1 );
// prepare flip of previous frame - Edge Post processed buffer
// the previous frame was post-processed; we'll prepare flip on it.
QmsPrepareFlipSubmit( GCM_USERCMD_FLIPREADY, nSurfacePrevFlipIdx );
}
else
{
// if previous frame wasn't post-processed, don't flip it because we don't want to flip the same framebuffer twice (although we probably could)
// so we don't have anything to flip here, but have a frame to post-process
g_spuGcm.ExecuteDeferredDrawQueue( 1 );
}
m_surfaceEdgePost[surfaceFlipIdx] = thisPostProcess; // is post-process required for this surface ?
if( thisPostProcess )
{
if( !( m_nMlaaFlagsThisFrame & EDGE_POST_MLAA_MODE_ENABLED ) )
{
m_bEdgePostResultAlreadyInLocalMemory = true; // don't attempt to transfer the results; we don't _really_ do edge post processing, so we consider the results are in memory already
}
else
{
// EDGE POST TODO: JTS - the previous EdgePost must release it. To avoid overwriting edge post buffer before it finished tranferring back to local memory
// to release JTS from the future, we can use a separate ring buffer "JTS-RET" sequences and just call into it here.
// or we can wait for a label and set it from SPU
// as a simplification, we can just wait for edge post to finish synchronously on ppu
// we can also use a mutex of sorts and insert JTS here only when edge post is not finished yet
// we only can start transferring the image after the SPU is done streaming previous frame (if previous frame was post-processed)
// so wait for SPU to release previous frame, if it was post-processed.
// Also, if SPU didn't finish post-processing, then we need to synchronize (wait on RSX for SPU to be done)
// but in many cases SPU will be done by now, so we don't need to spend 900+ns in RSX front-end on CALL+RET
if( !g_edgePostWorkload.ShouldUseLabelForSynchronization() )
{
*pThisJts = CELL_GCM_JUMP( uintp( pThisJts ) + g_spuGcmShared.m_nIoOffsetDelta ); // this will be JTS for SPU to overwrite when post-processing of this frame is done
}
CPs3gcmLocalMemoryBlockSystemGlobal & surfaceColor = g_ps3gcmGlobalState.m_display.surfaceColor[surfaceFlipIdx];
GCM_FUNC( cellGcmSetTransferImage, CELL_GCM_TRANSFER_LOCAL_TO_MAIN,
uintp( g_spuGcm.m_pMlaaBuffer ) + g_ps3gcmGlobalState.m_nIoOffsetDelta, g_ps3gcmGlobalState.m_nSurfaceRenderPitch, 0, 0,
surfaceColor.Offset(), g_ps3gcmGlobalState.m_nSurfaceRenderPitch, 0, 0,
g_ps3gcmGlobalState.m_nRenderSize[0], g_ps3gcmGlobalState.m_nRenderSize[1],
4 );
// This frame was rendered and transferred to main memory; we'll let interrupt thread know it's ready for Edge Post processing
m_interruptFifo.Queue( GCM_USERCMD_POSTPROCESS, surfaceFlipIdx );
m_bEdgePostResultAlreadyInLocalMemory = false;
}
}
else
{
// we aren't post-processing this frame, so we need to just prepare flip and flip this framebuffer
g_spuGcm.ExecuteDeferredDrawQueue( 0 );
QmsPrepareFlipSubmit( GCM_USERCMD_FLIPREADY, surfaceFlipIdx );
m_bEdgePostResultAlreadyInLocalMemory = true; // don't attempt to transfer the results; we don't do edge post - processing, so we consider the results are in memory already
}
g_spuGcm.FlipDeferredDrawQueue( );
if( thisPostProcess && !prevPostProcessed )
{
// we absolutely MUST reset RSX state before the next frame.
// QmsPrepareFlipSubmit() does that by definition, but if we don't call it in this Flip (i.e. when !prevPostProcessed && thisPostProcess)
// we must FORCE RSX state reset
g_spuGcm.GetDrawQueue()->Push1( SPUDRAWQUEUE_RESETRSXSTATE_METHOD );
}
#if GCM_ALLOW_TIMESTAMPS
{
// The current frame has just finished, insert a timestamp instruction right before flip
GCM_FUNC( cellGcmSetTimeStamp, surfaceFlipIdx * 2 + GCM_REPORT_TIMESTAMP_FRAME_FIRST + 1 );
g_ps3_timestampBeginIdx = nSurfaceNextFlipIdx * 2 + GCM_REPORT_TIMESTAMP_FRAME_FIRST;
}
#endif
m_interruptFifo.QueueRsxInterrupt();
g_ps3gcmGlobalState.CmdBufferFlush( CPs3gcmGlobalState::kFlushEndFrame );
//g_ps3gcmGlobalState.CmdBufferFinish();
//
// Make sure that the next framebuffer is free to render into. For that to be so,
// the flip should happen from the next to the buffer after next. When that happens,
// the TV shows the buffer after next, and the next buffer is not visible to the user,
// so it's allowed to render into the next buffer.
//
FLIP_LOG( "ev Wait %d", nSurfaceAfterNextFlipIdx );
m_evFlipReady[ nSurfaceAfterNextFlipIdx ].Wait();
m_evFlipReady[ nSurfaceAfterNextFlipIdx ].Reset();
FLIP_LOG( "Draw %d, ev Reset %d", nSurfaceNextFlipIdx, nSurfaceAfterNextFlipIdx );
#if GCM_ALLOW_TIMESTAMPS
{
// Since the previous flip completely finished, we can grab its timestamps now
uint32 uiLastFrameTimestampIdx = ( nSurfaceAfterNextFlipIdx ) * 2 + GCM_REPORT_TIMESTAMP_FRAME_FIRST;
uint64 uiStartTimestamp = cellGcmGetTimeStamp( uiLastFrameTimestampIdx );
uint64 uiEndTimestamp = cellGcmGetTimeStamp( uiLastFrameTimestampIdx + 1 );
uint64 uiRsxTimeInNanoSeconds = uiEndTimestamp - uiStartTimestamp;
OnFrameTimestampAvailableRsx( uiRsxTimeInNanoSeconds / 1000000.0f );
}
#endif
}
bool IsRsxReadyForNoninteractiveRefresh( )
{
uint nSurfaceAfterNextFlipIdx = g_ps3gcmGlobalState.m_display.NextSurfaceIndex( 2 );
return g_flipHandler.m_evFlipReady[ nSurfaceAfterNextFlipIdx ].Check();
// if we are 3 vblanks past last flip already, another refresh would be welcome ; if we have no surfaces to flip in this case, we are most likely ready to flip right away
// another thing to check is the interrupt FIFO: if it's not idle, let's just postpone being ready
// return g_flipHandler.m_nVblankCounter > 3 && g_flipHandler.m_nFlipSurfaceCount == 0 && g_flipHandler.m_interruptFifo.IsIdle();
}
void CFlipHandler::TryFlipVblank()
{
// artificially simulate an interrupt for cause, because there's suspicion it was dropped
//
// only attempt to generate artificial interrupts if our ready flip queue is empty, otherwise there's no need
// to tap the narrow 15.6Mb/s bus
uint nMarker = *g_flipHandler.m_pLastInterruptGet;
m_nVblankCounter ++;
#if ENABLE_FLIP_LOG
static int m_nLastFlipLogIdx = 0;
if( m_nLastFlipLogIdx != g_flipLogIdx )
{
V_snprintf( g_flipLog[m_nLastFlipLogIdx], sizeof( g_flipLog[m_nLastFlipLogIdx] ), "%X.Vblanks ..%d", nMarker, m_nVblankCounter );
}
else
{
m_nLastFlipLogIdx = cellAtomicIncr32( &g_flipLogIdx ) & ( ARRAYSIZE( g_flipLog ) - 1 );
V_snprintf( g_flipLog[m_nLastFlipLogIdx], sizeof( g_flipLog[m_nLastFlipLogIdx] ), "%X.Vblank %d", nMarker, m_nVblankCounter );
}
#endif
TryPumpEvents( nMarker, 1 );
}
bool CFlipHandler::TryFlipSurface( uint isVblank )
{
if( !m_nFlipSurfaceCount )
{
return false;
}
if( m_bVSync )
{
if( m_nVblankCounter < m_nPresentFrequency )
{
//FLIP_LOG( "no flip: %d vblanks", m_nVblankCounter, m_nPresentFrequency );
return false;
}
if( !isVblank )
{
double flVSyncInterval = m_flVBlankTimestamp - m_flVBlankTimestamp0, flMissThreshold = r_ps3_vblank_miss_threshold.GetFloat() * flVSyncInterval;
double flMiss = Plat_FloatTime() - m_flVBlankTimestamp;
if ( flMiss > flMissThreshold )
{
FLIP_LOG("no flip: %.2fms miss", flMiss * 1000 );
return false; // wait for another vsync, missed by too much
}
}
}
// flip the surface immediately
uint nSystemFlipId = m_nSystemFlipId[ m_nFlipSurfaceIdx ];
cellGcmSetFlipImmediate( nSystemFlipId );
#ifdef GCM_ALLOW_TIMESTAMPS
// Collect time since previous flip
double flFlipImmediateTimestamp = Plat_FloatTime();
OnFrameTimestampAvailableFlip( ( flFlipImmediateTimestamp - m_flFlipImmediateTimestamp ) * 1000.0f );
m_flFlipImmediateTimestamp = flFlipImmediateTimestamp;
#endif
FLIP_LOG( isVblank ? "vFlip%u, ev Set %u" : "_Flip%u, ev Set %u", nSystemFlipId, m_nFlipSurfaceIdx );
// Release PPU QMS thread waiting for this flip
m_evFlipReady[m_nFlipSurfaceIdx].Set();
m_nFlipSurfaceIdx = ( m_nFlipSurfaceIdx + 1 ) % CPs3gcmDisplay::SURFACE_COUNT;
m_nFlipSurfaceCount--;
m_nVblankCounter = 0;
return true;
}
void CFlipHandler::TryPumpEvents( uint nMarker, uint isVblank )
{
if ( m_mutexOfInterruptThread.TryLock() )
{
PumpEventsUnsafe( nMarker );
TryFlipSurface( isVblank ); // this will often be duplicate call
g_flipHandler.m_mutexOfInterruptThread.Unlock();
}
}
void CFlipHandler::PumpEventsUnsafe( uint nMarker )
{
while( m_interruptFifo.HasEvents( nMarker ) )
{
if( !OnRsxInterrupt( m_interruptFifo.DequeueEvent() ) )
break;
}
}
bool RsxInterruptFifo::IsValidMarker( uint nMarker )
{
return ( nMarker - m_nGet ) <= MAX_EVENT_COUNT;
}
bool CFlipHandler::OnRsxInterrupt( const RsxInterruptFifo::Event_t event )
{
switch( event.m_nCause )
{
case GCM_USERCMD_POSTPROCESS:
{
// start edge post processing phase here; we can't do the flip yet because we didn't post-process the buffer yet
// Simulating MLAA job running and adding the cause to the end of the array some time in the nearest (4-5ms) future
void * pColorSurface = g_ps3gcmGlobalState.m_display.surfaceColor[event.m_nSurfaceFlipIdx].DataInLocalMemory();
if( true )
{
// g_spuGcm.SyncMlaa();
g_edgePostWorkload.Kick( pColorSurface, event.m_nSurfaceFlipIdx );
}
else
{
FLIP_LOG( "mlaa sync %d", event.m_nSurfaceFlipIdx );
g_spuGcm.SyncMlaa( pColorSurface );
g_spuGcm.m_pEdgePostRsxLock[event.m_nSurfaceFlipIdx] = CELL_GCM_RETURN(); // this will be poked by the SPU job
}
}
break;
case GCM_USERCMD_FLIPREADY:
FlipAssert( ( m_nFlipSurfaceIdx + m_nFlipSurfaceCount ) % CPs3gcmDisplay::SURFACE_COUNT == event.m_nSurfaceFlipIdx );
FLIP_LOG( "flip ready %d:sys%d", event.m_nSurfaceFlipIdx, m_nSystemFlipId[event.m_nSurfaceFlipIdx] );
m_nFlipSurfaceCount++;
break;
}
return true;
}
void CFlipHandler::INTERRUPT_VBlankHandler( const uint32 head )
{
double flVBlankTimestampSave = g_flipHandler.m_flVBlankTimestamp;
g_flipHandler.m_flVBlankTimestamp = Plat_FloatTime();
g_flipHandler.m_flVBlankTimestamp0 = flVBlankTimestampSave;
g_flipHandler.TryFlipVblank( );
}
void CFlipHandler::INTERRUPT_UserHandler( const uint32 nMarker )
{
if( g_flipHandler.m_interruptFifo.IsValidMarker( nMarker ) )
{
//FLIP_LOG( "%X.UserInterrupt", nMarker );
g_flipHandler.TryPumpEvents( nMarker, 0 );
}
else
{
// invalid marker: this marker has already happened; skip it
//FLIP_LOG( "%X.ERROR.UserInterrupt", nMarker );
DebuggerBreak();
}
}
void Ps3gcmFlip_SetFlipPresentFrequency( int nNumVBlanks )
{
if ( g_flipHandler.m_nPresentFrequency != nNumVBlanks )
{
nNumVBlanks = MAX( 1, nNumVBlanks );
nNumVBlanks = MIN( 12, nNumVBlanks );
if ( g_flipHandler.m_nPresentFrequency != nNumVBlanks )
{
g_flipHandler.m_nPresentFrequency = nNumVBlanks;
}
}
}
/*
void CFlipHandler::OnState( int nState, int nValue )
{
m_nDebugStates[nState] = nValue;
if( m_nDebugStates[RENDERING_SURFACE] == m_nDebugStates[DISPLAYING_SURFACE] )
DebuggerBreak();
}*/
Loaded 100 of 14243 files, more files were not shown because too many files have changed in this diff. Show more