1
0
mirror of https://github.com/alliedmodders/hl2sdk.git synced 2024-12-22 17:47:38 +08:00

Merge branch 'tf2' into hl2dm

# Conflicts:
#	game/client/cdll_util.cpp
#	game/client/clientleafsystem.cpp
#	game/client/clientshadowmgr.cpp
#	game/client/detailobjectsystem.cpp
#	game/server/filters.cpp
#	game/server/hltvdirector.cpp
#	game/server/physconstraint.cpp
#	game/server/props.cpp
#	game/shared/gamerules.cpp
#	game/shared/takedamageinfo.cpp
#	game/shared/takedamageinfo.h
#	lib/linux/tier1_i486.a
#	lib/mac/tier1_i486.a
#	lib/public/tier1.lib
#	public/eiface.h
#	public/mathlib/mathlib.h
#	public/tier0/memalloc.h
#	public/tier1/utlmemory.h
#	public/tier1/utlvector.h
#	public/toolframework/itoolentity.h
#	tier1/KeyValues.cpp
This commit is contained in:
Nicholas Hastings 2024-11-17 09:32:27 -05:00
commit 697e316fa9
167 changed files with 8478 additions and 3304 deletions

161
AMBuildScript Normal file
View File

@ -0,0 +1,161 @@
# vim: set ts=2 sw=2 tw=99 noet ft=python:
import os, sys, shutil
from ambuild2 import util
def ResolveEnvPath(env, folder=None):
if env in os.environ:
path = os.environ[env]
if os.path.isdir(path):
return path
return None
if folder:
head = os.getcwd()
oldhead = None
while head != None and head != oldhead:
path = os.path.join(head, folder)
if os.path.isdir(path):
return path
oldhead = head
head, tail = os.path.split(head)
return None
def Normalize(path):
return os.path.abspath(os.path.normpath(path))
class SDKConfig(object):
def __init__(self):
self.libs = []
self.targets = []
self.target_archs = set()
if builder.options.targets:
target_archs = builder.options.targets.split(',')
else:
target_archs = ['x86', 'x86_64']
for arch in target_archs:
try:
cxx = builder.DetectCxx(target_arch = arch)
self.target_archs.add(cxx.target.arch)
except Exception as e:
if builder.options.targets:
raise
print('Skipping target {}: {}'.format(arch, e))
continue
self.targets.append(cxx)
if not self.targets:
raise Exception('No suitable C/C++ compiler was found.')
@property
def tag(self):
if builder.options.debug == '1':
return 'Debug'
return 'Release'
def configure_cxx(self, cxx):
if cxx.like('gcc'):
self.configure_gcc(cxx)
elif cxx.family == 'msvc':
self.configure_msvc(cxx)
# Optimization
if builder.options.opt == '1':
cxx.defines += ['NDEBUG']
# Debugging
if builder.options.debug == '1':
cxx.defines += ['DEBUG', '_DEBUG']
if cxx.target.arch == 'x86_64':
cxx.defines += ['X64BITS', 'PLATFORM_64BITS']
# Platform-specifics
if cxx.target.platform == 'linux':
self.configure_linux(cxx)
elif cxx.target.platform == 'windows':
self.configure_windows(cxx)
def configure_gcc(self, cxx):
cxx.cflags += [
'-Wall',
'-Werror',
'-Wno-overloaded-virtual',
'-msse',
'-fPIC'
]
cxx.defines += [
'COMPILER_GCC'
]
cxx.cxxflags += [
'-std=c++17'
]
if builder.options.opt == '1':
cxx.cflags += ['-O3']
return
def configure_msvc(self, cxx):
cxx.defines += ['COMPILER_MSVC']
if cxx.target.arch == 'x86':
cxx.defines += ['COMPILER_MSVC32']
elif cxx.target.arch == 'x86_64':
cxx.defines += ['COMPILER_MSVC64']
cxx.cxxflags += [
'/std:c++17',
'/WX'
]
if builder.options.opt == '1':
cxx.cflags += ['/Ox', '/Zo']
cxx.linkflags += ['/OPT:ICF', '/OPT:REF']
return
def configure_linux(self, cxx):
cxx.defines += ['_LINUX', 'LINUX', 'POSIX', 'GNUC']
# Set of defines required by the HL2SDK
cxx.defines += [
'_finite=finite', 'stricmp=strcasecmp',
'_stricmp=strcasecmp', '_strnicmp=strncasecmp',
'strnicmp=strncasecmp', '_vsnprintf=vsnprintf',
'_alloca=alloca', 'strcmpi=strcasecmp',
'NO_MALLOC_OVERRIDE'
]
return
def configure_windows(self, cxx):
cxx.defines += ['_WINDOWS']
if cxx.target.arch == 'x86':
cxx.defines += ['WIN32']
elif cxx.target.arch == 'x86_64':
cxx.defines += ['WIN64']
return
def configure(self):
for cxx in self.targets:
self.configure_cxx(cxx)
def ConfigureLibrary(self, project, compiler, context, prefix = ''):
name = prefix + project.name
if compiler.target.platform == 'linux' and compiler.target.arch == 'x86':
name += '_i486'
binary = project.Configure(compiler, name, '{0} - {1}'.format(self.tag, compiler.target.arch))
binary.compiler.cxxincludes += [
os.path.join(context.currentSourcePath)
]
return binary
HL2SDK = SDKConfig()
HL2SDK.configure()
BuildScripts = ['mathlib/AMBuilder', 'tier1/AMBuilder', 'PackageScript']
# Turn off the 'lib' prefix for all platform, we will add it if we need to
util.StaticLibPrefix = ''
builder.Build(BuildScripts, { 'HL2SDK': HL2SDK })

56
PackageScript Normal file
View File

@ -0,0 +1,56 @@
# vim: set ts=8 sts=2 sw=2 tw=99 et ft=python:
import os
# This is where the files will be output to
# package is the default
builder.SetBuildFolder('lib')
folder_list = []
for task in HL2SDK.libs:
if task.target.platform == 'windows':
folder_list += ['public', 'public/win64']
break
for task in HL2SDK.libs:
if task.target.platform == 'linux':
folder_list += ['linux', 'linux64']
break
# Create the distribution folder hierarchy.
folder_map = {}
for folder in folder_list:
norm_folder = os.path.normpath(folder)
folder_map[folder] = builder.AddFolder(norm_folder)
# Do all straight-up file copies from the source tree.
def CopyFiles(src, dest, files):
if not dest:
dest = src
dest_entry = folder_map[dest]
for source_file in files:
source_path = os.path.join(builder.sourcePath, src, source_file)
builder.AddCopy(source_path, dest_entry)
def CopyFile(src, dest):
dest_entry = folder_map[dest]
source_path = os.path.join(builder.sourcePath, src)
builder.AddCopy(source_path, dest_entry)
def CopyDirContent(src, dest):
dest_entry = folder_map[dest]
for item in os.scandir(os.path.join(builder.sourcePath, src)):
if item.is_file():
builder.AddCopy(item.path, dest_entry)
# Copy binaries.
for task in HL2SDK.libs:
if task.target.platform == 'linux':
if task.target.arch == 'x86_64':
builder.AddCopy(task.binary, folder_map['linux64'])
else:
builder.AddCopy(task.binary, folder_map['linux'])
elif task.target.platform == 'windows':
if task.target.arch == 'x86_64':
builder.AddCopy(task.binary, folder_map['public/win64'])
else:
builder.AddCopy(task.binary, folder_map['public'])

11
configure.py Normal file
View File

@ -0,0 +1,11 @@
import sys
from ambuild2 import run
parser = run.BuildParser(sourcePath = sys.path[0], api='2.2')
parser.options.add_argument('--enable-debug', action='store_const', const='1', dest='debug',
help='Enable debugging symbols')
parser.options.add_argument('--enable-optimize', action='store_const', const='1', dest='opt',
help='Enable optimization')
parser.options.add_argument('--targets', type=str, dest='targets', default=None,
help="Override the target architecture (use commas to separate multiple targets).")
parser.Configure()

View File

@ -943,7 +943,7 @@ static unsigned char ComputeDistanceFade( C_BaseEntity *pEntity, float flMinDist
if( flMinDist > flMaxDist )
{
V_swap( flMinDist, flMaxDist );
::V_swap( flMinDist, flMaxDist );
}
// If a negative value is provided for the min fade distance, then base it off the max.

View File

@ -1722,8 +1722,8 @@ void CClientLeafSystem::SortEntities( const Vector &vecRenderOrigin, const Vecto
{
if( dists[i] > dists[i+stepSize] )
{
V_swap( pEntities[i], pEntities[i+stepSize] );
V_swap( dists[i], dists[i+stepSize] );
::V_swap( pEntities[i], pEntities[i+stepSize] );
::V_swap( dists[i], dists[i+stepSize] );
if( i == 0 )
{

View File

@ -1138,7 +1138,7 @@ void CVisibleShadowList::PrioritySort()
flLargestArea = m_ShadowsInView[nIndex].m_flArea;
}
}
V_swap( m_PriorityIndex[i], m_PriorityIndex[nLargestInd] );
::V_swap( m_PriorityIndex[i], m_PriorityIndex[nLargestInd] );
}
}

View File

@ -1613,7 +1613,7 @@ void CDetailObjectSystem::UnserializeDetailSprites( CUtlBuffer& buf )
buf.Get( &m_DetailSpriteDict[i], sizeof(DetailSpriteDictLump_t) );
int flipi = m_DetailSpriteDictFlipped.AddToTail();
m_DetailSpriteDictFlipped[flipi] = m_DetailSpriteDict[i];
V_swap( m_DetailSpriteDictFlipped[flipi].m_TexUL.x, m_DetailSpriteDictFlipped[flipi].m_TexLR.x );
::V_swap( m_DetailSpriteDictFlipped[flipi].m_TexUL.x, m_DetailSpriteDictFlipped[flipi].m_TexLR.x );
}
}

View File

@ -536,7 +536,7 @@ bool CFilterEnemy::PassesProximityFilter( CBaseEntity *pCaller, CBaseEntity *pEn
float flSmallerRadius = m_flRadius;
if ( flSmallerRadius > flLargerRadius )
{
V_swap( flLargerRadius, flSmallerRadius );
::V_swap( flLargerRadius, flSmallerRadius );
}
float flDist;

View File

@ -562,7 +562,7 @@ void CHLTVDirector::CreateShotFromEvent( CGameEvent *event )
// if we show ineye view, show it more likely from killer
if ( RandomFloat(0,1) > (bInEye?0.3f:0.7f) )
{
V_swap( attacker, victim );
::V_swap( attacker, victim );
}
// hurting a victim is shown as chase more often

View File

@ -1280,7 +1280,7 @@ IPhysicsConstraint *CPhysSlideConstraint::CreateConstraint( IPhysicsConstraintGr
sliding.limitMax = DotProduct( axisDirection, m_axisEnd );
if ( sliding.limitMax < sliding.limitMin )
{
V_swap( sliding.limitMin, sliding.limitMax );
::V_swap( sliding.limitMin, sliding.limitMax );
}
// expand limits to make initial position of the attached object valid

View File

@ -4789,7 +4789,7 @@ void CPropDoorRotating::Spawn()
// that the model already be set.
if ( IsHingeOnLeft() )
{
V_swap( m_angRotationOpenForward, m_angRotationOpenBack );
::V_swap( m_angRotationOpenForward, m_angRotationOpenBack );
}
// Figure out our volumes of movement as this door opens

View File

@ -15,7 +15,7 @@
void ScratchPad_DrawWorldToScratchPad(
IScratchPad3D *pPad,
unsigned long flags )
uint32_t flags )
{
pPad->SetRenderState( IScratchPad3D::RS_FillMode, IScratchPad3D::FillMode_Wireframe );
@ -52,7 +52,7 @@ void ScratchPad_DrawWorldToScratchPad(
void ScratchPad_DrawEntityToScratchPad(
IScratchPad3D *pPad,
unsigned long flags,
uint32_t flags,
CBaseEntity *pEnt,
const Vector &vColor )
{

View File

@ -27,12 +27,12 @@ class IScratchPad3D;
// flags is a combination of the SPDRAWWORLD_ flags.
void ScratchPad_DrawWorldToScratchPad(
IScratchPad3D *pPad,
unsigned long flags );
uint32_t flags );
// Draw a specific entity into the scratch pad.
void ScratchPad_DrawEntityToScratchPad(
IScratchPad3D *pPad,
unsigned long flags,
uint32_t flags,
CBaseEntity *pEnt,
const Vector &vColor );

View File

@ -86,7 +86,7 @@ class Color;
namespace vgui2
{
typedef unsigned long HFont;
typedef uint32_t HFont;
}
// -----------------------------------------

View File

@ -1,4 +1,4 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//========= Copyright <EFBFBD> 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
@ -45,7 +45,7 @@ CChoreoActor& CChoreoActor::operator=( const CChoreoActor& src )
Q_strncpy( m_szName, src.m_szName, sizeof( m_szName ) );
Q_strncpy( m_szFacePoserModelName, src.m_szFacePoserModelName, sizeof( m_szFacePoserModelName ) );
for ( int i = 0; i < src.m_Channels.Size(); i++ )
for ( int i = 0; i < src.m_Channels.Count(); i++ )
{
CChoreoChannel *c = src.m_Channels[ i ];
CChoreoChannel *newChannel = new CChoreoChannel();
@ -92,7 +92,7 @@ const char *CChoreoActor::GetName( void )
//-----------------------------------------------------------------------------
int CChoreoActor::GetNumChannels( void )
{
return m_Channels.Size();
return m_Channels.Count();
}
//-----------------------------------------------------------------------------
@ -102,7 +102,7 @@ int CChoreoActor::GetNumChannels( void )
//-----------------------------------------------------------------------------
CChoreoChannel *CChoreoActor::GetChannel( int channel )
{
if ( channel < 0 || channel >= m_Channels.Size() )
if ( channel < 0 || channel >= m_Channels.Count() )
{
return NULL;
}
@ -161,7 +161,7 @@ void CChoreoActor::SwapChannels( int c1, int c2 )
//-----------------------------------------------------------------------------
int CChoreoActor::FindChannelIndex( CChoreoChannel *channel )
{
for ( int i = 0; i < m_Channels.Size(); i++ )
for ( int i = 0; i < m_Channels.Count(); i++ )
{
if ( channel == m_Channels[ i ] )
{

View File

@ -1,4 +1,4 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//========= Copyright <EFBFBD> 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
@ -45,7 +45,7 @@ CChoreoChannel& CChoreoChannel::operator=( const CChoreoChannel& src )
{
m_bActive = src.m_bActive;
Q_strncpy( m_szName, src.m_szName, sizeof( m_szName ) );
for ( int i = 0; i < src.m_Events.Size(); i++ )
for ( int i = 0; i < src.m_Events.Count(); i++ )
{
CChoreoEvent *e = src.m_Events[ i ];
CChoreoEvent *newEvent = new CChoreoEvent( e->GetScene() );
@ -83,7 +83,7 @@ const char *CChoreoChannel::GetName( void )
//-----------------------------------------------------------------------------
int CChoreoChannel::GetNumEvents( void )
{
return m_Events.Size();
return m_Events.Count();
}
//-----------------------------------------------------------------------------
@ -93,7 +93,7 @@ int CChoreoChannel::GetNumEvents( void )
//-----------------------------------------------------------------------------
CChoreoEvent *CChoreoChannel::GetEvent( int event )
{
if ( event < 0 || event >= m_Events.Size() )
if ( event < 0 || event >= m_Events.Count() )
{
return NULL;
}
@ -138,7 +138,7 @@ void CChoreoChannel::RemoveAllEvents()
//-----------------------------------------------------------------------------
int CChoreoChannel::FindEventIndex( CChoreoEvent *event )
{
for ( int i = 0; i < m_Events.Size(); i++ )
for ( int i = 0; i < m_Events.Count(); i++ )
{
if ( event == m_Events[ i ] )
{

View File

@ -1,4 +1,4 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//========= Copyright <EFBFBD> 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
@ -432,7 +432,7 @@ CFlexAnimationTrack::CFlexAnimationTrack( const CFlexAnimationTrack* src )
for ( int t = 0; t < 2; t++ )
{
m_Samples[ t ].Purge();
for ( int i = 0 ;i < src->m_Samples[ t ].Size(); i++ )
for ( int i = 0 ;i < src->m_Samples[ t ].Count(); i++ )
{
CExpressionSample s = src->m_Samples[ t ][ i ];
m_Samples[ t ].AddToTail( s );
@ -527,7 +527,7 @@ int CFlexAnimationTrack::GetNumSamples( int type /*=0*/ )
{
Assert( type == 0 || type == 1 );
return m_Samples[ type ].Size();
return m_Samples[ type ].Count();
}
//-----------------------------------------------------------------------------
@ -931,9 +931,9 @@ void CFlexAnimationTrack::Resort( int type /*=0*/ )
{
Assert( type == 0 || type == 1 );
for ( int i = 0; i < m_Samples[ type ].Size(); i++ )
for ( int i = 0; i < m_Samples[ type ].Count(); i++ )
{
for ( int j = i + 1; j < m_Samples[ type ].Size(); j++ )
for ( int j = i + 1; j < m_Samples[ type ].Count(); j++ )
{
CExpressionSample src = m_Samples[ type ][ i ];
CExpressionSample dest = m_Samples[ type ][ j ];
@ -1116,7 +1116,7 @@ void CFlexAnimationTrack::RemoveOutOfRangeSamples( int type )
Assert( m_pEvent->HasEndTime() );
float duration = m_pEvent->GetDuration();
int c = m_Samples[ type ].Size();
int c = m_Samples[ type ].Count();
for ( int i = c-1; i >= 0; i-- )
{
CExpressionSample src = m_Samples[ type ][ i ];
@ -1217,14 +1217,14 @@ CChoreoEvent& CChoreoEvent::operator=( const CChoreoEvent& src )
}
int i;
for ( i = 0; i < src.m_RelativeTags.Size(); i++ )
for ( i = 0; i < src.m_RelativeTags.Count(); i++ )
{
CEventRelativeTag newtag( src.m_RelativeTags[ i ] );
newtag.SetOwner( this );
m_RelativeTags.AddToTail( newtag );
}
for ( i = 0; i < src.m_TimingTags.Size(); i++ )
for ( i = 0; i < src.m_TimingTags.Count(); i++ )
{
CFlexTimingTag newtag( src.m_TimingTags[ i ] );
newtag.SetOwner( this );
@ -1232,7 +1232,7 @@ CChoreoEvent& CChoreoEvent::operator=( const CChoreoEvent& src )
}
for ( t = 0; t < NUM_ABS_TAG_TYPES; t++ )
{
for ( i = 0; i < src.m_AbsoluteTags[ t ].Size(); i++ )
for ( i = 0; i < src.m_AbsoluteTags[ t ].Count(); i++ )
{
CEventAbsoluteTag newtag( src.m_AbsoluteTags[ t ][ i ] );
newtag.SetOwner( this );
@ -1242,7 +1242,7 @@ CChoreoEvent& CChoreoEvent::operator=( const CChoreoEvent& src )
RemoveAllTracks();
for ( i = 0 ; i < src.m_FlexAnimationTracks.Size(); i++ )
for ( i = 0 ; i < src.m_FlexAnimationTracks.Count(); i++ )
{
CFlexAnimationTrack *newtrack = new CFlexAnimationTrack( src.m_FlexAnimationTracks[ i ] );
newtrack->SetEvent( this );
@ -2382,7 +2382,7 @@ void CChoreoEvent::ClearAllRelativeTags( void )
//-----------------------------------------------------------------------------
int CChoreoEvent::GetNumRelativeTags( void )
{
return m_RelativeTags.Size();
return m_RelativeTags.Count();
}
//-----------------------------------------------------------------------------
@ -2392,7 +2392,7 @@ int CChoreoEvent::GetNumRelativeTags( void )
//-----------------------------------------------------------------------------
CEventRelativeTag *CChoreoEvent::GetRelativeTag( int tagnum )
{
Assert( tagnum >= 0 && tagnum < m_RelativeTags.Size() );
Assert( tagnum >= 0 && tagnum < m_RelativeTags.Count() );
return &m_RelativeTags[ tagnum ];
}
@ -2413,7 +2413,7 @@ void CChoreoEvent::AddRelativeTag( const char *tagname, float percentage )
//-----------------------------------------------------------------------------
void CChoreoEvent::RemoveRelativeTag( const char *tagname )
{
for ( int i = 0; i < m_RelativeTags.Size(); i++ )
for ( int i = 0; i < m_RelativeTags.Count(); i++ )
{
CEventRelativeTag *prt = &m_RelativeTags[ i ];
if ( !prt )
@ -2434,7 +2434,7 @@ void CChoreoEvent::RemoveRelativeTag( const char *tagname )
//-----------------------------------------------------------------------------
CEventRelativeTag * CChoreoEvent::FindRelativeTag( const char *tagname )
{
for ( int i = 0; i < m_RelativeTags.Size(); i++ )
for ( int i = 0; i < m_RelativeTags.Count(); i++ )
{
CEventRelativeTag *prt = &m_RelativeTags[ i ];
if ( !prt )
@ -2517,7 +2517,7 @@ void CChoreoEvent::ClearAllTimingTags( void )
//-----------------------------------------------------------------------------
int CChoreoEvent::GetNumTimingTags( void )
{
return m_TimingTags.Size();
return m_TimingTags.Count();
}
//-----------------------------------------------------------------------------
@ -2527,7 +2527,7 @@ int CChoreoEvent::GetNumTimingTags( void )
//-----------------------------------------------------------------------------
CFlexTimingTag *CChoreoEvent::GetTimingTag( int tagnum )
{
Assert( tagnum >= 0 && tagnum < m_TimingTags.Size() );
Assert( tagnum >= 0 && tagnum < m_TimingTags.Count() );
return &m_TimingTags[ tagnum ];
}
@ -2545,9 +2545,9 @@ void CChoreoEvent::AddTimingTag( const char *tagname, float percentage, bool loc
CFlexTimingTag temp( (CChoreoEvent *)0x1, "", 0.0f, false );
// ugly bubble sort
for ( int i = 0; i < m_TimingTags.Size(); i++ )
for ( int i = 0; i < m_TimingTags.Count(); i++ )
{
for ( int j = i + 1; j < m_TimingTags.Size(); j++ )
for ( int j = i + 1; j < m_TimingTags.Count(); j++ )
{
CFlexTimingTag *t1 = &m_TimingTags[ i ];
CFlexTimingTag *t2 = &m_TimingTags[ j ];
@ -2568,7 +2568,7 @@ void CChoreoEvent::AddTimingTag( const char *tagname, float percentage, bool loc
//-----------------------------------------------------------------------------
void CChoreoEvent::RemoveTimingTag( const char *tagname )
{
for ( int i = 0; i < m_TimingTags.Size(); i++ )
for ( int i = 0; i < m_TimingTags.Count(); i++ )
{
CFlexTimingTag *ptt = &m_TimingTags[ i ];
if ( !ptt )
@ -2589,7 +2589,7 @@ void CChoreoEvent::RemoveTimingTag( const char *tagname )
//-----------------------------------------------------------------------------
CFlexTimingTag * CChoreoEvent::FindTimingTag( const char *tagname )
{
for ( int i = 0; i < m_TimingTags.Size(); i++ )
for ( int i = 0; i < m_TimingTags.Count(); i++ )
{
CFlexTimingTag *ptt = &m_TimingTags[ i ];
if ( !ptt )
@ -2626,7 +2626,7 @@ void CChoreoEvent::OnEndTimeChanged( void )
//-----------------------------------------------------------------------------
int CChoreoEvent::GetNumFlexAnimationTracks( void )
{
return m_FlexAnimationTracks.Size();
return m_FlexAnimationTracks.Count();
}
//-----------------------------------------------------------------------------
@ -2928,7 +2928,7 @@ void CChoreoEvent::ClearAllAbsoluteTags( AbsTagType type )
//-----------------------------------------------------------------------------
int CChoreoEvent::GetNumAbsoluteTags( AbsTagType type )
{
return m_AbsoluteTags[ type ].Size();
return m_AbsoluteTags[ type ].Count();
}
//-----------------------------------------------------------------------------
@ -2939,7 +2939,7 @@ int CChoreoEvent::GetNumAbsoluteTags( AbsTagType type )
//-----------------------------------------------------------------------------
CEventAbsoluteTag *CChoreoEvent::GetAbsoluteTag( AbsTagType type, int tagnum )
{
Assert( tagnum >= 0 && tagnum < m_AbsoluteTags[ type ].Size() );
Assert( tagnum >= 0 && tagnum < m_AbsoluteTags[ type ].Count() );
return &m_AbsoluteTags[ type ][ tagnum ];
}
@ -2951,7 +2951,7 @@ CEventAbsoluteTag *CChoreoEvent::GetAbsoluteTag( AbsTagType type, int tagnum )
//-----------------------------------------------------------------------------
CEventAbsoluteTag *CChoreoEvent::FindAbsoluteTag( AbsTagType type, const char *tagname )
{
for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ )
for ( int i = 0; i < m_AbsoluteTags[ type ].Count(); i++ )
{
CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ];
if ( !ptag )
@ -2980,9 +2980,9 @@ void CChoreoEvent::AddAbsoluteTag( AbsTagType type, const char *tagname, float t
CEventAbsoluteTag temp( (CChoreoEvent *)0x1, "", 0.0f );
// ugly bubble sort
for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ )
for ( int i = 0; i < m_AbsoluteTags[ type ].Count(); i++ )
{
for ( int j = i + 1; j < m_AbsoluteTags[ type ].Size(); j++ )
for ( int j = i + 1; j < m_AbsoluteTags[ type ].Count(); j++ )
{
CEventAbsoluteTag *t1 = &m_AbsoluteTags[ type ][ i ];
CEventAbsoluteTag *t2 = &m_AbsoluteTags[ type ][ j ];
@ -3004,7 +3004,7 @@ void CChoreoEvent::AddAbsoluteTag( AbsTagType type, const char *tagname, float t
//-----------------------------------------------------------------------------
void CChoreoEvent::RemoveAbsoluteTag( AbsTagType type, const char *tagname )
{
for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ )
for ( int i = 0; i < m_AbsoluteTags[ type ].Count(); i++ )
{
CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ];
if ( !ptag )
@ -3032,7 +3032,7 @@ bool CChoreoEvent::VerifyTagOrder( )
// Sort tags
CEventAbsoluteTag temp( (CChoreoEvent *)0x1, "", 0.0f );
for ( int i = 0; i < m_AbsoluteTags[ CChoreoEvent::ORIGINAL ].Size(); i++ )
for ( int i = 0; i < m_AbsoluteTags[ CChoreoEvent::ORIGINAL ].Count(); i++ )
{
CEventAbsoluteTag *ptag = &m_AbsoluteTags[ CChoreoEvent::ORIGINAL ][ i ];
if ( !ptag )
@ -3044,7 +3044,7 @@ bool CChoreoEvent::VerifyTagOrder( )
continue;
bInOrder = false;
for ( int j = i + 1; j < m_AbsoluteTags[ CChoreoEvent::PLAYBACK ].Size(); j++ )
for ( int j = i + 1; j < m_AbsoluteTags[ CChoreoEvent::PLAYBACK ].Count(); j++ )
{
CEventAbsoluteTag *t2 = &m_AbsoluteTags[ CChoreoEvent::PLAYBACK ][ j ];
@ -3529,9 +3529,9 @@ void CCurveData::Clear( void )
//-----------------------------------------------------------------------------
void CCurveData::Resort( ICurveDataAccessor *data )
{
for ( int i = 0; i < m_Ramp.Size(); i++ )
for ( int i = 0; i < m_Ramp.Count(); i++ )
{
for ( int j = i + 1; j < m_Ramp.Size(); j++ )
for ( int j = i + 1; j < m_Ramp.Count(); j++ )
{
CExpressionSample src = m_Ramp[ i ];
CExpressionSample dest = m_Ramp[ j ];
@ -3688,7 +3688,7 @@ bool CChoreoEvent::PreventTagOverlap( void )
//-----------------------------------------------------------------------------
CEventAbsoluteTag *CChoreoEvent::FindEntryTag( AbsTagType type )
{
for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ )
for ( int i = 0; i < m_AbsoluteTags[ type ].Count(); i++ )
{
CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ];
if ( !ptag )
@ -3709,7 +3709,7 @@ CEventAbsoluteTag *CChoreoEvent::FindEntryTag( AbsTagType type )
//-----------------------------------------------------------------------------
CEventAbsoluteTag *CChoreoEvent::FindExitTag( AbsTagType type )
{
for ( int i = 0; i < m_AbsoluteTags[ type ].Size(); i++ )
for ( int i = 0; i < m_AbsoluteTags[ type ].Count(); i++ )
{
CEventAbsoluteTag *ptag = &m_AbsoluteTags[ type ][ i ];
if ( !ptag )

View File

@ -1,4 +1,4 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//===== Copyright <EFBFBD> 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
@ -102,7 +102,7 @@ void CChoreoScene::choreoprintf( int level, const char *fmt, ... )
}
else
{
printf( string );
printf( "%s", string );
}
Msg( "%s", string );
@ -128,7 +128,7 @@ CChoreoScene& CChoreoScene::operator=( const CChoreoScene& src )
// Delete existing
int i;
for ( i = 0; i < m_Actors.Size(); i++ )
for ( i = 0; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
Assert( a );
@ -137,7 +137,7 @@ CChoreoScene& CChoreoScene::operator=( const CChoreoScene& src )
m_Actors.RemoveAll();
for ( i = 0; i < m_Events.Size(); i++ )
for ( i = 0; i < m_Events.Count(); i++ )
{
CChoreoEvent *e = m_Events[ i ];
Assert( e );
@ -146,7 +146,7 @@ CChoreoScene& CChoreoScene::operator=( const CChoreoScene& src )
m_Events.RemoveAll();
for ( i = 0 ; i < m_Channels.Size(); i++ )
for ( i = 0 ; i < m_Channels.Count(); i++ )
{
CChoreoChannel *c = m_Channels[ i ];
Assert( c );
@ -172,7 +172,7 @@ CChoreoScene& CChoreoScene::operator=( const CChoreoScene& src )
// Now copy the object tree
// First copy the global events
for ( i = 0; i < src.m_Events.Size(); i++ )
for ( i = 0; i < src.m_Events.Count(); i++ )
{
CChoreoEvent *event = src.m_Events[ i ];
if ( event->GetActor() == NULL )
@ -186,7 +186,7 @@ CChoreoScene& CChoreoScene::operator=( const CChoreoScene& src )
}
// Finally, push actors, channels, events onto global stacks
for ( i = 0; i < src.m_Actors.Size(); i++ )
for ( i = 0; i < src.m_Actors.Count(); i++ )
{
CChoreoActor *actor = src.m_Actors[ i ];
CChoreoActor *newActor = AllocActor();
@ -264,7 +264,7 @@ void CChoreoScene::Init( IChoreoEventCallback *callback )
CChoreoScene::~CChoreoScene( void )
{
int i;
for ( i = 0; i < m_Actors.Size(); i++ )
for ( i = 0; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
Assert( a );
@ -273,7 +273,7 @@ CChoreoScene::~CChoreoScene( void )
m_Actors.RemoveAll();
for ( i = 0; i < m_Events.Size(); i++ )
for ( i = 0; i < m_Events.Count(); i++ )
{
CChoreoEvent *e = m_Events[ i ];
Assert( e );
@ -282,7 +282,7 @@ CChoreoScene::~CChoreoScene( void )
m_Events.RemoveAll();
for ( i = 0 ; i < m_Channels.Size(); i++ )
for ( i = 0 ; i < m_Channels.Count(); i++ )
{
CChoreoChannel *c = m_Channels[ i ];
Assert( c );
@ -390,7 +390,7 @@ void CChoreoScene::Print( void )
// Look for events that don't have actor/channel set
int i;
for ( i = 0 ; i < m_Events.Size(); i++ )
for ( i = 0 ; i < m_Events.Count(); i++ )
{
CChoreoEvent *e = m_Events[ i ];
if ( e->GetActor() )
@ -399,7 +399,7 @@ void CChoreoScene::Print( void )
PrintEvent( 0, e );
}
for ( i = 0 ; i < m_Actors.Size(); i++ )
for ( i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -478,7 +478,7 @@ CChoreoActor *CChoreoScene::AllocActor( void )
//-----------------------------------------------------------------------------
CChoreoActor *CChoreoScene::FindActor( const char *name )
{
for ( int i = 0; i < m_Actors.Size(); i++ )
for ( int i = 0; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -497,7 +497,7 @@ CChoreoActor *CChoreoScene::FindActor( const char *name )
//-----------------------------------------------------------------------------
int CChoreoScene::GetNumEvents( void )
{
return m_Events.Size();
return m_Events.Count();
}
//-----------------------------------------------------------------------------
@ -507,7 +507,7 @@ int CChoreoScene::GetNumEvents( void )
//-----------------------------------------------------------------------------
CChoreoEvent *CChoreoScene::GetEvent( int event )
{
if ( event < 0 || event >= m_Events.Size() )
if ( event < 0 || event >= m_Events.Count() )
return NULL;
return m_Events[ event ];
@ -519,7 +519,7 @@ CChoreoEvent *CChoreoScene::GetEvent( int event )
//-----------------------------------------------------------------------------
int CChoreoScene::GetNumActors( void )
{
return m_Actors.Size();
return m_Actors.Count();
}
//-----------------------------------------------------------------------------
@ -540,7 +540,7 @@ CChoreoActor *CChoreoScene::GetActor( int actor )
//-----------------------------------------------------------------------------
int CChoreoScene::GetNumChannels( void )
{
return m_Channels.Size();
return m_Channels.Count();
}
//-----------------------------------------------------------------------------
@ -619,9 +619,9 @@ void CCurveData::Parse( ISceneTokenProcessor *tokenizer, ICurveDataAccessor *dat
s->SetCurveType( curveType );
}
if ( samples.Size() >= 1 )
if ( samples.Count() >= 1 )
{
for ( int i = 0; i < samples.Size(); i++ )
for ( int i = 0; i < samples.Count(); i++ )
{
CExpressionSample sample = samples[ i ];
@ -840,7 +840,7 @@ void CChoreoScene::ParseFlexAnimations( ISceneTokenProcessor *tokenizer, CChoreo
}
}
if ( active || samples[ 0 ].Size() >= 1 )
if ( active || samples[ 0 ].Count() >= 1 )
{
// Add it in
CFlexAnimationTrack *track = e->AddTrack( flexcontroller );
@ -853,7 +853,7 @@ void CChoreoScene::ParseFlexAnimations( ISceneTokenProcessor *tokenizer, CChoreo
for ( int t = 0; t < ( combo ? 2 : 1 ); t++ )
{
for ( int i = 0; i < samples[ t ].Size(); i++ )
for ( int i = 0; i < samples[ t ].Count(); i++ )
{
CExpressionSample *sample = &samples[ t ][ i ];
@ -1527,7 +1527,7 @@ void CChoreoScene::InternalDetermineEventTypes()
{
m_bitvecHasEventOfType.ClearAll();
for ( int i = 0 ; i < m_Actors.Size(); i++ )
for ( int i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -1619,7 +1619,7 @@ void CChoreoScene::MarkForSaveAll( bool mark )
int i;
// Mark global events
for ( i = 0 ; i < m_Events.Size(); i++ )
for ( i = 0 ; i < m_Events.Count(); i++ )
{
CChoreoEvent *e = m_Events[ i ];
if ( e->GetActor() )
@ -1629,7 +1629,7 @@ void CChoreoScene::MarkForSaveAll( bool mark )
}
// Recursively mark everything else
for ( i = 0 ; i < m_Actors.Size(); i++ )
for ( i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -1652,7 +1652,7 @@ bool CChoreoScene::ExportMarkedToFile( const char *filename )
// Look for events that don't have actor/channel set
int i;
for ( i = 0 ; i < m_Events.Size(); i++ )
for ( i = 0 ; i < m_Events.Count(); i++ )
{
CChoreoEvent *e = m_Events[ i ];
if ( e->GetActor() )
@ -1661,7 +1661,7 @@ bool CChoreoScene::ExportMarkedToFile( const char *filename )
FileSaveEvent( buf, 0, e );
}
for ( i = 0 ; i < m_Actors.Size(); i++ )
for ( i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -1695,7 +1695,7 @@ bool CChoreoScene::SaveToFile( const char *filename )
// Look for events that don't have actor/channel set
int i;
for ( i = 0 ; i < m_Events.Size(); i++ )
for ( i = 0 ; i < m_Events.Count(); i++ )
{
CChoreoEvent *e = m_Events[ i ];
if ( e->GetActor() )
@ -1704,7 +1704,7 @@ bool CChoreoScene::SaveToFile( const char *filename )
FileSaveEvent( buf, 0, e );
}
for ( i = 0 ; i < m_Actors.Size(); i++ )
for ( i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -2219,7 +2219,7 @@ float CChoreoScene::FindAdjustedStartTime( void )
CChoreoEvent *e;
for ( int i = 0; i < m_Events.Size(); i++ )
for ( int i = 0; i < m_Events.Count(); i++ )
{
e = m_Events[ i ];
@ -2251,7 +2251,7 @@ float CChoreoScene::FindAdjustedEndTime( void )
CChoreoEvent *e;
for ( int i = 0; i < m_Events.Size(); i++ )
for ( int i = 0; i < m_Events.Count(); i++ )
{
e = m_Events[ i ];
@ -2290,7 +2290,7 @@ void CChoreoScene::ResetSimulation( bool forward /*= true*/, float starttime /*=
m_PauseEvents.RemoveAll();
// Put all items into the pending queue
for ( int i = 0; i < m_Events.Size(); i++ )
for ( int i = 0; i < m_Events.Count(); i++ )
{
e = m_Events[ i ];
e->ResetProcessing();
@ -2317,7 +2317,7 @@ void CChoreoScene::ResetSimulation( bool forward /*= true*/, float starttime /*=
// choreoprintf( 0, "Start time %f\n", m_flCurrentTime );
m_flLastActiveTime = 0.0f;
m_nActiveEvents = m_Events.Size();
m_nActiveEvents = m_Events.Count();
m_flStartTime = starttime;
m_flEndTime = endtime;
@ -2332,7 +2332,7 @@ bool CChoreoScene::CheckEventCompletion( void )
bool bAllCompleted = true;
// check all items in the active pending queue
for ( int i = 0; i < m_ActiveResumeConditions.Size(); i++ )
for ( int i = 0; i < m_ActiveResumeConditions.Count(); i++ )
{
e = m_ActiveResumeConditions[ i ];
@ -2378,7 +2378,7 @@ CChoreoEvent *CChoreoScene::FindPauseBetweenTimes( float starttime, float endtim
CChoreoEvent *e;
// Iterate through all events in the scene
for ( int i = 0; i < m_PauseEvents.Size(); i++ )
for ( int i = 0; i < m_PauseEvents.Count(); i++ )
{
e = m_PauseEvents[ i ];
if ( !e )
@ -2648,7 +2648,7 @@ void CChoreoScene::Think( float curtime )
// Iterate through all events in the scene
int i;
for ( i = 0; i < m_Events.Size(); i++ )
for ( i = 0; i < m_Events.Count(); i++ )
{
e = m_Events[ i ];
if ( !e )
@ -2803,7 +2803,7 @@ void CChoreoScene::RemoveActor( CChoreoActor *actor )
//-----------------------------------------------------------------------------
int CChoreoScene::FindActorIndex( CChoreoActor *actor )
{
for ( int i = 0; i < m_Actors.Size(); i++ )
for ( int i = 0; i < m_Actors.Count(); i++ )
{
if ( actor == m_Actors[ i ] )
{
@ -2882,7 +2882,7 @@ void CChoreoScene::DeleteReferencedObjects( CChoreoEvent *event )
//-----------------------------------------------------------------------------
void CChoreoScene::DestroyActor( CChoreoActor *actor )
{
int size = m_Actors.Size();
int size = m_Actors.Count();
for ( int i = size - 1; i >= 0; i-- )
{
CChoreoActor *a = m_Actors[ i ];
@ -2901,7 +2901,7 @@ void CChoreoScene::DestroyActor( CChoreoActor *actor )
//-----------------------------------------------------------------------------
void CChoreoScene::DestroyChannel( CChoreoChannel *channel )
{
int size = m_Channels.Size();
int size = m_Channels.Count();
for ( int i = size - 1; i >= 0; i-- )
{
CChoreoChannel *c = m_Channels[ i ];
@ -2920,7 +2920,7 @@ void CChoreoScene::DestroyChannel( CChoreoChannel *channel )
//-----------------------------------------------------------------------------
void CChoreoScene::DestroyEvent( CChoreoEvent *event )
{
int size = m_Events.Size();
int size = m_Events.Count();
for ( int i = size - 1; i >= 0; i-- )
{
CChoreoEvent *e = m_Events[ i ];
@ -2998,7 +2998,7 @@ void CChoreoScene::GetSceneTimes( float& start, float& end )
//-----------------------------------------------------------------------------
void CChoreoScene::ReconcileTags( void )
{
for ( int i = 0 ; i < m_Actors.Size(); i++ )
for ( int i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -3055,7 +3055,7 @@ void CChoreoScene::ReconcileTags( void )
//-----------------------------------------------------------------------------
CChoreoEvent *CChoreoScene::FindTargetingEvent( const char *wavname, const char *name )
{
for ( int i = 0 ; i < m_Actors.Size(); i++ )
for ( int i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -3097,7 +3097,7 @@ CChoreoEvent *CChoreoScene::FindTargetingEvent( const char *wavname, const char
//-----------------------------------------------------------------------------
CEventRelativeTag *CChoreoScene::FindTagByName( const char *wavname, const char *name )
{
for ( int i = 0 ; i < m_Actors.Size(); i++ )
for ( int i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -3139,16 +3139,16 @@ CEventRelativeTag *CChoreoScene::FindTagByName( const char *wavname, const char
//-----------------------------------------------------------------------------
void CChoreoScene::ExportEvents( const char *filename, CUtlVector< CChoreoEvent * >& events )
{
if ( events.Size() <= 0 )
if ( events.Count() <= 0 )
return;
// Create a serialization buffer
CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
FilePrintf( buf, 0, "// Choreo version 1: <%i> Exported Events\n", events.Size() );
FilePrintf( buf, 0, "// Choreo version 1: <%i> Exported Events\n", events.Count() );
// Save out the selected events.
int i;
for ( i = 0 ; i < events.Size(); i++ )
for ( i = 0 ; i < events.Count(); i++ )
{
CChoreoEvent *e = events[ i ];
if ( !e->GetActor() )
@ -3275,7 +3275,7 @@ float CChoreoScene::SnapTime( float t )
//-----------------------------------------------------------------------------
void CChoreoScene::ReconcileGestureTimes()
{
for ( int i = 0 ; i < m_Actors.Size(); i++ )
for ( int i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -3387,7 +3387,7 @@ bool CChoreoScene::Merge( CChoreoScene *other )
// Look for events that don't have actor/channel set
int i;
for ( i = 0 ; i < other->m_Events.Size(); i++ )
for ( i = 0 ; i < other->m_Events.Count(); i++ )
{
CChoreoEvent *e = other->m_Events[ i ];
if ( e->GetActor() )
@ -3401,7 +3401,7 @@ bool CChoreoScene::Merge( CChoreoScene *other )
ecount++;
}
for ( i = 0 ; i < other->m_Actors.Size(); i++ )
for ( i = 0 ; i < other->m_Actors.Count(); i++ )
{
CChoreoActor *a = other->m_Actors[ i ];
@ -3472,7 +3472,7 @@ bool CChoreoScene::Merge( CChoreoScene *other )
//-----------------------------------------------------------------------------
void CChoreoScene::ReconcileCloseCaption()
{
for ( int i = 0 ; i < m_Actors.Size(); i++ )
for ( int i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )
@ -3507,7 +3507,7 @@ void CChoreoScene::SetFileName( char const *fn )
bool CChoreoScene::GetPlayingSoundName( char *pchBuff, int iBuffLength )
{
for ( int i = 0; i < m_Events.Size(); i++ )
for ( int i = 0; i < m_Events.Count(); i++ )
{
CChoreoEvent *e = m_Events[ i ];
if ( e->GetType() == CChoreoEvent::SPEAK && e->IsProcessing() )
@ -3525,7 +3525,7 @@ bool CChoreoScene::GetPlayingSoundName( char *pchBuff, int iBuffLength )
//-----------------------------------------------------------------------------
bool CChoreoScene::HasUnplayedSpeech()
{
for ( int i = 0; i < m_Events.Size(); i++ )
for ( int i = 0; i < m_Events.Count(); i++ )
{
CChoreoEvent *e = m_Events[ i ];
if ( e->GetType() == CChoreoEvent::SPEAK )
@ -3544,7 +3544,7 @@ bool CChoreoScene::HasUnplayedSpeech()
//-----------------------------------------------------------------------------
bool CChoreoScene::HasFlexAnimation()
{
for ( int i = 0; i < m_Events.Size(); i++ )
for ( int i = 0; i < m_Events.Count(); i++ )
{
CChoreoEvent *e = m_Events[ i ];
if ( e->GetType() == CChoreoEvent::FLEXANIMATION )
@ -3631,7 +3631,7 @@ void CChoreoScene::SaveToBinaryBuffer( CUtlBuffer& buf, unsigned int nTextVersio
// Look for events that don't have actor/channel set
CUtlVector< CChoreoEvent * > eventList;
int i;
for ( i = 0 ; i < m_Events.Size(); i++ )
for ( i = 0 ; i < m_Events.Count(); i++ )
{
CChoreoEvent *e = m_Events[ i ];
if ( e->GetActor() )
@ -3651,7 +3651,7 @@ void CChoreoScene::SaveToBinaryBuffer( CUtlBuffer& buf, unsigned int nTextVersio
// Now serialize the actors themselves
CUtlVector< CChoreoActor * > actorList;
for ( i = 0 ; i < m_Actors.Size(); i++ )
for ( i = 0 ; i < m_Actors.Count(); i++ )
{
CChoreoActor *a = m_Actors[ i ];
if ( !a )

View File

@ -1,4 +1,4 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
@ -42,9 +42,9 @@ public:
virtual void StartTrackPredictionErrors( CBasePlayer *pPlayer );
virtual void FinishTrackPredictionErrors( CBasePlayer *pPlayer );
virtual void DiffPrint( char const *fmt, ... );
virtual const Vector& GetPlayerMins( bool ducked ) const;
virtual const Vector& GetPlayerMaxs( bool ducked ) const;
virtual const Vector& GetPlayerViewOffset( bool ducked ) const;
virtual Vector GetPlayerMins( bool ducked ) const;
virtual Vector GetPlayerMaxs( bool ducked ) const;
virtual Vector GetPlayerViewOffset( bool ducked ) const;
// For sanity checking getting stuck on CMoveData::SetAbsOrigin
virtual void TracePlayerBBox( const Vector& start, const Vector& end, unsigned int fMask, int collisionGroup, trace_t& pm );
@ -105,8 +105,8 @@ protected:
// Implement this if you want to know when the player collides during OnPlayerMove
virtual void OnTryPlayerMoveCollision( trace_t &tr ) {}
virtual const Vector& GetPlayerMins( void ) const; // uses local player
virtual const Vector& GetPlayerMaxs( void ) const; // uses local player
virtual Vector GetPlayerMins( void ) const; // uses local player
virtual Vector GetPlayerMaxs( void ) const; // uses local player
typedef enum
{

View File

@ -637,7 +637,7 @@ bool CGameRules::ShouldCollide( int collisionGroup0, int collisionGroup1 )
if ( collisionGroup0 > collisionGroup1 )
{
// swap so that lowest is always first
V_swap(collisionGroup0,collisionGroup1);
::V_swap(collisionGroup0,collisionGroup1);
}
#ifndef HL2MP

View File

@ -62,6 +62,8 @@ void CTakeDamageInfo::Init( CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBa
m_flDamageBonus = 0.f;
m_bForceFriendlyFire = false;
m_flDamageForForce = 0.f;
m_eCritType = kCritType_None;
}
CTakeDamageInfo::CTakeDamageInfo()
@ -114,6 +116,18 @@ void CTakeDamageInfo::Set( CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBas
Init( pInflictor, pAttacker, pWeapon, damageForce, damagePosition, vecReported, flDamage, bitsDamageType, iKillType );
}
void CTakeDamageInfo::SetCritType( ECritType type )
{
if ( type == kCritType_None )
{
m_eCritType = kCritType_None;
}
else if ( type > m_eCritType )
{
m_eCritType = type;
}
}
//-----------------------------------------------------------------------------
// Squirrel the damage value away as BaseDamage, which will later be used to
// calculate damage force.

View File

@ -98,6 +98,14 @@ public:
void Set( CBaseEntity *pInflictor, CBaseEntity *pAttacker, const Vector &damageForce, const Vector &damagePosition, float flDamage, int bitsDamageType, int iKillType = 0, Vector *reportedPosition = NULL );
void Set( CBaseEntity *pInflictor, CBaseEntity *pAttacker, CBaseEntity *pWeapon, const Vector &damageForce, const Vector &damagePosition, float flDamage, int bitsDamageType, int iKillType = 0, Vector *reportedPosition = NULL );
enum ECritType
{
kCritType_None,
kCritType_MiniCrit,
kCritType_Crit,
};
void SetCritType( ECritType type );
void AdjustPlayerDamageInflictedForSkillLevel();
void AdjustPlayerDamageTakenForSkillLevel();
@ -133,6 +141,8 @@ protected:
float m_flDamageForForce;
ECritType m_eCritType;
DECLARE_SIMPLE_DATADESC();
};

View File

@ -162,7 +162,7 @@ bool CVoiceGameMgr::ClientCommand( CBasePlayer *pPlayer, const CCommand &args )
{
for(int i=1; i < args.ArgC(); i++)
{
unsigned long mask = 0;
uint32_t mask = 0;
sscanf( args[i], "%p", (void**)&mask);
if( i <= VOICE_MAX_PLAYERS_DW )

View File

@ -349,11 +349,11 @@ void CVoiceStatus::UpdateServerState(bool bForce)
Q_strncpy(str,"vban",sizeof(str));
bool bChange = false;
for(unsigned long dw=0; dw < VOICE_MAX_PLAYERS_DW; dw++)
for(uint32_t dw=0; dw < VOICE_MAX_PLAYERS_DW; dw++)
{
unsigned long serverBanMask = 0;
unsigned long banMask = 0;
for(unsigned long i=0; i < 32; i++)
uint32_t serverBanMask = 0;
uint32_t banMask = 0;
for(uint32_t i=0; i < 32; i++)
{
int playerIndex = ( dw * 32 + i );
if ( playerIndex >= MAX_PLAYERS )
@ -408,11 +408,11 @@ void CVoiceStatus::UpdateServerState(bool bForce)
void CVoiceStatus::HandleVoiceMaskMsg(bf_read &msg)
{
unsigned long dw;
uint32_t dw;
for(dw=0; dw < VOICE_MAX_PLAYERS_DW; dw++)
{
m_AudiblePlayers.SetDWord(dw, (unsigned long)msg.ReadLong());
m_ServerBannedPlayers.SetDWord(dw, (unsigned long)msg.ReadLong());
m_AudiblePlayers.SetDWord(dw, (uint32_t)msg.ReadLong());
m_ServerBannedPlayers.SetDWord(dw, (uint32_t)msg.ReadLong());
if( voice_clientdebug.GetInt())
{

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
lib/linux64/libtier0_srv.so Normal file

Binary file not shown.

Binary file not shown.

BIN
lib/linux64/mathlib.a Normal file

Binary file not shown.

BIN
lib/linux64/tier1.a Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
lib/public/win64/tier0.lib Normal file

Binary file not shown.

BIN
lib/public/win64/tier1.lib Normal file

Binary file not shown.

Binary file not shown.

View File

@ -1,175 +0,0 @@
#
# SDK Makefile for x86 Linux
#
#
OS := $(shell uname -s)
#############################################################################
# Developer configurable items
#############################################################################
# the name of the mod binary (_i486.so is appended to the end)
NAME = server
# the location of the vcproj that builds the mod
MOD_PROJ = ../game/server/server_scratch-2005.vcproj
# the name of the mod configuration (typically <proj name>_<build type><build target>)
MOD_CONFIG = Server\(SDK\)_ReleaseWin32
# the directory the base binaries (tier0_i486.so, etc) are located
# this should point to your orange box subfolder of where you have srcds installed.
SRCDS_DIR = ~/srcds/orangebox
# the path to your mods directory
# set this so that 'make install' or 'make installrelease' will copy your binary over automatically.
GAME_DIR = $(SRCDS_DIR)/scratchmod
# compiler options (gcc 3.4.1 or above is required - 4.1.2+ recommended)
ifeq "$(OS)" "Darwin"
CC = /usr/bin/clang
CPLUS = /usr/bin/clang++
CLINK = /usr/bin/clang
CPP_LIB =
else
CC = /usr/bin/gcc
CPLUS = /usr/bin/g++
CLINK = /usr/bin/gcc
CPP_LIB = $(SRCDS_DIR)/bin/libstdc++.so.6 $(SRCDS_DIR)/bin/libgcc_s.so.1
endif
# put any compiler flags you want passed here
USER_CFLAGS =
# link flags for your mod, make sure to include any special libraries here
LDFLAGS = "-lm -ldl $(LIB_DIR)/particles_i486.a $(LIB_DIR)/dmxloader_i486.a $(LIB_DIR)/mathlib_i486.a tier0_i486.so vstdlib_i486.so $(LIB_DIR)/tier1_i486.a $(LIB_DIR)/tier2_i486.a $(LIB_DIR)/tier3_i486.a $(LIB_DIR)/choreoobjects_i486.a steam_api_i486.so"
# XERCES 2.6.0 or above ( http://xml.apache.org/xerces-c/ ) is used by the vcproj to makefile converter
# it must be installed before being able to run this makefile
# if you have xerces installed already you should be able to use the two lines below
XERCES_INC_DIR = /usr/include
XERCES_LIB_DIR = /usr/lib
# Change this to true if you want to build debug binaries for everything
# The only exception is the mod/game as MOD_CONFIG determines if it's a debug build or not
DEBUG = false
#############################################################################
# Things below here shouldn't need to be altered
#############################################################################
MAKE = make
AR = "ar rvs"
# the dir we want to put binaries we build into
BUILD_DIR = .
# the place to put object files
BUILD_OBJ_DIR = $(BUILD_DIR)/obj
# the location of the source code
SRC_DIR = ..
# the location of the static libraries
ifeq "$(OS)" "Darwin"
LIB_DIR = $(SRC_DIR)/lib/mac
else
LIB_DIR = $(SRC_DIR)/lib/linux
endif
# the CPU target for the build, must be i486 for now
ARCH = i486
ARCH_CFLAGS = -mtune=i686 -march=pentium3 -mmmx -m32
ifeq "$(OS)" "Darwin"
DEFINES = -D_OSX -DOSX
SHLIBEXT = dylib
SHLIBLDFLAGS = -dynamiclib -mmacosx-version-min=10.5
SHLIBSUFFIX =
else
DEFINES = -D_LINUX -DLINUX
SHLIBEXT = so
SHLIBLDFLAGS = -shared -Wl,-Map,$@_map.txt -Wl
SHLIBSUFFIX = _srv
endif
DEFINES +=-DVPROF_LEVEL=1 -DSWDS -D_finite=finite -Dstricmp=strcasecmp -D_stricmp=strcasecmp -D_strnicmp=strncasecmp \
-Dstrnicmp=strncasecmp -D_vsnprintf=vsnprintf -D_alloca=alloca -Dstrcmpi=strcasecmp
UNDEF = -Usprintf -Ustrncpy -UPROTECTED_THINGS_ENABLE
BASE_CFLAGS = -fno-strict-aliasing -Wall -Wsign-compare -Werror -Wno-conversion -Wno-overloaded-virtual -Wno-non-virtual-dtor -Wno-invalid-offsetof \
-Wno-delete-non-virtual-dtor
SHLIBCFLAGS = -fPIC
# Flags passed to the c compiler
CFLAGS = $(DEFINES) $(ARCH_CFLAGS) -O3 $(BASE_CFLAGS)
ifdef USER_CFLAGS
CFLAGS += $(USER_CFLAGS)
endif
CFLAGS += $(UNDEF)
# Debug flags
DBG_DEFINES = "-D_DEBUG -DDEBUG"
DBG_CFLAGS = "$(DEFINES) $(ARCH_CFLAGS) -g -ggdb $(BASE_CFLAGS) $(UNDEF)"
# define list passed to make for the sub makefile
BASE_DEFINES = CC=$(CC) AR=$(AR) CPLUS=$(CPLUS) CPP_LIB=$(CPP_LIB) DEBUG=$(DEBUG) \
BUILD_DIR=$(BUILD_DIR) BUILD_OBJ_DIR=$(BUILD_OBJ_DIR) SRC_DIR=$(SRC_DIR) \
LIB_DIR=$(LIB_DIR) SHLIBLDFLAGS="$(SHLIBLDFLAGS)" SHLIBEXT=$(SHLIBEXT) SHLIBSUFFIX=$(SHLIBSUFFIX) \
CLINK=$(CLINK) CFLAGS="$(CFLAGS)" DBG_CFLAGS=$(DBG_CFLAGS) LDFLAGS=$(LDFLAGS) \
DEFINES="$(DEFINES)" DBG_DEFINES=$(DBG_DEFINES) \
ARCH=$(ARCH) SRCDS_DIR=$(SRCDS_DIR) MOD_CONFIG=$(MOD_CONFIG) NAME=$(NAME) \
XERCES_INC_DIR=$(XERCES_INC_DIR) XERCES_LIB_DIR=$(XERCES_LIB_DIR)
# Project Makefile
MAKE_SERVER = Makefile.server
MAKE_VCPM = Makefile.vcpm
MAKE_PLUGIN = Makefile.plugin
MAKE_TIER1 = Makefile.tier1
MAKE_MATH = Makefile.mathlib
MAKE_CHOREO = Makefile.choreo
all: check vcpm mod
check:
if [ -z "$(CC)" ]; then echo "Compiler not defined."; exit; fi
if [ ! -d $(BUILD_DIR) ];then mkdir -p $(BUILD_DIR);fi
cd $(BUILD_DIR)
if [ ! -e "$(LIB_DIR)/tier1_i486.a" ]; then $(MAKE) tier1;fi
if [ ! -e "$(LIB_DIR)/mathlib_i486.a" ]; then $(MAKE) mathlib;fi
if [ ! -e "$(LIB_DIR)/choreoobjects_i486.a" ]; then $(MAKE) choreo;fi
if [ ! -f "libtier0$(SHLIBSUFFIX).$(SHLIBEXT)" ]; then ln -fs $(LIB_DIR)/libtier0$(SHLIBSUFFIX).$(SHLIBEXT) .; fi
if [ ! -f "libvstdlib$(SHLIBSUFFIX).$(SHLIBEXT)" ]; then ln -fs $(LIB_DIR)/libvstdlib$(SHLIBSUFFIX).$(SHLIBEXT) .; fi
if [ ! -f "libsteam_api.$(SHLIBEXT)" ]; then ln -fs $(LIB_DIR)/libsteam_api.$(SHLIBEXT) .; fi
vcpm: check
if [ ! -e "vcpm" ]; then $(MAKE) -f $(MAKE_VCPM) $(BASE_DEFINES);fi
mod: check vcpm
./vcpm $(MOD_PROJ)
$(MAKE) -f $(MAKE_SERVER) $(BASE_DEFINES)
plugin: check
$(MAKE) -f $(MAKE_PLUGIN) $(BASE_DEFINES)
tier1:
$(MAKE) -f $(MAKE_TIER1) $(BASE_DEFINES)
mathlib:
$(MAKE) -f $(MAKE_MATH) $(BASE_DEFINES)
choreo:
$(MAKE) -f $(MAKE_CHOREO) $(BASE_DEFINES)
install:
cp -f $(NAME)_$(ARCH).$(SHLIBEXT) $(GAME_DIR)/bin/$(NAME)_$(ARCH).$(SHLIBEXT)
installrelease:
cp -f $(NAME)_$(ARCH).$(SHLIBEXT) $(GAME_DIR)/bin/$(NAME)_$(ARCH).$(SHLIBEXT)
strip $(GAME_DIR)/bin/$(NAME)_$(ARCH).$(SHLIBEXT)
clean:
$(MAKE) -f $(MAKE_VCPM) $(BASE_DEFINES) clean
$(MAKE) -f $(MAKE_PLUGIN) $(BASE_DEFINES) clean
$(MAKE) -f $(MAKE_SERVER) $(BASE_DEFINES) clean
$(MAKE) -f $(MAKE_TIER1) $(BASE_DEFINES) clean
$(MAKE) -f $(MAKE_MATH) $(BASE_DEFINES) clean
$(MAKE) -f $(MAKE_CHOREO) $(BASE_DEFINES) clean

View File

@ -1,57 +0,0 @@
#
# Choreoobjects Static Library Makefile
#
override NAME = choreoobjects
LIB_SRC_DIR = $(SRC_DIR)/game/shared
PUBLIC_SRC_DIR = $(SRC_DIR)/public
TIER0_PUBLIC_SRC_DIR = $(SRC_DIR)/public/tier0
TIER1_PUBLIC_SRC_DIR = $(SRC_DIR)/public/tier1
UTIL_COMMON_SRC_DIR = $(SRC_DIR)/utils/common
LIB_OBJ_DIR = $(BUILD_OBJ_DIR)/$(NAME)_$(ARCH)
# Extension of linux static library
override SHLIBEXT = a
INCLUDEDIRS = -I$(LIB_SRC_DIR) -I$(PUBLIC_SRC_DIR) -I$(TIER0_PUBLIC_SRC_DIR) -I$(TIER1_PUBLIC_SRC_DIR) -I$(UTIL_COMMON_SRC_DIR) -D_LIB -DCHOREOOBJECTS_STATIC_LIB
DO_CC = $(CPLUS) $(INCLUDEDIRS) -DARCH=$(ARCH)
ifeq "$(DEBUG)" "true"
DO_CC += $(DBG_DEFINES) $(DBG_CFLAGS)
else
DO_CC += -DNDEBUG $(CFLAGS)
endif
DO_CC += -o $@ -c $<
#####################################################################
LIB_OBJS= \
$(LIB_OBJ_DIR)/choreoactor.o \
$(LIB_OBJ_DIR)/choreochannel.o \
$(LIB_OBJ_DIR)/choreoevent.o \
$(LIB_OBJ_DIR)/choreoscene.o \
$(LIB_OBJ_DIR)/sceneimage.o \
all: dirs $(NAME)_$(ARCH).$(SHLIBEXT)
dirs:
-mkdir -p $(BUILD_OBJ_DIR)
-mkdir -p $(LIB_OBJ_DIR)
$(NAME)_$(ARCH).$(SHLIBEXT): $(LIB_OBJS)
$(AR) $(LIB_DIR)/$@ $(LIB_OBJS)
$(LIB_OBJ_DIR)/%.o: $(LIB_SRC_DIR)/%.cpp
$(DO_CC)
install:
cp -f $(NAME)_$(ARCH).$(SHLIBEXT) $(LIB_DIR)/$(NAME)_$(ARCH).$(SHLIBEXT)
clean:
-rm -rf $(LIB_OBJ_DIR)

View File

@ -1,70 +0,0 @@
#
# Mathlin Static Library Makefile
#
override NAME = mathlib
LIB_SRC_DIR = $(SRC_DIR)/$(NAME)
PUBLIC_SRC_DIR = $(SRC_DIR)/public
TIER0_PUBLIC_SRC_DIR = $(SRC_DIR)/public/tier0
TIER1_PUBLIC_SRC_DIR = $(SRC_DIR)/public/tier1
MATHLIB_PUBLIC_SRC_DIR = $(SRC_DIR)/public/mathlib
LIB_OBJ_DIR = $(BUILD_OBJ_DIR)/$(NAME)_$(ARCH)
# Extension of linux static library
override SHLIBEXT = a
INCLUDEDIRS = -I$(PUBLIC_SRC_DIR) -I$(TIER0_PUBLIC_SRC_DIR) -I$(TIER1_PUBLIC_SRC_DIR) -I$(MATHLIB_PUBLIC_SRC_DIR) -D_LIB
DO_CC = $(CPLUS) $(INCLUDEDIRS) -DARCH=$(ARCH)
ifeq "$(DEBUG)" "true"
DO_CC += $(DBG_DEFINES) $(DBG_CFLAGS)
else
DO_CC += -DNDEBUG $(CFLAGS)
endif
DO_CC += -o $@ -c $<
#####################################################################
LIB_OBJS= \
$(LIB_OBJ_DIR)/anorms.o \
$(LIB_OBJ_DIR)/bumpvects.o \
$(LIB_OBJ_DIR)/color_conversion.o \
$(LIB_OBJ_DIR)/halton.o \
$(LIB_OBJ_DIR)/IceKey.o \
$(LIB_OBJ_DIR)/imagequant.o \
$(LIB_OBJ_DIR)/lightdesc.o \
$(LIB_OBJ_DIR)/mathlib_base.o \
$(LIB_OBJ_DIR)/polyhedron.o \
$(LIB_OBJ_DIR)/powsse.o \
$(LIB_OBJ_DIR)/quantize.o \
$(LIB_OBJ_DIR)/randsse.o \
$(LIB_OBJ_DIR)/simdvectormatrix.o \
$(LIB_OBJ_DIR)/sparse_convolution_noise.o \
$(LIB_OBJ_DIR)/sse.o \
$(LIB_OBJ_DIR)/sseconst.o \
$(LIB_OBJ_DIR)/ssenoise.o \
$(LIB_OBJ_DIR)/vector.o \
$(LIB_OBJ_DIR)/vmatrix.o \
all: dirs $(NAME)_$(ARCH).$(SHLIBEXT)
dirs:
-mkdir -p $(BUILD_OBJ_DIR)
-mkdir -p $(LIB_OBJ_DIR)
$(NAME)_$(ARCH).$(SHLIBEXT): $(LIB_OBJS)
$(AR) $(LIB_DIR)/$@ $(LIB_OBJS)
$(LIB_OBJ_DIR)/%.o: $(LIB_SRC_DIR)/%.cpp
$(DO_CC)
install:
cp -f $(NAME)_$(ARCH).$(SHLIBEXT) $(LIB_DIR)/$(NAME)_$(ARCH).$(SHLIBEXT)
clean:
-rm -rf $(LIB_OBJ_DIR)

View File

@ -1,57 +0,0 @@
#
# Sample server plugin for SRC engine
#
# October 2004, alfred@valvesoftware.com
#
override NAME = serverplugin_empty
PLUGIN_SRC_DIR = $(SRC_DIR)/utils/serverplugin_sample
PUBLIC_SRC_DIR = $(SRC_DIR)/public
TIER0_PUBLIC_SRC_DIR = $(SRC_DIR)/public/tier0
TIER1_PUBLIC_SRC_DIR = $(SRC_DIR)/public/tier1
PLUGIN_OBJ_DIR = $(BUILD_OBJ_DIR)/serverplugin_empty_$(ARCH)
TIER0_OBJ_DIR = $(PLUGIN_OBJ_DIR)/tier0
INCLUDEDIRS = -I$(PUBLIC_SRC_DIR) -I$(TIER0_PUBLIC_SRC_DIR) -I$(TIER1_PUBLIC_SRC_DIR)
LDFLAGS_PLG = -lm -ldl tier0_i486.so vstdlib_i486.so $(LIB_DIR)/mathlib_i486.a $(LIB_DIR)/tier1_i486.a $(LIB_DIR)/tier2_i486.a
DO_CC = $(CPLUS) $(INCLUDEDIRS) -DARCH=$(ARCH)
ifeq "$(DEBUG)" "true"
DO_CC += $(DBG_DEFINES) $(DBG_CFLAGS)
else
DO_CC += -DNDEBUG $(CFLAGS)
endif
DO_CC += -o $@ -c $<
#####################################################################
PLUGIN_OBJS = \
$(PLUGIN_OBJ_DIR)/serverplugin_bot.o \
$(PLUGIN_OBJ_DIR)/serverplugin_empty.o \
TIER0_OBJS = \
$(TIER0_OBJ_DIR)/memoverride.o \
all: dirs $(NAME)_$(ARCH).$(SHLIBEXT)
dirs:
-mkdir -p $(BUILD_OBJ_DIR)
-mkdir -p $(PLUGIN_OBJ_DIR)
-mkdir -p $(TIER0_OBJ_DIR)
$(NAME)_$(ARCH).$(SHLIBEXT): $(PLUGIN_OBJS) $(TIER0_OBJS)
$(CLINK) -o $(BUILD_DIR)/$@ -m32 $(SHLIBLDFLAGS) $(PLUGIN_OBJS) $(TIER0_OBJS) $(PUBLIC_OBJS) $(CPP_LIB) $(LDFLAGS_PLG) $(CPP_LIB)
$(PLUGIN_OBJ_DIR)/%.o: $(PLUGIN_SRC_DIR)/%.cpp
$(DO_CC)
$(TIER0_OBJ_DIR)/%.o: $(TIER0_PUBLIC_SRC_DIR)/%.cpp
$(DO_CC)
clean:
-rm -rf $(PLUGIN_OBJ_DIR)
-rm -f $(NAME)_$(ARCH).$(SHLIBEXT)

View File

@ -1,28 +0,0 @@
#
# wrapper Makefile for auto-generated make files
#
#
#############################################################################
# PROJECT MAKEFILES
#############################################################################
MAKE_FILE = Makefile.$(MOD_CONFIG)
-include $(MAKE_FILE)
#############################################################################
# The compiler command line for each src code file to compile
#############################################################################
DO_CC = $(CPLUS) $(INCLUDES) -DARCH=$(ARCH)
ifeq (_DEBUG,$(findstring _DEBUG,$(CFLAGS)))
DO_CC += $(DEFINES) $(DBG_CFLAGS)
else
DO_CC += $(CFLAGS)
endif
DO_CC += -o $@ -c $<
clean:
rm -rf obj/$(NAME)_$(ARCH)
rm -f $(NAME)_$(ARCH).$(SHLIBEXT)

View File

@ -1,77 +0,0 @@
#
# Tier1 Static Library Makefile
#
override NAME = tier1
LIB_SRC_DIR = $(SRC_DIR)/$(NAME)
PUBLIC_SRC_DIR = $(SRC_DIR)/public
TIER0_PUBLIC_SRC_DIR = $(SRC_DIR)/public/tier0
TIER1_PUBLIC_SRC_DIR = $(SRC_DIR)/public/tier1
LIB_OBJ_DIR=$(BUILD_OBJ_DIR)/$(NAME)_$(ARCH)
# Extension of linux static library
override SHLIBEXT = a
INCLUDEDIRS = -I$(PUBLIC_SRC_DIR) -I$(TIER0_PUBLIC_SRC_DIR) -I$(TIER1_PUBLIC_SRC_DIR) -D_LIB -DTIER1_STATIC_LIB
DO_CC = $(CPLUS) $(INCLUDEDIRS) -DARCH=$(ARCH)
ifeq "$(DEBUG)" "true"
DO_CC += $(DBG_DEFINES) $(DBG_CFLAGS)
else
DO_CC += -DNDEBUG $(CFLAGS)
endif
DO_CC += -o $@ -c $<
#####################################################################
LIB_OBJS= \
$(LIB_OBJ_DIR)/bitbuf.o \
$(LIB_OBJ_DIR)/byteswap.o \
$(LIB_OBJ_DIR)/characterset.o \
$(LIB_OBJ_DIR)/checksum_crc.o \
$(LIB_OBJ_DIR)/checksum_md5.o \
$(LIB_OBJ_DIR)/commandbuffer.o \
$(LIB_OBJ_DIR)/convar.o \
$(LIB_OBJ_DIR)/datamanager.o \
$(LIB_OBJ_DIR)/diff.o \
$(LIB_OBJ_DIR)/generichash.o \
$(LIB_OBJ_DIR)/interface.o \
$(LIB_OBJ_DIR)/KeyValues.o \
$(LIB_OBJ_DIR)/mempool.o \
$(LIB_OBJ_DIR)/NetAdr.o \
$(LIB_OBJ_DIR)/newbitbuf.o \
$(LIB_OBJ_DIR)/processor_detect.o \
$(LIB_OBJ_DIR)/rangecheckedvar.o \
$(LIB_OBJ_DIR)/stringpool.o \
$(LIB_OBJ_DIR)/strtools.o \
$(LIB_OBJ_DIR)/tier1.o \
$(LIB_OBJ_DIR)/tokenreader.o \
$(LIB_OBJ_DIR)/undiff.o \
$(LIB_OBJ_DIR)/uniqueid.o \
$(LIB_OBJ_DIR)/utlbuffer.o \
$(LIB_OBJ_DIR)/utlbufferutil.o \
$(LIB_OBJ_DIR)/utlstring.o \
$(LIB_OBJ_DIR)/utlsymbol.o \
all: dirs $(NAME)_$(ARCH).$(SHLIBEXT)
dirs:
-mkdir -p $(BUILD_OBJ_DIR)
-mkdir -p $(LIB_OBJ_DIR)
$(NAME)_$(ARCH).$(SHLIBEXT): $(LIB_OBJS)
$(AR) $(LIB_DIR)/$@ $(LIB_OBJS)
$(LIB_OBJ_DIR)/%.o: $(LIB_SRC_DIR)/%.cpp
$(DO_CC)
install:
cp -f $(NAME)_$(ARCH).$(SHLIBEXT) $(LIB_DIR)/$(NAME)_$(ARCH).$(SHLIBEXT)
clean:
-rm -rf $(LIB_OBJ_DIR)

View File

@ -1,50 +0,0 @@
#
# VCProject file to Makefile converter
#
# November 2004, alfred@valvesoftware.com
#
VCPM_SRC_DIR = $(SRC_DIR)/utils/vprojtomake
PUBLIC_SRC_DIR = $(SRC_DIR)/public
TIER0_PUBLIC_SRC_DIR = $(SRC_DIR)/public/tier0
TIER1_PUBLIC_SRC_DIR = $(SRC_DIR)/public/tier1
UTIL_COMMON_SRC_DIR = $(SRC_DIR)/utils/common
VCPM_OBJ_DIR = $(BUILD_OBJ_DIR)/vcpm
INCLUDEDIRS = -I$(PUBLIC_SRC_DIR) -I$(XERCES_INC_DIR) -I$(TIER0_PUBLIC_SRC_DIR) -I$(TIER1_PUBLIC_SRC_DIR) -I$(UTIL_COMMON_SRC_DIR)
LDFLAGS_VC = -lm -ldl -L$(XERCES_LIB_DIR) -lxerces-c tier0_i486.so vstdlib_i486.so $(LIB_DIR)/tier1_i486.a
DO_CC = $(CPLUS) $(INCLUDEDIRS) -DARCH=$(ARCH)
ifeq "$(DEBUG)" "true"
DO_CC += $(DBG_DEFINES) $(DBG_CFLAGS)
else
DO_CC += -DNDEBUG $(CFLAGS)
endif
DO_CC += -o $@ -c $<
#####################################################################
VCPM_OBJS = \
$(VCPM_OBJ_DIR)/makefilecreator.o \
$(VCPM_OBJ_DIR)/vprojtomake.o \
$(VCPM_OBJ_DIR)/vcprojconvert.o \
all: dirs vcpm
dirs:
-mkdir -p $(BUILD_OBJ_DIR)
-mkdir -p $(VCPM_OBJ_DIR)
vcpm: $(VCPM_OBJS)
$(CLINK) -m32 -o $(BUILD_DIR)/$@ $(VCPM_OBJS) $(CPP_LIB) $(LDFLAGS_VC)
$(VCPM_OBJ_DIR)/%.o: $(VCPM_SRC_DIR)/%.cpp
$(DO_CC)
clean:
-rm -rf $(VCPM_OBJ_DIR)
-rm -f vcpm

197
mathlib/3dnow.cpp Normal file
View File

@ -0,0 +1,197 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: 3DNow Math primitives.
//
//=====================================================================================//
#include <math.h>
#include <float.h> // Needed for FLT_EPSILON
#include "basetypes.h"
#include <memory.h>
#include "tier0/dbg.h"
#include "mathlib/mathlib.h"
#include "mathlib/amd3dx.h"
#include "mathlib/vector.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#if !defined(COMPILER_MSVC64) && !defined(LINUX)
// Implement for 64-bit Windows if needed.
// Clang hits "fatal error: error in backend:" and other errors when trying
// to compile the inline assembly below. 3DNow support is highly unlikely to
// be useful/used, so it's not worth spending time on fixing.
#pragma warning(disable:4244) // "conversion from 'const int' to 'float', possible loss of data"
#pragma warning(disable:4730) // "mixing _m64 and floating point expressions may result in incorrect code"
//-----------------------------------------------------------------------------
// 3D Now Implementations of optimized routines:
//-----------------------------------------------------------------------------
float _3DNow_Sqrt(float x)
{
Assert( s_bMathlibInitialized );
float root = 0.f;
#ifdef _WIN32
_asm
{
femms
movd mm0, x
PFRSQRT (mm1,mm0)
punpckldq mm0, mm0
PFMUL (mm0, mm1)
movd root, mm0
femms
}
#elif LINUX
__asm __volatile__( "femms" );
__asm __volatile__
(
"pfrsqrt %y0, %y1 \n\t"
"punpckldq %y1, %y1 \n\t"
"pfmul %y1, %y0 \n\t"
: "=y" (root), "=y" (x)
:"0" (x)
);
__asm __volatile__( "femms" );
#else
#error
#endif
return root;
}
// NJS FIXME: Need to test Recripricol squareroot performance and accuraccy
// on AMD's before using the specialized instruction.
float _3DNow_RSqrt(float x)
{
Assert( s_bMathlibInitialized );
return 1.f / _3DNow_Sqrt(x);
}
float FASTCALL _3DNow_VectorNormalize (Vector& vec)
{
Assert( s_bMathlibInitialized );
float *v = &vec[0];
float radius = 0.f;
if ( v[0] || v[1] || v[2] )
{
#ifdef _WIN32
_asm
{
mov eax, v
femms
movq mm0, QWORD PTR [eax]
movd mm1, DWORD PTR [eax+8]
movq mm2, mm0
movq mm3, mm1
PFMUL (mm0, mm0)
PFMUL (mm1, mm1)
PFACC (mm0, mm0)
PFADD (mm1, mm0)
PFRSQRT (mm0, mm1)
punpckldq mm1, mm1
PFMUL (mm1, mm0)
PFMUL (mm2, mm0)
PFMUL (mm3, mm0)
movq QWORD PTR [eax], mm2
movd DWORD PTR [eax+8], mm3
movd radius, mm1
femms
}
#elif LINUX
long long a,c;
int b,d;
memcpy(&a,&vec[0],sizeof(a));
memcpy(&b,&vec[2],sizeof(b));
memcpy(&c,&vec[0],sizeof(c));
memcpy(&d,&vec[2],sizeof(d));
__asm __volatile__( "femms" );
__asm __volatile__
(
"pfmul %y3, %y3\n\t"
"pfmul %y0, %y0 \n\t"
"pfacc %y3, %y3 \n\t"
"pfadd %y3, %y0 \n\t"
"pfrsqrt %y0, %y3 \n\t"
"punpckldq %y0, %y0 \n\t"
"pfmul %y3, %y0 \n\t"
"pfmul %y3, %y2 \n\t"
"pfmul %y3, %y1 \n\t"
: "=y" (radius), "=y" (c), "=y" (d)
: "y" (a), "0" (b), "1" (c), "2" (d)
);
memcpy(&vec[0],&c,sizeof(c));
memcpy(&vec[2],&d,sizeof(d));
__asm __volatile__( "femms" );
#else
#error
#endif
}
return radius;
}
void FASTCALL _3DNow_VectorNormalizeFast (Vector& vec)
{
_3DNow_VectorNormalize( vec );
}
// JAY: This complains with the latest processor pack
#pragma warning(disable: 4730)
float _3DNow_InvRSquared(const float* v)
{
Assert( s_bMathlibInitialized );
float r2 = 1.f;
#ifdef _WIN32
_asm { // AMD 3DNow only routine
mov eax, v
femms
movq mm0, QWORD PTR [eax]
movd mm1, DWORD PTR [eax+8]
movd mm2, [r2]
PFMUL (mm0, mm0)
PFMUL (mm1, mm1)
PFACC (mm0, mm0)
PFADD (mm1, mm0)
PFMAX (mm1, mm2)
PFRCP (mm0, mm1)
movd [r2], mm0
femms
}
#elif LINUX
long long a,c;
int b;
memcpy(&a,&v[0],sizeof(a));
memcpy(&b,&v[2],sizeof(b));
memcpy(&c,&v[0],sizeof(c));
__asm __volatile__( "femms" );
__asm __volatile__
(
"PFMUL %y2, %y2 \n\t"
"PFMUL %y3, %y3 \n\t"
"PFACC %y2, %y2 \n\t"
"PFADD %y2, %y3 \n\t"
"PFMAX %y3, %y4 \n\t"
"PFRCP %y3, %y2 \n\t"
"movq %y2, %y0 \n\t"
: "=y" (r2)
: "0" (r2), "y" (a), "y" (b), "y" (c)
);
__asm __volatile__( "femms" );
#else
#error
#endif
return r2;
}
#endif // COMPILER_MSVC64

16
mathlib/3dnow.h Normal file
View File

@ -0,0 +1,16 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=====================================================================================//
#ifndef _3DNOW_H
#define _3DNOW_H
float _3DNow_Sqrt(float x);
float _3DNow_RSqrt(float x);
float FASTCALL _3DNow_VectorNormalize (Vector& vec);
void FASTCALL _3DNow_VectorNormalizeFast (Vector& vec);
float _3DNow_InvRSquared(const float* v);
#endif // _3DNOW_H

48
mathlib/AMBuilder Normal file
View File

@ -0,0 +1,48 @@
# vim: set ts=2 sw=2 tw=99 noet ft=python:
import os, sys
def AddSourceFilesFromDir(path, files):
list = []
for file in files:
list.append(os.path.join(path, file))
return list
builder.SetBuildFolder('/')
project = builder.StaticLibraryProject('mathlib')
project.sources = [
'3dnow.cpp',
'almostequal.cpp',
'anorms.cpp',
'bumpvects.cpp',
'color_conversion.cpp',
'halton.cpp',
'IceKey.cpp',
'imagequant.cpp',
'lightdesc.cpp',
'mathlib_base.cpp',
'polyhedron.cpp',
'powsse.cpp',
'quantize.cpp',
'randsse.cpp',
'simdvectormatrix.cpp',
'sparse_convolution_noise.cpp',
'spherical.cpp',
'sse.cpp',
'sseconst.cpp',
'ssenoise.cpp',
'vector.cpp',
'vmatrix.cpp',
]
for cxx in HL2SDK.targets:
binary = HL2SDK.ConfigureLibrary(project, cxx, builder)
compiler = binary.compiler
compiler.cxxincludes += [
os.path.join(builder.currentSourcePath, '..', 'public'),
os.path.join(builder.currentSourcePath, '..', 'public', 'tier0'),
os.path.join(builder.currentSourcePath, '..', 'public', 'mathlib')
]
HL2SDK.libs += builder.Add(project)

View File

@ -5,6 +5,9 @@
#if !defined(_STATIC_LINKED) || defined(_SHARED_LIB)
#include "mathlib/IceKey.H"
#include <cstdint>
#include "tier0/memdbgon.h"
#ifdef _MSC_VER
#pragma warning(disable: 4244)
@ -13,12 +16,12 @@
/* Structure of a single round subkey */
class IceSubkey {
public:
unsigned long val[3];
uint32_t val[3];
};
/* The S-boxes */
static unsigned long ice_sbox[4][1024];
static uint32_t ice_sbox[4][1024];
static int ice_sboxes_initialised = 0;
@ -37,7 +40,7 @@ static const int ice_sxor[4][4] = {
{0xea, 0xcb, 0x2e, 0x04}};
/* Permutation values for the P-box */
static const unsigned long ice_pbox[32] = {
static const uint32_t ice_pbox[32] = {
0x00000001, 0x00000080, 0x00000400, 0x00002000,
0x00080000, 0x00200000, 0x01000000, 0x40000000,
0x00000008, 0x00000020, 0x00000100, 0x00004000,
@ -61,11 +64,11 @@ static const int ice_keyrot[16] = {
static unsigned int
gf_mult (
register unsigned int a,
register unsigned int b,
register unsigned int m
unsigned int a,
unsigned int b,
unsigned int m
) {
register unsigned int res = 0;
unsigned int res = 0;
while (b) {
if (b & 1)
@ -87,12 +90,12 @@ gf_mult (
* Raise the base to the power of 7, modulo m.
*/
static unsigned long
static uint32_t
gf_exp7 (
register unsigned int b,
unsigned int b,
unsigned int m
) {
register unsigned int x;
unsigned int x;
if (b == 0)
return (0);
@ -108,12 +111,12 @@ gf_exp7 (
* Carry out the ICE 32-bit P-box permutation.
*/
static unsigned long
static uint32_t
ice_perm32 (
register unsigned long x
uint32_t x
) {
register unsigned long res = 0;
register const unsigned long *pbox = ice_pbox;
uint32_t res = 0;
const uint32_t *pbox = ice_pbox;
while (x) {
if (x & 1)
@ -134,12 +137,12 @@ ice_perm32 (
static void
ice_sboxes_init (void)
{
register int i;
int i;
for (i=0; i<1024; i++) {
int col = (i >> 1) & 0xff;
int row = (i & 0x1) | ((i & 0x200) >> 8);
unsigned long x;
uint32_t x;
x = gf_exp7 (col ^ ice_sxor[0][row], ice_smod[0][row]) << 24;
ice_sbox[0][i] = ice_perm32 (x);
@ -201,13 +204,13 @@ IceKey::~IceKey ()
* The single round ICE f function.
*/
static unsigned long
static uint32_t
ice_f (
register unsigned long p,
uint32_t p,
const IceSubkey *sk
) {
unsigned long tl, tr; /* Expanded 40-bit values */
unsigned long al, ar; /* Salted expanded 40-bit values */
uint32_t tl, tr; /* Expanded 40-bit values */
uint32_t al, ar; /* Salted expanded 40-bit values */
/* Left half expansion */
tl = ((p >> 16) & 0x3ff) | (((p >> 14) | (p << 18)) & 0xffc00);
@ -241,15 +244,15 @@ IceKey::encrypt (
unsigned char *ctext
) const
{
register int i;
register unsigned long l, r;
int i;
uint32_t l, r;
l = (((unsigned long) ptext[0]) << 24)
| (((unsigned long) ptext[1]) << 16)
| (((unsigned long) ptext[2]) << 8) | ptext[3];
r = (((unsigned long) ptext[4]) << 24)
| (((unsigned long) ptext[5]) << 16)
| (((unsigned long) ptext[6]) << 8) | ptext[7];
l = (((uint32_t) ptext[0]) << 24)
| (((uint32_t) ptext[1]) << 16)
| (((uint32_t) ptext[2]) << 8) | ptext[3];
r = (((uint32_t) ptext[4]) << 24)
| (((uint32_t) ptext[5]) << 16)
| (((uint32_t) ptext[6]) << 8) | ptext[7];
for (i = 0; i < _rounds; i += 2) {
l ^= ice_f (r, &_keysched[i]);
@ -276,15 +279,15 @@ IceKey::decrypt (
unsigned char *ptext
) const
{
register int i;
register unsigned long l, r;
int i;
uint32_t l, r;
l = (((unsigned long) ctext[0]) << 24)
| (((unsigned long) ctext[1]) << 16)
| (((unsigned long) ctext[2]) << 8) | ctext[3];
r = (((unsigned long) ctext[4]) << 24)
| (((unsigned long) ctext[5]) << 16)
| (((unsigned long) ctext[6]) << 8) | ctext[7];
l = (((uint32_t) ctext[0]) << 24)
| (((uint32_t) ctext[1]) << 16)
| (((uint32_t) ctext[2]) << 8) | ctext[3];
r = (((uint32_t) ctext[4]) << 24)
| (((uint32_t) ctext[5]) << 16)
| (((uint32_t) ctext[6]) << 8) | ctext[7];
for (i = _rounds - 1; i > 0; i -= 2) {
l ^= ice_f (r, &_keysched[i]);
@ -314,20 +317,20 @@ IceKey::scheduleBuild (
int i;
for (i=0; i<8; i++) {
register int j;
register int kr = keyrot[i];
int j;
int kr = keyrot[i];
IceSubkey *isk = &_keysched[n + i];
for (j=0; j<3; j++)
isk->val[j] = 0;
for (j=0; j<15; j++) {
register int k;
unsigned long *curr_sk = &isk->val[j % 3];
int k;
uint32_t *curr_sk = &isk->val[j % 3];
for (k=0; k<4; k++) {
unsigned short *curr_kb = &kb[(kr + k) & 3];
register int bit = *curr_kb & 1;
int bit = *curr_kb & 1;
*curr_sk = (*curr_sk << 1) | bit;
*curr_kb = (*curr_kb >> 1) | ((bit ^ 1) << 15);

97
mathlib/almostequal.cpp Normal file
View File

@ -0,0 +1,97 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Fast ways to compare equality of two floats. Assumes
// sizeof(float) == sizeof(int) and we are using IEEE format.
//
// Source: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
//=====================================================================================//
#include <float.h>
#include <math.h>
#include "mathlib/mathlib.h"
static inline bool AE_IsInfinite(float a)
{
const int kInfAsInt = 0x7F800000;
// An infinity has an exponent of 255 (shift left 23 positions) and
// a zero mantissa. There are two infinities - positive and negative.
if ((*(int*)&a & 0x7FFFFFFF) == kInfAsInt)
return true;
return false;
}
static inline bool AE_IsNan(float a)
{
// a NAN has an exponent of 255 (shifted left 23 positions) and
// a non-zero mantissa.
int exp = *(int*)&a & 0x7F800000;
int mantissa = *(int*)&a & 0x007FFFFF;
if (exp == 0x7F800000 && mantissa != 0)
return true;
return false;
}
static inline int AE_Sign(float a)
{
// The sign bit of a number is the high bit.
return (*(int*)&a) & 0x80000000;
}
// This is the 'final' version of the AlmostEqualUlps function.
// The optional checks are included for completeness, but in many
// cases they are not necessary, or even not desirable.
bool AlmostEqual(float a, float b, int maxUlps)
{
// There are several optional checks that you can do, depending
// on what behavior you want from your floating point comparisons.
// These checks should not be necessary and they are included
// mainly for completeness.
// If a or b are infinity (positive or negative) then
// only return true if they are exactly equal to each other -
// that is, if they are both infinities of the same sign.
// This check is only needed if you will be generating
// infinities and you don't want them 'close' to numbers
// near FLT_MAX.
if (AE_IsInfinite(a) || AE_IsInfinite(b))
return a == b;
// If a or b are a NAN, return false. NANs are equal to nothing,
// not even themselves.
// This check is only needed if you will be generating NANs
// and you use a maxUlps greater than 4 million or you want to
// ensure that a NAN does not equal itself.
if (AE_IsNan(a) || AE_IsNan(b))
return false;
// After adjusting floats so their representations are lexicographically
// ordered as twos-complement integers a very small positive number
// will compare as 'close' to a very small negative number. If this is
// not desireable, and if you are on a platform that supports
// subnormals (which is the only place the problem can show up) then
// you need this check.
// The check for a == b is because zero and negative zero have different
// signs but are equal to each other.
if (AE_Sign(a) != AE_Sign(b))
return a == b;
int aInt = *(int*)&a;
// Make aInt lexicographically ordered as a twos-complement int
if (aInt < 0)
aInt = 0x80000000 - aInt;
// Make bInt lexicographically ordered as a twos-complement int
int bInt = *(int*)&b;
if (bInt < 0)
bInt = 0x80000000 - bInt;
// Now we can compare aInt and bInt to find out how far apart a and b
// are.
int intDiff = abs(aInt - bInt);
if (intDiff <= maxUlps)
return true;
return false;
}

View File

@ -106,27 +106,23 @@ ALIGN128 float power2_n[256] = // 2**(index - 128) / 255
// You can use this to double check the exponent table and assert that
// the precomputation is correct.
#ifdef DBGFLAG_ASSERT
#ifdef _MSC_VER
#ifdef _WIN32
#pragma warning(push)
#pragma warning( disable : 4189 ) // disable unused local variable warning
#endif
#ifdef __GNUC__
__attribute__((unused)) static void CheckExponentTable()
#else
static void CheckExponentTable()
#endif
{
for( int i = 0; i < 256; i++ )
{
float testAgainst = pow( 2.0f, i - 128 ) / 255.0f;
float diff = testAgainst - power2_n[i] ;
float relativeDiff = diff / testAgainst;
Assert( sizeof(relativeDiff) > 0 && testAgainst == 0 ?
Assert( testAgainst == 0 ?
power2_n[i] < 1.16E-041 :
power2_n[i] == testAgainst );
}
}
#ifdef _MSC_VER
#ifdef _WIN32
#pragma warning(pop)
#endif
#endif
@ -617,10 +613,10 @@ void VectorToColorRGBExp32( const Vector& vin, ColorRGBExp32 &c )
scalar = *reinterpret_cast<float *>(&fbits);
}
// we should never need to clamp:
Assert(vin.x * scalar <= 255.0f &&
vin.y * scalar <= 255.0f &&
vin.z * scalar <= 255.0f);
// We can totally wind up above 255 and that's okay--but above 256 would be right out.
Assert(vin.x * scalar < 256.0f &&
vin.y * scalar < 256.0f &&
vin.z * scalar < 256.0f);
// This awful construction is necessary to prevent VC2005 from using the
// fldcw/fnstcw control words around every float-to-unsigned-char operation.

View File

@ -6,7 +6,7 @@
//
//=============================================================================//
#include <quantize.h>
#include <tier0/basetypes.h>
#include <minmax.h>
#define N_EXTRAVALUES 1
#define N_DIMENSIONS (3+N_EXTRAVALUES)
@ -46,7 +46,7 @@ void ColorQuantize(uint8 const *Image,
val1+=PIXEL(x,y,c)*ExtraValueXForms[i*3+c];
val1>>=8;
NthSample(s,y*Width+x,N_DIMENSIONS)->Value[c]=(uint8)
(MIN(255,MAX(0,val1)));
(V_min(255,V_max(0,val1)));
}
}
struct QuantizedValue *q=Quantize(s,Width*Height,N_DIMENSIONS,
@ -76,7 +76,7 @@ void ColorQuantize(uint8 const *Image,
tryc+=Error[x][c][ErrorUse];
Error[x][c][ErrorUse]=0;
}
samp[c]=(uint8) MIN(255,MAX(0,tryc));
samp[c]=(uint8) V_min(255,V_max(0,tryc));
}
struct QuantizedValue *f=FindMatch(samp,3,Weights,q);
out_pixels[Width*y+x]=(uint8) (f->value);

View File

@ -10,7 +10,7 @@
void LightDesc_t::RecalculateDerivedValues(void)
{
m_Flags=0;
m_Flags = LIGHTTYPE_OPTIMIZATIONFLAGS_DERIVED_VALUES_CALCED;
if (m_Attenuation0)
m_Flags|=LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION0;
if (m_Attenuation1)

View File

@ -1,399 +0,0 @@
<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="8.00"
Name="mathlib"
ProjectGUID="{884C66F2-7F84-4570-AE6C-B634C1113D69}"
RootNamespace="mathlib"
>
<Platforms>
<Platform
Name="Win32"
/>
</Platforms>
<ToolFiles>
</ToolFiles>
<Configurations>
<Configuration
Name="Debug|Win32"
OutputDirectory=".\Debug"
IntermediateDirectory=".\Debug"
ConfigurationType="4"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
CommandLine=""
ExcludedFromBuild="false"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
UseUnicodeResponseFiles="false"
Optimization="0"
AdditionalIncludeDirectories="..\public;..\public\tier0;..\public\tier1;..\public\mathlib"
PreprocessorDefinitions="WIN32;_WIN32;_DEBUG;DEBUG;_LIB;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE"
StringPooling="true"
MinimalRebuild="true"
ExceptionHandling="0"
BasicRuntimeChecks="3"
RuntimeLibrary="1"
BufferSecurityCheck="false"
FloatingPointModel="2"
TreatWChar_tAsBuiltInType="true"
ForceConformanceInForLoopScope="true"
RuntimeTypeInfo="true"
OpenMP="false"
UsePrecompiledHeader="0"
ExpandAttributedSource="false"
AssemblerOutput="0"
AssemblerListingLocation="$(IntDir)/"
ObjectFile="$(IntDir)/"
ProgramDataBaseFileName="$(IntDir)/"
GenerateXMLDocumentationFiles="false"
BrowseInformation="0"
BrowseInformationFile="$(IntDir)/"
WarningLevel="4"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="4"
CompileAs="2"
ErrorReporting="1"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
CommandLine=""
ExcludedFromBuild="false"
/>
<Tool
Name="VCLibrarianTool"
UseUnicodeResponseFiles="false"
OutputFile="..\lib\public\mathlib.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
SuppressStartupBanner="true"
/>
<Tool
Name="VCBscMakeTool"
SuppressStartupBanner="true"
OutputFile="$(OutDir)/mathlib.bsc"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
ExcludedFromBuild="false"
/>
</Configuration>
<Configuration
Name="Release|Win32"
OutputDirectory=".\Release"
IntermediateDirectory=".\Release"
ConfigurationType="4"
CharacterSet="2"
>
<Tool
Name="VCPreBuildEventTool"
CommandLine=""
ExcludedFromBuild="false"
/>
<Tool
Name="VCCustomBuildTool"
/>
<Tool
Name="VCXMLDataGeneratorTool"
/>
<Tool
Name="VCWebServiceProxyGeneratorTool"
/>
<Tool
Name="VCMIDLTool"
/>
<Tool
Name="VCCLCompilerTool"
UseUnicodeResponseFiles="false"
Optimization="2"
InlineFunctionExpansion="2"
EnableIntrinsicFunctions="true"
FavorSizeOrSpeed="1"
AdditionalIncludeDirectories="..\public;..\public\tier0;..\public\tier1;..\public\mathlib"
PreprocessorDefinitions="WIN32;_WIN32;NDEBUG;_LIB;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE"
StringPooling="true"
ExceptionHandling="0"
RuntimeLibrary="0"
BufferSecurityCheck="false"
EnableFunctionLevelLinking="true"
FloatingPointModel="2"
TreatWChar_tAsBuiltInType="true"
ForceConformanceInForLoopScope="true"
RuntimeTypeInfo="true"
OpenMP="false"
UsePrecompiledHeader="0"
ExpandAttributedSource="false"
AssemblerOutput="0"
AssemblerListingLocation="$(IntDir)/"
ObjectFile="$(IntDir)/"
ProgramDataBaseFileName="$(IntDir)/"
GenerateXMLDocumentationFiles="false"
BrowseInformation="0"
BrowseInformationFile="$(IntDir)/"
WarningLevel="4"
Detect64BitPortabilityProblems="true"
DebugInformationFormat="1"
CompileAs="2"
ErrorReporting="1"
/>
<Tool
Name="VCManagedResourceCompilerTool"
/>
<Tool
Name="VCResourceCompilerTool"
/>
<Tool
Name="VCPreLinkEventTool"
CommandLine=""
ExcludedFromBuild="false"
/>
<Tool
Name="VCLibrarianTool"
UseUnicodeResponseFiles="false"
OutputFile="..\lib\public\mathlib.lib"
SuppressStartupBanner="true"
/>
<Tool
Name="VCALinkTool"
/>
<Tool
Name="VCXDCMakeTool"
SuppressStartupBanner="true"
/>
<Tool
Name="VCBscMakeTool"
SuppressStartupBanner="true"
OutputFile="$(OutDir)/mathlib.bsc"
/>
<Tool
Name="VCFxCopTool"
/>
<Tool
Name="VCPostBuildEventTool"
ExcludedFromBuild="false"
/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Source Files"
Filter="cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
>
<File
RelativePath=".\anorms.cpp"
>
</File>
<File
RelativePath=".\bumpvects.cpp"
>
</File>
<File
RelativePath=".\color_conversion.cpp"
>
</File>
<File
RelativePath=".\halton.cpp"
>
</File>
<File
RelativePath=".\IceKey.cpp"
>
</File>
<File
RelativePath=".\imagequant.cpp"
>
</File>
<File
RelativePath=".\lightdesc.cpp"
>
</File>
<File
RelativePath=".\mathlib_base.cpp"
>
</File>
<File
RelativePath=".\polyhedron.cpp"
>
</File>
<File
RelativePath=".\powsse.cpp"
>
</File>
<File
RelativePath=".\quantize.cpp"
>
</File>
<File
RelativePath=".\randsse.cpp"
>
</File>
<File
RelativePath=".\simdvectormatrix.cpp"
>
</File>
<File
RelativePath=".\sparse_convolution_noise.cpp"
>
</File>
<File
RelativePath=".\sse.cpp"
>
</File>
<File
RelativePath=".\sseconst.cpp"
>
</File>
<File
RelativePath=".\ssenoise.cpp"
>
</File>
<File
RelativePath=".\vector.cpp"
>
</File>
<File
RelativePath=".\vmatrix.cpp"
>
</File>
</Filter>
<Filter
Name="Public Header Files"
Filter="h"
>
<File
RelativePath="..\public\mathlib\amd3dx.h"
>
</File>
<File
RelativePath="..\public\mathlib\anorms.h"
>
</File>
<File
RelativePath="..\public\mathlib\bumpvects.h"
>
</File>
<File
RelativePath="..\public\mathlib\compressed_3d_unitvec.h"
>
</File>
<File
RelativePath="..\public\mathlib\compressed_light_cube.h"
>
</File>
<File
RelativePath="..\public\mathlib\compressed_vector.h"
>
</File>
<File
RelativePath="..\public\mathlib\halton.h"
>
</File>
<File
RelativePath="..\public\mathlib\IceKey.H"
>
</File>
<File
RelativePath="..\public\mathlib\lightdesc.h"
>
</File>
<File
RelativePath="..\public\mathlib\math_pfns.h"
>
</File>
<File
RelativePath="..\public\mathlib\mathlib.h"
>
</File>
<File
RelativePath="..\public\mathlib\noise.h"
>
</File>
<File
RelativePath="..\public\mathlib\polyhedron.h"
>
</File>
<File
RelativePath="..\public\mathlib\quantize.h"
>
</File>
<File
RelativePath="..\public\mathlib\simdvectormatrix.h"
>
</File>
<File
RelativePath="..\public\mathlib\ssemath.h"
>
</File>
<File
RelativePath="..\public\mathlib\ssequaternion.h"
>
</File>
<File
RelativePath="..\public\mathlib\vector.h"
>
</File>
<File
RelativePath="..\public\mathlib\vector2d.h"
>
</File>
<File
RelativePath="..\public\mathlib\vector4d.h"
>
</File>
<File
RelativePath="..\public\mathlib\vmatrix.h"
>
</File>
<File
RelativePath="..\public\mathlib\vplane.h"
>
</File>
</Filter>
<Filter
Name="Header Files"
Filter="h;hpp;hxx;hm;inl"
>
<File
RelativePath=".\noisedata.h"
>
</File>
<File
RelativePath=".\sse.h"
>
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@ -1,4 +1,4 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//===== Copyright <EFBFBD> 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose: Math primitives.
//
@ -6,6 +6,7 @@
/// FIXME: As soon as all references to mathlib.c are gone, include it in here
#include <algorithm>
#include <math.h>
#include <float.h> // Needed for FLT_EPSILON
@ -16,7 +17,7 @@
#include "tier0/vprof.h"
//#define _VPROF_MATHLIB
#ifdef _MSC_VER
#ifdef _WIN32
#pragma warning(disable:4244) // "conversion from 'const int' to 'float', possible loss of data"
#pragma warning(disable:4730) // "mixing _m64 and floating point expressions may result in incorrect code"
#endif
@ -24,6 +25,10 @@
#include "mathlib/mathlib.h"
#include "mathlib/vector.h"
#if !defined( _X360 )
#include "mathlib/amd3dx.h"
#ifndef OSX
#include "3dnow.h"
#endif
#include "sse.h"
#endif
@ -425,6 +430,33 @@ void MatrixSetColumn( const Vector &in, int column, matrix3x4_t& out )
out[2][column] = in.z;
}
void MatrixScaleBy ( const float flScale, matrix3x4_t &out )
{
out[0][0] *= flScale;
out[1][0] *= flScale;
out[2][0] *= flScale;
out[0][1] *= flScale;
out[1][1] *= flScale;
out[2][1] *= flScale;
out[0][2] *= flScale;
out[1][2] *= flScale;
out[2][2] *= flScale;
}
void MatrixScaleByZero ( matrix3x4_t &out )
{
out[0][0] = 0.0f;
out[1][0] = 0.0f;
out[2][0] = 0.0f;
out[0][1] = 0.0f;
out[1][1] = 0.0f;
out[2][1] = 0.0f;
out[0][2] = 0.0f;
out[1][2] = 0.0f;
out[2][2] = 0.0f;
}
int VectorCompare (const float *v1, const float *v2)
{
@ -564,53 +596,128 @@ void ConcatRotations (const float in1[3][3], const float in2[3][3], float out[3]
in1[2][2] * in2[2][2];
}
void ConcatTransforms_Aligned( const matrix3x4_t &m0, const matrix3x4_t &m1, matrix3x4_t &out )
{
Assert( (((size_t)&m0) % 16) == 0 );
Assert( (((size_t)&m1) % 16) == 0 );
Assert( (((size_t)&out) % 16) == 0 );
fltx4 lastMask = *(fltx4 *)(&g_SIMD_ComponentMask[3]);
fltx4 rowA0 = LoadAlignedSIMD( m0.m_flMatVal[0] );
fltx4 rowA1 = LoadAlignedSIMD( m0.m_flMatVal[1] );
fltx4 rowA2 = LoadAlignedSIMD( m0.m_flMatVal[2] );
fltx4 rowB0 = LoadAlignedSIMD( m1.m_flMatVal[0] );
fltx4 rowB1 = LoadAlignedSIMD( m1.m_flMatVal[1] );
fltx4 rowB2 = LoadAlignedSIMD( m1.m_flMatVal[2] );
// now we have the rows of m0 and the columns of m1
// first output row
fltx4 A0 = SplatXSIMD(rowA0);
fltx4 A1 = SplatYSIMD(rowA0);
fltx4 A2 = SplatZSIMD(rowA0);
fltx4 mul00 = MulSIMD( A0, rowB0 );
fltx4 mul01 = MulSIMD( A1, rowB1 );
fltx4 mul02 = MulSIMD( A2, rowB2 );
fltx4 out0 = AddSIMD( mul00, AddSIMD(mul01,mul02) );
// second output row
A0 = SplatXSIMD(rowA1);
A1 = SplatYSIMD(rowA1);
A2 = SplatZSIMD(rowA1);
fltx4 mul10 = MulSIMD( A0, rowB0 );
fltx4 mul11 = MulSIMD( A1, rowB1 );
fltx4 mul12 = MulSIMD( A2, rowB2 );
fltx4 out1 = AddSIMD( mul10, AddSIMD(mul11,mul12) );
// third output row
A0 = SplatXSIMD(rowA2);
A1 = SplatYSIMD(rowA2);
A2 = SplatZSIMD(rowA2);
fltx4 mul20 = MulSIMD( A0, rowB0 );
fltx4 mul21 = MulSIMD( A1, rowB1 );
fltx4 mul22 = MulSIMD( A2, rowB2 );
fltx4 out2 = AddSIMD( mul20, AddSIMD(mul21,mul22) );
// add in translation vector
A0 = AndSIMD(rowA0,lastMask);
A1 = AndSIMD(rowA1,lastMask);
A2 = AndSIMD(rowA2,lastMask);
out0 = AddSIMD(out0, A0);
out1 = AddSIMD(out1, A1);
out2 = AddSIMD(out2, A2);
StoreAlignedSIMD( out.m_flMatVal[0], out0 );
StoreAlignedSIMD( out.m_flMatVal[1], out1 );
StoreAlignedSIMD( out.m_flMatVal[2], out2 );
}
/*
================
R_ConcatTransforms
================
*/
void ConcatTransforms (const matrix3x4_t& in1, const matrix3x4_t& in2, matrix3x4_t& out)
{
Assert( s_bMathlibInitialized );
if ( &in1 == &out )
#if 0
// test for ones that'll be 2x faster
if ( (((size_t)&in1) % 16) == 0 && (((size_t)&in2) % 16) == 0 && (((size_t)&out) % 16) == 0 )
{
matrix3x4_t in1b;
MatrixCopy( in1, in1b );
ConcatTransforms( in1b, in2, out );
ConcatTransforms_Aligned( in1, in2, out );
return;
}
if ( &in2 == &out )
{
matrix3x4_t in2b;
MatrixCopy( in2, in2b );
ConcatTransforms( in1, in2b, out );
return;
}
out[0][0] = in1[0][0] * in2[0][0] + in1[0][1] * in2[1][0] +
in1[0][2] * in2[2][0];
out[0][1] = in1[0][0] * in2[0][1] + in1[0][1] * in2[1][1] +
in1[0][2] * in2[2][1];
out[0][2] = in1[0][0] * in2[0][2] + in1[0][1] * in2[1][2] +
in1[0][2] * in2[2][2];
out[0][3] = in1[0][0] * in2[0][3] + in1[0][1] * in2[1][3] +
in1[0][2] * in2[2][3] + in1[0][3];
out[1][0] = in1[1][0] * in2[0][0] + in1[1][1] * in2[1][0] +
in1[1][2] * in2[2][0];
out[1][1] = in1[1][0] * in2[0][1] + in1[1][1] * in2[1][1] +
in1[1][2] * in2[2][1];
out[1][2] = in1[1][0] * in2[0][2] + in1[1][1] * in2[1][2] +
in1[1][2] * in2[2][2];
out[1][3] = in1[1][0] * in2[0][3] + in1[1][1] * in2[1][3] +
in1[1][2] * in2[2][3] + in1[1][3];
out[2][0] = in1[2][0] * in2[0][0] + in1[2][1] * in2[1][0] +
in1[2][2] * in2[2][0];
out[2][1] = in1[2][0] * in2[0][1] + in1[2][1] * in2[1][1] +
in1[2][2] * in2[2][1];
out[2][2] = in1[2][0] * in2[0][2] + in1[2][1] * in2[1][2] +
in1[2][2] * in2[2][2];
out[2][3] = in1[2][0] * in2[0][3] + in1[2][1] * in2[1][3] +
in1[2][2] * in2[2][3] + in1[2][3];
#endif
fltx4 lastMask = *(fltx4 *)(&g_SIMD_ComponentMask[3]);
fltx4 rowA0 = LoadUnalignedSIMD( in1.m_flMatVal[0] );
fltx4 rowA1 = LoadUnalignedSIMD( in1.m_flMatVal[1] );
fltx4 rowA2 = LoadUnalignedSIMD( in1.m_flMatVal[2] );
fltx4 rowB0 = LoadUnalignedSIMD( in2.m_flMatVal[0] );
fltx4 rowB1 = LoadUnalignedSIMD( in2.m_flMatVal[1] );
fltx4 rowB2 = LoadUnalignedSIMD( in2.m_flMatVal[2] );
// now we have the rows of m0 and the columns of m1
// first output row
fltx4 A0 = SplatXSIMD(rowA0);
fltx4 A1 = SplatYSIMD(rowA0);
fltx4 A2 = SplatZSIMD(rowA0);
fltx4 mul00 = MulSIMD( A0, rowB0 );
fltx4 mul01 = MulSIMD( A1, rowB1 );
fltx4 mul02 = MulSIMD( A2, rowB2 );
fltx4 out0 = AddSIMD( mul00, AddSIMD(mul01,mul02) );
// second output row
A0 = SplatXSIMD(rowA1);
A1 = SplatYSIMD(rowA1);
A2 = SplatZSIMD(rowA1);
fltx4 mul10 = MulSIMD( A0, rowB0 );
fltx4 mul11 = MulSIMD( A1, rowB1 );
fltx4 mul12 = MulSIMD( A2, rowB2 );
fltx4 out1 = AddSIMD( mul10, AddSIMD(mul11,mul12) );
// third output row
A0 = SplatXSIMD(rowA2);
A1 = SplatYSIMD(rowA2);
A2 = SplatZSIMD(rowA2);
fltx4 mul20 = MulSIMD( A0, rowB0 );
fltx4 mul21 = MulSIMD( A1, rowB1 );
fltx4 mul22 = MulSIMD( A2, rowB2 );
fltx4 out2 = AddSIMD( mul20, AddSIMD(mul21,mul22) );
// add in translation vector
A0 = AndSIMD(rowA0,lastMask);
A1 = AndSIMD(rowA1,lastMask);
A2 = AndSIMD(rowA2,lastMask);
out0 = AddSIMD(out0, A0);
out1 = AddSIMD(out1, A1);
out2 = AddSIMD(out2, A2);
// write to output
StoreUnalignedSIMD( out.m_flMatVal[0], out0 );
StoreUnalignedSIMD( out.m_flMatVal[1], out1 );
StoreUnalignedSIMD( out.m_flMatVal[2], out2 );
}
@ -1357,7 +1464,9 @@ float Bias( float x, float biasAmt )
{
lastExponent = log( biasAmt ) * -1.4427f; // (-1.4427 = 1 / log(0.5))
}
return pow( x, lastExponent );
float fRet = pow( x, lastExponent );
Assert ( !IS_NAN( fRet ) );
return fRet;
}
@ -1373,7 +1482,9 @@ float Gain( float x, float biasAmt )
float SmoothCurve( float x )
{
return (1 - cos( x * M_PI )) * 0.5f;
// Actual smooth curve. Visualization:
// http://www.wolframalpha.com/input/?i=plot%5B+0.5+*+%281+-+cos%5B2+*+pi+*+x%5D%29+for+x+%3D+%280%2C+1%29+%5D
return 0.5f * (1 - cos( 2.0f * M_PI * x ) );
}
@ -1565,7 +1676,9 @@ float QuaternionAngleDiff( const Quaternion &p, const Quaternion &q )
QuaternionConjugate( q, qInv );
QuaternionMult( p, qInv, diff );
float sinang = sqrt( diff.x * diff.x + diff.y * diff.y + diff.z * diff.z );
// Note if the quaternion is slightly non-normalized the square root below may be more than 1,
// the value is clamped to one otherwise it may result in asin() returning an undefined result.
float sinang = MIN( 1.0f, sqrt( diff.x * diff.x + diff.y * diff.y + diff.z * diff.z ) );
float angle = RAD2DEG( 2 * asin( sinang ) );
return angle;
#else
@ -1665,7 +1778,7 @@ void QuaternionScale( const Quaternion &p, float t, Quaternion &q )
// FIXME: nick, this isn't overly sensitive to accuracy, and it may be faster to
// use the cos part (w) of the quaternion (sin(omega)*N,cos(omega)) to figure the new scale.
float sinom = sqrt( DotProduct( &p.x, &p.x ) );
sinom = MIN( sinom, 1.f );
sinom = V_min( sinom, 1.f );
float sinsom = sin( asin( sinom ) * t );
@ -1749,8 +1862,14 @@ void QuaternionMult( const Quaternion &p, const Quaternion &q, Quaternion &qt )
void QuaternionMatrix( const Quaternion &q, const Vector &pos, matrix3x4_t& matrix )
{
#ifdef DBGFLAG_ASSERT
static bool s_bHushAsserts = !!CommandLine()->FindParm("-hushasserts");
if (!s_bHushAsserts)
{
Assert( pos.IsValid() );
}
#endif
QuaternionMatrix( q, matrix );
@ -1762,7 +1881,13 @@ void QuaternionMatrix( const Quaternion &q, const Vector &pos, matrix3x4_t& matr
void QuaternionMatrix( const Quaternion &q, matrix3x4_t& matrix )
{
Assert( s_bMathlibInitialized );
#ifdef DBGFLAG_ASSERT
static bool s_bHushAsserts = !!CommandLine()->FindParm("-hushasserts");
if ( !s_bHushAsserts )
{
Assert( q.IsValid() );
}
#endif
#ifdef _VPROF_MATHLIB
VPROF_BUDGET( "QuaternionMatrix", "Mathlib" );
@ -2949,9 +3074,9 @@ float CalcSqrDistanceToAABB( const Vector &mins, const Vector &maxs, const Vecto
void CalcClosestPointOnAABB( const Vector &mins, const Vector &maxs, const Vector &point, Vector &closestOut )
{
closestOut.x = clamp( point.x, mins.x, maxs.x );
closestOut.y = clamp( point.y, mins.y, maxs.y );
closestOut.z = clamp( point.z, mins.z, maxs.z );
closestOut.x = std::clamp( point.x, mins.x, maxs.x );
closestOut.y = std::clamp( point.y, mins.y, maxs.y );
closestOut.z = std::clamp( point.z, mins.z, maxs.z );
}
void CalcSqrDistAndClosestPointOnAABB( const Vector &mins, const Vector &maxs, const Vector &point, Vector &closestOut, float &distSqrOut )
@ -3027,7 +3152,7 @@ void CalcClosestPointOnLineSegment( const Vector &P, const Vector &vLineA, const
{
Vector vDir;
float t = CalcClosestPointToLineT( P, vLineA, vLineB, vDir );
t = clamp( t, 0, 1 );
t = std::clamp( t, 0.0f, 1.0f );
if ( outT )
{
*outT = t;
@ -3099,7 +3224,7 @@ void CalcClosestPointOnLineSegment2D( const Vector2D &P, const Vector2D &vLineA,
{
Vector2D vDir;
float t = CalcClosestPointToLineT2D( P, vLineA, vLineB, vDir );
t = clamp( t, 0, 1 );
t = std::clamp( t, 0.0f, 1.0f );
if ( outT )
{
*outT = t;
@ -3210,7 +3335,7 @@ void MathLib_Init( float gamma, float texGamma, float brightness, int overbright
#if !defined( _X360 )
// Grab the processor information:
const CPUInformation& pi = GetCPUInformation();
const CPUInformation& pi = *GetCPUInformation();
// Select the default generic routines.
pfSqrt = _sqrtf;
@ -3233,12 +3358,33 @@ void MathLib_Init( float gamma, float texGamma, float brightness, int overbright
s_bMMXEnabled = false;
}
// SSE Generally performs better than 3DNow when present, so this is placed
// first to allow SSE to override these settings.
#if !defined( OSX ) && !defined( PLATFORM_WINDOWS_PC64 ) && !defined(LINUX)
if ( bAllow3DNow && pi.m_b3DNow )
{
s_b3DNowEnabled = true;
// Select the 3DNow specific routines if available;
pfVectorNormalize = _3DNow_VectorNormalize;
pfVectorNormalizeFast = _3DNow_VectorNormalizeFast;
pfInvRSquared = _3DNow_InvRSquared;
pfSqrt = _3DNow_Sqrt;
pfRSqrt = _3DNow_RSqrt;
pfRSqrtFast = _3DNow_RSqrt;
}
else
#endif
{
s_b3DNowEnabled = false;
}
if ( bAllowSSE && pi.m_bSSE )
{
s_bSSEEnabled = true;
#ifndef PLATFORM_WINDOWS_PC64
// These are not yet available.
// Select the SSE specific routines if available
pfVectorNormalize = _VectorNormalize;
pfVectorNormalizeFast = _SSE_VectorNormalizeFast;
@ -3246,7 +3392,8 @@ void MathLib_Init( float gamma, float texGamma, float brightness, int overbright
pfSqrt = _SSE_Sqrt;
pfRSqrt = _SSE_RSqrtAccurate;
pfRSqrtFast = _SSE_RSqrtFast;
#ifdef _WIN32
#endif
#ifdef PLATFORM_WINDOWS_PC32
pfFastSinCos = _SSE_SinCos;
pfFastCos = _SSE_cos;
#endif
@ -3259,7 +3406,7 @@ void MathLib_Init( float gamma, float texGamma, float brightness, int overbright
if ( bAllowSSE2 && pi.m_bSSE2 )
{
s_bSSE2Enabled = true;
#ifdef _WIN32
#ifdef PLATFORM_WINDOWS_PC32
pfFastSinCos = _SSE2_SinCos;
pfFastCos = _SSE2_cos;
#endif
@ -3268,7 +3415,7 @@ void MathLib_Init( float gamma, float texGamma, float brightness, int overbright
{
s_bSSE2Enabled = false;
}
#endif
#endif // !_X360
s_bMathlibInitialized = true;
@ -3919,10 +4066,10 @@ void CalcTriangleTangentSpace( const Vector &p0, const Vector &p1, const Vector
//-----------------------------------------------------------------------------
void RGBtoHSV( const Vector &rgb, Vector &hsv )
{
float flMax = MAX( rgb.x, rgb.y );
flMax = MAX( flMax, rgb.z );
float flMin = MIN( rgb.x, rgb.y );
flMin = MIN( flMin, rgb.z );
float flMax = V_max( rgb.x, rgb.y );
flMax = V_max( flMax, rgb.z );
float flMin = V_min( rgb.x, rgb.y );
flMin = V_min( flMin, rgb.z );
// hsv.z is the value
hsv.z = flMax;
@ -4069,3 +4216,44 @@ void GetInterpolationData( float const *pKnotPositions,
*pInterpolationValue = FLerp( 0, 1, 0, flSizeOfGap, flOffsetFromStartOfGap );
return;
}
float RandomVectorInUnitSphere( Vector *pVector )
{
// Guarantee uniform random distribution within a sphere
// Graphics gems III contains this algorithm ("Nonuniform random point sets via warping")
float u = ((float)rand() / VALVE_RAND_MAX);
float v = ((float)rand() / VALVE_RAND_MAX);
float w = ((float)rand() / VALVE_RAND_MAX);
float flPhi = acos( 1 - 2 * u );
float flTheta = 2 * M_PI * v;
float flRadius = powf( w, 1.0f / 3.0f );
float flSinPhi, flCosPhi;
float flSinTheta, flCosTheta;
SinCos( flPhi, &flSinPhi, &flCosPhi );
SinCos( flTheta, &flSinTheta, &flCosTheta );
pVector->x = flRadius * flSinPhi * flCosTheta;
pVector->y = flRadius * flSinPhi * flSinTheta;
pVector->z = flRadius * flCosPhi;
return flRadius;
}
float RandomVectorInUnitCircle( Vector2D *pVector )
{
// Guarantee uniform random distribution within a sphere
// Graphics gems III contains this algorithm ("Nonuniform random point sets via warping")
float u = ((float)rand() / VALVE_RAND_MAX);
float v = ((float)rand() / VALVE_RAND_MAX);
float flTheta = 2 * M_PI * v;
float flRadius = powf( u, 1.0f / 2.0f );
float flSinTheta, flCosTheta;
SinCos( flTheta, &flSinTheta, &flCosTheta );
pVector->x = flRadius * flCosTheta;
pVector->y = flRadius * flSinTheta;
return flRadius;
}

View File

@ -34,7 +34,6 @@ CPolyhedron *ConvertLinkedGeometryToPolyhedron( GeneratePolyhedronFromPlanes_Uno
//#define DEBUG_DUMP_POLYHEDRONS_TO_NUMBERED_GLVIEWS //dumps successfully generated polyhedrons
#ifdef _DEBUG
#include "filesystem.h"
void DumpPolyhedronToGLView( const CPolyhedron *pPolyhedron, const char *pFilename, const VMatrix *pTransform );
void DumpPlaneToGlView( const float *pPlane, float fGrayScale, const char *pszFileName, const VMatrix *pTransform );
void DumpLineToGLView( const Vector &vPoint1, const Vector &vColor1, const Vector &vPoint2, const Vector &vColor2, float fThickness, FILE *pFile );
@ -103,19 +102,19 @@ CPolyhedron_AllocByNew *CPolyhedron_AllocByNew::Allocate( unsigned short iVertic
class CPolyhedron_TempMemory : public CPolyhedron
{
public:
#ifdef _DEBUG
#ifdef DBGFLAG_ASSERT
int iReferenceCount;
#endif
virtual void Release( void )
{
#ifdef _DEBUG
#ifdef DBGFLAG_ASSERT
--iReferenceCount;
#endif
}
CPolyhedron_TempMemory( void )
#ifdef _DEBUG
#ifdef DBGFLAG_ASSERT
: iReferenceCount( 0 )
#endif
{ };
@ -128,7 +127,7 @@ static CPolyhedron_TempMemory s_TempMemoryPolyhedron;
CPolyhedron *GetTempPolyhedron( unsigned short iVertices, unsigned short iLines, unsigned short iIndices, unsigned short iPolygons ) //grab the temporary polyhedron. Avoids new/delete for quick work. Can only be in use by one chunk of code at a time
{
AssertMsg( s_TempMemoryPolyhedron.iReferenceCount == 0, "Temporary polyhedron memory being rewritten before released" );
#ifdef _DEBUG
#ifdef DBGFLAG_ASSERT
++s_TempMemoryPolyhedron.iReferenceCount;
#endif
s_TempMemoryPolyhedron_Buffer.SetCount( (sizeof( Vector ) * iVertices) +
@ -857,8 +856,8 @@ const char * DumpPolyhedronCutHistory( const CUtlVector<CPolyhedron *> &DumpedHi
#else
#define AssertMsg_DumpPolyhedron(condition, message)
#define Assert_DumpPolyhedron(condition)
#define AssertMsg_DumpPolyhedron(condition, message) NULL;
#define Assert_DumpPolyhedron(condition) NULL;
#endif

View File

@ -6,6 +6,10 @@
#include "mathlib/ssemath.h"
// NOTE: This has to be the last file included!
#include "tier0/memdbgon.h"
fltx4 Pow_FixedPoint_Exponent_SIMD( const fltx4 & x, int exponent)
{
fltx4 rslt=Four_Ones; // x^0=1.0
@ -32,8 +36,61 @@ fltx4 Pow_FixedPoint_Exponent_SIMD( const fltx4 & x, int exponent)
break;
}
if (exponent<0)
return ReciprocalEstSIMD(rslt); // pow(x,-b)=1/pow(x,b)
return ReciprocalEstSaturateSIMD(rslt); // pow(x,-b)=1/pow(x,b)
else
return rslt;
}
/*
* (c) Ian Stephenson
*
* ian@dctsystems.co.uk
*
* Fast pow() reference implementation
*/
static float shift23=(1<<23);
static float OOshift23=1.0/(1<<23);
float FastLog2(float i)
{
float LogBodge=0.346607f;
float x;
float y;
x=*(int *)&i;
x*= OOshift23; //1/pow(2,23);
x=x-127;
y=x-floorf(x);
y=(y-y*y)*LogBodge;
return x+y;
}
float FastPow2(float i)
{
float PowBodge=0.33971f;
float x;
float y=i-floorf(i);
y=(y-y*y)*PowBodge;
x=i+127-y;
x*= shift23; //pow(2,23);
*(int*)&x=(int)x;
return x;
}
float FastPow(float a, float b)
{
if (a <= OOshift23)
{
return 0.0f;
}
return FastPow2(b*FastLog2(a));
}
float FastPow10( float i )
{
return FastPow2( i * 3.321928f );
}

View File

@ -18,11 +18,10 @@
#endif
#include <stdlib.h>
#include <minmax.h>
#include <math.h>
#include <tier0/basetypes.h>
static int current_ndims;
static struct QuantizedValue *current_root;
static int current_ssize;
@ -412,8 +411,8 @@ static void Label(struct QuantizedValue *q, int updatecolor)
else
for(int i=0;i<current_ndims;i++)
{
q->Mins[i]=MIN(q->Children[0]->Mins[i],q->Children[1]->Mins[i]);
q->Maxs[i]=MAX(q->Children[0]->Maxs[i],q->Children[1]->Maxs[i]);
q->Mins[i]=V_min(q->Children[0]->Mins[i],q->Children[1]->Mins[i]);
q->Maxs[i]=V_max(q->Children[0]->Maxs[i],q->Children[1]->Maxs[i]);
}
}
}

View File

@ -48,7 +48,7 @@ void CSIMDVectorMatrix::CreateFromRGBA_FloatImageData(int srcwidth, int srcheigh
{
for(int cp=0;cp<4; cp++)
{
int real_cp=MIN( cp, ntrailing_pixels_per_source_line-1 );
int real_cp=V_min( cp, ntrailing_pixels_per_source_line-1 );
data_out[4*c+cp]= data_in[c+4*real_cp];
}
}

124
mathlib/spherical.cpp Normal file
View File

@ -0,0 +1,124 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: spherical math routines
//
//=====================================================================================//
#include <math.h>
#include <float.h> // Needed for FLT_EPSILON
#include "basetypes.h"
#include <memory.h>
#include "tier0/dbg.h"
#include "mathlib/mathlib.h"
#include "mathlib/vector.h"
#include "mathlib/spherical_geometry.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
float s_flFactorials[]={
1.,
1.,
2.,
6.,
24.,
120.,
720.,
5040.,
40320.,
362880.,
3628800.,
39916800.,
479001600.,
6227020800.,
87178291200.,
1307674368000.,
20922789888000.,
355687428096000.,
6402373705728000.,
121645100408832000.,
2432902008176640000.,
51090942171709440000.,
1124000727777607680000.,
25852016738884976640000.,
620448401733239439360000.,
15511210043330985984000000.,
403291461126605635584000000.,
10888869450418352160768000000.,
304888344611713860501504000000.,
8841761993739701954543616000000.,
265252859812191058636308480000000.,
8222838654177922817725562880000000.,
263130836933693530167218012160000000.,
8683317618811886495518194401280000000.
};
float AssociatedLegendrePolynomial( int nL, int nM, float flX )
{
// evaluate associated legendre polynomial at flX, using recurrence relation
float flPmm = 1.;
if ( nM > 0 )
{
float flSomX2 = sqrt( ( 1 - flX ) * ( 1 + flX ) );
float flFact = 1.;
for( int i = 0 ; i < nM; i++ )
{
flPmm *= -flFact * flSomX2;
flFact += 2.0;
}
}
if ( nL == nM )
return flPmm;
float flPmmp1 = flX * ( 2.0 * nM + 1.0 ) * flPmm;
if ( nL == nM + 1 )
return flPmmp1;
float flPll = 0.;
for( int nLL = nM + 2 ; nLL <= nL; nLL++ )
{
flPll = ( ( 2.0 * nLL - 1.0 ) * flX * flPmmp1 - ( nLL + nM - 1.0 ) * flPmm ) * ( 1.0 / ( nLL - nM ) );
flPmm = flPmmp1;
flPmmp1 = flPll;
}
return flPll;
}
static float SHNormalizationFactor( int nL, int nM )
{
double flTemp = ( ( 2. * nL + 1.0 ) * s_flFactorials[ nL - nM ] )/ ( 4. * M_PI * s_flFactorials[ nL + nM ] );
return sqrt( flTemp );
}
#define SQRT_2 1.414213562373095
FORCEINLINE float SphericalHarmonic( int nL, int nM, float flTheta, float flPhi, float flCosTheta )
{
if ( nM == 0 )
return SHNormalizationFactor( nL, 0 ) * AssociatedLegendrePolynomial( nL, nM, flCosTheta );
if ( nM > 0 )
return SQRT_2 * SHNormalizationFactor( nL, nM ) * cos ( nM * flPhi ) *
AssociatedLegendrePolynomial( nL, nM, flCosTheta );
return
SQRT_2 * SHNormalizationFactor( nL, -nM ) * sin( -nM * flPhi ) * AssociatedLegendrePolynomial( nL, -nM, flCosTheta );
}
float SphericalHarmonic( int nL, int nM, float flTheta, float flPhi )
{
return SphericalHarmonic( nL, nM, flTheta, flPhi, cos( flTheta ) );
}
float SphericalHarmonic( int nL, int nM, Vector const &vecDirection )
{
Assert( fabs( VectorLength( vecDirection ) - 1.0 ) < 0.0001 );
float flPhi = acos( vecDirection.z );
float flTheta = 0;
float S = Square( vecDirection.x ) + Square( vecDirection.y );
if ( S > 0 )
{
flTheta = atan2( vecDirection.y, vecDirection.x );
}
return SphericalHarmonic( nL, nM, flTheta, flPhi, cos( flTheta ) );
}

View File

@ -1,4 +1,4 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//========= Copyright <EFBFBD> 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: SSE Math primitives.
//
@ -16,8 +16,13 @@
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#ifndef COMPILER_MSVC64
// Implement for 64-bit Windows if needed.
#ifdef _WIN32
static const uint32 _sincos_masks[] = { (uint32)0x0, (uint32)~0x0 };
static const uint32 _sincos_inv_masks[] = { (uint32)~0x0, (uint32)0x0 };
#endif
//-----------------------------------------------------------------------------
// Macros and constants required by some of the SSE assembly:
@ -35,20 +40,21 @@ static const uint32 _sincos_inv_masks[] = { (uint32)~0x0, (uint32)0x0 };
#define _PS_CONST(Name, Val) \
static const __declspec(align(16)) float _ps_##Name[4] = { Val, Val, Val, Val }
#elif defined _LINUX || defined __APPLE__
#elif POSIX
#define _PS_EXTERN_CONST(Name, Val) \
const __attribute__((aligned(16))) float _ps_##Name[4] = { Val, Val, Val, Val }
const float _ps_##Name[4] __attribute__((aligned(16))) = { Val, Val, Val, Val }
#define _PS_EXTERN_CONST_TYPE(Name, Type, Val) \
const __attribute__((aligned(16))) Type _ps_##Name[4] = { Val, Val, Val, Val }; \
const Type _ps_##Name[4] __attribute__((aligned(16))) = { Val, Val, Val, Val }; \
#define _EPI32_CONST(Name, Val) \
static const __attribute__((aligned(16))) int32 _epi32_##Name[4] = { Val, Val, Val, Val }
static const int32 _epi32_##Name[4] __attribute__((aligned(16))) = { Val, Val, Val, Val }
#define _PS_CONST(Name, Val) \
static const __attribute__((aligned(16))) float _ps_##Name[4] = { Val, Val, Val, Val }
static const float _ps_##Name[4] __attribute__((aligned(16))) = { Val, Val, Val, Val }
#endif
#ifdef _WIN32
_PS_EXTERN_CONST(am_0, 0.0f);
_PS_EXTERN_CONST(am_1, 1.0f);
_PS_EXTERN_CONST(am_m1, -1.0f);
@ -59,8 +65,8 @@ _PS_EXTERN_CONST(am_pi_o_2, (float)(M_PI / 2.0));
_PS_EXTERN_CONST(am_2_o_pi, (float)(2.0 / M_PI));
_PS_EXTERN_CONST(am_pi_o_4, (float)(M_PI / 4.0));
_PS_EXTERN_CONST(am_4_o_pi, (float)(4.0 / M_PI));
_PS_EXTERN_CONST_TYPE(am_sign_mask, int32, 0x80000000);
_PS_EXTERN_CONST_TYPE(am_inv_sign_mask, int32, ~0x80000000);
_PS_EXTERN_CONST_TYPE(am_sign_mask, int32, static_cast<int32>(0x80000000));
_PS_EXTERN_CONST_TYPE(am_inv_sign_mask, int32, static_cast<int32>(~0x80000000));
_PS_EXTERN_CONST_TYPE(am_min_norm_pos,int32, 0x00800000);
_PS_EXTERN_CONST_TYPE(am_mant_mask, int32, 0x7f800000);
_PS_EXTERN_CONST_TYPE(am_inv_mant_mask, int32, ~0x7f800000);
@ -72,6 +78,7 @@ _PS_CONST(sincos_p0, 0.15707963267948963959e1f);
_PS_CONST(sincos_p1, -0.64596409750621907082e0f);
_PS_CONST(sincos_p2, 0.7969262624561800806e-1f);
_PS_CONST(sincos_p3, -0.468175413106023168e-2f);
#endif
#ifdef PFN_VECTORMA
void __cdecl _SSE_VectorMA( const float *start, float scale, const float *direction, float *dest );
@ -90,14 +97,8 @@ float _SSE_Sqrt(float x)
sqrtss xmm0, x
movss root, xmm0
}
#elif defined _LINUX || defined __APPLE__
__asm__ __volatile__(
"movss %1,%%xmm2\n"
"sqrtss %%xmm2,%%xmm1\n"
"movss %%xmm1,%0"
: "=m" (root)
: "m" (x)
);
#elif POSIX
_mm_store_ss( &root, _mm_sqrt_ss( _mm_load_ss( &x ) ) );
#endif
return root;
}
@ -120,14 +121,21 @@ float _SSE_RSqrtAccurate(float x)
return (0.5f * rroot) * (3.f - (x * rroot) * rroot);
}
#else
#ifdef POSIX
const __m128 f3 = _mm_set_ss(3.0f); // 3 as SSE value
const __m128 f05 = _mm_set_ss(0.5f); // 0.5 as SSE value
#endif
// Intel / Kipps SSE RSqrt. Significantly faster than above.
float _SSE_RSqrtAccurate(float a)
{
#ifdef _WIN32
float x;
float half = 0.5f;
float three = 3.f;
#ifdef _WIN32
__asm
{
movss xmm3, a;
@ -143,26 +151,25 @@ float _SSE_RSqrtAccurate(float a)
movss x, xmm1;
}
#elif defined _LINUX || defined __APPLE__
__asm__ __volatile__(
"movss %1, %%xmm3 \n\t"
"movss %2, %%xmm1 \n\t"
"movss %3, %%xmm2 \n\t"
"rsqrtss %%xmm3, %%xmm0 \n\t"
"mulss %%xmm0, %%xmm3 \n\t"
"mulss %%xmm0, %%xmm1 \n\t"
"mulss %%xmm0, %%xmm3 \n\t"
"subss %%xmm3, %%xmm2 \n\t"
"mulss %%xmm2, %%xmm1 \n\t"
"movss %%xmm1, %0 \n\t"
: "=m" (x)
: "m" (a), "m" (half), "m" (three)
);
return x;
#elif POSIX
__m128 xx = _mm_load_ss( &a );
__m128 xr = _mm_rsqrt_ss( xx );
__m128 xt;
xt = _mm_mul_ss( xr, xr );
xt = _mm_mul_ss( xt, xx );
xt = _mm_sub_ss( f3, xt );
xt = _mm_mul_ss( xt, f05 );
xr = _mm_mul_ss( xr, xt );
_mm_store_ss( &a, xr );
return a;
#else
#error "Not Implemented"
#endif
return x;
}
#endif
@ -172,21 +179,15 @@ float _SSE_RSqrtFast(float x)
{
Assert( s_bMathlibInitialized );
float rroot = 0.0f;
float rroot;
#ifdef _WIN32
_asm
{
rsqrtss xmm0, x
movss rroot, xmm0
}
#elif defined _LINUX || defined __APPLE__
__asm__ __volatile__(
"rsqrtss %1, %%xmm0 \n\t"
"movss %%xmm0, %0 \n\t"
: "=m" (x)
: "m" (rroot)
: "%xmm0"
);
#elif POSIX
__asm__ __volatile__( "rsqrtss %0, %1" : "=x" (rroot) : "x" (x) );
#else
#error
#endif
@ -202,11 +203,14 @@ float FASTCALL _SSE_VectorNormalize (Vector& vec)
// sice vec only has 3 floats, we can't "movaps" directly into it.
#ifdef _WIN32
__declspec(align(16)) float result[4];
#elif defined _LINUX || defined __APPLE__
__attribute__((aligned(16))) float result[4];
#elif POSIX
float result[4] __attribute__((aligned(16)));
#endif
float *v = &vec[0];
#ifdef _WIN32
float *r = &result[0];
#endif
float radius = 0.f;
// Blah, get rid of these comparisons ... in reality, if you have all 3 as zero, it shouldn't
@ -214,7 +218,6 @@ float FASTCALL _SSE_VectorNormalize (Vector& vec)
if ( v[0] || v[1] || v[2] )
{
#ifdef _WIN32
float *r = &result[0];
_asm
{
mov eax, v
@ -239,7 +242,7 @@ float FASTCALL _SSE_VectorNormalize (Vector& vec)
mulps xmm4, xmm1 // r4 = vx * 1/radius, vy * 1/radius, vz * 1/radius, X
movaps [edx], xmm4 // v = vx * 1/radius, vy * 1/radius, vz * 1/radius, X
}
#elif defined _LINUX || defined __APPLE__
#elif POSIX
__asm__ __volatile__(
#ifdef ALIGNED_VECTOR
"movaps %2, %%xmm4 \n\t"
@ -262,6 +265,7 @@ float FASTCALL _SSE_VectorNormalize (Vector& vec)
"movaps %%xmm4, %1 \n\t"
: "=m" (radius), "=m" (result)
: "m" (*v)
: "xmm1", "xmm2", "xmm3", "xmm4"
);
#else
#error "Not Implemented"
@ -303,12 +307,13 @@ float _SSE_InvRSquared(const float* v)
shufps xmm2, xmm2, 1 // x2 = vy * vy, X, X, X
addss xmm1, xmm2 // x1 = (vx * vx) + (vy * vy), X, X, X
addss xmm1, xmm3 // x1 = (vx * vx) + (vy * vy) + (vz * vz), X, X, X
maxss xmm1, xmm5 // x1 = MAX( 1.0, x1 )
rcpss xmm0, xmm1 // x0 = 1 / MAX( 1.0, x1 )
maxss xmm1, xmm5 // x1 = max( 1.0, x1 )
rcpss xmm0, xmm1 // x0 = 1 / max( 1.0, x1 )
movss inv_r2, xmm0 // inv_r2 = x0
}
#elif defined _LINUX || defined __APPLE__
#elif POSIX
__asm__ __volatile__(
"movss %0, %%xmm5 \n\t"
#ifdef ALIGNED_VECTOR
"movaps %1, %%xmm4 \n\t"
#else
@ -324,8 +329,9 @@ float _SSE_InvRSquared(const float* v)
"maxss %%xmm5, %%xmm1 \n\t"
"rcpss %%xmm1, %%xmm0 \n\t"
"movss %%xmm0, %0 \n\t"
: "=m" (inv_r2)
: "m" (*v), "m" (inv_r2)
: "+m" (inv_r2)
: "m" (*v)
: "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"
);
#else
#error "Not Implemented"
@ -334,6 +340,50 @@ float _SSE_InvRSquared(const float* v)
return inv_r2;
}
#ifdef POSIX
// #define _PS_CONST(Name, Val) static const ALIGN16 float _ps_##Name[4] ALIGN16_POST = { Val, Val, Val, Val }
#define _PS_CONST_TYPE(Name, Type, Val) static const ALIGN16 Type _ps_##Name[4] ALIGN16_POST = { static_cast<Type>(Val), static_cast<Type>(Val), static_cast<Type>(Val), static_cast<Type>(Val) }
_PS_CONST_TYPE(sign_mask, int, 0x80000000);
_PS_CONST_TYPE(inv_sign_mask, int, ~0x80000000);
#define _PI32_CONST(Name, Val) static const ALIGN16 int _pi32_##Name[4] ALIGN16_POST = { Val, Val, Val, Val }
_PI32_CONST(1, 1);
_PI32_CONST(inv1, ~1);
_PI32_CONST(2, 2);
_PI32_CONST(4, 4);
#ifdef _WIN32
_PI32_CONST(0x7f, 0x7f);
#endif
_PS_CONST(1 , 1.0f);
_PS_CONST(0p5, 0.5f);
_PS_CONST(minus_cephes_DP1, -0.78515625);
_PS_CONST(minus_cephes_DP2, -2.4187564849853515625e-4);
_PS_CONST(minus_cephes_DP3, -3.77489497744594108e-8);
_PS_CONST(sincof_p0, -1.9515295891E-4);
_PS_CONST(sincof_p1, 8.3321608736E-3);
_PS_CONST(sincof_p2, -1.6666654611E-1);
_PS_CONST(coscof_p0, 2.443315711809948E-005);
_PS_CONST(coscof_p1, -1.388731625493765E-003);
_PS_CONST(coscof_p2, 4.166664568298827E-002);
_PS_CONST(cephes_FOPI, 1.27323954473516); // 4 / M_PI
typedef union xmm_mm_union {
__m128 xmm;
__m64 mm[2];
} xmm_mm_union;
#define COPY_MM_TO_XMM(mm0_, mm1_, xmm_) { xmm_mm_union u; u.mm[0]=mm0_; u.mm[1]=mm1_; xmm_ = u.xmm; }
typedef __m128 v4sf; // vector of 4 float (sse1)
typedef __m64 v2si; // vector of 2 int (mmx)
#endif
void _SSE_SinCos(float x, float* s, float* c)
{
#ifdef _WIN32
@ -421,8 +471,121 @@ void _SSE_SinCos(float x, float* s, float* c)
movss [eax], xmm0
movss [edx], xmm4
}
#elif defined _LINUX || defined __APPLE__
// #warning "_SSE_sincos NOT implemented!"
#elif POSIX
Assert( "Needs testing, verify impl!\n" );
v4sf xx = _mm_load_ss( &x );
v4sf xmm1, xmm2, xmm3 = _mm_setzero_ps(), sign_bit_sin, y;
v2si mm0, mm1, mm2, mm3, mm4, mm5;
sign_bit_sin = xx;
/* take the absolute value */
xx = _mm_and_ps(xx, *(v4sf*)_ps_inv_sign_mask);
/* extract the sign bit (upper one) */
sign_bit_sin = _mm_and_ps(sign_bit_sin, *(v4sf*)_ps_sign_mask);
/* scale by 4/Pi */
y = _mm_mul_ps(xx, *(v4sf*)_ps_cephes_FOPI);
/* store the integer part of y in mm2:mm3 */
xmm3 = _mm_movehl_ps(xmm3, y);
mm2 = _mm_cvttps_pi32(y);
mm3 = _mm_cvttps_pi32(xmm3);
/* j=(j+1) & (~1) (see the cephes sources) */
mm2 = _mm_add_pi32(mm2, *(v2si*)_pi32_1);
mm3 = _mm_add_pi32(mm3, *(v2si*)_pi32_1);
mm2 = _mm_and_si64(mm2, *(v2si*)_pi32_inv1);
mm3 = _mm_and_si64(mm3, *(v2si*)_pi32_inv1);
y = _mm_cvtpi32x2_ps(mm2, mm3);
mm4 = mm2;
mm5 = mm3;
/* get the swap sign flag for the sine */
mm0 = _mm_and_si64(mm2, *(v2si*)_pi32_4);
mm1 = _mm_and_si64(mm3, *(v2si*)_pi32_4);
mm0 = _mm_slli_pi32(mm0, 29);
mm1 = _mm_slli_pi32(mm1, 29);
v4sf swap_sign_bit_sin;
COPY_MM_TO_XMM(mm0, mm1, swap_sign_bit_sin);
/* get the polynom selection mask for the sine */
mm2 = _mm_and_si64(mm2, *(v2si*)_pi32_2);
mm3 = _mm_and_si64(mm3, *(v2si*)_pi32_2);
mm2 = _mm_cmpeq_pi32(mm2, _mm_setzero_si64());
mm3 = _mm_cmpeq_pi32(mm3, _mm_setzero_si64());
v4sf poly_mask;
COPY_MM_TO_XMM(mm2, mm3, poly_mask);
/* The magic pass: "Extended precision modular arithmetic"
x = ((x - y * DP1) - y * DP2) - y * DP3; */
xmm1 = *(v4sf*)_ps_minus_cephes_DP1;
xmm2 = *(v4sf*)_ps_minus_cephes_DP2;
xmm3 = *(v4sf*)_ps_minus_cephes_DP3;
xmm1 = _mm_mul_ps(y, xmm1);
xmm2 = _mm_mul_ps(y, xmm2);
xmm3 = _mm_mul_ps(y, xmm3);
xx = _mm_add_ps(xx, xmm1);
xx = _mm_add_ps(xx, xmm2);
xx = _mm_add_ps(xx, xmm3);
/* get the sign flag for the cosine */
mm4 = _mm_sub_pi32(mm4, *(v2si*)_pi32_2);
mm5 = _mm_sub_pi32(mm5, *(v2si*)_pi32_2);
mm4 = _mm_andnot_si64(mm4, *(v2si*)_pi32_4);
mm5 = _mm_andnot_si64(mm5, *(v2si*)_pi32_4);
mm4 = _mm_slli_pi32(mm4, 29);
mm5 = _mm_slli_pi32(mm5, 29);
v4sf sign_bit_cos;
COPY_MM_TO_XMM(mm4, mm5, sign_bit_cos);
_mm_empty(); /* good-bye mmx */
sign_bit_sin = _mm_xor_ps(sign_bit_sin, swap_sign_bit_sin);
/* Evaluate the first polynom (0 <= x <= Pi/4) */
v4sf z = _mm_mul_ps(xx,xx);
y = *(v4sf*)_ps_coscof_p0;
y = _mm_mul_ps(y, z);
y = _mm_add_ps(y, *(v4sf*)_ps_coscof_p1);
y = _mm_mul_ps(y, z);
y = _mm_add_ps(y, *(v4sf*)_ps_coscof_p2);
y = _mm_mul_ps(y, z);
y = _mm_mul_ps(y, z);
v4sf tmp = _mm_mul_ps(z, *(v4sf*)_ps_0p5);
y = _mm_sub_ps(y, tmp);
y = _mm_add_ps(y, *(v4sf*)_ps_1);
/* Evaluate the second polynom (Pi/4 <= x <= 0) */
v4sf y2 = *(v4sf*)_ps_sincof_p0;
y2 = _mm_mul_ps(y2, z);
y2 = _mm_add_ps(y2, *(v4sf*)_ps_sincof_p1);
y2 = _mm_mul_ps(y2, z);
y2 = _mm_add_ps(y2, *(v4sf*)_ps_sincof_p2);
y2 = _mm_mul_ps(y2, z);
y2 = _mm_mul_ps(y2, xx);
y2 = _mm_add_ps(y2, xx);
/* select the correct result from the two polynoms */
xmm3 = poly_mask;
v4sf ysin2 = _mm_and_ps(xmm3, y2);
v4sf ysin1 = _mm_andnot_ps(xmm3, y);
y2 = _mm_sub_ps(y2,ysin2);
y = _mm_sub_ps(y, ysin1);
xmm1 = _mm_add_ps(ysin1,ysin2);
xmm2 = _mm_add_ps(y,y2);
/* update the sign */
_mm_store_ss( s, _mm_xor_ps(xmm1, sign_bit_sin) );
_mm_store_ss( c, _mm_xor_ps(xmm2, sign_bit_cos) );
#else
#error "Not Implemented"
#endif
@ -479,8 +642,102 @@ float _SSE_cos( float x )
movss x, xmm0
}
#elif defined _LINUX || defined __APPLE__
// #warning "_SSE_cos NOT implemented!"
#elif POSIX
Assert( "Needs testing, verify impl!\n" );
v4sf xmm1, xmm2 = _mm_setzero_ps(), xmm3, y;
v2si mm0, mm1, mm2, mm3;
/* take the absolute value */
v4sf xx = _mm_load_ss( &x );
xx = _mm_and_ps(xx, *(v4sf*)_ps_inv_sign_mask);
/* scale by 4/Pi */
y = _mm_mul_ps(xx, *(v4sf*)_ps_cephes_FOPI);
/* store the integer part of y in mm0:mm1 */
xmm2 = _mm_movehl_ps(xmm2, y);
mm2 = _mm_cvttps_pi32(y);
mm3 = _mm_cvttps_pi32(xmm2);
/* j=(j+1) & (~1) (see the cephes sources) */
mm2 = _mm_add_pi32(mm2, *(v2si*)_pi32_1);
mm3 = _mm_add_pi32(mm3, *(v2si*)_pi32_1);
mm2 = _mm_and_si64(mm2, *(v2si*)_pi32_inv1);
mm3 = _mm_and_si64(mm3, *(v2si*)_pi32_inv1);
y = _mm_cvtpi32x2_ps(mm2, mm3);
mm2 = _mm_sub_pi32(mm2, *(v2si*)_pi32_2);
mm3 = _mm_sub_pi32(mm3, *(v2si*)_pi32_2);
/* get the swap sign flag in mm0:mm1 and the
polynom selection mask in mm2:mm3 */
mm0 = _mm_andnot_si64(mm2, *(v2si*)_pi32_4);
mm1 = _mm_andnot_si64(mm3, *(v2si*)_pi32_4);
mm0 = _mm_slli_pi32(mm0, 29);
mm1 = _mm_slli_pi32(mm1, 29);
mm2 = _mm_and_si64(mm2, *(v2si*)_pi32_2);
mm3 = _mm_and_si64(mm3, *(v2si*)_pi32_2);
mm2 = _mm_cmpeq_pi32(mm2, _mm_setzero_si64());
mm3 = _mm_cmpeq_pi32(mm3, _mm_setzero_si64());
v4sf sign_bit, poly_mask;
COPY_MM_TO_XMM(mm0, mm1, sign_bit);
COPY_MM_TO_XMM(mm2, mm3, poly_mask);
_mm_empty(); /* good-bye mmx */
/* The magic pass: "Extended precision modular arithmetic"
x = ((x - y * DP1) - y * DP2) - y * DP3; */
xmm1 = *(v4sf*)_ps_minus_cephes_DP1;
xmm2 = *(v4sf*)_ps_minus_cephes_DP2;
xmm3 = *(v4sf*)_ps_minus_cephes_DP3;
xmm1 = _mm_mul_ps(y, xmm1);
xmm2 = _mm_mul_ps(y, xmm2);
xmm3 = _mm_mul_ps(y, xmm3);
xx = _mm_add_ps(xx, xmm1);
xx = _mm_add_ps(xx, xmm2);
xx = _mm_add_ps(xx, xmm3);
/* Evaluate the first polynom (0 <= x <= Pi/4) */
y = *(v4sf*)_ps_coscof_p0;
v4sf z = _mm_mul_ps(xx,xx);
y = _mm_mul_ps(y, z);
y = _mm_add_ps(y, *(v4sf*)_ps_coscof_p1);
y = _mm_mul_ps(y, z);
y = _mm_add_ps(y, *(v4sf*)_ps_coscof_p2);
y = _mm_mul_ps(y, z);
y = _mm_mul_ps(y, z);
v4sf tmp = _mm_mul_ps(z, *(v4sf*)_ps_0p5);
y = _mm_sub_ps(y, tmp);
y = _mm_add_ps(y, *(v4sf*)_ps_1);
/* Evaluate the second polynom (Pi/4 <= x <= 0) */
v4sf y2 = *(v4sf*)_ps_sincof_p0;
y2 = _mm_mul_ps(y2, z);
y2 = _mm_add_ps(y2, *(v4sf*)_ps_sincof_p1);
y2 = _mm_mul_ps(y2, z);
y2 = _mm_add_ps(y2, *(v4sf*)_ps_sincof_p2);
y2 = _mm_mul_ps(y2, z);
y2 = _mm_mul_ps(y2, xx);
y2 = _mm_add_ps(y2, xx);
/* select the correct result from the two polynoms */
xmm3 = poly_mask;
y2 = _mm_and_ps(xmm3, y2); //, xmm3);
y = _mm_andnot_ps(xmm3, y);
y = _mm_add_ps(y,y2);
/* update the sign */
_mm_store_ss( &x, _mm_xor_ps(y, sign_bit) );
#else
#error "Not Implemented"
#endif
@ -491,6 +748,7 @@ float _SSE_cos( float x )
//-----------------------------------------------------------------------------
// SSE2 implementations of optimized routines:
//-----------------------------------------------------------------------------
#ifdef PLATFORM_WINDOWS_PC32
void _SSE2_SinCos(float x, float* s, float* c) // any x
{
#ifdef _WIN32
@ -569,13 +827,16 @@ void _SSE2_SinCos(float x, float* s, float* c) // any x
movss [eax], xmm0
movss [edx], xmm6
}
#elif defined _LINUX || defined __APPLE__
// #warning "_SSE2_SinCos NOT implemented!"
#elif POSIX
#warning "_SSE2_SinCos NOT implemented!"
Assert( 0 );
#else
#error "Not Implemented"
#endif
}
#endif // PLATFORM_WINDOWS_PC32
#ifdef PLATFORM_WINDOWS_PC32
float _SSE2_cos(float x)
{
#ifdef _WIN32
@ -624,15 +885,18 @@ float _SSE2_cos(float x)
mulss xmm0, xmm1
movss x, xmm0
}
#elif defined _LINUX || defined __APPLE__
// #warning "_SSE2_cos NOT implemented!"
#elif POSIX
#warning "_SSE2_cos NOT implemented!"
Assert( 0 );
#else
#error "Not Implemented"
#endif
return x;
}
#endif // PLATFORM_WINDOWS_PC32
#if 0
// SSE Version of VectorTransform
void VectorTransformSSE(const float *in1, const matrix3x4_t& in2, float *out1)
{
@ -681,8 +945,8 @@ void VectorTransformSSE(const float *in1, const matrix3x4_t& in2, float *out1)
addss xmm0, [ecx+12]
movss [edx+8], xmm0;
}
#elif defined _LINUX || defined __APPLE__
// #warning "VectorTransformSSE C implementation only"
#elif POSIX
#warning "VectorTransformSSE C implementation only"
out1[0] = DotProduct(in1, in2[0]) + in2[0][3];
out1[1] = DotProduct(in1, in2[1]) + in2[1][3];
out1[2] = DotProduct(in1, in2[2]) + in2[2][3];
@ -690,7 +954,9 @@ void VectorTransformSSE(const float *in1, const matrix3x4_t& in2, float *out1)
#error "Not Implemented"
#endif
}
#endif
#if 0
void VectorRotateSSE( const float *in1, const matrix3x4_t& in2, float *out1 )
{
Assert( s_bMathlibInitialized );
@ -735,8 +1001,8 @@ void VectorRotateSSE( const float *in1, const matrix3x4_t& in2, float *out1 )
addss xmm0, xmm2;
movss [edx+8], xmm0;
}
#elif defined _LINUX || defined __APPLE__
// #warning "VectorRotateSSE C implementation only"
#elif POSIX
#warning "VectorRotateSSE C implementation only"
out1[0] = DotProduct( in1, in2[0] );
out1[1] = DotProduct( in1, in2[1] );
out1[2] = DotProduct( in1, in2[2] );
@ -744,6 +1010,7 @@ void VectorRotateSSE( const float *in1, const matrix3x4_t& in2, float *out1 )
#error "Not Implemented"
#endif
}
#endif
#ifdef _WIN32
void _declspec(naked) _SSE_VectorMA( const float *start, float scale, const float *direction, float *dest )
@ -843,3 +1110,4 @@ vec_t DotProduct (const vec_t *a, const vec_t *c)
}
*/
#endif // COMPILER_MSVC64

View File

@ -15,9 +15,13 @@ void FASTCALL _SSE_VectorNormalizeFast(Vector& vec);
float _SSE_InvRSquared(const float* v);
void _SSE_SinCos(float x, float* s, float* c);
float _SSE_cos( float x);
#ifdef PLATFORM_WINDOWS_PC32
void _SSE2_SinCos(float x, float* s, float* c);
float _SSE2_cos(float x);
#endif
#if 0
void VectorTransformSSE(const float *in1, const matrix3x4_t& in2, float *out1);
void VectorRotateSSE( const float *in1, const matrix3x4_t& in2, float *out1 );
#endif
#endif // _SSE_H

View File

@ -1,4 +1,4 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//===== Copyright <EFBFBD> 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
@ -30,6 +30,7 @@ const fltx4 Four_FLT_MAX={FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX};
const fltx4 Four_Negative_FLT_MAX={-FLT_MAX,-FLT_MAX,-FLT_MAX,-FLT_MAX};
const fltx4 g_SIMD_0123 = { 0., 1., 2., 3. };
extern const fltx4 g_QuatMultRowSign[4];
const fltx4 g_QuatMultRowSign[4] =
{
{ 1.0f, 1.0f, -1.0f, 1.0f },
@ -38,24 +39,24 @@ const fltx4 g_QuatMultRowSign[4] =
{ -1.0f, -1.0f, -1.0f, 1.0f }
};
const int32 ALIGN16 g_SIMD_clear_signmask[4]= {0x7fffffff,0x7fffffff,0x7fffffff,0x7fffffff};
const int32 ALIGN16 g_SIMD_signmask[4]= { 0x80000000, 0x80000000, 0x80000000, 0x80000000 };
const int32 ALIGN16 g_SIMD_lsbmask[4]= { 0xfffffffe, 0xfffffffe, 0xfffffffe, 0xfffffffe };
const int32 ALIGN16 g_SIMD_clear_wmask[4]= { 0xffffffff, 0xffffffff, 0xffffffff, 0 };
const int32 ALIGN16 g_SIMD_AllOnesMask[4]= { 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff }; // ~0,~0,~0,~0
const int32 ALIGN16 g_SIMD_Low16BitsMask[4]= { 0xffff, 0xffff, 0xffff, 0xffff }; // 0xffff x 4
const int32 ALIGN16 g_SIMD_clear_signmask[4] ALIGN16_POST = {static_cast<int32>(0x7fffffff), static_cast<int32>(0x7fffffff), static_cast<int32>(0x7fffffff), static_cast<int32>(0x7fffffff)};
const int32 ALIGN16 g_SIMD_signmask[4] ALIGN16_POST = { static_cast<int32>(0x80000000), static_cast<int32>(0x80000000), static_cast<int32>(0x80000000), static_cast<int32>(0x80000000) };
const int32 ALIGN16 g_SIMD_lsbmask[4] ALIGN16_POST = { static_cast<int32>(0xfffffffe), static_cast<int32>(0xfffffffe), static_cast<int32>(0xfffffffe), static_cast<int32>(0xfffffffe) };
const int32 ALIGN16 g_SIMD_clear_wmask[4] ALIGN16_POST = { static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff), 0 };
const int32 ALIGN16 g_SIMD_AllOnesMask[4] ALIGN16_POST = { static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff) }; // ~0,~0,~0,~0
const int32 ALIGN16 g_SIMD_Low16BitsMask[4] ALIGN16_POST = { 0xffff, 0xffff, 0xffff, 0xffff }; // 0xffff x 4
const int32 ALIGN16 g_SIMD_ComponentMask[4][4] =
const int32 ALIGN16 g_SIMD_ComponentMask[4][4] ALIGN16_POST =
{
{ 0xFFFFFFFF, 0, 0, 0 }, { 0, 0xFFFFFFFF, 0, 0 }, { 0, 0, 0xFFFFFFFF, 0 }, { 0, 0, 0, 0xFFFFFFFF }
{ static_cast<int32>(0xFFFFFFFF), 0, 0, 0 }, { 0, static_cast<int32>(0xFFFFFFFF), 0, 0 }, { 0, 0, static_cast<int32>(0xFFFFFFFF), 0 }, { 0, 0, 0, static_cast<int32>(0xFFFFFFFF) }
};
const int32 ALIGN16 g_SIMD_SkipTailMask[4][4] =
const int32 ALIGN16 g_SIMD_SkipTailMask[4][4] ALIGN16_POST =
{
{ 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff },
{ 0xffffffff, 0x00000000, 0x00000000, 0x00000000 },
{ 0xffffffff, 0xffffffff, 0x00000000, 0x00000000 },
{ 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000 },
{ static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff) },
{ static_cast<int32>(0xffffffff), static_cast<int32>(0x00000000), static_cast<int32>(0x00000000), static_cast<int32>(0x00000000) },
{ static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff), static_cast<int32>(0x00000000), static_cast<int32>(0x00000000) },
{ static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff), static_cast<int32>(0xffffffff), static_cast<int32>(0x00000000) },
};

View File

@ -30,6 +30,10 @@ static ALIGN16 int32 idx_mask[4]= {0xffff, 0xffff, 0xffff, 0xffff};
// returns 0..1
static inline float GetLatticePointValue( int idx_x, int idx_y, int idx_z )
{
NOTE_UNUSED(perm_d);
NOTE_UNUSED(impulse_ycoords);
NOTE_UNUSED(impulse_zcoords);
int ret_idx = perm_a[idx_x & 0xff];
ret_idx = perm_b[( idx_y + ret_idx ) & 0xff];
ret_idx = perm_c[( idx_z + ret_idx ) & 0xff];

View File

@ -18,7 +18,7 @@
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#ifdef _MSC_VER
#ifdef _WIN32
#pragma warning (disable : 4700) // local variable 'x' used without having been initialized
#endif
@ -306,7 +306,7 @@ bool MatrixInverseGeneral(const VMatrix& src, VMatrix& dst)
for(iRow=0; iRow < 4; iRow++)
{
// Find the row with the largest element in this column.
fLargest = 0.001f;
fLargest = 0.00001f;
iLargest = -1;
for(iTest=iRow; iTest < 4; iTest++)
{
@ -509,7 +509,7 @@ bool VMatrix::IsRotationMatrix() const
FloatMakePositive( v2.Dot(v3) ) < 0.01f;
}
void VMatrix::SetupMatrixOrgAngles( const Vector &origin, const QAngle &vAngles )
static void SetupMatrixAnglesInternal( vec_t m[4][4], const QAngle & vAngles )
{
float sr, sp, sy, cr, cp, cy;
@ -530,6 +530,11 @@ void VMatrix::SetupMatrixOrgAngles( const Vector &origin, const QAngle &vAngles
m[0][3] = 0.f;
m[1][3] = 0.f;
m[2][3] = 0.f;
}
void VMatrix::SetupMatrixOrgAngles( const Vector &origin, const QAngle &vAngles )
{
SetupMatrixAnglesInternal( m, vAngles );
// Add translation
m[0][3] = origin.x;
@ -542,6 +547,21 @@ void VMatrix::SetupMatrixOrgAngles( const Vector &origin, const QAngle &vAngles
}
void VMatrix::SetupMatrixAngles( const QAngle &vAngles )
{
SetupMatrixAnglesInternal( m, vAngles );
// Zero everything else
m[0][3] = 0.0f;
m[1][3] = 0.0f;
m[2][3] = 0.0f;
m[3][0] = 0.0f;
m[3][1] = 0.0f;
m[3][2] = 0.0f;
m[3][3] = 1.0f;
}
//-----------------------------------------------------------------------------
// Sets matrix to identity
//-----------------------------------------------------------------------------
@ -728,7 +748,7 @@ void Vector4DMultiplyPosition( const VMatrix& src1, Vector const& src2, Vector4D
{
// Make sure it works if src2 == dst
Vector tmp;
Vector const&v = ( &src2 == &dst.AsVector3D() ) ? tmp : src2;
Vector const&v = ( &src2 == &dst.AsVector3D() ) ? static_cast<const Vector&>(tmp) : src2;
if (&src2 == &dst.AsVector3D())
{
@ -751,7 +771,7 @@ void Vector3DMultiply( const VMatrix &src1, const Vector &src2, Vector &dst )
{
// Make sure it works if src2 == dst
Vector tmp;
const Vector &v = (&src2 == &dst) ? tmp : src2;
const Vector &v = (&src2 == &dst) ? static_cast<const Vector&>(tmp) : src2;
if( &src2 == &dst )
{
@ -772,7 +792,7 @@ void Vector3DMultiplyPositionProjective( const VMatrix& src1, const Vector &src2
{
// Make sure it works if src2 == dst
Vector tmp;
const Vector &v = (&src2 == &dst) ? tmp: src2;
const Vector &v = (&src2 == &dst) ? static_cast<const Vector&>(tmp): src2;
if( &src2 == &dst )
{
VectorCopy( src2, tmp );
@ -799,7 +819,7 @@ void Vector3DMultiplyProjective( const VMatrix& src1, const Vector &src2, Vector
{
// Make sure it works if src2 == dst
Vector tmp;
const Vector &v = (&src2 == &dst) ? tmp : src2;
const Vector &v = (&src2 == &dst) ? static_cast<const Vector&>(tmp) : src2;
if( &src2 == &dst )
{
VectorCopy( src2, tmp );
@ -852,7 +872,7 @@ void Vector3DMultiplyTranspose( const VMatrix& src1, const Vector& src2, Vector&
bool srcEqualsDst = (&src2 == &dst);
Vector tmp;
const Vector&v = srcEqualsDst ? tmp : src2;
const Vector&v = srcEqualsDst ? static_cast<const Vector&>(tmp) : src2;
if (srcEqualsDst)
{
@ -937,7 +957,7 @@ void MatrixBuildTranslation( VMatrix& dst, const Vector &translation )
//-----------------------------------------------------------------------------
void MatrixBuildRotationAboutAxis( VMatrix &dst, const Vector &vAxisOfRot, float angleDegrees )
{
MatrixBuildRotationAboutAxis( vAxisOfRot, angleDegrees, dst.As3x4() );
MatrixBuildRotationAboutAxis( vAxisOfRot, angleDegrees, const_cast< matrix3x4_t &> ( dst.As3x4() ) );
dst[3][0] = 0;
dst[3][1] = 0;
dst[3][2] = 0;
@ -1233,19 +1253,29 @@ void MatrixBuildOrtho( VMatrix& dst, double left, double top, double right, doub
0.0f, 0.0f, 0.0f, 1.0f );
}
void MatrixBuildPerspectiveZRange( VMatrix& dst, double flZNear, double flZFar )
{
dst.m[2][0] = 0.0f;
dst.m[2][1] = 0.0f;
dst.m[2][2] = flZFar / ( flZNear - flZFar );
dst.m[2][3] = flZNear * flZFar / ( flZNear - flZFar );
}
void MatrixBuildPerspectiveX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar )
{
float flWidth = 2.0f * flZNear * tanf( flFovX * M_PI / 360.0f );
float flHeight = flWidth / flAspect;
dst.Init( 2.0f * flZNear / flWidth, 0.0f, 0.0f, 0.0f,
0.0f, 2.0f * flZNear/ flHeight, 0.0f, 0.0f,
0.0f, 0.0f, flZFar / ( flZNear - flZFar ), flZNear * flZFar / ( flZNear - flZFar ),
float flWidthScale = 1.0f / tanf( flFovX * M_PI / 360.0f );
float flHeightScale = flAspect * flWidthScale;
dst.Init( flWidthScale, 0.0f, 0.0f, 0.0f,
0.0f, flHeightScale, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f, 0.0f );
MatrixBuildPerspectiveZRange ( dst, flZNear, flZFar );
}
void MatrixBuildPerspectiveOffCenterX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar, double bottom, double top, double left, double right )
{
float flWidth = 2.0f * flZNear * tanf( flFovX * M_PI / 360.0f );
float flWidth = tanf( flFovX * M_PI / 360.0f );
float flHeight = flWidth / flAspect;
// bottom, top, left, right are 0..1 so convert to -<val>/2..<val>/2
@ -1254,10 +1284,12 @@ void MatrixBuildPerspectiveOffCenterX( VMatrix& dst, double flFovX, double flAsp
float flBottom = -(flHeight/2.0f) * (1.0f - bottom) + bottom * (flHeight/2.0f);
float flTop = -(flHeight/2.0f) * (1.0f - top) + top * (flHeight/2.0f);
dst.Init( (2.0f * flZNear) / (flRight-flLeft), 0.0f, (flLeft+flRight)/(flRight-flLeft), 0.0f,
0.0f, 2.0f*flZNear/(flTop-flBottom), (flTop+flBottom)/(flTop-flBottom), 0.0f,
0.0f, 0.0f, flZFar/(flZNear-flZFar), flZNear*flZFar/(flZNear-flZFar),
dst.Init( 1.0f / (flRight-flLeft), 0.0f, (flLeft+flRight)/(flRight-flLeft), 0.0f,
0.0f, 1.0f /(flTop-flBottom), (flTop+flBottom)/(flTop-flBottom), 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, -1.0f, 0.0f );
MatrixBuildPerspectiveZRange ( dst, flZNear, flZFar );
}
#endif // !_STATIC_LINKED || _SHARED_LIB

View File

@ -0,0 +1,162 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// ilaunchermgr.h
//
//==================================================================================================
#ifndef ILAUNCHERMGR_H
#define ILAUNCHERMGR_H
#ifdef _WIN32
#pragma once
#endif
#if defined( USE_SDL )
#include "tier0/threadtools.h"
#include "appframework/IAppSystem.h"
#if defined( DX_TO_GL_ABSTRACTION )
#if !defined(DEDICATED)
#include "togl/linuxwin/glmgrbasics.h"
#include "togl/linuxwin/glmdisplay.h"
#endif
class GLMDisplayDB;
class CShowPixelsParams;
#if defined(DEDICATED)
typedef void *PseudoGLContextPtr;
class GLMRendererInfoFields;
#endif
#endif
// if you rev this version also update materialsystem/cmaterialsystem.cpp CMaterialSystem::Connect as it defines the string directly
#define SDLMGR_INTERFACE_VERSION "SDLMgrInterface001"
class CCocoaEvent;
class CStackCrawlParams;
typedef struct SDL_Cursor SDL_Cursor;
class ILauncherMgr : public IAppSystem
{
public:
virtual bool Connect( CreateInterfaceFn factory ) = 0;
virtual void Disconnect() = 0;
virtual void *QueryInterface( const char *pInterfaceName ) = 0;
// Init, shutdown
virtual InitReturnVal_t Init() = 0;
virtual void Shutdown() = 0;
// Create the window.
virtual bool CreateGameWindow( const char *pTitle, bool bWindowed, int width, int height ) = 0;
virtual void IncWindowRefCount() = 0;
virtual void DecWindowRefCount() = 0;
// Get the next N events. The function returns the number of events that were filled into your array.
virtual int GetEvents( CCocoaEvent *pEvents, int nMaxEventsToReturn, bool debugEvents = false ) = 0;
#ifdef LINUX
virtual int PeekAndRemoveKeyboardEvents( bool *pbEsc, bool *pbReturn, bool *pbSpace, bool debugEvents = false ) = 0;
#endif
// Set the mouse cursor position.
virtual void SetCursorPosition( int x, int y ) = 0;
virtual void SetWindowFullScreen( bool bFullScreen, int nWidth, int nHeight ) = 0;
virtual bool IsWindowFullScreen() = 0;
virtual void MoveWindow( int x, int y ) = 0;
virtual void SizeWindow( int width, int tall ) = 0;
virtual void PumpWindowsMessageLoop() = 0;
virtual void DestroyGameWindow() = 0;
virtual void SetApplicationIcon( const char *pchAppIconFile ) = 0;
virtual void GetMouseDelta( int &x, int &y, bool bIgnoreNextMouseDelta = false ) = 0;
virtual void GetNativeDisplayInfo( int nDisplay, uint &nWidth, uint &nHeight, uint &nRefreshHz ) = 0; // Retrieve the size of the monitor (desktop)
virtual void RenderedSize( uint &width, uint &height, bool set ) = 0; // either set or retrieve rendered size value (from dxabstract)
virtual void DisplayedSize( uint &width, uint &height ) = 0; // query backbuffer size (window size whether FS or windowed)
#if defined( DX_TO_GL_ABSTRACTION )
virtual PseudoGLContextPtr GetMainContext() = 0;
// Get the NSGLContext for a window's main view - note this is the carbon windowref as an argument
virtual PseudoGLContextPtr GetGLContextForWindow( void* windowref ) = 0;
virtual PseudoGLContextPtr CreateExtraContext() = 0;
virtual void DeleteContext( PseudoGLContextPtr hContext ) = 0;
virtual bool MakeContextCurrent( PseudoGLContextPtr hContext ) = 0;
virtual GLMDisplayDB *GetDisplayDB( void ) = 0;
virtual void GetDesiredPixelFormatAttribsAndRendererInfo( uint **ptrOut, uint *countOut, GLMRendererInfoFields *rendInfoOut ) = 0;
virtual void ShowPixels( CShowPixelsParams *params ) = 0;
#endif
virtual void GetStackCrawl( CStackCrawlParams *params ) = 0;
virtual void WaitUntilUserInput( int msSleepTime ) = 0;
virtual void *GetWindowRef() = 0;
virtual void SetMouseVisible( bool bState ) = 0;
virtual void SetMouseCursor( SDL_Cursor *hCursor ) = 0;
virtual void SetForbidMouseGrab( bool bForbidMouseGrab ) = 0;
virtual void OnFrameRendered() = 0;
virtual void SetGammaRamp( const uint16 *pRed, const uint16 *pGreen, const uint16 *pBlue ) = 0;
virtual double GetPrevGLSwapWindowTime() = 0;
};
extern ILauncherMgr *g_pLauncherMgr;
enum CocoaEventType_t
{
CocoaEvent_KeyDown,
CocoaEvent_KeyUp,
CocoaEvent_MouseButtonDown,
CocoaEvent_MouseMove,
CocoaEvent_MouseButtonUp,
CocoaEvent_AppActivate,
CocoaEvent_MouseScroll,
CocoaEvent_AppQuit,
CocoaEvent_Deleted, // Event was one of the above, but has been handled and should be ignored now.
};
// enum values need to match bit-shifting logic in CInputSystem::UpdateMouseButtonState and
// the codes from NSEvent pressedMouseButtons, turns out the two are in agreement right now
enum CocoaMouseButton_t
{
COCOABUTTON_LEFT = 1 << 0,
COCOABUTTON_RIGHT = 1 << 1,
COCOABUTTON_MIDDLE = 1 << 2,
COCOABUTTON_4 = 1 << 3,
COCOABUTTON_5 = 1 << 4,
};
enum ECocoaKeyModifier
{
eCapsLockKey,
eShiftKey,
eControlKey,
eAltKey, // aka option
eCommandKey
};
class CCocoaEvent
{
public:
CocoaEventType_t m_EventType;
int m_VirtualKeyCode;
wchar_t m_UnicodeKey;
wchar_t m_UnicodeKeyUnmodified;
uint m_ModifierKeyMask; //
int m_MousePos[2];
int m_MouseButtonFlags; // Current state of the mouse buttons. See COCOABUTTON_xxxx.
uint m_nMouseClickCount;
int m_MouseButton; // which of the CocoaMouseButton_t buttons this is for from above
};
#endif // defined( USE_SDL )
#endif // ILAUNCHERMGR_H

View File

@ -1,4 +1,4 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
@ -30,7 +30,7 @@ public:
CBaseHandle();
CBaseHandle( const CBaseHandle &other );
CBaseHandle( unsigned long value );
CBaseHandle( uint32_t value );
CBaseHandle( int iEntry, int iSerialNumber );
void Init( int iEntry, int iSerialNumber );
@ -63,7 +63,7 @@ public:
protected:
// The low NUM_SERIAL_BITS hold the index. If this value is less than MAX_EDICTS, then the entity is networkable.
// The high NUM_SERIAL_NUM_BITS bits are the serial number.
unsigned long m_Index;
uint32_t m_Index;
};
@ -80,7 +80,7 @@ inline CBaseHandle::CBaseHandle( const CBaseHandle &other )
m_Index = other.m_Index;
}
inline CBaseHandle::CBaseHandle( unsigned long value )
inline CBaseHandle::CBaseHandle( uint32_t value )
{
m_Index = value;
}
@ -92,10 +92,10 @@ inline CBaseHandle::CBaseHandle( int iEntry, int iSerialNumber )
inline void CBaseHandle::Init( int iEntry, int iSerialNumber )
{
Assert( iEntry >= 0 && iEntry < NUM_ENT_ENTRIES );
Assert( iEntry >= 0 && (iEntry & ENT_ENTRY_MASK) == iEntry);
Assert( iSerialNumber >= 0 && iSerialNumber < (1 << NUM_SERIAL_NUM_BITS) );
m_Index = iEntry | (iSerialNumber << NUM_ENT_ENTRY_BITS);
m_Index = iEntry | (iSerialNumber << NUM_SERIAL_NUM_SHIFT_BITS);
}
inline void CBaseHandle::Term()
@ -110,12 +110,26 @@ inline bool CBaseHandle::IsValid() const
inline int CBaseHandle::GetEntryIndex() const
{
// There is a hack here: due to a bug in the original implementation of the
// entity handle system, an attempt to look up an invalid entity index in
// certain cirumstances might fall through to the the mask operation below.
// This would mask an invalid index to be in fact a lookup of entity number
// NUM_ENT_ENTRIES, so invalid ent indexes end up actually looking up the
// last slot in the entities array. Since this slot is always empty, the
// lookup returns NULL and the expected behavior occurs through this unexpected
// route.
// A lot of code actually depends on this behavior, and the bug was only exposed
// after a change to NUM_SERIAL_NUM_BITS increased the number of allowable
// static props in the world. So the if-stanza below detects this case and
// retains the prior (bug-submarining) behavior.
if ( !IsValid() )
return NUM_ENT_ENTRIES-1;
return m_Index & ENT_ENTRY_MASK;
}
inline int CBaseHandle::GetSerialNumber() const
{
return m_Index >> NUM_ENT_ENTRY_BITS;
return m_Index >> NUM_SERIAL_NUM_SHIFT_BITS;
}
inline int CBaseHandle::ToInt() const
@ -150,7 +164,7 @@ inline bool CBaseHandle::operator <( const CBaseHandle &other ) const
inline bool CBaseHandle::operator <( const IHandleEntity *pEntity ) const
{
unsigned long otherIndex = (pEntity) ? pEntity->GetRefEHandle().m_Index : INVALID_EHANDLE_INDEX;
uint32_t otherIndex = (pEntity) ? pEntity->GetRefEHandle().m_Index : INVALID_EHANDLE_INDEX;
return m_Index < otherIndex;
}

View File

@ -1403,7 +1403,7 @@ inline void CBitVecAccessor::operator=(int val)
if(val)
m_pDWords[m_iBit >> 5] |= (1 << (m_iBit & 31));
else
m_pDWords[m_iBit >> 5] &= ~(unsigned long)(1 << (m_iBit & 31));
m_pDWords[m_iBit >> 5] &= ~(uint32_t)(1 << (m_iBit & 31));
}
inline CBitVecAccessor::operator uint32()

View File

@ -660,7 +660,7 @@ public:
CDispCornerNeighbors m_CornerNeighbors[4]; // Indexed by CORNER_ defines.
enum unnamed { ALLOWEDVERTS_SIZE = PAD_NUMBER( MAX_DISPVERTS, 32 ) / 32 };
unsigned long m_AllowedVerts[ALLOWEDVERTS_SIZE]; // This is built based on the layout and sizes of our neighbors
uint32_t m_AllowedVerts[ALLOWEDVERTS_SIZE]; // This is built based on the layout and sizes of our neighbors
// and tells us which vertices are allowed to be active.
};

View File

@ -1,4 +1,4 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
@ -63,13 +63,13 @@
#define SIGNED_GUID_LEN 32 // Hashed CD Key (32 hex alphabetic chars + 0 terminator )
// Used for networking ehandles.
#define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 1)
#define NUM_ENT_ENTRY_BITS (MAX_EDICT_BITS + 2)
#define NUM_ENT_ENTRIES (1 << NUM_ENT_ENTRY_BITS)
#define ENT_ENTRY_MASK (NUM_ENT_ENTRIES - 1)
#define INVALID_EHANDLE_INDEX 0xFFFFFFFF
#define NUM_SERIAL_NUM_BITS (32 - NUM_ENT_ENTRY_BITS)
#define NUM_SERIAL_NUM_SHIFT_BITS 16
// Networked ehandles use less bits to encode the serial number.
#define NUM_NETWORKED_EHANDLE_SERIAL_NUMBER_BITS 10

View File

@ -513,13 +513,15 @@ public:
case DC_AGE_DISCARD:
case DC_FLUSH_DISCARD:
case DC_REMOVED:
{
STORAGE_TYPE *p = (STORAGE_TYPE *)notification.clientId;
p->DestroyResource();
return true;
}
return true;
default:
return CDefaultDataCacheClient::HandleCacheNotification( notification );
}
}
protected:

View File

@ -1,4 +1,4 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
@ -60,6 +60,7 @@ class CSteamID;
class IReplayFactory;
class IReplaySystem;
class IServer;
class WorkshopMapDesc_t;
typedef struct player_info_s player_info_t;
@ -73,6 +74,8 @@ typedef struct player_info_s player_info_t;
#define DLLEXPORT /* */
#endif
#define INTERFACEVERSION_VENGINESERVER_VERSION_21 "VEngineServer021"
#define INTERFACEVERSION_VENGINESERVER_VERSION_22 "VEngineServer022"
#define INTERFACEVERSION_VENGINESERVER "VEngineServer023"
#define INTERFACEVERSION_VENGINESERVER_INT 23
@ -340,9 +343,6 @@ public:
// even though we may not have waited enough time
virtual void AllowImmediateEdictReuse( ) = 0;
// Returns true if the engine is an internal build. i.e. is using the internal bugreporter.
virtual bool IsInternalBuild( void ) = 0;
virtual IChangeInfoAccessor *GetChangeAccessor( const edict_t *pEdict ) = 0;
// Name of most recently load .sav file
@ -410,8 +410,6 @@ public:
// Server version from the steam.inf, this will be compared to the GC version
virtual int GetServerVersion() const = 0;
// Only in VEngineServer022 and later
// Get sv.GetTime()
virtual float GetServerTime() const = 0;
@ -447,14 +445,15 @@ public:
virtual IReplaySystem *GetReplay() = 0;
};
#define INTERFACEVERSION_SERVERGAMEDLL_VERSION_4 "ServerGameDLL004"
#define INTERFACEVERSION_SERVERGAMEDLL_VERSION_5 "ServerGameDLL005"
#define INTERFACEVERSION_SERVERGAMEDLL_VERSION_6 "ServerGameDLL006"
#define INTERFACEVERSION_SERVERGAMEDLL_VERSION_7 "ServerGameDLL007"
// These only differ in new items added to the end
typedef IVEngineServer IVEngineServer021;
typedef IVEngineServer IVEngineServer022;
#define INTERFACEVERSION_SERVERGAMEDLL_VERSION_8 "ServerGameDLL008"
#define INTERFACEVERSION_SERVERGAMEDLL_VERSION_9 "ServerGameDLL009"
#define INTERFACEVERSION_SERVERGAMEDLL "ServerGameDLL010"
#define INTERFACEVERSION_SERVERGAMEDLL_INT 10
#define INTERFACEVERSION_SERVERGAMEDLL_VERSION_10 "ServerGameDLL010"
#define INTERFACEVERSION_SERVERGAMEDLL "ServerGameDLL012"
#define INTERFACEVERSION_SERVERGAMEDLL_INT 12
class IServerGCLobby;
@ -630,6 +629,8 @@ public:
// Called to see if the game server is okay with a manual changelevel or map command
virtual bool IsManualMapChangeOkay( const char **pszReason ) = 0;
virtual bool GetWorkshopMap( unsigned int unk, WorkshopMapDesc_t *pMapDesc ) = 0;
};
typedef IServerGameDLL IServerGameDLL008;

View File

@ -39,6 +39,7 @@ public:
virtual void AddTextOverlay(const Vector& origin, float duration, const char *format, ...) = 0;
virtual void AddTextOverlay(const Vector& origin, int line_offset, float duration, const char *format, ...) = 0;
virtual void AddScreenTextOverlay(float flXPos, float flYPos,float flDuration, int r, int g, int b, int a, const char *text) = 0;
virtual void AddScreenTextOverlay(float flXPos, float flYPos, int line_offset, float flDuration, int r, int g, int b, int a, const char *text) = 0;
virtual void AddSweptBoxOverlay(const Vector& start, const Vector& end, const Vector& mins, const Vector& max, const QAngle & angles, int r, int g, int b, int a, float flDuration) = 0;
virtual void AddGridOverlay(const Vector& origin) = 0;
virtual int ScreenPosition(const Vector& point, Vector& screen) = 0;

View File

@ -420,7 +420,7 @@ public:
virtual bool IsFileWritable( char const *pFileName, const char *pPathID = 0 ) = 0;
virtual bool SetFileWritable( char const *pFileName, bool writable, const char *pPathID = 0 ) = 0;
virtual long GetFileTime( const char *pFileName, const char *pPathID = 0 ) = 0;
virtual int32_t GetFileTime( const char *pFileName, const char *pPathID = 0 ) = 0;
//--------------------------------------------------------
// Reads/writes files to utlbuffers. Use this for optimal read performance when doing open/read/close
@ -505,7 +505,7 @@ public:
// File I/O and info
virtual bool IsDirectory( const char *pFileName, const char *pathID = 0 ) = 0;
virtual void FileTimeToString( char* pStrip, int maxCharsIncludingTerminator, long fileTime ) = 0;
virtual void FileTimeToString( char* pStrip, int maxCharsIncludingTerminator, int32_t fileTime ) = 0;
//--------------------------------------------------------
// Open file operations
@ -716,7 +716,7 @@ public:
virtual bool FullPathToRelativePathEx( const char *pFullpath, const char *pPathId, char *pRelative, int maxlen ) = 0;
virtual int GetPathIndex( const FileNameHandle_t &handle ) = 0;
virtual long GetPathTime( const char *pPath, const char *pPathID ) = 0;
virtual int32_t GetPathTime( const char *pPath, const char *pPathID ) = 0;
virtual DVDMode_t GetDVDMode() = 0;

View File

@ -14,6 +14,8 @@
#include "tier0/platform.h"
#include "appframework/IAppSystem.h"
class CFunctor;
enum LoaderError_t
{
LOADERERROR_NONE = 0,
@ -30,6 +32,8 @@ enum LoaderPriority_t
typedef void ( *QueuedLoaderCallback_t )( void *pContext, void *pContext2, const void *pData, int nSize, LoaderError_t loaderError );
typedef void ( *DynamicResourceCallback_t )( const char *pFilename, void *pContext, void *pContext2 );
struct LoaderJob_t
{
LoaderJob_t()
@ -106,7 +110,7 @@ public:
#define LOADER_DETAIL_LATECOMPLETIONS (1<<2)
#define LOADER_DETAIL_PURGES (1<<3)
#define QUEUEDLOADER_INTERFACE_VERSION "QueuedLoaderVersion001"
#define QUEUEDLOADER_INTERFACE_VERSION "QueuedLoaderVersion004"
abstract_class IQueuedLoader : public IAppSystem
{
public:
@ -122,6 +126,11 @@ public:
// injects a resource into the map's reslist, rejected if not understood
virtual void AddMapResource( const char *pFilename ) = 0;
// dynamically load a map resource
virtual void DynamicLoadMapResource( const char *pFilename, DynamicResourceCallback_t pCallback, void *pContext, void *pContext2 ) = 0;
virtual void QueueDynamicLoadFunctor( CFunctor* pFunctor ) = 0;
virtual bool CompleteDynamicLoad() = 0;
// callback is asynchronous
virtual bool ClaimAnonymousJob( const char *pFilename, QueuedLoaderCallback_t pCallback, void *pContext, void *pContext2 = NULL ) = 0;
// provides data if loaded, caller owns data
@ -134,6 +143,8 @@ public:
// callers can expect that jobs are not immediately started when batching
virtual bool IsBatching() const = 0;
virtual bool IsDynamic() const = 0;
// callers can conditionalize operational spew
virtual int GetSpewDetail() const = 0;

View File

@ -1,4 +1,4 @@
//====== Copyright © 1996-2004, Valve Corporation, All rights reserved. =======
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
@ -6,21 +6,24 @@
#undef PROTECTED_THINGS_ENABLE
#undef PROTECT_FILEIO_FUNCTIONS
#ifndef POSIX
#undef fopen
#endif
#if defined( _WIN32 ) && !defined( _X360 )
#include <windows.h>
#include <direct.h>
#include <io.h>
#include <process.h>
#elif defined( _LINUX ) || defined( __APPLE__ )
#elif defined( POSIX )
#include <unistd.h>
#define _putenv putenv
#define _chdir chdir
#define _access access
#endif
#include <stdio.h>
#include <sys/stat.h>
#include "tier1/strtools.h"
#include "tier1/utlbuffer.h"
#include "filesystem_init.h"
#include "tier0/icommandline.h"
#include "KeyValues.h"
@ -83,7 +86,7 @@ public:
if ( pValue )
{
m_bExisted = true;
m_OriginalValue.SetSize( strlen( pValue ) + 1 );
m_OriginalValue.SetSize( Q_strlen( pValue ) + 1 );
memcpy( m_OriginalValue.Base(), pValue, m_OriginalValue.Count() );
}
else
@ -144,16 +147,24 @@ public:
Q_vsnprintf( valueString, sizeof( valueString ), pValue, marker );
va_end( marker );
#ifdef WIN32
char str[4096];
Q_snprintf( str, sizeof( str ), "%s=%s", m_pVarName, valueString );
_putenv( str );
#else
setenv( m_pVarName, valueString, 1 );
#endif
}
void ClearValue()
{
#ifdef WIN32
char str[512];
Q_snprintf( str, sizeof( str ), "%s=", m_pVarName );
_putenv( str );
#else
setenv( m_pVarName, "", 1 );
#endif
}
private:
@ -213,6 +224,7 @@ CFSSearchPathsInit::CFSSearchPathsInit()
m_pDirectoryName = NULL;
m_pLanguage = NULL;
m_ModPath[0] = 0;
m_bMountHDContent = m_bLowViolence = false;
}
@ -248,47 +260,6 @@ const char *FileSystem_GetLastErrorString()
}
void AddLanguageGameDir( IFileSystem *pFileSystem, const char *pLocation, const char *pLanguage )
{
if ( IsX360() )
{
// 360 does not use this path for localization
return;
}
#if !defined( SWDS )
char temp[MAX_PATH];
Q_snprintf( temp, sizeof(temp), "%s_%s", pLocation, pLanguage );
pFileSystem->AddSearchPath( temp, "GAME", PATH_ADD_TO_TAIL );
if ( !pFileSystem->IsSteam() )
{
// also look in "..\localization\<folder>" if not running Steam
char baseDir[MAX_PATH];
char *tempPtr = NULL, *gameDir = NULL;
Q_strncpy( baseDir, pLocation, sizeof(baseDir) );
tempPtr = Q_strstr( baseDir, "\\game\\" );
if ( tempPtr )
{
gameDir = tempPtr + Q_strlen( "\\game\\" );
*tempPtr = 0;
Q_snprintf( temp, sizeof(temp), "%s%clocalization%c%s_%s", baseDir, CORRECT_PATH_SEPARATOR, CORRECT_PATH_SEPARATOR, gameDir, pLanguage );
pFileSystem->AddSearchPath( temp, "GAME", PATH_ADD_TO_TAIL );
}
}
#endif
}
void AddGameBinDir( IFileSystem *pFileSystem, const char *pLocation )
{
char temp[MAX_PATH];
Q_snprintf( temp, sizeof(temp), "%s%cbin", pLocation, CORRECT_PATH_SEPARATOR );
pFileSystem->AddSearchPath( temp, "GAMEBIN", PATH_ADD_TO_TAIL );
}
KeyValues* ReadKeyValuesFile( const char *pFilename )
{
// Read in the gameinfo.txt file and null-terminate it.
@ -376,7 +347,8 @@ bool FileSystem_GetExecutableDir( char *exedir, int exeDirLen )
Q_StrRight( exedir, 4, ext, sizeof( ext ) );
if ( ext[0] != CORRECT_PATH_SEPARATOR || Q_stricmp( ext+1, "bin" ) != 0 )
{
Q_strncat( exedir, "\\bin", exeDirLen, COPY_ALL_CHARACTERS );
Q_strncat( exedir, CORRECT_PATH_SEPARATOR_S, exeDirLen, COPY_ALL_CHARACTERS );
Q_strncat( exedir, "bin", exeDirLen, COPY_ALL_CHARACTERS );
Q_FixSlashes( exedir );
}
@ -489,124 +461,73 @@ FSReturnCode_t LoadGameInfoFile(
return FS_OK;
}
// checks the registry for the low violence setting
// Check "HKEY_CURRENT_USER\Software\Valve\Source\Settings" and "User Token 2" or "User Token 3"
bool IsLowViolenceBuild( void )
{
#if defined(_WIN32)
HKEY hKey;
char szValue[64];
unsigned long len = sizeof(szValue) - 1;
bool retVal = false;
if ( IsPC() && RegOpenKeyEx( HKEY_CURRENT_USER, "Software\\Valve\\Source\\Settings", NULL, KEY_READ, &hKey) == ERROR_SUCCESS )
{
// User Token 2
if ( RegQueryValueEx( hKey, "User Token 2", NULL, NULL, (unsigned char*)szValue, &len ) == ERROR_SUCCESS )
{
if ( Q_strlen( szValue ) > 0 )
{
retVal = true;
}
}
if ( !retVal )
{
// reset "len" for the next check
len = sizeof(szValue) - 1;
// User Token 3
if ( RegQueryValueEx( hKey, "User Token 3", NULL, NULL, (unsigned char*)szValue, &len ) == ERROR_SUCCESS )
{
if ( Q_strlen( szValue ) > 0 )
{
retVal = true;
}
}
}
RegCloseKey(hKey);
}
return retVal;
#elif _LINUX
return false;
#else
#error "Fix me"
#endif
}
static void FileSystem_AddLoadedSearchPath(
CFSSearchPathsInit &initInfo,
const char *pPathID,
bool *bFirstGamePath,
const char *pBaseDir,
const char *pLocation,
const char *fullLocationPath,
bool bLowViolence )
{
char fullLocationPath[MAX_PATH];
Q_MakeAbsolutePath( fullLocationPath, sizeof( fullLocationPath ), pLocation, pBaseDir );
// Now resolve any ./'s.
V_FixSlashes( fullLocationPath );
if ( !V_RemoveDotSlashes( fullLocationPath ) )
Error( "FileSystem_AddLoadedSearchPath - Can't resolve pathname for '%s'", fullLocationPath );
// Check for mounting LV game content in LV builds only
if ( V_stricmp( pPathID, "game_lv" ) == 0 )
{
// Add language, mod, and gamebin search paths automatically.
if ( Q_stricmp( pPathID, "game" ) == 0 )
{
// add the low violence path
if ( bLowViolence )
{
char szPath[MAX_PATH];
Q_snprintf( szPath, sizeof(szPath), "%s_lv", fullLocationPath );
initInfo.m_pFileSystem->AddSearchPath( szPath, pPathID, PATH_ADD_TO_TAIL );
// Not in LV build, don't mount
if ( !initInfo.m_bLowViolence )
return;
// Mount, as a game path
pPathID = "game";
}
// add the language path
if ( initInfo.m_pLanguage )
// Check for mounting HD game content if enabled
if ( V_stricmp( pPathID, "game_hd" ) == 0 )
{
AddLanguageGameDir( initInfo.m_pFileSystem, fullLocationPath, initInfo.m_pLanguage );
// Not in LV build, don't mount
if ( !initInfo.m_bMountHDContent )
return;
// Mount, as a game path
pPathID = "game";
}
// Special processing for ordinary game folders
if ( V_stristr( fullLocationPath, ".vpk" ) == NULL && Q_stricmp( pPathID, "game" ) == 0 )
{
if ( CommandLine()->FindParm( "-tempcontent" ) != 0 )
{
char szPath[MAX_PATH];
Q_snprintf( szPath, sizeof(szPath), "%s_tempcontent", fullLocationPath );
initInfo.m_pFileSystem->AddSearchPath( szPath, pPathID, PATH_ADD_TO_TAIL );
}
// mark the first "game" dir as the "MOD" dir
if ( *bFirstGamePath )
{
*bFirstGamePath = false;
initInfo.m_pFileSystem->AddSearchPath( fullLocationPath, "MOD", PATH_ADD_TO_TAIL );
Q_strncpy( initInfo.m_ModPath, fullLocationPath, sizeof( initInfo.m_ModPath ) );
}
// add the game bin
AddGameBinDir( initInfo.m_pFileSystem, fullLocationPath );
if ( initInfo.m_pLanguage &&
Q_stricmp( initInfo.m_pLanguage, "english" ) &&
V_strstr( fullLocationPath, "_english" ) != NULL )
{
char szPath[MAX_PATH];
char szLangString[MAX_PATH];
// Need to add a language version of this path first
Q_snprintf( szLangString, sizeof(szLangString), "_%s", initInfo.m_pLanguage);
V_StrSubst( fullLocationPath, "_english", szLangString, szPath, sizeof( szPath ), true );
initInfo.m_pFileSystem->AddSearchPath( szPath, pPathID, PATH_ADD_TO_TAIL );
}
initInfo.m_pFileSystem->AddSearchPath( fullLocationPath, pPathID, PATH_ADD_TO_TAIL );
}
bool FileSystem_IsHldsUpdateToolDedicatedServer()
static int SortStricmp( char * const * sz1, char * const * sz2 )
{
// To determine this, we see if the directory our executable was launched from is "orangebox".
// We only are under "orangebox" if we're run from hldsupdatetool.
char baseDir[MAX_PATH];
if ( !FileSystem_GetBaseDir( baseDir, sizeof( baseDir ) ) )
return false;
V_FixSlashes( baseDir );
V_StripTrailingSlash( baseDir );
const char *pLastDir = V_UnqualifiedFileName( baseDir );
return ( pLastDir && V_stricmp( pLastDir, "orangebox" ) == 0 );
return V_stricmp( *sz1, *sz2 );
}
FSReturnCode_t FileSystem_LoadSearchPaths( CFSSearchPathsInit &initInfo )
{
if ( !initInfo.m_pFileSystem || !initInfo.m_pDirectoryName )
@ -622,23 +543,41 @@ FSReturnCode_t FileSystem_LoadSearchPaths( CFSSearchPathsInit &initInfo )
if ( !FileSystem_GetBaseDir( baseDir, sizeof( baseDir ) ) )
return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetBaseDir failed." );
initInfo.m_ModPath[0] = 0;
// The MOD directory is always the one that contains gameinfo.txt
Q_strncpy( initInfo.m_ModPath, initInfo.m_pDirectoryName, sizeof( initInfo.m_ModPath ) );
#define GAMEINFOPATH_TOKEN "|gameinfo_path|"
#define BASESOURCEPATHS_TOKEN "|all_source_engine_paths|"
bool bLowViolence = IsLowViolenceBuild();
bool bFirstGamePath = true;
const char *pszExtraSearchPath = CommandLine()->ParmValue( "-insert_search_path" );
if ( pszExtraSearchPath )
{
CUtlStringList vecPaths;
V_SplitString( pszExtraSearchPath, ",", vecPaths );
FOR_EACH_VEC( vecPaths, idxExtraPath )
{
char szAbsSearchPath[MAX_PATH];
Q_StripPrecedingAndTrailingWhitespace( vecPaths[ idxExtraPath ] );
V_MakeAbsolutePath( szAbsSearchPath, sizeof( szAbsSearchPath ), vecPaths[ idxExtraPath ], baseDir );
V_FixSlashes( szAbsSearchPath );
if ( !V_RemoveDotSlashes( szAbsSearchPath ) )
Error( "Bad -insert_search_path - Can't resolve pathname for '%s'", szAbsSearchPath );
V_StripTrailingSlash( szAbsSearchPath );
FileSystem_AddLoadedSearchPath( initInfo, "GAME", szAbsSearchPath, false );
FileSystem_AddLoadedSearchPath( initInfo, "MOD", szAbsSearchPath, false );
}
}
bool bLowViolence = initInfo.m_bLowViolence;
for ( KeyValues *pCur=pSearchPaths->GetFirstValue(); pCur; pCur=pCur->GetNextValue() )
{
const char *pPathID = pCur->GetName();
const char *pLocation = pCur->GetString();
const char *pszBaseDir = baseDir;
if ( Q_stristr( pLocation, GAMEINFOPATH_TOKEN ) == pLocation )
{
pLocation += strlen( GAMEINFOPATH_TOKEN );
FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, initInfo.m_pDirectoryName, pLocation, bLowViolence );
pszBaseDir = initInfo.m_pDirectoryName;
}
else if ( Q_stristr( pLocation, BASESOURCEPATHS_TOKEN ) == pLocation )
{
@ -650,26 +589,117 @@ FSReturnCode_t FileSystem_LoadSearchPaths( CFSSearchPathsInit &initInfo )
// We need a special identifier in the gameinfo.txt here because the base hl2 folder exists in different places.
// In the case of a game or a Steam-launched dedicated server, all the necessary prior engine content is mapped in with the Steam depots,
// so we can just use the path as-is.
// In the case of an hldsupdatetool dedicated server, the base hl2 folder is "..\..\hl2" (since we're up in the 'orangebox' folder).
pLocation += strlen( BASESOURCEPATHS_TOKEN );
// Add the Orange-box path (which also will include whatever the depots mapped in as well if we're
// running a Steam-launched app).
FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, baseDir, pLocation, bLowViolence );
if ( FileSystem_IsHldsUpdateToolDedicatedServer() )
{
// If we're using the hldsupdatetool dedicated server, then go up a directory to get the ep1-era files too.
char ep1EraPath[MAX_PATH];
V_snprintf( ep1EraPath, sizeof( ep1EraPath ), "..%c%s", CORRECT_PATH_SEPARATOR, pLocation );
FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, baseDir, ep1EraPath, bLowViolence );
}
CUtlStringList vecFullLocationPaths;
char szAbsSearchPath[MAX_PATH];
V_MakeAbsolutePath( szAbsSearchPath, sizeof( szAbsSearchPath ), pLocation, pszBaseDir );
// Now resolve any ./'s.
V_FixSlashes( szAbsSearchPath );
if ( !V_RemoveDotSlashes( szAbsSearchPath ) )
Error( "FileSystem_AddLoadedSearchPath - Can't resolve pathname for '%s'", szAbsSearchPath );
V_StripTrailingSlash( szAbsSearchPath );
// Don't bother doing any wildcard expansion unless it has wildcards. This avoids the weird
// thing with xxx_dir.vpk files being referred to simply as xxx.vpk.
if ( V_stristr( pLocation, "?") == NULL && V_stristr( pLocation, "*") == NULL )
{
vecFullLocationPaths.CopyAndAddToTail( szAbsSearchPath );
}
else
{
FileSystem_AddLoadedSearchPath( initInfo, pPathID, &bFirstGamePath, baseDir, pLocation, bLowViolence );
FileFindHandle_t findHandle = 0;
const char *pszFoundShortName = initInfo.m_pFileSystem->FindFirst( szAbsSearchPath, &findHandle );
if ( pszFoundShortName )
{
do
{
// We only know how to mount VPK's and directories
if ( pszFoundShortName[0] != '.' && ( initInfo.m_pFileSystem->FindIsDirectory( findHandle ) || V_stristr( pszFoundShortName, ".vpk" ) ) )
{
char szAbsName[MAX_PATH];
V_ExtractFilePath( szAbsSearchPath, szAbsName, sizeof( szAbsName ) );
V_AppendSlash( szAbsName, sizeof(szAbsName) );
V_strcat_safe( szAbsName, pszFoundShortName );
vecFullLocationPaths.CopyAndAddToTail( szAbsName );
// Check for a common mistake
if (
!V_stricmp( pszFoundShortName, "materials" )
|| !V_stricmp( pszFoundShortName, "maps" )
|| !V_stricmp( pszFoundShortName, "resource" )
|| !V_stricmp( pszFoundShortName, "scripts" )
|| !V_stricmp( pszFoundShortName, "sound" )
|| !V_stricmp( pszFoundShortName, "models" ) )
{
char szReadme[MAX_PATH];
V_ExtractFilePath( szAbsSearchPath, szReadme, sizeof( szReadme ) );
V_AppendSlash( szReadme, sizeof(szReadme) );
V_strcat_safe( szReadme, "readme.txt" );
Error(
"Tried to add %s as a search path.\n"
"\nThis is probably not what you intended.\n"
"\nCheck %s for more info\n",
szAbsName, szReadme );
}
}
pszFoundShortName = initInfo.m_pFileSystem->FindNext( findHandle );
} while ( pszFoundShortName );
initInfo.m_pFileSystem->FindClose( findHandle );
}
// Sort alphabetically. Also note that this will put
// all the xxx_000.vpk packs just before the corresponding
// xxx_dir.vpk
vecFullLocationPaths.Sort( SortStricmp );
// Now for any _dir.vpk files, remove the _nnn.vpk ones.
int idx = vecFullLocationPaths.Count()-1;
while ( idx > 0 )
{
char szTemp[ MAX_PATH ];
V_strcpy_safe( szTemp, vecFullLocationPaths[ idx ] );
--idx;
char *szDirVpk = V_stristr( szTemp, "_dir.vpk" );
if ( szDirVpk != NULL )
{
*szDirVpk = '\0';
while ( idx >= 0 )
{
char *pszPath = vecFullLocationPaths[ idx ];
if ( V_stristr( pszPath, szTemp ) != pszPath )
break;
delete pszPath;
vecFullLocationPaths.Remove( idx );
--idx;
}
}
}
}
// Parse Path ID list
CUtlStringList vecPathIDs;
V_SplitString( pCur->GetName(), "+", vecPathIDs );
FOR_EACH_VEC( vecPathIDs, idxPathID )
{
Q_StripPrecedingAndTrailingWhitespace( vecPathIDs[ idxPathID ] );
}
// Mount them.
FOR_EACH_VEC( vecFullLocationPaths, idxLocation )
{
FOR_EACH_VEC( vecPathIDs, idxPathID )
{
FileSystem_AddLoadedSearchPath( initInfo, vecPathIDs[ idxPathID ], vecFullLocationPaths[ idxLocation ], bLowViolence );
}
}
}
@ -679,15 +709,13 @@ FSReturnCode_t FileSystem_LoadSearchPaths( CFSSearchPathsInit &initInfo )
// when people forget to specify a search path.
initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "executable_path", true );
initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "gamebin", true );
initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "download", true );
initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "mod", true );
if ( initInfo.m_ModPath[0] != 0 )
{
// Add the write path last.
initInfo.m_pFileSystem->AddSearchPath( initInfo.m_ModPath, "DEFAULT_WRITE_PATH", PATH_ADD_TO_TAIL );
}
initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "game_write", true );
initInfo.m_pFileSystem->MarkPathIDByRequestOnly( "mod_write", true );
#ifdef _DEBUG
initInfo.m_pFileSystem->PrintSearchPaths();
// initInfo.m_pFileSystem->PrintSearchPaths();
#endif
return FS_OK;
@ -954,60 +982,6 @@ bool DoesPathExistAlready( const char *pPathEnvVar, const char *pTestPath )
}
}
FSReturnCode_t SetSteamInstallPath( char *steamInstallPath, int steamInstallPathLen, CSteamEnvVars &steamEnvVars, bool bErrorsAsWarnings )
{
if ( IsConsole() )
{
// consoles don't use steam
return FS_MISSING_STEAM_DLL;
}
// Start at our bin directory and move up until we find a directory with steam.dll in it.
char executablePath[MAX_PATH];
if ( !FileSystem_GetExecutableDir( executablePath, sizeof( executablePath ) ) )
{
if ( bErrorsAsWarnings )
{
Warning( "SetSteamInstallPath: FileSystem_GetExecutableDir failed.\n" );
return FS_INVALID_PARAMETERS;
}
else
{
return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetExecutableDir failed." );
}
}
Q_strncpy( steamInstallPath, executablePath, steamInstallPathLen );
while ( 1 )
{
// Ignore steamapp.cfg here in case they're debugging. We still need to know the real steam path so we can find their username.
// find
if ( DoesFileExistIn( steamInstallPath, "steam.dll" ) && !DoesFileExistIn( steamInstallPath, "steamapp.cfg" ) )
break;
if ( !Q_StripLastDir( steamInstallPath, steamInstallPathLen ) )
{
if ( bErrorsAsWarnings )
{
Warning( "Can't find steam.dll relative to executable path: %s.\n", executablePath );
return FS_MISSING_STEAM_DLL;
}
else
{
return SetupFileSystemError( false, FS_MISSING_STEAM_DLL, "Can't find steam.dll relative to executable path: %s.", executablePath );
}
}
}
// Also, add the install path to their PATH environment variable, so filesystem_steam.dll can get to steam.dll.
char szPath[ 8192 ];
steamEnvVars.m_Path.GetValue( szPath, sizeof( szPath ) );
if ( !DoesPathExistAlready( szPath, steamInstallPath ) )
{
steamEnvVars.m_Path.SetValue( "%s;%s", szPath, steamInstallPath );
}
return FS_OK;
}
FSReturnCode_t GetSteamCfgPath( char *steamCfgPath, int steamCfgPathLen )
{
@ -1087,53 +1061,6 @@ void SetSteamUserPassphrase( KeyValues *pSteamInfo, CSteamEnvVars &steamEnvVars
}
}
void SetSteamAppId( KeyValues *pFileSystemInfo, const char *pGameInfoDirectory, CSteamEnvVars &steamEnvVars )
{
// SteamAppId is in gameinfo.txt->FileSystem->FileSystemInfo_Steam->SteamAppId.
int iAppId = pFileSystemInfo->GetInt( "SteamAppId", -1 );
if ( iAppId == -1 )
Error( "Missing SteamAppId in %s\\%s.", pGameInfoDirectory, GAMEINFO_FILENAME );
steamEnvVars.m_SteamAppId.SetValue( "%d", iAppId );
}
FSReturnCode_t SetupSteamStartupEnvironment( KeyValues *pFileSystemInfo, const char *pGameInfoDirectory, CSteamEnvVars &steamEnvVars )
{
// Ok, we're going to run Steam. See if they have SteamInfo.txt. If not, we'll try to deduce what we can.
char steamInfoFile[MAX_PATH];
Q_strncpy( steamInfoFile, pGameInfoDirectory, sizeof( steamInfoFile ) );
Q_AppendSlash( steamInfoFile, sizeof( steamInfoFile ) );
Q_strncat( steamInfoFile, "steaminfo.txt", sizeof( steamInfoFile ), COPY_ALL_CHARACTERS );
KeyValues *pSteamInfo = ReadKeyValuesFile( steamInfoFile );
char steamInstallPath[MAX_PATH];
FSReturnCode_t ret = SetSteamInstallPath( steamInstallPath, sizeof( steamInstallPath ), steamEnvVars, false );
if ( ret != FS_OK )
return ret;
SetSteamAppUser( pSteamInfo, steamInstallPath, steamEnvVars );
SetSteamUserPassphrase( pSteamInfo, steamEnvVars );
SetSteamAppId( pFileSystemInfo, pGameInfoDirectory, steamEnvVars );
if ( pSteamInfo )
pSteamInfo->deleteThis();
return FS_OK;
}
FSReturnCode_t GetSteamExtraAppId( const char *pDirectoryName, int *nExtraAppId )
{
// Now, load gameinfo.txt (to make sure it's there)
KeyValues *pMainFile, *pFileSystemInfo, *pSearchPaths;
FSReturnCode_t ret = LoadGameInfoFile( pDirectoryName, pMainFile, pFileSystemInfo, pSearchPaths );
if ( ret != FS_OK )
return ret;
*nExtraAppId = pFileSystemInfo->GetInt( "ToolsAppId", -1 );
pMainFile->deleteThis();
return FS_OK;
}
FSReturnCode_t FileSystem_SetBasePaths( IFileSystem *pFileSystem )
{
pFileSystem->RemoveSearchPaths( "EXECUTABLE_PATH" );
@ -1143,6 +1070,12 @@ FSReturnCode_t FileSystem_SetBasePaths( IFileSystem *pFileSystem )
return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetExecutableDir failed." );
pFileSystem->AddSearchPath( executablePath, "EXECUTABLE_PATH" );
if ( !FileSystem_GetBaseDir( executablePath, sizeof( executablePath ) ) )
return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetBaseDir failed." );
pFileSystem->AddSearchPath( executablePath, "BASE_PATH" );
return FS_OK;
}
@ -1159,40 +1092,30 @@ FSReturnCode_t FileSystem_GetFileSystemDLLName( char *pFileSystemDLL, int nMaxLe
if ( !FileSystem_GetExecutableDir( executablePath, sizeof( executablePath ) ) )
return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetExecutableDir failed." );
#if defined( _WIN32 ) && !defined( _X360 )
// If filesystem_stdio.dll is missing or -steam is specified, then load filesystem_steam.dll.
// There are two command line parameters for Steam:
// 1) -steam (runs Steam in remote filesystem mode; requires Steam backend)
// 2) -steamlocal (runs Steam in local filesystem mode (all content off HDD)
Q_snprintf( pFileSystemDLL, nMaxLen, "%s%cfilesystem_stdio.dll", executablePath, CORRECT_PATH_SEPARATOR );
if ( CommandLine()->FindParm( "-steam" ) || CommandLine()->FindParm( "-steamlocal" ) || _access( pFileSystemDLL, 0 ) != 0 )
{
Q_snprintf( pFileSystemDLL, nMaxLen, "%s%cfilesystem_steam.dll", executablePath, CORRECT_PATH_SEPARATOR );
// Assume we'll use local files
Q_snprintf( pFileSystemDLL, nMaxLen, "%s%cfilesystem_stdio" DLL_EXT_STRING, executablePath, CORRECT_PATH_SEPARATOR );
#if !defined( _X360 )
// Use filsystem_steam if it exists?
#if defined( OSX ) || defined( LINUX )
struct stat statBuf;
#endif
if (
#if defined( OSX ) || defined( LINUX )
stat( pFileSystemDLL, &statBuf ) != 0
#else
_access( pFileSystemDLL, 0 ) != 0
#endif
) {
Q_snprintf( pFileSystemDLL, nMaxLen, "%s%cfilesystem_steam" DLL_EXT_STRING, executablePath, CORRECT_PATH_SEPARATOR );
bSteam = true;
}
#elif defined( _X360 )
Q_snprintf( pFileSystemDLL, nMaxLen, "%s%cfilesystem_stdio.dll", executablePath, CORRECT_PATH_SEPARATOR );
#elif defined( _LINUX )
Q_snprintf( pFileSystemDLL, nMaxLen, "%s%cfilesystem_i486.so", executablePath, CORRECT_PATH_SEPARATOR );
#else
#error "define a filesystem dll name"
#endif
return FS_OK;
}
//-----------------------------------------------------------------------------
// Sets up the steam.dll install path in our PATH env var (so you can then just
// LoadLibrary() on filesystem_steam.dll without having to copy steam.dll anywhere special )
//-----------------------------------------------------------------------------
FSReturnCode_t FileSystem_SetupSteamInstallPath()
{
CSteamEnvVars steamEnvVars;
char steamInstallPath[MAX_PATH];
FSReturnCode_t ret = SetSteamInstallPath( steamInstallPath, sizeof( steamInstallPath ), steamEnvVars, true );
steamEnvVars.m_Path.SetRestoreOriginalValue( false ); // We want to keep the change to the path going forward.
return ret;
}
//-----------------------------------------------------------------------------
// Sets up the steam environment + gets back the gameinfo.txt path
@ -1205,45 +1128,13 @@ FSReturnCode_t FileSystem_SetupSteamEnvironment( CFSSteamSetupInfo &fsInfo )
return ret;
// This is so that processes spawned by this application will have the same VPROJECT
#ifdef WIN32
char pEnvBuf[MAX_PATH+32];
Q_snprintf( pEnvBuf, sizeof(pEnvBuf), "%s=%s", GAMEDIR_TOKEN, fsInfo.m_GameInfoPath );
_putenv( pEnvBuf );
CSteamEnvVars steamEnvVars;
if ( fsInfo.m_bSteam )
{
if ( fsInfo.m_bToolsMode )
{
// Now, load gameinfo.txt (to make sure it's there)
KeyValues *pMainFile, *pFileSystemInfo, *pSearchPaths;
ret = LoadGameInfoFile( fsInfo.m_GameInfoPath, pMainFile, pFileSystemInfo, pSearchPaths );
if ( ret != FS_OK )
return ret;
// If filesystem_stdio.dll is missing or -steam is specified, then load filesystem_steam.dll.
// There are two command line parameters for Steam:
// 1) -steam (runs Steam in remote filesystem mode; requires Steam backend)
// 2) -steamlocal (runs Steam in local filesystem mode (all content off HDD)
// Setup all the environment variables related to Steam so filesystem_steam.dll knows how to initialize Steam.
ret = SetupSteamStartupEnvironment( pFileSystemInfo, fsInfo.m_GameInfoPath, steamEnvVars );
if ( ret != FS_OK )
return ret;
steamEnvVars.m_SteamAppId.SetRestoreOriginalValue( false ); // We want to keep the change to the path going forward.
// We're done with main file
pMainFile->deleteThis();
}
else if ( fsInfo.m_bSetSteamDLLPath )
{
// This is used by the engine to automatically set the path to their steam.dll when running the engine,
// so they can debug it without having to copy steam.dll up into their hl2.exe folder.
char steamInstallPath[MAX_PATH];
ret = SetSteamInstallPath( steamInstallPath, sizeof( steamInstallPath ), steamEnvVars, true );
steamEnvVars.m_Path.SetRestoreOriginalValue( false ); // We want to keep the change to the path going forward.
}
}
#else
setenv( GAMEDIR_TOKEN, fsInfo.m_GameInfoPath, 1 );
#endif
return FS_OK;
}
@ -1287,33 +1178,33 @@ FSReturnCode_t FileSystem_MountContent( CFSMountContentInfo &mountContentInfo )
// This part is Steam-only.
if ( mountContentInfo.m_pFileSystem->IsSteam() )
{
// Find out the "extra app id". This is for tools, which want to mount a base app's filesystem
// like HL2, then mount the SDK content (tools materials and models, etc) in addition.
int nExtraAppId = -1;
if ( mountContentInfo.m_bToolsMode )
{
FSReturnCode_t ret = GetSteamExtraAppId( mountContentInfo.m_pDirectoryName, &nExtraAppId );
if ( ret != FS_OK )
return ret;
}
return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "Should not be using filesystem_steam anymore!" );
// Set our working directory temporarily so Steam can remember it.
// This is what Steam strips off absolute filenames like c:\program files\valve\steam\steamapps\username\sourcesdk
// to get to the relative part of the path.
char baseDir[MAX_PATH], oldWorkingDir[MAX_PATH];
if ( !FileSystem_GetBaseDir( baseDir, sizeof( baseDir ) ) )
return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetBaseDir failed." );
Q_getwd( oldWorkingDir, sizeof( oldWorkingDir ) );
_chdir( baseDir );
// Filesystem_tools needs to add dependencies in here beforehand.
FilesystemMountRetval_t retVal = mountContentInfo.m_pFileSystem->MountSteamContent( nExtraAppId );
_chdir( oldWorkingDir );
if ( retVal != FILESYSTEM_MOUNT_OK )
return SetupFileSystemError( true, FS_UNABLE_TO_INIT, "Unable to mount Steam content in the file system" );
// // Find out the "extra app id". This is for tools, which want to mount a base app's filesystem
// // like HL2, then mount the SDK content (tools materials and models, etc) in addition.
// int nExtraAppId = -1;
// if ( mountContentInfo.m_bToolsMode )
// {
// // !FIXME! Here we need to mount the tools content (VPK's) in some way...?
// }
//
// // Set our working directory temporarily so Steam can remember it.
// // This is what Steam strips off absolute filenames like c:\program files\valve\steam\steamapps\username\sourcesdk
// // to get to the relative part of the path.
// char baseDir[MAX_PATH], oldWorkingDir[MAX_PATH];
// if ( !FileSystem_GetBaseDir( baseDir, sizeof( baseDir ) ) )
// return SetupFileSystemError( false, FS_INVALID_PARAMETERS, "FileSystem_GetBaseDir failed." );
//
// Q_getwd( oldWorkingDir, sizeof( oldWorkingDir ) );
// _chdir( baseDir );
//
// // Filesystem_tools needs to add dependencies in here beforehand.
// FilesystemMountRetval_t retVal = mountContentInfo.m_pFileSystem->MountSteamContent( nExtraAppId );
//
// _chdir( oldWorkingDir );
//
// if ( retVal != FILESYSTEM_MOUNT_OK )
// return SetupFileSystemError( true, FS_UNABLE_TO_INIT, "Unable to mount Steam content in the file system" );
}
return FileSystem_SetBasePaths( mountContentInfo.m_pFileSystem );
@ -1342,17 +1233,9 @@ void FileSystem_ClearSteamEnvVars()
void FileSystem_AddSearchPath_Platform( IFileSystem *pFileSystem, const char *szGameInfoPath )
{
char platform[MAX_PATH];
if ( pFileSystem->IsSteam() )
{
// Steam doesn't support relative paths
Q_strncpy( platform, "platform", MAX_PATH );
}
else
{
Q_strncpy( platform, szGameInfoPath, MAX_PATH );
Q_StripTrailingSlash( platform );
Q_strncat( platform, "/../platform", MAX_PATH, MAX_PATH );
}
pFileSystem->AddSearchPath( platform, "PLATFORM" );
}

View File

@ -1,4 +1,4 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
@ -148,14 +148,17 @@ public:
// This specifies the directory where gameinfo.txt is. This must be set.
const char *m_pDirectoryName;
// If this is set, then it will add a search path with _<language> appended to the pathname
// for each search path with a path ID of "game".
// If this is set, then any search paths with a _english will be replaced with _m_pLanguage and added before the
// _english path
// (default: null)
const char *m_pLanguage;
// This is the filesystem FileSystem_LoadSearchPaths is talking to.
IFileSystem *m_pFileSystem;
bool m_bMountHDContent;
bool m_bLowViolence;
// Outputs.
public:
// This is the location of the first search path called "game", which also becomes your "mod" search path.
@ -206,11 +209,6 @@ void FileSystem_ClearSteamEnvVars();
// Find the steam.cfg above you for optional stuff
FSReturnCode_t GetSteamCfgPath( char *steamCfgPath, int steamCfgPathLen );
// Setup the Steam.dll path without needing all the extra gameinfo stuff first
// used by the CSteamApplication::Create() code to LoadModule() on the filesystem
// before the underlying apps know specific details about the environment to load
FSReturnCode_t FileSystem_SetupSteamInstallPath();
// Returns the last error.
const char *FileSystem_GetLastErrorString();

View File

@ -52,7 +52,7 @@ public:
virtual bool FileExists( const char *pFileName, const char *pPathID ) { return m_pBaseFileSystemPassThru->FileExists( pFileName, pPathID ); }
virtual bool IsFileWritable( char const *pFileName, const char *pPathID ) { return m_pBaseFileSystemPassThru->IsFileWritable( pFileName, pPathID ); }
virtual bool SetFileWritable( char const *pFileName, bool writable, const char *pPathID ) { return m_pBaseFileSystemPassThru->SetFileWritable( pFileName, writable, pPathID ); }
virtual long GetFileTime( const char *pFileName, const char *pPathID ) { return m_pBaseFileSystemPassThru->GetFileTime( pFileName, pPathID ); }
virtual int32_t GetFileTime( const char *pFileName, const char *pPathID ) { return m_pBaseFileSystemPassThru->GetFileTime( pFileName, pPathID ); }
virtual bool ReadFile( const char *pFileName, const char *pPath, CUtlBuffer &buf, int nMaxBytes = 0, int nStartingByte = 0, FSAllocFunc_t pfnAlloc = NULL ) { return m_pBaseFileSystemPassThru->ReadFile( pFileName, pPath, buf, nMaxBytes, nStartingByte, pfnAlloc ); }
virtual bool WriteFile( const char *pFileName, const char *pPath, CUtlBuffer &buf ) { return m_pBaseFileSystemPassThru->WriteFile( pFileName, pPath, buf ); }
virtual bool UnzipFile( const char *pFileName, const char *pPath, const char *pDestination ) { return m_pBaseFileSystemPassThru->UnzipFile( pFileName, pPath, pDestination ); }
@ -100,7 +100,7 @@ public:
virtual bool RenameFile( char const *pOldPath, char const *pNewPath, const char *pathID ) { return m_pFileSystemPassThru->RenameFile( pOldPath, pNewPath, pathID ); }
virtual void CreateDirHierarchy( const char *path, const char *pathID ) { m_pFileSystemPassThru->CreateDirHierarchy( path, pathID ); }
virtual bool IsDirectory( const char *pFileName, const char *pathID ) { return m_pFileSystemPassThru->IsDirectory( pFileName, pathID ); }
virtual void FileTimeToString( char* pStrip, int maxCharsIncludingTerminator, long fileTime ) { m_pFileSystemPassThru->FileTimeToString( pStrip, maxCharsIncludingTerminator, fileTime ); }
virtual void FileTimeToString( char* pStrip, int maxCharsIncludingTerminator, int32_t fileTime ) { m_pFileSystemPassThru->FileTimeToString( pStrip, maxCharsIncludingTerminator, fileTime ); }
virtual void SetBufferSize( FileHandle_t file, unsigned nBytes ) { m_pFileSystemPassThru->SetBufferSize( file, nBytes ); }
virtual bool IsOk( FileHandle_t file ) { return m_pFileSystemPassThru->IsOk( file ); }
virtual bool EndOfFile( FileHandle_t file ) { return m_pFileSystemPassThru->EndOfFile( file ); }
@ -211,7 +211,7 @@ public:
virtual bool ReadToBuffer( FileHandle_t hFile, CUtlBuffer &buf, int nMaxBytes = 0, FSAllocFunc_t pfnAlloc = NULL ) { return m_pFileSystemPassThru->ReadToBuffer( hFile, buf, nMaxBytes, pfnAlloc ); }
virtual bool FullPathToRelativePathEx( const char *pFullPath, const char *pPathId, char *pRelative, int nMaxLen ) { return m_pFileSystemPassThru->FullPathToRelativePathEx( pFullPath, pPathId, pRelative, nMaxLen ); }
virtual int GetPathIndex( const FileNameHandle_t &handle ) { return m_pFileSystemPassThru->GetPathIndex( handle ); }
virtual long GetPathTime( const char *pPath, const char *pPathID ) { return m_pFileSystemPassThru->GetPathTime( pPath, pPathID ); }
virtual int32_t GetPathTime( const char *pPath, const char *pPathID ) { return m_pFileSystemPassThru->GetPathTime( pPath, pPathID ); }
virtual DVDMode_t GetDVDMode() { return m_pFileSystemPassThru->GetDVDMode(); }

View File

@ -102,8 +102,91 @@ public:
#if defined( _X360 )
virtual void PublishToVXConsole( ) = 0;
#endif
virtual bool IsMaterialThreadSetAllowed( ) const = 0;
virtual void QueueMaterialThreadSetValue( ConVar *pConVar, const char *pValue ) = 0;
virtual void QueueMaterialThreadSetValue( ConVar *pConVar, int nValue ) = 0;
virtual void QueueMaterialThreadSetValue( ConVar *pConVar, float flValue ) = 0;
virtual bool HasQueuedMaterialThreadConVarSets() const = 0;
virtual int ProcessQueuedMaterialThreadConVarSets() = 0;
protected: class ICVarIteratorInternal;
public:
/// Iteration over all cvars.
/// (THIS IS A SLOW OPERATION AND YOU SHOULD AVOID IT.)
/// usage:
/// { ICVar::Iterator iter(g_pCVar);
/// for ( iter.SetFirst() ; iter.IsValid() ; iter.Next() )
/// {
/// ConCommandBase *cmd = iter.Get();
/// }
/// }
/// The Iterator class actually wraps the internal factory methods
/// so you don't need to worry about new/delete -- scope takes care
// of it.
/// We need an iterator like this because we can't simply return a
/// pointer to the internal data type that contains the cvars --
/// it's a custom, protected class with unusual semantics and is
/// prone to change.
class Iterator
{
public:
inline Iterator(ICvar *icvar);
inline ~Iterator(void);
inline void SetFirst( void );
inline void Next( void );
inline bool IsValid( void );
inline ConCommandBase *Get( void );
private:
ICVarIteratorInternal *m_pIter;
};
protected:
// internals for ICVarIterator
class ICVarIteratorInternal
{
public:
// warning: delete called on 'ICvar::ICVarIteratorInternal' that is abstract but has non-virtual destructor [-Wdelete-non-virtual-dtor]
virtual ~ICVarIteratorInternal() {}
virtual void SetFirst( void ) = 0;
virtual void Next( void ) = 0;
virtual bool IsValid( void ) = 0;
virtual ConCommandBase *Get( void ) = 0;
};
virtual ICVarIteratorInternal *FactoryInternalIterator( void ) = 0;
friend class Iterator;
};
inline ICvar::Iterator::Iterator(ICvar *icvar)
{
m_pIter = icvar->FactoryInternalIterator();
}
inline ICvar::Iterator::~Iterator( void )
{
delete m_pIter;
}
inline void ICvar::Iterator::SetFirst( void )
{
m_pIter->SetFirst();
}
inline void ICvar::Iterator::Next( void )
{
m_pIter->Next();
}
inline bool ICvar::Iterator::IsValid( void )
{
return m_pIter->IsValid();
}
inline ConCommandBase * ICvar::Iterator::Get( void )
{
return m_pIter->Get();
}
#define CVAR_INTERFACE_VERSION "VEngineCvar004"
@ -114,7 +197,7 @@ public:
// These are marked DLL_EXPORT for Linux.
DLL_EXPORT ICvar *cvar;
DLL_EXPORT ICvar *g_pCVar;
extern ICvar *g_pCVar;
#endif // ICVAR_H

View File

@ -28,8 +28,6 @@ public:
virtual void SetDataRate(float rate) = 0;
virtual bool RegisterMessage(INetMessage *msg) = 0;
virtual bool StartStreaming( unsigned int challengeNr ) = 0;
virtual void ResetStreaming( void ) = 0;
virtual void SetTimeout(float seconds) = 0;
virtual void SetDemoRecorder(IDemoRecorder *recorder) = 0;
virtual void SetChallengeNr(unsigned int chnr) = 0;
@ -39,7 +37,6 @@ public:
virtual void Shutdown(const char *reason) = 0;
virtual void ProcessPlayback( void ) = 0;
virtual bool ProcessStream( void ) = 0;
virtual void ProcessPacket( struct netpacket_s* packet, bool bHasHeader ) = 0;
virtual bool SendNetMsg(INetMessage &msg, bool bForceReliable = false, bool bVoice = false ) = 0;
@ -72,8 +69,6 @@ public:
virtual void SetCompressionMode( bool bUseCompression ) = 0;
virtual unsigned int RequestFile(const char *filename) = 0;
virtual float GetTimeSinceLastReceived( void ) const = 0;
virtual void SetMaxBufferSize(bool bReliable, int nBytes, bool bVoice = false ) = 0;
virtual bool IsNull() const = 0;

View File

@ -1,4 +1,4 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
@ -13,6 +13,7 @@
#include <inetmsghandler.h>
#include <bitvec.h>
#include <const.h>
#include <netadr.h>
class INetMessage;
class IRecipientFilter;
@ -31,7 +32,9 @@ public:
virtual int GetMaxClients( void ) const = 0; // returns current client limit
virtual IClient *GetClient( int index ) = 0; // returns interface to client
virtual int GetClientCount() const = 0; // returns number of clients slots (used & unused)
virtual int GetUDPPort( void ) const = 0; // returns current used UDP port
virtual netadr_t GetPublicAddress() = 0;
virtual bool IsUsingFakeIP( void ) const = 0;
virtual int GetLocalUDPPort( void ) const = 0; // returns current used UDP port
virtual float GetTime( void ) const = 0; // returns game world time
virtual int GetTick( void ) const = 0; // returns game world tick
virtual float GetTickInterval( void ) const = 0; // tick interval in seconds

View File

@ -209,7 +209,7 @@ public:
virtual IWorldRenderList * CreateWorldList() = 0;
virtual void BuildWorldLists( IWorldRenderList *pList, WorldListInfo_t* pInfo, int iForceFViewLeaf, const VisOverrideData_t* pVisData = NULL, bool bShadowDepth = false, float *pReflectionWaterHeight = NULL ) = 0;
virtual void DrawWorldLists( IWorldRenderList *pList, unsigned long flags, float waterZAdjust ) = 0;
virtual void DrawWorldLists( IWorldRenderList *pList, uint32_t flags, float waterZAdjust ) = 0;
// Optimization for top view
virtual void DrawTopView( bool enable ) = 0;
@ -221,7 +221,7 @@ public:
virtual void DrawMaskEntities( void ) = 0;
// Draw surfaces with alpha
virtual void DrawTranslucentSurfaces( IWorldRenderList *pList, int sortIndex, unsigned long flags, bool bShadowDepth ) = 0;
virtual void DrawTranslucentSurfaces( IWorldRenderList *pList, int sortIndex, uint32_t flags, bool bShadowDepth ) = 0;
// Draw Particles ( just draws the linefine for debugging map leaks )
virtual void DrawLineFile( void ) = 0;
@ -257,7 +257,7 @@ public:
virtual void DrawBrushModelShadow( IClientRenderable *pRenderable ) = 0;
// Does the leaf contain translucent surfaces?
virtual bool LeafContainsTranslucentSurfaces( IWorldRenderList *pList, int sortIndex, unsigned long flags ) = 0;
virtual bool LeafContainsTranslucentSurfaces( IWorldRenderList *pList, int sortIndex, uint32_t flags ) = 0;
virtual bool DoesBoxIntersectWaterVolume( const Vector &mins, const Vector &maxs, int leafWaterDataID ) = 0;

View File

@ -43,6 +43,7 @@ struct MaterialSystem_Config_t;
class VMatrix;
struct matrix3x4_t;
class ITexture;
class ITextureCompositor;
struct MaterialSystemHardwareIdentifier_t;
class KeyValues;
class IShader;
@ -65,7 +66,13 @@ typedef uint64 VertexFormat_t;
// NOTE NOTE NOTE!!!! If you up this, grep for "NEW_INTERFACE" to see if there is anything
// waiting to be enabled during an interface revision.
#define MATERIAL_SYSTEM_INTERFACE_VERSION "VMaterialSystem079"
#define MATERIAL_SYSTEM_INTERFACE_VERSION "VMaterialSystem081"
#ifdef POSIX
#define ABSOLUTE_MINIMUM_DXLEVEL 90
#else
#define ABSOLUTE_MINIMUM_DXLEVEL 80
#endif
enum ShaderParamType_t
{
@ -82,6 +89,7 @@ enum ShaderParamType_t
SHADER_PARAM_TYPE_MATRIX,
SHADER_PARAM_TYPE_MATERIAL,
SHADER_PARAM_TYPE_STRING,
SHADER_PARAM_TYPE_MATRIX4X2
};
enum MaterialMatrixMode_t
@ -217,6 +225,15 @@ enum MaterialContextType_t
MATERIAL_NULL_CONTEXT
};
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
enum MaterialFindContext_t
{
MATERIAL_FINDCONTEXT_NONE,
MATERIAL_FINDCONTEXT_ISONAMODEL,
};
//-----------------------------------------------------------------------------
// Light structure
@ -274,7 +291,6 @@ private:
#define CREATERENDERTARGETFLAGS_NOEDRAM 0x00000008 // inhibit allocation in 360 EDRAM
#define CREATERENDERTARGETFLAGS_TEMP 0x00000010 // only allocates memory upon first resolve, destroyed at level end
//-----------------------------------------------------------------------------
// allowed stencil operations. These match the d3d operations
//-----------------------------------------------------------------------------
@ -463,6 +479,21 @@ private:
int m_nBottom;
};
// Passed as the callback object to Async functions in the material system
// so that callers don't have to worry about memory going out of scope before the
// results return.
abstract_class IAsyncTextureOperationReceiver : public IRefCounted
{
public:
virtual void OnAsyncCreateComplete( ITexture* pTex, void* pExtraArgs ) = 0;
virtual void OnAsyncFindComplete( ITexture* pTex, void* pExtraArgs ) = 0;
virtual void OnAsyncMapComplete( ITexture* pTex, void* pExtraArgs, void* pMemory, int nPitch ) = 0;
virtual void OnAsyncReadbackBegin( ITexture* pDst, ITexture* pSrc, void* pExtraArgs ) = 0;
virtual int GetRefCount() const = 0;
};
//-----------------------------------------------------------------------------
// Flags to be used with the Init call
//-----------------------------------------------------------------------------
@ -508,7 +539,11 @@ enum RenderTargetSizeMode_t
RT_SIZE_HDR=3, // frame_buffer_width / 4
RT_SIZE_FULL_FRAME_BUFFER=4, // Same size as frame buffer, or next lower power of 2 if we can't do that.
RT_SIZE_OFFSCREEN=5, // Target of specified size, don't mess with dimensions
RT_SIZE_FULL_FRAME_BUFFER_ROUNDED_UP=6 // Same size as the frame buffer, rounded up if necessary for systems that can't do non-power of two textures.
RT_SIZE_FULL_FRAME_BUFFER_ROUNDED_UP=6, // Same size as the frame buffer, rounded up if necessary for systems that can't do non-power of two textures.
RT_SIZE_REPLAY_SCREENSHOT = 7, // Rounded down to power of 2, essentially...
RT_SIZE_LITERAL = 8, // Use the size passed in. Don't clamp it to the frame buffer size. Really.
RT_SIZE_LITERAL_PICMIP = 9 // Use the size passed in, don't clamp to the frame buffer size, but do apply picmip restrictions.
};
typedef void (*MaterialBufferReleaseFunc_t)( );
@ -571,6 +606,7 @@ public:
//---------------------------------------------------------
virtual void SetThreadMode( MaterialThreadMode_t mode, int nServiceThread = -1 ) = 0;
virtual MaterialThreadMode_t GetThreadMode( ) = 0;
virtual bool IsRenderThreadSafe( ) = 0;
virtual void ExecuteQueued() = 0;
//---------------------------------------------------------
@ -765,6 +801,8 @@ public:
//---------------------------------------------------------
// Material and texture management
//---------------------------------------------------------
virtual void SuspendTextureStreaming( void ) = 0;
virtual void ResumeTextureStreaming( void ) = 0;
// uncache all materials. . good for forcing reload of materials.
virtual void UncacheAllMaterials( ) = 0;
@ -800,6 +838,9 @@ public:
// (Or use the global IsErrorMaterial function, which checks if it's null too).
virtual IMaterial * FindMaterial( char const* pMaterialName, const char *pTextureGroupName, bool complain = true, const char *pComplainPrefix = NULL ) = 0;
// Query whether a material is loaded (eg, whether FindMaterial will be nonblocking)
virtual bool IsMaterialLoaded( char const* pMaterialName ) = 0;
//---------------------------------
// This is the interface for knowing what materials are available
// is to use the following functions to get a list of materials. The
@ -827,7 +868,9 @@ public:
//---------------------------------
virtual ITexture * FindTexture( char const* pTextureName, const char *pTextureGroupName, bool complain = true ) = 0;
virtual void SetAsyncTextureLoadCache( void* hFileCache ) = 0;
virtual ITexture * FindTexture( char const* pTextureName, const char *pTextureGroupName, bool complain = true, int nAdditionalCreationFlags = 0 ) = 0;
// Checks to see if a particular texture is loaded
virtual bool IsTextureLoaded( char const* pTextureName ) const = 0;
@ -997,6 +1040,49 @@ public:
// For sv_pure mode. The filesystem figures out which files the client needs to reload to be "pure" ala the server's preferences.
virtual void ReloadFilesInList( IFileList *pFilesToReload ) = 0;
virtual bool AllowThreading( bool bAllow, int nServiceThread ) = 0;
// Extended version of FindMaterial().
// Contains context in so it can make decisions (i.e. if it's a model, ignore certain cheat parameters)
virtual IMaterial * FindMaterialEx( char const* pMaterialName, const char *pTextureGroupName, int nContext, bool complain = true, const char *pComplainPrefix = NULL ) = 0;
#ifdef DX_TO_GL_ABSTRACTION
virtual void DoStartupShaderPreloading( void ) = 0;
#endif
// Sets the override sizes for all render target size tests. These replace the frame buffer size.
// Set them when you are rendering primarily to something larger than the frame buffer (as in VR mode).
virtual void SetRenderTargetFrameBufferSizeOverrides( int nWidth, int nHeight ) = 0;
// Returns the (possibly overridden) framebuffer size for render target sizing.
virtual void GetRenderTargetFrameBufferDimensions( int & nWidth, int & nHeight ) = 0;
// returns the display device name that matches the adapter index we were started with
virtual char *GetDisplayDeviceName() const = 0;
// creates a texture suitable for use with materials from a raw stream of bits.
// The bits will be retained by the material system and can be freed upon return.
virtual ITexture* CreateTextureFromBits(int w, int h, int mips, ImageFormat fmt, int srcBufferSize, byte* srcBits) = 0;
// Lie to the material system to pretend to be in render target allocation mode at the beginning of time.
// This was a thing that mattered a lot to old hardware, but doesn't matter at all to new hardware,
// where new is defined to be "anything from the last decade." However, we want to preserve legacy behavior
// for the old games because it's easier than testing them.
virtual void OverrideRenderTargetAllocation( bool rtAlloc ) = 0;
// creates a texture compositor that will attempt to composite a new textuer from the steps of the specified KeyValues.
virtual ITextureCompositor* NewTextureCompositor( int w, int h, const char* pCompositeName, int nTeamNum, uint64 randomSeed, KeyValues* stageDesc, uint32 texCompositeCreateFlags = 0 ) = 0;
// Loads the texture with the specified name, calls pRecipient->OnAsyncFindComplete with the result from the main thread.
// once the texture load is complete. If the texture cannot be found, the returned texture will return true for IsError().
virtual void AsyncFindTexture( const char* pFilename, const char *pTextureGroupName, IAsyncTextureOperationReceiver* pRecipient, void* pExtraArgs, bool bComplain = true, int nAdditionalCreationFlags = 0 ) = 0;
// creates a texture suitable for use with materials from a raw stream of bits.
// The bits will be retained by the material system and can be freed upon return.
virtual ITexture* CreateNamedTextureFromBitsEx( const char* pName, const char *pTextureGroupName, int w, int h, int mips, ImageFormat fmt, int srcBufferSize, byte* srcBits, int nFlags ) = 0;
virtual bool AddTextureCompositorTemplate( const char *pName, KeyValues *kv, int a ) = 0;
virtual bool VerifyTextureCompositorTemplates ( void ) = 0;
};
@ -1282,6 +1368,7 @@ public:
// Blit a subrect of the current render target to another texture
virtual void CopyRenderTargetToTextureEx( ITexture *pTexture, int nRenderTargetID, Rect_t *pSrcRect, Rect_t *pDstRect = NULL ) = 0;
virtual void CopyTextureToRenderTargetEx( int nRenderTargetID, ITexture *pTexture, Rect_t *pSrcRect, Rect_t *pDstRect = NULL ) = 0;
// Special off-center perspective matrix for DoF, MSAA jitter and poster rendering
virtual void PerspectiveOffCenterX( double fovx, double aspect, double zNear, double zFar, double bottom, double top, double left, double right ) = 0;
@ -1341,9 +1428,9 @@ public:
virtual void GetFogDistances( float *fStart, float *fEnd, float *fFogZ ) = 0;
// Hooks for firing PIX events from outside the Material System...
virtual void BeginPIXEvent( unsigned long color, const char *szName ) = 0;
virtual void BeginPIXEvent( uint32_t color, const char *szName ) = 0;
virtual void EndPIXEvent() = 0;
virtual void SetPIXMarker( unsigned long color, const char *szName ) = 0;
virtual void SetPIXMarker( uint32_t color, const char *szName ) = 0;
// Batch API
// from changelist 166623:
@ -1433,8 +1520,221 @@ public:
virtual void SetNonInteractiveTempFullscreenBuffer( ITexture *pTexture, MaterialNonInteractiveMode_t mode ) = 0;
virtual void EnableNonInteractiveMode( MaterialNonInteractiveMode_t mode ) = 0;
virtual void RefreshFrontBufferNonInteractive() = 0;
// Allocates temp render data. Renderdata goes out of scope at frame end in multicore
// Renderdata goes out of scope after refcount goes to zero in singlecore.
// Locking/unlocking increases + decreases refcount
virtual void * LockRenderData( int nSizeInBytes ) = 0;
virtual void UnlockRenderData( void *pData ) = 0;
// Typed version. If specified, pSrcData is copied into the locked memory.
template< class E > E* LockRenderDataTyped( int nCount, const E* pSrcData = NULL );
// Temp render data gets immediately freed after it's all unlocked in single core.
// This prevents it from being freed
virtual void AddRefRenderData() = 0;
virtual void ReleaseRenderData() = 0;
// Returns whether a pointer is render data. NOTE: passing NULL returns true
virtual bool IsRenderData( const void *pData ) const = 0;
virtual void PrintfVA( char *fmt, va_list vargs ) = 0;
virtual void Printf( PRINTF_FORMAT_STRING const char *fmt, ... ) = 0;
virtual float Knob( char *knobname, float *setvalue = NULL ) = 0;
// Allows us to override the alpha write setting of a material
virtual void OverrideAlphaWriteEnable( bool bEnable, bool bAlphaWriteEnable ) = 0;
virtual void OverrideColorWriteEnable( bool bOverrideEnable, bool bColorWriteEnable ) = 0;
virtual void ClearBuffersObeyStencilEx( bool bClearColor, bool bClearAlpha, bool bClearDepth ) = 0;
// Create a texture from the specified src render target, then call pRecipient->OnAsyncCreateComplete from the main thread.
// The texture will be created using the destination format, and will optionally have mipmaps generated.
// In case of error, the provided callback function will be called with the error texture.
virtual void AsyncCreateTextureFromRenderTarget( ITexture* pSrcRt, const char* pDstName, ImageFormat dstFmt, bool bGenMips, int nAdditionalCreationFlags, IAsyncTextureOperationReceiver* pRecipient, void* pExtraArgs ) = 0;
};
template< class E > inline E* IMatRenderContext::LockRenderDataTyped( int nCount, const E* pSrcData )
{
int nSizeInBytes = nCount * sizeof(E);
E *pDstData = (E*)LockRenderData( nSizeInBytes );
if ( pSrcData && pDstData )
{
memcpy( pDstData, pSrcData, nSizeInBytes );
}
return pDstData;
}
//-----------------------------------------------------------------------------
// Utility class for addreffing/releasing render data (prevents freeing on single core)
//-----------------------------------------------------------------------------
class CMatRenderDataReference
{
public:
CMatRenderDataReference();
CMatRenderDataReference( IMatRenderContext* pRenderContext );
~CMatRenderDataReference();
void Lock( IMatRenderContext *pRenderContext );
void Release();
private:
IMatRenderContext *m_pRenderContext;
};
inline CMatRenderDataReference::CMatRenderDataReference()
{
m_pRenderContext = NULL;
}
inline CMatRenderDataReference::CMatRenderDataReference( IMatRenderContext* pRenderContext )
{
m_pRenderContext = NULL;
Lock( pRenderContext );
}
inline CMatRenderDataReference::~CMatRenderDataReference()
{
Release();
}
inline void CMatRenderDataReference::Lock( IMatRenderContext* pRenderContext )
{
if ( !m_pRenderContext )
{
m_pRenderContext = pRenderContext;
m_pRenderContext->AddRefRenderData( );
}
}
inline void CMatRenderDataReference::Release()
{
if ( m_pRenderContext )
{
m_pRenderContext->ReleaseRenderData( );
m_pRenderContext = NULL;
}
}
//-----------------------------------------------------------------------------
// Utility class for locking/unlocking render data
//-----------------------------------------------------------------------------
template< typename E >
class CMatRenderData
{
public:
CMatRenderData( IMatRenderContext* pRenderContext );
CMatRenderData( IMatRenderContext* pRenderContext, int nCount, const E *pSrcData = NULL );
~CMatRenderData();
E* Lock( int nCount, const E* pSrcData = NULL );
void Release();
bool IsValid() const;
const E* Base() const;
E* Base();
const E& operator[]( int i ) const;
E& operator[]( int i );
private:
IMatRenderContext* m_pRenderContext;
E *m_pRenderData;
int m_nCount;
bool m_bNeedsUnlock;
};
template< typename E >
inline CMatRenderData<E>::CMatRenderData( IMatRenderContext* pRenderContext )
{
m_pRenderContext = pRenderContext;
m_nCount = 0;
m_pRenderData = 0;
m_bNeedsUnlock = false;
}
template< typename E >
inline CMatRenderData<E>::CMatRenderData( IMatRenderContext* pRenderContext, int nCount, const E* pSrcData )
{
m_pRenderContext = pRenderContext;
m_nCount = 0;
m_pRenderData = 0;
m_bNeedsUnlock = false;
Lock( nCount, pSrcData );
}
template< typename E >
inline CMatRenderData<E>::~CMatRenderData()
{
Release();
}
template< typename E >
inline bool CMatRenderData<E>::IsValid() const
{
return m_pRenderData != NULL;
}
template< typename E >
inline E* CMatRenderData<E>::Lock( int nCount, const E* pSrcData )
{
m_nCount = nCount;
if ( pSrcData && m_pRenderContext->IsRenderData( pSrcData ) )
{
// Yes, we're const-casting away, but that should be ok since
// the src data is render data
m_pRenderData = const_cast<E*>( pSrcData );
m_pRenderContext->AddRefRenderData();
m_bNeedsUnlock = false;
return m_pRenderData;
}
m_pRenderData = m_pRenderContext->LockRenderDataTyped<E>( nCount, pSrcData );
m_bNeedsUnlock = true;
return m_pRenderData;
}
template< typename E >
inline void CMatRenderData<E>::Release()
{
if ( m_pRenderContext && m_pRenderData )
{
if ( m_bNeedsUnlock )
{
m_pRenderContext->UnlockRenderData( m_pRenderData );
}
else
{
m_pRenderContext->ReleaseRenderData();
}
}
m_pRenderData = NULL;
m_nCount = 0;
m_bNeedsUnlock = false;
}
template< typename E >
inline E* CMatRenderData<E>::Base()
{
return m_pRenderData;
}
template< typename E >
inline const E* CMatRenderData<E>::Base() const
{
return m_pRenderData;
}
template< typename E >
inline E& CMatRenderData<E>::operator[]( int i )
{
Assert( ( i >= 0 ) && ( i < m_nCount ) );
return m_pRenderData[i];
}
template< typename E >
inline const E& CMatRenderData<E>::operator[]( int i ) const
{
Assert( ( i >= 0 ) && ( i < m_nCount ) );
return m_pRenderData[i];
}
//-----------------------------------------------------------------------------
class CMatRenderContextPtr : public CRefPtr<IMatRenderContext>
@ -1468,7 +1768,7 @@ private:
class PIXEvent
{
public:
PIXEvent( IMatRenderContext *pRenderContext, const char *szName, unsigned long color = PIX_VALVE_ORANGE )
PIXEvent( IMatRenderContext *pRenderContext, const char *szName, uint32_t color = PIX_VALVE_ORANGE )
{
m_pRenderContext = pRenderContext;
Assert( m_pRenderContext );
@ -1484,7 +1784,8 @@ private:
};
#define PIX_ENABLE 0 // set this to 1 and build engine/studiorender to enable pix events in the engine
// Also be sure to enable PIX_INSTRUMENTATION in shaderdevicedx8.h
//#define PIX_ENABLE 1 // set this to 1 and build engine/studiorender to enable pix events in the engine
#if PIX_ENABLE
# define PIXEVENT PIXEvent _pixEvent

View File

@ -21,8 +21,8 @@ class VMatrix;
class ITexture;
#define MAKE_MATERIALVAR_FOURCC(ch0, ch1, ch2, ch3) \
((unsigned long)(ch0) | ((unsigned long)(ch1) << 8) | \
((unsigned long)(ch2) << 16) | ((unsigned long)(ch3) << 24 ))
((uint32_t)(ch0) | ((uint32_t)(ch1) << 8) | \
((uint32_t)(ch2) << 16) | ((uint32_t)(ch3) << 24 ))
// This fourcc is reserved.
#define FOURCC_UNKNOWN MAKE_MATERIALVAR_FOURCC('U','N','K','N')
@ -49,7 +49,7 @@ typedef unsigned short MaterialVarSym_t;
class IMaterialVar
{
public:
typedef unsigned long FourCC;
typedef uint32_t FourCC;
protected:
// base data and accessors

1190
public/mathlib/amd3dx.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -8,6 +8,7 @@
#ifndef _3D_UNITVEC_H
#define _3D_UNITVEC_H
#include <cstdint>
#define UNITVEC_DECLARE_STATICS \
float cUnitVector::mUVAdjustment[0x2000]; \
@ -75,8 +76,8 @@ public:
// a little slower... old pack was 4 multiplies and 2 adds.
// This is 2 multiplies, 2 adds, and a divide....
float w = 126.0f / ( tmp.x + tmp.y + tmp.z );
long xbits = (long)( tmp.x * w );
long ybits = (long)( tmp.y * w );
int32_t xbits = (int32_t)( tmp.x * w );
int32_t ybits = (int32_t)( tmp.y * w );
Assert( xbits < 127 );
Assert( xbits >= 0 );
@ -110,8 +111,8 @@ public:
// multiplication
// get the x and y bits
long xbits = (( mVec & TOP_MASK ) >> 7 );
long ybits = ( mVec & BOTTOM_MASK );
int32_t xbits = (( mVec & TOP_MASK ) >> 7 );
int32_t ybits = ( mVec & BOTTOM_MASK );
// map the numbers back to the triangle (0,0)-(0,126)-(126,0)
if (( xbits + ybits ) >= 127 )
@ -139,8 +140,8 @@ public:
{
for ( int idx = 0; idx < 0x2000; idx++ )
{
long xbits = idx >> 7;
long ybits = idx & BOTTOM_MASK;
int32_t xbits = idx >> 7;
int32_t ybits = idx & BOTTOM_MASK;
// map the numbers back to the triangle (0,0)-(0,127)-(127,0)
if (( xbits + ybits ) >= 127 )

View File

@ -58,8 +58,8 @@ inline Vector32& Vector32::operator=(const Vector &vOther)
static float expScale[4] = { 4.0f, 16.0f, 32.f, 64.f };
float fmax = MAX( fabs( vOther.x ), fabs( vOther.y ) );
fmax = fpmax( fmax, fabs( vOther.z ) );
float fmax = Max( fabs( vOther.x ), fabs( vOther.y ) );
fmax = Max( fmax, (float)fabs( vOther.z ) );
for (exp = 0; exp < 3; exp++)
{
@ -70,9 +70,9 @@ inline Vector32& Vector32::operator=(const Vector &vOther)
float fexp = 512.0f / expScale[exp];
x = clamp( (int)(vOther.x * fexp) + 512, 0, 1023 );
y = clamp( (int)(vOther.y * fexp) + 512, 0, 1023 );
z = clamp( (int)(vOther.z * fexp) + 512, 0, 1023 );
x = Clamp( (int)(vOther.x * fexp) + 512, 0, 1023 );
y = Clamp( (int)(vOther.y * fexp) + 512, 0, 1023 );
z = Clamp( (int)(vOther.z * fexp) + 512, 0, 1023 );
return *this;
}
@ -118,8 +118,8 @@ inline Normal32& Normal32::operator=(const Vector &vOther)
{
CHECK_VALID(vOther);
x = clamp( (int)(vOther.x * 16384) + 16384, 0, 32767 );
y = clamp( (int)(vOther.y * 16384) + 16384, 0, 32767 );
x = Clamp( (int)(vOther.x * 16384) + 16384, 0, 32767 );
y = Clamp( (int)(vOther.y * 16384) + 16384, 0, 32767 );
zneg = (vOther.z < 0);
//x = vOther.x;
//y = vOther.y;
@ -182,9 +182,9 @@ inline Quaternion64& Quaternion64::operator=(const Quaternion &vOther)
{
CHECK_VALID(vOther);
x = clamp( (int)(vOther.x * 1048576) + 1048576, 0, 2097151 );
y = clamp( (int)(vOther.y * 1048576) + 1048576, 0, 2097151 );
z = clamp( (int)(vOther.z * 1048576) + 1048576, 0, 2097151 );
x = Clamp( (int)(vOther.x * 1048576) + 1048576, 0, 2097151 );
y = Clamp( (int)(vOther.y * 1048576) + 1048576, 0, 2097151 );
z = Clamp( (int)(vOther.z * 1048576) + 1048576, 0, 2097151 );
wneg = (vOther.w < 0);
return *this;
}
@ -229,9 +229,9 @@ inline Quaternion48& Quaternion48::operator=(const Quaternion &vOther)
{
CHECK_VALID(vOther);
x = clamp( (int)(vOther.x * 32768) + 32768, 0, 65535 );
y = clamp( (int)(vOther.y * 32768) + 32768, 0, 65535 );
z = clamp( (int)(vOther.z * 16384) + 16384, 0, 32767 );
x = Clamp( (int)(vOther.x * 32768) + 32768, 0, 65535 );
y = Clamp( (int)(vOther.y * 32768) + 32768, 0, 65535 );
z = Clamp( (int)(vOther.z * 16384) + 16384, 0, 32767 );
wneg = (vOther.w < 0);
return *this;
}
@ -276,9 +276,9 @@ inline Quaternion32& Quaternion32::operator=(const Quaternion &vOther)
{
CHECK_VALID(vOther);
x = clamp( (int)(vOther.x * 1024) + 1024, 0, 2047 );
y = clamp( (int)(vOther.y * 512) + 512, 0, 1023 );
z = clamp( (int)(vOther.z * 512) + 512, 0, 1023 );
x = Clamp( (int)(vOther.x * 1024) + 1024, 0, 2047 );
y = Clamp( (int)(vOther.y * 512) + 512, 0, 1023 );
z = Clamp( (int)(vOther.z * 512) + 512, 0, 1023 );
wneg = (vOther.w < 0);
return *this;
}

View File

@ -28,6 +28,7 @@ enum LightType_OptimizationFlags_t
LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION0 = 1,
LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION1 = 2,
LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION2 = 4,
LIGHTTYPE_OPTIMIZATIONFLAGS_DERIVED_VALUES_CALCED = 8,
};
struct LightDesc_t
@ -102,6 +103,11 @@ public:
{
return ((m_Type!=MATERIAL_LIGHT_SPOT) || (rdir.Dot(m_Direction)>=m_PhiDot));
}
float OneOverThetaDotMinusPhiDot() const
{
return OneOver_ThetaDot_Minus_PhiDot;
}
};

View File

@ -28,6 +28,14 @@ extern float (*pfFastCos)(float x);
#define FastSinCos(x,s,c) (*pfFastSinCos)(x,s,c)
#define FastCos(x) (*pfFastCos)(x)
#if defined(__i386__) || defined(_M_IX86)
// On x86, the inline FPU or SSE sqrt instruction is faster than
// the overhead of setting up a function call and saving/restoring
// the FPU or SSE register state and can be scheduled better, too.
#undef FastSqrt
#define FastSqrt(x) ::sqrtf(x)
#endif
#endif // !_X360
#if defined( _X360 )

View File

@ -1,4 +1,4 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//===== Copyright <EFBFBD> 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
@ -7,6 +7,7 @@
#ifndef MATH_LIB_H
#define MATH_LIB_H
#include <cmath>
#include <math.h>
#include "tier0/basetypes.h"
#include "mathlib/vector.h"
@ -15,6 +16,61 @@
#include "mathlib/math_pfns.h"
#if defined(__i386__) || defined(_M_IX86)
// For MMX intrinsics
#include <xmmintrin.h>
#endif
// XXX remove me
#undef clamp
#ifdef DEBUG // stop crashing edit-and-continue
FORCEINLINE float clamp( float val, float minVal, float maxVal )
{
if ( maxVal < minVal )
return maxVal;
else if( val < minVal )
return minVal;
else if( val > maxVal )
return maxVal;
else
return val;
}
#else // DEBUG
FORCEINLINE float clamp( float val, float minVal, float maxVal )
{
#if defined(__i386__) || defined(_M_IX86)
_mm_store_ss( &val,
_mm_min_ss(
_mm_max_ss(
_mm_load_ss(&val),
_mm_load_ss(&minVal) ),
_mm_load_ss(&maxVal) ) );
#else
val = fpmax(minVal, val);
val = fpmin(maxVal, val);
#endif
return val;
}
#endif // DEBUG
//
// Returns a clamped value in the range [min, max].
//
template< class T >
inline T clamp( T const &val, T const &minVal, T const &maxVal )
{
if ( maxVal < minVal )
return maxVal;
else if( val < minVal )
return minVal;
else if( val > maxVal )
return maxVal;
else
return val;
}
// plane_t structure
// !!! if this is changed, it must be changed in asm code too !!!
// FIXME: does the asm code even exist anymore?
@ -224,12 +280,12 @@ FORCEINLINE void VectorClear(vec_t *a)
FORCEINLINE float VectorMaximum(const vec_t *v)
{
return MAX( v[0], MAX( v[1], v[2] ) );
return V_max( v[0], V_max( v[1], v[2] ) );
}
FORCEINLINE float VectorMaximum(const Vector& v)
{
return MAX( v.x, MAX( v.y, v.z ) );
return V_max( v.x, V_max( v.y, v.z ) );
}
FORCEINLINE void VectorScale (const float* in, vec_t scale, float* out)
@ -254,7 +310,7 @@ inline void VectorNegate(vec_t *a)
}
//#define VectorMaximum(a) ( MAX( (a)[0], MAX( (a)[1], (a)[2] ) ) )
//#define VectorMaximum(a) ( V_max( (a)[0], V_max( (a)[1], (a)[2] ) ) )
#define Vector2Clear(x) {(x)[0]=(x)[1]=0;}
#define Vector2Negate(x) {(x)[0]=-((x)[0]);(x)[1]=-((x)[1]);}
#define Vector2Copy(a,b) {(b)[0]=(a)[0];(b)[1]=(a)[1];}
@ -281,10 +337,10 @@ FORCEINLINE void VectorMAInline( const Vector& start, float scale, const Vector&
dest.z=start.z+direction.z*scale;
}
//FORCEINLINE void VectorMA( const Vector& start, float scale, const Vector& direction, Vector& dest )
//{
// VectorMAInline(start, scale, direction, dest);
//}
FORCEINLINE void VectorMA( const Vector& start, float scale, const Vector& direction, Vector& dest )
{
VectorMAInline(start, scale, direction, dest);
}
FORCEINLINE void VectorMA( const float * start, float scale, const float *direction, float *dest )
{
@ -315,7 +371,7 @@ void inline SinCos( float radians, float *sine, float *cosine )
{
#if defined( _X360 )
XMScalarSinCos( sine, cosine, radians );
#elif defined( _WIN32 )
#elif defined( PLATFORM_WINDOWS_PC32 )
_asm
{
fld DWORD PTR [radians]
@ -327,11 +383,12 @@ void inline SinCos( float radians, float *sine, float *cosine )
fstp DWORD PTR [edx]
fstp DWORD PTR [eax]
}
#elif defined( _LINUX ) || defined ( __APPLE__ )
register double __cosr, __sinr;
__asm __volatile__
("fsincos"
: "=t" (__cosr), "=u" (__sinr) : "0" (radians));
#elif defined( PLATFORM_WINDOWS_PC64 )
*sine = sin( radians );
*cosine = cos( radians );
#elif defined( POSIX )
double __cosr, __sinr;
__asm ("fsincos" : "=t" (__cosr), "=u" (__sinr) : "0" (radians));
*sine = __sinr;
*cosine = __cosr;
@ -375,11 +432,6 @@ FORCEINLINE T Square( T const &a )
}
FORCEINLINE bool IsPowerOfTwo( uint x )
{
return ( x & ( x - 1 ) ) == 0;
}
// return the smallest power of two >= x.
// returns 0 if x == 0 or x > 0x80000000 (ie numbers that would be negative if x was signed)
// NOTE: the old code took an int, and if you pass in an int of 0x80000000 casted to a uint,
@ -446,6 +498,19 @@ bool MatricesAreEqual( const matrix3x4_t &src1, const matrix3x4_t &src2, float f
void MatrixGetColumn( const matrix3x4_t &in, int column, Vector &out );
void MatrixSetColumn( const Vector &in, int column, matrix3x4_t &out );
inline void MatrixGetTranslation( const matrix3x4_t &in, Vector &out )
{
MatrixGetColumn ( in, 3, out );
}
inline void MatrixSetTranslation( const Vector &in, matrix3x4_t &out )
{
MatrixSetColumn ( in, 3, out );
}
void MatrixScaleBy ( const float flScale, matrix3x4_t &out );
void MatrixScaleByZero ( matrix3x4_t &out );
//void DecomposeRotation( const matrix3x4_t &mat, float *out );
void ConcatRotations (const matrix3x4_t &in1, const matrix3x4_t &in2, matrix3x4_t &out);
void ConcatTransforms (const matrix3x4_t &in1, const matrix3x4_t &in2, matrix3x4_t &out);
@ -606,7 +671,7 @@ template<> FORCEINLINE QAngleByValue Lerp<QAngleByValue>( float flPercent, const
#endif // VECTOR_NO_SLOW_OPERATIONS
// Swap two of anything.
/// Same as swap(), but won't cause problems with std::swap
template <class T>
FORCEINLINE void V_swap( T& x, T& y )
{
@ -621,15 +686,11 @@ template <class T> FORCEINLINE T AVG(T a, T b)
}
// number of elements in an array of static size
#define NELEMS(x) ((sizeof(x))/sizeof(x[0]))
#define NELEMS(x) ARRAYSIZE(x)
// XYZ macro, for printf type functions - ex printf("%f %f %f",XYZ(myvector));
#define XYZ(v) (v).x,(v).y,(v).z
//
// Returns a clamped value in the range [min, max].
//
#define V_clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val)))
inline float Sign( float x )
{
@ -1066,13 +1127,15 @@ inline float SimpleSplineRemapValClamped( float val, float A, float B, float C,
if ( A == B )
return val >= B ? D : C;
float cVal = (val - A) / (B - A);
cVal = V_clamp( cVal, 0.0f, 1.0f );
cVal = clamp( cVal, 0.0f, 1.0f );
return C + (D - C) * SimpleSpline( cVal );
}
FORCEINLINE int RoundFloatToInt(float f)
{
#if defined( _X360 )
#if defined(__i386__) || defined(_M_IX86) || defined( PLATFORM_WINDOWS_PC64 ) || defined(__x86_64__)
return _mm_cvtss_si32(_mm_load_ss(&f));
#elif defined( _X360 )
#ifdef Assert
Assert( IsFPUControlWordSet() );
#endif
@ -1083,63 +1146,18 @@ FORCEINLINE int RoundFloatToInt(float f)
};
flResult = __fctiw( f );
return pResult[1];
#else // !X360
int nResult;
#if defined( _WIN32 )
__asm
{
fld f
fistp nResult
}
#elif defined( _LINUX ) || defined( __APPLE__ )
__asm __volatile__ (
"fistpl %0;": "=m" (nResult): "t" (f) : "st"
);
#endif
return nResult;
#else
#error Unknown architecture
#endif
}
FORCEINLINE unsigned char RoundFloatToByte(float f)
{
#if defined( _X360 )
int nResult = RoundFloatToInt(f);
#ifdef Assert
Assert( IsFPUControlWordSet() );
#endif
union
{
double flResult;
int pIntResult[2];
unsigned char pResult[8];
};
flResult = __fctiw( f );
#ifdef Assert
Assert( pIntResult[1] >= 0 && pIntResult[1] <= 255 );
#endif
return pResult[8];
#else // !X360
int nResult;
#if defined( _WIN32 )
__asm
{
fld f
fistp nResult
}
#elif defined( _LINUX ) || defined( __APPLE__ )
__asm __volatile__ (
"fistpl %0;": "=m" (nResult): "t" (f) : "st"
);
#endif
#ifdef Assert
Assert( nResult >= 0 && nResult <= 255 );
#endif
return nResult;
Assert( (nResult & ~0xFF) == 0 );
#endif
return (unsigned char) nResult;
}
FORCEINLINE unsigned long RoundFloatToUnsignedLong(float f)
@ -1159,6 +1177,24 @@ FORCEINLINE unsigned long RoundFloatToUnsignedLong(float f)
return pResult[1];
#else // !X360
#if defined( PLATFORM_WINDOWS_PC64 )
uint nRet = ( uint ) f;
if ( nRet & 1 )
{
if ( ( f - floor( f ) >= 0.5 ) )
{
nRet++;
}
}
else
{
if ( ( f - floor( f ) > 0.5 ) )
{
nRet++;
}
}
return nRet;
#else // PLATFORM_WINDOWS_PC64
unsigned char nResult[8];
#if defined( _WIN32 )
@ -1167,14 +1203,15 @@ FORCEINLINE unsigned long RoundFloatToUnsignedLong(float f)
fld f
fistp qword ptr nResult
}
#elif defined( _LINUX ) || defined( __APPLE__ )
#elif POSIX
__asm __volatile__ (
"fistpl %0;": "=m" (nResult): "t" (f) : "st"
);
#endif
return *((unsigned long*)nResult);
#endif
#endif // PLATFORM_WINDOWS_PC64
#endif // !X360
}
FORCEINLINE bool IsIntegralValue( float flValue, float flTolerance = 0.001f )
@ -1194,29 +1231,8 @@ FORCEINLINE int Float2Int( float a )
flResult = __fctiwz( a );
return pResult[1];
#else // !X360
int RetVal;
#if defined( _WIN32 )
int CtrlwdHolder;
int CtrlwdSetter;
__asm
{
fld a // push 'a' onto the FP stack
fnstcw CtrlwdHolder // store FPU control word
movzx eax, CtrlwdHolder // move and zero extend word into eax
and eax, 0xFFFFF3FF // set all bits except rounding bits to 1
or eax, 0x00000C00 // set rounding mode bits to round towards zero
mov CtrlwdSetter, eax // Prepare to set the rounding mode -- prepare to enter plaid!
fldcw CtrlwdSetter // Entering plaid!
fistp RetVal // Store and converted (to int) result
fldcw CtrlwdHolder // Restore control word
}
#elif defined( _LINUX ) || defined ( __APPLE__ )
RetVal = static_cast<int>( a );
#endif
return RetVal;
// Rely on compiler to generate CVTTSS2SI on x86
return (int) a;
#endif
}
@ -1224,46 +1240,45 @@ FORCEINLINE int Float2Int( float a )
inline int Floor2Int( float a )
{
int RetVal;
#if defined( _X360 )
RetVal = (int)floor( a );
#elif defined( _WIN32 )
int CtrlwdHolder;
int CtrlwdSetter;
__asm
{
fld a // push 'a' onto the FP stack
fnstcw CtrlwdHolder // store FPU control word
movzx eax, CtrlwdHolder // move and zero extend word into eax
and eax, 0xFFFFF3FF // set all bits except rounding bits to 1
or eax, 0x00000400 // set rounding mode bits to round down
mov CtrlwdSetter, eax // Prepare to set the rounding mode -- prepare to enter plaid!
fldcw CtrlwdSetter // Entering plaid!
fistp RetVal // Store floored and converted (to int) result
fldcw CtrlwdHolder // Restore control word
}
#elif defined( _LINUX ) || defined( __APPLE__ )
#if defined( __i386__ )
// Convert to int and back, compare, subtract one if too big
__m128 a128 = _mm_set_ss(a);
RetVal = _mm_cvtss_si32(a128);
__m128 rounded128 = _mm_cvt_si2ss(_mm_setzero_ps(), RetVal);
RetVal -= _mm_comigt_ss( rounded128, a128 );
#else
RetVal = static_cast<int>( floor(a) );
#endif
return RetVal;
}
//-----------------------------------------------------------------------------
// Fast color conversion from float to unsigned char
//-----------------------------------------------------------------------------
FORCEINLINE unsigned char FastFToC( float c )
FORCEINLINE unsigned int FastFToC( float c )
{
volatile float dc;
// ieee trick
dc = c * 255.0f + (float)(1 << 23);
// return the lsb
#if defined( _X360 )
return ((unsigned char*)&dc)[3];
#if defined( __i386__ )
// IEEE float bit manipulation works for values between [0, 1<<23)
union { float f; int i; } convert = { c*255.0f + (float)(1<<23) };
return convert.i & 255;
#else
return *(unsigned char*)&dc;
// consoles CPUs suffer from load-hit-store penalty
return Float2Int( c * 255.0f );
#endif
}
//-----------------------------------------------------------------------------
// Fast conversion from float to integer with magnitude less than 2**22
//-----------------------------------------------------------------------------
FORCEINLINE int FastFloatToSmallInt( float c )
{
#if defined( __i386__ )
// IEEE float bit manipulation works for values between [-1<<22, 1<<22)
union { float f; int i; } convert = { c + (float)(3<<22) };
return (convert.i & ((1<<23)-1)) - (1<<22);
#else
// consoles CPUs suffer from load-hit-store penalty
return Float2Int( c );
#endif
}
@ -1275,35 +1290,22 @@ FORCEINLINE unsigned char FastFToC( float c )
inline float ClampToMsec( float in )
{
int msec = Floor2Int( in * 1000.0f + 0.5f );
return msec / 1000.0f;
return 0.001f * msec;
}
// Over 15x faster than: (int)ceil(value)
inline int Ceil2Int( float a )
{
int RetVal;
#if defined( _X360 )
RetVal = (int)ceil( a );
#elif defined( _WIN32 )
int CtrlwdHolder;
int CtrlwdSetter;
__asm
{
fld a // push 'a' onto the FP stack
fnstcw CtrlwdHolder // store FPU control word
movzx eax, CtrlwdHolder // move and zero extend word into eax
and eax, 0xFFFFF3FF // set all bits except rounding bits to 1
or eax, 0x00000800 // set rounding mode bits to round down
mov CtrlwdSetter, eax // Prepare to set the rounding mode -- prepare to enter plaid!
fldcw CtrlwdSetter // Entering plaid!
fistp RetVal // Store floored and converted (to int) result
fldcw CtrlwdHolder // Restore control word
}
#elif defined( _LINUX ) || defined( __APPLE__ )
#if defined( __i386__ )
// Convert to int and back, compare, add one if too small
__m128 a128 = _mm_load_ss(&a);
RetVal = _mm_cvtss_si32(a128);
__m128 rounded128 = _mm_cvt_si2ss(_mm_setzero_ps(), RetVal);
RetVal += _mm_comilt_ss( rounded128, a128 );
#else
RetVal = static_cast<int>( ceil(a) );
#endif
return RetVal;
}
@ -1419,7 +1421,7 @@ FORCEINLINE unsigned char LinearToLightmap( float f )
FORCEINLINE void ColorClamp( Vector& color )
{
float maxc = MAX( color.x, MAX( color.y, color.z ) );
float maxc = V_max( color.x, V_max( color.y, color.z ) );
if ( maxc > 1.0f )
{
float ooMax = 1.0f / maxc;
@ -1915,10 +1917,10 @@ FORCEINLINE unsigned int * PackNormal_SHORT2( float nx, float ny, float nz, unsi
ny *= 16384.0f;
// '0' and '32768' values are invalid encodings
nx = MAX( nx, 1.0f ); // Make sure there are no zero values
ny = MAX( ny, 1.0f );
nx = MIN( nx, 32767.0f ); // Make sure there are no 32768 values
ny = MIN( ny, 32767.0f );
nx = V_max( nx, 1.0f ); // Make sure there are no zero values
ny = V_max( ny, 1.0f );
nx = V_min( nx, 32767.0f ); // Make sure there are no 32768 values
ny = V_min( ny, 32767.0f );
if ( nz < 0.0f )
nx = -nx; // Set the sign bit for z
@ -2068,6 +2070,46 @@ void RGBtoHSV( const Vector &rgb, Vector &hsv );
void HSVtoRGB( const Vector &hsv, Vector &rgb );
//-----------------------------------------------------------------------------
// Fast version of pow and log
//-----------------------------------------------------------------------------
float FastLog2(float i); // log2( i )
float FastPow2(float i); // 2^i
float FastPow(float a, float b); // a^b
float FastPow10( float i ); // 10^i
//-----------------------------------------------------------------------------
// For testing float equality
//-----------------------------------------------------------------------------
inline bool CloseEnough( float a, float b, float epsilon = EQUAL_EPSILON )
{
return fabs( a - b ) <= epsilon;
}
inline bool CloseEnough( const Vector &a, const Vector &b, float epsilon = EQUAL_EPSILON )
{
return fabs( a.x - b.x ) <= epsilon &&
fabs( a.y - b.y ) <= epsilon &&
fabs( a.z - b.z ) <= epsilon;
}
// Fast compare
// maxUlps is the maximum error in terms of Units in the Last Place. This
// specifies how big an error we are willing to accept in terms of the value
// of the least significant digit of the floating point numbers
// representation. maxUlps can also be interpreted in terms of how many
// representable floats we are willing to accept between A and B.
// This function will allow maxUlps-1 floats between A and B.
bool AlmostEqual(float a, float b, int maxUlps = 10);
inline bool AlmostEqual( const Vector &a, const Vector &b, int maxUlps = 10)
{
return AlmostEqual( a.x, b.x, maxUlps ) &&
AlmostEqual( a.y, b.y, maxUlps ) &&
AlmostEqual( a.z, b.z, maxUlps );
}
#endif // MATH_BASE_H

385
public/mathlib/matrixmath.h Normal file
View File

@ -0,0 +1,385 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// A set of generic, template-based matrix functions.
//===========================================================================//
#ifndef MATRIXMATH_H
#define MATRIXMATH_H
#include <stdarg.h>
// The operations in this file can perform basic matrix operations on matrices represented
// using any class that supports the necessary operations:
//
// .Element( row, col ) - return the element at a given matrox position
// .SetElement( row, col, val ) - modify an element
// .Width(), .Height() - get dimensions
// .SetDimensions( nrows, ncols) - set a matrix to be un-initted and the appropriate size
//
// Generally, vectors can be used with these functions by using N x 1 matrices to represent them.
// Matrices are addressed as row, column, and indices are 0-based
//
//
// Note that the template versions of these routines are defined for generality - it is expected
// that template specialization is used for common high performance cases.
namespace MatrixMath
{
/// M *= flScaleValue
template<class MATRIXCLASS>
void ScaleMatrix( MATRIXCLASS &matrix, float flScaleValue )
{
for( int i = 0; i < matrix.Height(); i++ )
{
for( int j = 0; j < matrix.Width(); j++ )
{
matrix.SetElement( i, j, flScaleValue * matrix.Element( i, j ) );
}
}
}
/// AppendElementToMatrix - same as setting the element, except only works when all calls
/// happen in top to bottom left to right order, end you have to call FinishedAppending when
/// done. For normal matrix classes this is not different then SetElement, but for
/// CSparseMatrix, it is an accelerated way to fill a matrix from scratch.
template<class MATRIXCLASS>
FORCEINLINE void AppendElement( MATRIXCLASS &matrix, int nRow, int nCol, float flValue )
{
matrix.SetElement( nRow, nCol, flValue ); // default implementation
}
template<class MATRIXCLASS>
FORCEINLINE void FinishedAppending( MATRIXCLASS &matrix ) {} // default implementation
/// M += fl
template<class MATRIXCLASS>
void AddToMatrix( MATRIXCLASS &matrix, float flAddend )
{
for( int i = 0; i < matrix.Height(); i++ )
{
for( int j = 0; j < matrix.Width(); j++ )
{
matrix.SetElement( i, j, flAddend + matrix.Element( i, j ) );
}
}
}
/// transpose
template<class MATRIXCLASSIN, class MATRIXCLASSOUT>
void TransposeMatrix( MATRIXCLASSIN const &matrixIn, MATRIXCLASSOUT *pMatrixOut )
{
pMatrixOut->SetDimensions( matrixIn.Width(), matrixIn.Height() );
for( int i = 0; i < pMatrixOut->Height(); i++ )
{
for( int j = 0; j < pMatrixOut->Width(); j++ )
{
AppendElement( *pMatrixOut, i, j, matrixIn.Element( j, i ) );
}
}
FinishedAppending( *pMatrixOut );
}
/// copy
template<class MATRIXCLASSIN, class MATRIXCLASSOUT>
void CopyMatrix( MATRIXCLASSIN const &matrixIn, MATRIXCLASSOUT *pMatrixOut )
{
pMatrixOut->SetDimensions( matrixIn.Height(), matrixIn.Width() );
for( int i = 0; i < matrixIn.Height(); i++ )
{
for( int j = 0; j < matrixIn.Width(); j++ )
{
AppendElement( *pMatrixOut, i, j, matrixIn.Element( i, j ) );
}
}
FinishedAppending( *pMatrixOut );
}
/// M+=M
template<class MATRIXCLASSIN, class MATRIXCLASSOUT>
void AddMatrixToMatrix( MATRIXCLASSIN const &matrixIn, MATRIXCLASSOUT *pMatrixOut )
{
for( int i = 0; i < matrixIn.Height(); i++ )
{
for( int j = 0; j < matrixIn.Width(); j++ )
{
pMatrixOut->SetElement( i, j, pMatrixOut->Element( i, j ) + matrixIn.Element( i, j ) );
}
}
}
// M += scale * M
template<class MATRIXCLASSIN, class MATRIXCLASSOUT>
void AddScaledMatrixToMatrix( float flScale, MATRIXCLASSIN const &matrixIn, MATRIXCLASSOUT *pMatrixOut )
{
for( int i = 0; i < matrixIn.Height(); i++ )
{
for( int j = 0; j < matrixIn.Width(); j++ )
{
pMatrixOut->SetElement( i, j, pMatrixOut->Element( i, j ) + flScale * matrixIn.Element( i, j ) );
}
}
}
// simple way to initialize a matrix with constants from code.
template<class MATRIXCLASSOUT>
void SetMatrixToIdentity( MATRIXCLASSOUT *pMatrixOut, float flDiagonalValue = 1.0 )
{
for( int i = 0; i < pMatrixOut->Height(); i++ )
{
for( int j = 0; j < pMatrixOut->Width(); j++ )
{
AppendElement( *pMatrixOut, i, j, ( i == j ) ? flDiagonalValue : 0 );
}
}
FinishedAppending( *pMatrixOut );
}
//// simple way to initialize a matrix with constants from code
template<class MATRIXCLASSOUT>
void SetMatrixValues( MATRIXCLASSOUT *pMatrix, int nRows, int nCols, ... )
{
va_list argPtr;
va_start( argPtr, nCols );
pMatrix->SetDimensions( nRows, nCols );
for( int nRow = 0; nRow < nRows; nRow++ )
{
for( int nCol = 0; nCol < nCols; nCol++ )
{
double flNewValue = va_arg( argPtr, double );
pMatrix->SetElement( nRow, nCol, flNewValue );
}
}
va_end( argPtr );
}
/// row and colum accessors. treat a row or a column as a column vector
template<class MATRIXTYPE> class MatrixRowAccessor
{
public:
FORCEINLINE MatrixRowAccessor( MATRIXTYPE const &matrix, int nRow )
{
m_pMatrix = &matrix;
m_nRow = nRow;
}
FORCEINLINE float Element( int nRow, int nCol ) const
{
Assert( nCol == 0 );
return m_pMatrix->Element( m_nRow, nRow );
}
FORCEINLINE int Width( void ) const { return 1; };
FORCEINLINE int Height( void ) const { return m_pMatrix->Width(); }
private:
MATRIXTYPE const *m_pMatrix;
int m_nRow;
};
template<class MATRIXTYPE> class MatrixColumnAccessor
{
public:
FORCEINLINE MatrixColumnAccessor( MATRIXTYPE const &matrix, int nColumn )
{
m_pMatrix = &matrix;
m_nColumn = nColumn;
}
FORCEINLINE float Element( int nRow, int nColumn ) const
{
Assert( nColumn == 0 );
return m_pMatrix->Element( nRow, m_nColumn );
}
FORCEINLINE int Width( void ) const { return 1; }
FORCEINLINE int Height( void ) const { return m_pMatrix->Height(); }
private:
MATRIXTYPE const *m_pMatrix;
int m_nColumn;
};
/// this translator acts as a proxy for the transposed matrix
template<class MATRIXTYPE> class MatrixTransposeAccessor
{
public:
FORCEINLINE MatrixTransposeAccessor( MATRIXTYPE const & matrix )
{
m_pMatrix = &matrix;
}
FORCEINLINE float Element( int nRow, int nColumn ) const
{
return m_pMatrix->Element( nColumn, nRow );
}
FORCEINLINE int Width( void ) const { return m_pMatrix->Height(); }
FORCEINLINE int Height( void ) const { return m_pMatrix->Width(); }
private:
MATRIXTYPE const *m_pMatrix;
};
/// this tranpose returns a wrapper around it's argument, allowing things like AddMatrixToMatrix( Transpose( matA ), &matB ) without an extra copy
template<class MATRIXCLASSIN>
MatrixTransposeAccessor<MATRIXCLASSIN> TransposeMatrix( MATRIXCLASSIN const &matrixIn )
{
return MatrixTransposeAccessor<MATRIXCLASSIN>( matrixIn );
}
/// retrieve rows and columns
template<class MATRIXTYPE>
FORCEINLINE MatrixColumnAccessor<MATRIXTYPE> MatrixColumn( MATRIXTYPE const &matrix, int nColumn )
{
return MatrixColumnAccessor<MATRIXTYPE>( matrix, nColumn );
}
template<class MATRIXTYPE>
FORCEINLINE MatrixRowAccessor<MATRIXTYPE> MatrixRow( MATRIXTYPE const &matrix, int nRow )
{
return MatrixRowAccessor<MATRIXTYPE>( matrix, nRow );
}
//// dot product between vectors (or rows and/or columns via accessors)
template<class MATRIXACCESSORATYPE, class MATRIXACCESSORBTYPE >
float InnerProduct( MATRIXACCESSORATYPE const &vecA, MATRIXACCESSORBTYPE const &vecB )
{
Assert( vecA.Width() == 1 );
Assert( vecB.Width() == 1 );
Assert( vecA.Height() == vecB.Height() );
double flResult = 0;
for( int i = 0; i < vecA.Height(); i++ )
{
flResult += vecA.Element( i, 0 ) * vecB.Element( i, 0 );
}
return flResult;
}
/// matrix x matrix multiplication
template<class MATRIXATYPE, class MATRIXBTYPE, class MATRIXOUTTYPE>
void MatrixMultiply( MATRIXATYPE const &matA, MATRIXBTYPE const &matB, MATRIXOUTTYPE *pMatrixOut )
{
Assert( matA.Width() == matB.Height() );
pMatrixOut->SetDimensions( matA.Height(), matB.Width() );
for( int i = 0; i < matA.Height(); i++ )
{
for( int j = 0; j < matB.Width(); j++ )
{
pMatrixOut->SetElement( i, j, InnerProduct( MatrixRow( matA, i ), MatrixColumn( matB, j ) ) );
}
}
}
/// solve Ax=B via the conjugate graident method. Code and naming conventions based on the
/// wikipedia article.
template<class ATYPE, class XTYPE, class BTYPE>
void ConjugateGradient( ATYPE const &matA, BTYPE const &vecB, XTYPE &vecX, float flTolerance = 1.0e-20 )
{
XTYPE vecR;
vecR.SetDimensions( vecX.Height(), 1 );
MatrixMultiply( matA, vecX, &vecR );
ScaleMatrix( vecR, -1 );
AddMatrixToMatrix( vecB, &vecR );
XTYPE vecP;
CopyMatrix( vecR, &vecP );
float flRsOld = InnerProduct( vecR, vecR );
for( int nIter = 0; nIter < 100; nIter++ )
{
XTYPE vecAp;
MatrixMultiply( matA, vecP, &vecAp );
float flDivisor = InnerProduct( vecAp, vecP );
float flAlpha = flRsOld / flDivisor;
AddScaledMatrixToMatrix( flAlpha, vecP, &vecX );
AddScaledMatrixToMatrix( -flAlpha, vecAp, &vecR );
float flRsNew = InnerProduct( vecR, vecR );
if ( flRsNew < flTolerance )
{
break;
}
ScaleMatrix( vecP, flRsNew / flRsOld );
AddMatrixToMatrix( vecR, &vecP );
flRsOld = flRsNew;
}
}
/// solve (A'*A) x=B via the conjugate gradient method. Code and naming conventions based on
/// the wikipedia article. Same as Conjugate gradient but allows passing in two matrices whose
/// product is used as the A matrix (in order to preserve sparsity)
template<class ATYPE, class APRIMETYPE, class XTYPE, class BTYPE>
void ConjugateGradient( ATYPE const &matA, APRIMETYPE const &matAPrime, BTYPE const &vecB, XTYPE &vecX, float flTolerance = 1.0e-20 )
{
XTYPE vecR1;
vecR1.SetDimensions( vecX.Height(), 1 );
MatrixMultiply( matA, vecX, &vecR1 );
XTYPE vecR;
vecR.SetDimensions( vecR1.Height(), 1 );
MatrixMultiply( matAPrime, vecR1, &vecR );
ScaleMatrix( vecR, -1 );
AddMatrixToMatrix( vecB, &vecR );
XTYPE vecP;
CopyMatrix( vecR, &vecP );
float flRsOld = InnerProduct( vecR, vecR );
for( int nIter = 0; nIter < 100; nIter++ )
{
XTYPE vecAp1;
MatrixMultiply( matA, vecP, &vecAp1 );
XTYPE vecAp;
MatrixMultiply( matAPrime, vecAp1, &vecAp );
float flDivisor = InnerProduct( vecAp, vecP );
float flAlpha = flRsOld / flDivisor;
AddScaledMatrixToMatrix( flAlpha, vecP, &vecX );
AddScaledMatrixToMatrix( -flAlpha, vecAp, &vecR );
float flRsNew = InnerProduct( vecR, vecR );
if ( flRsNew < flTolerance )
{
break;
}
ScaleMatrix( vecP, flRsNew / flRsOld );
AddMatrixToMatrix( vecR, &vecP );
flRsOld = flRsNew;
}
}
template<class ATYPE, class XTYPE, class BTYPE>
void LeastSquaresFit( ATYPE const &matA, BTYPE const &vecB, XTYPE &vecX )
{
// now, generate the normal equations
BTYPE vecBeta;
MatrixMath::MatrixMultiply( MatrixMath::TransposeMatrix( matA ), vecB, &vecBeta );
vecX.SetDimensions( matA.Width(), 1 );
MatrixMath::SetMatrixToIdentity( &vecX );
ATYPE matATransposed;
TransposeMatrix( matA, &matATransposed );
ConjugateGradient( matA, matATransposed, vecBeta, vecX, 1.0e-20 );
}
};
/// a simple fixed-size matrix class
template<int NUMROWS, int NUMCOLS> class CFixedMatrix
{
public:
FORCEINLINE int Width( void ) const { return NUMCOLS; }
FORCEINLINE int Height( void ) const { return NUMROWS; }
FORCEINLINE float Element( int nRow, int nCol ) const { return m_flValues[nRow][nCol]; }
FORCEINLINE void SetElement( int nRow, int nCol, float flValue ) { m_flValues[nRow][nCol] = flValue; }
FORCEINLINE void SetDimensions( int nNumRows, int nNumCols ) { Assert( ( nNumRows == NUMROWS ) && ( nNumCols == NUMCOLS ) ); }
private:
float m_flValues[NUMROWS][NUMCOLS];
};
#endif //matrixmath_h

View File

@ -1,4 +1,4 @@
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======//
//===== Copyright <EFBFBD> 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose: - defines SIMD "structure of arrays" classes and functions.
//
@ -15,7 +15,7 @@
#include <mathlib/vector.h>
#include <mathlib/mathlib.h>
#if defined(_LINUX) || defined(__APPLE__)
#if defined(GNUC)
#define USE_STDC_FOR_SIMD 0
#else
#define USE_STDC_FOR_SIMD 0
@ -108,7 +108,7 @@ struct ALIGN16 intx4
m_i32[2] == other.m_i32[2] &&
m_i32[3] == other.m_i32[3] ;
}
};
} ALIGN16_POST;
#if defined( _DEBUG ) && defined( _X360 )
@ -170,17 +170,17 @@ extern const fltx4 Four_Negative_FLT_MAX; // -FLT_MAX, -FLT_MAX, -FLT_MAX,
extern const fltx4 g_SIMD_0123; // 0 1 2 3 as float
// external aligned integer constants
extern const ALIGN16 int32 g_SIMD_clear_signmask[]; // 0x7fffffff x 4
extern const ALIGN16 int32 g_SIMD_signmask[]; // 0x80000000 x 4
extern const ALIGN16 int32 g_SIMD_lsbmask[]; // 0xfffffffe x 4
extern const ALIGN16 int32 g_SIMD_clear_wmask[]; // -1 -1 -1 0
extern const ALIGN16 int32 g_SIMD_ComponentMask[4][4]; // [0xFFFFFFFF 0 0 0], [0 0xFFFFFFFF 0 0], [0 0 0xFFFFFFFF 0], [0 0 0 0xFFFFFFFF]
extern const ALIGN16 int32 g_SIMD_AllOnesMask[]; // ~0,~0,~0,~0
extern const ALIGN16 int32 g_SIMD_Low16BitsMask[]; // 0xffff x 4
extern const ALIGN16 int32 g_SIMD_clear_signmask[] ALIGN16_POST; // 0x7fffffff x 4
extern const ALIGN16 int32 g_SIMD_signmask[] ALIGN16_POST; // 0x80000000 x 4
extern const ALIGN16 int32 g_SIMD_lsbmask[] ALIGN16_POST; // 0xfffffffe x 4
extern const ALIGN16 int32 g_SIMD_clear_wmask[] ALIGN16_POST; // -1 -1 -1 0
extern const ALIGN16 int32 g_SIMD_ComponentMask[4][4] ALIGN16_POST; // [0xFFFFFFFF 0 0 0], [0 0xFFFFFFFF 0 0], [0 0 0xFFFFFFFF 0], [0 0 0 0xFFFFFFFF]
extern const ALIGN16 int32 g_SIMD_AllOnesMask[] ALIGN16_POST; // ~0,~0,~0,~0
extern const ALIGN16 int32 g_SIMD_Low16BitsMask[] ALIGN16_POST; // 0xffff x 4
// this mask is used for skipping the tail of things. If you have N elements in an array, and wish
// to mask out the tail, g_SIMD_SkipTailMask[N & 3] what you want to use for the last iteration.
extern const int32 ALIGN16 g_SIMD_SkipTailMask[4][4];
extern const int32 ALIGN16 g_SIMD_SkipTailMask[4][4] ALIGN16_POST;
// Define prefetch macros.
// The characteristics of cache and prefetch are completely
@ -436,23 +436,23 @@ FORCEINLINE fltx4 ArcTan2SIMD( const fltx4 &a, const fltx4 &b )
return result;
}
FORCEINLINE fltx4 MaxSIMD( const fltx4 & a, const fltx4 & b ) // MAX(a,b)
FORCEINLINE fltx4 MaxSIMD( const fltx4 & a, const fltx4 & b ) // max(a,b)
{
fltx4 retVal;
SubFloat( retVal, 0 ) = MAX( SubFloat( a, 0 ), SubFloat( b, 0 ) );
SubFloat( retVal, 1 ) = MAX( SubFloat( a, 1 ), SubFloat( b, 1 ) );
SubFloat( retVal, 2 ) = MAX( SubFloat( a, 2 ), SubFloat( b, 2 ) );
SubFloat( retVal, 3 ) = MAX( SubFloat( a, 3 ), SubFloat( b, 3 ) );
SubFloat( retVal, 0 ) = max( SubFloat( a, 0 ), SubFloat( b, 0 ) );
SubFloat( retVal, 1 ) = max( SubFloat( a, 1 ), SubFloat( b, 1 ) );
SubFloat( retVal, 2 ) = max( SubFloat( a, 2 ), SubFloat( b, 2 ) );
SubFloat( retVal, 3 ) = max( SubFloat( a, 3 ), SubFloat( b, 3 ) );
return retVal;
}
FORCEINLINE fltx4 MinSIMD( const fltx4 & a, const fltx4 & b ) // MIN(a,b)
FORCEINLINE fltx4 MinSIMD( const fltx4 & a, const fltx4 & b ) // min(a,b)
{
fltx4 retVal;
SubFloat( retVal, 0 ) = MIN( SubFloat( a, 0 ), SubFloat( b, 0 ) );
SubFloat( retVal, 1 ) = MIN( SubFloat( a, 1 ), SubFloat( b, 1 ) );
SubFloat( retVal, 2 ) = MIN( SubFloat( a, 2 ), SubFloat( b, 2 ) );
SubFloat( retVal, 3 ) = MIN( SubFloat( a, 3 ), SubFloat( b, 3 ) );
SubFloat( retVal, 0 ) = min( SubFloat( a, 0 ), SubFloat( b, 0 ) );
SubFloat( retVal, 1 ) = min( SubFloat( a, 1 ), SubFloat( b, 1 ) );
SubFloat( retVal, 2 ) = min( SubFloat( a, 2 ), SubFloat( b, 2 ) );
SubFloat( retVal, 3 ) = min( SubFloat( a, 3 ), SubFloat( b, 3 ) );
return retVal;
}
@ -858,7 +858,7 @@ FORCEINLINE void TransposeSIMD( fltx4 & x, fltx4 & y, fltx4 & z, fltx4 & w )
// and replicate it to the whole return value.
FORCEINLINE fltx4 FindLowestSIMD3( const fltx4 & a )
{
float lowest = MIN( MIN( SubFloat(a, 0), SubFloat(a, 1) ), SubFloat(a, 2));
float lowest = min( min( SubFloat(a, 0), SubFloat(a, 1) ), SubFloat(a, 2));
return ReplicateX4(lowest);
}
@ -866,7 +866,7 @@ FORCEINLINE fltx4 FindLowestSIMD3( const fltx4 & a )
// and replicate it to the whole return value.
FORCEINLINE fltx4 FindHighestSIMD3( const fltx4 & a )
{
float highest = MAX( MAX( SubFloat(a, 0), SubFloat(a, 1) ), SubFloat(a, 2));
float highest = max( max( SubFloat(a, 0), SubFloat(a, 1) ), SubFloat(a, 2));
return ReplicateX4(highest);
}
@ -1067,12 +1067,12 @@ FORCEINLINE fltx4 ArcTan2SIMD( const fltx4 &a, const fltx4 &b )
// DivSIMD defined further down, since it uses ReciprocalSIMD
FORCEINLINE fltx4 MaxSIMD( const fltx4 & a, const fltx4 & b ) // MAX(a,b)
FORCEINLINE fltx4 MaxSIMD( const fltx4 & a, const fltx4 & b ) // max(a,b)
{
return __vmaxfp( a, b );
}
FORCEINLINE fltx4 MinSIMD( const fltx4 & a, const fltx4 & b ) // MIN(a,b)
FORCEINLINE fltx4 MinSIMD( const fltx4 & a, const fltx4 & b ) // min(a,b)
{
return __vminfp( a, b );
}
@ -1520,11 +1520,11 @@ FORCEINLINE fltx4 FindLowestSIMD3( const fltx4 & a )
compareOne = __vrlimi( compareOne, a, 8 | 4 , 1 );
// compareOne is [y,z,G,G]
fltx4 retval = MinSIMD( a, compareOne );
// retVal is [MIN(x,y), MIN(y,z), G, G]
// retVal is [min(x,y), min(y,z), G, G]
compareOne = __vrlimi( compareOne, a, 8 , 2);
// compareOne is [z, G, G, G]
retval = MinSIMD( retval, compareOne );
// retVal = [ MIN(MIN(x,y),z), G, G, G ]
// retVal = [ min(min(x,y),z), G, G, G ]
// splat the x component out to the whole vector and return
return SplatXSIMD( retval );
@ -1544,11 +1544,11 @@ FORCEINLINE fltx4 FindHighestSIMD3( const fltx4 & a )
compareOne = __vrlimi( compareOne, a, 8 | 4 , 1 );
// compareOne is [y,z,G,G]
fltx4 retval = MaxSIMD( a, compareOne );
// retVal is [MAX(x,y), MAX(y,z), G, G]
// retVal is [max(x,y), max(y,z), G, G]
compareOne = __vrlimi( compareOne, a, 8 , 2);
// compareOne is [z, G, G, G]
retval = MaxSIMD( retval, compareOne );
// retVal = [ MAX(MAX(x,y),z), G, G, G ]
// retVal = [ max(max(x,y),z), G, G, G ]
// splat the x component out to the whole vector and return
return SplatXSIMD( retval );
@ -1757,7 +1757,7 @@ FORCEINLINE fltx4 AndSIMD( const fltx4 & a, const fltx4 & b ) // a & b
return _mm_and_ps( a, b );
}
FORCEINLINE fltx4 AndNotSIMD( const fltx4 & a, const fltx4 & b ) // a & ~b
FORCEINLINE fltx4 AndNotSIMD( const fltx4 & a, const fltx4 & b ) // ~a & b
{
return _mm_andnot_ps( a, b );
}
@ -1813,7 +1813,7 @@ FORCEINLINE fltx4 ReplicateX4( float flValue )
FORCEINLINE float SubFloat( const fltx4 & a, int idx )
{
// NOTE: if the output goes into a register, this causes a Load-Hit-Store stall (don't mix fpu/vpu math!)
#if !defined _LINUX && !defined __APPLE__
#ifndef POSIX
return a.m128_f32[ idx ];
#else
return (reinterpret_cast<float const *>(&a))[idx];
@ -1822,7 +1822,7 @@ FORCEINLINE float SubFloat( const fltx4 & a, int idx )
FORCEINLINE float & SubFloat( fltx4 & a, int idx )
{
#if !defined _LINUX && !defined __APPLE__
#ifndef POSIX
return a.m128_f32[ idx ];
#else
return (reinterpret_cast<float *>(&a))[idx];
@ -1836,7 +1836,7 @@ FORCEINLINE uint32 SubFloatConvertToInt( const fltx4 & a, int idx )
FORCEINLINE uint32 SubInt( const fltx4 & a, int idx )
{
#if !defined _LINUX && !defined __APPLE__
#ifndef POSIX
return a.m128_u32[idx];
#else
return (reinterpret_cast<uint32 const *>(&a))[idx];
@ -1845,7 +1845,7 @@ FORCEINLINE uint32 SubInt( const fltx4 & a, int idx )
FORCEINLINE uint32 & SubInt( fltx4 & a, int idx )
{
#if !defined _LINUX && !defined __APPLE__
#ifndef POSIX
return a.m128_u32[idx];
#else
return (reinterpret_cast<uint32 *>(&a))[idx];
@ -2120,12 +2120,12 @@ FORCEINLINE fltx4 CmpInBoundsSIMD( const fltx4 & a, const fltx4 & b ) // (a <=
return AndSIMD( CmpLeSIMD(a,b), CmpGeSIMD(a, NegSIMD(b)) );
}
FORCEINLINE fltx4 MinSIMD( const fltx4 & a, const fltx4 & b ) // MIN(a,b)
FORCEINLINE fltx4 MinSIMD( const fltx4 & a, const fltx4 & b ) // min(a,b)
{
return _mm_min_ps( a, b );
}
FORCEINLINE fltx4 MaxSIMD( const fltx4 & a, const fltx4 & b ) // MAX(a,b)
FORCEINLINE fltx4 MaxSIMD( const fltx4 & a, const fltx4 & b ) // max(a,b)
{
return _mm_max_ps( a, b );
}
@ -2271,11 +2271,11 @@ FORCEINLINE fltx4 FindLowestSIMD3( const fltx4 &a )
fltx4 compareOne = RotateLeft( a );
// compareOne is [y,z,G,x]
fltx4 retval = MinSIMD( a, compareOne );
// retVal is [MIN(x,y), ... ]
// retVal is [min(x,y), ... ]
compareOne = RotateLeft2( a );
// compareOne is [z, G, x, y]
retval = MinSIMD( retval, compareOne );
// retVal = [ MIN(MIN(x,y),z)..]
// retVal = [ min(min(x,y),z)..]
// splat the x component out to the whole vector and return
return SplatXSIMD( retval );
@ -2288,11 +2288,11 @@ FORCEINLINE fltx4 FindHighestSIMD3( const fltx4 &a )
fltx4 compareOne = RotateLeft( a );
// compareOne is [y,z,G,x]
fltx4 retval = MaxSIMD( a, compareOne );
// retVal is [MAX(x,y), ... ]
// retVal is [max(x,y), ... ]
compareOne = RotateLeft2( a );
// compareOne is [z, G, x, y]
retval = MaxSIMD( retval, compareOne );
// retVal = [ MAX(MAX(x,y),z)..]
// retVal = [ max(max(x,y),z)..]
// splat the x component out to the whole vector and return
return SplatXSIMD( retval );
@ -2407,6 +2407,12 @@ FORCEINLINE i32x4 IntShiftLeftWordSIMD(const i32x4 &vSrcA, const i32x4 &vSrcB)
// like this.
FORCEINLINE void ConvertStoreAsIntsSIMD(intx4 * RESTRICT pDest, const fltx4 &vSrc)
{
#ifdef COMPILER_MSVC64
(*pDest)[0] = SubFloat(vSrc, 0);
(*pDest)[1] = SubFloat(vSrc, 1);
(*pDest)[2] = SubFloat(vSrc, 2);
(*pDest)[3] = SubFloat(vSrc, 3);
#else
__m64 bottom = _mm_cvttps_pi32( vSrc );
__m64 top = _mm_cvttps_pi32( _mm_movehl_ps(vSrc,vSrc) );
@ -2414,6 +2420,7 @@ FORCEINLINE void ConvertStoreAsIntsSIMD(intx4 * RESTRICT pDest, const fltx4 &vSr
*reinterpret_cast<__m64 *>(&(*pDest)[2]) = top;
_mm_empty();
#endif
}

View File

@ -233,7 +233,7 @@ FORCEINLINE fltx4 QuaternionScaleSIMD( const fltx4 &p, float t )
// FIXME: nick, this isn't overly sensitive to accuracy, and it may be faster to
// use the cos part (w) of the quaternion (sin(omega)*N,cos(omega)) to figure the new scale.
float sinom = sqrt( SubFloat( p, 0 ) * SubFloat( p, 0 ) + SubFloat( p, 1 ) * SubFloat( p, 1 ) + SubFloat( p, 2 ) * SubFloat( p, 2 ) );
sinom = MIN( sinom, 1.f );
sinom = min( sinom, 1.f );
float sinsom = sin( asin( sinom ) * t );

View File

@ -1,4 +1,4 @@
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//====== Copyright © 1996-2005, Valve Corporation, All rights reserved. =======//
//
// Purpose:
//
@ -31,6 +31,7 @@
#include "tier0/threadtools.h"
#include "mathlib/vector2d.h"
#include "mathlib/math_pfns.h"
#include "minmax.h"
// Uncomment this to add extra Asserts to check for NANs, uninitialized vecs, etc.
//#define VECTOR_PARANOIA 1
@ -48,7 +49,11 @@
#ifdef VECTOR_PARANOIA
#define CHECK_VALID( _v) Assert( (_v).IsValid() )
#else
#ifdef GNUC
#define CHECK_VALID( _v)
#else
#define CHECK_VALID( _v) 0
#endif
#endif
#define VecToString(v) (static_cast<const char *>(CFmtStr("(%f, %f, %f)", (v).x, (v).y, (v).z))) // ** Note: this generates a temporary, don't hold reference!
@ -67,7 +72,7 @@ public:
// Construction/destruction:
Vector(void);
Vector(vec_t X, vec_t Y, vec_t Z);
Vector(vec_t XYZ); // TODO (Ilya): is this potentially a bad idea?
explicit Vector(vec_t XYZ); ///< broadcast initialize
// Initialization
void Init(vec_t ix=0.0f, vec_t iy=0.0f, vec_t iz=0.0f);
@ -129,6 +134,7 @@ public:
}
vec_t NormalizeInPlace();
Vector Normalized() const;
bool IsLengthGreaterThan( float val ) const;
bool IsLengthLessThan( float val ) const;
@ -202,9 +208,11 @@ private:
#endif
};
FORCEINLINE void NetworkVarConstruct( Vector &v ) { v.Zero(); }
#define USE_M64S ( ( !defined( _X360 ) ) && ( ! defined( _LINUX) ) )
#if ( ( !defined( _X360 ) ) && ( ! defined( _LINUX) ) )
#define USE_M64S 1
#endif
@ -259,7 +267,7 @@ private:
// No assignment operators either...
// ShortVector& operator=( ShortVector const& src );
};
} ALIGN8_POST;
@ -395,7 +403,7 @@ public:
#endif
float w; // this space is used anyway
};
} ALIGN16_POST;
//-----------------------------------------------------------------------------
// Vector related operations
@ -415,7 +423,9 @@ FORCEINLINE void VectorMultiply( const Vector& a, const Vector& b, Vector& resul
FORCEINLINE void VectorDivide( const Vector& a, vec_t b, Vector& result );
FORCEINLINE void VectorDivide( const Vector& a, const Vector& b, Vector& result );
inline void VectorScale ( const Vector& in, vec_t scale, Vector& result );
inline void VectorMA( const Vector& start, float scale, const Vector& direction, Vector& dest );
// Don't mark this as inline in its function declaration. That's only necessary on its
// definition, and 'inline' here leads to gcc warnings.
void VectorMA( const Vector& start, float scale, const Vector& direction, Vector& dest );
// Vector equality with tolerance
bool VectorsAreEqual( const Vector& src1, const Vector& src2, float tolerance = 0.0f );
@ -442,6 +452,31 @@ void VectorMax( const Vector &a, const Vector &b, Vector &result );
// Linearly interpolate between two vectors
void VectorLerp(const Vector& src1, const Vector& src2, vec_t t, Vector& dest );
Vector VectorLerp(const Vector& src1, const Vector& src2, vec_t t );
FORCEINLINE Vector ReplicateToVector( float x )
{
return Vector( x, x, x );
}
// check if a point is in the field of a view of an object. supports up to 180 degree fov.
FORCEINLINE bool PointWithinViewAngle( Vector const &vecSrcPosition,
Vector const &vecTargetPosition,
Vector const &vecLookDirection, float flCosHalfFOV )
{
Vector vecDelta = vecTargetPosition - vecSrcPosition;
float cosDiff = DotProduct( vecLookDirection, vecDelta );
if ( cosDiff < 0 )
return false;
float flLen2 = vecDelta.LengthSqr();
// a/sqrt(b) > c == a^2 > b * c ^2
return ( cosDiff * cosDiff > flLen2 * flCosHalfFOV * flCosHalfFOV );
}
#ifndef VECTOR_NO_SLOW_OPERATIONS
@ -453,6 +488,10 @@ Vector RandomVector( vec_t minVal, vec_t maxVal );
#endif
float RandomVectorInUnitSphere( Vector *pVector );
float RandomVectorInUnitCircle( Vector2D *pVector );
//-----------------------------------------------------------------------------
//
// Inlined Vector methods
@ -516,9 +555,9 @@ inline void Vector::Init( vec_t ix, vec_t iy, vec_t iz )
inline void Vector::Random( vec_t minVal, vec_t maxVal )
{
x = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal);
y = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal);
z = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal);
x = minVal + ((float)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
y = minVal + ((float)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
z = minVal + ((float)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
CHECK_VALID(*this);
}
@ -1081,14 +1120,6 @@ inline void VectorScale ( const Vector& in, vec_t scale, Vector& result )
VectorMultiply( in, scale, result );
}
inline void VectorMA( const Vector& start, float scale, const Vector& direction, Vector& dest )
{
CHECK_VALID(start);
CHECK_VALID(direction);
dest.x = start.x + scale * direction.x;
dest.y = start.y + scale * direction.y;
dest.z = start.z + scale * direction.z;
}
FORCEINLINE void VectorDivide( const Vector& a, vec_t b, Vector& c )
{
@ -1130,6 +1161,12 @@ inline void VectorLerp(const Vector& src1, const Vector& src2, vec_t t, Vector&
dest.z = src1.z + (src2.z - src1.z) * t;
}
inline Vector VectorLerp(const Vector& src1, const Vector& src2, vec_t t )
{
Vector result;
VectorLerp( src1, src2, t, result );
return result;
}
//-----------------------------------------------------------------------------
// Temporary storage for vector results so const Vector& results can be returned
@ -1430,6 +1467,13 @@ inline void VectorMax( const Vector &a, const Vector &b, Vector &result )
result.z = fpmax(a.z, b.z);
}
inline float ComputeVolume( const Vector &vecMins, const Vector &vecMaxs )
{
Vector vecDelta;
VectorSubtract( vecMaxs, vecMins, vecDelta );
return DotProduct( vecDelta, vecDelta );
}
// Get a random vector.
inline Vector RandomVector( float minVal, float maxVal )
{
@ -1609,7 +1653,7 @@ public:
}
#endif
};
} ALIGN16_POST;
//-----------------------------------------------------------------------------
@ -1642,6 +1686,9 @@ public:
extern void AngleQuaternion( RadianEuler const &angles, Quaternion &qt );
extern void QuaternionAngles( Quaternion const &q, RadianEuler &angles );
FORCEINLINE void NetworkVarConstruct( Quaternion &q ) { q.x = q.y = q.z = q.w = 0.0f; }
inline Quaternion::Quaternion(RadianEuler const &angle)
{
AngleQuaternion( angle, *this );
@ -1789,6 +1836,8 @@ private:
#endif
};
FORCEINLINE void NetworkVarConstruct( QAngle &q ) { q.x = q.y = q.z = 0.0f; }
//-----------------------------------------------------------------------------
// Allows us to specifically pass the vector by value when we need to
//-----------------------------------------------------------------------------
@ -1852,9 +1901,9 @@ inline void QAngle::Init( vec_t ix, vec_t iy, vec_t iz )
inline void QAngle::Random( vec_t minVal, vec_t maxVal )
{
x = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal);
y = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal);
z = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal);
x = minVal + ((float)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
y = minVal + ((float)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
z = minVal + ((float)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
CHECK_VALID(*this);
}
@ -2127,11 +2176,16 @@ inline void AngularImpulseToQAngle( const AngularImpulse &impulse, QAngle &angle
}
#if !defined( _X360 )
extern float (*pfInvRSquared)( const float *v );
FORCEINLINE vec_t InvRSquared( float const *v )
{
return (*pfInvRSquared)(v);
#if defined(__i386__) || defined(_M_IX86)
float sqrlen = v[0]*v[0]+v[1]*v[1]+v[2]*v[2] + 1.0e-10f, result;
_mm_store_ss(&result, _mm_rcp_ss( _mm_max_ss( _mm_set_ss(1.0f), _mm_load_ss(&sqrlen) ) ));
return result;
#else
return 1.f/fpmax(1.f, v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
#endif
}
FORCEINLINE vec_t InvRSquared( const Vector &v )
@ -2139,36 +2193,63 @@ FORCEINLINE vec_t InvRSquared( const Vector &v )
return InvRSquared(&v.x);
}
#else
// call directly
FORCEINLINE float _VMX_InvRSquared( const Vector &v )
#if defined(__i386__) || defined(_M_IX86)
inline void _SSE_RSqrtInline( float a, float* out )
{
XMVECTOR xmV = XMVector3ReciprocalLength( XMLoadVector3( v.Base() ) );
xmV = XMVector3Dot( xmV, xmV );
return xmV.x;
__m128 xx = _mm_load_ss( &a );
__m128 xr = _mm_rsqrt_ss( xx );
__m128 xt;
xt = _mm_mul_ss( xr, xr );
xt = _mm_mul_ss( xt, xx );
xt = _mm_sub_ss( _mm_set_ss(3.f), xt );
xt = _mm_mul_ss( xt, _mm_set_ss(0.5f) );
xr = _mm_mul_ss( xr, xt );
_mm_store_ss( out, xr );
}
#define InvRSquared(x) _VMX_InvRSquared(x)
#endif // _X360
#if !defined( _X360 )
extern float (FASTCALL *pfVectorNormalize)(Vector& v);
#endif
// FIXME: Change this back to a #define once we get rid of the vec_t version
FORCEINLINE float VectorNormalize( Vector& v )
FORCEINLINE float VectorNormalize( Vector& vec )
{
return (*pfVectorNormalize)(v);
#ifndef DEBUG // stop crashing my edit-and-continue!
#if defined(__i386__) || defined(_M_IX86)
#define DO_SSE_OPTIMIZATION
#endif
#endif
#if defined( DO_SSE_OPTIMIZATION )
float sqrlen = vec.LengthSqr() + 1.0e-10f, invlen;
_SSE_RSqrtInline(sqrlen, &invlen);
vec.x *= invlen;
vec.y *= invlen;
vec.z *= invlen;
return sqrlen * invlen;
#else
extern float (FASTCALL *pfVectorNormalize)(Vector& v);
return (*pfVectorNormalize)(vec);
#endif
}
// FIXME: Obsolete version of VectorNormalize, once we remove all the friggin float*s
FORCEINLINE float VectorNormalize( float * v )
{
return VectorNormalize(*(reinterpret_cast<Vector *>(v)));
}
FORCEINLINE void VectorNormalizeFast( Vector &vec )
{
VectorNormalize(vec);
}
#else
FORCEINLINE float _VMX_InvRSquared( const Vector &v )
{
XMVECTOR xmV = XMVector3ReciprocalLength( XMLoadVector3( v.Base() ) );
xmV = XMVector3Dot( xmV, xmV );
return xmV.x;
}
// call directly
FORCEINLINE float _VMX_VectorNormalize( Vector &vec )
{
@ -2179,6 +2260,9 @@ FORCEINLINE float _VMX_VectorNormalize( Vector &vec )
vec.z *= den;
return mag;
}
#define InvRSquared(x) _VMX_InvRSquared(x)
// FIXME: Change this back to a #define once we get rid of the vec_t version
FORCEINLINE float VectorNormalize( Vector& v )
{
@ -2190,18 +2274,6 @@ FORCEINLINE float VectorNormalize( float *pV )
return _VMX_VectorNormalize(*(reinterpret_cast<Vector*>(pV)));
}
#endif // _X360
#if !defined( _X360 )
extern void (FASTCALL *pfVectorNormalizeFast)(Vector& v);
FORCEINLINE void VectorNormalizeFast( Vector& v )
{
(*pfVectorNormalizeFast)(v);
}
#else
// call directly
FORCEINLINE void VectorNormalizeFast( Vector &vec )
{
@ -2214,11 +2286,19 @@ FORCEINLINE void VectorNormalizeFast( Vector &vec )
#endif // _X360
inline vec_t Vector::NormalizeInPlace()
{
return VectorNormalize( *this );
}
inline Vector Vector::Normalized() const
{
Vector norm = *this;
VectorNormalize( norm );
return norm;
}
inline bool Vector::IsLengthGreaterThan( float val ) const
{
return LengthSqr() > val*val;

View File

@ -1,4 +1,4 @@
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
@ -239,8 +239,8 @@ inline void Vector2D::Init( vec_t ix, vec_t iy )
inline void Vector2D::Random( float minVal, float maxVal )
{
x = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal);
y = minVal + ((float)rand() / RAND_MAX) * (maxVal - minVal);
x = minVal + ((float)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
y = minVal + ((float)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
}
inline void Vector2DClear( Vector2D& a )

View File

@ -132,11 +132,7 @@ const Vector4D vec4_invalid( FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX );
// SSE optimized routines
//-----------------------------------------------------------------------------
#ifdef _WIN32
class __declspec(align(16)) Vector4DAligned : public Vector4D
#elif defined _LINUX || defined __APPLE__
class __attribute__((aligned(16))) Vector4DAligned : public Vector4D
#endif
class ALIGN16 Vector4DAligned : public Vector4D
{
public:
Vector4DAligned(void) {}
@ -154,7 +150,7 @@ private:
// No assignment operators either...
Vector4DAligned& operator=( Vector4DAligned const& src );
};
} ALIGN16_POST;
//-----------------------------------------------------------------------------
// Vector4D related operations
@ -249,10 +245,10 @@ inline void Vector4D::Init( vec_t ix, vec_t iy, vec_t iz, vec_t iw )
inline void Vector4D::Random( vec_t minVal, vec_t maxVal )
{
x = minVal + ((vec_t)rand() / RAND_MAX) * (maxVal - minVal);
y = minVal + ((vec_t)rand() / RAND_MAX) * (maxVal - minVal);
z = minVal + ((vec_t)rand() / RAND_MAX) * (maxVal - minVal);
w = minVal + ((vec_t)rand() / RAND_MAX) * (maxVal - minVal);
x = minVal + ((vec_t)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
y = minVal + ((vec_t)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
z = minVal + ((vec_t)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
w = minVal + ((vec_t)rand() / VALVE_RAND_MAX) * (maxVal - minVal);
}
inline void Vector4DClear( Vector4D& a )

View File

@ -54,6 +54,7 @@ public:
// Creates a matrix where the X axis = forward
// the Y axis = left, and the Z axis = up
VMatrix( const Vector& forward, const Vector& left, const Vector& up );
VMatrix( const Vector& forward, const Vector& left, const Vector& up, const Vector& translation );
// Construct from a 3x4 matrix
VMatrix( const matrix3x4_t& matrix3x4 );
@ -106,7 +107,6 @@ public:
void PreTranslate(const Vector &vTrans);
void PostTranslate(const Vector &vTrans);
matrix3x4_t& As3x4();
const matrix3x4_t& As3x4() const;
void CopyFrom3x4( const matrix3x4_t &m3x4 );
void Set3x4( matrix3x4_t& matrix3x4 ) const;
@ -199,6 +199,9 @@ public:
// Setup a matrix for origin and angles.
void SetupMatrixOrgAngles( const Vector &origin, const QAngle &vAngles );
// Setup a matrix for angles and no translation.
void SetupMatrixAngles( const QAngle &vAngles );
// General inverse. This may fail so check the return!
bool InverseGeneral(VMatrix &vInverse) const;
@ -457,6 +460,16 @@ inline VMatrix::VMatrix( const Vector& xAxis, const Vector& yAxis, const Vector&
);
}
inline VMatrix::VMatrix( const Vector& xAxis, const Vector& yAxis, const Vector& zAxis, const Vector& translation )
{
Init(
xAxis.x, yAxis.x, zAxis.x, translation.x,
xAxis.y, yAxis.y, zAxis.y, translation.y,
xAxis.z, yAxis.z, zAxis.z, translation.z,
0.0f, 0.0f, 0.0f, 1.0f
);
}
inline void VMatrix::Init(
vec_t m00, vec_t m01, vec_t m02, vec_t m03,
@ -616,11 +629,6 @@ inline const matrix3x4_t& VMatrix::As3x4() const
return *((const matrix3x4_t*)this);
}
inline matrix3x4_t& VMatrix::As3x4()
{
return *((matrix3x4_t*)this);
}
inline void VMatrix::CopyFrom3x4( const matrix3x4_t &m3x4 )
{
memcpy( m, m3x4.Base(), sizeof( matrix3x4_t ) );
@ -902,6 +910,7 @@ inline bool MatricesAreEqual( const VMatrix &src1, const VMatrix &src2, float fl
void MatrixBuildOrtho( VMatrix& dst, double left, double top, double right, double bottom, double zNear, double zFar );
void MatrixBuildPerspectiveX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar );
void MatrixBuildPerspectiveOffCenterX( VMatrix& dst, double flFovX, double flAspect, double flZNear, double flZFar, double bottom, double top, double left, double right );
void MatrixBuildPerspectiveZRange( VMatrix& dst, double flZNear, double flZFar );
inline void MatrixOrtho( VMatrix& dst, double left, double top, double right, double bottom, double zNear, double zFar )
{

View File

@ -72,7 +72,7 @@ public:
// Returns the checksums that the stripping info was generated for:
// plChecksumOriginal if non-NULL will hold the checksum of the original model submitted for stripping
// plChecksumStripped if non-NULL will hold the resulting checksum of the stripped model
virtual bool GetCheckSum( long *plChecksumOriginal, long *plChecksumStripped ) const = 0;
virtual bool GetCheckSum( int32_t *plChecksumOriginal, int32_t *plChecksumStripped ) const = 0;
//
// Stripping

Some files were not shown because too many files have changed in this diff Show More