First version of the SOurce SDK 2013

This commit is contained in:
Joe Ludwig
2013-06-26 15:22:04 -07:00
commit 39ed87570b
7469 changed files with 3312656 additions and 0 deletions

View File

@@ -0,0 +1,261 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>Captioncompiler</ProjectName>
<ProjectGuid>{E85D01E5-DA1B-00A2-5D72-A9B6DEA9A995}</ProjectGuid>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>captioncompiler</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>captioncompiler</TargetName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PostBuildEventUseInBuild>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PostBuildEventUseInBuild>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 captioncompiler.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;..\common;..\..\game\shared;.\</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_ITERATOR_DEBUGGING=0;WIN32;_WIN32;_DEBUG;DEBUG;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;captioncompiler;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\captioncompiler;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\captioncompiler.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmt</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Console</SubSystem>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/captioncompiler.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 captioncompiler.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP /d2Zi+</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;..\common;..\..\game\shared;.\</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;captioncompiler;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\captioncompiler;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /DYNAMICBASE /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\captioncompiler.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmtd</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/captioncompiler.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemGroup>
<Library Include="..\..\lib\public\appframework.lib" />
<Library Include="..\..\lib\public\mathlib.lib" />
<Library Include="..\..\lib\public\tier0.lib" />
<Library Include="..\..\lib\public\tier1.lib" />
<Library Include="..\..\lib\public\tier2.lib" />
<Library Include="..\..\lib\public\tier3.lib" />
<Library Include="..\..\lib\public\vstdlib.lib" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="cbase.h" />
<ClInclude Include="..\common\filesystem_tools.h" />
<ClInclude Include="..\common\cmdlib.h" />
<ClInclude Include="..\..\public\filesystem_helpers.h" />
<ClInclude Include="..\..\public\filesystem_init.h" />
<ClInclude Include="..\..\public\mathlib\mathlib.h" />
<ClInclude Include="..\common\pacifier.h" />
<ClInclude Include="..\common\scriplib.h" />
<ClInclude Include="..\..\public\stringregistry.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\common\cmdlib.cpp" />
<ClCompile Include="..\..\public\filesystem_helpers.cpp" />
<ClCompile Include="..\..\public\filesystem_init.cpp" />
<ClCompile Include="..\common\pacifier.cpp" />
<ClCompile Include="..\common\scriplib.cpp" />
<ClCompile Include="..\..\public\stringregistry.cpp" />
<ClCompile Include="captioncompiler.cpp" />
<ClCompile Include="..\..\common\compiledcaptionswap.cpp" />
<ClCompile Include="..\common\filesystem_tools.cpp" />
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)\%(Filename).obj</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)\%(Filename).obj</Outputs>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{1680C80B-FF1E-EA4D-9817-CC12254F2E40}</UniqueIdentifier>
</Filter>
<Filter Include="Link Libraries">
<UniqueIdentifier>{C5D73B3A-C648-896C-B7CE-F174808E5BA5}</UniqueIdentifier>
</Filter>
<Filter Include="Shared Code">
<UniqueIdentifier>{C0A65B3F-3B05-094C-44FA-B1624BAD7BAC}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{BA03E055-4FA2-FCE3-8A1C-D348547D379C}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<Library Include="..\..\lib\public\appframework.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\mathlib.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier0.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier1.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier2.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier3.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\vstdlib.lib">
<Filter>Link Libraries</Filter>
</Library>
</ItemGroup>
<ItemGroup>
<ClInclude Include="cbase.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\common\filesystem_tools.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\common\cmdlib.h">
<Filter>Shared Code</Filter>
</ClInclude>
<ClInclude Include="..\..\public\filesystem_helpers.h">
<Filter>Shared Code</Filter>
</ClInclude>
<ClInclude Include="..\..\public\filesystem_init.h">
<Filter>Shared Code</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\mathlib.h">
<Filter>Shared Code</Filter>
</ClInclude>
<ClInclude Include="..\common\pacifier.h">
<Filter>Shared Code</Filter>
</ClInclude>
<ClInclude Include="..\common\scriplib.h">
<Filter>Shared Code</Filter>
</ClInclude>
<ClInclude Include="..\..\public\stringregistry.h">
<Filter>Shared Code</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\common\cmdlib.cpp">
<Filter>Shared Code</Filter>
</ClCompile>
<ClCompile Include="..\..\public\filesystem_helpers.cpp">
<Filter>Shared Code</Filter>
</ClCompile>
<ClCompile Include="..\..\public\filesystem_init.cpp">
<Filter>Shared Code</Filter>
</ClCompile>
<ClCompile Include="..\common\pacifier.cpp">
<Filter>Shared Code</Filter>
</ClCompile>
<ClCompile Include="..\common\scriplib.cpp">
<Filter>Shared Code</Filter>
</ClCompile>
<ClCompile Include="..\..\public\stringregistry.cpp">
<Filter>Shared Code</Filter>
</ClCompile>
<ClCompile Include="captioncompiler.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\common\compiledcaptionswap.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\common\filesystem_tools.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Filter>Source Files</Filter>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,588 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: vcd_sound_check.cpp : Defines the entry point for the console application.
//
//===========================================================================//
#include <stdio.h>
#include <windows.h>
#include "tier0/dbg.h"
#include "tier1/utldict.h"
#include "filesystem.h"
#include "cmdlib.h"
#include "scriplib.h"
#include "vstdlib/random.h"
#include "tier1/UtlBuffer.h"
#include "pacifier.h"
#include "appframework/tier3app.h"
#include "tier0/icommandline.h"
#include "vgui/IVGui.h"
#include "vgui_controls/controls.h"
#include "vgui/ILocalize.h"
#include "tier1/checksum_crc.h"
#include "tier1/UtlSortVector.h"
#include "tier1/utlmap.h"
#include "captioncompiler.h"
#include "tier0/fasttimer.h"
using namespace vgui;
// #define TESTING 1
bool uselogfile = false;
bool bX360 = false;
struct AnalysisData
{
CUtlSymbolTable symbols;
};
static AnalysisData g_Analysis;
IBaseFileSystem *filesystem = NULL;
static bool spewed = false;
SpewRetval_t SpewFunc( SpewType_t type, char const *pMsg )
{
spewed = true;
printf( "%s", pMsg );
OutputDebugString( pMsg );
if ( type == SPEW_ERROR )
{
printf( "\n" );
OutputDebugString( "\n" );
}
return SPEW_CONTINUE;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : depth -
// *fmt -
// ... -
//-----------------------------------------------------------------------------
void vprint( int depth, const char *fmt, ... )
{
char string[ 8192 ];
va_list va;
va_start( va, fmt );
vsprintf( string, fmt, va );
va_end( va );
FILE *fp = NULL;
if ( uselogfile )
{
fp = fopen( "log.txt", "ab" );
}
while ( depth-- > 0 )
{
printf( " " );
OutputDebugString( " " );
if ( fp )
{
fprintf( fp, " " );
}
}
::printf( string );
OutputDebugString( string );
if ( fp )
{
char *p = string;
while ( *p )
{
if ( *p == '\n' )
{
fputc( '\r', fp );
}
fputc( *p, fp );
p++;
}
fclose( fp );
}
}
void logprint( char const *logfile, const char *fmt, ... )
{
char string[ 8192 ];
va_list va;
va_start( va, fmt );
vsprintf( string, fmt, va );
va_end( va );
FILE *fp = NULL;
static bool first = true;
if ( first )
{
first = false;
fp = fopen( logfile, "wb" );
}
else
{
fp = fopen( logfile, "ab" );
}
if ( fp )
{
char *p = string;
while ( *p )
{
if ( *p == '\n' )
{
fputc( '\r', fp );
}
fputc( *p, fp );
p++;
}
fclose( fp );
}
}
void Con_Printf( const char *fmt, ... )
{
va_list args;
static char output[1024];
va_start( args, fmt );
vprintf( fmt, args );
vsprintf( output, fmt, args );
vprint( 0, output );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void printusage( void )
{
vprint( 0, "usage: captioncompiler closecaptionfile.txt\n\
\t-v = verbose output\n\
\t-l = log to file log.txt\n\
\ne.g.: kvc -l u:/xbox/game/hl2x/resource/closecaption_english.txt" );
// Exit app
exit( 1 );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CheckLogFile( void )
{
if ( uselogfile )
{
_unlink( "log.txt" );
vprint( 0, " Outputting to log.txt\n" );
}
}
void PrintHeader()
{
vprint( 0, "Valve Software - captioncompiler.exe (%s)\n", __DATE__ );
vprint( 0, "--- Close Caption File compiler ---\n" );
}
//-----------------------------------------------------------------------------
// The application object
//-----------------------------------------------------------------------------
class CCompileCaptionsApp : public CTier3SteamApp
{
typedef CTier3SteamApp BaseClass;
public:
// Methods of IApplication
virtual bool Create();
virtual bool PreInit();
virtual int Main();
virtual void PostShutdown();
virtual void Destroy();
private:
// Sets up the search paths
bool SetupSearchPaths();
void CompileCaptionFile( char const *infile, char const *outfile );
void DescribeCaptions( char const *file );
};
bool CCompileCaptionsApp::Create()
{
SpewOutputFunc( SpewFunc );
SpewActivate( "kvc", 2 );
AppSystemInfo_t appSystems[] =
{
{ "vgui2.dll", VGUI_IVGUI_INTERFACE_VERSION },
{ "", "" } // Required to terminate the list
};
return AddSystems( appSystems );
}
void CCompileCaptionsApp::Destroy()
{
}
//-----------------------------------------------------------------------------
// Sets up the game path
//-----------------------------------------------------------------------------
bool CCompileCaptionsApp::SetupSearchPaths()
{
if ( !BaseClass::SetupSearchPaths( NULL, false, true ) )
return false;
// Set gamedir.
Q_MakeAbsolutePath( gamedir, sizeof( gamedir ), GetGameInfoPath() );
Q_AppendSlash( gamedir, sizeof( gamedir ) );
return true;
}
//-----------------------------------------------------------------------------
// Init, shutdown
//-----------------------------------------------------------------------------
bool CCompileCaptionsApp::PreInit( )
{
if ( !BaseClass::PreInit() )
return false;
g_pFileSystem = g_pFullFileSystem;
if ( !g_pFileSystem || !g_pVGui || !g_pVGuiLocalize )
{
Error( "Unable to load required library interface!\n" );
return false;
}
// MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f, false, false, false, false );
g_pFullFileSystem->SetWarningFunc( Warning );
// Add paths...
if ( !SetupSearchPaths() )
return false;
return true;
}
void CCompileCaptionsApp::PostShutdown()
{
g_pFileSystem = NULL;
BaseClass::PostShutdown();
}
void CCompileCaptionsApp::CompileCaptionFile( char const *infile, char const *outfile )
{
StringIndex_t maxindex = (StringIndex_t)-1;
int maxunicodesize = 0;
int totalsize = 0;
int c = 0;
int curblock = 0;
int usedBytes = 0;
int blockSize = MAX_BLOCK_SIZE;
int freeSpace = 0;
CUtlVector< CaptionLookup_t > directory;
CUtlBuffer data;
CUtlRBTree< unsigned int > hashcollision( 0, 0, DefLessFunc( unsigned int ) );
for ( StringIndex_t i = g_pVGuiLocalize->GetFirstStringIndex(); i != INVALID_LOCALIZE_STRING_INDEX; i = g_pVGuiLocalize->GetNextStringIndex( i ), ++c )
{
char const *entryName = g_pVGuiLocalize->GetNameByIndex( i );
CaptionLookup_t entry;
entry.SetHash( entryName );
// vprint( 0, "%d / %d: %s == %u\n", c, i, g_pVGuiLocalize->GetNameByIndex( i ), entry.hash );
if ( hashcollision.Find( entry.hash ) != hashcollision.InvalidIndex() )
{
Error( "Hash name collision on %s!!!\n", g_pVGuiLocalize->GetNameByIndex( i ) );
}
hashcollision.Insert( entry.hash );
const wchar_t *text = g_pVGuiLocalize->GetValueByIndex( i );
if ( verbose )
{
vprint( 0, "Processing: '%30.30s' = '%S'\n", entryName, text );
}
int len = text ? ( wcslen( text ) + 1 ) * sizeof( short ) : 0;
if ( len > maxunicodesize )
{
maxindex = i;
maxunicodesize = len;
}
if ( len > blockSize )
{
Error( "Caption text file '%s' contains a single caption '%s' of %d bytes (%d is max), change MAX_BLOCK_SIZE in captioncompiler.h to fix!!!\n", g_pVGuiLocalize->GetNameByIndex( i ),
entryName, len, blockSize );
}
totalsize += len;
if ( usedBytes + len >= blockSize )
{
++curblock;
int leftover = ( blockSize - usedBytes );
totalsize += leftover;
freeSpace += leftover;
while ( --leftover >= 0 )
{
data.PutChar( 0 );
}
usedBytes = len;
entry.offset = 0;
data.Put( (const void *)text, len );
}
else
{
entry.offset = usedBytes;
usedBytes += len;
data.Put( (const void *)text, len );
}
entry.length = len;
entry.blockNum = curblock;
directory.AddToTail( entry );
}
int leftover = ( blockSize - usedBytes );
totalsize += leftover;
freeSpace += leftover;
while ( --leftover >= 0 )
{
data.PutChar( 0 );
}
vprint( 0, "Found %i strings in '%s'\n", c, infile );
if ( maxindex != INVALID_LOCALIZE_STRING_INDEX )
{
vprint( 0, "Longest string '%s' = (%i) bytes average(%.3f)\n%",
g_pVGuiLocalize->GetNameByIndex( maxindex ), maxunicodesize, (float)totalsize/(float)c );
}
vprint( 0, "%d blocks (%d bytes each), %d bytes wasted (%.3f per block average), total bytes %d\n",
curblock + 1, blockSize, freeSpace, (float)freeSpace/(float)( curblock + 1 ), totalsize );
vprint( 0, "directory size %d entries, %d bytes, data size %d bytes\n",
directory.Count(), directory.Count() * sizeof( CaptionLookup_t ), data.TellPut() );
CompiledCaptionHeader_t header;
header.magic = COMPILED_CAPTION_FILEID;
header.version = COMPILED_CAPTION_VERSION;
header.numblocks = curblock + 1;
header.blocksize = blockSize;
header.directorysize = directory.Count();
header.dataoffset = 0;
// Now write the outfile
CUtlBuffer out;
out.Put( &header, sizeof( header ) );
out.Put( directory.Base(), directory.Count() * sizeof( CaptionLookup_t ) );
int curOffset = out.TellPut();
// Round it up to the next 512 byte boundary
int nBytesDestBuffer = AlignValue( curOffset, 512 ); // align to HD sector
int nPadding = nBytesDestBuffer - curOffset;
while ( --nPadding >= 0 )
{
out.PutChar( 0 );
}
out.Put( data.Base(), data.TellPut() );
// Write out a corrected header
header.dataoffset = nBytesDestBuffer;
int savePos = out.TellPut();
out.SeekPut( CUtlBuffer::SEEK_HEAD, 0 );
out.Put( &header, sizeof( header ) );
out.SeekPut( CUtlBuffer::SEEK_HEAD, savePos );
g_pFullFileSystem->WriteFile( outfile, NULL, out );
// Jeep: this function no longer exisits
/*if ( bX360 )
{
UpdateOrCreateCaptionFile_X360( g_pFullFileSystem, outfile, NULL, true );
}*/
}
void CCompileCaptionsApp::DescribeCaptions( char const *file )
{
CUtlBuffer buf;
if ( !g_pFullFileSystem->ReadFile( file, NULL, buf ) )
{
Error( "Unable to read '%s' into buffer\n", file );
}
CompiledCaptionHeader_t header;
buf.Get( &header, sizeof( header ) );
if ( header.magic != COMPILED_CAPTION_FILEID )
Error( "Invalid file id for %s\n", file );
if ( header.version != COMPILED_CAPTION_VERSION )
Error( "Invalid file version for %s\n", file );
// Read the directory
CUtlSortVector< CaptionLookup_t, CCaptionLookupLess > directory;
directory.EnsureCapacity( header.directorysize );
directory.CopyArray( (const CaptionLookup_t *)buf.PeekGet(), header.directorysize );
directory.RedoSort( true );
buf.SeekGet( CUtlBuffer::SEEK_HEAD, header.dataoffset );
int i;
CUtlVector< CaptionBlock_t > blocks;
for ( i = 0; i < header.numblocks; ++i )
{
CaptionBlock_t& newBlock = blocks[ blocks.AddToTail() ];
Q_memset( newBlock.data, 0, sizeof( newBlock.data ) );
buf.Get( newBlock.data, header.blocksize );
}
CUtlMap< unsigned int, StringIndex_t > inverseMap( 0, 0, DefLessFunc( unsigned int ) );
for ( StringIndex_t idx = g_pVGuiLocalize->GetFirstStringIndex(); idx != INVALID_LOCALIZE_STRING_INDEX; idx = g_pVGuiLocalize->GetNextStringIndex( idx ) )
{
const char *name = g_pVGuiLocalize->GetNameByIndex( idx );
CaptionLookup_t dummy;
dummy.SetHash( name );
inverseMap.Insert( dummy.hash, idx );
}
// Now print everything out...
for ( i = 0; i < header.directorysize; ++i )
{
const CaptionLookup_t& entry = directory[ i ];
char const *name = g_pVGuiLocalize->GetNameByIndex( inverseMap.Element( inverseMap.Find( entry.hash ) ) );
const CaptionBlock_t& block = blocks[ entry.blockNum ];
const wchar_t *data = (const wchar_t *)&block.data[ entry.offset ];
wchar_t *temp = ( wchar_t * )_alloca( entry.length * sizeof( short ) );
wcsncpy( temp, data, ( entry.length / sizeof( short ) ) - 1 );
vprint( 0, "%3.3d: (%40.40s) hash(%15.15u), block(%4.4d), offset(%4.4d), len(%4.4d) %S\n",
i, name, entry.hash, entry.blockNum, entry.offset, entry.length, temp );
}
}
//-----------------------------------------------------------------------------
// main application
//-----------------------------------------------------------------------------
int CCompileCaptionsApp::Main()
{
CUtlVector< CUtlSymbol > worklist;
int i = 1;
for ( i ; i<CommandLine()->ParmCount() ; i++)
{
if ( CommandLine()->GetParm( i )[ 0 ] == '-' )
{
switch( CommandLine()->GetParm( i )[ 1 ] )
{
case 'l':
uselogfile = true;
break;
case 'v':
verbose = true;
break;
case 'x':
bX360 = true;
break;
case 'g': // -game
++i;
break;
default:
printusage();
break;
}
}
else if ( i != 0 )
{
char fn[ 512 ];
Q_strncpy( fn, CommandLine()->GetParm( i ), sizeof( fn ) );
Q_FixSlashes( fn );
Q_strlower( fn );
CUtlSymbol sym;
sym = fn;
worklist.AddToTail( sym );
}
}
if ( CommandLine()->ParmCount() < 2 || ( i != CommandLine()->ParmCount() ) || worklist.Count() != 1 )
{
PrintHeader();
printusage();
}
CheckLogFile();
PrintHeader();
char binaries[MAX_PATH];
Q_strncpy( binaries, gamedir, MAX_PATH );
Q_StripTrailingSlash( binaries );
Q_strncat( binaries, "/../bin", MAX_PATH, MAX_PATH );
char outfile[ 512 ];
if ( Q_stristr( worklist[ worklist.Count() - 1 ].String(), gamedir ) )
{
Q_strncpy( outfile, &worklist[ worklist.Count() - 1 ].String()[ Q_strlen( gamedir ) ] , sizeof( outfile ) );
}
else
{
Q_snprintf( outfile, sizeof( outfile ), "resource\\%s", worklist[ worklist.Count() - 1 ].String() );
}
char infile[ 512 ];
Q_strncpy( infile, outfile, sizeof( infile ) );
Q_SetExtension( outfile, ".dat", sizeof( outfile ) );
vprint( 0, "gamedir[ %s ]\n", gamedir );
vprint( 0, "infile[ %s ]\n", infile );
vprint( 0, "outfile[ %s ]\n", outfile );
g_pFullFileSystem->AddSearchPath( binaries, "EXECUTABLE_PATH" );
if ( !g_pVGuiLocalize->AddFile( infile, "MOD", false ) )
{
Error( "Unable to add localization file '%s'\n", infile );
}
vprint( 0, " Compiling Captions for '%s'...\n", infile );
CompileCaptionFile( infile, outfile );
if ( verbose )
{
DescribeCaptions( outfile );
}
g_pVGuiLocalize->RemoveAll();
return 0;
}
//-----------------------------------------------------------------------------
// Purpose: Main entry point
//-----------------------------------------------------------------------------
DEFINE_CONSOLE_STEAM_APPLICATION_OBJECT( CCompileCaptionsApp )

View File

@@ -0,0 +1,19 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================
#ifndef CBASE_H
#define CBASE_H
#ifdef _WIN32
#pragma once
#endif
#include "basetypes.h"
// This is just a dummy file to make this tool compile
#include "ai_activity.h"
#include "utlvector.h"
#endif // CBASE_H

View File

@@ -0,0 +1,29 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef ISQLDLREPLYTARGET_H
#define ISQLDLREPLYTARGET_H
#ifdef _WIN32
#pragma once
#endif
//-----------------------------------------------------------------------------
// Purpose: Interface to handle results of SQL queries
//-----------------------------------------------------------------------------
class ISQLDBReplyTarget
{
public:
// handles a response from the database
virtual void SQLDBResponse(int cmdID, int returnState, int returnVal, void *data) = 0;
// called from a seperate thread; tells the reply target that a message is waiting for it
virtual void WakeUp() = 0;
};
#endif // ISQLDLREPLYTARGET_H

View File

@@ -0,0 +1,192 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "MySqlDatabase.h"
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
CMySqlDatabase::CMySqlDatabase()
{
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
// blocks until db process thread has stopped
//-----------------------------------------------------------------------------
CMySqlDatabase::~CMySqlDatabase()
{
// flag the thread to stop
m_bRunThread = false;
// pulse the thread to make it run
::SetEvent(m_hEvent);
// make sure it's done
::EnterCriticalSection(&m_csThread);
::LeaveCriticalSection(&m_csThread);
}
//-----------------------------------------------------------------------------
// Purpose: Thread access function
//-----------------------------------------------------------------------------
static DWORD WINAPI staticThreadFunc(void *param)
{
((CMySqlDatabase *)param)->RunThread();
return 0;
}
//-----------------------------------------------------------------------------
// Purpose: Establishes connection to the database and sets up this object to handle db command
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CMySqlDatabase::Initialize()
{
// prepare critical sections
//!! need to download SDK and replace these with InitializeCriticalSectionAndSpinCount() calls
::InitializeCriticalSection(&m_csThread);
::InitializeCriticalSection(&m_csInQueue);
::InitializeCriticalSection(&m_csOutQueue);
::InitializeCriticalSection(&m_csDBAccess);
// initialize wait calls
m_hEvent = ::CreateEvent(NULL, false, true, NULL);
// start the DB-access thread
m_bRunThread = true;
unsigned long threadID;
::CreateThread(NULL, 0, staticThreadFunc, this, 0, &threadID);
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Main thread loop
//-----------------------------------------------------------------------------
void CMySqlDatabase::RunThread()
{
::EnterCriticalSection(&m_csThread);
while (m_bRunThread)
{
if (m_InQueue.Count() > 0)
{
// get a dispatched DB request
::EnterCriticalSection(&m_csInQueue);
// pop the front of the queue
int headIndex = m_InQueue.Head();
msg_t msg = m_InQueue[headIndex];
m_InQueue.Remove(headIndex);
::LeaveCriticalSection(&m_csInQueue);
::EnterCriticalSection(&m_csDBAccess);
// run sqldb command
msg.result = msg.cmd->RunCommand();
::LeaveCriticalSection(&m_csDBAccess);
if (msg.replyTarget)
{
// put the results in the outgoing queue
::EnterCriticalSection(&m_csOutQueue);
m_OutQueue.AddToTail(msg);
::LeaveCriticalSection(&m_csOutQueue);
// wake up out queue
msg.replyTarget->WakeUp();
}
else
{
// there is no return data from the call, so kill the object now
msg.cmd->deleteThis();
}
}
else
{
// nothing in incoming queue, so wait until we get the signal
::WaitForSingleObject(m_hEvent, INFINITE);
}
// check the size of the outqueue; if it's getting too big, sleep to let the main thread catch up
if (m_OutQueue.Count() > 50)
{
::Sleep(2);
}
}
::LeaveCriticalSection(&m_csThread);
}
//-----------------------------------------------------------------------------
// Purpose: Adds a database command to the queue, and wakes the db thread
//-----------------------------------------------------------------------------
void CMySqlDatabase::AddCommandToQueue(ISQLDBCommand *cmd, ISQLDBReplyTarget *replyTarget, int returnState)
{
::EnterCriticalSection(&m_csInQueue);
// add to the queue
msg_t msg = { cmd, replyTarget, 0, returnState };
m_InQueue.AddToTail(msg);
::LeaveCriticalSection(&m_csInQueue);
// signal the thread to start running
::SetEvent(m_hEvent);
}
//-----------------------------------------------------------------------------
// Purpose: Dispatches responses to SQLDB queries
//-----------------------------------------------------------------------------
bool CMySqlDatabase::RunFrame()
{
bool doneWork = false;
while (m_OutQueue.Count() > 0)
{
::EnterCriticalSection(&m_csOutQueue);
// pop the first item in the queue
int headIndex = m_OutQueue.Head();
msg_t msg = m_OutQueue[headIndex];
m_OutQueue.Remove(headIndex);
::LeaveCriticalSection(&m_csOutQueue);
// run result
if (msg.replyTarget)
{
msg.replyTarget->SQLDBResponse(msg.cmd->GetID(), msg.returnState, msg.result, msg.cmd->GetReturnData());
// kill command
// it would be a good optimization to be able to reuse these
msg.cmd->deleteThis();
}
doneWork = true;
}
return doneWork;
}
//-----------------------------------------------------------------------------
// Purpose: load info - returns the number of sql db queries waiting to be processed
//-----------------------------------------------------------------------------
int CMySqlDatabase::QueriesInOutQueue()
{
// the queue names are from the DB point of view, not the server - thus the reversal
return m_InQueue.Count();
}
//-----------------------------------------------------------------------------
// Purpose: number of queries finished processing, waiting to be responded to
//-----------------------------------------------------------------------------
int CMySqlDatabase::QueriesInFinishedQueue()
{
return m_OutQueue.Count();
}

View File

@@ -0,0 +1,104 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef MYSQLDATABASE_H
#define MYSQLDATABASE_H
#ifdef _WIN32
#pragma once
#endif
#include <windows.h>
#include "ISQLDBReplyTarget.h"
#include "utlvector.h"
#include "UtlLinkedList.h"
class ISQLDBCommand;
//-----------------------------------------------------------------------------
// Purpose: Generic MySQL accessing database
// Provides threaded I/O queue functionality for accessing a mysql db
//-----------------------------------------------------------------------------
class CMySqlDatabase
{
public:
// constructor
CMySqlDatabase();
~CMySqlDatabase();
// initialization - must be called before this object can be used
bool Initialize();
// Dispatches responses to SQLDB queries
bool RunFrame();
// load info - returns the number of sql db queries waiting to be processed
virtual int QueriesInOutQueue();
// number of queries finished processing, waiting to be responded to
virtual int QueriesInFinishedQueue();
// activates the thread
void RunThread();
// command queues
void AddCommandToQueue(ISQLDBCommand *cmd, ISQLDBReplyTarget *replyTarget, int returnState = 0);
private:
// threading data
bool m_bRunThread;
CRITICAL_SECTION m_csThread;
CRITICAL_SECTION m_csInQueue;
CRITICAL_SECTION m_csOutQueue;
CRITICAL_SECTION m_csDBAccess;
// wait event
HANDLE m_hEvent;
struct msg_t
{
ISQLDBCommand *cmd;
ISQLDBReplyTarget *replyTarget;
int result;
int returnState;
};
// command queues
CUtlLinkedList<msg_t, int> m_InQueue;
CUtlLinkedList<msg_t, int> m_OutQueue;
};
class Connection;
//-----------------------------------------------------------------------------
// Purpose: Interface to a command
//-----------------------------------------------------------------------------
class ISQLDBCommand
{
public:
// makes the command run (blocking), returning the success code
virtual int RunCommand() = 0;
// return data
virtual void *GetReturnData() { return NULL; }
// returns the command ID
virtual int GetID() { return 0; }
// gets information about the command for if it failed
virtual void GetDebugInfo(char *buf, int bufSize) { buf[0] = 0; }
// use to delete
virtual void deleteThis() = 0;
protected:
// protected destructor, so that it has to be deleted through deleteThis()
virtual ~ISQLDBCommand() {}
};
#endif // MYSQLDATABASE_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,404 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#ifndef BSPLIB_H
#define BSPLIB_H
#ifdef _WIN32
#pragma once
#endif
#include "bspfile.h"
#include "utlvector.h"
#include "utlstring.h"
#include "utllinkedlist.h"
#include "byteswap.h"
#ifdef ENGINE_DLL
#include "zone.h"
#endif
#ifdef ENGINE_DLL
typedef CUtlVector<unsigned char, CHunkMemory<unsigned char> > CDispLightmapSamplePositions;
#else
typedef CUtlVector<unsigned char> CDispLightmapSamplePositions;
#endif
class ISpatialQuery;
struct Ray_t;
class Vector2D;
struct portal_t;
class CUtlBuffer;
class IZip;
// this is only true in vrad
extern bool g_bHDR;
// default width/height of luxels in world units.
#define DEFAULT_LUXEL_SIZE ( 16.0f )
#define SINGLE_BRUSH_MAP (MAX_BRUSH_LIGHTMAP_DIM_INCLUDING_BORDER*MAX_BRUSH_LIGHTMAP_DIM_INCLUDING_BORDER)
#define SINGLEMAP (MAX_LIGHTMAP_DIM_INCLUDING_BORDER*MAX_LIGHTMAP_DIM_INCLUDING_BORDER)
struct entity_t
{
Vector origin;
int firstbrush;
int numbrushes;
epair_t *epairs;
// only valid for func_areaportals
int areaportalnum;
int portalareas[2];
portal_t *m_pPortalsLeadingIntoAreas[2]; // portals leading into portalareas
};
extern int num_entities;
extern entity_t entities[MAX_MAP_ENTITIES];
extern int nummodels;
extern dmodel_t dmodels[MAX_MAP_MODELS];
extern int visdatasize;
extern byte dvisdata[MAX_MAP_VISIBILITY];
extern dvis_t *dvis;
extern CUtlVector<byte> dlightdataHDR;
extern CUtlVector<byte> dlightdataLDR;
extern CUtlVector<byte> *pdlightdata;
extern CUtlVector<char> dentdata;
extern int numleafs;
#if !defined( _X360 )
extern dleaf_t dleafs[MAX_MAP_LEAFS];
#else
extern dleaf_t *dleafs;
#endif
extern CUtlVector<dleafambientlighting_t> *g_pLeafAmbientLighting;
extern CUtlVector<dleafambientindex_t> *g_pLeafAmbientIndex;
extern unsigned short g_LeafMinDistToWater[MAX_MAP_LEAFS];
extern int numplanes;
extern dplane_t dplanes[MAX_MAP_PLANES];
extern int numvertexes;
extern dvertex_t dvertexes[MAX_MAP_VERTS];
extern int g_numvertnormalindices; // dfaces reference these. These index g_vertnormals.
extern unsigned short g_vertnormalindices[MAX_MAP_VERTNORMALS];
extern int g_numvertnormals;
extern Vector g_vertnormals[MAX_MAP_VERTNORMALS];
extern int numnodes;
extern dnode_t dnodes[MAX_MAP_NODES];
extern CUtlVector<texinfo_t> texinfo;
extern int numtexdata;
extern dtexdata_t dtexdata[MAX_MAP_TEXDATA];
// displacement map .bsp file info
extern CUtlVector<ddispinfo_t> g_dispinfo;
extern CUtlVector<CDispVert> g_DispVerts;
extern CUtlVector<CDispTri> g_DispTris;
extern CDispLightmapSamplePositions g_DispLightmapSamplePositions; // LUMP_DISP_LIGHTMAP_SAMPLE_POSITIONS
extern int numorigfaces;
extern dface_t dorigfaces[MAX_MAP_FACES];
extern int g_numprimitives;
extern dprimitive_t g_primitives[MAX_MAP_PRIMITIVES];
extern int g_numprimverts;
extern dprimvert_t g_primverts[MAX_MAP_PRIMVERTS];
extern int g_numprimindices;
extern unsigned short g_primindices[MAX_MAP_PRIMINDICES];
extern int numfaces;
extern dface_t dfaces[MAX_MAP_FACES];
extern int numfaceids;
extern CUtlVector<dfaceid_t> dfaceids;
extern int numfaces_hdr;
extern dface_t dfaces_hdr[MAX_MAP_FACES];
extern int numedges;
extern dedge_t dedges[MAX_MAP_EDGES];
extern int numleaffaces;
extern unsigned short dleaffaces[MAX_MAP_LEAFFACES];
extern int numleafbrushes;
extern unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES];
extern int numsurfedges;
extern int dsurfedges[MAX_MAP_SURFEDGES];
extern int numareas;
extern darea_t dareas[MAX_MAP_AREAS];
extern int numareaportals;
extern dareaportal_t dareaportals[MAX_MAP_AREAPORTALS];
extern int numbrushes;
extern dbrush_t dbrushes[MAX_MAP_BRUSHES];
extern int numbrushsides;
extern dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES];
extern int *pNumworldlights;
extern dworldlight_t *dworldlights;
extern Vector g_ClipPortalVerts[MAX_MAP_PORTALVERTS];
extern int g_nClipPortalVerts;
extern dcubemapsample_t g_CubemapSamples[MAX_MAP_CUBEMAPSAMPLES];
extern int g_nCubemapSamples;
extern int g_nOverlayCount;
extern doverlay_t g_Overlays[MAX_MAP_OVERLAYS];
extern doverlayfade_t g_OverlayFades[MAX_MAP_OVERLAYS]; // Parallel array of fade info in a separate lump to avoid breaking backwards compat
extern int g_nWaterOverlayCount;
extern dwateroverlay_t g_WaterOverlays[MAX_MAP_WATEROVERLAYS];
extern CUtlVector<char> g_TexDataStringData;
extern CUtlVector<int> g_TexDataStringTable;
extern int numleafwaterdata;
extern dleafwaterdata_t dleafwaterdata[MAX_MAP_LEAFWATERDATA];
extern CUtlVector<CFaceMacroTextureInfo> g_FaceMacroTextureInfos;
extern CUtlVector<doccluderdata_t> g_OccluderData;
extern CUtlVector<doccluderpolydata_t> g_OccluderPolyData;
extern CUtlVector<int> g_OccluderVertexIndices;
// level flags - see LVLFLAGS_xxx in bspfile.h
extern uint32 g_LevelFlags;
// physics collision data
extern byte *g_pPhysCollide;
extern int g_PhysCollideSize;
extern byte *g_pPhysDisp;
extern int g_PhysDispSize;
// Embedded pack/pak file
IZip *GetPakFile( void );
IZip *GetSwapPakFile( void );
void ClearPakFile( IZip *pak );
void AddFileToPak( IZip *pak, const char *pRelativeName, const char *fullpath );
void AddBufferToPak( IZip *pak, const char *pRelativeName, void *data, int length, bool bTextMode );
bool FileExistsInPak( IZip *pak, const char *pRelativeName );
bool ReadFileFromPak( IZip *pak, const char *pRelativeName, bool bTextMode, CUtlBuffer &buf );
void RemoveFileFromPak( IZip *pak, const char *pRelativeName );
int GetNextFilename( IZip *pak, int id, char *pBuffer, int bufferSize, int &fileSize );
void ForceAlignment( IZip *pak, bool bAlign, bool bCompatibleFormat, unsigned int alignmentSize );
typedef bool (*CompressFunc_t)( CUtlBuffer &inputBuffer, CUtlBuffer &outputBuffer );
typedef bool (*VTFConvertFunc_t)( const char *pDebugName, CUtlBuffer &sourceBuf, CUtlBuffer &targetBuf, CompressFunc_t pCompressFunc );
typedef bool (*VHVFixupFunc_t)( const char *pVhvFilename, const char *pModelName, CUtlBuffer &sourceBuf, CUtlBuffer &targetBuf );
//-----------------------------------------------------------------------------
// Game lump memory storage
//-----------------------------------------------------------------------------
// NOTE: This is not optimal at all; since I expect client lumps to
// not be accessed all that often.
struct GameLump_t
{
GameLumpId_t m_Id;
unsigned short m_Flags;
unsigned short m_Version;
CUtlMemory< unsigned char > m_Memory;
};
//-----------------------------------------------------------------------------
// Handle to a game lump
//-----------------------------------------------------------------------------
typedef unsigned short GameLumpHandle_t;
class CGameLump
{
public:
//-----------------------------------------------------------------------------
// Convert four-CC code to a handle + back
//-----------------------------------------------------------------------------
GameLumpHandle_t GetGameLumpHandle( GameLumpId_t id );
GameLumpId_t GetGameLumpId( GameLumpHandle_t handle );
int GetGameLumpFlags( GameLumpHandle_t handle );
int GetGameLumpVersion( GameLumpHandle_t handle );
void ComputeGameLumpSizeAndCount( int& size, int& clumpCount );
void ParseGameLump( dheader_t* pHeader );
void SwapGameLump( GameLumpId_t id, int version, byte *dest, byte *src, int size );
//-----------------------------------------------------------------------------
// Game lump accessor methods
//-----------------------------------------------------------------------------
void* GetGameLump( GameLumpHandle_t handle );
int GameLumpSize( GameLumpHandle_t handle );
//-----------------------------------------------------------------------------
// Game lump iteration methods
//-----------------------------------------------------------------------------
GameLumpHandle_t FirstGameLump();
GameLumpHandle_t NextGameLump( GameLumpHandle_t handle );
GameLumpHandle_t InvalidGameLump();
//-----------------------------------------------------------------------------
// Game lump creation/destruction method
//-----------------------------------------------------------------------------
GameLumpHandle_t CreateGameLump( GameLumpId_t id, int size, int flags, int version );
void DestroyGameLump( GameLumpHandle_t handle );
void DestroyAllGameLumps();
private:
CUtlLinkedList< GameLump_t, GameLumpHandle_t > m_GameLumps;
};
extern CGameLump g_GameLumps;
extern CByteswap g_Swap;
//-----------------------------------------------------------------------------
// Helper for the bspzip tool
//-----------------------------------------------------------------------------
void ExtractZipFileFromBSP( char *pBSPFileName, char *pZipFileName );
//-----------------------------------------------------------------------------
// String table methods
//-----------------------------------------------------------------------------
const char * TexDataStringTable_GetString( int stringID );
int TexDataStringTable_AddOrFindString( const char *pString );
void DecompressVis (byte *in, byte *decompressed);
int CompressVis (byte *vis, byte *dest);
void OpenBSPFile( const char *filename );
void CloseBSPFile(void);
void LoadBSPFile( const char *filename );
void LoadBSPFile_FileSystemOnly( const char *filename );
void LoadBSPFileTexinfo( const char *filename );
void WriteBSPFile( const char *filename, char *pUnused = NULL );
void PrintBSPFileSizes(void);
void PrintBSPPackDirectory(void);
void ReleasePakFileLumps(void);
bool SwapBSPFile( const char *filename, const char *swapFilename, bool bSwapOnLoad, VTFConvertFunc_t pVTFConvertFunc, VHVFixupFunc_t pVHVFixupFunc, CompressFunc_t pCompressFunc );
bool GetPakFileLump( const char *pBSPFilename, void **pPakData, int *pPakSize );
bool SetPakFileLump( const char *pBSPFilename, const char *pNewFilename, void *pPakData, int pakSize );
void WriteLumpToFile( char *filename, int lump );
void WriteLumpToFile( char *filename, int lump, int nLumpVersion, void *pBuffer, size_t nBufLen );
bool GetBSPDependants( const char *pBSPFilename, CUtlVector< CUtlString > *pList );
void UnloadBSPFile();
void ParseEntities (void);
void UnparseEntities (void);
void PrintEntity (entity_t *ent);
void SetKeyValue (entity_t *ent, const char *key, const char *value);
char *ValueForKey (entity_t *ent, char *key);
// will return "" if not present
int IntForKey (entity_t *ent, char *key);
int IntForKeyWithDefault(entity_t *ent, char *key, int nDefault );
vec_t FloatForKey (entity_t *ent, char *key);
vec_t FloatForKeyWithDefault (entity_t *ent, char *key, float default_value);
void GetVectorForKey (entity_t *ent, char *key, Vector& vec);
void GetVector2DForKey (entity_t *ent, char *key, Vector2D& vec);
void GetAnglesForKey (entity_t *ent, char *key, QAngle& vec);
epair_t *ParseEpair (void);
void StripTrailing (char *e);
// Build a list of the face's vertices (index into dvertexes).
// points must be able to hold pFace->numedges indices.
void BuildFaceCalcWindingData( dface_t *pFace, int *points );
// Convert a tristrip to a trilist.
// Removes degenerates.
// Fills in pTriListIndices and pnTriListIndices.
// You must free pTriListIndices with delete[].
void TriStripToTriList(
unsigned short const *pTriStripIndices,
int nTriStripIndices,
unsigned short **pTriListIndices,
int *pnTriListIndices );
// Calculates the lightmap coordinates at a given set of positions given the
// lightmap basis information.
void CalcTextureCoordsAtPoints(
float const texelsPerWorldUnits[2][4],
int const subtractOffset[2],
Vector const *pPoints,
int const nPoints,
Vector2D *pCoords );
// Figure out lightmap extents on all (lit) faces.
void UpdateAllFaceLightmapExtents();
//-----------------------------------------------------------------------------
// Gets at an interface for the tree for enumeration of leaves in volumes.
//-----------------------------------------------------------------------------
ISpatialQuery* ToolBSPTree();
class IBSPNodeEnumerator
{
public:
// call back with a node and a context
virtual bool EnumerateNode( int node, Ray_t const& ray, float f, int context ) = 0;
// call back with a leaf and a context
virtual bool EnumerateLeaf( int leaf, Ray_t const& ray, float start, float end, int context ) = 0;
};
//-----------------------------------------------------------------------------
// Enumerates nodes + leafs in front to back order...
//-----------------------------------------------------------------------------
bool EnumerateNodesAlongRay( Ray_t const& ray, IBSPNodeEnumerator* pEnum, int context );
//-----------------------------------------------------------------------------
// Helps us find all leaves associated with a particular cluster
//-----------------------------------------------------------------------------
struct clusterlist_t
{
int leafCount;
CUtlVector<int> leafs;
};
extern CUtlVector<clusterlist_t> g_ClusterLeaves;
// Call this to build the mapping from cluster to leaves
void BuildClusterTable( );
void GetPlatformMapPath( const char *pMapPath, char *pPlatformMapPath, int dxlevel, int maxLength );
void SetHDRMode( bool bHDR );
// ----------------------------------------------------------------------------- //
// Helper accessors for the various structures.
// ----------------------------------------------------------------------------- //
inline ColorRGBExp32* dface_AvgLightColor( dface_t *pFace, int nLightStyleIndex )
{
return (ColorRGBExp32*)&(*pdlightdata)[pFace->lightofs - (nLightStyleIndex+1) * 4];
}
inline const char* TexInfo_TexName( int iTexInfo )
{
return TexDataStringTable_GetString( dtexdata[texinfo[iTexInfo].texdata].nameStringTableID );
}
#endif // BSPLIB_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,178 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#ifndef CMDLIB_H
#define CMDLIB_H
#ifdef _WIN32
#pragma once
#endif
// cmdlib.h
#include "basetypes.h"
// This can go away when everything is in bin.
#if defined( CMDLIB_NODBGLIB )
void Error( PRINTF_FORMAT_STRING char const *pMsg, ... );
#else
#include "tier0/dbg.h"
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <stdarg.h>
#include "filesystem.h"
#include "filesystem_tools.h"
#include "tier1/utlstring.h"
// Tools should use this as the read path ID. It'll look into the paths specified by gameinfo.txt
#define TOOLS_READ_PATH_ID "GAME"
// Tools should use this to fprintf data to files.
void CmdLib_FPrintf( FileHandle_t hFile, PRINTF_FORMAT_STRING const char *pFormat, ... );
char* CmdLib_FGets( char *pOut, int outSize, FileHandle_t hFile );
// This can be set so Msg() sends output to hook functions (like the VMPI MySQL database),
// but doesn't actually printf the output.
extern bool g_bSuppressPrintfOutput;
extern IBaseFileSystem *g_pFileSystem;
// These call right into the functions in filesystem_tools.h
void CmdLib_InitFileSystem( const char *pFilename, int maxMemoryUsage = 0 );
void CmdLib_TermFileSystem(); // GracefulExit calls this.
CreateInterfaceFn CmdLib_GetFileSystemFactory();
#ifdef _WIN32
#pragma warning(disable : 4244) // MIPS
#pragma warning(disable : 4136) // X86
#pragma warning(disable : 4051) // ALPHA
#pragma warning(disable : 4018) // signed/unsigned mismatch
#pragma warning(disable : 4305) // truncate from double to float
#pragma warning(disable : 4389) // singned/unsigned mismatch in ==
#pragma warning(disable: 4512) // assignment operator could not be generated
#endif
// the dec offsetof macro doesnt work very well...
#define myoffsetof(type,identifier) offsetof( type, identifier )
// set these before calling CheckParm
extern int myargc;
extern char **myargv;
int Q_filelength (FileHandle_t f);
int FileTime (char *path);
void Q_mkdir( char *path );
char *ExpandArg (char *path); // expand relative to CWD
char *ExpandPath (char *path); // expand relative to gamedir
char *ExpandPathAndArchive (char *path);
// Fills in pOut with "X hours, Y minutes, Z seconds". Leaves out hours or minutes if they're zero.
void GetHourMinuteSecondsString( int nInputSeconds, char *pOut, int outLen );
int CheckParm (char *check);
FileHandle_t SafeOpenWrite ( const char *filename );
FileHandle_t SafeOpenRead ( const char *filename );
void SafeRead( FileHandle_t f, void *buffer, int count);
void SafeWrite( FileHandle_t f, void *buffer, int count);
int LoadFile ( const char *filename, void **bufferptr );
void SaveFile ( const char *filename, void *buffer, int count );
qboolean FileExists ( const char *filename );
int ParseNum (char *str);
// Do a printf in the specified color.
#define CP_ERROR stderr, 1, 0, 0, 1 // default colors..
#define CP_WARNING stderr, 1, 1, 0, 1
#define CP_STARTUP stdout, 0, 1, 1, 1
#define CP_NOTIFY stdout, 1, 1, 1, 1
void ColorPrintf( FILE *pFile, bool red, bool green, bool blue, bool intensity, PRINTF_FORMAT_STRING char const *pFormat, ... );
// Initialize spew output.
void InstallSpewFunction();
// This registers an extra callback for spew output.
typedef void (*SpewHookFn)( const char * );
void InstallExtraSpewHook( SpewHookFn pFn );
// Install allocation hooks so we error out if an allocation can't happen.
void InstallAllocationFunctions();
// This shuts down mgrs that use threads gracefully. If you just call exit(), the threads can
// get in a state where you can't tell if they are shutdown or not, and it can stall forever.
typedef void (*CleanupFn)();
void CmdLib_AtCleanup( CleanupFn pFn ); // register a callback when Cleanup() is called.
void CmdLib_Cleanup();
void CmdLib_Exit( int exitCode ); // Use this to cleanup and call exit().
// entrypoint if chaining spew functions
SpewRetval_t CmdLib_SpewOutputFunc( SpewType_t type, char const *pMsg );
unsigned short SetConsoleTextColor( int red, int green, int blue, int intensity );
void RestoreConsoleTextColor( unsigned short color );
// Append all spew output to the specified file.
void SetSpewFunctionLogFile( char const *pFilename );
char *COM_Parse (char *data);
extern char com_token[1024];
char *copystring(const char *s);
void CreatePath( char *path );
void QCopyFile( char *from, char *to );
void SafeCreatePath( char *path );
extern qboolean archive;
extern char archivedir[1024];
extern qboolean verbose;
void qprintf( PRINTF_FORMAT_STRING const char *format, ... );
void ExpandWildcards (int *argc, char ***argv);
void CmdLib_AddBasePath( const char *pBasePath );
bool CmdLib_HasBasePath( const char *pFileName, int &pathLength );
int CmdLib_GetNumBasePaths( void );
const char *CmdLib_GetBasePath( int i );
// Like ExpandPath but expands the path for each base path like SafeOpenRead
int CmdLib_ExpandWithBasePaths( CUtlVector< CUtlString > &expandedPathList, const char *pszPath );
extern bool g_bStopOnExit;
// for compression routines
typedef struct
{
byte *data;
int count;
} cblock_t;
#endif // CMDLIB_H

View File

@@ -0,0 +1,333 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include <windows.h>
#include "consolewnd.h"
#pragma warning( disable : 4311 ) // warning C4311: 'reinterpret_cast' : pointer truncation from 'CConsoleWnd *const ' to 'LONG'
#pragma warning( disable : 4312 ) // warning C4312: 'type cast' : conversion from 'LONG' to 'CConsoleWnd *' of greater size
#define EDITCONTROL_BORDER_SIZE 5
// ------------------------------------------------------------------------------------------------ //
// Functions to manage the console window.
// ------------------------------------------------------------------------------------------------ //
class CConsoleWnd : public IConsoleWnd
{
public:
CConsoleWnd();
~CConsoleWnd();
bool Init( void *hInstance, int dialogResourceID, int editControlID, bool bVisible );
void Term();
virtual void Release();
virtual void SetVisible( bool bVisible );
virtual bool IsVisible() const;
virtual void PrintToConsole( const char *pMsg );
virtual void SetTitle( const char *pTitle );
virtual void SetDeleteOnClose( bool bDelete );
private:
int WindowProc(
HWND hwndDlg, // handle to dialog box
UINT uMsg, // message
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);
static int CALLBACK StaticWindowProc(
HWND hwndDlg, // handle to dialog box
UINT uMsg, // message
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);
void RepositionEditControl();
private:
HWND m_hWnd;
HWND m_hEditControl;
bool m_bVisible;
bool m_bDeleteOnClose;
int m_nCurrentChars;
};
CConsoleWnd::CConsoleWnd()
{
m_hWnd = m_hEditControl = NULL;
m_bVisible = false;
m_bDeleteOnClose = false;
m_nCurrentChars = 0;
}
CConsoleWnd::~CConsoleWnd()
{
Term();
}
bool CConsoleWnd::Init( void *hInstance, int dialogResourceID, int editControlID, bool bVisible )
{
// Create the window.
m_hWnd = CreateDialog(
(HINSTANCE)hInstance,
MAKEINTRESOURCE( dialogResourceID ),
NULL,
&CConsoleWnd::StaticWindowProc );
if ( !m_hWnd )
return false;
SetWindowLong( m_hWnd, GWL_USERDATA, reinterpret_cast< LONG >( this ) );
if ( bVisible )
ShowWindow( m_hWnd, SW_SHOW );
// Get a handle to the edit control.
m_hEditControl = GetDlgItem( m_hWnd, editControlID );
if ( !m_hEditControl )
return false;
RepositionEditControl();
m_bVisible = bVisible;
return true;
}
void CConsoleWnd::Term()
{
if ( m_hWnd )
{
DestroyWindow( m_hWnd );
m_hWnd = NULL;
}
}
void CConsoleWnd::Release()
{
delete this;
}
void CConsoleWnd::SetVisible( bool bVisible )
{
ShowWindow( m_hWnd, bVisible ? SW_RESTORE : SW_HIDE );
if ( bVisible )
{
ShowWindow( m_hWnd, SW_SHOW );
SetWindowPos( m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );
UpdateWindow( m_hWnd );
int nLen = (int)SendMessage( m_hEditControl, EM_GETLIMITTEXT, 0, 0 );
SendMessage( m_hEditControl, EM_SETSEL, nLen, nLen );
}
else
{
SetWindowPos( m_hWnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_HIDEWINDOW | SWP_NOOWNERZORDER );
}
m_bVisible = bVisible;
}
bool CConsoleWnd::IsVisible() const
{
return m_bVisible;
}
void CConsoleWnd::PrintToConsole( const char *pMsg )
{
if ( m_nCurrentChars >= 16*1024 )
{
// Clear the edit control otherwise it'll stop outputting anything.
m_nCurrentChars = 0;
int nLen = (int)SendMessage( m_hEditControl, EM_GETLIMITTEXT, 0, 0 );
SendMessage( m_hEditControl, EM_SETSEL, 0, nLen );
SendMessage( m_hEditControl, EM_REPLACESEL, FALSE, (LPARAM)"" );
}
FormatAndSendToEditControl( m_hEditControl, pMsg );
m_nCurrentChars += (int)strlen( pMsg );
}
void CConsoleWnd::SetTitle( const char *pTitle )
{
SetWindowText( m_hWnd, pTitle );
}
int CConsoleWnd::WindowProc(
HWND hwndDlg, // handle to dialog box
UINT uMsg, // message
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
lParam = lParam; // avoid compiler warning
if ( hwndDlg != m_hWnd )
return false;
switch ( uMsg )
{
case WM_SYSCOMMAND:
{
if ( wParam == SC_CLOSE )
{
if ( m_bDeleteOnClose )
{
Release();
}
else
{
SetVisible( false );
return true;
}
}
}
break;
case WM_SHOWWINDOW:
{
m_bVisible = (wParam != 0);
}
break;
case WM_SIZE:
case WM_INITDIALOG:
{
RepositionEditControl();
}
break;
}
return false;
}
int CConsoleWnd::StaticWindowProc(
HWND hwndDlg, // handle to dialog box
UINT uMsg, // message
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
CConsoleWnd *pDlg = (CConsoleWnd*)GetWindowLong( hwndDlg, GWL_USERDATA );
if ( pDlg )
return pDlg->WindowProc( hwndDlg, uMsg, wParam, lParam );
else
return false;
}
void CConsoleWnd::RepositionEditControl()
{
RECT rcMain;
GetClientRect( m_hWnd, &rcMain );
RECT rcNew;
rcNew.left = rcMain.left + EDITCONTROL_BORDER_SIZE;
rcNew.right = rcMain.right - EDITCONTROL_BORDER_SIZE;
rcNew.top = rcMain.top + EDITCONTROL_BORDER_SIZE;
rcNew.bottom = rcMain.bottom - EDITCONTROL_BORDER_SIZE;
SetWindowPos(
m_hEditControl,
NULL,
rcNew.left,
rcNew.top,
rcNew.right - rcNew.left,
rcNew.bottom - rcNew.top,
SWP_NOZORDER );
}
void CConsoleWnd::SetDeleteOnClose( bool bDelete )
{
m_bDeleteOnClose = bDelete;
}
// ------------------------------------------------------------------------------------ //
// Module interface.
// ------------------------------------------------------------------------------------ //
void SendToEditControl( HWND hEditControl, const char *pText )
{
int nLen = (int)SendMessage( hEditControl, EM_GETLIMITTEXT, 0, 0 );
SendMessage( hEditControl, EM_SETSEL, nLen, nLen );
SendMessage( hEditControl, EM_REPLACESEL, FALSE, (LPARAM)pText );
}
void FormatAndSendToEditControl( void *hWnd, const char *pText )
{
HWND hEditControl = (HWND)hWnd;
// Translate \n to \r\n.
char outMsg[1024];
const char *pIn = pText;
char *pOut = outMsg;
while ( *pIn )
{
if ( *pIn == '\n' )
{
*pOut = '\r';
pOut++;
}
*pOut = *pIn;
++pIn;
++pOut;
if ( pOut - outMsg >= 1020 )
{
*pOut = 0;
SendToEditControl( hEditControl, outMsg );
pOut = outMsg;
}
}
*pOut = 0;
SendToEditControl( hEditControl, outMsg );
}
IConsoleWnd* CreateConsoleWnd( void *hInstance, int dialogResourceID, int editControlID, bool bVisible )
{
CConsoleWnd *pWnd = new CConsoleWnd;
if ( pWnd->Init( hInstance, dialogResourceID, editControlID, bVisible ) )
{
return pWnd;
}
else
{
pWnd->Release();
return NULL;
}
}

View File

@@ -0,0 +1,45 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef CONSOLEWND_H
#define CONSOLEWND_H
#ifdef _WIN32
#pragma once
#endif
class IConsoleWnd
{
public:
virtual void Release() = 0;
// Print a message to the console.
virtual void PrintToConsole( const char *pMsg ) = 0;
// Set the window title.
virtual void SetTitle( const char *pTitle ) = 0;
// Show and hide the console window.
virtual void SetVisible( bool bVisible ) = 0;
virtual bool IsVisible() const = 0;
// Normally, the window just hides itself when closed. You can use this to make the window
// automatically go away when they close it.
virtual void SetDeleteOnClose( bool bDelete ) = 0;
};
// Utility functions.
// This converts adds \r's where necessary and sends the text to the edit control.
void FormatAndSendToEditControl( void *hWnd, const char *pText );
IConsoleWnd* CreateConsoleWnd( void *hInstance, int dialogResourceID, int editControlID, bool bVisible );
#endif // CONSOLEWND_H

View File

@@ -0,0 +1,209 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//===========================================================================//
#if defined( _WIN32 ) && !defined( _X360 )
#include <windows.h>
#include <direct.h>
#include <io.h> // _chmod
#elif _LINUX
#include <unistd.h>
#endif
#include <stdio.h>
#include <sys/stat.h>
#include "tier1/strtools.h"
#include "filesystem_tools.h"
#include "tier0/icommandline.h"
#include "KeyValues.h"
#include "tier2/tier2.h"
#ifdef MPI
#include "vmpi.h"
#include "vmpi_tools_shared.h"
#include "vmpi_filesystem.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
// ---------------------------------------------------------------------------------------------------- //
// Module interface.
// ---------------------------------------------------------------------------------------------------- //
IBaseFileSystem *g_pFileSystem = NULL;
// These are only used for tools that need the search paths that the engine's file system provides.
CSysModule *g_pFullFileSystemModule = NULL;
// ---------------------------------------------------------------------------
//
// These are the base paths that everything will be referenced relative to (textures especially)
// All of these directories include the trailing slash
//
// ---------------------------------------------------------------------------
// This is the the path of the initial source file (relative to the cwd)
char qdir[1024];
// This is the base engine + mod-specific game dir (e.g. "c:\tf2\mytfmod\")
char gamedir[1024];
void FileSystem_SetupStandardDirectories( const char *pFilename, const char *pGameInfoPath )
{
// Set qdir.
if ( !pFilename )
{
pFilename = ".";
}
Q_MakeAbsolutePath( qdir, sizeof( qdir ), pFilename, NULL );
Q_StripFilename( qdir );
Q_strlower( qdir );
if ( qdir[0] != 0 )
{
Q_AppendSlash( qdir, sizeof( qdir ) );
}
// Set gamedir.
Q_MakeAbsolutePath( gamedir, sizeof( gamedir ), pGameInfoPath );
Q_AppendSlash( gamedir, sizeof( gamedir ) );
}
bool FileSystem_Init_Normal( const char *pFilename, FSInitType_t initType, bool bOnlyUseDirectoryName )
{
if ( initType == FS_INIT_FULL )
{
// First, get the name of the module
char fileSystemDLLName[MAX_PATH];
bool bSteam;
if ( FileSystem_GetFileSystemDLLName( fileSystemDLLName, MAX_PATH, bSteam ) != FS_OK )
return false;
// If we're under Steam we need extra setup to let us find the proper modules
FileSystem_SetupSteamInstallPath();
// Next, load the module, call Connect/Init.
CFSLoadModuleInfo loadModuleInfo;
loadModuleInfo.m_pFileSystemDLLName = fileSystemDLLName;
loadModuleInfo.m_pDirectoryName = pFilename;
loadModuleInfo.m_bOnlyUseDirectoryName = bOnlyUseDirectoryName;
loadModuleInfo.m_ConnectFactory = Sys_GetFactoryThis();
loadModuleInfo.m_bSteam = bSteam;
loadModuleInfo.m_bToolsMode = true;
if ( FileSystem_LoadFileSystemModule( loadModuleInfo ) != FS_OK )
return false;
// Next, mount the content
CFSMountContentInfo mountContentInfo;
mountContentInfo.m_pDirectoryName= loadModuleInfo.m_GameInfoPath;
mountContentInfo.m_pFileSystem = loadModuleInfo.m_pFileSystem;
mountContentInfo.m_bToolsMode = true;
if ( FileSystem_MountContent( mountContentInfo ) != FS_OK )
return false;
// Finally, load the search paths.
CFSSearchPathsInit searchPathsInit;
searchPathsInit.m_pDirectoryName = loadModuleInfo.m_GameInfoPath;
searchPathsInit.m_pFileSystem = loadModuleInfo.m_pFileSystem;
if ( FileSystem_LoadSearchPaths( searchPathsInit ) != FS_OK )
return false;
// Store the data we got from filesystem_init.
g_pFileSystem = g_pFullFileSystem = loadModuleInfo.m_pFileSystem;
g_pFullFileSystemModule = loadModuleInfo.m_pModule;
FileSystem_AddSearchPath_Platform( g_pFullFileSystem, loadModuleInfo.m_GameInfoPath );
FileSystem_SetupStandardDirectories( pFilename, loadModuleInfo.m_GameInfoPath );
}
else
{
if ( !Sys_LoadInterface(
"filesystem_stdio",
FILESYSTEM_INTERFACE_VERSION,
&g_pFullFileSystemModule,
(void**)&g_pFullFileSystem ) )
{
return false;
}
if ( g_pFullFileSystem->Init() != INIT_OK )
return false;
g_pFullFileSystem->RemoveAllSearchPaths();
g_pFullFileSystem->AddSearchPath( "../platform", "PLATFORM" );
g_pFullFileSystem->AddSearchPath( ".", "GAME" );
g_pFileSystem = g_pFullFileSystem;
}
return true;
}
bool FileSystem_Init( const char *pBSPFilename, int maxMemoryUsage, FSInitType_t initType, bool bOnlyUseFilename )
{
Assert( CommandLine()->GetCmdLine() != NULL ); // Should have called CreateCmdLine by now.
// If this app uses VMPI, then let VMPI intercept all filesystem calls.
#if defined( MPI )
if ( g_bUseMPI )
{
if ( g_bMPIMaster )
{
if ( !FileSystem_Init_Normal( pBSPFilename, initType, bOnlyUseFilename ) )
return false;
g_pFileSystem = g_pFullFileSystem = VMPI_FileSystem_Init( maxMemoryUsage, g_pFullFileSystem );
SendQDirInfo();
}
else
{
g_pFileSystem = g_pFullFileSystem = VMPI_FileSystem_Init( maxMemoryUsage, NULL );
RecvQDirInfo();
}
return true;
}
#endif
return FileSystem_Init_Normal( pBSPFilename, initType, bOnlyUseFilename );
}
void FileSystem_Term()
{
#if defined( MPI )
if ( g_bUseMPI )
{
g_pFileSystem = g_pFullFileSystem = VMPI_FileSystem_Term();
}
#endif
if ( g_pFullFileSystem )
{
g_pFullFileSystem->Shutdown();
g_pFullFileSystem = NULL;
g_pFileSystem = NULL;
}
if ( g_pFullFileSystemModule )
{
Sys_UnloadModule( g_pFullFileSystemModule );
g_pFullFileSystemModule = NULL;
}
}
CreateInterfaceFn FileSystem_GetFactory()
{
#if defined( MPI )
if ( g_bUseMPI )
return VMPI_FileSystem_GetFactory();
#endif
return Sys_GetFactory( g_pFullFileSystemModule );
}

View File

@@ -0,0 +1,59 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#ifndef FILESYSTEM_TOOLS_H
#define FILESYSTEM_TOOLS_H
#ifdef _WIN32
#pragma once
#endif
#include "filesystem.h"
#include "filesystem_init.h"
// This is the the path of the initial source file
extern char qdir[1024];
// This is the base engine + mod-specific game dir (e.g. "d:\tf2\mytfmod\")
extern char gamedir[1024];
// ---------------------------------------------------------------------------------------- //
// Filesystem initialization.
// ---------------------------------------------------------------------------------------- //
enum FSInitType_t
{
FS_INIT_FULL, // Load gameinfo.txt, maybe use filesystem_steam, and setup search paths.
FS_INIT_COMPATIBILITY_MODE // Load filesystem_stdio and that's it.
};
//
// Initializes qdir, and gamedir. Also initializes the VMPI filesystem if MPI is defined.
//
// pFilename can be NULL if you want to rely on vproject and qproject. If it's specified, FileSystem_Init
// will go up directories from pFilename looking for gameinfo.txt (if vproject isn't specified).
//
// If bOnlyUseFilename is true, then it won't use any alternative methods of finding the vproject dir
// (ie: it won't use -game or -vproject or the vproject env var or qproject).
//
bool FileSystem_Init( const char *pFilename, int maxMemoryUsage=0, FSInitType_t initType=FS_INIT_FULL, bool bOnlyUseFilename=false );
void FileSystem_Term();
// Used to connect app-framework based console apps to the filesystem tools
void FileSystem_SetupStandardDirectories( const char *pFilename, const char *pGameInfoPath );
CreateInterfaceFn FileSystem_GetFactory( void );
extern IBaseFileSystem *g_pFileSystem;
extern IFileSystem *g_pFullFileSystem; // NOTE: this is here when VMPI is being used, but a VMPI app can
// ONLY use LoadModule/UnloadModule.
#endif // FILESYSTEM_TOOLS_H

View File

@@ -0,0 +1,136 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "map_shared.h"
#include "bsplib.h"
#include "cmdlib.h"
CMapError g_MapError;
int g_nMapFileVersion;
//-----------------------------------------------------------------------------
// Purpose:
// Input : *szKey -
// *szValue -
// *pLoadEntity -
// Output : ChunkFileResult_t
//-----------------------------------------------------------------------------
ChunkFileResult_t LoadEntityKeyCallback(const char *szKey, const char *szValue, LoadEntity_t *pLoadEntity)
{
if (!stricmp(szKey, "classname"))
{
if (!stricmp(szValue, "func_detail"))
{
pLoadEntity->nBaseContents = CONTENTS_DETAIL;
}
else if (!stricmp(szValue, "func_ladder"))
{
pLoadEntity->nBaseContents = CONTENTS_LADDER;
}
else if (!stricmp(szValue, "func_water"))
{
pLoadEntity->nBaseContents = CONTENTS_WATER;
}
}
else if (!stricmp(szKey, "id"))
{
// UNDONE: flag entity errors by ID instead of index
//g_MapError.EntityState( atoi( szValue ) );
// rename this field since DME code uses this name
SetKeyValue( pLoadEntity->pEntity, "hammerid", szValue );
return(ChunkFile_Ok);
}
else if( !stricmp( szKey, "mapversion" ) )
{
// .vmf map revision number
g_MapRevision = atoi( szValue );
SetKeyValue( pLoadEntity->pEntity, szKey, szValue );
return ( ChunkFile_Ok );
}
SetKeyValue( pLoadEntity->pEntity, szKey, szValue );
return(ChunkFile_Ok);
}
static ChunkFileResult_t LoadEntityCallback( CChunkFile *pFile, int nParam )
{
if (num_entities == MAX_MAP_ENTITIES)
{
// Exits.
g_MapError.ReportError ("num_entities == MAX_MAP_ENTITIES");
}
entity_t *mapent = &entities[num_entities];
num_entities++;
memset(mapent, 0, sizeof(*mapent));
mapent->numbrushes = 0;
LoadEntity_t LoadEntity;
LoadEntity.pEntity = mapent;
// No default flags/contents
LoadEntity.nBaseFlags = 0;
LoadEntity.nBaseContents = 0;
//
// Read the entity chunk.
//
ChunkFileResult_t eResult = pFile->ReadChunk((KeyHandler_t)LoadEntityKeyCallback, &LoadEntity);
return eResult;
}
bool LoadEntsFromMapFile( char const *pFilename )
{
//
// Dummy this up for the texture handling. This can be removed when old .MAP file
// support is removed.
//
g_nMapFileVersion = 400;
//
// Open the file.
//
CChunkFile File;
ChunkFileResult_t eResult = File.Open( pFilename, ChunkFile_Read );
if(eResult == ChunkFile_Ok)
{
num_entities = 0;
//
// Set up handlers for the subchunks that we are interested in.
//
CChunkHandlerMap Handlers;
Handlers.AddHandler("entity", (ChunkHandler_t)LoadEntityCallback, 0);
File.PushHandlers(&Handlers);
//
// Read the sub-chunks. We ignore keys in the root of the file.
//
while (eResult == ChunkFile_Ok)
{
eResult = File.ReadChunk();
}
File.PopHandlers();
return true;
}
else
{
Error("Error in LoadEntsFromMapFile (in-memory file): %s.\n", File.GetErrorText(eResult));
return false;
}
}

View File

@@ -0,0 +1,91 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef MAP_SHARED_H
#define MAP_SHARED_H
#ifdef _WIN32
#pragma once
#endif
#include "ChunkFile.h"
#include "bsplib.h"
#include "cmdlib.h"
struct LoadEntity_t
{
entity_t *pEntity;
int nID;
int nBaseFlags;
int nBaseContents;
};
class CMapError
{
public:
void BrushState( int brushID )
{
m_brushID = brushID;
}
void BrushSide( int side )
{
m_sideIndex = side;
}
void TextureState( const char *pTextureName )
{
Q_strncpy( m_textureName, pTextureName, sizeof( m_textureName ) );
}
void ClearState( void )
{
BrushState( 0 );
BrushSide( 0 );
TextureState( "Not a Parse error!" );
}
//-----------------------------------------------------------------------------
// Purpose: Hook the map parse errors and report brush/ent/texture state
// Input : *pErrorString -
//-----------------------------------------------------------------------------
void ReportError( const char *pErrorString )
{
Error( "Brush %i: %s\nSide %i\nTexture: %s\n", m_brushID, pErrorString, m_sideIndex, m_textureName );
}
//-----------------------------------------------------------------------------
// Purpose: Hook the map parse errors and report brush/ent/texture state without exiting.
// Input : pWarningString -
//-----------------------------------------------------------------------------
void ReportWarning( const char *pWarningString )
{
printf( "Brush %i, Side %i: %s\n", m_brushID, m_sideIndex, pWarningString );
}
private:
int m_brushID;
int m_sideIndex;
char m_textureName[80];
};
extern CMapError g_MapError;
extern int g_nMapFileVersion;
// Shared mapload code.
ChunkFileResult_t LoadEntityKeyCallback( const char *szKey, const char *szValue, LoadEntity_t *pLoadEntity );
// Used by VRAD incremental lighting - only load ents from the file and
// fill in the global entities/num_entities array.
bool LoadEntsFromMapFile( char const *pFilename );
#endif // MAP_SHARED_H

View File

@@ -0,0 +1,34 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#ifndef _MOVIE_H_
#define _MOVIE_H_
/*
movie.h
definitions and such for dumping screen shots to make a movie
*/
typedef struct
{
unsigned long tag;
unsigned long size;
} movieblockheader_t;
typedef struct
{
short width;
short height;
short depth;
} movieframe_t;
#endif _MOVIE_H_

View File

@@ -0,0 +1,839 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
// Nasty headers!
#include "MySqlDatabase.h"
#include "tier1/strtools.h"
#include "vmpi.h"
#include "vmpi_dispatch.h"
#include "mpi_stats.h"
#include "cmdlib.h"
#include "imysqlwrapper.h"
#include "threadhelpers.h"
#include "vmpi_tools_shared.h"
#include "tier0/icommandline.h"
/*
-- MySQL code to create the databases, create the users, and set access privileges.
-- You only need to ever run this once.
create database vrad;
use mysql;
create user vrad_worker;
create user vmpi_browser;
-- This updates the "user" table, which is checked when someone tries to connect to the database.
grant select,insert,update on vrad.* to vrad_worker;
grant select on vrad.* to vmpi_browser;
flush privileges;
/*
-- SQL code to (re)create the tables.
-- Master generates a unique job ID (in job_master_start) and sends it to workers.
-- Each worker (and the master) make a job_worker_start, link it to the primary job ID,
-- get their own unique ID, which represents that process in that job.
-- All JobWorkerID fields link to the JobWorkerID field in job_worker_start.
-- NOTE: do a "use vrad" or "use vvis" first, depending on the DB you want to create.
use vrad;
drop table job_master_start;
create table job_master_start (
JobID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, index id( JobID, MachineName(5) ),
BSPFilename TINYTEXT NOT NULL,
StartTime TIMESTAMP NOT NULL,
MachineName TEXT NOT NULL,
RunningTimeMS INTEGER UNSIGNED NOT NULL,
NumWorkers INTEGER UNSIGNED NOT NULL default 0
);
drop table job_master_end;
create table job_master_end (
JobID INTEGER UNSIGNED NOT NULL, PRIMARY KEY ( JobID ),
NumWorkersConnected SMALLINT UNSIGNED NOT NULL,
NumWorkersDisconnected SMALLINT UNSIGNED NOT NULL,
ErrorText TEXT NOT NULL
);
drop table job_worker_start;
create table job_worker_start (
JobWorkerID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
index index_jobid( JobID ),
index index_jobworkerid( JobWorkerID ),
JobID INTEGER UNSIGNED NOT NULL, -- links to job_master_start::JobID
IsMaster BOOL NOT NULL, -- Set to 1 if this "worker" is the master process.
RunningTimeMS INTEGER UNSIGNED NOT NULL default 0,
MachineName TEXT NOT NULL,
WorkerState SMALLINT UNSIGNED NOT NULL default 0, -- 0 = disconnected, 1 = connected
NumWorkUnits INTEGER UNSIGNED NOT NULL default 0, -- how many work units this worker has completed
CurrentStage TINYTEXT NOT NULL, -- which compile stage is it on
Thread0WU INTEGER NOT NULL default 0, -- which WU thread 0 is on
Thread1WU INTEGER NOT NULL default 0, -- which WU thread 1 is on
Thread2WU INTEGER NOT NULL default 0, -- which WU thread 2 is on
Thread3WU INTEGER NOT NULL default 0 -- which WU thread 3 is on
);
drop table text_messages;
create table text_messages (
JobWorkerID INTEGER UNSIGNED NOT NULL, index id( JobWorkerID, MessageIndex ),
MessageIndex INTEGER UNSIGNED NOT NULL,
Text TEXT NOT NULL
);
drop table graph_entry;
create table graph_entry (
JobWorkerID INTEGER UNSIGNED NOT NULL, index id( JobWorkerID ),
MSSinceJobStart INTEGER UNSIGNED NOT NULL,
BytesSent INTEGER UNSIGNED NOT NULL,
BytesReceived INTEGER UNSIGNED NOT NULL
);
drop table events;
create table events (
JobWorkerID INTEGER UNSIGNED NOT NULL, index id( JobWorkerID ),
Text TEXT NOT NULL
);
*/
// Stats set by the app.
int g_nWorkersConnected = 0;
int g_nWorkersDisconnected = 0;
DWORD g_StatsStartTime;
CMySqlDatabase *g_pDB = NULL;
IMySQL *g_pSQL = NULL;
CSysModule *g_hMySQLDLL = NULL;
char g_BSPFilename[256];
bool g_bMaster = false;
unsigned long g_JobPrimaryID = 0; // This represents this job, but doesn't link to a particular machine.
unsigned long g_JobWorkerID = 0; // A unique key in the DB that represents this machine in this job.
char g_MachineName[MAX_COMPUTERNAME_LENGTH+1] = {0};
unsigned long g_CurrentMessageIndex = 0;
HANDLE g_hPerfThread = NULL;
DWORD g_PerfThreadID = 0xFEFEFEFE;
HANDLE g_hPerfThreadExitEvent = NULL;
// These are set by the app and they go into the database.
extern uint64 g_ThreadWUs[4];
extern uint64 VMPI_GetNumWorkUnitsCompleted( int iProc );
// ---------------------------------------------------------------------------------------------------- //
// This is a helper class to build queries like the stream IO.
// ---------------------------------------------------------------------------------------------------- //
class CMySQLQuery
{
friend class CMySQL;
public:
// This is like a sprintf, but it will grow the string as necessary.
void Format( const char *pFormat, ... );
int Execute( IMySQL *pDB );
private:
CUtlVector<char> m_QueryText;
};
void CMySQLQuery::Format( const char *pFormat, ... )
{
#define QUERYTEXT_GROWSIZE 1024
// This keeps growing the buffer and calling _vsnprintf until the buffer is
// large enough to hold all the data.
m_QueryText.SetSize( QUERYTEXT_GROWSIZE );
while ( 1 )
{
va_list marker;
va_start( marker, pFormat );
int ret = _vsnprintf( m_QueryText.Base(), m_QueryText.Count(), pFormat, marker );
va_end( marker );
if ( ret < 0 )
{
m_QueryText.SetSize( m_QueryText.Count() + QUERYTEXT_GROWSIZE );
}
else
{
m_QueryText[ m_QueryText.Count() - 1 ] = 0;
break;
}
}
}
int CMySQLQuery::Execute( IMySQL *pDB )
{
int ret = pDB->Execute( m_QueryText.Base() );
m_QueryText.Purge();
return ret;
}
// ---------------------------------------------------------------------------------------------------- //
// This inserts the necessary backslashes in front of backslashes or quote characters.
// ---------------------------------------------------------------------------------------------------- //
char* FormatStringForSQL( const char *pText )
{
// First, count the quotes in the string. We need to put a backslash in front of each one.
int nChars = 0;
const char *pCur = pText;
while ( *pCur != 0 )
{
if ( *pCur == '\"' || *pCur == '\\' )
++nChars;
++pCur;
++nChars;
}
pCur = pText;
char *pRetVal = new char[nChars+1];
for ( int i=0; i < nChars; )
{
if ( *pCur == '\"' || *pCur == '\\' )
pRetVal[i++] = '\\';
pRetVal[i++] = *pCur;
++pCur;
}
pRetVal[nChars] = 0;
return pRetVal;
}
// -------------------------------------------------------------------------------- //
// Commands to add data to the database.
// -------------------------------------------------------------------------------- //
class CSQLDBCommandBase : public ISQLDBCommand
{
public:
virtual ~CSQLDBCommandBase()
{
}
virtual void deleteThis()
{
delete this;
}
};
class CSQLDBCommand_WorkerStats : public CSQLDBCommandBase
{
public:
virtual int RunCommand()
{
int nCurConnections = VMPI_GetCurrentNumberOfConnections();
// Update the NumWorkers entry.
char query[2048];
Q_snprintf( query, sizeof( query ), "update job_master_start set NumWorkers=%d where JobID=%lu",
nCurConnections,
g_JobPrimaryID );
g_pSQL->Execute( query );
// Update the job_master_worker_stats stuff.
for ( int i=1; i < nCurConnections; i++ )
{
unsigned long jobWorkerID = VMPI_GetJobWorkerID( i );
if ( jobWorkerID != 0xFFFFFFFF )
{
Q_snprintf( query, sizeof( query ), "update "
"job_worker_start set WorkerState=%d, NumWorkUnits=%d where JobWorkerID=%lu",
VMPI_IsProcConnected( i ),
(int) VMPI_GetNumWorkUnitsCompleted( i ),
VMPI_GetJobWorkerID( i )
);
g_pSQL->Execute( query );
}
}
return 1;
}
};
class CSQLDBCommand_JobMasterEnd : public CSQLDBCommandBase
{
public:
virtual int RunCommand()
{
CMySQLQuery query;
query.Format( "insert into job_master_end values ( %lu, %d, %d, \"no errors\" )", g_JobPrimaryID, g_nWorkersConnected, g_nWorkersDisconnected );
query.Execute( g_pSQL );
// Now set RunningTimeMS.
unsigned long runningTimeMS = GetTickCount() - g_StatsStartTime;
query.Format( "update job_master_start set RunningTimeMS=%lu where JobID=%lu", runningTimeMS, g_JobPrimaryID );
query.Execute( g_pSQL );
return 1;
}
};
void UpdateJobWorkerRunningTime()
{
unsigned long runningTimeMS = GetTickCount() - g_StatsStartTime;
char curStage[256];
VMPI_GetCurrentStage( curStage, sizeof( curStage ) );
CMySQLQuery query;
query.Format( "update job_worker_start set RunningTimeMS=%lu, CurrentStage=\"%s\", "
"Thread0WU=%d, Thread1WU=%d, Thread2WU=%d, Thread3WU=%d where JobWorkerID=%lu",
runningTimeMS,
curStage,
(int) g_ThreadWUs[0],
(int) g_ThreadWUs[1],
(int) g_ThreadWUs[2],
(int) g_ThreadWUs[3],
g_JobWorkerID );
query.Execute( g_pSQL );
}
class CSQLDBCommand_GraphEntry : public CSQLDBCommandBase
{
public:
CSQLDBCommand_GraphEntry( DWORD msTime, DWORD nBytesSent, DWORD nBytesReceived )
{
m_msTime = msTime;
m_nBytesSent = nBytesSent;
m_nBytesReceived = nBytesReceived;
}
virtual int RunCommand()
{
CMySQLQuery query;
query.Format( "insert into graph_entry (JobWorkerID, MSSinceJobStart, BytesSent, BytesReceived) "
"values ( %lu, %lu, %lu, %lu )",
g_JobWorkerID,
m_msTime,
m_nBytesSent,
m_nBytesReceived );
query.Execute( g_pSQL );
UpdateJobWorkerRunningTime();
++g_CurrentMessageIndex;
return 1;
}
DWORD m_nBytesSent;
DWORD m_nBytesReceived;
DWORD m_msTime;
};
class CSQLDBCommand_TextMessage : public CSQLDBCommandBase
{
public:
CSQLDBCommand_TextMessage( const char *pText )
{
m_pText = FormatStringForSQL( pText );
}
virtual ~CSQLDBCommand_TextMessage()
{
delete [] m_pText;
}
virtual int RunCommand()
{
CMySQLQuery query;
query.Format( "insert into text_messages (JobWorkerID, MessageIndex, Text) values ( %lu, %lu, \"%s\" )", g_JobWorkerID, g_CurrentMessageIndex, m_pText );
query.Execute( g_pSQL );
++g_CurrentMessageIndex;
return 1;
}
char *m_pText;
};
// -------------------------------------------------------------------------------- //
// Internal helpers.
// -------------------------------------------------------------------------------- //
// This is the spew output before it has connected to the MySQL database.
CCriticalSection g_SpewTextCS;
CUtlVector<char> g_SpewText( 1024 );
void VMPI_Stats_SpewHook( const char *pMsg )
{
CCriticalSectionLock csLock( &g_SpewTextCS );
csLock.Lock();
// Queue the text up so we can send it to the DB right away when we connect.
g_SpewText.AddMultipleToTail( strlen( pMsg ), pMsg );
}
void PerfThread_SendSpewText()
{
// Send the spew text to the database.
CCriticalSectionLock csLock( &g_SpewTextCS );
csLock.Lock();
if ( g_SpewText.Count() > 0 )
{
g_SpewText.AddToTail( 0 );
if ( g_bMPI_StatsTextOutput )
{
g_pDB->AddCommandToQueue( new CSQLDBCommand_TextMessage( g_SpewText.Base() ), NULL );
}
else
{
// Just show one message in the vmpi_job_watch window to let them know that they need
// to use a command line option to get the output.
static bool bFirst = true;
if ( bFirst )
{
char msg[512];
V_snprintf( msg, sizeof( msg ), "%s not enabled", VMPI_GetParamString( mpi_Stats_TextOutput ) );
bFirst = false;
g_pDB->AddCommandToQueue( new CSQLDBCommand_TextMessage( msg ), NULL );
}
}
g_SpewText.RemoveAll();
}
csLock.Unlock();
}
void PerfThread_AddGraphEntry( DWORD startTicks, DWORD &lastSent, DWORD &lastReceived )
{
// Send the graph entry with data transmission info.
DWORD curSent = g_nBytesSent + g_nMulticastBytesSent;
DWORD curReceived = g_nBytesReceived + g_nMulticastBytesReceived;
g_pDB->AddCommandToQueue(
new CSQLDBCommand_GraphEntry(
GetTickCount() - startTicks,
curSent - lastSent,
curReceived - lastReceived ),
NULL );
lastSent = curSent;
lastReceived = curReceived;
}
// This function adds a graph_entry into the database periodically.
DWORD WINAPI PerfThreadFn( LPVOID pParameter )
{
DWORD lastSent = 0;
DWORD lastReceived = 0;
DWORD startTicks = GetTickCount();
while ( WaitForSingleObject( g_hPerfThreadExitEvent, 1000 ) != WAIT_OBJECT_0 )
{
PerfThread_AddGraphEntry( startTicks, lastSent, lastReceived );
// Send updates for text output.
PerfThread_SendSpewText();
// If we're the master, update all the worker stats.
if ( g_bMaster )
{
g_pDB->AddCommandToQueue(
new CSQLDBCommand_WorkerStats,
NULL );
}
}
// Add the remaining text and one last graph entry (which will include the current stage info).
PerfThread_SendSpewText();
PerfThread_AddGraphEntry( startTicks, lastSent, lastReceived );
SetEvent( g_hPerfThreadExitEvent );
return 0;
}
// -------------------------------------------------------------------------------- //
// VMPI_Stats interface.
// -------------------------------------------------------------------------------- //
void VMPI_Stats_InstallSpewHook()
{
InstallExtraSpewHook( VMPI_Stats_SpewHook );
}
void UnloadMySQLWrapper()
{
if ( g_hMySQLDLL )
{
if ( g_pSQL )
{
g_pSQL->Release();
g_pSQL = NULL;
}
Sys_UnloadModule( g_hMySQLDLL );
g_hMySQLDLL = NULL;
}
}
bool LoadMySQLWrapper(
const char *pHostName,
const char *pDBName,
const char *pUserName
)
{
UnloadMySQLWrapper();
// Load the DLL and the interface.
if ( !Sys_LoadInterface( "mysql_wrapper", MYSQL_WRAPPER_VERSION_NAME, &g_hMySQLDLL, (void**)&g_pSQL ) )
return false;
// Try to init the database.
if ( !g_pSQL->InitMySQL( pDBName, pHostName, pUserName ) )
{
UnloadMySQLWrapper();
return false;
}
return true;
}
bool VMPI_Stats_Init_Master(
const char *pHostName,
const char *pDBName,
const char *pUserName,
const char *pBSPFilename,
unsigned long *pDBJobID )
{
Assert( !g_pDB );
g_bMaster = true;
// Connect the database.
g_pDB = new CMySqlDatabase;
if ( !g_pDB || !g_pDB->Initialize() || !LoadMySQLWrapper( pHostName, pDBName, pUserName ) )
{
delete g_pDB;
g_pDB = NULL;
return false;
}
DWORD size = sizeof( g_MachineName );
GetComputerName( g_MachineName, &size );
// Create the job_master_start row.
Q_FileBase( pBSPFilename, g_BSPFilename, sizeof( g_BSPFilename ) );
g_JobPrimaryID = 0;
CMySQLQuery query;
query.Format( "insert into job_master_start ( BSPFilename, StartTime, MachineName, RunningTimeMS ) values ( \"%s\", null, \"%s\", %lu )", g_BSPFilename, g_MachineName, RUNNINGTIME_MS_SENTINEL );
query.Execute( g_pSQL );
g_JobPrimaryID = g_pSQL->InsertID();
if ( g_JobPrimaryID == 0 )
{
delete g_pDB;
g_pDB = NULL;
return false;
}
// Now init the worker portion.
*pDBJobID = g_JobPrimaryID;
return VMPI_Stats_Init_Worker( NULL, NULL, NULL, g_JobPrimaryID );
}
bool VMPI_Stats_Init_Worker( const char *pHostName, const char *pDBName, const char *pUserName, unsigned long DBJobID )
{
g_StatsStartTime = GetTickCount();
// If pDBServerName is null, then we're the master and we just want to make the job_worker_start entry.
if ( pHostName )
{
Assert( !g_pDB );
// Connect the database.
g_pDB = new CMySqlDatabase;
if ( !g_pDB || !g_pDB->Initialize() || !LoadMySQLWrapper( pHostName, pDBName, pUserName ) )
{
delete g_pDB;
g_pDB = NULL;
return false;
}
// Get our machine name to store in the database.
DWORD size = sizeof( g_MachineName );
GetComputerName( g_MachineName, &size );
}
g_JobPrimaryID = DBJobID;
g_JobWorkerID = 0;
CMySQLQuery query;
query.Format( "insert into job_worker_start ( JobID, CurrentStage, IsMaster, MachineName ) values ( %lu, \"none\", %d, \"%s\" )",
g_JobPrimaryID, g_bMaster, g_MachineName );
query.Execute( g_pSQL );
g_JobWorkerID = g_pSQL->InsertID();
if ( g_JobWorkerID == 0 )
{
delete g_pDB;
g_pDB = NULL;
return false;
}
// Now create a thread that samples perf data and stores it in the database.
g_hPerfThreadExitEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
g_hPerfThread = CreateThread(
NULL,
0,
PerfThreadFn,
NULL,
0,
&g_PerfThreadID );
return true;
}
void VMPI_Stats_Term()
{
if ( !g_pDB )
return;
// Stop the thread.
SetEvent( g_hPerfThreadExitEvent );
WaitForSingleObject( g_hPerfThread, INFINITE );
CloseHandle( g_hPerfThreadExitEvent );
g_hPerfThreadExitEvent = NULL;
CloseHandle( g_hPerfThread );
g_hPerfThread = NULL;
if ( g_bMaster )
{
// (Write a job_master_end entry here).
g_pDB->AddCommandToQueue( new CSQLDBCommand_JobMasterEnd, NULL );
}
// Wait for up to a second for the DB to finish writing its data.
DWORD startTime = GetTickCount();
while ( GetTickCount() - startTime < 1000 )
{
if ( g_pDB->QueriesInOutQueue() == 0 )
break;
}
delete g_pDB;
g_pDB = NULL;
UnloadMySQLWrapper();
}
static bool ReadStringFromFile( FILE *fp, char *pStr, int strSize )
{
int i=0;
for ( i; i < strSize-2; i++ )
{
if ( fread( &pStr[i], 1, 1, fp ) != 1 ||
pStr[i] == '\n' )
{
break;
}
}
pStr[i] = 0;
return i != 0;
}
// This looks for pDBInfoFilename in the same path as pBaseExeFilename.
// The file has 3 lines: machine name (with database), database name, username
void GetDBInfo( const char *pDBInfoFilename, CDBInfo *pInfo )
{
char baseExeFilename[512];
if ( !GetModuleFileName( GetModuleHandle( NULL ), baseExeFilename, sizeof( baseExeFilename ) ) )
Error( "GetModuleFileName failed." );
// Look for the info file in the same directory as the exe.
char dbInfoFilename[512];
Q_strncpy( dbInfoFilename, baseExeFilename, sizeof( dbInfoFilename ) );
Q_StripFilename( dbInfoFilename );
if ( dbInfoFilename[0] == 0 )
Q_strncpy( dbInfoFilename, ".", sizeof( dbInfoFilename ) );
Q_strncat( dbInfoFilename, "/", sizeof( dbInfoFilename ), COPY_ALL_CHARACTERS );
Q_strncat( dbInfoFilename, pDBInfoFilename, sizeof( dbInfoFilename ), COPY_ALL_CHARACTERS );
FILE *fp = fopen( dbInfoFilename, "rt" );
if ( !fp )
{
Error( "Can't open %s for database info.\n", dbInfoFilename );
}
if ( !ReadStringFromFile( fp, pInfo->m_HostName, sizeof( pInfo->m_HostName ) ) ||
!ReadStringFromFile( fp, pInfo->m_DBName, sizeof( pInfo->m_DBName ) ) ||
!ReadStringFromFile( fp, pInfo->m_UserName, sizeof( pInfo->m_UserName ) )
)
{
Error( "%s is not a valid database info file.\n", dbInfoFilename );
}
fclose( fp );
}
void RunJobWatchApp( char *pCmdLine )
{
STARTUPINFO si;
memset( &si, 0, sizeof( si ) );
si.cb = sizeof( si );
PROCESS_INFORMATION pi;
memset( &pi, 0, sizeof( pi ) );
// Working directory should be the same as our exe's directory.
char dirName[512];
if ( GetModuleFileName( NULL, dirName, sizeof( dirName ) ) != 0 )
{
char *s1 = V_strrchr( dirName, '\\' );
char *s2 = V_strrchr( dirName, '/' );
if ( s1 || s2 )
{
// Get rid of the last slash.
s1 = max( s1, s2 );
s1[0] = 0;
if ( !CreateProcess(
NULL,
pCmdLine,
NULL, // security
NULL,
TRUE,
0, // flags
NULL, // environment
dirName, // current directory
&si,
&pi ) )
{
Warning( "%s - error launching '%s'\n", VMPI_GetParamString( mpi_Job_Watch ), pCmdLine );
}
}
}
}
void StatsDB_InitStatsDatabase(
int argc,
char **argv,
const char *pDBInfoFilename )
{
// Did they disable the stats database?
if ( !g_bMPI_Stats && !VMPI_IsParamUsed( mpi_Job_Watch ) )
return;
unsigned long jobPrimaryID;
// Now open the DB.
if ( g_bMPIMaster )
{
CDBInfo dbInfo;
GetDBInfo( pDBInfoFilename, &dbInfo );
if ( !VMPI_Stats_Init_Master( dbInfo.m_HostName, dbInfo.m_DBName, dbInfo.m_UserName, argv[argc-1], &jobPrimaryID ) )
{
Warning( "VMPI_Stats_Init_Master( %s, %s, %s ) failed.\n", dbInfo.m_HostName, dbInfo.m_DBName, dbInfo.m_UserName );
// Tell the workers not to use stats.
dbInfo.m_HostName[0] = 0;
}
char cmdLine[2048];
Q_snprintf( cmdLine, sizeof( cmdLine ), "vmpi_job_watch -JobID %d", jobPrimaryID );
Msg( "\nTo watch this job, run this command line:\n%s\n\n", cmdLine );
if ( VMPI_IsParamUsed( mpi_Job_Watch ) )
{
// Convenience thing to automatically launch the job watch for this job.
RunJobWatchApp( cmdLine );
}
// Send the database info to all the workers.
SendDBInfo( &dbInfo, jobPrimaryID );
}
else
{
// Wait to get DB info so we can connect to the MySQL database.
CDBInfo dbInfo;
unsigned long jobPrimaryID;
RecvDBInfo( &dbInfo, &jobPrimaryID );
if ( dbInfo.m_HostName[0] != 0 )
{
if ( !VMPI_Stats_Init_Worker( dbInfo.m_HostName, dbInfo.m_DBName, dbInfo.m_UserName, jobPrimaryID ) )
Error( "VMPI_Stats_Init_Worker( %s, %s, %s, %d ) failed.\n", dbInfo.m_HostName, dbInfo.m_DBName, dbInfo.m_UserName, jobPrimaryID );
}
}
}
unsigned long StatsDB_GetUniqueJobID()
{
return g_JobPrimaryID;
}
unsigned long VMPI_Stats_GetJobWorkerID()
{
return g_JobWorkerID;
}

View File

@@ -0,0 +1,59 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef MPI_STATS_H
#define MPI_STATS_H
#ifdef _WIN32
#pragma once
#endif
// The VMPI stats module reports a bunch of statistics to a MySQL server, and the
// stats can be used to trace and graph a compile session.
//
// Call this as soon as possible to initialize spew hooks.
void VMPI_Stats_InstallSpewHook();
//
// pDBServerName is the hostname (or dotted IP address) of the MySQL server to connect to.
// pBSPFilename is the last argument on the command line.
// pMachineIP is the dotted IP address of this machine.
// jobID is an 8-byte unique identifier for this job.
//
bool VMPI_Stats_Init_Master( const char *pHostName, const char *pDBName, const char *pUserName, const char *pBSPFilename, unsigned long *pDBJobID );
bool VMPI_Stats_Init_Worker( const char *pHostName, const char *pDBName, const char *pUserName, unsigned long DBJobID );
void VMPI_Stats_Term();
// Add a generic text event to the database.
void VMPI_Stats_AddEventText( const char *pText );
class CDBInfo
{
public:
char m_HostName[128];
char m_DBName[128];
char m_UserName[128];
};
// If you're the master, this loads pDBInfoFilename, sends that info to the workers, and
// connects to the database.
//
// If you're a worker, this waits for the DB info, then connects to the database.
void StatsDB_InitStatsDatabase(
int argc,
char **argv,
const char *pDBInfoFilename );
// The database gives back a unique ID for the job.
unsigned long StatsDB_GetUniqueJobID();
// Get the worker ID (used for the JobWorkerID fields in the database).
unsigned long VMPI_Stats_GetJobWorkerID();
#endif // MPI_STATS_H

View File

@@ -0,0 +1,930 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
//-----------------------------------------------------------------------------
// FILE: TRISTRIP.CPP
//
// Desc: Xbox tristripper
//
// Copyright (c) 1999-2000 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
// identifier was truncated to '255' characters in the debug information
#pragma warning(disable: 4786)
// conversion from 'double' to 'float'
#pragma warning(disable: 4244)
#pragma warning(disable: 4530)
#include <stdio.h>
#include <stdarg.h>
#include <algorithm>
#include <list>
#include <vector>
#include <assert.h>
#ifdef _DEBUG
#include <crtdbg.h>
#endif
#include "mstristrip.h"
using namespace std;
//=========================================================================
// structs
//=========================================================================
typedef vector<WORD> STRIPVERTS;
typedef list<STRIPVERTS *> STRIPLIST;
typedef WORD (*TRIANGLELIST)[3];
struct TRIANGLEINFO
{
int neighbortri[3];
int neighboredge[3];
};
// return true if strip starts clockwise
inline bool FIsStripCW(const STRIPVERTS &stripvertices)
{
// last index should have cw/ccw bool
return !!stripvertices[stripvertices.size() - 1];
}
// return length of strip
inline int StripLen(const STRIPVERTS &stripvertices)
{
return (int)stripvertices.size() - 1;
}
// free all stripverts and clear the striplist
inline void FreeStripListVerts(STRIPLIST *pstriplist)
{
STRIPLIST::iterator istriplist = pstriplist->begin();
while(istriplist != pstriplist->end())
{
STRIPVERTS *pstripverts = *istriplist;
delete pstripverts;
pstriplist->erase(istriplist++);
}
}
//=========================================================================
// main stripper class
//=========================================================================
class CStripper
{
public:
// ctors/dtors
CStripper(int numtris, TRIANGLELIST ptriangles);
~CStripper();
// initialize tri info
void InitTriangleInfo(int tri, int vert);
// get maximum length strip from tri/vert
int CreateStrip(int tri, int vert, int maxlen, int *pswaps,
bool flookahead, bool fstartcw, int *pstriptris, int *pstripverts);
// stripify entire mesh
void BuildStrips(STRIPLIST *pstriplist, int maxlen, bool flookahead);
// blast strip indices to ppstripindices
int CreateManyStrips(STRIPLIST *pstriplist, WORD **ppstripindices);
int CreateLongStrip(STRIPLIST *pstriplist, WORD **ppstripindices);
inline int GetNeighborCount(int tri)
{
int count = 0;
for(int vert = 0; vert < 3; vert++)
{
int neighbortri = m_ptriinfo[tri].neighbortri[vert];
count += (neighbortri != -1) && !m_pused[neighbortri];
}
return count;
}
// from callee
int m_numtris; // # tris
TRIANGLELIST m_ptriangles; // trilist
TRIANGLEINFO *m_ptriinfo; // tri edge, neighbor info
int *m_pused; // tri used flag
};
//=========================================================================
// vertex cache class
//=========================================================================
class CVertCache
{
public:
CVertCache()
{ Reset(); }
~CVertCache()
{};
// reset cache
void Reset()
{
m_iCachePtr = 0;
m_cachehits = 0;
memset(m_rgCache, 0xff, sizeof(m_rgCache));
}
// add vertindex to cache
bool Add(int strip, int vertindex);
int NumCacheHits() const
{ return m_cachehits; }
// enum { CACHE_SIZE = 10 };
enum { CACHE_SIZE = 18 };
private:
int m_cachehits; // current # of cache hits
WORD m_rgCache[CACHE_SIZE]; // vertex cache
int m_rgCacheStrip[CACHE_SIZE]; // strip # which added vert
int m_iCachePtr; // fifo ptr
};
//=========================================================================
// Get maximum length of strip starting at tri/vert
//=========================================================================
int CStripper::CreateStrip(int tri, int vert, int maxlen, int *pswaps,
bool flookahead, bool fstartcw, int *pstriptris, int *pstripverts)
{
*pswaps = 0;
// this guy has already been used?
if(m_pused[tri])
return 0;
// mark tri as used
m_pused[tri] = 1;
int swaps = 0;
// add first tri info
pstriptris[0] = tri;
pstriptris[1] = tri;
pstriptris[2] = tri;
if(fstartcw)
{
pstripverts[0] = (vert) % 3;
pstripverts[1] = (vert + 1) % 3;
pstripverts[2] = (vert + 2) % 3;
}
else
{
pstripverts[0] = (vert + 1) % 3;
pstripverts[1] = (vert + 0) % 3;
pstripverts[2] = (vert + 2) % 3;
}
fstartcw = !fstartcw;
// get next tri information
int edge = (fstartcw ? vert + 2 : vert + 1) % 3;
int nexttri = m_ptriinfo[tri].neighbortri[edge];
int nextvert = m_ptriinfo[tri].neighboredge[edge];
// start building the strip until we run out of room or indices
int stripcount;
for( stripcount = 3; stripcount < maxlen; stripcount++)
{
// dead end?
if(nexttri == -1 || m_pused[nexttri])
break;
// move to next tri
tri = nexttri;
vert = nextvert;
// toggle orientation
fstartcw = !fstartcw;
// find the next natural edge
int edge = (fstartcw ? vert + 2 : vert + 1) % 3;
nexttri = m_ptriinfo[tri].neighbortri[edge];
nextvert = m_ptriinfo[tri].neighboredge[edge];
bool fswap = false;
if(nexttri == -1 || m_pused[nexttri])
{
// if the next tri is a dead end - try swapping orientation
fswap = true;
}
else if(flookahead)
{
// try a swap and see who our new neighbor would be
int edgeswap = (fstartcw ? vert + 1 : vert + 2) % 3;
int nexttriswap = m_ptriinfo[tri].neighbortri[edgeswap];
int nextvertswap = m_ptriinfo[tri].neighboredge[edgeswap];
if(nexttriswap != -1 && !m_pused[nexttriswap])
{
assert(nexttri != -1);
// if the swap neighbor has a lower count, change directions
if(GetNeighborCount(nexttriswap) < GetNeighborCount(nexttri))
{
fswap = true;
}
else if(GetNeighborCount(nexttriswap) == GetNeighborCount(nexttri))
{
// if they have the same number of neighbors - check their neighbors
edgeswap = (fstartcw ? nextvertswap + 2 : nextvertswap + 1) % 3;
nexttriswap = m_ptriinfo[nexttriswap].neighbortri[edgeswap];
int edge1 = (fstartcw ? nextvert + 1 : nextvert + 2) % 3;
int nexttri1 = m_ptriinfo[nexttri].neighbortri[edge1];
if(nexttri1 == -1 || m_pused[nexttri1])
{
// natural winding order leads us to a dead end so turn
fswap = true;
}
else if(nexttriswap != -1 && !m_pused[nexttriswap])
{
// check neighbor counts on both directions and swap if it's better
if(GetNeighborCount(nexttriswap) < GetNeighborCount(nexttri1))
fswap = true;
}
}
}
}
if(fswap)
{
// we've been told to change directions so make sure we actually can
// and then add the swap vertex
int edgeswap = (fstartcw ? vert + 1 : vert + 2) % 3;
nexttri = m_ptriinfo[tri].neighbortri[edgeswap];
nextvert = m_ptriinfo[tri].neighboredge[edgeswap];
if(nexttri != -1 && !m_pused[nexttri])
{
pstriptris[stripcount] = pstriptris[stripcount - 2];
pstripverts[stripcount] = pstripverts[stripcount - 2];
stripcount++;
swaps++;
fstartcw = !fstartcw;
}
}
// record index information
pstriptris[stripcount] = tri;
pstripverts[stripcount] = (vert + 2) % 3;
// mark triangle as used
m_pused[tri] = 1;
}
// clear the used flags
for(int j = 2; j < stripcount; j++)
m_pused[pstriptris[j]] = 0;
// return swap count and striplen
*pswaps = swaps;
return stripcount;
}
//=========================================================================
// Given a striplist and current cache state, pick the best next strip
//=========================================================================
STRIPLIST::iterator FindBestCachedStrip(STRIPLIST *pstriplist,
const CVertCache &vertcachestate)
{
if(pstriplist->empty())
return pstriplist->end();
bool fFlipStrip = false;
int maxcachehits = -1;
STRIPLIST::iterator istriplistbest = pstriplist->begin();
int striplen = StripLen(**istriplistbest);
bool fstartcw = FIsStripCW(**istriplistbest);
// go through all the other strips looking for the best caching
for(STRIPLIST::iterator istriplist = pstriplist->begin();
istriplist != pstriplist->end();
++istriplist)
{
bool fFlip = false;
const STRIPVERTS &stripverts = **istriplist;
int striplennew = StripLen(stripverts);
// check cache if this strip is the same type as us (ie: cw/odd)
if((FIsStripCW(stripverts) == fstartcw) &&
((striplen & 0x1) == (striplennew & 0x1)))
{
// copy current state of cache
CVertCache vertcachenew = vertcachestate;
// figure out what this guy would do to our cache
for(int ivert = 0; ivert < striplennew; ivert++)
vertcachenew.Add(2, stripverts[ivert]);
// even length strip - see if better cache hits reversed
if(!(striplennew & 0x1))
{
CVertCache vertcacheflipped = vertcachestate;
for(int ivert = StripLen(stripverts) - 1; ivert >= 0; ivert--)
vertcacheflipped.Add(2, stripverts[ivert]);
if(vertcacheflipped.NumCacheHits() > vertcachenew.NumCacheHits())
{
vertcachenew = vertcacheflipped;
fFlip = true;
}
}
// record the best number of cache hits to date
int numcachehits = vertcachenew.NumCacheHits() - vertcachestate.NumCacheHits();
if(numcachehits > maxcachehits)
{
maxcachehits = numcachehits;
istriplistbest = istriplist;
fFlipStrip = fFlip;
}
}
}
if(fFlipStrip)
{
STRIPVERTS &stripverts = **istriplistbest;
STRIPVERTS::iterator vend = stripverts.end();
reverse(stripverts.begin(), --vend);
}
// make sure we keep the list in order and always pull off
// the first dude.
if(istriplistbest != pstriplist->begin())
swap(*istriplistbest, *pstriplist->begin());
return pstriplist->begin();
}
//=========================================================================
// Don't merge the strips - just blast em into the stripbuffer one by one
// (useful for debugging)
//=========================================================================
int CStripper::CreateManyStrips(STRIPLIST *pstriplist, WORD **ppstripindices)
{
// allow room for each of the strips size plus the final 0
int indexcount = (int)pstriplist->size() + 1;
// we're storing the strips in [size1 i1 i2 i3][size2 i4 i5 i6][0] format
STRIPLIST::iterator istriplist;
for( istriplist = pstriplist->begin(); istriplist != pstriplist->end(); ++istriplist)
{
// add striplength plus potential degenerate to swap ccw --> cw
indexcount += StripLen(**istriplist) + 1;
}
// alloc the space for all this stuff
WORD *pstripindices = new WORD [indexcount];
assert(pstripindices);
CVertCache vertcache;
int numstripindices = 0;
for(istriplist = pstriplist->begin();
!pstriplist->empty();
istriplist = FindBestCachedStrip(pstriplist, vertcache))
{
const STRIPVERTS &stripverts = **istriplist;
if(!FIsStripCW(stripverts))
{
// add an extra index if it's ccw
pstripindices[numstripindices++] = StripLen(stripverts) + 1;
pstripindices[numstripindices++] = stripverts[0];
}
else
{
// add the strip length
pstripindices[numstripindices++] = StripLen(stripverts);
}
// add all the strip indices
for(int i = 0; i < StripLen(stripverts); i++)
{
pstripindices[numstripindices++] = stripverts[i];
vertcache.Add(1, stripverts[i]);
}
// free this guy and pop him off the list
delete &stripverts;
pstriplist->pop_front();
}
// add terminating zero
pstripindices[numstripindices++] = 0;
*ppstripindices = pstripindices;
return numstripindices;
}
//=========================================================================
// Merge striplist into one big uberlist with (hopefully) optimal caching
//=========================================================================
int CStripper::CreateLongStrip(STRIPLIST *pstriplist, WORD **ppstripindices)
{
// allow room for one strip length plus a possible 3 extra indices per
// concatenated strip list plus the final 0
int indexcount = ((int)pstriplist->size() * 3) + 2;
// we're storing the strips in [size1 i1 i2 i3][size2 i4 i5 i6][0] format
STRIPLIST::iterator istriplist;
for( istriplist = pstriplist->begin(); istriplist != pstriplist->end(); ++istriplist)
{
indexcount += StripLen(**istriplist);
}
// alloc the space for all this stuff
WORD *pstripindices = new WORD [indexcount];
assert(pstripindices);
CVertCache vertcache;
int numstripindices = 0;
// add first strip
istriplist = pstriplist->begin();
const STRIPVERTS &stripverts = **istriplist;
// first strip should be cw
assert(FIsStripCW(stripverts));
for(int ivert = 0; ivert < StripLen(stripverts); ivert++)
{
pstripindices[numstripindices++] = stripverts[ivert];
vertcache.Add(1, stripverts[ivert]);
}
// kill first dude
delete &stripverts;
pstriplist->erase(istriplist);
// add all the others
while(pstriplist->size())
{
istriplist = FindBestCachedStrip(pstriplist, vertcache);
STRIPVERTS &stripverts = **istriplist;
short lastvert = pstripindices[numstripindices - 1];
short firstvert = stripverts[0];
if(firstvert != lastvert)
{
// add degenerate from last strip
pstripindices[numstripindices++] = lastvert;
// add degenerate from our strip
pstripindices[numstripindices++] = firstvert;
}
// if we're not orientated correctly, we need to add a degenerate
if(FIsStripCW(stripverts) != !(numstripindices & 0x1))
{
// This shouldn't happen - we're currently trying very hard
// to keep everything oriented correctly.
assert(false);
pstripindices[numstripindices++] = firstvert;
}
// add these verts
for(int ivert = 0; ivert < StripLen(stripverts); ivert++)
{
pstripindices[numstripindices++] = stripverts[ivert];
vertcache.Add(1, stripverts[ivert]);
}
// free these guys
delete &stripverts;
pstriplist->erase(istriplist);
}
*ppstripindices = pstripindices;
return numstripindices;
}
//=========================================================================
// Build a (hopefully) optimal set of strips from a trilist
//=========================================================================
void CStripper::BuildStrips(STRIPLIST *pstriplist, int maxlen, bool flookahead)
{
// temp indices storage
const int ctmpverts = 1024;
int pstripverts[ctmpverts + 1];
int pstriptris[ctmpverts + 1];
assert(maxlen <= ctmpverts);
// clear all the used flags for the tris
memset(m_pused, 0, sizeof(m_pused[0]) * m_numtris);
bool fstartcw = true;
for(;;)
{
int besttri = 0;
int bestvert = 0;
float bestratio = 2.0f;
int bestneighborcount = INT_MAX;
int tri;
for( tri = 0; tri < m_numtris; tri++)
{
// if used the continue
if(m_pused[tri])
continue;
// get the neighbor count
int curneightborcount = GetNeighborCount(tri);
assert(curneightborcount >= 0 && curneightborcount <= 3);
// push all the singletons to the very end
if(!curneightborcount)
curneightborcount = 4;
// if this guy has more neighbors than the current best - bail
if(curneightborcount > bestneighborcount)
continue;
// try starting the strip with each of this tris verts
for(int vert = 0; vert < 3; vert++)
{
int swaps;
int len = CreateStrip(tri, vert, maxlen, &swaps, flookahead,
fstartcw, pstriptris, pstripverts);
assert(len);
float ratio = (len == 3) ? 1.0f : (float)swaps / len;
// check if this ratio is better than what we've already got for
// this neighborcount
if((curneightborcount < bestneighborcount) ||
((curneightborcount == bestneighborcount) && (ratio < bestratio)))
{
bestneighborcount = curneightborcount;
besttri = tri;
bestvert = vert;
bestratio = ratio;
}
}
}
// no strips found?
if(bestneighborcount == INT_MAX)
break;
// recreate this strip
int swaps;
int len = CreateStrip(besttri, bestvert, maxlen,
&swaps, flookahead, fstartcw, pstriptris, pstripverts);
assert(len);
// mark the tris on the best strip as used
for(tri = 0; tri < len; tri++)
m_pused[pstriptris[tri]] = 1;
// create a new STRIPVERTS and stuff in the indices
STRIPVERTS *pstripvertices = new STRIPVERTS(len + 1);
assert(pstripvertices);
// store orientation in first entry
for(tri = 0; tri < len; tri++)
(*pstripvertices)[tri] = m_ptriangles[pstriptris[tri]][pstripverts[tri]];
(*pstripvertices)[len] = fstartcw;
// store the STRIPVERTS
pstriplist->push_back(pstripvertices);
// if strip was odd - swap orientation
if((len & 0x1))
fstartcw = !fstartcw;
}
#ifdef _DEBUG
// make sure all tris are used
for(int t = 0; t < m_numtris; t++)
assert(m_pused[t]);
#endif
}
//=========================================================================
// Guesstimate on the total index count for this list of strips
//=========================================================================
int EstimateStripCost(STRIPLIST *pstriplist)
{
int count = 0;
for(STRIPLIST::iterator istriplist = pstriplist->begin();
istriplist != pstriplist->end();
++istriplist)
{
// add count of indices
count += StripLen(**istriplist);
}
// assume 2 indices per strip to tack all these guys together
return count + ((int)pstriplist->size() - 1) * 2;
}
//=========================================================================
// Initialize triangle information (edges, #neighbors, etc.)
//=========================================================================
void CStripper::InitTriangleInfo(int tri, int vert)
{
WORD *ptriverts = &m_ptriangles[tri + 1][0];
int vert1 = m_ptriangles[tri][(vert + 1) % 3];
int vert2 = m_ptriangles[tri][vert];
for(int itri = tri + 1; itri < m_numtris; itri++, ptriverts += 3)
{
if(m_pused[itri] != 0x7)
{
for(int ivert = 0; ivert < 3; ivert++)
{
if((ptriverts[ivert] == vert1) &&
(ptriverts[(ivert + 1) % 3] == vert2))
{
// add the triangle info
m_ptriinfo[tri].neighbortri[vert] = itri;
m_ptriinfo[tri].neighboredge[vert] = ivert;
m_pused[tri] |= (1 << vert);
m_ptriinfo[itri].neighbortri[ivert] = tri;
m_ptriinfo[itri].neighboredge[ivert] = vert;
m_pused[itri] |= (1 << ivert);
return;
}
}
}
}
}
//=========================================================================
// CStripper ctor
//=========================================================================
CStripper::CStripper(int numtris, TRIANGLELIST ptriangles)
{
// store trilist info
m_numtris = numtris;
m_ptriangles = ptriangles;
m_pused = new int[numtris];
assert(m_pused);
m_ptriinfo = new TRIANGLEINFO[numtris];
assert(m_ptriinfo);
// init triinfo
int itri;
for( itri = 0; itri < numtris; itri++)
{
m_ptriinfo[itri].neighbortri[0] = -1;
m_ptriinfo[itri].neighbortri[1] = -1;
m_ptriinfo[itri].neighbortri[2] = -1;
}
// clear the used flag
memset(m_pused, 0, sizeof(m_pused[0]) * m_numtris);
// go through all the triangles and find edges, neighbor counts
for(itri = 0; itri < numtris; itri++)
{
for(int ivert = 0; ivert < 3; ivert++)
{
if(!(m_pused[itri] & (1 << ivert)))
InitTriangleInfo(itri, ivert);
}
}
// clear the used flags from InitTriangleInfo
memset(m_pused, 0, sizeof(m_pused[0]) * m_numtris);
}
//=========================================================================
// CStripper dtor
//=========================================================================
CStripper::~CStripper()
{
// free stuff
delete [] m_pused;
m_pused = NULL;
delete [] m_ptriinfo;
m_ptriinfo = NULL;
}
//=========================================================================
// Add an index to the cache - returns true if it was added, false otherwise
//=========================================================================
bool CVertCache::Add(int strip, int vertindex)
{
// find index in cache
for(int iCache = 0; iCache < CACHE_SIZE; iCache++)
{
if(vertindex == m_rgCache[iCache])
{
// if it's in the cache and it's from a different strip
// change the strip to the new one and count the cache hit
if(strip != m_rgCacheStrip[iCache])
{
m_cachehits++;
m_rgCacheStrip[iCache] = strip;
return true;
}
// we added this item to the cache earlier - carry on
return false;
}
}
// not in cache, add vert and strip
m_rgCache[m_iCachePtr] = vertindex;
m_rgCacheStrip[m_iCachePtr] = strip;
m_iCachePtr = (m_iCachePtr + 1) % CACHE_SIZE;
return true;
}
#ifdef _DEBUG
//=========================================================================
// Turn on c runtime leak checking, etc.
//=========================================================================
void EnableLeakChecking()
{
int flCrtDbgFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
flCrtDbgFlags &=
~(_CRTDBG_LEAK_CHECK_DF |
_CRTDBG_CHECK_ALWAYS_DF |
_CRTDBG_DELAY_FREE_MEM_DF);
// always check for memory leaks
flCrtDbgFlags |= _CRTDBG_LEAK_CHECK_DF;
// others you may / may not want to set
flCrtDbgFlags |= _CRTDBG_CHECK_ALWAYS_DF;
flCrtDbgFlags |= _CRTDBG_DELAY_FREE_MEM_DF;
_CrtSetDbgFlag(flCrtDbgFlags);
// all types of reports go via OutputDebugString
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_DEBUG);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
// big errors and asserts get their own assert window
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW);
// _CrtSetBreakAlloc(0);
}
#endif
//=========================================================================
// Main Stripify routine
//=========================================================================
int Stripify(int numtris, WORD *ptriangles, int *pnumindices, WORD **ppstripindices)
{
if(!numtris || !ptriangles)
return 0;
#ifdef _DEBUG
// EnableLeakChecking();
#endif
CStripper stripper(numtris, (TRIANGLELIST)ptriangles);
// map of various args to try stripifying mesh with
struct ARGMAP
{
int maxlen; // maximum length of strips
bool flookahead; // use sgi greedy lookahead (or not)
} rgargmap[] =
{
{ 1024, true },
{ 1024, false },
};
static const int cargmaps = sizeof(rgargmap) / sizeof(rgargmap[0]);
STRIPLIST striplistbest;
int bestlistcost = 0;
for(int imap = 0; imap < cargmaps; imap++)
{
STRIPLIST striplist;
// build the strip with the various args
stripper.BuildStrips(&striplist, rgargmap[imap].maxlen,
rgargmap[imap].flookahead);
// guesstimate the list cost and store it if it's good
int listcost = EstimateStripCost(&striplist);
if(!bestlistcost || (listcost < bestlistcost))
{
// free the old best list
FreeStripListVerts(&striplistbest);
// store the new best list
striplistbest = striplist;
bestlistcost = listcost;
assert(bestlistcost > 0);
}
else
{
FreeStripListVerts(&striplist);
}
}
#ifdef NEVER
// Return the strips in [size1 i1 i2 i3][size2 i4 i5 i6]...[0] format
// Very useful for debugging...
return stripper.CreateManyStrips(&striplistbest, ppstripindices);
#endif // NEVER
// return one big long strip
int numindices = stripper.CreateLongStrip(&striplistbest, ppstripindices);
if(pnumindices)
*pnumindices = numindices;
return numindices;
}
//=========================================================================
// Class used to vertices for locality of access.
//=========================================================================
struct SortEntry
{
public:
int iFirstUsed;
int iOrigIndex;
bool operator<(const SortEntry& rhs)
{
return iFirstUsed < rhs.iFirstUsed;
}
};
//=========================================================================
// Reorder the vertices
//=========================================================================
void ComputeVertexPermutation(int numstripindices, WORD* pstripindices,
int* pnumverts, WORD** ppvertexpermutation)
{
// Sort verts to maximize locality.
SortEntry* pSortTable = new SortEntry[*pnumverts];
// Fill in original index.
int i;
for( i = 0; i < *pnumverts; i++)
{
pSortTable[i].iOrigIndex = i;
pSortTable[i].iFirstUsed = -1;
}
// Fill in first used flag.
for(i = 0; i < numstripindices; i++)
{
int index = pstripindices[i];
if(pSortTable[index].iFirstUsed == -1)
pSortTable[index].iFirstUsed = i;
}
// Sort the table.
sort(pSortTable, pSortTable + *pnumverts);
// Copy re-mapped to orignal vertex permutaion into output array.
*ppvertexpermutation = new WORD[*pnumverts];
for(i = 0; i < *pnumverts; i++)
{
(*ppvertexpermutation)[i] = pSortTable[i].iOrigIndex;
}
// Build original to re-mapped permutation.
WORD* pInversePermutation = new WORD[numstripindices];
for(i = 0; i < *pnumverts; i++)
{
pInversePermutation[pSortTable[i].iOrigIndex] = i;
}
// We need to remap indices as well.
for(i = 0; i < numstripindices; i++)
{
pstripindices[i] = pInversePermutation[pstripindices[i]];
}
delete[] pSortTable;
delete[] pInversePermutation;
}

View File

@@ -0,0 +1,43 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
//-----------------------------------------------------------------------------
// FILE: TRISTRIP.H
//
// Desc: tristrip header file
//
// Copyright (c) 1999-2000 Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
typedef unsigned short WORD;
//
// Main Stripify routine. Returns number of strip indices contained
// in ppstripindices. Caller must delete [] ppstripindices.
//
int Stripify(
int numtris, // Number of triangles
WORD *ptriangles, // triangle indices pointer
int *pnumindices, // number of indices in ppstripindices (out)
WORD **ppstripindices // triangle strip indices
);
//
// Re-arrange vertices so that they occur in the order that they are first
// used. This function doesn't actually move vertex data around, it returns
// an array that specifies where in the new vertex array each old vertex
// should go. It also re-maps the strip indices to use the new vertex
// locations. Caller must delete [] pVertexPermutation.
//
void ComputeVertexPermutation
(
int numstripindices, // Number of strip indices
WORD *pstripindices, // Strip indices
int *pnumverts, // Number of verts (in and out)
WORD **ppvertexpermutation // Map from orignal index to remapped index
);

View File

@@ -0,0 +1,63 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include <stdio.h>
#include "basetypes.h"
#include "pacifier.h"
#include "tier0/dbg.h"
static int g_LastPacifierDrawn = -1;
static bool g_bPacifierSuppressed = false;
#define clamp(a,b,c) ( (a) > (c) ? (c) : ( (a) < (b) ? (b) : (a) ) )
void StartPacifier( char const *pPrefix )
{
Msg( "%s", pPrefix );
g_LastPacifierDrawn = -1;
UpdatePacifier( 0.001f );
}
void UpdatePacifier( float flPercent )
{
int iCur = (int)(flPercent * 40.0f);
iCur = clamp( iCur, g_LastPacifierDrawn, 40 );
if( iCur != g_LastPacifierDrawn && !g_bPacifierSuppressed )
{
for( int i=g_LastPacifierDrawn+1; i <= iCur; i++ )
{
if ( !( i % 4 ) )
{
Msg("%d", i/4);
}
else
{
if( i != 40 )
{
Msg(".");
}
}
}
g_LastPacifierDrawn = iCur;
}
}
void EndPacifier( bool bCarriageReturn )
{
UpdatePacifier(1);
if( bCarriageReturn && !g_bPacifierSuppressed )
Msg("\n");
}
void SuppressPacifier( bool bSuppress )
{
g_bPacifierSuppressed = bSuppress;
}

View File

@@ -0,0 +1,23 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PACIFIER_H
#define PACIFIER_H
#ifdef _WIN32
#pragma once
#endif
// Use these to display a pacifier like:
// ProcessBlock_Thread: 0...1...2...3...4...5...6...7...8...9... (0)
void StartPacifier( char const *pPrefix ); // Prints the prefix and resets the pacifier
void UpdatePacifier( float flPercent ); // percent value between 0 and 1.
void EndPacifier( bool bCarriageReturn = true ); // Completes pacifier as if 100% was done
void SuppressPacifier( bool bSuppress = true ); // Suppresses pacifier updates if another thread might still be firing them
#endif // PACIFIER_H

View File

@@ -0,0 +1,31 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#include <stdio.h>
#include "physdll.h"
#include "filesystem_tools.h"
static CSysModule *pPhysicsModule = NULL;
CreateInterfaceFn GetPhysicsFactory( void )
{
if ( !pPhysicsModule )
{
pPhysicsModule = g_pFullFileSystem->LoadModule( "VPHYSICS.DLL" );
if ( !pPhysicsModule )
return NULL;
}
return Sys_GetFactory( pPhysicsModule );
}
void PhysicsDLLPath( const char *pPathname )
{
if ( !pPhysicsModule )
{
pPhysicsModule = g_pFullFileSystem->LoadModule( pPathname );
}
}

View File

@@ -0,0 +1,30 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef PHYSDLL_H
#define PHYSDLL_H
#pragma once
#ifdef __cplusplus
#include "vphysics_interface.h"
class IPhysics;
class IPhysicsCollision;
extern CreateInterfaceFn GetPhysicsFactory( void );
extern "C" {
#endif
// tools need to force the path
void PhysicsDLLPath( const char *pPathname );
#ifdef __cplusplus
}
#endif
#endif // PHYSDLL_H

View File

@@ -0,0 +1,915 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#include "cmdlib.h"
#include "mathlib/mathlib.h"
#include "polylib.h"
#include "worldsize.h"
#include "threads.h"
#include "tier0/dbg.h"
// doesn't seem to need to be here? -- in threads.h
//extern int numthreads;
// counters are only bumped when running single threaded,
// because they are an awefull coherence problem
int c_active_windings;
int c_peak_windings;
int c_winding_allocs;
int c_winding_points;
void pw(winding_t *w)
{
int i;
for (i=0 ; i<w->numpoints ; i++)
printf ("(%5.1f, %5.1f, %5.1f)\n",w->p[i][0], w->p[i][1],w->p[i][2]);
}
winding_t *winding_pool[MAX_POINTS_ON_WINDING+4];
/*
=============
AllocWinding
=============
*/
winding_t *AllocWinding (int points)
{
winding_t *w;
if (numthreads == 1)
{
c_winding_allocs++;
c_winding_points += points;
c_active_windings++;
if (c_active_windings > c_peak_windings)
c_peak_windings = c_active_windings;
}
ThreadLock();
if (winding_pool[points])
{
w = winding_pool[points];
winding_pool[points] = w->next;
}
else
{
w = (winding_t *)malloc(sizeof(*w));
w->p = (Vector *)calloc( points, sizeof(Vector) );
}
ThreadUnlock();
w->numpoints = 0; // None are occupied yet even though allocated.
w->maxpoints = points;
w->next = NULL;
return w;
}
void FreeWinding (winding_t *w)
{
if (w->numpoints == 0xdeaddead)
Error ("FreeWinding: freed a freed winding");
ThreadLock();
w->numpoints = 0xdeaddead; // flag as freed
w->next = winding_pool[w->maxpoints];
winding_pool[w->maxpoints] = w;
ThreadUnlock();
}
/*
============
RemoveColinearPoints
============
*/
int c_removed;
void RemoveColinearPoints (winding_t *w)
{
int i, j, k;
Vector v1, v2;
int nump;
Vector p[MAX_POINTS_ON_WINDING];
nump = 0;
for (i=0 ; i<w->numpoints ; i++)
{
j = (i+1)%w->numpoints;
k = (i+w->numpoints-1)%w->numpoints;
VectorSubtract (w->p[j], w->p[i], v1);
VectorSubtract (w->p[i], w->p[k], v2);
VectorNormalize(v1);
VectorNormalize(v2);
if (DotProduct(v1, v2) < 0.999)
{
VectorCopy (w->p[i], p[nump]);
nump++;
}
}
if (nump == w->numpoints)
return;
if (numthreads == 1)
c_removed += w->numpoints - nump;
w->numpoints = nump;
memcpy (w->p, p, nump*sizeof(p[0]));
}
/*
============
WindingPlane
============
*/
void WindingPlane (winding_t *w, Vector &normal, vec_t *dist)
{
Vector v1, v2;
VectorSubtract (w->p[1], w->p[0], v1);
// HACKHACK: Avoid potentially collinear verts
if ( w->numpoints > 3 )
{
VectorSubtract (w->p[3], w->p[0], v2);
}
else
{
VectorSubtract (w->p[2], w->p[0], v2);
}
CrossProduct (v2, v1, normal);
VectorNormalize (normal);
*dist = DotProduct (w->p[0], normal);
}
/*
=============
WindingArea
=============
*/
vec_t WindingArea(winding_t *w)
{
int i;
Vector d1, d2, cross;
vec_t total;
total = 0;
for (i=2 ; i<w->numpoints ; i++)
{
VectorSubtract (w->p[i-1], w->p[0], d1);
VectorSubtract (w->p[i], w->p[0], d2);
CrossProduct (d1, d2, cross);
total += VectorLength ( cross );
}
return total * 0.5;
}
void WindingBounds (winding_t *w, Vector &mins, Vector &maxs)
{
vec_t v;
int i,j;
mins[0] = mins[1] = mins[2] = 99999;
maxs[0] = maxs[1] = maxs[2] = -99999;
for (i=0 ; i<w->numpoints ; i++)
{
for (j=0 ; j<3 ; j++)
{
v = w->p[i][j];
if (v < mins[j])
mins[j] = v;
if (v > maxs[j])
maxs[j] = v;
}
}
}
/*
=============
WindingCenter
=============
*/
void WindingCenter (winding_t *w, Vector &center)
{
int i;
float scale;
VectorCopy (vec3_origin, center);
for (i=0 ; i<w->numpoints ; i++)
VectorAdd (w->p[i], center, center);
scale = 1.0/w->numpoints;
VectorScale (center, scale, center);
}
/*
=============
WindingCenter
=============
*/
vec_t WindingAreaAndBalancePoint( winding_t *w, Vector &center )
{
int i;
Vector d1, d2, cross;
vec_t total;
VectorCopy (vec3_origin, center);
if ( !w )
return 0.0f;
total = 0;
for (i=2 ; i<w->numpoints ; i++)
{
VectorSubtract (w->p[i-1], w->p[0], d1);
VectorSubtract (w->p[i], w->p[0], d2);
CrossProduct (d1, d2, cross);
float area = VectorLength ( cross );
total += area;
// center of triangle, weighed by area
VectorMA( center, area / 3.0, w->p[i-1], center );
VectorMA( center, area / 3.0, w->p[i], center );
VectorMA( center, area / 3.0, w->p[0], center );
}
if (total)
{
VectorScale( center, 1.0 / total, center );
}
return total * 0.5;
}
/*
=================
BaseWindingForPlane
=================
*/
winding_t *BaseWindingForPlane (const Vector &normal, vec_t dist)
{
int i, x;
vec_t max, v;
Vector org, vright, vup;
winding_t *w;
// find the major axis
max = -1;
x = -1;
for (i=0 ; i<3; i++)
{
v = fabs(normal[i]);
if (v > max)
{
x = i;
max = v;
}
}
if (x==-1)
Error ("BaseWindingForPlane: no axis found");
VectorCopy (vec3_origin, vup);
switch (x)
{
case 0:
case 1:
vup[2] = 1;
break;
case 2:
vup[0] = 1;
break;
}
v = DotProduct (vup, normal);
VectorMA (vup, -v, normal, vup);
VectorNormalize (vup);
VectorScale (normal, dist, org);
CrossProduct (vup, normal, vright);
VectorScale (vup, (MAX_COORD_INTEGER*4), vup);
VectorScale (vright, (MAX_COORD_INTEGER*4), vright);
// project a really big axis aligned box onto the plane
w = AllocWinding (4);
VectorSubtract (org, vright, w->p[0]);
VectorAdd (w->p[0], vup, w->p[0]);
VectorAdd (org, vright, w->p[1]);
VectorAdd (w->p[1], vup, w->p[1]);
VectorAdd (org, vright, w->p[2]);
VectorSubtract (w->p[2], vup, w->p[2]);
VectorSubtract (org, vright, w->p[3]);
VectorSubtract (w->p[3], vup, w->p[3]);
w->numpoints = 4;
return w;
}
/*
==================
CopyWinding
==================
*/
winding_t *CopyWinding (winding_t *w)
{
int size;
winding_t *c;
c = AllocWinding (w->numpoints);
c->numpoints = w->numpoints;
size = w->numpoints*sizeof(w->p[0]);
memcpy (c->p, w->p, size);
return c;
}
/*
==================
ReverseWinding
==================
*/
winding_t *ReverseWinding (winding_t *w)
{
int i;
winding_t *c;
c = AllocWinding (w->numpoints);
for (i=0 ; i<w->numpoints ; i++)
{
VectorCopy (w->p[w->numpoints-1-i], c->p[i]);
}
c->numpoints = w->numpoints;
return c;
}
// BUGBUG: Hunt this down - it's causing CSG errors
#pragma optimize("g", off)
/*
=============
ClipWindingEpsilon
=============
*/
void ClipWindingEpsilon (winding_t *in, const Vector &normal, vec_t dist,
vec_t epsilon, winding_t **front, winding_t **back)
{
vec_t dists[MAX_POINTS_ON_WINDING+4];
int sides[MAX_POINTS_ON_WINDING+4];
int counts[3];
vec_t dot;
int i, j;
Vector mid = vec3_origin;
winding_t *f, *b;
int maxpts;
counts[0] = counts[1] = counts[2] = 0;
// determine sides for each point
for (i=0 ; i<in->numpoints ; i++)
{
dot = DotProduct (in->p[i], normal);
dot -= dist;
dists[i] = dot;
if (dot > epsilon)
sides[i] = SIDE_FRONT;
else if (dot < -epsilon)
sides[i] = SIDE_BACK;
else
{
sides[i] = SIDE_ON;
}
counts[sides[i]]++;
}
sides[i] = sides[0];
dists[i] = dists[0];
*front = *back = NULL;
if (!counts[0])
{
*back = CopyWinding (in);
return;
}
if (!counts[1])
{
*front = CopyWinding (in);
return;
}
maxpts = in->numpoints+4; // cant use counts[0]+2 because
// of fp grouping errors
*front = f = AllocWinding (maxpts);
*back = b = AllocWinding (maxpts);
for (i=0 ; i<in->numpoints ; i++)
{
Vector& p1 = in->p[i];
if (sides[i] == SIDE_ON)
{
VectorCopy (p1, f->p[f->numpoints]);
f->numpoints++;
VectorCopy (p1, b->p[b->numpoints]);
b->numpoints++;
continue;
}
if (sides[i] == SIDE_FRONT)
{
VectorCopy (p1, f->p[f->numpoints]);
f->numpoints++;
}
if (sides[i] == SIDE_BACK)
{
VectorCopy (p1, b->p[b->numpoints]);
b->numpoints++;
}
if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
continue;
// generate a split point
Vector& p2 = in->p[(i+1)%in->numpoints];
dot = dists[i] / (dists[i]-dists[i+1]);
for (j=0 ; j<3 ; j++)
{ // avoid round off error when possible
if (normal[j] == 1)
mid[j] = dist;
else if (normal[j] == -1)
mid[j] = -dist;
else
mid[j] = p1[j] + dot*(p2[j]-p1[j]);
}
VectorCopy (mid, f->p[f->numpoints]);
f->numpoints++;
VectorCopy (mid, b->p[b->numpoints]);
b->numpoints++;
}
if (f->numpoints > maxpts || b->numpoints > maxpts)
Error ("ClipWinding: points exceeded estimate");
if (f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING)
Error ("ClipWinding: MAX_POINTS_ON_WINDING");
}
#pragma optimize("", on)
// NOTE: This is identical to ClipWindingEpsilon, but it does a pre/post translation to improve precision
void ClipWindingEpsilon_Offset( winding_t *in, const Vector &normal, vec_t dist, vec_t epsilon, winding_t **front, winding_t **back, const Vector &offset )
{
TranslateWinding( in, offset );
ClipWindingEpsilon( in, normal, dist+DotProduct(offset,normal), epsilon, front, back );
TranslateWinding( in, -offset );
if ( front && *front )
{
TranslateWinding( *front, -offset );
}
if ( back && *back )
{
TranslateWinding( *back, -offset );
}
}
void ClassifyWindingEpsilon_Offset( winding_t *in, const Vector &normal, vec_t dist, vec_t epsilon, winding_t **front, winding_t **back, winding_t **on, const Vector &offset)
{
TranslateWinding( in, offset );
ClassifyWindingEpsilon( in, normal, dist+DotProduct(offset,normal), epsilon, front, back, on );
TranslateWinding( in, -offset );
if ( front && *front )
{
TranslateWinding( *front, -offset );
}
if ( back && *back )
{
TranslateWinding( *back, -offset );
}
if ( on && *on )
{
TranslateWinding( *on, -offset );
}
}
/*
=============
ClassifyWindingEpsilon
=============
*/
// This version returns the winding as "on" if all verts lie in the plane
void ClassifyWindingEpsilon( winding_t *in, const Vector &normal, vec_t dist,
vec_t epsilon, winding_t **front, winding_t **back, winding_t **on)
{
vec_t dists[MAX_POINTS_ON_WINDING+4];
int sides[MAX_POINTS_ON_WINDING+4];
int counts[3];
vec_t dot;
int i, j;
Vector mid = vec3_origin;
winding_t *f, *b;
int maxpts;
counts[0] = counts[1] = counts[2] = 0;
// determine sides for each point
for (i=0 ; i<in->numpoints ; i++)
{
dot = DotProduct (in->p[i], normal);
dot -= dist;
dists[i] = dot;
if (dot > epsilon)
sides[i] = SIDE_FRONT;
else if (dot < -epsilon)
sides[i] = SIDE_BACK;
else
{
sides[i] = SIDE_ON;
}
counts[sides[i]]++;
}
sides[i] = sides[0];
dists[i] = dists[0];
*front = *back = *on = NULL;
if ( !counts[0] && !counts[1] )
{
*on = CopyWinding(in);
return;
}
if (!counts[0])
{
*back = CopyWinding(in);
return;
}
if (!counts[1])
{
*front = CopyWinding(in);
return;
}
maxpts = in->numpoints+4; // cant use counts[0]+2 because
// of fp grouping errors
*front = f = AllocWinding (maxpts);
*back = b = AllocWinding (maxpts);
for (i=0 ; i<in->numpoints ; i++)
{
Vector& p1 = in->p[i];
if (sides[i] == SIDE_ON)
{
VectorCopy (p1, f->p[f->numpoints]);
f->numpoints++;
VectorCopy (p1, b->p[b->numpoints]);
b->numpoints++;
continue;
}
if (sides[i] == SIDE_FRONT)
{
VectorCopy (p1, f->p[f->numpoints]);
f->numpoints++;
}
if (sides[i] == SIDE_BACK)
{
VectorCopy (p1, b->p[b->numpoints]);
b->numpoints++;
}
if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
continue;
// generate a split point
Vector& p2 = in->p[(i+1)%in->numpoints];
dot = dists[i] / (dists[i]-dists[i+1]);
for (j=0 ; j<3 ; j++)
{ // avoid round off error when possible
if (normal[j] == 1)
mid[j] = dist;
else if (normal[j] == -1)
mid[j] = -dist;
else
mid[j] = p1[j] + dot*(p2[j]-p1[j]);
}
VectorCopy (mid, f->p[f->numpoints]);
f->numpoints++;
VectorCopy (mid, b->p[b->numpoints]);
b->numpoints++;
}
if (f->numpoints > maxpts || b->numpoints > maxpts)
Error ("ClipWinding: points exceeded estimate");
if (f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING)
Error ("ClipWinding: MAX_POINTS_ON_WINDING");
}
/*
=============
ChopWindingInPlace
=============
*/
void ChopWindingInPlace (winding_t **inout, const Vector &normal, vec_t dist, vec_t epsilon)
{
winding_t *in;
vec_t dists[MAX_POINTS_ON_WINDING+4];
int sides[MAX_POINTS_ON_WINDING+4];
int counts[3];
vec_t dot;
int i, j;
Vector mid = vec3_origin;
winding_t *f;
int maxpts;
in = *inout;
counts[0] = counts[1] = counts[2] = 0;
// determine sides for each point
for (i=0 ; i<in->numpoints ; i++)
{
dot = DotProduct (in->p[i], normal);
dot -= dist;
dists[i] = dot;
if (dot > epsilon)
{
sides[i] = SIDE_FRONT;
}
else if (dot < -epsilon)
{
sides[i] = SIDE_BACK;
}
else
{
sides[i] = SIDE_ON;
}
counts[sides[i]]++;
}
sides[i] = sides[0];
dists[i] = dists[0];
if (!counts[0])
{
FreeWinding (in);
*inout = NULL;
return;
}
if (!counts[1])
return; // inout stays the same
maxpts = in->numpoints+4; // cant use counts[0]+2 because
// of fp grouping errors
f = AllocWinding (maxpts);
for (i=0 ; i<in->numpoints ; i++)
{
Vector& p1 = in->p[i];
if (sides[i] == SIDE_ON)
{
VectorCopy (p1, f->p[f->numpoints]);
f->numpoints++;
continue;
}
if (sides[i] == SIDE_FRONT)
{
VectorCopy (p1, f->p[f->numpoints]);
f->numpoints++;
}
if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i])
continue;
// generate a split point
Vector& p2 = in->p[(i+1)%in->numpoints];
dot = dists[i] / (dists[i]-dists[i+1]);
for (j=0 ; j<3 ; j++)
{ // avoid round off error when possible
if (normal[j] == 1)
mid[j] = dist;
else if (normal[j] == -1)
mid[j] = -dist;
else
mid[j] = p1[j] + dot*(p2[j]-p1[j]);
}
VectorCopy (mid, f->p[f->numpoints]);
f->numpoints++;
}
if (f->numpoints > maxpts)
Error ("ClipWinding: points exceeded estimate");
if (f->numpoints > MAX_POINTS_ON_WINDING)
Error ("ClipWinding: MAX_POINTS_ON_WINDING");
FreeWinding (in);
*inout = f;
}
/*
=================
ChopWinding
Returns the fragment of in that is on the front side
of the cliping plane. The original is freed.
=================
*/
winding_t *ChopWinding (winding_t *in, const Vector &normal, vec_t dist)
{
winding_t *f, *b;
ClipWindingEpsilon (in, normal, dist, ON_EPSILON, &f, &b);
FreeWinding (in);
if (b)
FreeWinding (b);
return f;
}
/*
=================
CheckWinding
=================
*/
void CheckWinding (winding_t *w)
{
int i, j;
vec_t d, edgedist;
Vector dir, edgenormal, facenormal;
vec_t area;
vec_t facedist;
if (w->numpoints < 3)
Error ("CheckWinding: %i points",w->numpoints);
area = WindingArea(w);
if (area < 1)
Error ("CheckWinding: %f area", area);
WindingPlane (w, facenormal, &facedist);
for (i=0 ; i<w->numpoints ; i++)
{
Vector& p1 = w->p[i];
for (j=0 ; j<3 ; j++)
{
if (p1[j] > MAX_COORD_INTEGER || p1[j] < MIN_COORD_INTEGER)
Error ("CheckFace: out of range: %f",p1[j]);
}
j = i+1 == w->numpoints ? 0 : i+1;
// check the point is on the face plane
d = DotProduct (p1, facenormal) - facedist;
if (d < -ON_EPSILON || d > ON_EPSILON)
Error ("CheckWinding: point off plane");
// check the edge isnt degenerate
Vector& p2 = w->p[j];
VectorSubtract (p2, p1, dir);
if (VectorLength (dir) < ON_EPSILON)
Error ("CheckWinding: degenerate edge");
CrossProduct (facenormal, dir, edgenormal);
VectorNormalize (edgenormal);
edgedist = DotProduct (p1, edgenormal);
edgedist += ON_EPSILON;
// all other points must be on front side
for (j=0 ; j<w->numpoints ; j++)
{
if (j == i)
continue;
d = DotProduct (w->p[j], edgenormal);
if (d > edgedist)
Error ("CheckWinding: non-convex");
}
}
}
/*
============
WindingOnPlaneSide
============
*/
int WindingOnPlaneSide (winding_t *w, const Vector &normal, vec_t dist)
{
qboolean front, back;
int i;
vec_t d;
front = false;
back = false;
for (i=0 ; i<w->numpoints ; i++)
{
d = DotProduct (w->p[i], normal) - dist;
if (d < -ON_EPSILON)
{
if (front)
return SIDE_CROSS;
back = true;
continue;
}
if (d > ON_EPSILON)
{
if (back)
return SIDE_CROSS;
front = true;
continue;
}
}
if (back)
return SIDE_BACK;
if (front)
return SIDE_FRONT;
return SIDE_ON;
}
//-----------------------------------------------------------------------------
// Purpose: 2d point inside of winding test (assumes the point resides in the
// winding plane)
//-----------------------------------------------------------------------------
bool PointInWinding( const Vector &pt, winding_t *pWinding )
{
if( !pWinding )
return false;
#if 0
//
// NOTE: this will be a quicker way to calculate this, however I don't
// know the trick off hand (post dot product tests??)
// TODO: look in graphics gems!!!! (cab)
//
Vector edge1, edge2;
for( int ndxPt = 0; ndxPt < pWinding->numpoints; ndxPt++ )
{
edge1 = pWinding->p[ndxPt] - pt;
edge2 = pWinding->p[(ndxPt+1)%pWinding->numpoints] - pt;
VectorNormalize( edge1 );
VectorNormalize( edge2 );
if( edge2.Dot( edge1 ) < 0.0f )
return false;
}
return true;
#else
Vector edge, toPt, cross, testCross;
//
// get the first normal to test
//
toPt = pt - pWinding->p[0];
edge = pWinding->p[1] - pWinding->p[0];
testCross = edge.Cross( toPt );
VectorNormalize( testCross );
for( int ndxPt = 1; ndxPt < pWinding->numpoints; ndxPt++ )
{
toPt = pt - pWinding->p[ndxPt];
edge = pWinding->p[(ndxPt+1)%pWinding->numpoints] - pWinding->p[ndxPt];
cross = edge.Cross( toPt );
VectorNormalize( cross );
if( cross.Dot( testCross ) < 0.0f )
return false;
}
return true;
#endif
}
void TranslateWinding( winding_t *pWinding, const Vector &offset )
{
for ( int i = 0; i < pWinding->numpoints; i++ )
{
pWinding->p[i] += offset;
}
}

View File

@@ -0,0 +1,78 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#ifndef POLYLIB_H
#define POLYLIB_H
#pragma once
#ifndef MATHLIB_H
#include "mathlib/mathlib.h"
#endif
struct winding_t
{
int numpoints;
Vector *p; // variable sized
int maxpoints;
winding_t *next;
};
#define MAX_POINTS_ON_WINDING 64
// you can define on_epsilon in the makefile as tighter
// point on plane side epsilon
// todo: need a world-space epsilon, a lightmap-space epsilon, and a texture space epsilon
// or at least convert from a world-space epsilon to lightmap and texture space epsilons
#ifndef ON_EPSILON
#define ON_EPSILON 0.1
#endif
winding_t *AllocWinding (int points);
vec_t WindingArea (winding_t *w);
void WindingCenter (winding_t *w, Vector &center);
vec_t WindingAreaAndBalancePoint( winding_t *w, Vector &center );
void ClipWindingEpsilon (winding_t *in, const Vector &normal, vec_t dist,
vec_t epsilon, winding_t **front, winding_t **back);
// translates everything by offset, then does the clip, then translates back (to keep precision)
void ClipWindingEpsilon_Offset( winding_t *in, const Vector &normal, vec_t dist, vec_t epsilon, winding_t **front, winding_t **back, const Vector &offset );
void ClassifyWindingEpsilon( winding_t *in, const Vector &normal, vec_t dist,
vec_t epsilon, winding_t **front, winding_t **back, winding_t **on);
void ClassifyWindingEpsilon_Offset( winding_t *in, const Vector &normal, vec_t dist,
vec_t epsilon, winding_t **front, winding_t **back, winding_t **on, const Vector &offset);
winding_t *ChopWinding (winding_t *in, const Vector &normal, vec_t dist);
winding_t *CopyWinding (winding_t *w);
winding_t *ReverseWinding (winding_t *w);
winding_t *BaseWindingForPlane (const Vector &normal, vec_t dist);
void CheckWinding (winding_t *w);
void WindingPlane (winding_t *w, Vector &normal, vec_t *dist);
void RemoveColinearPoints (winding_t *w);
int WindingOnPlaneSide (winding_t *w, const Vector &normal, vec_t dist);
void FreeWinding (winding_t *w);
void WindingBounds (winding_t *w, Vector &mins, Vector &maxs);
void ChopWindingInPlace (winding_t **w, const Vector &normal, vec_t dist, vec_t epsilon);
// frees the original if clipped
bool PointInWinding( Vector const &pt, winding_t *pWinding );
// translates a winding by offset
void TranslateWinding( winding_t *pWinding, const Vector &offset );
void pw(winding_t *w);
#endif // POLYLIB_H

View File

@@ -0,0 +1,42 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#ifndef QFILES_H
#define QFILES_H
#pragma once
//
// qfiles.h: quake file formats
// This file must be identical in the quake and utils directories
//
#include "basetypes.h"
#include "commonmacros.h"
#include "worldsize.h"
#include "bspfile.h"
#define MAX_OSPATH 260
#define MAX_QPATH 64
/*
========================================================================
The .pak files are just a linear collapse of a directory tree
========================================================================
*/
#define IDPAKHEADER (('K'<<24)+('C'<<16)+('A'<<8)+'P')
#endif // QFILES_H

View File

@@ -0,0 +1,103 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "scratchpad_helpers.h"
#include "bspfile.h"
#include "bsplib.h"
void ScratchPad_DrawWinding(
IScratchPad3D *pPad,
int nPoints,
Vector *pPoints,
Vector vColor,
Vector vOffset )
{
for ( int i=0; i < nPoints; i++ )
{
pPad->DrawLine( CSPVert( pPoints[i]+vOffset, vColor ), CSPVert( pPoints[(i+1)%nPoints]+vOffset, vColor ) );
}
}
void ScratchPad_DrawFace( IScratchPad3D *pPad, dface_t *f, int iFaceNumber, const CSPColor &faceColor, const Vector &vOffset )
{
// Draw the face's outline, then put text for its face index on it too.
CUtlVector<Vector> points;
for ( int iEdge = 0; iEdge < f->numedges; iEdge++ )
{
int v;
int se = dsurfedges[f->firstedge + iEdge];
if ( se < 0 )
v = dedges[-se].v[1];
else
v = dedges[se].v[0];
dvertex_t *dv = &dvertexes[v];
points.AddToTail( dv->point );
}
// Draw the outline.
Vector vCenter( 0, 0, 0 );
for ( int iEdge=0; iEdge < points.Count(); iEdge++ )
{
pPad->DrawLine( CSPVert( points[iEdge]+vOffset, faceColor ), CSPVert( points[(iEdge+1)%points.Count()]+vOffset, faceColor ) );
vCenter += points[iEdge];
}
vCenter /= points.Count();
vCenter += vOffset;
// Draw the text.
if ( iFaceNumber != -1 )
{
char str[64];
Q_snprintf( str, sizeof( str ), "%d", iFaceNumber );
CTextParams params;
params.m_bCentered = true;
params.m_bOutline = true;
params.m_flLetterWidth = 2;
params.m_vColor.Init( 1, 0, 0 );
VectorAngles( dplanes[f->planenum].normal, params.m_vAngles );
params.m_bTwoSided = true;
params.m_vPos = vCenter;
pPad->DrawText( str, params );
}
}
void ScratchPad_DrawWorld( IScratchPad3D *pPad, bool bDrawFaceNumbers, const CSPColor &faceColor )
{
bool bAutoFlush = pPad->GetAutoFlush();
pPad->SetAutoFlush( false );
for ( int i=0; i < numleafs; i++ )
{
dleaf_t *l = &dleafs[i];
if ( l->contents & CONTENTS_DETAIL )
continue;
for ( int z=0; z < l->numleaffaces; z++ )
{
int iFace = dleaffaces[l->firstleafface+z];
dface_t *f = &dfaces[iFace];
ScratchPad_DrawFace( pPad, f, bDrawFaceNumbers ? i : -1 );
}
}
pPad->SetAutoFlush( bAutoFlush );
}
void ScratchPad_DrawWorld( bool bDrawFaceNumbers, const CSPColor &faceColor )
{
IScratchPad3D *pPad = ScratchPad3D_Create();
ScratchPad_DrawWorld( pPad, bDrawFaceNumbers );
}

View File

@@ -0,0 +1,25 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef SCRATCHPAD_HELPERS_H
#define SCRATCHPAD_HELPERS_H
#ifdef _WIN32
#pragma once
#endif
#include "iscratchpad3d.h"
#include "bspfile.h"
void ScratchPad_DrawWinding( IScratchPad3D *pPad, int nPoints, Vector *pPoints, Vector vColor, Vector vOffset = Vector(0,0,0) );
void ScratchPad_DrawFace( IScratchPad3D *pPad, dface_t *f, int iFaceNumber = -1, const CSPColor &faceColor=CSPColor(1,1,1,1), const Vector &vOffset=Vector(0,0,0) );
void ScratchPad_DrawWorld( IScratchPad3D *pPad, bool bDrawFaceNumbers, const CSPColor &faceColor=CSPColor(1,1,1,1) );
void ScratchPad_DrawWorld( bool bDrawFaceNumbers, const CSPColor &faceColor=CSPColor(1,1,1,1) );
#endif // SCRATCHPAD_HELPERS_H

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,96 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#ifndef SCRIPLIB_H
#define SCRIPLIB_H
#ifdef _WIN32
#pragma once
#endif
enum ScriptPathMode_t
{
SCRIPT_USE_ABSOLUTE_PATH,
SCRIPT_USE_RELATIVE_PATH
};
// scriplib.h
#define MAXTOKEN 1024
extern char token[MAXTOKEN];
extern char *scriptbuffer,*script_p,*scriptend_p;
extern int grabbed;
extern int scriptline;
extern qboolean endofscript;
// If pathMode is SCRIPT_USE_ABSOLUTE_PATH, then it uses ExpandPath() on the filename before
// trying to open it. Otherwise, it passes the filename straight into the filesystem
// (so you can leave it as a relative path).
void LoadScriptFile (char *filename, ScriptPathMode_t pathMode=SCRIPT_USE_ABSOLUTE_PATH);
void ParseFromMemory (char *buffer, int size);
qboolean GetToken (qboolean crossline);
qboolean GetExprToken (qboolean crossline);
void UnGetToken (void);
qboolean TokenAvailable (void);
qboolean GetTokenizerStatus( char **pFilename, int *pLine );
bool SetCheckSingleCharTokens( bool bCheck );
// SCRIPT_LOADED_CALLBACK:
// Is called after the contents of a file is loaded.
// pFilenameLoaded is the path of a file that got loaded.
// pIncludedFromFileName is the name of the parent file or NULL if loaded because of "LoadScriptFile" toplevel call.
// nIncludeLineNumber is the number of the line in the parent file with $include statement or 0 in case of "LoadScriptFile"
typedef void ( * SCRIPT_LOADED_CALLBACK )( char const *pFilenameLoaded, char const *pIncludedFromFileName, int nIncludeLineNumber );
// SetScriptLoadedCallback:
// Sets the new callback for script loading.
// Returns the previous callback function.
SCRIPT_LOADED_CALLBACK SetScriptLoadedCallback( SCRIPT_LOADED_CALLBACK pfnNewScriptLoadedCallback );
#include "tier1/utlstring.h"
#include "tier1/utlvector.h"
CUtlString SetSingleCharTokenList( const char *pszSingleCharTokenList );
class CUtlBuffer;
enum DiskWriteMode_t
{
WRITE_TO_DISK_NEVER,
WRITE_TO_DISK_ALWAYS,
WRITE_TO_DISK_UPDATE, // file must exist
};
struct fileList_t
{
CUtlString fileName;
time_t timeWrite;
};
class IScriptLib
{
public:
virtual bool ReadFileToBuffer( const char *pSourceName, CUtlBuffer &buffer, bool bText = false, bool bNoOpenFailureWarning = false ) = 0;
virtual bool WriteBufferToFile( const char *pTargetName, CUtlBuffer &buffer, DiskWriteMode_t writeMode ) = 0;
virtual int FindFiles( char* pFileMask, bool bRecurse, CUtlVector<fileList_t> &fileList ) = 0;
virtual char *MakeTemporaryFilename( char const *pchModPath, char *pPath, int pathSize ) = 0;
virtual void DeleteTemporaryFiles( const char *pFileMask ) = 0;
virtual int CompareFileTime( const char *pFilenameA, const char *pFilenameB ) = 0;
virtual bool DoesFileExist( const char *pFilename ) = 0;
};
extern IScriptLib *scriptlib;
#endif // SCRIPLIB_H

View File

@@ -0,0 +1,257 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#define USED
#include <windows.h>
#include "cmdlib.h"
#define NO_THREAD_NAMES
#include "threads.h"
#include "pacifier.h"
#define MAX_THREADS 16
class CRunThreadsData
{
public:
int m_iThread;
void *m_pUserData;
RunThreadsFn m_Fn;
};
CRunThreadsData g_RunThreadsData[MAX_THREADS];
int dispatch;
int workcount;
qboolean pacifier;
qboolean threaded;
bool g_bLowPriorityThreads = false;
HANDLE g_ThreadHandles[MAX_THREADS];
/*
=============
GetThreadWork
=============
*/
int GetThreadWork (void)
{
int r;
ThreadLock ();
if (dispatch == workcount)
{
ThreadUnlock ();
return -1;
}
UpdatePacifier( (float)dispatch / workcount );
r = dispatch;
dispatch++;
ThreadUnlock ();
return r;
}
ThreadWorkerFn workfunction;
void ThreadWorkerFunction( int iThread, void *pUserData )
{
int work;
while (1)
{
work = GetThreadWork ();
if (work == -1)
break;
workfunction( iThread, work );
}
}
void RunThreadsOnIndividual (int workcnt, qboolean showpacifier, ThreadWorkerFn func)
{
if (numthreads == -1)
ThreadSetDefault ();
workfunction = func;
RunThreadsOn (workcnt, showpacifier, ThreadWorkerFunction);
}
/*
===================================================================
WIN32
===================================================================
*/
int numthreads = -1;
CRITICAL_SECTION crit;
static int enter;
class CCritInit
{
public:
CCritInit()
{
InitializeCriticalSection (&crit);
}
} g_CritInit;
void SetLowPriority()
{
SetPriorityClass( GetCurrentProcess(), IDLE_PRIORITY_CLASS );
}
void ThreadSetDefault (void)
{
SYSTEM_INFO info;
if (numthreads == -1) // not set manually
{
GetSystemInfo (&info);
numthreads = info.dwNumberOfProcessors;
if (numthreads < 1 || numthreads > 32)
numthreads = 1;
}
Msg ("%i threads\n", numthreads);
}
void ThreadLock (void)
{
if (!threaded)
return;
EnterCriticalSection (&crit);
if (enter)
Error ("Recursive ThreadLock\n");
enter = 1;
}
void ThreadUnlock (void)
{
if (!threaded)
return;
if (!enter)
Error ("ThreadUnlock without lock\n");
enter = 0;
LeaveCriticalSection (&crit);
}
// This runs in the thread and dispatches a RunThreadsFn call.
DWORD WINAPI InternalRunThreadsFn( LPVOID pParameter )
{
CRunThreadsData *pData = (CRunThreadsData*)pParameter;
pData->m_Fn( pData->m_iThread, pData->m_pUserData );
return 0;
}
void RunThreads_Start( RunThreadsFn fn, void *pUserData, ERunThreadsPriority ePriority )
{
Assert( numthreads > 0 );
threaded = true;
if ( numthreads > MAX_TOOL_THREADS )
numthreads = MAX_TOOL_THREADS;
for ( int i=0; i < numthreads ;i++ )
{
g_RunThreadsData[i].m_iThread = i;
g_RunThreadsData[i].m_pUserData = pUserData;
g_RunThreadsData[i].m_Fn = fn;
DWORD dwDummy;
g_ThreadHandles[i] = CreateThread(
NULL, // LPSECURITY_ATTRIBUTES lpsa,
0, // DWORD cbStack,
InternalRunThreadsFn, // LPTHREAD_START_ROUTINE lpStartAddr,
&g_RunThreadsData[i], // LPVOID lpvThreadParm,
0, // DWORD fdwCreate,
&dwDummy );
if ( ePriority == k_eRunThreadsPriority_UseGlobalState )
{
if( g_bLowPriorityThreads )
SetThreadPriority( g_ThreadHandles[i], THREAD_PRIORITY_LOWEST );
}
else if ( ePriority == k_eRunThreadsPriority_Idle )
{
SetThreadPriority( g_ThreadHandles[i], THREAD_PRIORITY_IDLE );
}
}
}
void RunThreads_End()
{
WaitForMultipleObjects( numthreads, g_ThreadHandles, TRUE, INFINITE );
for ( int i=0; i < numthreads; i++ )
CloseHandle( g_ThreadHandles[i] );
threaded = false;
}
/*
=============
RunThreadsOn
=============
*/
void RunThreadsOn( int workcnt, qboolean showpacifier, RunThreadsFn fn, void *pUserData )
{
int start, end;
start = Plat_FloatTime();
dispatch = 0;
workcount = workcnt;
StartPacifier("");
pacifier = showpacifier;
#ifdef _PROFILE
threaded = false;
(*func)( 0 );
return;
#endif
RunThreads_Start( fn, pUserData );
RunThreads_End();
end = Plat_FloatTime();
if (pacifier)
{
EndPacifier(false);
printf (" (%i)\n", end-start);
}
}

View File

@@ -0,0 +1,65 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#ifndef THREADS_H
#define THREADS_H
#pragma once
// Arrays that are indexed by thread should always be MAX_TOOL_THREADS+1
// large so THREADINDEX_MAIN can be used from the main thread.
#define MAX_TOOL_THREADS 16
#define THREADINDEX_MAIN (MAX_TOOL_THREADS)
extern int numthreads;
// If set to true, then all the threads that are created are low priority.
extern bool g_bLowPriorityThreads;
typedef void (*ThreadWorkerFn)( int iThread, int iWorkItem );
typedef void (*RunThreadsFn)( int iThread, void *pUserData );
enum ERunThreadsPriority
{
k_eRunThreadsPriority_UseGlobalState=0, // Default.. uses g_bLowPriorityThreads to decide what to set the priority to.
k_eRunThreadsPriority_Normal, // Doesn't touch thread priorities.
k_eRunThreadsPriority_Idle // Sets threads to idle priority.
};
// Put the process into an idle priority class so it doesn't hog the UI.
void SetLowPriority();
void ThreadSetDefault (void);
int GetThreadWork (void);
void RunThreadsOnIndividual ( int workcnt, qboolean showpacifier, ThreadWorkerFn fn );
void RunThreadsOn ( int workcnt, qboolean showpacifier, RunThreadsFn fn, void *pUserData=NULL );
// This version doesn't track work items - it just runs your function and waits for it to finish.
void RunThreads_Start( RunThreadsFn fn, void *pUserData, ERunThreadsPriority ePriority=k_eRunThreadsPriority_UseGlobalState );
void RunThreads_End();
void ThreadLock (void);
void ThreadUnlock (void);
#ifndef NO_THREAD_NAMES
#define RunThreadsOn(n,p,f) { if (p) printf("%-20s ", #f ":"); RunThreadsOn(n,p,f); }
#define RunThreadsOnIndividual(n,p,f) { if (p) printf("%-20s ", #f ":"); RunThreadsOnIndividual(n,p,f); }
#endif
#endif // THREADS_H

View File

@@ -0,0 +1,61 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include <windows.h>
#include <dbghelp.h>
#include "tier0/minidump.h"
#include "tools_minidump.h"
static bool g_bToolsWriteFullMinidumps = false;
static ToolsExceptionHandler g_pCustomExceptionHandler = NULL;
// --------------------------------------------------------------------------------- //
// Internal helpers.
// --------------------------------------------------------------------------------- //
static LONG __stdcall ToolsExceptionFilter( struct _EXCEPTION_POINTERS *ExceptionInfo )
{
// Non VMPI workers write a minidump and show a crash dialog like normal.
int iType = MiniDumpNormal;
if ( g_bToolsWriteFullMinidumps )
iType = MiniDumpWithDataSegs | MiniDumpWithIndirectlyReferencedMemory;
WriteMiniDumpUsingExceptionInfo( ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionInfo, (MINIDUMP_TYPE)iType );
return EXCEPTION_CONTINUE_SEARCH;
}
static LONG __stdcall ToolsExceptionFilter_Custom( struct _EXCEPTION_POINTERS *ExceptionInfo )
{
// Run their custom handler.
g_pCustomExceptionHandler( ExceptionInfo->ExceptionRecord->ExceptionCode, ExceptionInfo );
return EXCEPTION_EXECUTE_HANDLER; // (never gets here anyway)
}
// --------------------------------------------------------------------------------- //
// Interface functions.
// --------------------------------------------------------------------------------- //
void EnableFullMinidumps( bool bFull )
{
g_bToolsWriteFullMinidumps = bFull;
}
void SetupDefaultToolsMinidumpHandler()
{
SetUnhandledExceptionFilter( ToolsExceptionFilter );
}
void SetupToolsMinidumpHandler( ToolsExceptionHandler fn )
{
g_pCustomExceptionHandler = fn;
SetUnhandledExceptionFilter( ToolsExceptionFilter_Custom );
}

View File

@@ -0,0 +1,35 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef TOOLS_MINIDUMP_H
#define TOOLS_MINIDUMP_H
#ifdef _WIN32
#pragma once
#endif
// Defaults to false. If true, it'll write larger minidump files with the contents
// of global variables and following pointers from where the crash occurred.
void EnableFullMinidumps( bool bFull );
// This handler catches any crash, writes a minidump, and runs the default system
// crash handler (which usually shows a dialog).
void SetupDefaultToolsMinidumpHandler();
// (Used by VMPI) - you specify your own crash handler.
// Arguments passed to ToolsExceptionHandler
// exceptionCode - exception code
// pvExceptionInfo - on Win32 platform points to "struct _EXCEPTION_POINTERS"
// otherwise NULL
//
typedef void (*ToolsExceptionHandler)( unsigned long exceptionCode, void *pvExceptionInfo );
void SetupToolsMinidumpHandler( ToolsExceptionHandler fn );
#endif // MINIDUMP_H

View File

@@ -0,0 +1,184 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
// C callable material system interface for the utils.
#include "materialsystem/imaterialsystem.h"
#include "materialsystem/imaterial.h"
#include "materialsystem/imaterialvar.h"
#include <cmdlib.h>
#include "utilmatlib.h"
#include "tier0/dbg.h"
#include <windows.h>
#include "filesystem.h"
#include "materialsystem/materialsystem_config.h"
#include "mathlib/Mathlib.h"
void LoadMaterialSystemInterface( CreateInterfaceFn fileSystemFactory )
{
if( g_pMaterialSystem )
return;
// materialsystem.dll should be in the path, it's in bin along with vbsp.
const char *pDllName = "materialsystem.dll";
CSysModule *materialSystemDLLHInst;
materialSystemDLLHInst = g_pFullFileSystem->LoadModule( pDllName );
if( !materialSystemDLLHInst )
{
Error( "Can't load MaterialSystem.dll\n" );
}
CreateInterfaceFn clientFactory = Sys_GetFactory( materialSystemDLLHInst );
if ( clientFactory )
{
g_pMaterialSystem = (IMaterialSystem *)clientFactory( MATERIAL_SYSTEM_INTERFACE_VERSION, NULL );
if ( !g_pMaterialSystem )
{
Error( "Could not get the material system interface from materialsystem.dll (" __FILE__ ")" );
}
}
else
{
Error( "Could not find factory interface in library MaterialSystem.dll" );
}
if (!g_pMaterialSystem->Init( "shaderapiempty.dll", 0, fileSystemFactory ))
{
Error( "Could not start the empty shader (shaderapiempty.dll)!" );
}
}
void InitMaterialSystem( const char *materialBaseDirPath, CreateInterfaceFn fileSystemFactory )
{
LoadMaterialSystemInterface( fileSystemFactory );
MaterialSystem_Config_t config;
g_pMaterialSystem->OverrideConfig( config, false );
}
void ShutdownMaterialSystem( )
{
if ( g_pMaterialSystem )
{
g_pMaterialSystem->Shutdown();
g_pMaterialSystem = NULL;
}
}
MaterialSystemMaterial_t FindMaterial( const char *materialName, bool *pFound, bool bComplain )
{
IMaterial *pMat = g_pMaterialSystem->FindMaterial( materialName, TEXTURE_GROUP_OTHER, bComplain );
MaterialSystemMaterial_t matHandle = pMat;
if ( pFound )
{
*pFound = true;
if ( IsErrorMaterial( pMat ) )
*pFound = false;
}
return matHandle;
}
void GetMaterialDimensions( MaterialSystemMaterial_t materialHandle, int *width, int *height )
{
PreviewImageRetVal_t retVal;
ImageFormat dummyImageFormat;
IMaterial *material = ( IMaterial * )materialHandle;
bool translucent;
retVal = material->GetPreviewImageProperties( width, height, &dummyImageFormat, &translucent );
if (retVal != MATERIAL_PREVIEW_IMAGE_OK )
{
#if 0
if (retVal == MATERIAL_PREVIEW_IMAGE_BAD )
{
Error( "problem getting preview image for %s",
g_pMaterialSystem->GetMaterialName( materialInfo[matID].materialHandle ) );
}
#else
*width = 128;
*height = 128;
#endif
}
}
void GetMaterialReflectivity( MaterialSystemMaterial_t materialHandle, float *reflectivityVect )
{
IMaterial *material = ( IMaterial * )materialHandle;
const IMaterialVar *reflectivityVar;
bool found;
reflectivityVar = material->FindVar( "$reflectivity", &found, false );
if( !found )
{
Vector tmp;
material->GetReflectivity( tmp );
VectorCopy( tmp.Base(), reflectivityVect );
}
else
{
reflectivityVar->GetVecValue( reflectivityVect, 3 );
}
}
int GetMaterialShaderPropertyBool( MaterialSystemMaterial_t materialHandle, int propID )
{
IMaterial *material = ( IMaterial * )materialHandle;
switch( propID )
{
case UTILMATLIB_NEEDS_BUMPED_LIGHTMAPS:
return material->GetPropertyFlag( MATERIAL_PROPERTY_NEEDS_BUMPED_LIGHTMAPS );
case UTILMATLIB_NEEDS_LIGHTMAP:
return material->GetPropertyFlag( MATERIAL_PROPERTY_NEEDS_LIGHTMAP );
default:
Assert( 0 );
return 0;
}
}
int GetMaterialShaderPropertyInt( MaterialSystemMaterial_t materialHandle, int propID )
{
IMaterial *material = ( IMaterial * )materialHandle;
switch( propID )
{
case UTILMATLIB_OPACITY:
if (material->IsTranslucent())
return UTILMATLIB_TRANSLUCENT;
if (material->IsAlphaTested())
return UTILMATLIB_ALPHATEST;
return UTILMATLIB_OPAQUE;
default:
Assert( 0 );
return 0;
}
}
const char *GetMaterialVar( MaterialSystemMaterial_t materialHandle, const char *propertyName )
{
IMaterial *material = ( IMaterial * )materialHandle;
IMaterialVar *var;
bool found;
var = material->FindVar( propertyName, &found, false );
if( found )
{
return var->GetStringValue();
}
else
{
return NULL;
}
}
const char *GetMaterialShaderName( MaterialSystemMaterial_t materialHandle )
{
IMaterial *material = ( IMaterial * )materialHandle;
return material->GetShaderName();
}

View File

@@ -0,0 +1,41 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Workfile: $
// $Date: $
// $NoKeywords: $
//=============================================================================//
#ifndef UTILMATLIB_H
#define UTILMATLIB_H
#ifdef _WIN32
#pragma once
#endif
#define MATERIAL_NOT_FOUND NULL
class IMaterialSystem;
extern IMaterialSystem *g_pMaterialSystem;
typedef void *MaterialSystemMaterial_t;
#define UTILMATLIB_NEEDS_BUMPED_LIGHTMAPS 0
#define UTILMATLIB_NEEDS_LIGHTMAP 1
#define UTILMATLIB_OPACITY 2
enum { UTILMATLIB_ALPHATEST = 0, UTILMATLIB_OPAQUE, UTILMATLIB_TRANSLUCENT };
void InitMaterialSystem( const char *materialBaseDirPath, CreateInterfaceFn fileSystemFactory );
void ShutdownMaterialSystem( );
MaterialSystemMaterial_t FindMaterial( const char *materialName, bool *pFound, bool bComplain = true );
void GetMaterialDimensions( MaterialSystemMaterial_t materialHandle, int *width, int *height );
int GetMaterialShaderPropertyBool( MaterialSystemMaterial_t materialHandle, int propID );
int GetMaterialShaderPropertyInt( MaterialSystemMaterial_t materialHandle, int propID );
const char *GetMaterialVar( MaterialSystemMaterial_t materialHandle, const char *propertyName );
void GetMaterialReflectivity( MaterialSystemMaterial_t materialHandle, float *reflectivityVect );
const char *GetMaterialShaderName( MaterialSystemMaterial_t materialHandle );
#endif // UTILMATLIB_H

View File

@@ -0,0 +1,374 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include <windows.h>
#include <dbghelp.h>
#include "vmpi.h"
#include "cmdlib.h"
#include "vmpi_tools_shared.h"
#include "tier1/strtools.h"
#include "mpi_stats.h"
#include "iphelpers.h"
#include "tier0/minidump.h"
// ----------------------------------------------------------------------------- //
// Globals.
// ----------------------------------------------------------------------------- //
static bool g_bReceivedDirectoryInfo = false; // Have we gotten the qdir info yet?
static bool g_bReceivedDBInfo = false;
static CDBInfo g_DBInfo;
static unsigned long g_JobPrimaryID;
static int g_nDisconnects = 0; // Tracks how many remote processes have disconnected ungracefully.
// ----------------------------------------------------------------------------- //
// Shared dispatch code.
// ----------------------------------------------------------------------------- //
bool SharedDispatch( MessageBuffer *pBuf, int iSource, int iPacketID )
{
char *pInPos = &pBuf->data[2];
switch ( pBuf->data[1] )
{
case VMPI_SUBPACKETID_DIRECTORIES:
{
Q_strncpy( gamedir, pInPos, sizeof( gamedir ) );
pInPos += strlen( pInPos ) + 1;
Q_strncpy( qdir, pInPos, sizeof( qdir ) );
g_bReceivedDirectoryInfo = true;
}
return true;
case VMPI_SUBPACKETID_DBINFO:
{
g_DBInfo = *((CDBInfo*)pInPos);
pInPos += sizeof( CDBInfo );
g_JobPrimaryID = *((unsigned long*)pInPos);
g_bReceivedDBInfo = true;
}
return true;
case VMPI_SUBPACKETID_CRASH:
{
char const chCrashInfoType = *pInPos;
pInPos += 2;
switch ( chCrashInfoType )
{
case 't':
Warning( "\nWorker '%s' dead: %s\n", VMPI_GetMachineName( iSource ), pInPos );
break;
case 'f':
{
int iFileSize = * reinterpret_cast< int const * >( pInPos );
pInPos += sizeof( iFileSize );
// Temp folder
char const *szFolder = NULL;
if ( !szFolder ) szFolder = getenv( "TEMP" );
if ( !szFolder ) szFolder = getenv( "TMP" );
if ( !szFolder ) szFolder = "c:";
// Base module name
char chModuleName[_MAX_PATH], *pModuleName = chModuleName;
::GetModuleFileName( NULL, chModuleName, sizeof( chModuleName ) / sizeof( chModuleName[0] ) );
if ( char *pch = strrchr( chModuleName, '.' ) )
*pch = 0;
if ( char *pch = strrchr( chModuleName, '\\' ) )
*pch = 0, pModuleName = pch + 1;
// Current time
time_t currTime = ::time( NULL );
struct tm * pTime = ::localtime( &currTime );
// Number of minidumps this run
static int s_numMiniDumps = 0;
++ s_numMiniDumps;
// Prepare the filename
char chSaveFileName[ 2 * _MAX_PATH ] = { 0 };
sprintf( chSaveFileName, "%s\\vmpi_%s_on_%s_%d%.2d%2d%.2d%.2d%.2d_%d.mdmp",
szFolder,
pModuleName,
VMPI_GetMachineName( iSource ),
pTime->tm_year + 1900, /* Year less 2000 */
pTime->tm_mon + 1, /* month (0 - 11 : 0 = January) */
pTime->tm_mday, /* day of month (1 - 31) */
pTime->tm_hour, /* hour (0 - 23) */
pTime->tm_min, /* minutes (0 - 59) */
pTime->tm_sec, /* seconds (0 - 59) */
s_numMiniDumps
);
if ( FILE *fDump = fopen( chSaveFileName, "wb" ) )
{
fwrite( pInPos, 1, iFileSize, fDump );
fclose( fDump );
Warning( "\nSaved worker crash minidump '%s', size %d byte(s).\n",
chSaveFileName, iFileSize );
}
else
{
Warning( "\nReceived worker crash minidump size %d byte(s), failed to save.\n", iFileSize );
}
}
break;
}
}
return true;
}
return false;
}
CDispatchReg g_SharedDispatchReg( VMPI_SHARED_PACKET_ID, SharedDispatch );
// ----------------------------------------------------------------------------- //
// Module interfaces.
// ----------------------------------------------------------------------------- //
void SendQDirInfo()
{
char cPacketID[2] = { VMPI_SHARED_PACKET_ID, VMPI_SUBPACKETID_DIRECTORIES };
MessageBuffer mb;
mb.write( cPacketID, 2 );
mb.write( gamedir, strlen( gamedir ) + 1 );
mb.write( qdir, strlen( qdir ) + 1 );
VMPI_SendData( mb.data, mb.getLen(), VMPI_PERSISTENT );
}
void RecvQDirInfo()
{
while ( !g_bReceivedDirectoryInfo )
VMPI_DispatchNextMessage();
}
void SendDBInfo( const CDBInfo *pInfo, unsigned long jobPrimaryID )
{
char cPacketInfo[2] = { VMPI_SHARED_PACKET_ID, VMPI_SUBPACKETID_DBINFO };
const void *pChunks[] = { cPacketInfo, pInfo, &jobPrimaryID };
int chunkLengths[] = { 2, sizeof( CDBInfo ), sizeof( jobPrimaryID ) };
VMPI_SendChunks( pChunks, chunkLengths, ARRAYSIZE( pChunks ), VMPI_PERSISTENT );
}
void RecvDBInfo( CDBInfo *pInfo, unsigned long *pJobPrimaryID )
{
while ( !g_bReceivedDBInfo )
VMPI_DispatchNextMessage();
*pInfo = g_DBInfo;
*pJobPrimaryID = g_JobPrimaryID;
}
// If the file is successfully opened, read and sent returns the size of the file in bytes
// otherwise returns 0 and nothing is sent
int VMPI_SendFileChunk( const void *pvChunkPrefix, int lenPrefix, tchar const *ptchFileName )
{
HANDLE hFile = NULL;
HANDLE hMapping = NULL;
void const *pvMappedData = NULL;
int iResult = 0;
hFile = ::CreateFile( ptchFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL );
if ( !hFile || ( hFile == INVALID_HANDLE_VALUE ) )
goto done;
hMapping = ::CreateFileMapping( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
if ( !hMapping || ( hMapping == INVALID_HANDLE_VALUE ) )
goto done;
pvMappedData = ::MapViewOfFile( hMapping, FILE_MAP_READ, 0, 0, 0 );
if ( !pvMappedData )
goto done;
int iMappedFileSize = ::GetFileSize( hFile, NULL );
if ( INVALID_FILE_SIZE == iMappedFileSize )
goto done;
// Send the data over VMPI
if ( VMPI_Send3Chunks(
pvChunkPrefix, lenPrefix,
&iMappedFileSize, sizeof( iMappedFileSize ),
pvMappedData, iMappedFileSize,
VMPI_MASTER_ID ) )
iResult = iMappedFileSize;
// Fall-through for cleanup code to execute
done:
if ( pvMappedData )
::UnmapViewOfFile( pvMappedData );
if ( hMapping && ( hMapping != INVALID_HANDLE_VALUE ) )
::CloseHandle( hMapping );
if ( hFile && ( hFile != INVALID_HANDLE_VALUE ) )
::CloseHandle( hFile );
return iResult;
}
void VMPI_HandleCrash( const char *pMessage, void *pvExceptionInfo, bool bAssert )
{
static LONG crashHandlerCount = 0;
if ( InterlockedIncrement( &crashHandlerCount ) == 1 )
{
Msg( "\nFAILURE: '%s' (assert: %d)\n", pMessage, bAssert );
// Send a message to the master.
char crashMsg[4] = { VMPI_SHARED_PACKET_ID, VMPI_SUBPACKETID_CRASH, 't', ':' };
VMPI_Send2Chunks(
crashMsg,
sizeof( crashMsg ),
pMessage,
strlen( pMessage ) + 1,
VMPI_MASTER_ID );
// Now attempt to create a minidump with the given exception information
if ( pvExceptionInfo )
{
struct _EXCEPTION_POINTERS *pvExPointers = ( struct _EXCEPTION_POINTERS * ) pvExceptionInfo;
tchar tchMinidumpFileName[_MAX_PATH] = { 0 };
bool bSucceededWritingMinidump = WriteMiniDumpUsingExceptionInfo(
pvExPointers->ExceptionRecord->ExceptionCode,
pvExPointers,
( MINIDUMP_TYPE )( MiniDumpWithDataSegs | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithProcessThreadData ),
// ( MINIDUMP_TYPE )( MiniDumpWithDataSegs | MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithProcessThreadData | MiniDumpWithPrivateReadWriteMemory ),
// ( MINIDUMP_TYPE )( MiniDumpNormal ),
tchMinidumpFileName );
if ( bSucceededWritingMinidump )
{
crashMsg[2] = 'f';
VMPI_SendFileChunk( crashMsg, sizeof( crashMsg ), tchMinidumpFileName );
::DeleteFile( tchMinidumpFileName );
}
}
// Let the messages go out.
Sleep( 500 );
}
InterlockedDecrement( &crashHandlerCount );
}
// This is called if we crash inside our crash handler. It just terminates the process immediately.
LONG __stdcall VMPI_SecondExceptionFilter( struct _EXCEPTION_POINTERS *ExceptionInfo )
{
TerminateProcess( GetCurrentProcess(), 2 );
return EXCEPTION_EXECUTE_HANDLER; // (never gets here anyway)
}
void VMPI_ExceptionFilter( unsigned long uCode, void *pvExceptionInfo )
{
// This is called if we crash inside our crash handler. It just terminates the process immediately.
SetUnhandledExceptionFilter( VMPI_SecondExceptionFilter );
//DWORD code = ExceptionInfo->ExceptionRecord->ExceptionCode;
#define ERR_RECORD( name ) { name, #name }
struct
{
int code;
char *pReason;
} errors[] =
{
ERR_RECORD( EXCEPTION_ACCESS_VIOLATION ),
ERR_RECORD( EXCEPTION_ARRAY_BOUNDS_EXCEEDED ),
ERR_RECORD( EXCEPTION_BREAKPOINT ),
ERR_RECORD( EXCEPTION_DATATYPE_MISALIGNMENT ),
ERR_RECORD( EXCEPTION_FLT_DENORMAL_OPERAND ),
ERR_RECORD( EXCEPTION_FLT_DIVIDE_BY_ZERO ),
ERR_RECORD( EXCEPTION_FLT_INEXACT_RESULT ),
ERR_RECORD( EXCEPTION_FLT_INVALID_OPERATION ),
ERR_RECORD( EXCEPTION_FLT_OVERFLOW ),
ERR_RECORD( EXCEPTION_FLT_STACK_CHECK ),
ERR_RECORD( EXCEPTION_FLT_UNDERFLOW ),
ERR_RECORD( EXCEPTION_ILLEGAL_INSTRUCTION ),
ERR_RECORD( EXCEPTION_IN_PAGE_ERROR ),
ERR_RECORD( EXCEPTION_INT_DIVIDE_BY_ZERO ),
ERR_RECORD( EXCEPTION_INT_OVERFLOW ),
ERR_RECORD( EXCEPTION_INVALID_DISPOSITION ),
ERR_RECORD( EXCEPTION_NONCONTINUABLE_EXCEPTION ),
ERR_RECORD( EXCEPTION_PRIV_INSTRUCTION ),
ERR_RECORD( EXCEPTION_SINGLE_STEP ),
ERR_RECORD( EXCEPTION_STACK_OVERFLOW ),
ERR_RECORD( EXCEPTION_ACCESS_VIOLATION ),
};
int nErrors = sizeof( errors ) / sizeof( errors[0] );
int i=0;
char *pchReason = NULL;
char chUnknownBuffer[32];
for ( i; ( i < nErrors ) && !pchReason; i++ )
{
if ( errors[i].code == uCode )
pchReason = errors[i].pReason;
}
if ( i == nErrors )
{
sprintf( chUnknownBuffer, "Error code 0x%08X", uCode );
pchReason = chUnknownBuffer;
}
VMPI_HandleCrash( pchReason, pvExceptionInfo, true );
TerminateProcess( GetCurrentProcess(), 1 );
}
void HandleMPIDisconnect( int procID, const char *pReason )
{
int nLiveWorkers = VMPI_GetCurrentNumberOfConnections() - g_nDisconnects - 1;
// We ran into the size limit before and it wasn't readily apparent that the size limit had
// been breached, so make sure to show errors about invalid packet sizes..
bool bOldSuppress = g_bSuppressPrintfOutput;
g_bSuppressPrintfOutput = ( Q_stristr( pReason, "invalid packet size" ) == 0 );
Warning( "\n\n--- WARNING: lost connection to '%s' (%s).\n", VMPI_GetMachineName( procID ), pReason );
if ( g_bMPIMaster )
{
Warning( "%d workers remain.\n\n", nLiveWorkers );
++g_nDisconnects;
/*
if ( VMPI_GetCurrentNumberOfConnections() - g_nDisconnects <= 1 )
{
Error( "All machines disconnected!" );
}
*/
}
else
{
VMPI_HandleAutoRestart();
Error( "Worker quitting." );
}
g_bSuppressPrintfOutput = bOldSuppress;
}

View File

@@ -0,0 +1,45 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef VMPI_TOOLS_SHARED_H
#define VMPI_TOOLS_SHARED_H
#ifdef _WIN32
#pragma once
#endif
// Packet IDs.
#define VMPI_SUBPACKETID_DIRECTORIES 0 // qdir directories.
#define VMPI_SUBPACKETID_DBINFO 1 // MySQL database info.
#define VMPI_SUBPACKETID_CRASH 3 // A worker saying it crashed.
#define VMPI_SUBPACKETID_MULTICAST_ADDR 4 // Filesystem multicast address.
class CDBInfo;
class CIPAddr;
// Send/receive the qdir info.
void SendQDirInfo();
void RecvQDirInfo();
void SendDBInfo( const CDBInfo *pInfo, unsigned long jobPrimaryID );
void RecvDBInfo( CDBInfo *pInfo, unsigned long *pJobPrimaryID );
void SendMulticastIP( const CIPAddr *pAddr );
void RecvMulticastIP( CIPAddr *pAddr );
void VMPI_HandleCrash( const char *pMessage, void *pvExceptionInfo, bool bAssert );
// Call this from an exception handler (set by SetUnhandledExceptionHandler).
// uCode = ExceptionInfo->ExceptionRecord->ExceptionCode.
// pvExceptionInfo = ExceptionInfo
void VMPI_ExceptionFilter( unsigned long uCode, void *pvExceptionInfo );
void HandleMPIDisconnect( int procID, const char *pReason );
#endif // VMPI_TOOLS_SHARED_H

View File

@@ -0,0 +1,334 @@
//========= Copyright © 1996-2005, Valve LLC, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// wad2lib.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
//#include <sys/file.h>
#include <stdarg.h>
#ifdef NeXT
#include <libc.h>
#endif
#include "cmdlib.h"
#include "wadlib.h"
#include "commonmacros.h"
/*
============================================================================
WAD READING
============================================================================
*/
lumpinfo_t *lumpinfo; // location of each lump on disk
int numlumps;
wadinfo_t header;
FILE *wadhandle;
/*
====================
W_OpenWad
====================
*/
void W_OpenWad (char *filename)
{
lumpinfo_t *lump_p;
unsigned i;
int length;
//
// open the file and add to directory
//
wadhandle = SafeOpenRead (filename);
SafeRead (wadhandle, &header, sizeof(header));
if (!STRING_MATCHES_ID(header.identification,WAD_ID))
Error ("Wad file %s doesn't have %s identifier\n",filename, WAD_IDNAME);
header.numlumps = LittleLong(header.numlumps);
header.infotableofs = LittleLong(header.infotableofs);
numlumps = header.numlumps;
length = numlumps*sizeof(lumpinfo_t);
lumpinfo = malloc (length);
lump_p = lumpinfo;
fseek (wadhandle, header.infotableofs, SEEK_SET);
SafeRead (wadhandle, lumpinfo, length);
//
// Fill in lumpinfo
//
for (i=0 ; i<numlumps ; i++,lump_p++)
{
lump_p->filepos = LittleLong(lump_p->filepos);
lump_p->size = LittleLong(lump_p->size);
}
}
void CleanupName (char *in, char *out)
{
int i;
for (i=0 ; i<sizeof( ((lumpinfo_t *)0)->name ) ; i++ )
{
if (!in[i])
break;
out[i] = toupper(in[i]);
}
for ( ; i<sizeof( ((lumpinfo_t *)0)->name ); i++ )
out[i] = 0;
}
/*
====================
W_CheckNumForName
Returns -1 if name not found
====================
*/
int W_CheckNumForName (char *name)
{
char cleanname[TEXTURE_NAME_LENGTH];
int v1,v2, v3, v4;
int i;
lumpinfo_t *lump_p;
CleanupName (name, cleanname);
// make the name into four integers for easy compares
v1 = *(int *)cleanname;
v2 = *(int *)&cleanname[4];
v3 = *(int *)&cleanname[8];
v4 = *(int *)&cleanname[12];
// find it
lump_p = lumpinfo;
for (i=0 ; i<numlumps ; i++, lump_p++)
{
if ( *(int *)lump_p->name == v1
&& *(int *)&lump_p->name[4] == v2
&& *(int *)&lump_p->name[8] == v3
&& *(int *)&lump_p->name[12] == v4
&& !strcmp( lump_p->name, cleanname ) )
return i;
}
return -1;
}
/*
====================
W_GetNumForName
Calls W_CheckNumForName, but bombs out if not found
====================
*/
int W_GetNumForName (char *name)
{
int i;
i = W_CheckNumForName (name);
if (i != -1)
return i;
Error ("W_GetNumForName: %s not found!",name);
return -1;
}
/*
====================
W_LumpLength
Returns the buffer size needed to load the given lump
====================
*/
int W_LumpLength (int lump)
{
if (lump >= numlumps)
Error ("W_LumpLength: %i >= numlumps",lump);
return lumpinfo[lump].size;
}
/*
====================
W_ReadLumpNum
Loads the lump into the given buffer, which must be >= W_LumpLength()
====================
*/
void W_ReadLumpNum (int lump, void *dest)
{
lumpinfo_t *l;
if (lump >= numlumps)
Error ("W_ReadLump: %i >= numlumps",lump);
l = lumpinfo+lump;
fseek (wadhandle, l->filepos, SEEK_SET);
SafeRead (wadhandle, dest, l->size);
}
/*
====================
W_LoadLumpNum
====================
*/
void *W_LoadLumpNum (int lump)
{
void *buf;
if ((unsigned)lump >= numlumps)
Error ("W_CacheLumpNum: %i >= numlumps",lump);
buf = malloc (W_LumpLength (lump));
W_ReadLumpNum (lump, buf);
return buf;
}
/*
====================
W_LoadLumpName
====================
*/
void *W_LoadLumpName (char *name)
{
return W_LoadLumpNum (W_GetNumForName(name));
}
/*
===============================================================================
WAD CREATION
===============================================================================
*/
FILE *outwad;
lumpinfo_t outinfo[4096];
int outlumps;
short (*wadshort) (short l);
int (*wadlong) (int l);
/*
===============
NewWad
===============
*/
void NewWad (char *pathname, qboolean bigendien)
{
outwad = SafeOpenWrite (pathname);
fseek (outwad, sizeof(wadinfo_t), SEEK_SET);
memset (outinfo, 0, sizeof(outinfo));
if (bigendien)
{
wadshort = BigShort;
wadlong = BigLong;
}
else
{
wadshort = LittleShort;
wadlong = LittleLong;
}
outlumps = 0;
}
/*
===============
AddLump
===============
*/
void AddLump (char *name, void *buffer, int length, int type, int compress)
{
lumpinfo_t *info;
int ofs;
info = &outinfo[outlumps];
outlumps++;
memset (info,0,sizeof(info));
strcpy (info->name, name);
Q_strupr (info->name);
ofs = ftell(outwad);
info->filepos = wadlong(ofs);
info->size = info->disksize = wadlong(length);
info->type = type;
info->compression = compress;
// FIXME: do compression
SafeWrite (outwad, buffer, length);
}
/*
===============
WriteWad
===============
*/
void WriteWad (int wad3)
{
wadinfo_t header;
int ofs;
// write the lumpingo
ofs = ftell(outwad);
SafeWrite (outwad, outinfo, outlumps*sizeof(lumpinfo_t) );
// write the header
// a program will be able to tell the ednieness of a wad by the id
ID_TO_STRING( WAD_ID, header.identification );
header.numlumps = wadlong(outlumps);
header.infotableofs = wadlong(ofs);
fseek (outwad, 0, SEEK_SET);
SafeWrite (outwad, &header, sizeof(header));
fclose (outwad);
}

View File

@@ -0,0 +1,46 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// wadlib.h
//
// wad reading
//
#define CMP_NONE 0
#define CMP_LZSS 1
#define TYP_NONE 0
#define TYP_LABEL 1
#define TYP_LUMPY 64 // 64 + grab command number
#ifndef WADTYPES_H
#include "wadtypes.h"
#endif
extern lumpinfo_t *lumpinfo; // location of each lump on disk
extern int numlumps;
extern wadinfo_t header;
void W_OpenWad (char *filename);
int W_CheckNumForName (char *name);
int W_GetNumForName (char *name);
int W_LumpLength (int lump);
void W_ReadLumpNum (int lump, void *dest);
void *W_LoadLumpNum (int lump);
void *W_LoadLumpName (char *name);
void CleanupName (char *in, char *out);
//
// wad creation
//
void NewWad (char *pathname, qboolean bigendien);
void AddLump (char *name, void *buffer, int length, int type, int compress);
void WriteWad (int wad3);

View File

@@ -0,0 +1,21 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// GLOS.H
//
// This is an OS specific header file
#include <windows.h>
// disable data conversion warnings
#pragma warning(disable : 4244) // MIPS
#pragma warning(disable : 4136) // X86
#pragma warning(disable : 4051) // ALPHA

View File

@@ -0,0 +1,250 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>Glview</ProjectName>
<ProjectGuid>{DC76828F-1DD4-7E83-371E-EA4058FEE050}</ProjectGuid>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>glview</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>glview</TargetName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PostBuildEventUseInBuild>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PostBuildEventUseInBuild>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 glview.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;..\common</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_ITERATOR_DEBUGGING=0;WIN32;_WIN32;_DEBUG;DEBUG;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;PROTECTED_THINGS_DISABLE;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\glview;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies);glu32.lib;opengl32.lib;odbc32.lib;odbccp32.lib;winmm.lib</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\glview.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmt</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/glview.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 glview.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP /d2Zi+</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;..\common</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;PROTECTED_THINGS_DISABLE;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\glview;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /DYNAMICBASE /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies);glu32.lib;opengl32.lib;odbc32.lib;odbccp32.lib;winmm.lib</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\glview.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmtd</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/glview.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemGroup>
<Library Include="..\..\lib\public\mathlib.lib" />
<Library Include="..\..\lib\public\tier0.lib" />
<Library Include="..\..\lib\public\tier1.lib" />
<Library Include="..\..\lib\public\tier2.lib" />
<Library Include="..\..\lib\public\vstdlib.lib" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\cmdlib.h" />
<ClInclude Include="glos.h" />
<ClInclude Include="..\..\public\mathlib\mathlib.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="glview.cpp" />
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="..\common\cmdlib.cpp" />
<ClCompile Include="..\..\public\filesystem_helpers.cpp" />
<ClCompile Include="..\..\public\filesystem_init.cpp" />
<ClCompile Include="..\common\filesystem_tools.cpp" />
<ClCompile Include="..\common\physdll.cpp" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)\%(Filename).obj</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)\%(Filename).obj</Outputs>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,77 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{1680C80B-FF1E-EA4D-9817-CC12254F2E40}</UniqueIdentifier>
</Filter>
<Filter Include="Link Libraries">
<UniqueIdentifier>{C5D73B3A-C648-896C-B7CE-F174808E5BA5}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{BA03E055-4FA2-FCE3-8A1C-D348547D379C}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files\common files">
<UniqueIdentifier>{66CEFED7-D9FA-AC06-065F-BBA238DD0568}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<Library Include="..\..\lib\public\mathlib.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier0.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier1.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier2.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\vstdlib.lib">
<Filter>Link Libraries</Filter>
</Library>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\cmdlib.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="glos.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\mathlib.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="glview.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\common\cmdlib.cpp">
<Filter>Source Files\common files</Filter>
</ClCompile>
<ClCompile Include="..\..\public\filesystem_helpers.cpp">
<Filter>Source Files\common files</Filter>
</ClCompile>
<ClCompile Include="..\..\public\filesystem_init.cpp">
<Filter>Source Files\common files</Filter>
</ClCompile>
<ClCompile Include="..\common\filesystem_tools.cpp">
<Filter>Source Files\common files</Filter>
</ClCompile>
<ClCompile Include="..\common\physdll.cpp">
<Filter>Source Files\common files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Filter>Source Files</Filter>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,241 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>Height2normal</ProjectName>
<ProjectGuid>{129A563E-9F48-79D9-E0C5-EE2DAF7FEAB7}</ProjectGuid>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>height2normal</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>height2normal</TargetName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PostBuildEventUseInBuild>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PostBuildEventUseInBuild>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 height2normal.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;..\common</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_ITERATOR_DEBUGGING=0;_DEBUG;_WIN32;_CONSOLE;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\height2normal;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\height2normal.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmt</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Console</SubSystem>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/height2normal.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 height2normal.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP /d2Zi+</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;..\common</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_ITERATOR_DEBUGGING=0;_DEBUG;_WIN32;_CONSOLE;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\height2normal;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /DYNAMICBASE /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\height2normal.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmtd</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/height2normal.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemGroup>
<Library Include="..\..\lib\public\bitmap.lib" />
<Library Include="..\..\lib\public\mathlib.lib" />
<Library Include="..\..\lib\public\tier0.lib" />
<Library Include="..\..\lib\public\tier1.lib" />
<Library Include="..\..\lib\public\tier2.lib" />
<Library Include="..\..\lib\public\vstdlib.lib" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\public\tier1\interface.h" />
<ClInclude Include="..\..\public\tier1\utlbuffer.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="height2normal.cpp" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)\%(Filename).obj</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)\%(Filename).obj</Outputs>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,56 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{1680C80B-FF1E-EA4D-9817-CC12254F2E40}</UniqueIdentifier>
</Filter>
<Filter Include="Link Libraries">
<UniqueIdentifier>{C5D73B3A-C648-896C-B7CE-F174808E5BA5}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{BA03E055-4FA2-FCE3-8A1C-D348547D379C}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<Library Include="..\..\lib\public\bitmap.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\mathlib.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier0.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier1.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier2.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\vstdlib.lib">
<Filter>Link Libraries</Filter>
</Library>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\public\tier1\interface.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlbuffer.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="height2normal.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Filter>Source Files</Filter>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,343 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#include <stdio.h>
#include <stdlib.h>
#include <direct.h>
#include "bitmap/imageformat.h"
#include "tier1/strtools.h"
#include "mathlib/mathlib.h"
#include "bitmap/TGAWriter.h"
#include "bitmap/TGALoader.h"
#include <math.h>
#include <conio.h>
#include "tier1/utlbuffer.h"
#include "tier2/tier2.h"
#include "filesystem.h"
static bool g_NoPause = false;
static bool g_Quiet = false;
static void Pause( void )
{
if( !g_NoPause )
{
printf( "Hit a key to continue\n" );
getch();
}
}
static bool ImageRGBA8888HasAlpha( unsigned char *pImage, int numTexels )
{
int i;
for( i = 0; i < numTexels; i++ )
{
if( pImage[i*4+3] != 255 )
{
return true;
}
}
return false;
}
static bool GetKeyValueFromBuffer( CUtlBuffer &buf, char **key, char **val )
{
char stringBuf[2048];
while( buf.IsValid() )
{
buf.GetLine( stringBuf, sizeof(stringBuf) );
char *scan = stringBuf;
// search for the first quote for the key.
while( 1 )
{
if( *scan == '\"' )
{
*key = ++scan;
break;
}
if( *scan == '#' )
{
goto next_line; // comment
}
if( *scan == '\0' )
{
goto next_line; // end of line.
}
scan++;
}
// read the key until another quote.
while( 1 )
{
if( *scan == '\"' )
{
*scan = '\0';
scan++;
break;
}
if( *scan == '\0' )
{
goto next_line;
}
scan++;
}
// search for the first quote for the value.
while( 1 )
{
if( *scan == '\"' )
{
*val = ++scan;
break;
}
if( *scan == '#' )
{
goto next_line; // comment
}
if( *scan == '\0' )
{
goto next_line; // end of line.
}
scan++;
}
// read the value until another quote.
while( 1 )
{
if( *scan == '\"' )
{
*scan = '\0';
scan++;
// got a key and a value, so get the hell out of here.
return true;
}
if( *scan == '\0' )
{
goto next_line;
}
scan++;
}
next_line:
;
}
return false;
}
static void LoadConfigFile( const char *pFileName, float *bumpScale, int *startFrame, int *endFrame )
{
CUtlBuffer buf( 0, 0, CUtlBuffer::TEXT_BUFFER );
if ( !g_pFullFileSystem->ReadFile( pFileName, NULL, buf ) )
{
fprintf( stderr, "Can't open: %s\n", pFileName );
Pause();
exit( -1 );
}
char *key = NULL;
char *val = NULL;
while( GetKeyValueFromBuffer( buf, &key, &val ) )
{
if( stricmp( key, "bumpscale" ) == 0 )
{
*bumpScale = atof( val );
}
if( stricmp( key, "startframe" ) == 0 )
{
*startFrame = atoi( val );
}
else if( stricmp( key, "endframe" ) == 0 )
{
*endFrame = atoi( val );
}
}
}
static void Usage()
{
fprintf( stderr, "Usage: height2normal [-nopause] [-quiet] tex1_normal.txt tex2_normal.txt . . .\n" );
fprintf( stderr, "-quiet : don't print anything out, don't pause for input\n" );
fprintf( stderr, "-nopause : don't pause for input\n" );
Pause();
exit( -1 );
}
void ProcessFiles( const char *pNormalFileNameWithoutExtension,
int startFrame, int endFrame,
float bumpScale )
{
static char heightTGAFileName[1024];
static char normalTGAFileName[1024];
static char buf[1024];
bool animated = !( startFrame == -1 || endFrame == -1 );
int numFrames = endFrame - startFrame + 1;
int frameID;
for( frameID = 0; frameID < numFrames; frameID++ )
{
if( animated )
{
sprintf( normalTGAFileName, "%s%03d.tga", pNormalFileNameWithoutExtension, frameID + startFrame );
}
else
{
sprintf( normalTGAFileName, "%s.tga", pNormalFileNameWithoutExtension );
}
if( !Q_stristr( pNormalFileNameWithoutExtension, "_normal" ) )
{
fprintf( stderr, "ERROR: config file name must end in _normal.txt\n" );
return;
}
strcpy( buf, pNormalFileNameWithoutExtension );
// Strip '_normal' off the end because we're looking for '_height'
char *pcUnderscore = Q_stristr( buf, "_normal" );
*pcUnderscore = NULL;
if( animated )
{
sprintf( heightTGAFileName, "%s_height%03d.tga", buf, frameID + startFrame );
}
else
{
sprintf( heightTGAFileName, "%s_height.tga", buf );
}
enum ImageFormat imageFormat;
int width, height;
float sourceGamma;
CUtlBuffer buf;
if ( !g_pFullFileSystem->ReadFile( heightTGAFileName, NULL, buf ) )
{
fprintf( stderr, "%s not found\n", heightTGAFileName );
return;
}
if ( !TGALoader::GetInfo( buf, &width, &height, &imageFormat, &sourceGamma ) )
{
fprintf( stderr, "error in %s\n", heightTGAFileName );
return;
}
int memRequired = ImageLoader::GetMemRequired( width, height, 1, IMAGE_FORMAT_IA88, false );
unsigned char *pImageIA88 = new unsigned char[memRequired];
buf.SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
TGALoader::Load( pImageIA88, buf, width, height, IMAGE_FORMAT_IA88, sourceGamma, false );
memRequired = ImageLoader::GetMemRequired( width, height, 1, IMAGE_FORMAT_RGBA8888, false );
unsigned char *pImageRGBA8888 = new unsigned char[memRequired];
ImageLoader::ConvertIA88ImageToNormalMapRGBA8888( pImageIA88, width, height, pImageRGBA8888, bumpScale );
CUtlBuffer normalBuf;
ImageLoader::NormalizeNormalMapRGBA8888( pImageRGBA8888, width * height );
if( ImageRGBA8888HasAlpha( pImageRGBA8888, width * height ) )
{
TGAWriter::WriteToBuffer( pImageRGBA8888, normalBuf, width, height, IMAGE_FORMAT_RGBA8888, IMAGE_FORMAT_RGBA8888 );
}
else
{
memRequired = ImageLoader::GetMemRequired( width, height, 1, IMAGE_FORMAT_RGB888, false );
unsigned char *pImageRGB888 = new unsigned char[memRequired];
ImageLoader::ConvertImageFormat( pImageRGBA8888, IMAGE_FORMAT_RGBA8888,
pImageRGB888, IMAGE_FORMAT_RGB888, width, height, 0, 0 );
TGAWriter::WriteToBuffer( pImageRGB888, normalBuf, width, height, IMAGE_FORMAT_RGB888, IMAGE_FORMAT_RGB888 );
delete [] pImageRGB888;
}
if ( !g_pFullFileSystem->WriteFile( normalTGAFileName, NULL, normalBuf ) )
{
fprintf( stderr, "unable to write %s\n", normalTGAFileName );
return;
}
delete [] pImageIA88;
delete [] pImageRGBA8888;
}
}
int main( int argc, char **argv )
{
if( argc < 2 )
{
Usage();
}
MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f );
InitDefaultFileSystem();
int i = 1;
while( i < argc )
{
if( stricmp( argv[i], "-quiet" ) == 0 )
{
i++;
g_Quiet = true;
g_NoPause = true; // no point in pausing if we aren't going to print anything out.
}
if( stricmp( argv[i], "-nopause" ) == 0 )
{
i++;
g_NoPause = true;
}
else
{
break;
}
}
char pCurrentDirectory[MAX_PATH];
if ( _getcwd( pCurrentDirectory, sizeof(pCurrentDirectory) ) == NULL )
{
fprintf( stderr, "Unable to get the current directory\n" );
return -1;
}
Q_FixSlashes( pCurrentDirectory );
Q_StripTrailingSlash( pCurrentDirectory );
for( ; i < argc; i++ )
{
static char normalFileNameWithoutExtension[1024];
char *pFileName;
if ( !Q_IsAbsolutePath( argv[i] ) )
{
Q_snprintf( normalFileNameWithoutExtension, sizeof(normalFileNameWithoutExtension), "%s\\%s", pCurrentDirectory, argv[i] );
pFileName = normalFileNameWithoutExtension;
}
else
{
pFileName = argv[i];
}
if( !g_Quiet )
{
printf( "file: %s\n", pFileName );
}
float bumpScale = -1.0f;
int startFrame = -1;
int endFrame = -1;
LoadConfigFile( pFileName, &bumpScale, &startFrame, &endFrame );
if( bumpScale == -1.0f )
{
fprintf( stderr, "Must specify \"bumpscale\" in config file\n" );
Pause();
continue;
}
if( ( startFrame == -1 && endFrame != -1 ) ||
( startFrame != -1 && endFrame == -1 ) )
{
fprintf( stderr, "ERROR: If you use startframe, you must use endframe, and vice versa.\n" );
Pause();
continue;
}
if( !g_Quiet )
{
printf( "\tbumpscale: %f\n", bumpScale );
}
Q_StripExtension( pFileName, normalFileNameWithoutExtension, sizeof( normalFileNameWithoutExtension ) );
ProcessFiles( normalFileNameWithoutExtension,
startFrame, endFrame,
bumpScale );
}
return 0;
}

View File

@@ -0,0 +1,288 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>Motionmapper</ProjectName>
<ProjectGuid>{C805838C-256D-6672-3417-589B6AF7D95E}</ProjectGuid>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>motionmapper</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>motionmapper</TargetName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PostBuildEventUseInBuild>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PostBuildEventUseInBuild>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 motionmapper.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;..\common;..\nvtristriplib;..\..\Game_Shared</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_ITERATOR_DEBUGGING=0;WIN32;_WIN32;_DEBUG;DEBUG;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;PROTECTED_THINGS_DISABLE;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\motionmapper;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies);winmm.lib</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\motionmapper.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmt</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Console</SubSystem>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/motionmapper.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 motionmapper.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP /d2Zi+</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;..\common;..\nvtristriplib;..\..\Game_Shared</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;PROTECTED_THINGS_DISABLE;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\motionmapper;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /DYNAMICBASE /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies);winmm.lib</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\motionmapper.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmtd</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/motionmapper.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemGroup>
<Library Include="..\..\lib\public\mathlib.lib" />
<Library Include="..\..\lib\public\nvtristrip.lib" />
<Library Include="..\..\lib\public\tier0.lib" />
<Library Include="..\..\lib\public\tier1.lib" />
<Library Include="..\..\lib\public\tier2.lib" />
<Library Include="..\..\lib\public\vstdlib.lib" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\public\mathlib\amd3dx.h" />
<ClInclude Include="..\..\public\tier0\basetypes.h" />
<ClInclude Include="..\..\public\tier1\characterset.h" />
<ClInclude Include="..\common\cmdlib.h" />
<ClInclude Include="..\..\public\Color.h" />
<ClInclude Include="..\..\public\tier0\commonmacros.h" />
<ClInclude Include="..\..\public\mathlib\compressed_vector.h" />
<ClInclude Include="..\..\public\tier0\dbg.h" />
<ClInclude Include="..\..\public\tier0\fasttimer.h" />
<ClInclude Include="..\..\public\filesystem.h" />
<ClInclude Include="..\..\public\filesystem_helpers.h" />
<ClInclude Include="..\common\filesystem_tools.h" />
<ClInclude Include="..\..\public\appframework\IAppSystem.h" />
<ClInclude Include="..\..\public\tier0\icommandline.h" />
<ClInclude Include="..\..\public\vstdlib\IKeyValuesSystem.h" />
<ClInclude Include="..\..\public\tier1\interface.h" />
<ClInclude Include="..\..\public\tier1\KeyValues.h" />
<ClInclude Include="..\..\public\mathlib\mathlib.h" />
<ClInclude Include="..\..\public\tier0\mem.h" />
<ClInclude Include="..\..\public\tier0\memalloc.h" />
<ClInclude Include="..\..\public\tier0\memdbgoff.h" />
<ClInclude Include="..\..\public\tier0\memdbgon.h" />
<ClInclude Include="motionmapper.h" />
<ClInclude Include="..\..\public\tier0\platform.h" />
<ClInclude Include="..\..\public\tier0\protected_things.h" />
<ClInclude Include="..\common\scriplib.h" />
<ClInclude Include="..\..\public\string_t.h" />
<ClInclude Include="..\..\public\tier1\strtools.h" />
<ClInclude Include="..\..\public\studio.h" />
<ClInclude Include="..\..\public\tier1\utlbuffer.h" />
<ClInclude Include="..\..\public\tier1\utldict.h" />
<ClInclude Include="..\..\public\tier1\utllinkedlist.h" />
<ClInclude Include="..\..\public\tier1\utlmemory.h" />
<ClInclude Include="..\..\public\tier1\utlrbtree.h" />
<ClInclude Include="..\..\public\tier1\utlsymbol.h" />
<ClInclude Include="..\..\public\tier1\utlvector.h" />
<ClInclude Include="..\..\public\mathlib\vector.h" />
<ClInclude Include="..\..\public\mathlib\vector2d.h" />
<ClInclude Include="..\..\public\mathlib\vector4d.h" />
<ClInclude Include="..\..\public\vstdlib\vstdlib.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\common\cmdlib.cpp" />
<ClCompile Include="..\..\public\filesystem_helpers.cpp" />
<ClCompile Include="..\..\public\filesystem_init.cpp" />
<ClCompile Include="..\common\filesystem_tools.cpp" />
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="motionmapper.cpp" />
<ClCompile Include="..\common\scriplib.cpp" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)\%(Filename).obj</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)\%(Filename).obj</Outputs>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,188 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{1680C80B-FF1E-EA4D-9817-CC12254F2E40}</UniqueIdentifier>
</Filter>
<Filter Include="Link Libraries">
<UniqueIdentifier>{C5D73B3A-C648-896C-B7CE-F174808E5BA5}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{BA03E055-4FA2-FCE3-8A1C-D348547D379C}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<Library Include="..\..\lib\public\mathlib.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\nvtristrip.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier0.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier1.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier2.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\vstdlib.lib">
<Filter>Link Libraries</Filter>
</Library>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\public\mathlib\amd3dx.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\basetypes.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\characterset.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\common\cmdlib.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\Color.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\commonmacros.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\compressed_vector.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\dbg.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\fasttimer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\filesystem.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\filesystem_helpers.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\common\filesystem_tools.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\appframework\IAppSystem.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\icommandline.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\vstdlib\IKeyValuesSystem.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\interface.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\KeyValues.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\mathlib.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\mem.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\memalloc.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\memdbgoff.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\memdbgon.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="motionmapper.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\platform.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\protected_things.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\common\scriplib.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\string_t.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\strtools.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\studio.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlbuffer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utldict.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utllinkedlist.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlmemory.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlrbtree.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlsymbol.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlvector.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\vector.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\vector2d.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\vector4d.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\vstdlib\vstdlib.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\common\cmdlib.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\public\filesystem_helpers.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\public\filesystem_init.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\common\filesystem_tools.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="motionmapper.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\common\scriplib.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Filter>Source Files</Filter>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,274 @@
/***
*
//========= Copyright Valve Corporation, All rights reserved. ============//
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
****/
#include <stdio.h>
#include "basetypes.h"
#include "utlvector.h"
#include "utlsymbol.h"
#include "mathlib/vector.h"
#include "studio.h"
struct LodScriptData_t;
#define IDSTUDIOHEADER (('T'<<24)+('S'<<16)+('D'<<8)+'I')
// little-endian "IDST"
#define IDSTUDIOANIMGROUPHEADER (('G'<<24)+('A'<<16)+('D'<<8)+'I')
// little-endian "IDAG"
#define STUDIO_QUADRATIC_MOTION 0x00002000
#define MAXSTUDIOANIMFRAMES 2000 // max frames per animation
#define MAXSTUDIOSEQUENCES 1524 // total sequences
#define MAXSTUDIOSRCBONES 512 // bones allowed at source movement
#define MAXSTUDIOBONEWEIGHTS 3
#define MAXSTUDIONAME 128
#ifndef EXTERN
#define EXTERN extern
#endif
EXTERN char outname[1024];
EXTERN int numdirs;
EXTERN char cddir[32][MAX_PATH];
EXTERN char fullpath[1024];
EXTERN float g_defaultscale;
EXTERN float g_currentscale;
EXTERN RadianEuler g_defaultrotation;
EXTERN char defaulttexture[16][MAX_PATH];
EXTERN char sourcetexture[16][MAX_PATH];
EXTERN int numrep;
EXTERN int flip_triangles;
EXTERN float normal_blend;
void *kalloc( int num, int size );
struct s_trianglevert_t
{
int vertindex;
int normindex; // index into normal array
int s,t;
float u,v;
};
struct s_boneweight_t
{
int numbones;
int bone[MAXSTUDIOBONEWEIGHTS];
float weight[MAXSTUDIOBONEWEIGHTS];
};
struct s_vertexinfo_t
{
// wtf is this doing here?
int material;
int firstref;
int lastref;
int flexmask;
int numflex;
int flexoffset;
};
struct s_tmpface_t
{
int material;
unsigned long a, b, c;
unsigned long ta, tb, tc;
unsigned long na, nb, nc;
};
struct s_face_t
{
unsigned long a, b, c;
};
struct s_node_t
{
char name[MAXSTUDIONAME];
int parent;
};
struct s_bone_t
{
Vector pos;
RadianEuler rot;
};
struct s_texture_t
{
char name[MAX_PATH];
int flags;
int parent;
int material;
float width;
float height;
float dPdu;
float dPdv;
};
EXTERN s_texture_t g_texture[MAXSTUDIOSKINS];
EXTERN int g_numtextures;
EXTERN int g_material[MAXSTUDIOSKINS]; // link into texture array
EXTERN int g_nummaterials;
EXTERN float g_gamma;
EXTERN int g_numskinref;
EXTERN int g_numskinfamilies;
EXTERN int g_skinref[256][MAXSTUDIOSKINS]; // [skin][skinref], returns texture index
EXTERN int g_numtexturegroups;
EXTERN int g_numtexturelayers[32];
EXTERN int g_numtexturereps[32];
EXTERN int g_texturegroup[32][32][32];
struct s_mesh_t
{
int numvertices;
int vertexoffset;
int numfaces;
int faceoffset;
};
struct s_vertanim_t
{
int vertex;
float speed;
float side;
Vector pos;
Vector normal;
};
// processed aggregate lod pools
struct s_loddata_t
{
int numvertices;
s_boneweight_t *globalBoneweight;
s_vertexinfo_t *vertexInfo;
Vector *vertex;
Vector *normal;
Vector4D *tangentS;
Vector2D *texcoord;
int numfaces;
s_face_t *face;
s_mesh_t mesh[MAXSTUDIOSKINS];
// remaps verts from an lod's source mesh to this all-lod processed aggregate pool
int *pMeshVertIndexMaps[MAX_NUM_LODS];
};
// raw off-disk source files. Raw data should be not processed.
struct s_source_t
{
char filename[MAX_PATH];
int time; // time stamp
bool isActiveModel;
// local skeleton hierarchy
int numbones;
s_node_t localBone[MAXSTUDIOSRCBONES];
matrix3x4_t boneToPose[MAXSTUDIOSRCBONES]; // converts bone local data into initial pose data
// bone remapping
int boneflags[MAXSTUDIOSRCBONES]; // attachment, vertex, etc flags for this bone
int boneref[MAXSTUDIOSRCBONES]; // flags for this and child bones
int boneLocalToGlobal[MAXSTUDIOSRCBONES]; // bonemap : local bone to world bone mapping
int boneGlobalToLocal[MAXSTUDIOSRCBONES]; // boneimap : world bone to local bone mapping
int texmap[MAXSTUDIOSKINS*4]; // map local MAX materials to unique textures
// per material mesh
int nummeshes;
int meshindex[MAXSTUDIOSKINS]; // mesh to skin index
s_mesh_t mesh[MAXSTUDIOSKINS];
// model global copy of vertices
int numvertices;
s_boneweight_t *localBoneweight; // vertex info about local bone weighting
s_boneweight_t *globalBoneweight; // vertex info about global bone weighting
s_vertexinfo_t *vertexInfo; // generic vertex info
Vector *vertex;
Vector *normal;
Vector4D *tangentS;
Vector2D *texcoord;
int numfaces;
s_face_t *face; // vertex indexs per face
// raw skeletal animation
int numframes;
int startframe;
int endframe;
s_bone_t *rawanim[MAXSTUDIOANIMFRAMES]; // [frame][bones];
// vertex animation
int *vanim_mapcount; // local verts map to N target verts
int **vanim_map; // local vertices to target vertices mapping list
int *vanim_flag; // local vert does animate
int numvanims[MAXSTUDIOANIMFRAMES];
s_vertanim_t *vanim[MAXSTUDIOANIMFRAMES]; // [frame][vertex]
// processed aggregate lod data
s_loddata_t *pLodData;
};
EXTERN int g_numsources;
EXTERN s_source_t *g_source[MAXSTUDIOSEQUENCES];
EXTERN int is_v1support;
EXTERN int g_numverts;
EXTERN Vector g_vertex[MAXSTUDIOVERTS];
EXTERN s_boneweight_t g_bone[MAXSTUDIOVERTS];
EXTERN int g_numnormals;
EXTERN Vector g_normal[MAXSTUDIOVERTS];
EXTERN int g_numtexcoords;
EXTERN Vector2D g_texcoord[MAXSTUDIOVERTS];
EXTERN int g_numfaces;
EXTERN s_tmpface_t g_face[MAXSTUDIOTRIANGLES];
EXTERN s_face_t g_src_uface[MAXSTUDIOTRIANGLES]; // max res unified faces
struct v_unify_t
{
int refcount;
int lastref;
int firstref;
int v;
int m;
int n;
int t;
v_unify_t *next;
};
EXTERN v_unify_t *v_list[MAXSTUDIOVERTS];
EXTERN v_unify_t v_listdata[MAXSTUDIOVERTS];
EXTERN int numvlist;
int SortAndBalanceBones( int iCount, int iMaxCount, int bones[], float weights[] );
void Grab_Vertexanimation( s_source_t *psource );
extern void BuildIndividualMeshes( s_source_t *psource );

View File

@@ -0,0 +1,124 @@
#ifndef NVTRISTRIP_H
#define NVTRISTRIP_H
#ifndef NULL
#define NULL 0
#endif
#pragma comment(lib, "nvtristrip")
////////////////////////////////////////////////////////////////////////////////////////
// Public interface for stripifier
////////////////////////////////////////////////////////////////////////////////////////
//GeForce1 and 2 cache size
#define CACHESIZE_GEFORCE1_2 16
//GeForce3 cache size
#define CACHESIZE_GEFORCE3 24
enum PrimType
{
PT_LIST,
PT_STRIP,
PT_FAN
};
struct PrimitiveGroup
{
PrimType type;
unsigned int numIndices;
unsigned short* indices;
////////////////////////////////////////////////////////////////////////////////////////
PrimitiveGroup() : type(PT_STRIP), numIndices(0), indices(NULL) {}
~PrimitiveGroup()
{
if(indices)
delete[] indices;
indices = NULL;
}
};
////////////////////////////////////////////////////////////////////////////////////////
// SetCacheSize()
//
// Sets the cache size which the stripfier uses to optimize the data.
// Controls the length of the generated individual strips.
// This is the "actual" cache size, so 24 for GeForce3 and 16 for GeForce1/2
// You may want to play around with this number to tweak performance.
//
// Default value: 16
//
void SetCacheSize(const unsigned int cacheSize);
////////////////////////////////////////////////////////////////////////////////////////
// SetStitchStrips()
//
// bool to indicate whether to stitch together strips into one huge strip or not.
// If set to true, you'll get back one huge strip stitched together using degenerate
// triangles.
// If set to false, you'll get back a large number of separate strips.
//
// Default value: true
//
void SetStitchStrips(const bool bStitchStrips);
////////////////////////////////////////////////////////////////////////////////////////
// SetMinStripSize()
//
// Sets the minimum acceptable size for a strip, in triangles.
// All strips generated which are shorter than this will be thrown into one big, separate list.
//
// Default value: 0
//
void SetMinStripSize(const unsigned int minSize);
////////////////////////////////////////////////////////////////////////////////////////
// SetListsOnly()
//
// If set to true, will return an optimized list, with no strips at all.
//
// Default value: false
//
void SetListsOnly(const bool bListsOnly);
////////////////////////////////////////////////////////////////////////////////////////
// GenerateStrips()
//
// in_indices: input index list, the indices you would use to render
// in_numIndices: number of entries in in_indices
// primGroups: array of optimized/stripified PrimitiveGroups
// numGroups: number of groups returned
//
// Be sure to call delete[] on the returned primGroups to avoid leaking mem
//
void GenerateStrips(const unsigned short* in_indices, const unsigned int in_numIndices,
PrimitiveGroup** primGroups, unsigned short* numGroups);
////////////////////////////////////////////////////////////////////////////////////////
// RemapIndices()
//
// Function to remap your indices to improve spatial locality in your vertex buffer.
//
// in_primGroups: array of PrimitiveGroups you want remapped
// numGroups: number of entries in in_primGroups
// numVerts: number of vertices in your vertex buffer, also can be thought of as the range
// of acceptable values for indices in your primitive groups.
// remappedGroups: array of remapped PrimitiveGroups
//
// Note that, according to the remapping handed back to you, you must reorder your
// vertex buffer.
//
// Credit goes to the MS Xbox crew for the idea for this interface.
//
void RemapIndices(const PrimitiveGroup* in_primGroups, const unsigned short numGroups,
const unsigned short numVerts, PrimitiveGroup** remappedGroups);
#endif

View File

@@ -0,0 +1,28 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include <windows.h>
#include <stdio.h>
//-----------------------------------------------------------------------------
// Purpose: converts an english string to unicode
//-----------------------------------------------------------------------------
int ConvertANSIToUnicode(const char *ansi, wchar_t *unicode, int unicodeBufferSize)
{
return ::MultiByteToWideChar(CP_ACP, 0, ansi, -1, unicode, unicodeBufferSize);
}
char *va( const char *fmt, ... )
{
va_list args;
static char output[4][1024];
static int outbuffer = 0;
outbuffer++;
va_start( args, fmt );
vprintf( fmt, args );
vsprintf( output[ outbuffer & 3 ], fmt, args );
return output[ outbuffer & 3 ];
}

View File

@@ -0,0 +1,268 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>Phonemeextractor</ProjectName>
<ProjectGuid>{079933D6-F849-3176-49FC-D50E4B461AC4}</ProjectGuid>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>phonemeextractor</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>phonemeextractor</TargetName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PostBuildEventUseInBuild>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PostBuildEventUseInBuild>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PreBuildEvent>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP /wd4995</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;../common;../hlfaceposer;../sapi51/include</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_ITERATOR_DEBUGGING=0;WIN32;_WIN32;_DEBUG;DEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;DLLNAME=phonemeextractor;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;PHONEMEEXTRACTOR_EXPORTS;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\phonemeextractor;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<GenerateXMLDocumentationFiles>false</GenerateXMLDocumentationFiles>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies);odbc32.lib;odbccp32.lib</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\phonemeextractor.dll</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>..\..\lib\common;..\..\lib\public</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmt</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/phonemeextractor.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin\phonemeextractors</Message>
<Command>if not exist &quot;..\..\..\game\bin\phonemeextractors&quot; mkdir &quot;..\..\..\game\bin\phonemeextractors&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) &quot;..\..\..\game\bin\phonemeextractors\$(TargetFileName)&quot;&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\phonemeextractors\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\phonemeextractors\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PreBuildEvent>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP /d2Zi+ /wd4995</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;../common;../hlfaceposer;../sapi51/include</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WIN32;NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;DLLNAME=phonemeextractor;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;PHONEMEEXTRACTOR_EXPORTS;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\phonemeextractor;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<GenerateXMLDocumentationFiles>false</GenerateXMLDocumentationFiles>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /DYNAMICBASE /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies);odbc32.lib;odbccp32.lib</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\phonemeextractor.dll</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>..\..\lib\common;..\..\lib\public</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmtd</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/phonemeextractor.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin\phonemeextractors</Message>
<Command>if not exist &quot;..\..\..\game\bin\phonemeextractors&quot; mkdir &quot;..\..\..\game\bin\phonemeextractors&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) &quot;..\..\..\game\bin\phonemeextractors\$(TargetFileName)&quot;&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\phonemeextractors\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\phonemeextractors\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemGroup>
<Library Include="..\..\lib\public\mathlib.lib" />
<Library Include="..\sapi51\lib\i386\sapi.lib" />
<Library Include="..\..\lib\public\tier0.lib" />
<Library Include="..\..\lib\public\tier1.lib" />
<Library Include="..\..\lib\public\vstdlib.lib" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="talkback.h" />
<ClInclude Include="..\..\public\mathlib\amd3dx.h" />
<ClInclude Include="..\..\public\tier0\basetypes.h" />
<ClInclude Include="..\..\public\tier0\commonmacros.h" />
<ClInclude Include="..\..\public\tier0\dbg.h" />
<ClInclude Include="..\..\public\tier0\fasttimer.h" />
<ClInclude Include="..\..\public\appframework\IAppSystem.h" />
<ClInclude Include="..\..\public\mathlib\mathlib.h" />
<ClInclude Include="..\..\public\phonemeconverter.h" />
<ClInclude Include="..\..\public\phonemeextractor\phonemeextractor.h" />
<ClInclude Include="..\..\public\tier0\platform.h" />
<ClInclude Include="..\..\public\tier0\protected_things.h" />
<ClInclude Include="..\..\public\sentence.h" />
<ClInclude Include="..\..\public\string_t.h" />
<ClInclude Include="..\..\public\tier1\strtools.h" />
<ClInclude Include="..\..\public\tier1\utllinkedlist.h" />
<ClInclude Include="..\..\public\tier1\utlmemory.h" />
<ClInclude Include="..\..\public\tier1\utlvector.h" />
<ClInclude Include="..\..\public\mathlib\vector.h" />
<ClInclude Include="..\..\public\mathlib\vector2d.h" />
<ClInclude Include="..\..\public\vstdlib\vstdlib.h" />
<ClInclude Include="..\sapi51\Include\sapi.h" />
<ClInclude Include="..\sapi51\Include\sapiddk.h" />
<ClInclude Include="..\sapi51\Include\Spddkhlp.h" />
<ClInclude Include="..\sapi51\Include\spdebug.h" />
<ClInclude Include="..\sapi51\Include\sperror.h" />
<ClInclude Include="..\sapi51\Include\sphelper.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="extractor_utils.cpp" />
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="..\..\public\phonemeconverter.cpp" />
<ClCompile Include="phonemeextractor.cpp" />
<ClCompile Include="..\..\public\sentence.cpp" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)\%(Filename).obj</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)\%(Filename).obj</Outputs>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,146 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{1680C80B-FF1E-EA4D-9817-CC12254F2E40}</UniqueIdentifier>
</Filter>
<Filter Include="Link Libraries">
<UniqueIdentifier>{C5D73B3A-C648-896C-B7CE-F174808E5BA5}</UniqueIdentifier>
</Filter>
<Filter Include="Public Header Files">
<UniqueIdentifier>{680EF60A-F852-B6F6-8E56-5693F8167FE5}</UniqueIdentifier>
</Filter>
<Filter Include="SAPI Header Files">
<UniqueIdentifier>{0339A88D-F26D-9E55-2AC4-F2CED0F7745A}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{BA03E055-4FA2-FCE3-8A1C-D348547D379C}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<Library Include="..\..\lib\public\mathlib.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\sapi51\lib\i386\sapi.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier0.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier1.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\vstdlib.lib">
<Filter>Link Libraries</Filter>
</Library>
</ItemGroup>
<ItemGroup>
<ClInclude Include="talkback.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\amd3dx.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\basetypes.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\commonmacros.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\dbg.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\fasttimer.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\appframework\IAppSystem.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\mathlib.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\phonemeconverter.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\phonemeextractor\phonemeextractor.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\platform.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\protected_things.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\sentence.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\string_t.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\strtools.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utllinkedlist.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlmemory.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlvector.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\vector.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\mathlib\vector2d.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\vstdlib\vstdlib.h">
<Filter>Public Header Files</Filter>
</ClInclude>
<ClInclude Include="..\sapi51\Include\sapi.h">
<Filter>SAPI Header Files</Filter>
</ClInclude>
<ClInclude Include="..\sapi51\Include\sapiddk.h">
<Filter>SAPI Header Files</Filter>
</ClInclude>
<ClInclude Include="..\sapi51\Include\Spddkhlp.h">
<Filter>SAPI Header Files</Filter>
</ClInclude>
<ClInclude Include="..\sapi51\Include\spdebug.h">
<Filter>SAPI Header Files</Filter>
</ClInclude>
<ClInclude Include="..\sapi51\Include\sperror.h">
<Filter>SAPI Header Files</Filter>
</ClInclude>
<ClInclude Include="..\sapi51\Include\sphelper.h">
<Filter>SAPI Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="extractor_utils.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\public\phonemeconverter.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="phonemeextractor.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="..\..\public\sentence.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Filter>Source Files</Filter>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@@ -0,0 +1,732 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// =============================================================================
// Interface to the LIPSinc TalkBack 1.1 library (TalkBack_*.lib).
//
// Copyright © 1998-2002 LIPSinc. All rights reserved.
#if !defined(TalkBack_h)
#define TalkBack_h
#include <stddef.h> // size_t.
// Enforce a C API.
#if defined(__cplusplus)
extern "C"
{
#endif
// -----------------------------------------------------------------------------
// Use the preprocessor to make the new API compatible with the old one.
#define TalkbackStartupLibrary TalkBackStartupLibrary
#define TalkbackShutdownLibrary TalkBackShutdownLibrary
#define TalkbackGetVersion TalkBackGetVersion
#define TalkbackGetVersionString TalkBackGetVersionString
#define TalkbackCheckSoundFile TalkBackCheckSoundFile
#define TalkbackCheckSpokenText TalkBackCheckSpokenText
#define TalkbackGetErrorString TalkBackGetErrorString
#define TalkbackGetAnalysis TalkBackGetAnalysis
#define TalkbackFreeAnalysis TalkBackFreeAnalysis
#define TalkbackGetFirstFrameNum TalkBackGetFirstFrameNum
#define TalkbackGetLastFrameNum TalkBackGetLastFrameNum
#define TalkbackGetFrameStartTime TalkBackGetFrameStartTime
#define TalkbackGetFrameEndTime TalkBackGetFrameEndTime
#define TalkbackGetNumPhonemes TalkBackGetNumPhonemes
#define TalkbackGetPhonemeEnum TalkBackGetPhonemeEnum
#define TalkbackGetPhonemeStartTime TalkBackGetPhonemeStartTime
#define TalkbackGetPhonemeEndTime TalkBackGetPhonemeEndTime
#define TalkbackInsertPhoneme TalkBackInsertPhoneme
#define TalkbackDeletePhoneme TalkBackDeletePhoneme
#define TalkbackChangePhonemeStart TalkBackChangePhonemeStart
#define TalkbackChangePhonemeEnd TalkBackChangePhonemeEnd
#define TalkbackChangePhonemeEnum TalkBackChangePhonemeEnum
#define TalkbackGetNumWords TalkBackGetNumWords
#define TalkbackGetWord TalkBackGetWord
#define TalkbackGetWordStartTime TalkBackGetWordStartTime
#define TalkbackGetWordEndTime TalkBackGetWordEndTime
#define TalkbackGetNumSpeechTargetTracks TalkBackGetNumSpeechTargetTracks
#define TalkbackGetNumSpeechTargetKeys TalkBackGetNumSpeechTargetKeys
#define TalkbackGetSpeechTargetKeyInfo TalkBackGetSpeechTargetKeyInfo
#define TalkbackGetSpeechTargetValueAtFrame TalkBackGetSpeechTargetValueAtFrame
#define TalkbackGetDominantSpeechTargetAtFrame TalkBackGetDominantSpeechTargetAtFrame
#define TalkbackGetSpeechTargetValueAtTime TalkBackGetSpeechTargetValueAtTime
#define TalkbackGetSpeechTargetDerivativesAtTime TalkBackGetSpeechTargetDerivativesAtTime
#define TalkbackGetNumGestureTracks TalkBackGetNumGestureTracks
#define TalkbackGetNumGestureKeys TalkBackGetNumGestureKeys
#define TalkbackGetGestureKeyInfo TalkBackGetGestureKeyInfo
#define TalkbackGetGestureValueAtFrame TalkBackGetGestureValueAtFrame
#define TalkbackGetGestureValueAtTime TalkBackGetGestureValueAtTime
#define TalkbackGetGestureDerivativesAtTime TalkBackGetGestureDerivativesAtTime
// -----------------------------------------------------------------------------
// For debug builds, set this to a non-zero value to get verbose debugging
// output from TalkBack.
extern int g_enableTalkBackDebuggingOutput;
// -----------------------------------------------------------------------------
// Miscellaneous constants.
// For calling TalkBackGetAnalysis() with all defaults.
#define TALKBACK_DEFAULT_SETTINGS NULL
// For setting the iSoundText parameter in TalkBackGetAnalysis() to "no text."
#define TALKBACK_NO_TEXT NULL
// Handy constants for TALKBACK_ANALYSIS_SETTINGS fields:
// For setting fSize.
#define TALKBACK_SETTINGS_SIZE sizeof(TALKBACK_ANALYSIS_SETTINGS)
// For setting fFrameRate to the
// default.
#define TALKBACK_DEFAULT_FRAME_RATE 30
// For setting fOptimizeForFlipbook
// to *not* optimize for flipbook.
#define TALKBACK_OPTIMIZE_FOR_FLIPBOOK_OFF 0
// For setting fOptimizeForFlipbook
// to optimize for flipbook.
#define TALKBACK_OPTIMIZE_FOR_FLIPBOOK_ON 1
// For setting fRandomSeed to use the
// current time to seed the random
// number generator and thereby get
// non-deterministic speech gestures.
#define TALKBACK_RANDOM_SEED -1
// For setting fConfigFile to "no
// config file."
#define TALKBACK_NO_CONFIG_FILE NULL
// -----------------------------------------------------------------------------
// Data types.
// TALKBACK_NOERR if successful, TalkBack error code if not.
typedef long TALKBACK_ERR;
// Opaque analysis results.
typedef void TALKBACK_ANALYSIS;
// Speech target.
typedef long TALKBACK_SPEECH_TARGET;
// Speech gesture.
typedef long TALKBACK_GESTURE;
// Phoneme.
typedef long TALKBACK_PHONEME;
// -----------------------------------------------------------------------------
// Data structures.
#pragma pack(push, 1)
// Optional analysis settings passed to TalkBackGetAnalysis().
typedef struct
{
// Set this field to sizeof(TALKBACK_ANALYSIS_SETTINGS) before using the
// structure.
long fSize;
// Frame rate for analysis. This only matters if you will be using *AtFrame
// functions.
//
// Default value: 30 (frames per second).
long fFrameRate;
// Set this to 1 to optimize for flipbook output, 0 to do analysis normally.
//
// Default value: 0 (normal analysis).
long fOptimizeForFlipbook;
// Set this to -1 to seed the random number generator with the current time.
// Any other number will be used directly for the random number seed, which
// is useful if you want repeatable speech gestures. This value does not
// influence lip-synching at all.
//
// Default value: -1 (use current time).
long fRandomSeed;
// Path to the configuration (.INI) file with phoneme-to-speech-target
// mapping. Set this to NULL to use the default mapping.
//
// Default value: NULL (use default mapping).
char const *fConfigFile;
} TALKBACK_ANALYSIS_SETTINGS;
typedef struct
{
// Set this field to sizeof(TALKBACK_SOUND_FILE_METRICS) before using the
// structure. This will allow the structure to evolve if necessary.
size_t m_size;
// Bits per sample.
long m_bitsPerSample;
// Sample rate in Hertz.
long m_sampleRate;
// Duration of the audio in seconds.
double m_duration;
// 1 if the sound file can be analyzed, 0 if not.
long m_canBeAnalyzed;
// 1 if the sound file is clipped, 0 if not.
long m_isClipped;
// The decibel range of the sound file.
double m_decibelRange;
// A quality value for the sound file: the nominal range is 0 to 100. Try
// to keep it above 45 for good results.
int m_quality;
// Added for version 2 of the metrics structure:
// ---------------------------------------------
// The number of channels in the sound file: 1 for mono, 2 for stereo, etc.
long m_channelCount;
} TALKBACK_SOUND_FILE_METRICS;
#pragma pack(pop)
// -----------------------------------------------------------------------------
// Constants.
// TalkBack error codes. Use TalkBackGetErrorString() to return text
// descriptions for these codes.
enum
{
// Windows convention: set this bit to indicate an application-defined error
// code.
BIT29 = (1 << 29),
// Success (not an error).
TALKBACK_NOERR = 0,
// The first error code: useful for iterating through the error codes.
TALKBACK_ERROR_FIRST = 4201 | BIT29,
// Generic error.
TALKBACK_ERROR = TALKBACK_ERROR_FIRST,
// TalkBackStartupLibrary() failed [internal error] or was never called.
TALKBACK_STARTUP_FAILED_ERR,
// TalkBackShutdownLibrary() failed, either because
// TalkBackStartupLibrary() was never called or because
// TalkBackShutdownLibrary() has already been called.
TALKBACK_SHUTDOWN_FAILED_ERR,
// The TalkBack data files could not be found [invalid path or missing
// files].
TALKBACK_CORE_DATA_NOT_FOUND_ERR,
// One or more of the parameters are NULL.
TALKBACK_NULL_PARAMETER_ERR,
// One or more of the parameters is invalid.
TALKBACK_INVALID_PARAMETER_ERR,
// The analysis object pointer is invalid.
TALKBACK_INVALID_ANALYSIS_ERR,
// Analysis failed [the sound file cannot be analyzed or an internal error
// occurred].
TALKBACK_ANALYSIS_FAILED_ERR,
// One or more of the indices (track, key, frame, word, phoneme) are
// invalid (out of range).
TALKBACK_INVALID_INDEX_ERR,
// The time parameter is invalid (out of range).
TALKBACK_INVALID_TIME_ERR,
// A serious internal error occurred in TalkBack; please alert LIPSinc by
// sending mail with a description of how the error was triggered to
// talkback-support@LIPSinc.com.
TALKBACK_INTERNAL_ERR,
// Could not open the specified sound file.
TALKBACK_COULD_NOT_LOAD_SOUND_ERR,
// TalkBackStartupLibrary() has not been called.
TALKBACK_STARTUP_NOT_CALLED,
// The configuration file specified in the TALKBACK_ANALYSIS_SETTINGS
// structure is invalid.
TALKBACK_CONFIG_PARSE_ERROR,
// The last error code: useful for iterating through the error codes.
TALKBACK_ERROR_LAST = TALKBACK_CONFIG_PARSE_ERROR
};
// Default lip-synching track identifiers.
//
// NOTE: these track identifiers apply *only* to the default phoneme-to-track
// mapping! Consult the TalkBack Reference Guide for more details.
//
// NOTE: these values are valid *only* if you use the default mapping and are
// provided as a convenience. If you use your own mapping, these values
// are invalid and should not be used.
enum
{
TALKBACK_SPEECH_TARGET_INVALID = -1,
TALKBACK_SPEECH_TARGET_FIRST = 0,
TALKBACK_SPEECH_TARGET_EAT = TALKBACK_SPEECH_TARGET_FIRST, // 0
TALKBACK_SPEECH_TARGET_EARTH, // 1
TALKBACK_SPEECH_TARGET_IF, // 2
TALKBACK_SPEECH_TARGET_OX, // 3
TALKBACK_SPEECH_TARGET_OAT, // 4
TALKBACK_SPEECH_TARGET_WET, // 5
TALKBACK_SPEECH_TARGET_SIZE, // 6
TALKBACK_SPEECH_TARGET_CHURCH, // 7
TALKBACK_SPEECH_TARGET_FAVE, // 8
TALKBACK_SPEECH_TARGET_THOUGH, // 9
TALKBACK_SPEECH_TARGET_TOLD, // 10
TALKBACK_SPEECH_TARGET_BUMP, // 11
TALKBACK_SPEECH_TARGET_NEW, // 12
TALKBACK_SPEECH_TARGET_ROAR, // 13
TALKBACK_SPEECH_TARGET_CAGE, // 14
TALKBACK_SPEECH_TARGET_LAST = TALKBACK_SPEECH_TARGET_CAGE, // 14
TALKBACK_NUM_SPEECH_TARGETS // 15 (0..14)
};
// Speech gesture track identifiers.
enum
{
TALKBACK_GESTURE_INVALID = -1,
TALKBACK_GESTURE_FIRST = 0,
TALKBACK_GESTURE_EYEBROW_RAISE_LEFT = TALKBACK_GESTURE_FIRST, // 0
TALKBACK_GESTURE_EYEBROW_RAISE_RIGHT, // 1
TALKBACK_GESTURE_BLINK_LEFT, // 2
TALKBACK_GESTURE_BLINK_RIGHT, // 3
TALKBACK_GESTURE_HEAD_BEND, // 4
TALKBACK_GESTURE_HEAD_SIDE_SIDE, // 5
TALKBACK_GESTURE_HEAD_TWIST, // 6
TALKBACK_GESTURE_EYE_SIDE_SIDE_LEFT, // 7
TALKBACK_GESTURE_EYE_SIDE_SIDE_RIGHT, // 8
TALKBACK_GESTURE_EYE_UP_DOWN_LEFT, // 9
TALKBACK_GESTURE_EYE_UP_DOWN_RIGHT, // 10
TALKBACK_GESTURE_LAST = TALKBACK_GESTURE_EYE_UP_DOWN_RIGHT, // 10
TALKBACK_NUM_GESTURES // 11 (0..10)
};
// Phoneme identifiers.
enum
{
TALKBACK_PHONEME_INVALID = -1,
TALKBACK_PHONEME_FIRST = 0,
TALKBACK_PHONEME_IY = TALKBACK_PHONEME_FIRST, // 0
TALKBACK_PHONEME_IH, // 1
TALKBACK_PHONEME_EH, // 2
TALKBACK_PHONEME_EY, // 3
TALKBACK_PHONEME_AE, // 4
TALKBACK_PHONEME_AA, // 5
TALKBACK_PHONEME_AW, // 6
TALKBACK_PHONEME_AY, // 7
TALKBACK_PHONEME_AH, // 8
TALKBACK_PHONEME_AO, // 9
TALKBACK_PHONEME_OY, // 10
TALKBACK_PHONEME_OW, // 11
TALKBACK_PHONEME_UH, // 12
TALKBACK_PHONEME_UW, // 13
TALKBACK_PHONEME_ER, // 14
TALKBACK_PHONEME_AX, // 15
TALKBACK_PHONEME_S, // 16
TALKBACK_PHONEME_SH, // 17
TALKBACK_PHONEME_Z, // 18
TALKBACK_PHONEME_ZH, // 19
TALKBACK_PHONEME_F, // 20
TALKBACK_PHONEME_TH, // 21
TALKBACK_PHONEME_V, // 22
TALKBACK_PHONEME_DH, // 23
TALKBACK_PHONEME_M, // 24
TALKBACK_PHONEME_N, // 25
TALKBACK_PHONEME_NG, // 26
TALKBACK_PHONEME_L, // 27
TALKBACK_PHONEME_R, // 28
TALKBACK_PHONEME_W, // 29
TALKBACK_PHONEME_Y, // 30
TALKBACK_PHONEME_HH, // 31
TALKBACK_PHONEME_B, // 32
TALKBACK_PHONEME_D, // 33
TALKBACK_PHONEME_JH, // 34
TALKBACK_PHONEME_G, // 35
TALKBACK_PHONEME_P, // 36
TALKBACK_PHONEME_T, // 37
TALKBACK_PHONEME_K, // 38
TALKBACK_PHONEME_CH, // 39
TALKBACK_PHONEME_SIL, // 40
TALKBACK_PHONEME_LAST = TALKBACK_PHONEME_SIL, // 40
TALKBACK_NUM_PHONEMES // 41 (0..40)
};
// -----------------------------------------------------------------------------
// Function declarations.
// ---------------------------
// Startup/shutdown functions.
// ---------------------------
// Must be the first function called when using TalkBack.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackStartupLibrary(
char const *iCoreDataDir); // IN: full path of folder containing TalkBack data files.
// Should be the last function called when using TalkBack.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackShutdownLibrary(); // IN: nothing.
// ------------------
// Version functions.
// ------------------
// Gets the TalkBack version number.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetVersion(
long *oMajor, // OUT: major version number.
long *oMinor, // OUT: minor version number.
long *oRevision); // OUT: revision version number.
// Gets the TalkBack version number as a string.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetVersionString(
long iMaxChars, // IN: size of version string buffer.
char *oVersion); // OUT: version string buffer.
// ------------------
// Utility functions.
// ------------------
// Checks whether a sound file can be analyzed and returns some quality metrics.
//
// NOTE: this function is deprecated and has been supplanted by
// TalkBackGetSoundFileMetrics().
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackCheckSoundFile(
char const *iSoundFileName, // IN: name of sound file to be checked.
long *oCanBeAnalyzed, // OUT: 1 if sound can be analyzed, 0 if not.
long *oIsClipped, // OUT: 1 if sound is clipped, 0 if not.
double *oDecibelRange); // OUT: used decibel range of sound.
// Returns metrics for the specified sound file.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetSoundFileMetrics(
char const *iSoundFileName, // IN: name of sound file to be checked.
TALKBACK_SOUND_FILE_METRICS *ioMetrics); // IN/OUT: address of a structure where the metrics will be stored.
// Checks whether text can be used for text-based analysis, returning the text
// as it will be analyzed.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackCheckSpokenText(
char const *iSpokenText, // IN: text to check.
long iMaxChars, // IN: size of analyzed text buffer.
char *oAnalyzedText); // OUT: buffer for text as it will be analyzed.
// Convert a TalkBack error code to a description string.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetErrorString(
TALKBACK_ERR iErrorCode, // IN: TalkBack error code to convert.
long iMaxChars, // IN: size of the buffer.
char *oErrorString); // OUT: buffer for the description string.
// Gets the error code and text for the most recent TalkBack error.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetLastError(
long iMaxChars, // IN: size of the buffer.
char *oErrorString, // OUT: buffer for the description string.
TALKBACK_ERR *oErrorCode); // OUT: most recent TalkBack error code.
// -------------------
// Analysis functions.
// -------------------
// Gets an opaque TALKBACK_ANALYSIS object. This object is then queried with the
// TalkBackGet* functions below.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetAnalysis(
TALKBACK_ANALYSIS **ioAnalysis, // IN/OUT: address of a TALKBACK_ANALYSIS *variable where analysis will be stored.
char const *iSoundFileName, // IN: name of the sound file to analyze.
char const *iSoundText, // IN: text spoken in sound file (can be NULL to use textless analysis).
TALKBACK_ANALYSIS_SETTINGS *iSettings); // IN: pointer to a TALKBACK_ANALYSIS_SETTINGS structure (can be NULL for defaults).
// Frees an opaque TALKBACK_ANALYSIS object. This releases all memory used by
// the analysis.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackFreeAnalysis(
TALKBACK_ANALYSIS **ioAnalysis); // IN/OUT: analysis to free.
// #######################################################################
// NOTE: all functions from this point on require a valid analysis object.
// #######################################################################
// ------------------------
// Speech target functions.
// ------------------------
// Gets the number of speech target tracks.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetNumSpeechTargetTracks(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long *oResult); // OUT: number of speech target tracks.
// Gets the number of keys in the specified speech target track.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetNumSpeechTargetKeys(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iTrackNum, // IN: speech target track.
long *oResult); // OUT: number of keys in the speech target track.
// Gets key information (time, value, derivative in, and derivative out) for the
// specified key in the specified speech target track.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetSpeechTargetKeyInfo(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iTrackNum, // IN: speech target track.
long iKeyNum, // IN: speech target key.
double *oTime, // OUT: time of key.
double *oValue, // OUT: value of key.
double *oDerivativeIn, // OUT: incoming derivative of key.
double *oDerivativeOut); // OUT: outgoing derivative of key.
// Gets the value of the function curve for the specified speech target track at
// the specified time.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetSpeechTargetValueAtTime(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iTrackNum, // IN: speech target track.
double iTime, // IN: time in seconds.
double *oResult); // OUT: value of the function curve.
// Gets the derivatives of the function curve for the specified speech target
// track at the specified time.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetSpeechTargetDerivativesAtTime(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iTrackNum, // IN: speech target track.
double iTime, // IN: time in seconds.
double *oDerivativeIn, // OUT: value of the incoming derivative of the function curve.
double *oDerivativeOut); // OUT: value of the outgoing derivative of the function curve.
// -------------------------
// Speech gesture functions.
// -------------------------
// Gets the number of speech gesture tracks.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetNumGestureTracks(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long *oResult); // OUT: number of speech gesture tracks
// Gets the number of keys in the specified speech gesture track.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetNumGestureKeys(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iTrackNum, // IN: speech gesture track.
long *oResult); // OUT: number of keys in the speech gesture track.
// Gets key information (time, value, derivative in, and derivative out) for the
// specified key in the specified speech gesture track.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetGestureKeyInfo(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iTrackNum, // IN: speech gesture track.
long iKeyNum, // IN: speech gesture key.
double *oTime, // OUT: time of key.
double *oValue, // OUT: value of key.
double *oDerivativeIn, // OUT: incoming derivative of key.
double *oDerivativeOut); // OUT: outgoing derivative of key.
// Gets the value of the function curve for the specified speech gesture track
// at the specified time.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetGestureValueAtTime(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iTrackNum, // IN: speech gesture track.
double iTime, // IN: time in seconds.
double *oResult); // OUT: value of the function curve.
// Gets the derivatives of the function curve for the specified speech gesture
// track at the specified time.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetGestureDerivativesAtTime(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iTrackNum, // IN: speech gesture track.
double iTime, // IN: time in seconds.
double *oDerivativeIn, // OUT: value of the incoming derivative of the function curve.
double *oDerivativeOut); // OUT: value of the outgoing derivative of the function curve.
// ----------------
// Frame functions.
// ----------------
// NOTE: these functions use the frame rate specified in the
// TALKBACK_ANALYSIS_SETTINGS structure passed to TalkBackGetAnalysis() and
// default to 30 fps (TALKBACK_DEFAULT_FRAME_RATE) if the structure pointer was
// NULL.
// Gets the first frame number.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetFirstFrameNum(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long *oResult); // OUT: number of the first frame.
// Gets the last frame number.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetLastFrameNum(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long *oResult); // OUT: number of the last frame.
// Gets the start time of the specified frame.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetFrameStartTime(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iFrameNum, // IN: frame.
double *oResult); // OUT: start time of the frame in seconds.
// Gets the end time of the specified frame.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetFrameEndTime(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iFrameNum, // IN: frame.
double *oResult); // OUT: end time of the frame in seconds.
// Gets the value of the function curve for a speech target integrated over the
// specified frame.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetSpeechTargetValueAtFrame(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iTrackNum, // IN: speech target track.
long iFrameNum, // IN: frame number.
double *oResult); // OUT: value of the function curve integrated over the frame.
// Gets the dominant speech target at the specified frame.
//
// NOTE: this function is meant to be used in flipbook mode only.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetDominantSpeechTargetAtFrame(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iFrameNum, // IN: frame number.
TALKBACK_SPEECH_TARGET *oSpeechTarget); // OUT: dominant speech target.
// Gets the value of the function curve for a speech gesture integrated over the
// specified frame.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetGestureValueAtFrame(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iTrackNum, // IN: speech gesture track.
long iFrameNum, // IN: frame number.
double *oResult); // OUT: value of the function curve integrated over the frame.
// ------------------
// Phoneme functions.
// ------------------
// Gets the number of phonemes.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetNumPhonemes(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long *oResult); // OUT: number of phonemes.
// Gets the enumeration of the specified phoneme.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetPhonemeEnum(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iPhonemeNum, // IN: phoneme.
TALKBACK_PHONEME *oResult); // OUT: enumeration of the specified phoneme.
// Gets the start time of the specified phoneme.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetPhonemeStartTime(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iPhonemeNum, // IN: phoneme.
double *oResult); // OUT: start time of the phoneme in seconds.
// Gets the end time of the specified phoneme.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetPhonemeEndTime(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iPhonemeNum, // IN: phoneme.
double *oResult); // OUT: end time of the phoneme in seconds.
// ---------------
// Word functions.
// ---------------
// NOTE: these functions only yield data for text-based analysis.
// Gets the number of words.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetNumWords(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long *oResult); // OUT: number of words.
// Gets the text of the specified word.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetWord(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iWordNum, // IN: word.
long iMaxChars, // IN: size of word buffer.
char *oWord); // OUT: word buffer.
// Gets the start time of the specified word.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetWordStartTime(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iWordNum, // IN: word.
double *oResult); // OUT: start time of the word in seconds.
// Gets the end time of the specified word.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackGetWordEndTime(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iWordNum, // IN: word.
double *oResult); // OUT: end time of the word in seconds.
// --------------------------
// Phoneme editing functions.
// --------------------------
// Use these functions to modify the phoneme list after you get an opaque
// analysis object from TalkBackGetAnalysis(). After modifying the phoneme list
// in the opaque analysis object, subsequent TalkBackGet* calls on that opaque
// analysis object for speech target (lip-synching) data will return values
// based on the modified phoneme list. However, speech gesture data is not
// affected by phoneme editing.
//
// NOTE: phoneme editing is only provided in order to support Ventriloquist-like
// applications where tweaking of the phoneme segmenation (and subsequent
// recalculation of the animation data) is required. Most customers probably
// won't need this functionality.
// Inserts a phoneme at the specified position in the specified manner.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackInsertPhoneme(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
TALKBACK_PHONEME iPhoneme, // IN: enumeration of phoneme to insert.
long iInsertPosition, // IN: position (phoneme number) at which to insert.
int iInsertBefore); // IN: manner of insertion:
// 0 means put phoneme after insert position;
// 1 means put phoneme before insert position.
// Deletes the specified phoneme.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackDeletePhoneme(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iPhonemeToDelete); // IN: phoneme to delete.
// Changes the start time of the specified phoneme.
//
// NOTE: the start time specified may not be the actual start time for a number
// of reasons, most notably if the specified start time will make the phoneme
// too short. This function returns the actual start time so the caller can
// check the result without having to query the phoneme.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackChangePhonemeStart(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iPhonemeToChange, // IN: phoneme to change.
double *ioNewTime); // IN/OUT: new start time value in seconds (in); actual start time (out).
// Changes the end time of the specified phoneme.
//
// NOTE: the end time specified may not be the actual end time for a number of
// reasons, most notably if the specified end time will make the phoneme too
// short. This function returns the actual end time so the caller can check the
// result without having to query the phoneme.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackChangePhonemeEnd(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iPhonemeToChange, // IN: phoneme to change.
double *ioNewTime); // IN/OUT: new end time value in seconds (in); actual end time (out).
// Changes the enumeration of the specified phoneme.
TALKBACK_ERR // RETURNS: TALKBACK_NOERR if successful, TalkBack error code if not.
TalkBackChangePhonemeEnum(
TALKBACK_ANALYSIS *iAnalysis, // IN: opaque analysis object returned by TalkBackGetAnalysis().
long iPhonemeToChange, // IN: phoneme to change.
TALKBACK_PHONEME iNewPhoneme); // IN: new phoneme enumeration.
#if defined(__cplusplus)
}
#endif
#endif

View File

@@ -0,0 +1,73 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
// QC_Eyes.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "QC_Eyes.h"
#include "QC_EyesDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CQC_EyesApp
BEGIN_MESSAGE_MAP(CQC_EyesApp, CWinApp)
//{{AFX_MSG_MAP(CQC_EyesApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CQC_EyesApp construction
CQC_EyesApp::CQC_EyesApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CQC_EyesApp object
CQC_EyesApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CQC_EyesApp initialization
BOOL CQC_EyesApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#endif
CQC_EyesDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}

View File

@@ -0,0 +1,50 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
// QC_Eyes.h : main header file for the QC_EYES application
//
#if !defined(AFX_QC_EYES_H__398BAF8D_D3C0_4326_BEF0_5129884EE1A3__INCLUDED_)
#define AFX_QC_EYES_H__398BAF8D_D3C0_4326_BEF0_5129884EE1A3__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CQC_EyesApp:
// See QC_Eyes.cpp for the implementation of this class
//
class CQC_EyesApp : public CWinApp
{
public:
CQC_EyesApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CQC_EyesApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CQC_EyesApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_QC_EYES_H__398BAF8D_D3C0_4326_BEF0_5129884EE1A3__INCLUDED_)

View File

@@ -0,0 +1,276 @@
// Microsoft Visual C++ generated resource script.
//
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""afxres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"#define _AFX_NO_SPLITTER_RESOURCES\r\n"
"#define _AFX_NO_OLE_RESOURCES\r\n"
"#define _AFX_NO_TRACKER_RESOURCES\r\n"
"#define _AFX_NO_PROPERTY_RESOURCES\r\n"
"\r\n"
"#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\r\n"
"#ifdef _WIN32\r\n"
"LANGUAGE 9, 1\r\n"
"#pragma code_page(1252)\r\n"
"#endif //_WIN32\r\n"
"#include ""res\\QC_Eyes.rc2"" // non-Microsoft Visual C++ edited resources\r\n"
"#include ""afxres.rc"" // Standard components\r\n"
"#endif\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDR_MAINFRAME ICON "res\\QC_Eyes.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_QC_EYES_DIALOG DIALOGEX 0, 0, 695, 510
STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION |
WS_SYSMENU
EXSTYLE WS_EX_APPWINDOW
CAPTION "QC Eyes"
FONT 8, "MS Sans Serif", 0, 0, 0x1
BEGIN
EDITTEXT IDC_REFERENCE_FILENAME,87,24,93,14,ES_AUTOHSCROLL
EDITTEXT IDC_EXPRESSIONS_FILENAME,87,42,93,14,ES_AUTOHSCROLL
EDITTEXT IDC_MODEL_FILENAME,87,60,93,14,ES_AUTOHSCROLL
EDITTEXT IDC_RIGHT_EYE_X,19,140,40,14,ES_AUTOHSCROLL
EDITTEXT IDC_RIGHT_EYE_Y,83,140,40,14,ES_AUTOHSCROLL
EDITTEXT IDC_RIGHT_EYE_Z,147,140,40,14,ES_AUTOHSCROLL
EDITTEXT IDC_LEFT_EYE_X,19,205,40,14,ES_AUTOHSCROLL
EDITTEXT IDC_LEFT_EYE_Y,83,205,40,14,ES_AUTOHSCROLL
EDITTEXT IDC_LEFT_EYE_Z,147,205,40,14,ES_AUTOHSCROLL
GROUPBOX "3D Platform",IDC_STATIC,219,7,126,47
GROUPBOX "Options",IDC_STATIC,219,58,126,47
GROUPBOX "Upper Lid Positions",IDC_STATIC,219,109,126,60
EDITTEXT IDC_UPPER_LID_RAISED,264,118,74,14,ES_AUTOHSCROLL
EDITTEXT IDC_UPPER_LID_NEUTRAL,264,134,74,14,ES_AUTOHSCROLL
EDITTEXT IDC_UPPER_LID_LOWERED,264,150,74,14,ES_AUTOHSCROLL
EDITTEXT IDC_LOWER_LID_RAISED,264,184,74,14,ES_AUTOHSCROLL
EDITTEXT IDC_LOWER_LID_NEUTRAL,264,200,74,14,ES_AUTOHSCROLL
EDITTEXT IDC_LOWER_LID_LOWERED,264,216,74,14,ES_AUTOHSCROLL
GROUPBOX "Iris Color",IDC_STATIC,351,175,75,60
GROUPBOX "Eye White Color",IDC_STATIC,431,175,126,60
EDITTEXT IDC_IRIS_SIZE,469,21,59,14,ES_AUTOHSCROLL
EDITTEXT IDC_EYEBALL_SIZE,469,43,59,14,ES_AUTOHSCROLL
PUSHBUTTON "Create QC Text",IDC_CREATE_QC_TEXT,7,243,93,19
PUSHBUTTON "Copy Text To Clipboard",IDC_COPY_TEXT_TO_CLIPBOARD,109,
243,93,19
EDITTEXT IDC_OUTPUT_TEXT,7,271,681,232,ES_MULTILINE |
ES_AUTOHSCROLL
CONTROL "Y Axis Up (XSI, Maya)",IDC_Y_AXIS_UP,"Button",
BS_AUTORADIOBUTTON | WS_GROUP,228,21,92,10
CONTROL "Z Axis Up (MAX)",IDC_Z_AXIS_UP,"Button",
BS_AUTORADIOBUTTON,228,36,94,10
CONTROL "Default Controls",IDC_DEFAULT_CONTROLS,"Button",
BS_AUTORADIOBUTTON | WS_GROUP,228,72,92,10
CONTROL "Advanced Controls",IDC_ADVANCED_CONTROLS,"Button",
BS_AUTORADIOBUTTON,228,88,94,10
RADIOBUTTON "Brown Irises",IDC_IRIS_COLOR_BROWN,360,188,55,10,
WS_GROUP
RADIOBUTTON "Green Irises",IDC_IRIS_COLOR_GREEN,360,203,54,10
RADIOBUTTON "Blue Irises",IDC_IRIS_COLOR_BLUE,360,218,54,10
RADIOBUTTON "Light Whites (paler skin tones)",IDC_EYE_COLOR_LIGHT,
438,193,108,10,WS_GROUP
RADIOBUTTON "Dark Whites (darker skin tones)",IDC_EYE_COLOR_DARK,438,
214,112,10
RTEXT "Reference Filename:",IDC_STATIC,13,27,70,8
RTEXT "Expressions Filename:",IDC_STATIC,13,45,70,8
RTEXT "Model Filename:",IDC_STATIC,13,64,70,8
LTEXT ".SMD",IDC_STATIC,184,29,19,8
LTEXT ".VTA",IDC_STATIC,184,47,17,8
LTEXT ".MDL",IDC_STATIC,184,65,18,8
GROUPBOX "Eye Positions",IDC_STATIC,7,95,200,140
GROUPBOX "Right Eye",IDC_STATIC,14,108,185,56
LTEXT "Y Position",IDC_STATIC,85,126,32,8
LTEXT "X Position",IDC_STATIC,21,126,32,8
LTEXT "Z Position",IDC_STATIC,149,126,32,8
GROUPBOX "Left Eye",IDC_STATIC,14,173,185,56
LTEXT "Y Position",IDC_STATIC,85,191,32,8
LTEXT "X Position",IDC_STATIC,21,191,32,8
LTEXT "Z Position",IDC_STATIC,149,191,32,8
GROUPBOX "Filenames",IDC_STATIC,7,7,200,78
CONTROL "",IDC_PICTURES,"Static",SS_BITMAP,352,7,336,162
RTEXT "Raised:",IDC_STATIC,228,122,32,8
RTEXT "Neutral:",IDC_STATIC,227,137,32,8
RTEXT "Lowered:",IDC_STATIC,227,153,32,8
GROUPBOX "Lowered Lid Positions",IDC_STATIC,219,175,126,60
RTEXT "Raised:",IDC_STATIC,228,188,32,8
RTEXT "Neutral:",IDC_STATIC,227,204,32,8
RTEXT "Lowered:",IDC_STATIC,227,220,32,8
GROUPBOX "Eye Detail Control",IDC_EYE_DETAIL_CONTROL_FRAME,414,7,
140,73
RTEXT "Iris Size:",IDC_IRIS_SIZE_LABEL,417,25,48,8
RTEXT "Eyeball Size:",IDC_EYEBALL_SIZE_LABEL,417,47,48,8
CTEXT "",IDC_PICTURE_LABEL,375,162,285,8
CONTROL "Enable Independent Left Lid Control",
IDC_LEFT_LID_CONTROL,"Button",BS_AUTOCHECKBOX |
WS_TABSTOP,421,62,128,10
GROUPBOX "Upper Left Lid Positions",IDC_UPPER_LEFT_LID_PANEL,562,
7,126,60
EDITTEXT IDC_UPPER_LEFT_LID_RAISED,607,16,74,14,ES_AUTOHSCROLL
EDITTEXT IDC_UPPER_LEFT_LID_NEUTRAL,607,32,74,14,ES_AUTOHSCROLL
EDITTEXT IDC_UPPER_LEFT_LID_LOWERED,607,48,74,14,ES_AUTOHSCROLL
EDITTEXT IDC_LOWER_LEFT_LID_RAISED,607,82,74,14,ES_AUTOHSCROLL
EDITTEXT IDC_LOWER_LEFT_LID_NEUTRAL,607,98,74,14,ES_AUTOHSCROLL
EDITTEXT IDC_LOWER_LEFT_LID_LOWERED,607,114,74,14,ES_AUTOHSCROLL
RTEXT "Raised:",IDC_UPPER_LEFT_LID_RAISED_LABEL,571,20,32,8
RTEXT "Neutral:",IDC_UPPER_LEFT_LID_NEUTRAL_LABEL,570,35,32,8
RTEXT "Lowered:",IDC_UPPER_LEFT_LID_LOWERED_LABEL,570,51,32,8
GROUPBOX "Lowered Left Lid Positions",IDC_LOWER_LEFT_LID_PANEL,
562,73,126,60
RTEXT "Raised:",IDC_LOWER_LEFT_LID_RAISED_LABEL,571,86,32,8
RTEXT "Neutral:",IDC_LOWER_LEFT_LID_NEUTRAL_LABEL,570,102,32,8
RTEXT "Lowered:",IDC_LOWER_LEFT_LID_LOWERED_LABEL,570,118,32,8
END
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,0,1
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x1L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904B0"
BEGIN
VALUE "FileDescription", "QC_Eyes MFC Application"
VALUE "FileVersion", "1, 0, 0, 1"
VALUE "InternalName", "QC_Eyes"
VALUE "LegalCopyright", "Copyright (C) 2005"
VALUE "OriginalFilename", "QC_Eyes.EXE"
VALUE "ProductName", "QC_Eyes Application"
VALUE "ProductVersion", "1, 0, 0, 1"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200
END
END
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO
BEGIN
IDD_QC_EYES_DIALOG, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 688
TOPMARGIN, 7
BOTTOMMARGIN, 503
END
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Bitmap
//
IDB_EYE_DEFAULT BITMAP "res\\eye_default.bmp"
IDB_EYE_LOWER_HI BITMAP "res\\eye_lower_hi.bmp"
IDB_EYE_LOWER_LO BITMAP "res\\eye_lower_lo.bmp"
IDB_EYE_LOWER_MID BITMAP "res\\eye_lower_mid.bmp"
IDB_EYE_UPPER_HI BITMAP "res\\eye_upper_hi.bmp"
IDB_EYE_UPPER_LO BITMAP "res\\eye_upper_lo.bmp"
IDB_EYE_UPPER_MID BITMAP "res\\eye_upper_mid.bmp"
IDB_EYE_XY_L BITMAP "res\\eye_xy_l.bmp"
IDB_EYE_XY_R BITMAP "res\\eye_xy_r.bmp"
IDB_EYE_Z_L BITMAP "res\\eye_z_l.bmp"
IDB_EYE_Z_R BITMAP "res\\eye_z_r.bmp"
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
#define _AFX_NO_SPLITTER_RESOURCES
#define _AFX_NO_OLE_RESOURCES
#define _AFX_NO_TRACKER_RESOURCES
#define _AFX_NO_PROPERTY_RESOURCES
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE 9, 1
#pragma code_page(1252)
#endif //_WIN32
#include "res\QC_Eyes.rc2" // non-Microsoft Visual C++ edited resources
#include "afxres.rc" // Standard components
#endif
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@@ -0,0 +1,705 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
// QC_EyesDlg.cpp : implementation file
//
#include "stdafx.h"
#include <math.h>
#include "QC_Eyes.h"
#include "QC_EyesDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CQC_EyesDlg dialog
CQC_EyesDlg::CQC_EyesDlg(CWnd* pParent /*=NULL*/)
: CDialog(CQC_EyesDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CQC_EyesDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_pBitmapHead = NULL;
}
void CQC_EyesDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CQC_EyesDlg)
DDX_Control(pDX, IDC_LEFT_LID_CONTROL, m_IndependentLeftLidControl);
DDX_Control(pDX, IDC_PICTURES, m_PictureControl);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CQC_EyesDlg, CDialog)
//{{AFX_MSG_MAP(CQC_EyesDlg)
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_CREATE_QC_TEXT, OnCreateQcText)
ON_BN_CLICKED(IDC_IRIS_COLOR_BROWN, OnIrisColorBrown)
ON_BN_CLICKED(IDC_IRIS_COLOR_GREEN, OnIrisColorGreen)
ON_BN_CLICKED(IDC_IRIS_COLOR_BLUE, OnIrisColorBlue)
ON_BN_CLICKED(IDC_EYE_COLOR_DARK, OnEyeColorDark)
ON_BN_CLICKED(IDC_EYE_COLOR_LIGHT, OnEyeColorLight)
ON_EN_SETFOCUS(IDC_RIGHT_EYE_X, OnSetfocusRightEyeX)
ON_EN_SETFOCUS(IDC_RIGHT_EYE_Y, OnSetfocusRightEyeY)
ON_EN_SETFOCUS(IDC_RIGHT_EYE_Z, OnSetfocusRightEyeZ)
ON_EN_SETFOCUS(IDC_LEFT_EYE_X, OnSetfocusLeftEyeX)
ON_EN_SETFOCUS(IDC_LEFT_EYE_Y, OnSetfocusLeftEyeY)
ON_EN_SETFOCUS(IDC_LEFT_EYE_Z, OnSetfocusLeftEyeZ)
ON_EN_SETFOCUS(IDC_UPPER_LID_LOWERED, OnSetfocusUpperLidLowered)
ON_EN_SETFOCUS(IDC_UPPER_LID_NEUTRAL, OnSetfocusUpperLidNeutral)
ON_EN_SETFOCUS(IDC_UPPER_LID_RAISED, OnSetfocusUpperLidRaised)
ON_EN_SETFOCUS(IDC_LOWER_LID_LOWERED, OnSetfocusLowerLidLowered)
ON_EN_SETFOCUS(IDC_LOWER_LID_NEUTRAL, OnSetfocusLowerLidNeutral)
ON_EN_SETFOCUS(IDC_LOWER_LID_RAISED, OnSetfocusLowerLidRaised)
ON_BN_CLICKED(IDC_COPY_TEXT_TO_CLIPBOARD, OnCopyTextToClipboard)
ON_BN_CLICKED(IDC_DEFAULT_CONTROLS, OnDefaultControls)
ON_BN_CLICKED(IDC_ADVANCED_CONTROLS, OnAdvancedControls)
ON_BN_CLICKED(IDC_LEFT_LID_CONTROL, OnLeftLidControl)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CQC_EyesDlg::AddText( const char *pFormat, ... )
{
char tempMsg[4096];
va_list marker;
va_start( marker, pFormat );
_vsnprintf( tempMsg, sizeof( tempMsg ), pFormat, marker );
tempMsg[ ARRAYSIZE(tempMsg) - 1 ] = 0;
va_end( marker );
size_t nCharsInBuf = strlen( m_Buf );
size_t nCharsInMsg = strlen( tempMsg );
if ( nCharsInBuf + nCharsInMsg + 1 > m_BufSize )
{
m_BufSize = nCharsInBuf + nCharsInMsg + 4096;
char *newbuf = new char[m_BufSize];
memcpy( newbuf, m_Buf, nCharsInBuf + 1 );
delete [] m_Buf;
m_Buf = newbuf;
}
strcat( m_Buf, tempMsg );
}
void SendToEditControl( HWND hEditControl, const char *pText )
{
LRESULT nLen = SendMessage( hEditControl, EM_GETLIMITTEXT, 0, 0 );
SendMessage( hEditControl, EM_SETSEL, nLen, nLen );
SendMessage( hEditControl, EM_REPLACESEL, FALSE, (LPARAM)pText );
}
void FormatAndSendToEditControl( void *hWnd, const char *pText )
{
HWND hEditControl = (HWND)hWnd;
// Translate \n to \r\n.
char outMsg[1024];
const char *pIn = pText;
char *pOut = outMsg;
while ( *pIn )
{
if ( *pIn == '\n' )
{
*pOut = '\r';
pOut++;
}
*pOut = *pIn;
++pIn;
++pOut;
if ( pOut - outMsg >= 1020 )
{
*pOut = 0;
SendToEditControl( hEditControl, outMsg );
pOut = outMsg;
}
}
*pOut = 0;
SendToEditControl( hEditControl, outMsg );
}
HBITMAP CQC_EyesDlg::GetCachedBitmap( UINT id )
{
for ( CBitmapRef *pCur=m_pBitmapHead; pCur; pCur=pCur->m_pNext )
{
if ( pCur->m_iResource == id )
return pCur->m_hBitmap;
}
CBitmapRef *pNew = new CBitmapRef;
pNew->m_iResource = id;
pNew->m_hBitmap = ::LoadBitmap( AfxGetInstanceHandle(), MAKEINTRESOURCE(id) );
pNew->m_pNext = m_pBitmapHead;
m_pBitmapHead = pNew;
return pNew->m_hBitmap;
}
/////////////////////////////////////////////////////////////////////////////
// CQC_EyesDlg message handlers
BOOL CQC_EyesDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
GetDlgItem( IDC_REFERENCE_FILENAME )->SetWindowText( "filename_reference" );
GetDlgItem( IDC_EXPRESSIONS_FILENAME )->SetWindowText( "filename_expressions" );
GetDlgItem( IDC_MODEL_FILENAME )->SetWindowText( "filename_model" );
GetDlgItem( IDC_IRIS_SIZE )->SetWindowText( "0.63" );
GetDlgItem( IDC_EYEBALL_SIZE )->SetWindowText( "1.0" );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_Y_AXIS_UP ), BM_SETCHECK, BST_CHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_DEFAULT_CONTROLS ), BM_SETCHECK, BST_CHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_IRIS_COLOR_BROWN ), BM_SETCHECK, BST_CHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_EYE_COLOR_LIGHT ), BM_SETCHECK, BST_CHECKED, 0 );
m_hOutputText = ::GetDlgItem( m_hWnd, IDC_OUTPUT_TEXT );
m_PictureControl.SetBitmap( GetCachedBitmap( IDB_EYE_DEFAULT ) );
OnDefaultControls(); // Hide the advanced controls.
return TRUE; // return TRUE unless you set the focus to a control
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CQC_EyesDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CQC_EyesDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
void HandleYAxisUp( float &yVal, float &zVal )
{
float flTemp = yVal;
yVal = -zVal;
zVal = flTemp;
}
float CQC_EyesDlg::GetDlgItemFloat( UINT id )
{
char text[4096];
GetDlgItemText( id, text, sizeof( text ) );
return (float)atof( text );
}
bool CQC_EyesDlg::IsOptionChecked( UINT option )
{
return (::SendMessage( ::GetDlgItem( m_hWnd, option ), BM_GETCHECK, 0, 0 ) == BST_CHECKED);
}
void CQC_EyesDlg::GetDialogParams( CDialogParams &p )
{
p.m_flLeftEye[0] = GetDlgItemFloat( IDC_LEFT_EYE_X );
p.m_flLeftEye[1] = GetDlgItemFloat( IDC_LEFT_EYE_Y );
p.m_flLeftEye[2] = GetDlgItemFloat( IDC_LEFT_EYE_Z );
p.m_flRightEye[0] = GetDlgItemFloat( IDC_RIGHT_EYE_X );
p.m_flRightEye[1] = GetDlgItemFloat( IDC_RIGHT_EYE_Y );
p.m_flRightEye[2] = GetDlgItemFloat( IDC_RIGHT_EYE_Z );
bool bYAxisUp = IsOptionChecked( IDC_Y_AXIS_UP );
if ( bYAxisUp )
{
HandleYAxisUp( p.m_flLeftEye[1], p.m_flLeftEye[2] );
HandleYAxisUp( p.m_flRightEye[1], p.m_flRightEye[2] );
}
GetDlgItemText( IDC_REFERENCE_FILENAME, p.m_ReferenceFilename, sizeof( p.m_ReferenceFilename ) );
GetDlgItemText( IDC_EXPRESSIONS_FILENAME, p.m_ExpressionsFilename, sizeof( p.m_ExpressionsFilename ) );
GetDlgItemText( IDC_MODEL_FILENAME, p.m_ModelFilename, sizeof( p.m_ModelFilename ) );
p.m_flIrisSize = GetDlgItemFloat( IDC_IRIS_SIZE );
p.m_flEyeballSize = GetDlgItemFloat( IDC_EYEBALL_SIZE );
p.m_flRightUpperLidRaised = GetDlgItemFloat( IDC_UPPER_LID_RAISED );
p.m_flRightUpperLidNeutral = GetDlgItemFloat( IDC_UPPER_LID_NEUTRAL );
p.m_flRightUpperLidLowered = GetDlgItemFloat( IDC_UPPER_LID_LOWERED );
p.m_flRightLowerLidRaised = GetDlgItemFloat( IDC_LOWER_LID_RAISED );
p.m_flRightLowerLidNeutral = GetDlgItemFloat( IDC_LOWER_LID_NEUTRAL );
p.m_flRightLowerLidLowered = GetDlgItemFloat( IDC_LOWER_LID_LOWERED );
if ( IsIndependentLeftLidControlEnabled() )
{
p.m_flLeftUpperLidRaised = GetDlgItemFloat( IDC_UPPER_LEFT_LID_RAISED );
p.m_flLeftUpperLidNeutral = GetDlgItemFloat( IDC_UPPER_LEFT_LID_NEUTRAL );
p.m_flLeftUpperLidLowered = GetDlgItemFloat( IDC_UPPER_LEFT_LID_LOWERED );
p.m_flLeftLowerLidRaised = GetDlgItemFloat( IDC_LOWER_LEFT_LID_RAISED );
p.m_flLeftLowerLidNeutral = GetDlgItemFloat( IDC_LOWER_LEFT_LID_NEUTRAL );
p.m_flLeftLowerLidLowered = GetDlgItemFloat( IDC_LOWER_LEFT_LID_LOWERED );
}
else
{
// Left lids follow the right lids.
p.m_flLeftUpperLidRaised = p.m_flRightUpperLidRaised;
p.m_flLeftUpperLidNeutral = p.m_flRightUpperLidNeutral;
p.m_flLeftUpperLidLowered = p.m_flRightUpperLidLowered;
p.m_flLeftLowerLidRaised = p.m_flRightLowerLidRaised;
p.m_flLeftLowerLidNeutral = p.m_flRightLowerLidNeutral;
p.m_flLeftLowerLidLowered = p.m_flRightLowerLidLowered;
}
// Figure out the eyeball prefix.
if ( IsOptionChecked( IDC_EYE_COLOR_LIGHT ) )
strcpy( p.m_EyeballPrefix, "eyeball" );
else
strcpy( p.m_EyeballPrefix, "dark_eyeball" );
// Figure out the pupil prefix.
if ( IsOptionChecked( IDC_IRIS_COLOR_BROWN ) )
strcpy( p.m_PupilPrefix, "pupil" );
else if ( IsOptionChecked( IDC_IRIS_COLOR_GREEN ) )
strcpy( p.m_PupilPrefix, "grn_pupil" );
else
strcpy( p.m_PupilPrefix, "bl_pupil" );
}
void CQC_EyesDlg::GenerateQCText()
{
CDialogParams p;
GetDialogParams( p );
m_BufSize = 16 * 1024;
m_Buf = new char[m_BufSize];
m_Buf[0] = 0;
AddText( "//start eye/face data\n" );
AddText( "$eyeposition 0 0 70\n\n" );
AddText( "//head controllers\n" );
AddText( "$attachment \"eyes\" \"ValveBiped.Bip01_Head1\" %.2f %.2f %.2f absolute\n",
p.m_flLeftEye[0] - ((fabs( p.m_flRightEye[0] ) + p.m_flLeftEye[0]) * 0.5),
(p.m_flLeftEye[1] + p.m_flRightEye[1]) * 0.5,
(p.m_flLeftEye[2] + p.m_flRightEye[2]) * 0.5 );
AddText( "$attachment \"mouth\" \"ValveBiped.Bip01_Head1\" 0.80 -5.80 -0.15 rotate 0 -80 -90\n\n" );
AddText( "$model %s \"%s.smd\" {\n",
p.m_ModelFilename, p.m_ReferenceFilename );
AddText( "\teyeball righteye \"ValveBiped.Bip01_Head1\" %.2f %.2f %.2f \"%s_r\" %.2f 4 \"%s_r\" %.2f\n",
p.m_flRightEye[0],
p.m_flRightEye[1],
p.m_flRightEye[2],
p.m_EyeballPrefix,
p.m_flEyeballSize,
p.m_PupilPrefix,
p.m_flIrisSize );
AddText( "\teyeball lefteye \"ValveBiped.Bip01_Head1\" %.2f %.2f %.2f \"%s_l\" %.2f -4 \"%s_l\" %.2f\n\n",
p.m_flLeftEye[0],
p.m_flLeftEye[1],
p.m_flLeftEye[2],
p.m_EyeballPrefix,
p.m_flEyeballSize,
p.m_PupilPrefix,
p.m_flIrisSize );
AddText( "\teyelid upper_right \"%s\" lowerer 1 %.2f neutral 0 %.2f raiser 2 %.2f split 0.1 eyeball righteye\n",
p.m_ExpressionsFilename,
p.m_flRightUpperLidLowered - p.m_flRightEye[2],
p.m_flRightUpperLidNeutral - p.m_flRightEye[2],
p.m_flRightUpperLidRaised - p.m_flRightEye[2] );
AddText( "\teyelid lower_right \"%s\" lowerer 3 %.2f neutral 0 %.2f raiser 4 %.2f split 0.1 eyeball righteye\n",
p.m_ExpressionsFilename,
p.m_flRightLowerLidLowered - p.m_flRightEye[2],
p.m_flRightLowerLidNeutral - p.m_flRightEye[2],
p.m_flRightLowerLidRaised - p.m_flRightEye[2] );
AddText( "\teyelid upper_left \"%s\" lowerer 1 %.2f neutral 0 %.2f raiser 2 %.2f split -0.1 eyeball lefteye\n",
p.m_ExpressionsFilename,
p.m_flLeftUpperLidLowered - p.m_flLeftEye[2],
p.m_flLeftUpperLidNeutral - p.m_flLeftEye[2],
p.m_flLeftUpperLidRaised - p.m_flLeftEye[2] );
AddText( "\teyelid lower_left \"%s\" lowerer 3 %.2f neutral 0 %.2f raiser 4 %.2f split -0.1 eyeball lefteye\n\n",
p.m_ExpressionsFilename,
p.m_flLeftLowerLidLowered - p.m_flLeftEye[2],
p.m_flLeftLowerLidNeutral - p.m_flLeftEye[2],
p.m_flLeftLowerLidRaised - p.m_flLeftEye[2] );
AddText( "\tmouth 0 \"mouth\" \"ValveBiped.Bip01_Head1\" 0 1 0 // mouth illumination\n" );
AddText( "\tflexfile \"%s\" {\n", p.m_ExpressionsFilename );
AddText( "\t\t$include \"../standardflex_xsi.qci\"\n" );
AddText( "\t}\n" );
AddText( "\t$include \"../facerules_xsi.qci\"\n" );
AddText( "\t$include \"../bodyrules_xsi.qci\"\n" );
AddText( "}\n" );
AddText( "//end eye/face data\n" );
}
bool CQC_EyesDlg::CheckNumericInputs()
{
struct
{
const char *pControlName;
UINT controlID;
}
controls[] =
{
{"Right Eye X", IDC_RIGHT_EYE_X},
{"Right Eye Y", IDC_RIGHT_EYE_Y},
{"Right Eye Z", IDC_RIGHT_EYE_Z},
{"Left Eye X", IDC_LEFT_EYE_X},
{"Left Eye Y", IDC_LEFT_EYE_Y},
{"Left Eye Z", IDC_LEFT_EYE_Z},
{"Upper Lid Raised", IDC_UPPER_LID_RAISED},
{"Upper Lid Neutral", IDC_UPPER_LID_NEUTRAL},
{"Upper Lid Lowered", IDC_UPPER_LID_LOWERED},
{"Lower Lid Raised", IDC_LOWER_LID_RAISED},
{"Lower Lid Neutral", IDC_LOWER_LID_NEUTRAL},
{"Lower Lid Lowered", IDC_LOWER_LID_LOWERED},
{"Upper Left Lid Raised", IDC_UPPER_LEFT_LID_RAISED},
{"Upper Left Lid Neutral", IDC_UPPER_LEFT_LID_NEUTRAL},
{"Upper Left Lid Lowered", IDC_UPPER_LEFT_LID_LOWERED},
{"Lower Left Lid Raised", IDC_LOWER_LEFT_LID_RAISED},
{"Lower Left Lid Neutral", IDC_LOWER_LEFT_LID_NEUTRAL},
{"Lower Left Lid Lowered", IDC_LOWER_LEFT_LID_LOWERED},
{"Iris Size", IDC_IRIS_SIZE},
{"Eyeball Size", IDC_EYEBALL_SIZE}
};
for ( int i=0; i < sizeof( controls ) / sizeof( controls[0] ); i++ )
{
char text[512];
GetDlgItem( controls[i].controlID )->GetWindowText( text, sizeof( text ) );
for ( int z=0; z < (int)strlen( text ); z++ )
{
if ( text[z] < '0' || text[z] > '9' )
{
if ( text[z] != '.' && text[z] != '-' )
{
char errMsg[512];
_snprintf( errMsg, sizeof( errMsg ), "The '%s' control must have a numeric value.", controls[i].pControlName );
AfxMessageBox( errMsg, MB_OK );
return false;
}
}
}
}
return true;
}
void CQC_EyesDlg::OnCreateQcText()
{
if ( !CheckNumericInputs() )
return;
GenerateQCText();
// Clear the edit control.
LRESULT nLen = ::SendMessage( m_hOutputText, EM_GETLIMITTEXT, 0, 0 );
::SendMessage( m_hOutputText, EM_SETSEL, 0, nLen );
::SendMessage( m_hOutputText, EM_REPLACESEL, FALSE, (LPARAM)"" );
FormatAndSendToEditControl( m_hOutputText, m_Buf );
delete [] m_Buf;
}
void CQC_EyesDlg::OnIrisColorBrown()
{
::SendMessage( ::GetDlgItem( m_hWnd, IDC_IRIS_COLOR_BROWN ), BM_SETCHECK, BST_CHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_IRIS_COLOR_GREEN ), BM_SETCHECK, BST_UNCHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_IRIS_COLOR_BLUE ), BM_SETCHECK, BST_UNCHECKED, 0 );
SetupBitmapLabel( IDB_EYE_DEFAULT, "" );
}
void CQC_EyesDlg::OnIrisColorGreen()
{
::SendMessage( ::GetDlgItem( m_hWnd, IDC_IRIS_COLOR_BROWN ), BM_SETCHECK, BST_UNCHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_IRIS_COLOR_GREEN ), BM_SETCHECK, BST_CHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_IRIS_COLOR_BLUE ), BM_SETCHECK, BST_UNCHECKED, 0 );
SetupBitmapLabel( IDB_EYE_DEFAULT, "" );
}
void CQC_EyesDlg::OnIrisColorBlue()
{
::SendMessage( ::GetDlgItem( m_hWnd, IDC_IRIS_COLOR_BROWN ), BM_SETCHECK, BST_UNCHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_IRIS_COLOR_GREEN ), BM_SETCHECK, BST_UNCHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_IRIS_COLOR_BLUE ), BM_SETCHECK, BST_CHECKED, 0 );
SetupBitmapLabel( IDB_EYE_DEFAULT, "" );
}
void CQC_EyesDlg::OnEyeColorDark()
{
::SendMessage( ::GetDlgItem( m_hWnd, IDC_EYE_COLOR_LIGHT ), BM_SETCHECK, BST_UNCHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_EYE_COLOR_DARK ), BM_SETCHECK, BST_CHECKED, 0 );
SetupBitmapLabel( IDB_EYE_DEFAULT, "" );
}
void CQC_EyesDlg::OnEyeColorLight()
{
::SendMessage( ::GetDlgItem( m_hWnd, IDC_EYE_COLOR_LIGHT ), BM_SETCHECK, BST_CHECKED, 0 );
::SendMessage( ::GetDlgItem( m_hWnd, IDC_EYE_COLOR_DARK ), BM_SETCHECK, BST_UNCHECKED, 0 );
SetupBitmapLabel( IDB_EYE_DEFAULT, "" );
}
void CQC_EyesDlg::SetupBitmapLabel( UINT iBitmapResourceID, const char *pString, ... )
{
char msg[4096];
va_list marker;
va_start( marker, pString );
_vsnprintf( msg, sizeof( msg ), pString, marker );
msg[ ARRAYSIZE(msg) - 1 ] = 0;
va_end( marker );
m_PictureControl.SetBitmap( GetCachedBitmap( iBitmapResourceID ) );
GetDlgItem( IDC_PICTURE_LABEL )->SetWindowText( msg );
}
void CQC_EyesDlg::OnSetfocusRightEyeX()
{
SetupBitmapLabel( IDB_EYE_XY_R, "Enter the X position of the center vertex of the right eye" );
}
void CQC_EyesDlg::OnSetfocusRightEyeY()
{
SetupBitmapLabel( IsOptionChecked( IDC_Y_AXIS_UP ) ? IDB_EYE_XY_R : IDB_EYE_Z_R, "Enter the Y position of the center vertex of the right eye" );
}
void CQC_EyesDlg::OnSetfocusRightEyeZ()
{
SetupBitmapLabel( IsOptionChecked( IDC_Y_AXIS_UP ) ? IDB_EYE_Z_R : IDB_EYE_XY_R, "Enter the Z position of the center vertex of the right eye" );
}
void CQC_EyesDlg::OnSetfocusLeftEyeX()
{
SetupBitmapLabel( IDB_EYE_XY_L, "Enter the X position of the center vertex of the right eye" );
}
void CQC_EyesDlg::OnSetfocusLeftEyeY()
{
SetupBitmapLabel( IsOptionChecked( IDC_Y_AXIS_UP ) ? IDB_EYE_XY_L : IDB_EYE_Z_L, "Enter the Y position of the center vertex of the right eye" );
}
void CQC_EyesDlg::OnSetfocusLeftEyeZ()
{
SetupBitmapLabel( IsOptionChecked( IDC_Y_AXIS_UP ) ? IDB_EYE_Z_L : IDB_EYE_XY_L, "Enter the Z position of the center vertex of the right eye" );
}
void CQC_EyesDlg::OnSetfocusUpperLidLowered()
{
const char *pCoord = IsOptionChecked( IDC_Y_AXIS_UP ) ? "Y" : "Z";
SetupBitmapLabel( IDB_EYE_UPPER_LO, "At Frame 1, enter the %s position of the center vertex of the right upper eye lid", pCoord );
}
void CQC_EyesDlg::OnSetfocusUpperLidNeutral()
{
const char *pCoord = IsOptionChecked( IDC_Y_AXIS_UP ) ? "Y" : "Z";
SetupBitmapLabel( IDB_EYE_UPPER_MID, "At Frame 0, enter the %s position of the center vertex of the right upper eye lid", pCoord );
}
void CQC_EyesDlg::OnSetfocusUpperLidRaised()
{
const char *pCoord = IsOptionChecked( IDC_Y_AXIS_UP ) ? "Y" : "Z";
SetupBitmapLabel( IDB_EYE_UPPER_HI, "At Frame 2, enter the %s position of the center vertex of the right upper eye lid", pCoord );
}
void CQC_EyesDlg::OnSetfocusLowerLidLowered()
{
const char *pCoord = IsOptionChecked( IDC_Y_AXIS_UP ) ? "Y" : "Z";
SetupBitmapLabel( IDB_EYE_LOWER_LO, "At Frame 3, enter the %s position of the center vertex of the right lower eye lid", pCoord );
}
void CQC_EyesDlg::OnSetfocusLowerLidNeutral()
{
const char *pCoord = IsOptionChecked( IDC_Y_AXIS_UP ) ? "Y" : "Z";
SetupBitmapLabel( IDB_EYE_LOWER_MID, "At Frame 0, enter the %s position of the center vertex of the right lower eye lid", pCoord );
}
void CQC_EyesDlg::OnSetfocusLowerLidRaised()
{
const char *pCoord = IsOptionChecked( IDC_Y_AXIS_UP ) ? "Y" : "Z";
SetupBitmapLabel( IDB_EYE_LOWER_HI, "At Frame 4, enter the %s position of the center vertex of the right lower eye lid", pCoord );
}
void CQC_EyesDlg::OnCopyTextToClipboard()
{
if ( !CheckNumericInputs() )
return;
GenerateQCText();
if ( !OpenClipboard() )
return;
size_t textLen = strlen( m_Buf );
HANDLE hmem = GlobalAlloc( GMEM_MOVEABLE | GMEM_DDESHARE, textLen + 1 );
if ( hmem )
{
void *ptr = GlobalLock( hmem );
if ( ptr )
{
memcpy( ptr, m_Buf, textLen+1 );
GlobalUnlock( hmem );
SetClipboardData( CF_TEXT, hmem );
}
}
CloseClipboard();
delete [] m_Buf;
}
int g_AdvancedControls[] =
{
IDC_EYE_DETAIL_CONTROL_FRAME,
IDC_IRIS_SIZE,
IDC_IRIS_SIZE_LABEL,
IDC_EYEBALL_SIZE,
IDC_EYEBALL_SIZE_LABEL,
IDC_LEFT_LID_CONTROL
};
#define NUM_ADVANCED_CONTROLS ( sizeof( g_AdvancedControls ) / sizeof( g_AdvancedControls[0] ) )
int g_LeftLidPositionControls[] =
{
IDC_UPPER_LEFT_LID_PANEL,
IDC_UPPER_LEFT_LID_RAISED,
IDC_UPPER_LEFT_LID_RAISED_LABEL,
IDC_UPPER_LEFT_LID_NEUTRAL,
IDC_UPPER_LEFT_LID_NEUTRAL_LABEL,
IDC_UPPER_LEFT_LID_LOWERED,
IDC_UPPER_LEFT_LID_LOWERED_LABEL,
IDC_LOWER_LEFT_LID_PANEL,
IDC_LOWER_LEFT_LID_RAISED,
IDC_LOWER_LEFT_LID_RAISED_LABEL,
IDC_LOWER_LEFT_LID_NEUTRAL,
IDC_LOWER_LEFT_LID_NEUTRAL_LABEL,
IDC_LOWER_LEFT_LID_LOWERED,
IDC_LOWER_LEFT_LID_LOWERED_LABEL
};
#define NUM_LEFT_LID_POSITION_CONTROLS ( sizeof( g_LeftLidPositionControls ) / sizeof( g_LeftLidPositionControls[0] ) )
void CQC_EyesDlg::OnDefaultControls()
{
GetDlgItem( IDC_PICTURES )->ShowWindow( SW_SHOW );
// Hide all the advanced controls.
for ( int i=0; i < NUM_ADVANCED_CONTROLS; i++ )
{
GetDlgItem( g_AdvancedControls[i] )->ShowWindow( SW_HIDE );
}
for ( int i=0; i < NUM_LEFT_LID_POSITION_CONTROLS; i++ )
{
GetDlgItem( g_LeftLidPositionControls[i] )->ShowWindow( SW_HIDE );
}
}
void CQC_EyesDlg::OnAdvancedControls()
{
GetDlgItem( IDC_PICTURES )->ShowWindow( SW_HIDE );
// Show the advanced controls.
for ( int i=0; i < NUM_ADVANCED_CONTROLS; i++ )
{
GetDlgItem( g_AdvancedControls[i] )->ShowWindow( SW_SHOW );
GetDlgItem( g_AdvancedControls[i] )->InvalidateRect( NULL );
}
if ( IsIndependentLeftLidControlEnabled() )
{
OnLeftLidControl();
}
}
bool CQC_EyesDlg::IsIndependentLeftLidControlEnabled()
{
return m_IndependentLeftLidControl.GetCheck() == 1;
}
void CQC_EyesDlg::OnLeftLidControl()
{
if ( IsIndependentLeftLidControlEnabled() )
{
for ( int i=0; i < NUM_LEFT_LID_POSITION_CONTROLS; i++ )
{
GetDlgItem( g_LeftLidPositionControls[i] )->ShowWindow( SW_SHOW );
GetDlgItem( g_LeftLidPositionControls[i] )->InvalidateRect( NULL );
}
}
else
{
for ( int i=0; i < NUM_LEFT_LID_POSITION_CONTROLS; i++ )
{
GetDlgItem( g_LeftLidPositionControls[i] )->ShowWindow( SW_HIDE );
GetDlgItem( g_LeftLidPositionControls[i] )->InvalidateRect( NULL );
}
}
}

View File

@@ -0,0 +1,134 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
// QC_EyesDlg.h : header file
//
#if !defined(AFX_QC_EYESDLG_H__9130E22D_05ED_4851_960C_38D90DA94967__INCLUDED_)
#define AFX_QC_EYESDLG_H__9130E22D_05ED_4851_960C_38D90DA94967__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CDialogParams
{
public:
float m_flLeftEye[3];
float m_flRightEye[3];
float m_flIrisSize;
float m_flEyeballSize;
float m_flLeftUpperLidRaised;
float m_flLeftUpperLidNeutral;
float m_flLeftUpperLidLowered;
float m_flLeftLowerLidRaised;
float m_flLeftLowerLidNeutral;
float m_flLeftLowerLidLowered;
float m_flRightUpperLidRaised;
float m_flRightUpperLidNeutral;
float m_flRightUpperLidLowered;
float m_flRightLowerLidRaised;
float m_flRightLowerLidNeutral;
float m_flRightLowerLidLowered;
char m_ReferenceFilename[1024];
char m_ExpressionsFilename[1024];
char m_ModelFilename[1024];
char m_EyeballPrefix[1024]; // eyeball_ or dark_eyeball_
char m_PupilPrefix[1024]; // pupil_ or grn_pupil_ or bl_pupil_
};
/////////////////////////////////////////////////////////////////////////////
// CQC_EyesDlg dialog
class CQC_EyesDlg : public CDialog
{
// Construction
public:
CQC_EyesDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CQC_EyesDlg)
enum { IDD = IDD_QC_EYES_DIALOG };
CButton m_IndependentLeftLidControl;
CStatic m_PictureControl;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CQC_EyesDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
void GenerateQCText();
void AddText( const char *pFormat, ... );
bool IsOptionChecked( UINT option );
float GetDlgItemFloat( UINT id );
void GetDialogParams( CDialogParams &p );
void SetupBitmapLabel( UINT iBitmapResourceID, const char *pString, ... );
HWND m_hOutputText;
// Cached list of bitmaps.
class CBitmapRef
{
public:
UINT m_iResource;
HBITMAP m_hBitmap;
CBitmapRef *m_pNext;
};
CBitmapRef *m_pBitmapHead;
HBITMAP GetCachedBitmap( UINT id );
size_t m_BufSize;
char *m_Buf;
bool IsIndependentLeftLidControlEnabled();
bool CheckNumericInputs();
// Generated message map functions
//{{AFX_MSG(CQC_EyesDlg)
virtual BOOL OnInitDialog();
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnCreateQcText();
afx_msg void OnIrisColorBrown();
afx_msg void OnIrisColorGreen();
afx_msg void OnIrisColorBlue();
afx_msg void OnEyeColorDark();
afx_msg void OnEyeColorLight();
afx_msg void OnSetfocusRightEyeX();
afx_msg void OnSetfocusRightEyeY();
afx_msg void OnSetfocusRightEyeZ();
afx_msg void OnSetfocusLeftEyeX();
afx_msg void OnSetfocusLeftEyeY();
afx_msg void OnSetfocusLeftEyeZ();
afx_msg void OnSetfocusUpperLidLowered();
afx_msg void OnSetfocusUpperLidNeutral();
afx_msg void OnSetfocusUpperLidRaised();
afx_msg void OnSetfocusLowerLidLowered();
afx_msg void OnSetfocusLowerLidNeutral();
afx_msg void OnSetfocusLowerLidRaised();
afx_msg void OnCopyTextToClipboard();
afx_msg void OnDefaultControls();
afx_msg void OnAdvancedControls();
afx_msg void OnLeftLidControl();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_QC_EYESDLG_H__9130E22D_05ED_4851_960C_38D90DA94967__INCLUDED_)

View File

@@ -0,0 +1,9 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
// stdafx.cpp : source file that includes just the standard includes
// QC_Eyes.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"

View File

@@ -0,0 +1,28 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#if !defined(AFX_STDAFX_H__88FA48B3_A92C_49CA_8A82_50D120A84756__INCLUDED_)
#define AFX_STDAFX_H__88FA48B3_A92C_49CA_8A82_50D120A84756__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#include <afxwin.h> // MFC core and standard components
#include <afxext.h> // MFC extensions
#include <afxdisp.h> // MFC Automation classes
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_STDAFX_H__88FA48B3_A92C_49CA_8A82_50D120A84756__INCLUDED_)

View File

@@ -0,0 +1,261 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>QC_Eyes</ProjectName>
<ProjectGuid>{EA02FAE0-2A4F-C7C8-6176-5DEDA8E139E9}</ProjectGuid>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>qc_eyes</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>qc_eyes</TargetName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PostBuildEventUseInBuild>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PostBuildEventUseInBuild>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 qc_eyes.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_ITERATOR_DEBUGGING=0;WIN32;_WIN32;_DEBUG;DEBUG;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\qc_eyes;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>Sync</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderOutputFile>Debug/QC_Eyes.pch</PrecompiledHeaderOutputFile>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\qc_eyes.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmt</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/qc_eyes.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 qc_eyes.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP /d2Zi+</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\qc_eyes;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>Sync</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>Use</PrecompiledHeader>
<PrecompiledHeaderOutputFile>Debug/QC_Eyes.pch</PrecompiledHeaderOutputFile>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /DYNAMICBASE /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\qc_eyes.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmtd</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/qc_eyes.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemGroup>
<Library Include="..\..\lib\public\tier0.lib" />
<Library Include="..\..\lib\public\tier1.lib" />
<Library Include="..\..\lib\public\vstdlib.lib" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="QC_Eyes.h" />
<ClInclude Include="QC_EyesDlg.h" />
<ClInclude Include="Resource.h" />
<ClInclude Include="StdAfx.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="QC_Eyes.cpp" />
<ClCompile Include="QC_EyesDlg.cpp" />
<ClCompile Include="StdAfx.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Create</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Create</PrecompiledHeader>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="QC_Eyes.rc" />
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)\%(Filename).obj</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)\%(Filename).obj</Outputs>
</CustomBuild>
</ItemGroup>
<ItemGroup>
<None Include="res\eye_default.bmp" />
<None Include="res\eye_lower_hi.bmp" />
<None Include="res\eye_lower_lo.bmp" />
<None Include="res\eye_lower_mid.bmp" />
<None Include="res\eye_upper_hi.bmp" />
<None Include="res\eye_upper_lo.bmp" />
<None Include="res\eye_upper_mid.bmp" />
<None Include="res\eye_XY_L.bmp" />
<None Include="res\eye_XY_R.bmp" />
<None Include="res\eye_Z_L.bmp" />
<None Include="res\eye_Z_R.bmp" />
<None Include="res\QC_Eyes.ico" />
<None Include="res\QC_Eyes.rc2" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,104 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{1680C80B-FF1E-EA4D-9817-CC12254F2E40}</UniqueIdentifier>
</Filter>
<Filter Include="Link Libraries">
<UniqueIdentifier>{C5D73B3A-C648-896C-B7CE-F174808E5BA5}</UniqueIdentifier>
</Filter>
<Filter Include="Resources">
<UniqueIdentifier>{DDCF50C2-9294-D441-4F3F-7C1BBC892CB5}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{BA03E055-4FA2-FCE3-8A1C-D348547D379C}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<Library Include="..\..\lib\public\tier0.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier1.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\vstdlib.lib">
<Filter>Link Libraries</Filter>
</Library>
</ItemGroup>
<ItemGroup>
<ClInclude Include="QC_Eyes.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="QC_EyesDlg.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Resource.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="StdAfx.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="QC_Eyes.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="QC_EyesDlg.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="StdAfx.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="QC_Eyes.rc">
<Filter>Source Files</Filter>
</ResourceCompile>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Filter>Source Files</Filter>
</CustomBuild>
</ItemGroup>
<ItemGroup>
<None Include="res\eye_default.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\eye_lower_hi.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\eye_lower_lo.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\eye_lower_mid.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\eye_upper_hi.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\eye_upper_lo.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\eye_upper_mid.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\eye_XY_L.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\eye_XY_R.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\eye_Z_L.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\eye_Z_R.bmp">
<Filter>Resources</Filter>
</None>
<None Include="res\QC_Eyes.ico">
<Filter>Resources</Filter>
</None>
<None Include="res\QC_Eyes.rc2">
<Filter>Resources</Filter>
</None>
</ItemGroup>
</Project>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,13 @@
//
// QC_EYES.RC2 - resources Microsoft Visual C++ does not edit directly
//
#ifdef APSTUDIO_INVOKED
#error this file is not editable by Microsoft Visual C++
#endif //APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
// Add manually edited resources here...
/////////////////////////////////////////////////////////////////////////////

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 92 KiB

View File

@@ -0,0 +1,78 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by QC_Eyes.rc
//
#define IDD_QC_EYES_DIALOG 102
#define IDR_MAINFRAME 128
#define IDB_EYE_DEFAULT 150
#define IDB_EYE_LOWER_HI 151
#define IDB_EYE_LOWER_LO 152
#define IDB_EYE_LOWER_MID 153
#define IDB_EYE_UPPER_HI 154
#define IDB_EYE_UPPER_LO 155
#define IDB_EYE_UPPER_MID 156
#define IDB_EYE_XY_L 157
#define IDB_EYE_XY_R 158
#define IDB_EYE_Z_L 159
#define IDB_EYE_Z_R 160
#define IDC_REFERENCE_FILENAME 1000
#define IDC_EXPRESSIONS_FILENAME 1001
#define IDC_MODEL_FILENAME 1002
#define IDC_RIGHT_EYE_X 1003
#define IDC_RIGHT_EYE_Y 1004
#define IDC_RIGHT_EYE_Z 1005
#define IDC_LEFT_EYE_X 1006
#define IDC_LEFT_EYE_Y 1007
#define IDC_LEFT_EYE_Z 1008
#define IDC_Y_AXIS_UP 1009
#define IDC_Z_AXIS_UP 1010
#define IDC_DEFAULT_CONTROLS 1011
#define IDC_ADVANCED_CONTROLS 1012
#define IDC_UPPER_LID_RAISED 1013
#define IDC_OUTPUT_TEXT 1014
#define IDC_UPPER_LEFT_LID_RAISED 1015
#define IDC_UPPER_LID_LOWERED 1016
#define IDC_UPPER_LID_NEUTRAL 1017
#define IDC_LOWER_LID_RAISED 1018
#define IDC_LOWER_LID_LOWERED 1019
#define IDC_LOWER_LID_NEUTRAL 1020
#define IDC_IRIS_COLOR_GREEN 1021
#define IDC_IRIS_COLOR_BLUE 1022
#define IDC_IRIS_COLOR_BROWN 1023
#define IDC_EYE_COLOR_LIGHT 1024
#define IDC_EYE_COLOR_DARK 1025
#define IDC_IRIS_SIZE 1026
#define IDC_CREATE_QC_TEXT 1027
#define IDC_EYEBALL_SIZE 1028
#define IDC_COPY_TEXT_TO_CLIPBOARD 1029
#define IDC_PICTURES 1030
#define IDC_PICTURE_LABEL 1031
#define IDC_LEFT_LID_CONTROL 1032
#define IDC_UPPER_LEFT_LID_NEUTRAL 1033
#define IDC_UPPER_LEFT_LID_LOWERED 1034
#define IDC_LOWER_LEFT_LID_RAISED 1035
#define IDC_LOWER_LEFT_LID_NEUTRAL 1036
#define IDC_LOWER_LEFT_LID_LOWERED 1037
#define IDC_EYE_DETAIL_CONTROL_FRAME 1038
#define IDC_IRIS_SIZE_LABEL 1039
#define IDC_EYEBALL_SIZE_LABEL 1040
#define IDC_UPPER_LEFT_LID_PANEL 1041
#define IDC_UPPER_LEFT_LID_RAISED_LABEL 1042
#define IDC_UPPER_LEFT_LID_NEUTRAL_LABEL 1043
#define IDC_UPPER_LEFT_LID_LOWERED_LABEL 1044
#define IDC_LOWER_LEFT_LID_PANEL 1045
#define IDC_LOWER_LEFT_LID_RAISED_LABEL 1046
#define IDC_LOWER_LEFT_LID_NEUTRAL_LABEL 1047
#define IDC_LOWER_LEFT_LID_LOWERED_LABEL 1048
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 130
#define _APS_NEXT_COMMAND_VALUE 32771
#define _APS_NEXT_CONTROL_VALUE 1049
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

View File

@@ -0,0 +1,383 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Basic BOT handling.
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================//
#include "interface.h"
#include "filesystem.h"
#undef VECTOR_NO_SLOW_OPERATIONS
#include "mathlib/vector.h"
#include "eiface.h"
#include "edict.h"
#include "game/server/iplayerinfo.h"
#include "igameevents.h"
#include "convar.h"
#include "vstdlib/random.h"
#include "../../game/shared/in_buttons.h"
#include "../../game/shared/shareddefs.h"
//#include "../../game_shared/util_shared.h"
#include "engine/IEngineTrace.h"
extern IBotManager *botmanager;
extern IUniformRandomStream *randomStr;
extern IPlayerInfoManager *playerinfomanager;
extern IVEngineServer *engine;
extern IEngineTrace *enginetrace;
extern IPlayerInfoManager *playerinfomanager; // game dll interface to interact with players
extern IServerPluginHelpers *helpers; // special 3rd party plugin helpers from the engine
extern CGlobalVars *gpGlobals;
ConVar bot_forcefireweapon( "plugin_bot_forcefireweapon", "", 0, "Force bots with the specified weapon to fire." );
ConVar bot_forceattack2( "plugin_bot_forceattack2", "0", 0, "When firing, use attack2." );
ConVar bot_forceattackon( "plugin_bot_forceattackon", "0", 0, "When firing, don't tap fire, hold it down." );
ConVar bot_flipout( "plugin_bot_flipout", "0", 0, "When on, all bots fire their guns." );
ConVar bot_changeclass( "plugin_bot_changeclass", "0", 0, "Force all bots to change to the specified class." );
static ConVar bot_mimic( "plugin_bot_mimic", "0", 0, "Bot uses usercmd of player by index." );
static ConVar bot_mimic_yaw_offset( "plugin_bot_mimic_yaw_offset", "0", 0, "Offsets the bot yaw." );
ConVar bot_sendcmd( "plugin_bot_sendcmd", "", 0, "Forces bots to send the specified command." );
ConVar bot_crouch( "plugin_bot_crouch", "0", 0, "Bot crouches" );
// This is our bot class.
class CPluginBot
{
public:
CPluginBot() :
m_bBackwards(0),
m_flNextTurnTime(0),
m_bLastTurnToRight(0),
m_flNextStrafeTime(0),
m_flSideMove(0),
m_ForwardAngle(),
m_LastAngles()
{
}
bool m_bBackwards;
float m_flNextTurnTime;
bool m_bLastTurnToRight;
float m_flNextStrafeTime;
float m_flSideMove;
QAngle m_ForwardAngle;
QAngle m_LastAngles;
IBotController *m_BotInterface;
IPlayerInfo *m_PlayerInfo;
edict_t *m_BotEdict;
};
CUtlVector<CPluginBot> s_Bots;
void Bot_Think( CPluginBot *pBot );
// Handler for the "bot" command.
void BotAdd_f()
{
if ( !botmanager )
return;
static int s_BotNum = 0;
char botName[64];
Q_snprintf( botName, sizeof(botName), "Bot_%i", s_BotNum );
s_BotNum++;
edict_t *botEdict = botmanager->CreateBot( botName );
if ( botEdict )
{
int botIndex = s_Bots.AddToTail();
CPluginBot & bot = s_Bots[ botIndex ];
bot.m_BotInterface = botmanager->GetBotController( botEdict );
bot.m_PlayerInfo = playerinfomanager->GetPlayerInfo( botEdict );
bot.m_BotEdict = botEdict;
Assert( bot.m_BotInterface );
}
}
ConCommand cc_Bot( "plugin_bot_add", BotAdd_f, "Add a bot." );
//-----------------------------------------------------------------------------
// Purpose: Run through all the Bots in the game and let them think.
//-----------------------------------------------------------------------------
void Bot_RunAll( void )
{
if ( !botmanager )
return;
for ( int i = 0; i < s_Bots.Count(); i++ )
{
CPluginBot & bot = s_Bots[i];
if ( bot.m_BotEdict->IsFree() || !bot.m_BotEdict->GetUnknown()|| !bot.m_PlayerInfo->IsConnected() )
{
s_Bots.Remove(i);
--i;
}
else
{
Bot_Think( &bot );
}
}
}
bool Bot_RunMimicCommand( CBotCmd& cmd )
{
if ( bot_mimic.GetInt() <= 0 )
return false;
if ( bot_mimic.GetInt() > gpGlobals->maxClients )
return false;
IPlayerInfo *playerInfo = playerinfomanager->GetPlayerInfo( engine->PEntityOfEntIndex( bot_mimic.GetInt() ) );
if ( !playerInfo )
return false;
cmd = playerInfo->GetLastUserCommand();
cmd.viewangles[YAW] += bot_mimic_yaw_offset.GetFloat();
if( bot_crouch.GetInt() )
cmd.buttons |= IN_DUCK;
return true;
}
void Bot_UpdateStrafing( CPluginBot *pBot, CBotCmd &cmd )
{
if ( gpGlobals->curtime >= pBot->m_flNextStrafeTime )
{
pBot->m_flNextStrafeTime = gpGlobals->curtime + 1.0f;
if ( randomStr->RandomInt( 0, 5 ) == 0 )
{
pBot->m_flSideMove = -600.0f + 1200.0f * randomStr->RandomFloat( 0, 2 );
}
else
{
pBot->m_flSideMove = 0;
}
cmd.sidemove = pBot->m_flSideMove;
if ( randomStr->RandomInt( 0, 20 ) == 0 )
{
pBot->m_bBackwards = true;
}
else
{
pBot->m_bBackwards = false;
}
}
}
void Bot_UpdateDirection( CPluginBot *pBot )
{
float angledelta = 15.0;
int maxtries = (int)360.0/angledelta;
if ( pBot->m_bLastTurnToRight )
{
angledelta = -angledelta;
}
QAngle angle( pBot->m_BotInterface->GetLocalAngles() );
trace_t trace;
Vector vecSrc, vecEnd, forward;
while ( --maxtries >= 0 )
{
AngleVectors( angle, &forward );
vecSrc = pBot->m_BotInterface->GetLocalOrigin() + Vector( 0, 0, 36 );
vecEnd = vecSrc + forward * 10;
Ray_t ray;
ray.Init( vecSrc, vecEnd, Vector(-16, -16, 0 ), Vector( 16, 16, 72 ) );
CTraceFilterWorldAndPropsOnly traceFilter;
enginetrace->TraceRay( ray, MASK_PLAYERSOLID, &traceFilter, &trace );
if ( trace.fraction == 1.0 )
{
if ( gpGlobals->curtime < pBot->m_flNextTurnTime )
{
break;
}
}
angle.y += angledelta;
if ( angle.y > 180 )
angle.y -= 360;
else if ( angle.y < -180 )
angle.y += 360;
pBot->m_flNextTurnTime = gpGlobals->curtime + 2.0;
pBot->m_bLastTurnToRight = randomStr->RandomInt( 0, 1 ) == 0 ? true : false;
pBot->m_ForwardAngle = angle;
pBot->m_LastAngles = angle;
}
pBot->m_BotInterface->SetLocalAngles( angle );
}
void Bot_FlipOut( CPluginBot *pBot, CBotCmd &cmd )
{
if ( bot_flipout.GetInt() > 0 && !pBot->m_PlayerInfo->IsDead() )
{
if ( bot_forceattackon.GetBool() || (RandomFloat(0.0,1.0) > 0.5) )
{
cmd.buttons |= bot_forceattack2.GetBool() ? IN_ATTACK2 : IN_ATTACK;
}
if ( bot_flipout.GetInt() >= 2 )
{
QAngle angOffset = RandomAngle( -1, 1 );
pBot->m_LastAngles += angOffset;
for ( int i = 0 ; i < 2; i++ )
{
if ( fabs( pBot->m_LastAngles[ i ] - pBot->m_ForwardAngle[ i ] ) > 15.0f )
{
if ( pBot->m_LastAngles[ i ] > pBot->m_ForwardAngle[ i ] )
{
pBot->m_LastAngles[ i ] = pBot->m_ForwardAngle[ i ] + 15;
}
else
{
pBot->m_LastAngles[ i ] = pBot->m_ForwardAngle[ i ] - 15;
}
}
}
pBot->m_LastAngles[ 2 ] = 0;
pBot->m_BotInterface->SetLocalAngles( pBot->m_LastAngles );
}
}
}
void Bot_HandleSendCmd( CPluginBot *pBot )
{
if ( strlen( bot_sendcmd.GetString() ) > 0 )
{
//send the cmd from this bot
helpers->ClientCommand( pBot->m_BotEdict, bot_sendcmd.GetString() );
bot_sendcmd.SetValue("");
}
}
// If bots are being forced to fire a weapon, see if I have it
void Bot_ForceFireWeapon( CPluginBot *pBot, CBotCmd &cmd )
{
if ( Q_strlen( bot_forcefireweapon.GetString() ) > 0 )
{
pBot->m_BotInterface->SetActiveWeapon( bot_forcefireweapon.GetString() );
bot_forcefireweapon.SetValue( "" );
// Start firing
// Some weapons require releases, so randomise firing
if ( bot_forceattackon.GetBool() || (RandomFloat(0.0,1.0) > 0.5) )
{
cmd.buttons |= bot_forceattack2.GetBool() ? IN_ATTACK2 : IN_ATTACK;
}
}
}
void Bot_SetForwardMovement( CPluginBot *pBot, CBotCmd &cmd )
{
if ( !pBot->m_BotInterface->IsEFlagSet(EFL_BOT_FROZEN) )
{
if ( pBot->m_PlayerInfo->GetHealth() == 100 )
{
cmd.forwardmove = 600 * ( pBot->m_bBackwards ? -1 : 1 );
if ( pBot->m_flSideMove != 0.0f )
{
cmd.forwardmove *= randomStr->RandomFloat( 0.1, 1.0f );
}
}
else
{
// Stop when shot
cmd.forwardmove = 0;
}
}
}
void Bot_HandleRespawn( CPluginBot *pBot, CBotCmd &cmd )
{
// Wait for Reinforcement wave
if ( pBot->m_PlayerInfo->IsDead() )
{
if ( pBot->m_PlayerInfo->GetTeamIndex() == 0 )
{
helpers->ClientCommand( pBot->m_BotEdict, "joingame" );
helpers->ClientCommand( pBot->m_BotEdict, "jointeam 3" );
helpers->ClientCommand( pBot->m_BotEdict, "joinclass 0" );
}
}
}
//-----------------------------------------------------------------------------
// Run this Bot's AI for one frame.
//-----------------------------------------------------------------------------
void Bot_Think( CPluginBot *pBot )
{
CBotCmd cmd;
Q_memset( &cmd, 0, sizeof( cmd ) );
// Finally, override all this stuff if the bot is being forced to mimic a player.
if ( !Bot_RunMimicCommand( cmd ) )
{
cmd.sidemove = pBot->m_flSideMove;
if ( !pBot->m_PlayerInfo->IsDead() )
{
Bot_SetForwardMovement( pBot, cmd );
// Only turn if I haven't been hurt
if ( !pBot->m_BotInterface->IsEFlagSet(EFL_BOT_FROZEN) && pBot->m_PlayerInfo->GetHealth() == 100 )
{
Bot_UpdateDirection( pBot );
Bot_UpdateStrafing( pBot, cmd );
}
// Handle console settings.
Bot_ForceFireWeapon( pBot, cmd );
Bot_HandleSendCmd( pBot );
}
else
{
Bot_HandleRespawn( pBot, cmd );
}
Bot_FlipOut( pBot, cmd );
cmd.viewangles = pBot->m_BotInterface->GetLocalAngles();
cmd.upmove = 0;
cmd.impulse = 0;
}
pBot->m_BotInterface->RunPlayerMove( &cmd );
}

View File

@@ -0,0 +1,258 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>Serverplugin_empty</ProjectName>
<ProjectGuid>{394B82B6-3999-E576-5458-2D2EB4229509}</ProjectGuid>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>serverplugin_empty</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>serverplugin_empty</TargetName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PostBuildEventUseInBuild>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PostBuildEventUseInBuild>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PreBuildEvent>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;..\..\game\server;..\..\game\shared</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_ITERATOR_DEBUGGING=0;WIN32;_WIN32;_DEBUG;DEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;DLLNAME=serverplugin_empty;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;serverplugin_emptyONLY;_MBCS;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\serverplugin_sample;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<GenerateXMLDocumentationFiles>false</GenerateXMLDocumentationFiles>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies);odbc32.lib;odbccp32.lib</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\serverplugin_empty.dll</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>..\..\lib\common;..\..\lib\public</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmt</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/serverplugin_empty.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) &quot;..\..\..\game\bin\$(TargetFileName)&quot;&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PreBuildEvent>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP /d2Zi+</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1;..\..\game\server;..\..\game\shared</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WIN32;NDEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;DLLNAME=serverplugin_empty;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;serverplugin_emptyONLY;_MBCS;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\serverplugin_sample;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<GenerateXMLDocumentationFiles>false</GenerateXMLDocumentationFiles>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /DYNAMICBASE /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies);odbc32.lib;odbccp32.lib</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\serverplugin_empty.dll</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<AdditionalLibraryDirectories>..\..\lib\common;..\..\lib\public</AdditionalLibraryDirectories>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmtd</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Windows</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<LinkLibraryDependencies>false</LinkLibraryDependencies>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/serverplugin_empty.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) &quot;..\..\..\game\bin\$(TargetFileName)&quot;&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemGroup>
<Library Include="..\..\lib\public\mathlib.lib" />
<Library Include="..\..\lib\public\tier0.lib" />
<Library Include="..\..\lib\public\tier1.lib" />
<Library Include="..\..\lib\public\tier2.lib" />
<Library Include="..\..\lib\public\vstdlib.lib" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\public\tier0\basetypes.h" />
<ClInclude Include="..\..\public\Color.h" />
<ClInclude Include="..\..\public\tier0\dbg.h" />
<ClInclude Include="..\..\public\eiface.h" />
<ClInclude Include="..\..\public\filesystem.h" />
<ClInclude Include="..\..\public\tier0\icommandline.h" />
<ClInclude Include="..\..\public\igameevents.h" />
<ClInclude Include="..\..\public\tier1\interface.h" />
<ClInclude Include="..\..\public\game\server\iplayerinfo.h" />
<ClInclude Include="..\..\public\engine\iserverplugin.h" />
<ClInclude Include="..\..\public\tier1\KeyValues.h" />
<ClInclude Include="..\..\public\tier0\mem.h" />
<ClInclude Include="..\..\public\tier0\memalloc.h" />
<ClInclude Include="..\..\public\tier0\memdbgon.h" />
<ClInclude Include="..\..\public\tier1\strtools.h" />
<ClInclude Include="..\..\public\tier1\utlbuffer.h" />
<ClInclude Include="..\..\public\tier1\utlmemory.h" />
<ClInclude Include="..\..\public\tier1\utlvector.h" />
<ClInclude Include="..\..\public\vstdlib\vstdlib.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="serverplugin_bot.cpp" />
<ClCompile Include="serverplugin_empty.cpp" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)\%(Filename).obj</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)\%(Filename).obj</Outputs>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{1680C80B-FF1E-EA4D-9817-CC12254F2E40}</UniqueIdentifier>
</Filter>
<Filter Include="Link Libraries">
<UniqueIdentifier>{C5D73B3A-C648-896C-B7CE-F174808E5BA5}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{BA03E055-4FA2-FCE3-8A1C-D348547D379C}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<Library Include="..\..\lib\public\mathlib.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier0.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier1.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier2.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\vstdlib.lib">
<Filter>Link Libraries</Filter>
</Library>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\..\public\tier0\basetypes.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\Color.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\dbg.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\eiface.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\filesystem.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\icommandline.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\igameevents.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\interface.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\game\server\iplayerinfo.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\engine\iserverplugin.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\KeyValues.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\mem.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\memalloc.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier0\memdbgon.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\strtools.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlbuffer.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlmemory.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\tier1\utlvector.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="..\..\public\vstdlib\vstdlib.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="serverplugin_bot.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="serverplugin_empty.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Filter>Source Files</Filter>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,922 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#include <stdio.h>
//#define GAME_DLL
#ifdef GAME_DLL
#include "cbase.h"
#endif
#include <stdio.h>
#include "interface.h"
#include "filesystem.h"
#include "engine/iserverplugin.h"
#include "eiface.h"
#include "igameevents.h"
#include "convar.h"
#include "Color.h"
#include "vstdlib/random.h"
#include "engine/IEngineTrace.h"
#include "tier2/tier2.h"
#include "game/server/pluginvariant.h"
#include "game/server/iplayerinfo.h"
#include "game/server/ientityinfo.h"
#include "game/server/igameinfo.h"
//#define SAMPLE_TF2_PLUGIN
#ifdef SAMPLE_TF2_PLUGIN
#include "tf/tf_shareddefs.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
// Interfaces from the engine
IVEngineServer *engine = NULL; // helper functions (messaging clients, loading content, making entities, running commands, etc)
IGameEventManager *gameeventmanager_ = NULL; // game events interface
#ifndef GAME_DLL
#define gameeventmanager gameeventmanager_
#endif
IPlayerInfoManager *playerinfomanager = NULL; // game dll interface to interact with players
IEntityInfoManager *entityinfomanager = NULL; // game dll interface to interact with all entities (like IPlayerInfo)
IGameInfoManager *gameinfomanager = NULL; // game dll interface to get data from game rules directly
IBotManager *botmanager = NULL; // game dll interface to interact with bots
IServerPluginHelpers *helpers = NULL; // special 3rd party plugin helpers from the engine
IUniformRandomStream *randomStr = NULL;
IEngineTrace *enginetrace = NULL;
CGlobalVars *gpGlobals = NULL;
// function to initialize any cvars/command in this plugin
void Bot_RunAll( void );
// useful helper func
#ifndef GAME_DLL
inline bool FStrEq(const char *sz1, const char *sz2)
{
return(Q_stricmp(sz1, sz2) == 0);
}
#endif
//---------------------------------------------------------------------------------
// Purpose: a sample 3rd party plugin class
//---------------------------------------------------------------------------------
class CEmptyServerPlugin: public IServerPluginCallbacks, public IGameEventListener
{
public:
CEmptyServerPlugin();
~CEmptyServerPlugin();
// IServerPluginCallbacks methods
virtual bool Load( CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory );
virtual void Unload( void );
virtual void Pause( void );
virtual void UnPause( void );
virtual const char *GetPluginDescription( void );
virtual void LevelInit( char const *pMapName );
virtual void ServerActivate( edict_t *pEdictList, int edictCount, int clientMax );
virtual void GameFrame( bool simulating );
virtual void LevelShutdown( void );
virtual void ClientActive( edict_t *pEntity );
virtual void ClientDisconnect( edict_t *pEntity );
virtual void ClientPutInServer( edict_t *pEntity, char const *playername );
virtual void SetCommandClient( int index );
virtual void ClientSettingsChanged( edict_t *pEdict );
virtual PLUGIN_RESULT ClientConnect( bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen );
virtual PLUGIN_RESULT ClientCommand( edict_t *pEntity, const CCommand &args );
virtual PLUGIN_RESULT NetworkIDValidated( const char *pszUserName, const char *pszNetworkID );
virtual void OnQueryCvarValueFinished( QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue );
virtual void OnEdictAllocated( edict_t *edict );
virtual void OnEdictFreed( const edict_t *edict );
// IGameEventListener Interface
virtual void FireGameEvent( KeyValues * event );
virtual int GetCommandIndex() { return m_iClientCommandIndex; }
private:
int m_iClientCommandIndex;
};
//
// The plugin is a static singleton that is exported as an interface
//
CEmptyServerPlugin g_EmtpyServerPlugin;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CEmptyServerPlugin, IServerPluginCallbacks, INTERFACEVERSION_ISERVERPLUGINCALLBACKS, g_EmtpyServerPlugin );
//---------------------------------------------------------------------------------
// Purpose: constructor/destructor
//---------------------------------------------------------------------------------
CEmptyServerPlugin::CEmptyServerPlugin()
{
m_iClientCommandIndex = 0;
}
CEmptyServerPlugin::~CEmptyServerPlugin()
{
}
//---------------------------------------------------------------------------------
// Purpose: called when the plugin is loaded, load the interface we need from the engine
//---------------------------------------------------------------------------------
bool CEmptyServerPlugin::Load( CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory )
{
ConnectTier1Libraries( &interfaceFactory, 1 );
ConnectTier2Libraries( &interfaceFactory, 1 );
entityinfomanager = (IEntityInfoManager *)gameServerFactory(INTERFACEVERSION_ENTITYINFOMANAGER,NULL);
if ( !entityinfomanager )
{
Warning( "Unable to load entityinfomanager, ignoring\n" ); // this isn't fatal, we just won't be able to access entity data
}
playerinfomanager = (IPlayerInfoManager *)gameServerFactory(INTERFACEVERSION_PLAYERINFOMANAGER,NULL);
if ( !playerinfomanager )
{
Warning( "Unable to load playerinfomanager, ignoring\n" ); // this isn't fatal, we just won't be able to access specific player data
}
botmanager = (IBotManager *)gameServerFactory(INTERFACEVERSION_PLAYERBOTMANAGER, NULL);
if ( !botmanager )
{
Warning( "Unable to load botcontroller, ignoring\n" ); // this isn't fatal, we just won't be able to access specific bot functions
}
gameinfomanager = (IGameInfoManager *)gameServerFactory(INTERFACEVERSION_GAMEINFOMANAGER, NULL);
if (!gameinfomanager)
{
Warning( "Unable to load gameinfomanager, ignoring\n" );
}
engine = (IVEngineServer*)interfaceFactory(INTERFACEVERSION_VENGINESERVER, NULL);
gameeventmanager = (IGameEventManager *)interfaceFactory(INTERFACEVERSION_GAMEEVENTSMANAGER,NULL);
helpers = (IServerPluginHelpers*)interfaceFactory(INTERFACEVERSION_ISERVERPLUGINHELPERS, NULL);
enginetrace = (IEngineTrace *)interfaceFactory(INTERFACEVERSION_ENGINETRACE_SERVER,NULL);
randomStr = (IUniformRandomStream *)interfaceFactory(VENGINE_SERVER_RANDOM_INTERFACE_VERSION, NULL);
// get the interfaces we want to use
if( ! ( engine && gameeventmanager && g_pFullFileSystem && helpers && enginetrace && randomStr ) )
{
return false; // we require all these interface to function
}
if ( playerinfomanager )
{
gpGlobals = playerinfomanager->GetGlobalVars();
}
MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f );
ConVar_Register( 0 );
return true;
}
//---------------------------------------------------------------------------------
// Purpose: called when the plugin is unloaded (turned off)
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::Unload( void )
{
gameeventmanager->RemoveListener( this ); // make sure we are unloaded from the event system
ConVar_Unregister( );
DisconnectTier2Libraries( );
DisconnectTier1Libraries( );
}
//---------------------------------------------------------------------------------
// Purpose: called when the plugin is paused (i.e should stop running but isn't unloaded)
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::Pause( void )
{
}
//---------------------------------------------------------------------------------
// Purpose: called when the plugin is unpaused (i.e should start executing again)
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::UnPause( void )
{
}
//---------------------------------------------------------------------------------
// Purpose: the name of this plugin, returned in "plugin_print" command
//---------------------------------------------------------------------------------
const char *CEmptyServerPlugin::GetPluginDescription( void )
{
return "Emtpy-Plugin V2, Valve";
}
//---------------------------------------------------------------------------------
// Purpose: called on level start
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::LevelInit( char const *pMapName )
{
Msg( "Level \"%s\" has been loaded\n", pMapName );
gameeventmanager->AddListener( this, true );
}
//---------------------------------------------------------------------------------
// Purpose: called on level start, when the server is ready to accept client connections
// edictCount is the number of entities in the level, clientMax is the max client count
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::ServerActivate( edict_t *pEdictList, int edictCount, int clientMax )
{
}
//---------------------------------------------------------------------------------
// Purpose: called once per server frame, do recurring work here (like checking for timeouts)
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::GameFrame( bool simulating )
{
if ( simulating )
{
Bot_RunAll();
}
}
//---------------------------------------------------------------------------------
// Purpose: called on level end (as the server is shutting down or going to a new map)
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::LevelShutdown( void ) // !!!!this can get called multiple times per map change
{
gameeventmanager->RemoveListener( this );
}
//---------------------------------------------------------------------------------
// Purpose: called when a client spawns into a server (i.e as they begin to play)
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::ClientActive( edict_t *pEntity )
{
}
//---------------------------------------------------------------------------------
// Purpose: called when a client leaves a server (or is timed out)
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::ClientDisconnect( edict_t *pEntity )
{
}
//---------------------------------------------------------------------------------
// Purpose: called on
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::ClientPutInServer( edict_t *pEntity, char const *playername )
{
KeyValues *kv = new KeyValues( "msg" );
kv->SetString( "title", "Hello" );
kv->SetString( "msg", "Hello there" );
kv->SetColor( "color", Color( 255, 0, 0, 255 ));
kv->SetInt( "level", 5);
kv->SetInt( "time", 10);
helpers->CreateMessage( pEntity, DIALOG_MSG, kv, this );
kv->deleteThis();
}
//---------------------------------------------------------------------------------
// Purpose: called on level start
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::SetCommandClient( int index )
{
m_iClientCommandIndex = index;
}
void ClientPrint( edict_t *pEdict, char *format, ... )
{
va_list argptr;
static char string[1024];
va_start (argptr, format);
Q_vsnprintf(string, sizeof(string), format,argptr);
va_end (argptr);
engine->ClientPrintf( pEdict, string );
}
//---------------------------------------------------------------------------------
// Purpose: called on level start
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::ClientSettingsChanged( edict_t *pEdict )
{
if ( playerinfomanager )
{
IPlayerInfo *playerinfo = playerinfomanager->GetPlayerInfo( pEdict );
const char * name = engine->GetClientConVarValue( engine->IndexOfEdict(pEdict), "name" );
// CAN'T use Q_stricmp here, this dll is made by 3rd parties and may not link to tier0/vstdlib
if ( playerinfo && name && playerinfo->GetName() &&
stricmp( name, playerinfo->GetName()) ) // playerinfo may be NULL if the MOD doesn't support access to player data
// OR if you are accessing the player before they are fully connected
{
ClientPrint( pEdict, "Your name changed to \"%s\" (from \"%s\"\n", name, playerinfo->GetName() );
// this is the bad way to check this, the better option it to listen for the "player_changename" event in FireGameEvent()
// this is here to give a real example of how to use the playerinfo interface
}
}
}
//---------------------------------------------------------------------------------
// Purpose: called when a client joins a server
//---------------------------------------------------------------------------------
PLUGIN_RESULT CEmptyServerPlugin::ClientConnect( bool *bAllowConnect, edict_t *pEntity, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen )
{
return PLUGIN_CONTINUE;
}
CON_COMMAND( DoAskConnect, "Server plugin example of using the ask connect dialog" )
{
if ( args.ArgC() < 2 )
{
Warning ( "DoAskConnect <server IP>\n" );
}
else
{
const char *pServerIP = args.Arg( 1 );
KeyValues *kv = new KeyValues( "menu" );
kv->SetString( "title", pServerIP ); // The IP address of the server to connect to goes in the "title" field.
kv->SetInt( "time", 3 );
for ( int i=1; i < gpGlobals->maxClients; i++ )
{
edict_t *pEdict = engine->PEntityOfEntIndex( i );
if ( pEdict )
{
helpers->CreateMessage( pEdict, DIALOG_ASKCONNECT, kv, &g_EmtpyServerPlugin );
}
}
kv->deleteThis();
}
}
#ifdef SAMPLE_TF2_PLUGIN
const char *classNames[] =
{
"unknown",
"scout",
"sniper",
"soldier",
"demoman",
"medic",
"heavy weapons guy",
"pyro",
"spy",
"engineer",
};
bool TFPlayerHasCondition( int inBits, int condition )
{
Assert( condition >= 0 && condition < TF_COND_LAST );
return ( ( inBits & (1<<condition) ) != 0 );
}
void SentryStatus( edict_t *pEntity )
{
IPlayerInfo *playerinfo = playerinfomanager->GetPlayerInfo( pEntity );
if (!playerinfo)
{
Msg("couldn't get playerinfo\n");
return;
}
Msg("Sentry Status:\n");
pluginvariant value;
pluginvariant emptyVariant;
edict_t *pSentry = NULL;
if (playerinfo->GetCustomInfo(TFPLAYERINFO_ENTINDEX_SENTRY, value, emptyVariant))
{
pSentry = engine->PEntityOfEntIndex( value.Int() );
if (!pSentry)
{
Warning("couldn't attain sentry gun entity\n");
return;
}
}
else
{
Msg("No Sentrygun built.\n");
return;
}
IEntityInfo *entinfo = entityinfomanager->GetEntityInfo( pSentry );
if (!entinfo)
{
Warning("couldn't get entinfo for sentry gun\n");
return;
}
if (playerinfo->GetCustomInfo(TFPLAYERINFO_BUILDING_SENTRY, value, emptyVariant))
{
if (value.Bool())
Msg("Sentry Under Construction...\n");
}
if (playerinfo->GetCustomInfo(TFPLAYERINFO_UPGRADING_SENTRY, value, emptyVariant))
{
if (value.Bool())
Msg("Sentry Upgrading...\n");
}
int sentryLevel = 0;
if (playerinfo->GetCustomInfo(TFPLAYERINFO_SENTRY_LEVEL, value, emptyVariant))
{
sentryLevel = value.Int();
Msg("Sentry Level: %i\n", sentryLevel );
}
else
Msg("Unable to retrive sentry level\n");
if (playerinfo->GetCustomInfo(TFPLAYERINFO_SENTRY_PROGRESS, value, emptyVariant))
{
if (sentryLevel < 3)
{
int iMetal, iRequiredMetal;
iRequiredMetal = value.Int() & 0xFF;
iMetal = (value.Int()>>8) & 0xFF;
Msg("%i / %i Metal Required for Sentry Level %i\n", iMetal, iRequiredMetal, sentryLevel+1);
}
else
Msg("Sentry cannot be upgraded further.\n");
}
Msg("Health: %i\n", entinfo->GetHealth() );
if (playerinfo->GetCustomInfo(TFPLAYERINFO_SENTRY_KILLS, value, emptyVariant))
Msg("Kills: %i\n", value.Int() );
else
Msg("Unable to retrieve sentry kills\n");
if (playerinfo->GetCustomInfo(TFPLAYERINFO_SENTRY_AMMO_SHELLS, value, emptyVariant))
{
int iShells, iMaxShells;
iMaxShells = value.Int() & 0xFF;
iShells = (value.Int()>>8) & 0xFF;
Msg("Shells: %i / %i\n", iShells, iMaxShells);
}
if (sentryLevel > 2)
{
if (playerinfo->GetCustomInfo(TFPLAYERINFO_SENTRY_AMMO_ROCKETS, value, emptyVariant))
{
int iRockets, iMaxRockets;
iMaxRockets = value.Int() & 0xFF;
iRockets = (value.Int()>>8) & 0xFF;
Msg("Rockets: %i / %i\n", iRockets, iMaxRockets);
}
}
}
void DispenserStatus( edict_t *pEntity )
{
IPlayerInfo *playerinfo = playerinfomanager->GetPlayerInfo( pEntity );
if (!playerinfo)
{
Msg("couldn't get playerinfo\n");
return;
}
Msg("Dispenser Status:\n");
pluginvariant value;
pluginvariant emptyVariant;
edict_t *pDispenser = NULL;
if (playerinfo->GetCustomInfo(TFPLAYERINFO_ENTINDEX_DISPENSER, value, emptyVariant))
{
pDispenser = engine->PEntityOfEntIndex( value.Int() );
if (!pDispenser)
{
Warning("couldn't attain dispenser entity\n");
return;
}
}
else
{
Msg("No dispenser built.\n");
return;
}
IEntityInfo *entinfo = entityinfomanager->GetEntityInfo( pDispenser );
if (!entinfo)
{
Warning("couldn't get entinfo for dispenser\n");
return;
}
if (playerinfo->GetCustomInfo(TFPLAYERINFO_BUILDING_DISPENSER, value, emptyVariant))
{
if (value.Bool())
Msg("Dispenser Under Construction...\n");
}
Msg("Health: %i\n", entinfo->GetHealth() );
if (playerinfo->GetCustomInfo(TFPLAYERINFO_DISPENSER_METAL, value, emptyVariant))
Msg("Metal: %i\n", value.Int() );
}
void TeleporterStatus( edict_t *pEntity )
{
IPlayerInfo *playerinfo = playerinfomanager->GetPlayerInfo( pEntity );
if (!playerinfo)
{
Msg("couldn't get playerinfo\n");
return;
}
Msg("Teleporter Status:\n");
pluginvariant value;
pluginvariant emptyVariant;
edict_t *pEntrance = NULL;
edict_t *pExit = NULL;
if (playerinfo->GetCustomInfo(TFPLAYERINFO_ENTINDEX_TELEPORTER_ENTRANCE, value, emptyVariant))
{
pEntrance = engine->PEntityOfEntIndex( value.Int() );
if (!pEntrance)
{
Warning("couldn't attain entrance entity\n");
}
}
else
{
Msg("No Teleporter Entrance built.\n");
}
if (playerinfo->GetCustomInfo(TFPLAYERINFO_ENTINDEX_TELEPORTER_EXIT, value, emptyVariant))
{
pExit = engine->PEntityOfEntIndex( value.Int() );
if (!pExit)
{
Warning("couldn't attain exit entity\n");
}
}
else
{
Msg("No Teleporter Entrance built.\n");
}
IEntityInfo *entranceInfo = entityinfomanager->GetEntityInfo( pEntrance );
if (!entranceInfo)
{
Warning("couldn't get entinfo for teleporter entrance\n");
}
IEntityInfo *exitInfo = entityinfomanager->GetEntityInfo( pExit );
if (!exitInfo)
{
Warning("couldn't get entinfo for teleporter exit\n");
}
if (pEntrance && entranceInfo)
{
if (playerinfo->GetCustomInfo(TFPLAYERINFO_BUILDING_TELEPORTER_ENTRANCE, value, emptyVariant))
{
if (value.Bool())
Msg("Entrance Under Construction...\n");
}
Msg("Entrance Health: %i\n", entranceInfo->GetHealth() );
if (playerinfo->GetCustomInfo(TFPLAYERINFO_TELEPORTER_USES, value, emptyVariant))
Msg("Entrance Used %i Times.\n", value.Int() );
}
if (pExit && exitInfo)
{
if (playerinfo->GetCustomInfo(TFPLAYERINFO_BUILDING_TELEPORTER_EXIT, value, emptyVariant))
{
if (value.Bool())
Msg("Exit Under Construction...\n");
}
Msg("Exit Health: %i\n", exitInfo->GetHealth() );
}
}
void ClassStatus( edict_t *pEntity )
{
IPlayerInfo *playerinfo = playerinfomanager->GetPlayerInfo( pEntity );
if (!playerinfo)
{
Msg("couldn't get playerinfo\n");
return;
}
int playerClassId = playerinfo->GetPlayerClassId();
Msg("Player Class: %s\n", playerinfo->GetPlayerClassName());
pluginvariant conditionValue;
pluginvariant emptyVariant;
if (!playerinfo->GetCustomInfo(TFPLAYERINFO_CONDITIONS, conditionValue, emptyVariant))
{
Warning("unable to retrieve conditions!\n");
}
if (TFPlayerHasCondition(conditionValue.Int(), TF_COND_INVULNERABLE ))
Msg("You are Invulnerable!\n");
if (TFPlayerHasCondition(conditionValue.Int(), TF_COND_SELECTED_TO_TELEPORT ))
Msg("You are about to Teleport.\n");
if (TFPlayerHasCondition(conditionValue.Int(), TF_COND_TELEPORTED ))
Msg("You have recently been teleported.\n");
switch(playerClassId)
{
default:
case TF_CLASS_MEDIC:
break;
case TF_CLASS_ENGINEER:
Msg("Building Information:\n");
SentryStatus( pEntity );
DispenserStatus( pEntity );
TeleporterStatus( pEntity );
break;
case TF_CLASS_SPY:
{
int disguiseClass = 0;
pluginvariant value;
if (playerinfo->GetCustomInfo(TFPLAYERINFO_SPY_DISGUISEDAS, value, emptyVariant))
disguiseClass = value.Int();
if ( TFPlayerHasCondition(conditionValue.Int(), TF_COND_DISGUISING ) )
Msg("Disguising..\n");
else if (TFPlayerHasCondition(conditionValue.Int(), TF_COND_DISGUISED ) )
Msg("Disguised as: %s\n", classNames[disguiseClass] );
if (TFPlayerHasCondition(conditionValue.Int(), TF_COND_STEALTHED ))
Msg("Cloaked!\n");
if (playerinfo->GetCustomInfo(TFPLAYERINFO_SPY_CLOAKCHARGELEVEL, value, emptyVariant))
Msg("Cloak Charge Percent: %d\n", value.Float() );
break;
}
case TF_CLASS_DEMOMAN:
break;
}
}
const char *ctf_flagtype[] =
{
"ctf", //TF_FLAGTYPE_CTF = 0,
"attack / defend", //TF_FLAGTYPE_ATTACK_DEFEND,
"territory control", //TF_FLAGTYPE_TERRITORY_CONTROL,
"invade", //TF_FLAGTYPE_INVADE,
"king of the hill", //TF_FLAGTYPE_KINGOFTHEHILL,
};
const char *ctf_flagstatus[] =
{
"unknown",
"At Home",
"Dropped",
"Stolen",
};
void FlagStatus( edict_t *pPlayer )
{
IPlayerInfo *pInfo = playerinfomanager->GetPlayerInfo( pPlayer );
if (!pInfo)
{
Msg( "couldn't get playerinfo\n" );
return;
}
IGameInfo *gameInfo = gameinfomanager->GetGameInfo();
if (!gameInfo)
{
Msg( "couldn't get gameinfo\n" );
}
int gameType = gameInfo->GetInfo_GameType();
if (gameType != 1)
{
Msg( "Game is not CTF.\n" );
return;
}
Msg( "===============================\n" );
Msg( "Capture The Flag -- Flag Status\n" );
Msg( "===============================\n" );
pluginvariant value, options;
edict_t *pFlag = NULL;
while ( (pFlag = entityinfomanager->FindEntityByClassname(pFlag, "item_teamflag")) != NULL )
{
IEntityInfo *pFlagInfo = entityinfomanager->GetEntityInfo( pFlag );
if (!pFlagInfo)
continue;
Msg( "\nTeam %s's Flag\n", gameInfo->GetInfo_GetTeamName( pFlagInfo->GetTeamIndex() ) );
options.SetInt(engine->IndexOfEdict(pFlag));
if ( gameInfo->GetInfo_Custom( TFGAMEINFO_CTF_FLAG_TYPE, value, options) )
Msg( "Type: %s\n", ctf_flagtype[value.Int()] );
if ( gameInfo->GetInfo_Custom( TFGAMEINFO_CTF_FLAG_STATUS, value, options) )
{
Msg( "Status: %s\n", ctf_flagstatus[value.Int()] );
//Tony; if we're carried, find out who has us.
if (value.Int() == 3)
{
edict_t *pPlayer = pFlagInfo->GetOwner();
if (pPlayer)
{
IPlayerInfo *pPlayerInfo = playerinfomanager->GetPlayerInfo( pPlayer );
if (pPlayerInfo)
Msg( "Carried by: %s\n", pPlayerInfo->GetName() );
}
}
}
}
Msg( "===============================\n" );
}
#endif
//---------------------------------------------------------------------------------
// Purpose: called when a client types in a command (only a subset of commands however, not CON_COMMAND's)
//---------------------------------------------------------------------------------
PLUGIN_RESULT CEmptyServerPlugin::ClientCommand( edict_t *pEntity, const CCommand &args )
{
const char *pcmd = args[0];
if ( !pEntity || pEntity->IsFree() )
{
return PLUGIN_CONTINUE;
}
if ( FStrEq( pcmd, "menu" ) )
{
KeyValues *kv = new KeyValues( "menu" );
kv->SetString( "title", "You've got options, hit ESC" );
kv->SetInt( "level", 1 );
kv->SetColor( "color", Color( 255, 0, 0, 255 ));
kv->SetInt( "time", 20 );
kv->SetString( "msg", "Pick an option\nOr don't." );
for( int i = 1; i < 9; i++ )
{
char num[10], msg[10], cmd[10];
Q_snprintf( num, sizeof(num), "%i", i );
Q_snprintf( msg, sizeof(msg), "Option %i", i );
Q_snprintf( cmd, sizeof(cmd), "option%i", i );
KeyValues *item1 = kv->FindKey( num, true );
item1->SetString( "msg", msg );
item1->SetString( "command", cmd );
}
helpers->CreateMessage( pEntity, DIALOG_MENU, kv, this );
kv->deleteThis();
return PLUGIN_STOP; // we handled this function
}
else if ( FStrEq( pcmd, "rich" ) )
{
KeyValues *kv = new KeyValues( "menu" );
kv->SetString( "title", "A rich message" );
kv->SetInt( "level", 1 );
kv->SetInt( "time", 20 );
kv->SetString( "msg", "This is a long long long text string.\n\nIt also has line breaks." );
helpers->CreateMessage( pEntity, DIALOG_TEXT, kv, this );
kv->deleteThis();
return PLUGIN_STOP; // we handled this function
}
else if ( FStrEq( pcmd, "msg" ) )
{
KeyValues *kv = new KeyValues( "menu" );
kv->SetString( "title", "Just a simple hello" );
kv->SetInt( "level", 1 );
kv->SetInt( "time", 20 );
helpers->CreateMessage( pEntity, DIALOG_MSG, kv, this );
kv->deleteThis();
return PLUGIN_STOP; // we handled this function
}
else if ( FStrEq( pcmd, "entry" ) )
{
KeyValues *kv = new KeyValues( "entry" );
kv->SetString( "title", "Stuff" );
kv->SetString( "msg", "Enter something" );
kv->SetString( "command", "say" ); // anything they enter into the dialog turns into a say command
kv->SetInt( "level", 1 );
kv->SetInt( "time", 20 );
helpers->CreateMessage( pEntity, DIALOG_ENTRY, kv, this );
kv->deleteThis();
return PLUGIN_STOP; // we handled this function
}
#ifdef SAMPLE_TF2_PLUGIN
else if ( FStrEq( pcmd, "gameinfo" ) )
{
IGameInfo *gameInfo = gameinfomanager->GetGameInfo();
if (!gameInfo)
return PLUGIN_STOP;
Msg("=== Game Information ===\n");
Msg("Game Type: %i / %s\n", gameInfo->GetInfo_GameType(), gameInfo->GetInfo_GameTypeName() );
int teamCount = gameInfo->GetInfo_GetTeamCount();
Msg("Num Teams: %i\n", teamCount );
Msg("Player Counts:\n");
for (int i = 0;i<teamCount;i++)
{
//If this failes, we can assume the rest is invalid too.
if (!gameInfo->GetInfo_GetTeamName(i) )
continue;
Msg("Team: %s, Players: %i\n", gameInfo->GetInfo_GetTeamName(i), gameInfo->GetInfo_NumPlayersOnTeam(i) );
}
return PLUGIN_STOP;
}
// Sample to use the new CustomInfo added to TF2 for plugins
else if ( FStrEq( pcmd, "tfcond" ) )
{
IPlayerInfo *playerinfo = playerinfomanager->GetPlayerInfo( pEntity );
if (!playerinfo)
return PLUGIN_STOP;
pluginvariant conditionValue;
pluginvariant emptyVariant;
if (!playerinfo->GetCustomInfo(TFPLAYERINFO_CONDITIONS, conditionValue, emptyVariant))
{
Msg("unable to retrieve conditions!\n");
return PLUGIN_STOP;
}
Msg("Disguising?: %s\n", TFPlayerHasCondition(conditionValue.Int(), TF_COND_DISGUISING ) ? "yes" : "no" );
Msg("Disguised?: %s\n", TFPlayerHasCondition(conditionValue.Int(), TF_COND_DISGUISED ) ? "yes" : "no" );
Msg("Stealthed?: %s\n", TFPlayerHasCondition(conditionValue.Int(), TF_COND_STEALTHED ) ? "yes" : "no" );
Msg("Invulnerable?: %s\n", TFPlayerHasCondition(conditionValue.Int(), TF_COND_INVULNERABLE ) ? "yes" : "no" );
Msg("Teleported Recently?: %s\n", TFPlayerHasCondition(conditionValue.Int(), TF_COND_TELEPORTED ) ? "yes" : "no" );
Msg("Selected for Teleportation?: %s\n", TFPlayerHasCondition(conditionValue.Int(), TF_COND_SELECTED_TO_TELEPORT ) ? "yes" : "no" );
Msg("On Fire?: %s\n", TFPlayerHasCondition(conditionValue.Int(), TF_COND_BURNING ) ? "yes" : "no" );
return PLUGIN_STOP;
}
else if ( FStrEq( pcmd, "sentry_status" ) )
{
SentryStatus(pEntity);
return PLUGIN_STOP;
}
else if ( FStrEq( pcmd, "class_status" ) )
{
ClassStatus(pEntity);
return PLUGIN_STOP;
}
else if ( FStrEq( pcmd, "flag_status" ) )
{
FlagStatus(pEntity);
return PLUGIN_STOP;
}
#ifdef GAME_DLL
else if ( FStrEq( pcmd, "cbe_test" ) )
{
IPlayerInfo *playerinfo = playerinfomanager->GetPlayerInfo( pEntity );
if (!playerinfo)
return PLUGIN_STOP;
CBaseEntity *pEnt = static_cast< CBaseEntity* >(entityinfomanager->GetEntity( pEntity ));
if (pEnt)
Msg("got a pointer to CBaseEntity..\n");
Msg("attempting to print this entities modelname directly..\n");
Msg("ModelName: %s\n", STRING(pEnt->GetModelName()) );
return PLUGIN_STOP;
}
#endif
#endif
return PLUGIN_CONTINUE;
}
//---------------------------------------------------------------------------------
// Purpose: called when a client is authenticated
//---------------------------------------------------------------------------------
PLUGIN_RESULT CEmptyServerPlugin::NetworkIDValidated( const char *pszUserName, const char *pszNetworkID )
{
return PLUGIN_CONTINUE;
}
//---------------------------------------------------------------------------------
// Purpose: called when a cvar value query is finished
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::OnQueryCvarValueFinished( QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue )
{
Msg( "Cvar query (cookie: %d, status: %d) - name: %s, value: %s\n", iCookie, eStatus, pCvarName, pCvarValue );
}
void CEmptyServerPlugin::OnEdictAllocated( edict_t *edict )
{
}
void CEmptyServerPlugin::OnEdictFreed( const edict_t *edict )
{
}
//---------------------------------------------------------------------------------
// Purpose: called when an event is fired
//---------------------------------------------------------------------------------
void CEmptyServerPlugin::FireGameEvent( KeyValues * event )
{
const char * name = event->GetName();
Msg( "CEmptyServerPlugin::FireGameEvent: Got event \"%s\"\n", name );
}
//---------------------------------------------------------------------------------
// Purpose: an example of how to implement a new command
//---------------------------------------------------------------------------------
CON_COMMAND( empty_version, "prints the version of the empty plugin" )
{
Msg( "Version:2.0.0.0\n" );
}
CON_COMMAND( empty_log, "logs the version of the empty plugin" )
{
engine->LogPrint( "Version:2.0.0.0\n" );
}
//---------------------------------------------------------------------------------
// Purpose: an example cvar
//---------------------------------------------------------------------------------
static ConVar empty_cvar("plugin_empty", "0", FCVAR_NOTIFY, "Example plugin cvar");

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
LIBRARY smdlexp
EXPORTS
LibDescription @1
LibNumberClasses @2
LibClassDesc @3
LibVersion @4
SECTIONS
.data READ WRITE

View File

@@ -0,0 +1,325 @@
# Microsoft Developer Studio Generated NMAKE File, Format Version 4.20
# ** DO NOT EDIT **
# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
!IF "$(CFG)" == ""
CFG=smdlexp - Win32 Debug
!MESSAGE No configuration specified. Defaulting to smdlexp - Win32 Debug.
!ENDIF
!IF "$(CFG)" != "smdlexp - Win32 Release" && "$(CFG)" !=\
"smdlexp - Win32 Debug"
!MESSAGE Invalid configuration "$(CFG)" specified.
!MESSAGE You can specify a configuration when running NMAKE on this makefile
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "smdlexp.mak" CFG="smdlexp - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "smdlexp - Win32 Release" (based on\
"Win32 (x86) Dynamic-Link Library")
!MESSAGE "smdlexp - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")
!MESSAGE
!ERROR An invalid configuration is specified.
!ENDIF
!IF "$(OS)" == "Windows_NT"
NULL=
!ELSE
NULL=nul
!ENDIF
################################################################################
# Begin Project
# PROP Target_Last_Scanned "smdlexp - Win32 Debug"
RSC=rc.exe
MTL=mktyplib.exe
CPP=cl.exe
!IF "$(CFG)" == "smdlexp - Win32 Release"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 0
# PROP BASE Output_Dir "Release"
# PROP BASE Intermediate_Dir "Release"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 0
# PROP Output_Dir "Release"
# PROP Intermediate_Dir "Release"
# PROP Target_Dir ""
OUTDIR=.\Release
INTDIR=.\Release
ALL : "..\..\..\3DSMAX\STDPLUGS\SMDLEXP.DLE"
CLEAN :
-@erase "$(INTDIR)\smdlexp.obj"
-@erase "$(INTDIR)\smdlexp.res"
-@erase "$(OUTDIR)\SMDLEXP.exp"
-@erase "$(OUTDIR)\SMDLEXP.lib"
-@erase "..\..\..\3DSMAX\STDPLUGS\SMDLEXP.DLE"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
# ADD CPP /nologo /MT /W3 /GX /O2 /I "\3DSMAX2.5\MAXSDK\INCLUDE" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /YX /c
CPP_PROJ=/nologo /MT /W3 /GX /O2 /I "\3DSMAX2.5\MAXSDK\INCLUDE" /D "WIN32" /D\
"NDEBUG" /D "_WINDOWS" /Fp"$(INTDIR)/smdlexp.pch" /YX /Fo"$(INTDIR)/" /c
CPP_OBJS=.\Release/
CPP_SBRS=.\.
# ADD BASE MTL /nologo /D "NDEBUG" /win32
# ADD MTL /nologo /D "NDEBUG" /win32
MTL_PROJ=/nologo /D "NDEBUG" /win32
# ADD BASE RSC /l 0x409 /d "NDEBUG"
# ADD RSC /l 0x409 /d "NDEBUG"
RSC_PROJ=/l 0x409 /fo"$(INTDIR)/smdlexp.res" /d "NDEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
BSC32_FLAGS=/nologo /o"$(OUTDIR)/smdlexp.bsc"
BSC32_SBRS= \
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /subsystem:windows /dll /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib COMCTL32.LIB /nologo /subsystem:windows /dll /machine:I386 /out:"\3DSMAX\STDPLUGS\SMDLEXP.DLE"
LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib\
advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib COMCTL32.LIB /nologo\
/subsystem:windows /dll /incremental:no /pdb:"$(OUTDIR)/SMDLEXP.pdb"\
/machine:I386 /def:".\smdlexp.def" /out:"\3DSMAX\STDPLUGS\SMDLEXP.DLE"\
/implib:"$(OUTDIR)/SMDLEXP.lib"
DEF_FILE= \
".\smdlexp.def"
LINK32_OBJS= \
"$(INTDIR)\smdlexp.obj" \
"$(INTDIR)\smdlexp.res" \
"..\..\..\quiver\src\utils\3dsmax\CORE.LIB" \
"..\..\..\quiver\src\utils\3dsmax\GEOM.LIB" \
"..\..\..\quiver\src\utils\3dsmax\MESH.LIB" \
"..\..\..\quiver\src\utils\3dsmax\UTIL.LIB"
"..\..\..\3DSMAX\STDPLUGS\SMDLEXP.DLE" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
!ELSEIF "$(CFG)" == "smdlexp - Win32 Debug"
# PROP BASE Use_MFC 0
# PROP BASE Use_Debug_Libraries 1
# PROP BASE Output_Dir "Debug"
# PROP BASE Intermediate_Dir "Debug"
# PROP BASE Target_Dir ""
# PROP Use_MFC 0
# PROP Use_Debug_Libraries 1
# PROP Output_Dir "Debug"
# PROP Intermediate_Dir "Debug"
# PROP Target_Dir ""
OUTDIR=.\Debug
INTDIR=.\Debug
ALL : "..\..\..\3DSMAX\STDPLUGS\SMDLEXP.DLE" "$(OUTDIR)\smdlexp.bsc"
CLEAN :
-@erase "$(INTDIR)\smdlexp.obj"
-@erase "$(INTDIR)\smdlexp.res"
-@erase "$(INTDIR)\smdlexp.sbr"
-@erase "$(INTDIR)\vc40.idb"
-@erase "$(INTDIR)\vc40.pdb"
-@erase "$(OUTDIR)\smdlexp.bsc"
-@erase "$(OUTDIR)\SMDLEXP.exp"
-@erase "$(OUTDIR)\SMDLEXP.lib"
-@erase "$(OUTDIR)\SMDLEXP.pdb"
-@erase "..\..\..\3DSMAX\STDPLUGS\SMDLEXP.DLE"
-@erase "..\..\..\3DSMAX\STDPLUGS\SMDLEXP.ILK"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /YX /c
# ADD CPP /nologo /MD /W3 /Gm /GX /Zi /Od /I "\3DSMAX2.5\MAXSDK\INCLUDE" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /FR /YX /c
CPP_PROJ=/nologo /MD /W3 /Gm /GX /Zi /Od /I "\3DSMAX2.5\MAXSDK\INCLUDE" /D\
"WIN32" /D "_DEBUG" /D "_WINDOWS" /FR"$(INTDIR)/" /Fp"$(INTDIR)/smdlexp.pch"\
/YX /Fo"$(INTDIR)/" /Fd"$(INTDIR)/" /c
CPP_OBJS=.\Debug/
CPP_SBRS=.\Debug/
# ADD BASE MTL /nologo /D "_DEBUG" /win32
# ADD MTL /nologo /D "_DEBUG" /win32
MTL_PROJ=/nologo /D "_DEBUG" /win32
# ADD BASE RSC /l 0x409 /d "_DEBUG"
# ADD RSC /l 0x409 /d "_DEBUG"
RSC_PROJ=/l 0x409 /fo"$(INTDIR)/smdlexp.res" /d "_DEBUG"
BSC32=bscmake.exe
# ADD BASE BSC32 /nologo
# ADD BSC32 /nologo
BSC32_FLAGS=/nologo /o"$(OUTDIR)/smdlexp.bsc"
BSC32_SBRS= \
"$(INTDIR)\smdlexp.sbr"
"$(OUTDIR)\smdlexp.bsc" : "$(OUTDIR)" $(BSC32_SBRS)
$(BSC32) @<<
$(BSC32_FLAGS) $(BSC32_SBRS)
<<
LINK32=link.exe
# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib /nologo /subsystem:windows /dll /debug /machine:I386
# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib COMCTL32.LIB /nologo /subsystem:windows /dll /debug /machine:I386 /out:"\3DSMAX\STDPLUGS\SMDLEXP.DLE"
LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib\
advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib COMCTL32.LIB /nologo\
/subsystem:windows /dll /incremental:yes /pdb:"$(OUTDIR)/SMDLEXP.pdb" /debug\
/machine:I386 /def:".\smdlexp.def" /out:"\3DSMAX\STDPLUGS\SMDLEXP.DLE"\
/implib:"$(OUTDIR)/SMDLEXP.lib"
DEF_FILE= \
".\smdlexp.def"
LINK32_OBJS= \
"$(INTDIR)\smdlexp.obj" \
"$(INTDIR)\smdlexp.res" \
"..\..\..\quiver\src\utils\3dsmax\CORE.LIB" \
"..\..\..\quiver\src\utils\3dsmax\GEOM.LIB" \
"..\..\..\quiver\src\utils\3dsmax\MESH.LIB" \
"..\..\..\quiver\src\utils\3dsmax\UTIL.LIB"
"..\..\..\3DSMAX\STDPLUGS\SMDLEXP.DLE" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
!ENDIF
.c{$(CPP_OBJS)}.obj:
$(CPP) $(CPP_PROJ) $<
.cpp{$(CPP_OBJS)}.obj:
$(CPP) $(CPP_PROJ) $<
.cxx{$(CPP_OBJS)}.obj:
$(CPP) $(CPP_PROJ) $<
.c{$(CPP_SBRS)}.sbr:
$(CPP) $(CPP_PROJ) $<
.cpp{$(CPP_SBRS)}.sbr:
$(CPP) $(CPP_PROJ) $<
.cxx{$(CPP_SBRS)}.sbr:
$(CPP) $(CPP_PROJ) $<
################################################################################
# Begin Target
# Name "smdlexp - Win32 Release"
# Name "smdlexp - Win32 Debug"
!IF "$(CFG)" == "smdlexp - Win32 Release"
!ELSEIF "$(CFG)" == "smdlexp - Win32 Debug"
!ENDIF
################################################################################
# Begin Source File
SOURCE=.\smdlexp.cpp
DEP_CPP_SMDLE=\
".\smedefs.h"\
NODEP_CPP_SMDLE=\
".\ANIMTBL.H"\
".\DECOMP.H"\
".\istdplug.h"\
".\MAX.H"\
".\STDMAT.H"\
!IF "$(CFG)" == "smdlexp - Win32 Release"
"$(INTDIR)\smdlexp.obj" : $(SOURCE) $(DEP_CPP_SMDLE) "$(INTDIR)"
!ELSEIF "$(CFG)" == "smdlexp - Win32 Debug"
"$(INTDIR)\smdlexp.obj" : $(SOURCE) $(DEP_CPP_SMDLE) "$(INTDIR)"
"$(INTDIR)\smdlexp.sbr" : $(SOURCE) $(DEP_CPP_SMDLE) "$(INTDIR)"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\smdlexp.def
!IF "$(CFG)" == "smdlexp - Win32 Release"
!ELSEIF "$(CFG)" == "smdlexp - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=.\smdlexp.rc
"$(INTDIR)\smdlexp.res" : $(SOURCE) "$(INTDIR)"
$(RSC) $(RSC_PROJ) $(SOURCE)
# End Source File
################################################################################
# Begin Source File
SOURCE=\quiver\src\utils\3dsmax\UTIL.LIB
!IF "$(CFG)" == "smdlexp - Win32 Release"
!ELSEIF "$(CFG)" == "smdlexp - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=\quiver\src\utils\3dsmax\GEOM.LIB
!IF "$(CFG)" == "smdlexp - Win32 Release"
!ELSEIF "$(CFG)" == "smdlexp - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=\quiver\src\utils\3dsmax\MESH.LIB
!IF "$(CFG)" == "smdlexp - Win32 Release"
!ELSEIF "$(CFG)" == "smdlexp - Win32 Debug"
!ENDIF
# End Source File
################################################################################
# Begin Source File
SOURCE=\quiver\src\utils\3dsmax\CORE.LIB
!IF "$(CFG)" == "smdlexp - Win32 Release"
!ELSEIF "$(CFG)" == "smdlexp - Win32 Debug"
!ENDIF
# End Source File
# End Target
# End Project
################################################################################

View File

@@ -0,0 +1,147 @@
//Microsoft Developer Studio generated resource script.
//
#include "smexprc.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "afxres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (U.S.) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
IDD_EXPORTOPTIONS DIALOG DISCARDABLE 0, 0, 186, 42
STYLE DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "SMD Exporter"
FONT 8, "MS Sans Serif"
BEGIN
DEFPUSHBUTTON "OK",IDOK,129,7,50,14
PUSHBUTTON "Cancel",IDCANCEL,129,22,50,14
CONTROL "Skeletal Animation",IDC_CHECK_SKELETAL,"Button",
BS_AUTORADIOBUTTON | WS_GROUP,15,10,74,10
CONTROL "Reference Frame",IDC_CHECK_REFFRAME,"Button",
BS_AUTORADIOBUTTON | WS_GROUP,15,24,71,10
END
/////////////////////////////////////////////////////////////////////////////
//
// DESIGNINFO
//
#ifdef APSTUDIO_INVOKED
GUIDELINES DESIGNINFO DISCARDABLE
BEGIN
IDD_EXPORTOPTIONS, DIALOG
BEGIN
LEFTMARGIN, 7
RIGHTMARGIN, 179
TOPMARGIN, 7
BOTTOMMARGIN, 36
END
END
#endif // APSTUDIO_INVOKED
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE DISCARDABLE
BEGIN
"smexprc.h\0"
END
2 TEXTINCLUDE DISCARDABLE
BEGIN
"#include ""afxres.h""\r\n"
"\0"
END
3 TEXTINCLUDE DISCARDABLE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
#ifndef _MAC
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 2,0,0,1
PRODUCTVERSION 2,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x40004L
FILETYPE 0x2L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904b0"
BEGIN
VALUE "Comments", "\0"
VALUE "CompanyName", "Valve LLC\0"
VALUE "FileDescription", "SMD file exporter (3D Studio Max plugin)\0"
VALUE "FileVersion", "2, 0, 0, 1\0"
VALUE "InternalName", "SMDLEXP\0"
VALUE "LegalCopyright", "Copyright © 1998, Valve LLC\0"
VALUE "LegalTrademarks", "The following are registered trademarks of Autodesk, Inc.: 3D Studio MAX. The following are trademarks of Autodesk, Inc.: Kinetix, Kinetix(logo), BIPED, Physique, Character Studio, MAX DWG, DWG Unplugged, Heidi, FLI, FLC, DXF.\0"
VALUE "OriginalFilename", "SMDLEXP.DLE\0"
VALUE "PrivateBuild", "\0"
VALUE "ProductName", "Valve LLC SMDLEXP\0"
VALUE "ProductVersion", "2, 0, 0, 1\0"
VALUE "SpecialBuild", "\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1200
END
END
#endif // !_MAC
#endif // English (U.S.) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED

View File

@@ -0,0 +1,178 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
//===================================================================
// Useful macros
//
#define CONSTRUCTOR
#define DESTRUCTOR
#define EXPORT_THIS __declspec(dllexport)
#define DEFAULT_EXT _T("smd")
#define FStrEq(sz1, sz2) (strcmp((sz1), (sz2)) == 0)
//===================================================================
// Class that implements the scene-export.
//
class SmdExportClass : public SceneExport
{
friend BOOL CALLBACK ExportOptionsDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
friend class DumpModelTEP;
friend class DumpDeformsTEP;
public:
CONSTRUCTOR SmdExportClass (void);
DESTRUCTOR ~SmdExportClass (void);
// Required by classes derived from SceneExport
virtual int ExtCount (void) { return 1; }
virtual const TCHAR* Ext (int i) { return DEFAULT_EXT; }
virtual const TCHAR* LongDesc (void) { return _T("Valve Skeletal Model Exporter for 3D Studio Max"); }
virtual const TCHAR* ShortDesc (void) { return _T("Valve SMD"); }
virtual const TCHAR* AuthorName (void) { return _T("Valve, LLC"); }
virtual const TCHAR* CopyrightMessage(void) { return _T("Copyright (c) 1998, Valve LLC"); }
virtual const TCHAR* OtherMessage1 (void) { return _T(""); }
virtual const TCHAR* OtherMessage2 (void) { return _T(""); }
virtual unsigned int Version (void) { return 201; }
virtual void ShowAbout (HWND hWnd) { return; }
// virtual int DoExport (const TCHAR *name, ExpInterface *ei, Interface *i);
virtual int DoExport(const TCHAR *name,ExpInterface *ei,Interface *i, BOOL suppressPrompts=FALSE,DWORD options=0); // Export file
// Integer constants for this class
enum
{
MAX_NAME_CHARS = 70,
UNDESIRABLE_NODE_MARKER = -7777
};
// For keeping info about each (non-ignored) 3dsMax node in the tree
typedef struct
{
char szNodeName[MAX_NAME_CHARS]; // usefull for lookups
Matrix3 mat3NodeTM; // node's transformation matrix (at time zero)
Matrix3 mat3ObjectTM; // object-offset transformation matrix (at time zero)
int imaxnodeParent; // cached index of parent node
float xRotFirstFrame; // 1st frame's X rotation
float yRotFirstFrame; // 1st frame's Y rotation
float zRotFirstFrame; // 1st frame's Z rotation
bool isMirrored;
} MaxNode;
MaxNode *m_rgmaxnode; // array of nodes
long m_imaxnodeMac; // # of nodes
// Animation metrics (gleaned from 3dsMax and cached for convenience)
Interval m_intervalOfAnimation;
TimeValue m_tvStart;
TimeValue m_tvEnd;
int m_tpf; // ticks-per-frame
private:
BOOL CollectNodes (ExpInterface *expiface);
BOOL DumpBones (FILE *pFile, ExpInterface *pexpiface);
BOOL DumpRotations (FILE *pFile, ExpInterface *pexpiface);
BOOL DumpModel (FILE *pFile, ExpInterface *pexpiface);
BOOL DumpDeforms (FILE *pFile, ExpInterface *pexpiface);
// Is this MAX file just the reference frame, or an animation?
// If TRUE, the "bones" and "mesh" files will be created.
// If FALSE, the "rots" file will be created.
BOOL m_fReferenceFrame;
};
//===================================================================
// Basically just a ClassFactory for communicating with 3DSMAX.
//
class SmdExportClassDesc : public ClassDesc
{
public:
int IsPublic (void) { return TRUE; }
void * Create (BOOL loading=FALSE) { return new SmdExportClass; }
const TCHAR * ClassName (void) { return _T("SmdExport"); }
SClass_ID SuperClassID (void) { return SCENE_EXPORT_CLASS_ID; }
Class_ID ClassID (void) { return Class_ID(0x774a43fd, 0x794d2210); }
const TCHAR * Category (void) { return _T(""); }
};
//===================================================================
// Tree Enumeration Callback
// Just counts the nodes in the node tree
//
class CountNodesTEP : public ITreeEnumProc
{
public:
virtual int callback(INode *node);
int m_cNodes; // running count of nodes
};
//===================================================================
// Tree Enumeration Callback
// Collects the nodes in the tree into the global array
//
class CollectNodesTEP : public ITreeEnumProc
{
public:
virtual int callback(INode *node);
SmdExportClass *m_phec;
};
//===================================================================
// Tree Enumeration Callback
// Dumps the bone offsets to a file.
//
class DumpNodesTEP : public ITreeEnumProc
{
public:
virtual int callback(INode *node);
FILE *m_pfile; // write to this file
SmdExportClass *m_phec;
};
//===================================================================
// Tree Enumeration Callback
// Dumps the per-frame bone rotations to a file.
//
class DumpFrameRotationsTEP : public ITreeEnumProc
{
public:
virtual int callback(INode *node);
void cleanup(void);
FILE *m_pfile; // write to this file
TimeValue m_tvToDump; // dump snapshot at this frame time
SmdExportClass *m_phec;
};
//===================================================================
// Tree Enumeration Callback
// Dumps the triangle meshes to a file.
//
class DumpModelTEP : public ITreeEnumProc
{
public:
virtual int callback(INode *node);
void cleanup(void);
FILE *m_pfile; // write to this file
TimeValue m_tvToDump; // dump snapshot at this frame time
SmdExportClass *m_phec;
IPhyContextExport *m_mcExport;
IPhysiqueExport *m_phyExport;
Modifier *m_phyMod;
Modifier *m_bonesProMod;
BonesPro_WeightArray *m_wa;
private:
Point3 Pt3GetRVertexNormal(RVertex *prvertex, DWORD smGroupFace);
void DumpWeights( int iVertex );
};

View File

@@ -0,0 +1,28 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by smdlexp.rc
//
#define IDD_SMDLEXP_UI 101
#define IDD_EXPORTOPTIONS 101
#define IDC_CHECK_SKELETAL 1000
#define IDC_CHECK_DEFORM 1001
#define IDC_CHECK_REFFRAME 1002
#define IDC_CHECK_PHYSIQUE 1003
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1006
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif

View File

@@ -0,0 +1,243 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectName>Tgadiff</ProjectName>
<ProjectGuid>{C6A1B4E3-DFD8-CD7B-5CBF-D3267A96FF21}</ProjectGuid>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>tgadiff</TargetName>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<CharacterSet>MultiByte</CharacterSet>
<TargetName>tgadiff</TargetName>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">.\Debug\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">true</PostBuildEventUseInBuild>
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</OutDir>
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">.\Release\win32\</IntDir>
<ExecutablePath Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\devtools\vstools;$(ExecutablePath);$(Path)</ExecutablePath>
<PreBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreBuildEventUseInBuild>
<PreLinkEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PreLinkEventUseInBuild>
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
<GenerateManifest Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</GenerateManifest>
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">true</PostBuildEventUseInBuild>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 tgadiff.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP</AdditionalOptions>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1</AdditionalIncludeDirectories>
<PreprocessorDefinitions>_HAS_ITERATOR_DEBUGGING=0;WIN32;_WIN32;_DEBUG;DEBUG;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\tgadiff;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<BasicRuntimeChecks>Default</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<BufferSecurityCheck>true</BufferSecurityCheck>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\tgadiff.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmt</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Console</SubSystem>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/tgadiff.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<PreBuildEvent>
<Command>if EXIST ..\..\..\game\bin\$(TargetFileName) for /f &quot;delims=&quot; %%A in (&apos;attrib &quot;..\..\..\game\bin\$(TargetFileName)&quot;&apos;) do set valveTmpIsReadOnly=&quot;%%A&quot;&#x0D;&#x0A;set valveTmpIsReadOnlyLetter=%valveTmpIsReadOnly:~6,1%&#x0D;&#x0A;if &quot;%valveTmpIsReadOnlyLetter%&quot;==&quot;R&quot; del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;if exist ..\..\devtools\bin\vpc.exe ..\..\devtools\bin\vpc.exe -crc2 tgadiff.vcxproj&#x0D;&#x0A;if ERRORLEVEL 1 exit 1</Command>
</PreBuildEvent>
<ClCompile>
<AdditionalOptions> /MP /d2Zi+</AdditionalOptions>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>AnySuitable</InlineFunctionExpansion>
<IntrinsicFunctions>true</IntrinsicFunctions>
<FavorSizeOrSpeed>Speed</FavorSizeOrSpeed>
<AdditionalIncludeDirectories>..\..\common;..\..\public;..\..\public\tier0;..\..\public\tier1</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE;RAD_TELEMETRY_DISABLED;COMPILER_MSVC32;VPCGAMECAPS=VALVE;PROJECTDIR=D:\dev\games\rel\hl2\src\utils\tgadiff;_DLL_EXT=.dll;VPCGAME=valve</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<ExceptionHandling>false</ExceptionHandling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<BufferSecurityCheck>false</BufferSecurityCheck>
<FunctionLevelLinking>true</FunctionLevelLinking>
<EnableEnhancedInstructionSet>StreamingSIMDExtensions</EnableEnhancedInstructionSet>
<FloatingPointModel>Fast</FloatingPointModel>
<TreatWChar_tAsBuiltInType>true</TreatWChar_tAsBuiltInType>
<ForceConformanceInForLoopScope>true</ForceConformanceInForLoopScope>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<OpenMPSupport>false</OpenMPSupport>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<ExpandAttributedSource>false</ExpandAttributedSource>
<AssemblerOutput>NoListing</AssemblerOutput>
<AssemblerListingLocation>$(IntDir)/</AssemblerListingLocation>
<ObjectFileName>$(IntDir)/</ObjectFileName>
<ProgramDataBaseFileName>$(IntDir)/</ProgramDataBaseFileName>
<BrowseInformation>false</BrowseInformation>
<WarningLevel>Level4</WarningLevel>
<TreatWarningAsError>true</TreatWarningAsError>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>CompileAsCpp</CompileAs>
<BrowseInformationFile>$(IntDir)/</BrowseInformationFile>
<ErrorReporting>Prompt</ErrorReporting>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;_CRT_SECURE_NO_DEPRECATE;_CRT_NONSTDC_NO_DEPRECATE</PreprocessorDefinitions>
<Culture>1033</Culture>
</ResourceCompile>
<PreLinkEvent>
</PreLinkEvent>
<Link>
<AdditionalOptions> /DYNAMICBASE /NXCOMPAT /ignore:4221</AdditionalOptions>
<AdditionalDependencies>%(AdditionalDependencies)</AdditionalDependencies>
<ShowProgress>NotSet</ShowProgress>
<OutputFile>$(OutDir)\tgadiff.exe</OutputFile>
<SuppressStartupBanner>true</SuppressStartupBanner>
<IgnoreSpecificDefaultLibraries>libc;libcd;libcmtd</IgnoreSpecificDefaultLibraries>
<GenerateDebugInformation>true</GenerateDebugInformation>
<ProgramDatabaseFile>$(IntDir)/$(TargetName).pdb</ProgramDatabaseFile>
<GenerateMapFile>false</GenerateMapFile>
<MapFileName>$(IntDir)/$(TargetName).map</MapFileName>
<SubSystem>Console</SubSystem>
<OptimizeReferences>true</OptimizeReferences>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<BaseAddress> </BaseAddress>
<TargetMachine>MachineX86</TargetMachine>
<LinkErrorReporting>PromptImmediately</LinkErrorReporting>
</Link>
<Manifest>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Manifest>
<Xdcmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Xdcmake>
<Bscmake>
<SuppressStartupBanner>true</SuppressStartupBanner>
<OutputFile>$(OutDir)/tgadiff.bsc</OutputFile>
</Bscmake>
<PostBuildEvent>
<Message>Publishing to ..\..\..\game\bin</Message>
<Command>if not exist &quot;..\..\..\game\bin&quot; mkdir &quot;..\..\..\game\bin&quot;&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetFileName) ..\..\..\game\bin\$(TargetFileName)&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;if exist &quot;$(TargetDir)&quot;$(TargetName).map copy &quot;$(TargetDir)&quot;$(TargetName).map ..\..\..\game\bin\$(TargetName).map&#x0D;&#x0A;copy &quot;$(TargetDir)&quot;$(TargetName).pdb ..\..\..\game\bin\$(TargetName).pdb&#x0D;&#x0A;if ERRORLEVEL 1 goto BuildEventFailed&#x0D;&#x0A;goto BuildEventOK&#x0D;&#x0A;:BuildEventFailed&#x0D;&#x0A;echo *** ERROR! PostBuildStep FAILED for $(ProjectName)! EXE or DLL is probably running. ***&#x0D;&#x0A;del /q &quot;$(TargetDir)&quot;$(TargetFileName)&#x0D;&#x0A;exit 1&#x0D;&#x0A;:BuildEventOK&#x0D;&#x0A;</Command>
</PostBuildEvent>
<CustomBuildStep>
</CustomBuildStep>
</ItemDefinitionGroup>
<ItemGroup>
<Library Include="..\..\lib\public\bitmap.lib" />
<Library Include="..\..\lib\public\mathlib.lib" />
<Library Include="..\..\lib\public\tier0.lib" />
<Library Include="..\..\lib\public\tier1.lib" />
<Library Include="..\..\lib\public\tier2.lib" />
<Library Include="..\..\lib\public\vstdlib.lib" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">NotUsing</PrecompiledHeader>
</ClCompile>
<ClCompile Include="tgadiff.cpp" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Message Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(IntDir)\%(Filename).obj</Outputs>
<Message Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Compiling pointeroverride.asm</Message>
<Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">&quot;$(VCInstallDir)bin\ml.exe&quot; /c /Cp /Zi /Fo&quot;$(IntDir)\%(Filename).obj&quot; &quot;%(FullPath)&quot;</Command>
<Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(IntDir)\%(Filename).obj</Outputs>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Link Libraries">
<UniqueIdentifier>{C5D73B3A-C648-896C-B7CE-F174808E5BA5}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{BA03E055-4FA2-FCE3-8A1C-D348547D379C}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<Library Include="..\..\lib\public\bitmap.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\mathlib.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier0.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier1.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\tier2.lib">
<Filter>Link Libraries</Filter>
</Library>
<Library Include="..\..\lib\public\vstdlib.lib">
<Filter>Link Libraries</Filter>
</Library>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\public\tier0\memoverride.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="tgadiff.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<CustomBuild Include="..\..\public\tier0\pointeroverride.asm">
<Filter>Source Files</Filter>
</CustomBuild>
</ItemGroup>
<ItemGroup>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,184 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
#include <stdlib.h>
#include <stdio.h>
#include <direct.h>
#include "bitmap/tgaloader.h"
#include "bitmap/tgawriter.h"
#include "tier1/utlbuffer.h"
#include "tier2/tier2.h"
#include "mathlib/mathlib.h"
#include "filesystem.h"
void Usage( void )
{
printf( "Usage: tgadiff src1.tga src2.tga diff.tga\n" );
exit( -1 );
}
int main( int argc, char **argv )
{
if( argc != 4 )
{
Usage();
}
MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f );
InitDefaultFileSystem();
char pCurrentDirectory[MAX_PATH];
if ( _getcwd( pCurrentDirectory, sizeof(pCurrentDirectory) ) == NULL )
{
fprintf( stderr, "Unable to get the current directory\n" );
return -1;
}
Q_FixSlashes( pCurrentDirectory );
Q_StripTrailingSlash( pCurrentDirectory );
char pBuf[3][MAX_PATH];
const char *pFileName[3];
for ( int i = 0; i < 3; ++i )
{
if ( !Q_IsAbsolutePath( argv[i+1] ) )
{
Q_snprintf( pBuf[i], sizeof(pBuf[i]), "%s\\%s", pCurrentDirectory, argv[i+1] );
pFileName[i] = pBuf[i];
}
else
{
pFileName[i] = argv[i+1];
}
}
int width1, height1;
ImageFormat imageFormat1;
float gamma1;
CUtlBuffer buf1;
if ( !g_pFullFileSystem->ReadFile( pFileName[0], NULL, buf1 ) )
{
fprintf( stderr, "%s not found\n", pFileName[0] );
return -1;
}
if( !TGALoader::GetInfo( buf1, &width1, &height1, &imageFormat1, &gamma1 ) )
{
printf( "error loading %s\n", pFileName[0] );
exit( -1 );
}
int width2, height2;
ImageFormat imageFormat2;
float gamma2;
CUtlBuffer buf2;
if ( !g_pFullFileSystem->ReadFile( pFileName[1], NULL, buf2 ) )
{
fprintf( stderr, "%s not found\n", pFileName[1] );
return -1;
}
if( !TGALoader::GetInfo( buf2, &width2, &height2, &imageFormat2, &gamma2 ) )
{
printf( "error loading %s\n", pFileName[1] );
exit( -1 );
}
if( width1 != width2 || height1 != height2 )
{
printf( "image dimensions different (%dx%d!=%dx%d): can't do diff for %s\n",
width1, height1, width2, height2, pFileName[2] );
exit( -1 );
}
#if 0
// have to allow for different formats for now due to *.txt file screwup.
if( imageFormat1 != imageFormat2 )
{
printf( "image format different (%s!=%s). . can't do diff for %s\n",
ImageLoader::GetName( imageFormat1 ), ImageLoader::GetName( imageFormat2 ), pFileName[2] );
exit( -1 );
}
#endif
if( gamma1 != gamma2 )
{
printf( "image gamma different (%f!=%f). . can't do diff for %s\n", gamma1, gamma2, pFileName[2] );
exit( -1 );
}
unsigned char *pImage1Tmp = new unsigned char[ImageLoader::GetMemRequired( width1, height1, 1, imageFormat1, false )];
unsigned char *pImage2Tmp = new unsigned char[ImageLoader::GetMemRequired( width2, height2, 1, imageFormat2, false )];
buf1.SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
if( !TGALoader::Load( pImage1Tmp, buf1, width1, height1, imageFormat1, 2.2f, false ) )
{
printf( "error loading %s\n", pFileName[0] );
exit( -1 );
}
buf2.SeekGet( CUtlBuffer::SEEK_HEAD, 0 );
if( !TGALoader::Load( pImage2Tmp, buf2, width2, height2, imageFormat2, 2.2f, false ) )
{
printf( "error loading %s\n", pFileName[1] );
exit( -1 );
}
unsigned char *pImage1 = new unsigned char[ImageLoader::GetMemRequired( width1, height1, 1, IMAGE_FORMAT_ABGR8888, false )];
unsigned char *pImage2 = new unsigned char[ImageLoader::GetMemRequired( width2, height2, 1, IMAGE_FORMAT_ABGR8888, false )];
unsigned char *pDiff = new unsigned char[ImageLoader::GetMemRequired( width2, height2, 1, IMAGE_FORMAT_ABGR8888, false )];
ImageLoader::ConvertImageFormat( pImage1Tmp, imageFormat1, pImage1, IMAGE_FORMAT_ABGR8888, width1, height1, 0, 0 );
ImageLoader::ConvertImageFormat( pImage2Tmp, imageFormat2, pImage2, IMAGE_FORMAT_ABGR8888, width2, height2, 0, 0 );
int sizeInBytes = ImageLoader::SizeInBytes( IMAGE_FORMAT_ABGR8888 );
bool isDifferent = false;
for( int i = 0; i < width1 * height1 * sizeInBytes; i++ )
{
int d;
d = pImage2[i] - pImage1[i];
pDiff[i] = d > 0 ? d : -d;
if( d != 0 )
{
isDifferent = true;
}
}
if( !isDifferent )
{
printf( "Files are the same %s %s : not generating %s\n", pFileName[0], pFileName[1], pFileName[2] );
exit( -1 );
}
else
{
printf( "Generating diff: %s!\n", pFileName[2] );
}
ImageFormat dstImageFormat;
// get rid of this until we get the formats matching
// if( sizeInBytes == 3 )
// {
// dstImageFormat = IMAGE_FORMAT_RGB888;
// }
// else
{
dstImageFormat = IMAGE_FORMAT_RGBA8888;
}
CUtlBuffer outBuffer;
if ( !TGAWriter::WriteToBuffer( pDiff, outBuffer, width1, height1, dstImageFormat, dstImageFormat ) )
{
printf( "error writing %s to buffer\n", pFileName[2] );
exit( -1 );
}
if ( !g_pFullFileSystem->WriteFile( pFileName[2], NULL, outBuffer ) )
{
fprintf( stderr, "unable to write %s\n", pFileName[2] );
return -1;
}
return 0;
}

View File

@@ -0,0 +1,285 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include "vbsp.h"
#include "BoundBox.h"
//#include "hammer_mathlib.h"
//#include "MapDefs.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
float rint(float f)
{
if (f > 0.0f) {
return (float) floor(f + 0.5f);
} else if (f < 0.0f) {
return (float) ceil(f - 0.5f);
} else
return 0.0f;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
BoundBox::BoundBox(void)
{
ResetBounds();
}
BoundBox::BoundBox(const Vector &mins, const Vector &maxs)
{
bmins = mins;
bmaxs = maxs;
}
//-----------------------------------------------------------------------------
// Purpose: Sets the box to an uninitialized state, so that calls to UpdateBounds
// will properly set the mins and maxs.
//-----------------------------------------------------------------------------
void BoundBox::ResetBounds(void)
{
bmins[0] = bmins[1] = bmins[2] = COORD_NOTINIT;
bmaxs[0] = bmaxs[1] = bmaxs[2] = -COORD_NOTINIT;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pt -
//-----------------------------------------------------------------------------
void BoundBox::UpdateBounds(const Vector& pt)
{
if(pt[0] < bmins[0])
bmins[0] = pt[0];
if(pt[1] < bmins[1])
bmins[1] = pt[1];
if(pt[2] < bmins[2])
bmins[2] = pt[2];
if(pt[0] > bmaxs[0])
bmaxs[0] = pt[0];
if(pt[1] > bmaxs[1])
bmaxs[1] = pt[1];
if(pt[2] > bmaxs[2])
bmaxs[2] = pt[2];
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : bmins -
// bmaxs -
//-----------------------------------------------------------------------------
void BoundBox::UpdateBounds(const Vector& mins, const Vector& maxs)
{
if(mins[0] < bmins[0])
bmins[0] = mins[0];
if(mins[1] < bmins[1])
bmins[1] = mins[1];
if(mins[2] < bmins[2])
bmins[2] = mins[2];
if(maxs[0] > bmaxs[0])
bmaxs[0] = maxs[0];
if(maxs[1] > bmaxs[1])
bmaxs[1] = maxs[1];
if(maxs[2] > bmaxs[2])
bmaxs[2] = maxs[2];
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pBox -
//-----------------------------------------------------------------------------
void BoundBox::UpdateBounds(const BoundBox *pBox)
{
UpdateBounds(pBox->bmins, pBox->bmaxs);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : ptdest -
//-----------------------------------------------------------------------------
void BoundBox::GetBoundsCenter(Vector& ptdest)
{
ptdest = (bmins + bmaxs)/2.0f;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pt -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool BoundBox::ContainsPoint(const Vector& pt) const
{
for (int i = 0; i < 3; i++)
{
if (pt[i] < bmins[i] || pt[i] > bmaxs[i])
{
return(false);
}
}
return(true);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pfMins -
// pfMaxs -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool BoundBox::IsIntersectingBox(const Vector& pfMins, const Vector& pfMaxs) const
{
if ((bmins[0] >= pfMaxs[0]) || (bmaxs[0] <= pfMins[0]))
{
return(false);
}
if ((bmins[1] >= pfMaxs[1]) || (bmaxs[1] <= pfMins[1]))
{
return(false);
}
if ((bmins[2] >= pfMaxs[2]) || (bmaxs[2] <= pfMins[2]))
{
return(false);
}
return(true);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : pfMins -
// pfMaxs -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool BoundBox::IsInsideBox(const Vector& pfMins, const Vector& pfMaxs) const
{
if ((bmins[0] < pfMins[0]) || (bmaxs[0] > pfMaxs[0]))
{
return(false);
}
if ((bmins[1] < pfMins[1]) || (bmaxs[1] > pfMaxs[1]))
{
return(false);
}
if ((bmins[2] < pfMins[2]) || (bmaxs[2] > pfMaxs[2]))
{
return(false);
}
return(true);
}
//-----------------------------------------------------------------------------
// Purpose: Returns whether this bounding box is valid, ie maxs >= mins.
//-----------------------------------------------------------------------------
bool BoundBox::IsValidBox(void) const
{
for (int i = 0; i < 3; i++)
{
if (bmins[i] > bmaxs[i])
{
return(false);
}
}
return(true);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : size -
//-----------------------------------------------------------------------------
void BoundBox::GetBoundsSize(Vector& size)
{
size[0] = bmaxs[0] - bmins[0];
size[1] = bmaxs[1] - bmins[1];
size[2] = bmaxs[2] - bmins[2];
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : iValue -
// iGridSize -
// Output :
//-----------------------------------------------------------------------------
static int Snap(/*int*/ float iValue, int iGridSize)
{
return (int)(rint(iValue/iGridSize) * iGridSize);
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : iGridSize -
//-----------------------------------------------------------------------------
void BoundBox::SnapToGrid(int iGridSize)
{
// does not alter the size of the box .. snaps its minimal coordinates
// to the grid size specified in iGridSize
Vector size;
GetBoundsSize(size);
for(int i = 0; i < 3; i++)
{
bmins[i] = (float)Snap(/* YWB (int)*/bmins[i], iGridSize);
bmaxs[i] = bmins[i] + size[i];
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : axis -
//-----------------------------------------------------------------------------
void BoundBox::Rotate90(int axis)
{
int e1 = AXIS_X, e2 = AXIS_Y;
// get bounds center first
Vector center;
GetBoundsCenter(center);
switch(axis)
{
case AXIS_Z:
e1 = AXIS_X;
e2 = AXIS_Y;
break;
case AXIS_X:
e1 = AXIS_Y;
e2 = AXIS_Z;
break;
case AXIS_Y:
e1 = AXIS_X;
e2 = AXIS_Z;
break;
}
float tmp1, tmp2;
tmp1 = bmins[e1] - center[e1] + center[e2];
tmp2 = bmaxs[e1] - center[e1] + center[e2];
bmins[e1] = bmins[e2] - center[e2] + center[e1];
bmaxs[e1] = bmaxs[e2] - center[e2] + center[e1];
bmins[e2] = tmp1;
bmaxs[e2] = tmp2;
}

View File

@@ -0,0 +1,79 @@
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: An axis aligned bounding box class.
//
// $NoKeywords: $
//=============================================================================//
#ifndef BOUNDBOX_H
#define BOUNDBOX_H
#ifdef _WIN32
#pragma once
#endif
#include "mathlib/vector.h"
#define COORD_NOTINIT ((float)(99999.0))
enum
{
AXIS_X = 0,
AXIS_Y,
AXIS_Z
};
class BoundBox
{
public:
BoundBox(void);
BoundBox(const Vector &mins, const Vector &maxs);
void ResetBounds(void);
inline void SetBounds(const Vector &mins, const Vector &maxs);
void UpdateBounds(const Vector& bmins, const Vector& bmaxs);
void UpdateBounds(const Vector& pt);
void UpdateBounds(const BoundBox *pBox);
void GetBoundsCenter(Vector& ptdest);
inline void GetBounds(Vector& Mins, Vector& Maxs);
virtual bool IsIntersectingBox(const Vector& pfMins, const Vector& pfMaxs) const;
bool IsInsideBox(const Vector& pfMins, const Vector& pfMaxs) const;
bool ContainsPoint(const Vector& pt) const;
bool IsValidBox(void) const;
void GetBoundsSize(Vector& size);
void SnapToGrid(int iGridSize);
void Rotate90(int axis);
Vector bmins;
Vector bmaxs;
};
//-----------------------------------------------------------------------------
// Purpose: Gets the bounding box as two vectors, a min and a max.
// Input : Mins - Receives the box's minima.
// Maxs - Receives the box's maxima.
//-----------------------------------------------------------------------------
void BoundBox::GetBounds(Vector &Mins, Vector &Maxs)
{
Mins = bmins;
Maxs = bmaxs;
}
//-----------------------------------------------------------------------------
// Purpose: Sets the box outright, equivalent to ResetBounds + UpdateBounds.
// Input : mins - Minima to set.
// maxs - Maxima to set.
//-----------------------------------------------------------------------------
void BoundBox::SetBounds(const Vector &mins, const Vector &maxs)
{
bmins = mins;
bmaxs = maxs;
}
#endif // BOUNDBOX_H

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