1
0
forked from metin2/client

Solution refactoring and restructuring, removed Boost dependency, removed unused tools

This commit is contained in:
2022-11-21 23:42:01 +02:00
parent 33f19f9ff6
commit 9ef9f39e88
817 changed files with 326 additions and 59698 deletions

299
src/EterBase/CPostIt.cpp Normal file
View File

@ -0,0 +1,299 @@
#include "StdAfx.h"
#include "CPostIt.h"
#include "../eterBase/utils.h"
class _CPostItMemoryBlock
{
public:
_CPostItMemoryBlock( void );
~_CPostItMemoryBlock( void );
BOOL Assign( HANDLE hBlock );
HANDLE CreateHandle( void );
BOOL DestroyHandle( void );
LPSTR Find( LPCSTR lpszKeyName );
BOOL Put( LPCSTR lpBuffer );
BOOL Put( LPCSTR lpszKeyName, LPCSTR lpBuffer );
BOOL Get( LPCSTR lpszKeyName, LPSTR lpBuffer, DWORD nSize );
protected:
typedef std::list<CHAR *> StrList;
typedef StrList::iterator StrListItr;
HANDLE m_hHandle;
StrList m_StrList;
};
CPostIt::CPostIt( LPCSTR szAppName ) : m_pMemoryBlock(NULL), m_bModified(FALSE)
{
Init( szAppName );
}
CPostIt::~CPostIt( void )
{
Destroy();
}
BOOL CPostIt::Init( LPCSTR szAppName )
{
if( szAppName == NULL || !*szAppName ) {
strcpy( m_szClipFormatName, "YMCF" );
} else {
strcpy( m_szClipFormatName, "YMCF_" );
strcat( m_szClipFormatName, szAppName );
}
return TRUE;
}
BOOL CPostIt::CopyTo( CPostIt *pPostIt, LPCSTR lpszKeyName )
{
if( m_pMemoryBlock == NULL )
return FALSE;
LPSTR szText = m_pMemoryBlock->Find( lpszKeyName );
if( szText == NULL )
return FALSE;
return pPostIt->Set( szText );
}
BOOL CPostIt::Flush( void )
{
if( m_bModified == FALSE )
return FALSE;
if( m_pMemoryBlock == NULL )
return FALSE;
UINT uDGPFormat;
uDGPFormat = ::RegisterClipboardFormatA( m_szClipFormatName );
if( ::OpenClipboard( NULL ) == FALSE )
return FALSE;
if( ::SetClipboardData( uDGPFormat, m_pMemoryBlock->CreateHandle() ) == NULL ) {
// DWORD dwLastError = ::GetLastError();
m_pMemoryBlock->DestroyHandle();
::CloseClipboard();
m_bModified = FALSE;
return FALSE;
}
::CloseClipboard();
m_bModified = FALSE;
return TRUE;
}
void CPostIt::Empty( void )
{
SAFE_DELETE( m_pMemoryBlock );
UINT uDGPFormat;
uDGPFormat = ::RegisterClipboardFormatA( m_szClipFormatName );
if( ::OpenClipboard( NULL ) == FALSE )
return;
HANDLE hClipboardMemory = ::GetClipboardData( uDGPFormat );
if( hClipboardMemory ) {
// ::GlobalFree( hClipboardMemory );
::SetClipboardData( uDGPFormat, NULL );
}
::CloseClipboard();
m_bModified = FALSE;
}
void CPostIt::Destroy( void )
{
Flush();
SAFE_DELETE( m_pMemoryBlock );
}
BOOL CPostIt::Set( LPCSTR lpszKeyName, LPCSTR lpBuffer )
{
if( m_pMemoryBlock == NULL )
m_pMemoryBlock = new _CPostItMemoryBlock;
m_pMemoryBlock->Put( lpszKeyName, lpBuffer );
m_bModified = TRUE;
return TRUE;
}
BOOL CPostIt::Set( LPCSTR lpszKeyName, DWORD dwValue )
{
CHAR szValue[12];
_snprintf( szValue, 12, "%d", dwValue );
return Set( lpszKeyName, szValue );
}
BOOL CPostIt::Set( LPCSTR lpBuffer )
{
if( lpBuffer == NULL )
return FALSE;
if( m_pMemoryBlock == NULL )
m_pMemoryBlock = new _CPostItMemoryBlock;
m_pMemoryBlock->Put( lpBuffer );
m_bModified = TRUE;
return TRUE;
}
BOOL CPostIt::Get( LPCSTR lpszKeyName, LPSTR lpBuffer, DWORD nSize )
{
if( m_pMemoryBlock == NULL ) {
UINT uDGPFormat;
uDGPFormat = ::RegisterClipboardFormatA( m_szClipFormatName );
if( ::OpenClipboard( NULL ) == FALSE )
return FALSE;
HANDLE hClipboardMemory = ::GetClipboardData( uDGPFormat );
if( hClipboardMemory == NULL ) {
::CloseClipboard();
return FALSE;
}
m_pMemoryBlock = new _CPostItMemoryBlock;
m_pMemoryBlock->Assign( hClipboardMemory );
::CloseClipboard();
}
return m_pMemoryBlock->Get( lpszKeyName, lpBuffer, nSize );
}
_CPostItMemoryBlock::_CPostItMemoryBlock( void ) : m_hHandle( NULL )
{
}
_CPostItMemoryBlock::~_CPostItMemoryBlock( void )
{
for( StrListItr itr = m_StrList.begin(); itr != m_StrList.end(); ) {
LPSTR lpszText = *itr;
SAFE_DELETE_ARRAY( lpszText );
itr = m_StrList.erase( itr );
}
}
BOOL _CPostItMemoryBlock::Assign( HANDLE hBlock )
{
if( hBlock == NULL || hBlock == INVALID_HANDLE_VALUE )
return FALSE;
LPBYTE lpBuffer = (LPBYTE) ::GlobalLock( hBlock );
if( lpBuffer == NULL )
return FALSE;
DWORD dwCount = *((LPDWORD) lpBuffer); lpBuffer += sizeof( DWORD );
for( DWORD dwI=0; dwI < dwCount; dwI++ ) {
WORD wLen = *((LPWORD) lpBuffer); lpBuffer += sizeof( WORD );
LPSTR lpszText = new CHAR[ wLen + 1 ];
::CopyMemory( lpszText, lpBuffer, wLen );
lpszText[ wLen ] = '\0';
lpBuffer += wLen;
Put( lpszText );
}
::GlobalUnlock( hBlock );
return TRUE;
}
HANDLE _CPostItMemoryBlock::CreateHandle( void )
{
if( m_StrList.size() == 0 )
return INVALID_HANDLE_VALUE;
DWORD dwBlockSize = sizeof( DWORD );
StrListItr itr;
// Calculation for Memory Block Size
for( itr = m_StrList.begin(); itr != m_StrList.end(); ++itr ) {
dwBlockSize += sizeof( WORD );
dwBlockSize += (DWORD) strlen( *itr );
}
HANDLE hBlock = ::GlobalAlloc( GMEM_ZEROINIT | GMEM_MOVEABLE, dwBlockSize );
if( hBlock == NULL )
return INVALID_HANDLE_VALUE;
LPBYTE lpBuffer = (LPBYTE) ::GlobalLock( hBlock );
if( lpBuffer == NULL ) {
::GlobalFree( hBlock );
return INVALID_HANDLE_VALUE;
}
*((LPDWORD) lpBuffer) = (DWORD) m_StrList.size(); lpBuffer += sizeof( DWORD );
for( itr = m_StrList.begin(); itr != m_StrList.end(); ++itr ) {
*((LPWORD) lpBuffer) = (WORD) strlen( *itr ); lpBuffer += sizeof( WORD );
::CopyMemory( lpBuffer, *itr, strlen( *itr ) ); lpBuffer += strlen( *itr );
}
::GlobalUnlock( hBlock );
m_hHandle = hBlock;
return hBlock;
}
BOOL _CPostItMemoryBlock::DestroyHandle( void )
{
::GlobalFree( m_hHandle );
m_hHandle = NULL;
return TRUE;
}
LPSTR _CPostItMemoryBlock::Find( LPCSTR lpszKeyName )
{
for( StrListItr itr = m_StrList.begin(); itr != m_StrList.end(); ++itr ) {
LPSTR lpszText = *itr;
if( _strnicmp( lpszText, lpszKeyName, strlen( lpszKeyName ) ) != 0 )
continue;
if( *(lpszText + strlen( lpszKeyName )) != '=' )
continue;
return lpszText;
}
return NULL;
}
BOOL _CPostItMemoryBlock::Put( LPCSTR lpszKeyName, LPCSTR lpBuffer )
{
LPSTR lpszText;
if( (lpszText = Find( lpszKeyName )) != NULL ) {
for( StrListItr itr = m_StrList.begin(); itr != m_StrList.end(); ++itr ) {
if( lpszText == *itr ) {
SAFE_DELETE_ARRAY( lpszText );
m_StrList.erase( itr );
break;
}
}
}
if( lpBuffer == NULL || !*lpBuffer )
return TRUE;
size_t nStrLen = strlen( lpszKeyName ) + 1 /* '=' */ + strlen( lpBuffer );
lpszText = new CHAR[ nStrLen + 1 ];
::CopyMemory( lpszText, lpszKeyName, strlen( lpszKeyName ) );
*(lpszText + strlen( lpszKeyName )) = '=';
::CopyMemory( lpszText + strlen( lpszKeyName ) + 1, lpBuffer, strlen( lpBuffer ) );
*(lpszText + nStrLen) = '\0';
m_StrList.push_back( lpszText );
return TRUE;
}
BOOL _CPostItMemoryBlock::Put( LPCSTR lpBuffer )
{
LPSTR lpszText;
if( lpBuffer == NULL || !*lpBuffer )
return TRUE;
size_t nStrLen = strlen( lpBuffer );
lpszText = new CHAR[ nStrLen + 1 ];
::CopyMemory( lpszText, lpBuffer, nStrLen );
*(lpszText + nStrLen) = '\0';
m_StrList.push_back( lpszText );
return TRUE;
}
BOOL _CPostItMemoryBlock::Get( LPCSTR lpszKeyName, LPSTR lpBuffer, DWORD nSize )
{
LPSTR lpszText = Find( lpszKeyName );
if( lpszText == NULL )
return FALSE;
lpszText += (strlen( lpszKeyName ) + 1);
::ZeroMemory( lpBuffer, nSize );
strncpy( lpBuffer, lpszText, (nSize < strlen( lpszText )) ? nSize : strlen( lpszText ) );
return TRUE;
}

80
src/EterBase/CPostIt.h Normal file
View File

@ -0,0 +1,80 @@
#ifndef _EL_CPOSTIT_H_
#define _EL_CPOSTIT_H_
// _CPostItMemoryBlock is defined in CPostIt.cpp
class _CPostItMemoryBlock;
/**
* @class CPostIt
* @brief <09><><EFBFBD>ӷ<EFBFBD>ó<EFBFBD><C3B3><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> Ŭ<><C5AC><EFBFBD>̾<EFBFBD>Ʈ<EFBFBD><C6AE> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><> Ŭ<><C5AC><EFBFBD>̾<EFBFBD>Ʈ<EFBFBD><C6AE><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ϱ<EFBFBD> <20><><EFBFBD>Ͽ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>Ǵ<EFBFBD> Ŭ<><C5AC><EFBFBD><EFBFBD>
*/
class CPostIt
{
public:
/**
* @brief CPostIt constructor
* @param [in] szAppName : <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20≯<EFBFBD><CCB8><EFBFBD> <20><><EFBFBD><EFBFBD><EEB0A3>.
*/
explicit CPostIt( LPCSTR szAppName );
/**
* @brief CPostIt destructor
*/
~CPostIt( void );
/**
* @brief CPostIt class<73><73><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ϰ<EFBFBD> <20>ִ<EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ<EFBFBD><C5B8> Ŭ<><C5AC><EFBFBD><EFBFBD><EFBFBD><20><><EFBFBD><EFBFBD><EFBFBD>Ѵ<EFBFBD>.
*/
BOOL Flush( void );
/**
* @brief CPostIt class<73><73><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ϰ<EFBFBD> <20>ִ<EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ <20><> Ŭ<><C5AC><EFBFBD><EFBFBD><EFBFBD><20>ִ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.
*/
void Empty( void );
/**
* @brief <09><><EFBFBD><EFBFBD>Ÿ<EFBFBD><C5B8> <20>о<EFBFBD><D0BE>´<EFBFBD>.
* @param [in] lpszKeyName : <20>ҷ<EFBFBD><D2B7><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ<EFBFBD><C5B8> Ű. "KEY" <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ִ´<D6B4>.
* @param [in] lpszData : <20>ҷ<EFBFBD><D2B7><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ<EFBFBD><C5B8> <20><><EFBFBD><EFBFBD>
* @param [in] nSize : lpszData <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ִ<EFBFBD><D6B4><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
*/
BOOL Get( LPCSTR lpszKeyName, LPSTR lpszData, DWORD nSize );
/**
* @brief <09><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ<EFBFBD><C5B8> <20>ִ´<D6B4>.
* @param [in] lpBuffer : <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ. "KEY=DATA" <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ִ´<D6B4>.
*/
BOOL Set( LPCSTR lpszData );
/**
* @brief <09><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ<EFBFBD><C5B8> <20>ִ´<D6B4>.
* @param [in] lpszKeyName : <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ<EFBFBD><C5B8> Ű. "KEY" <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ִ´<D6B4>.
* @param [in] lpszData : <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ. "DATA" <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ִ´<D6B4>.
*/
BOOL Set( LPCSTR lpszKeyName, LPCSTR lpszData );
/**
* @brief <09><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ(DWORD)<29><> <20>ִ´<D6B4>.
* @param [in] lpBuffer : <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ. "KEY=DATA" <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ<EFBFBD><C5B8> <20>ִ´<D6B4>.
* @param [in] dwValue : <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>Ÿ. (DWORD)
*/
BOOL Set( LPCSTR lpszKeyName, DWORD dwValue );
/**
* @brief CPostIt class<73><73> <20><><EFBFBD><EFBFBD><EFBFBD>Ѵ<EFBFBD>. (Ŭ<><C5AC><EFBFBD><EFBFBD> constructor<6F><72> <20≯<EFBFBD> <20><><EFBFBD>ڰ<EFBFBD> <20>ֱ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20><> <20≯<EFBFBD><CCB8><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ؾ<EFBFBD><D8BE><EFBFBD>)
* @param [in] pPostIt : Destination class
* @param [in] lpszKeyName : Destination class's new app-name
*/
BOOL CopyTo( CPostIt *pPostIt, LPCSTR lpszKeyName );
protected:
BOOL Init( LPCSTR szAppName );
void Destroy( void );
protected:
BOOL m_bModified;
CHAR m_szClipFormatName[_MAX_PATH];
_CPostItMemoryBlock* m_pMemoryBlock;
};
#endif /* _EL_CPOSTIT_H_ */

211
src/EterBase/CRC32.cpp Normal file
View File

@ -0,0 +1,211 @@
#include "StdAfx.h"
#include "CRC32.h"
static unsigned long CRCTable[256] =
{
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,
0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,
0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,0x1DB71064,0x6AB020F2,
0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,
0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,
0xFA0F3D63,0x8D080DF5,0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,
0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,
0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,
0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,
0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,0x76DC4190,0x01DB7106,
0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,
0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,
0x91646C97,0xE6635C01,0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,
0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,
0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,
0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,
0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,0x5005713C,0x270241AA,
0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,
0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,
0xB7BD5C3B,0xC0BA6CAD,0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,
0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,
0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,
0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,
0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,0xD6D6A3E8,0xA1D1937E,
0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,
0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,
0x316E8EEF,0x4669BE79,0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,
0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,
0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,
0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,
0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,0x86D3D2D4,0xF1D4E242,
0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,
0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,
0x616BFFD3,0x166CCF45,0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,
0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,
0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,
0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,
0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D
};
#define DO1(buf, i) crc = CRCTable[(crc ^ buf[i]) & 0xff] ^ (crc >> 8)
#define DO2(buf, i) DO1(buf, i); DO1(buf, i + 1);
#define DO4(buf, i) DO2(buf, i); DO2(buf, i + 2);
#define DO8(buf, i) DO4(buf, i); DO4(buf, i + 4);
#define DO16(buf, i) DO8(buf, i); DO8(buf, i + 8);
DWORD GetCRC32(const char * buf, size_t len)
{
DWORD crc = 0xffffffff;
if (len >= 16)
{
do
{
DO16(buf, 0);
buf += 16;
len -= 16;
} while (len >= 16);
}
if (len != 0)
{
do
{
DO1(buf, 0);
++buf;
--len;
} while (len > 0);
}
crc ^= 0xffffffff;
return crc;
}
#ifndef UPPER
#define UPPER(c) (((c)>='a' && (c) <= 'z') ? ((c)+('A'-'a')) : (c))
#endif
#define DO1CI(buf, i) crc = CRCTable[(crc ^ UPPER(buf[i])) & 0xff] ^ (crc >> 8)
#define DO2CI(buf, i) DO1CI(buf, i); DO1CI(buf, i + 1);
#define DO4CI(buf, i) DO2CI(buf, i); DO2CI(buf, i + 2);
#define DO8CI(buf, i) DO4CI(buf, i); DO4CI(buf, i + 4);
#define DO16CI(buf, i) DO8CI(buf, i); DO8CI(buf, i + 8);
DWORD GetCaseCRC32(const char * buf, size_t len)
{
DWORD crc = 0xffffffff;
if (16 <= len)
{
do
{
DO16CI(buf, 0);
buf += 16;
len -= 16;
} while (len >= 16);
}
if (0 != len)
{
do
{
DO1CI(buf, 0);
++buf;
--len;
} while (len > 0);
}
crc ^= 0xffffffff;
return crc;
}
DWORD GetHFILECRC32(HANDLE hFile)
{
DWORD dwRetCRC32=0;
DWORD dwFileSize = GetFileSize(hFile, NULL);
DWORD dataOffset=0;
DWORD mapSize=dwFileSize;
SYSTEM_INFO SysInfo;
GetSystemInfo(&SysInfo);
DWORD dwSysGran = SysInfo.dwAllocationGranularity;
DWORD dwFileMapStart = (dataOffset / dwSysGran) * dwSysGran;
DWORD dwMapViewSize = (dataOffset % dwSysGran) + mapSize;
//INT iViewDelta = dataOffset - dwFileMapStart;
HANDLE hFM = CreateFileMapping(hFile, // handle
NULL, // security
PAGE_READONLY, // flProtect
0, // high
dataOffset + mapSize, // low
NULL); // name
if (hFM)
{
LPVOID lpMapData = MapViewOfFile(hFM,
FILE_MAP_READ,
0,
dwFileMapStart,
dwMapViewSize);
dwRetCRC32=GetCRC32((const char*)lpMapData, dwFileSize);
if (lpMapData)
{
UnmapViewOfFile(lpMapData);
}
CloseHandle(hFM);
}
return dwRetCRC32;
}
DWORD GetFileCRC32(const char* c_szFileName)
{
HANDLE hFile = CreateFile(c_szFileName, // name of the file
GENERIC_READ, // desired access
FILE_SHARE_READ, // share mode
NULL, // security attributes
OPEN_EXISTING, // creation disposition
FILE_ATTRIBUTE_NORMAL, // flags and attr
NULL); // template file
if (INVALID_HANDLE_VALUE == hFile)
return 0;
DWORD dwRetCRC32=GetHFILECRC32(hFile);
CloseHandle(hFile);
return dwRetCRC32;
}
DWORD GetFileSize(const char* c_szFileName)
{
HANDLE hFile = CreateFile(c_szFileName, // name of the file
GENERIC_READ, // desired access
FILE_SHARE_READ, // share mode
NULL, // security attributes
OPEN_EXISTING, // creation disposition
FILE_ATTRIBUTE_NORMAL, // flags and attr
NULL); // template file
if (INVALID_HANDLE_VALUE == hFile)
return 0;
DWORD dwSize = GetFileSize(hFile, NULL);
CloseHandle(hFile);
return dwSize;
}

12
src/EterBase/CRC32.h Normal file
View File

@ -0,0 +1,12 @@
#ifndef __INC_CRC32_H__
#define __INC_CRC32_H__
#include <windows.h>
DWORD GetCRC32(const char* buffer, size_t count);
DWORD GetCaseCRC32(const char * buf, size_t len);
DWORD GetHFILECRC32(HANDLE hFile);
DWORD GetFileCRC32(const char* c_szFileName);
DWORD GetFileSize(const char* c_szFileName);
#endif

326
src/EterBase/Debug.cpp Normal file
View File

@ -0,0 +1,326 @@
#include "StdAfx.h"
#include <time.h>
#include <stdio.h>
#include "Debug.h"
#include "Singleton.h"
#include "Timer.h"
const DWORD DEBUG_STRING_MAX_LEN = 1024;
static int isLogFile = false;
HWND g_PopupHwnd = NULL;
class CLogFile : public CSingleton<CLogFile>
{
public:
CLogFile() : m_fp(NULL)
{
}
virtual ~CLogFile()
{
if (m_fp)
fclose(m_fp);
m_fp = NULL;
}
void Initialize()
{
m_fp = fopen("log.txt", "w");
}
void Write(const char * c_pszMsg)
{
if (!m_fp)
return;
time_t ct = time(0);
struct tm ctm = *localtime(&ct);
fprintf(m_fp, "%02d%02d %02d:%02d:%05d :: %s",
ctm.tm_mon + 1,
ctm.tm_mday,
ctm.tm_hour,
ctm.tm_min,
ELTimer_GetMSec() % 60000,
c_pszMsg);
fflush(m_fp);
}
protected:
FILE * m_fp;
};
static CLogFile gs_logfile;
static UINT gs_uLevel=0;
void SetLogLevel(UINT uLevel)
{
gs_uLevel=uLevel;
}
void Log(UINT uLevel, const char* c_szMsg)
{
if (uLevel>=gs_uLevel)
Trace(c_szMsg);
}
void Logn(UINT uLevel, const char* c_szMsg)
{
if (uLevel>=gs_uLevel)
Tracen(c_szMsg);
}
void Logf(UINT uLevel, const char* c_szFormat, ...)
{
if (uLevel<gs_uLevel)
return;
char szBuf[DEBUG_STRING_MAX_LEN+1];
va_list args;
va_start(args, c_szFormat);
_vsnprintf(szBuf, sizeof(szBuf), c_szFormat, args);
va_end(args);
#ifdef _DEBUG
OutputDebugString(szBuf);
fputs(szBuf, stdout);
#endif
if (isLogFile)
LogFile(szBuf);
}
void Lognf(UINT uLevel, const char* c_szFormat, ...)
{
if (uLevel<gs_uLevel)
return;
va_list args;
va_start(args, c_szFormat);
char szBuf[DEBUG_STRING_MAX_LEN+2];
int len = _vsnprintf(szBuf, sizeof(szBuf)-1, c_szFormat, args);
if (len > 0)
{
szBuf[len] = '\n';
szBuf[len + 1] = '\0';
}
va_end(args);
#ifdef _DEBUG
OutputDebugString(szBuf);
puts(szBuf);
#endif
if (isLogFile)
LogFile(szBuf);
}
void Trace(const char * c_szMsg)
{
#ifdef _DEBUG
OutputDebugString(c_szMsg);
printf("%s", c_szMsg);
#endif
if (isLogFile)
LogFile(c_szMsg);
}
void Tracen(const char* c_szMsg)
{
#ifdef _DEBUG
char szBuf[DEBUG_STRING_MAX_LEN+1];
_snprintf(szBuf, sizeof(szBuf), "%s\n", c_szMsg);
OutputDebugString(szBuf);
puts(c_szMsg);
if (isLogFile)
LogFile(szBuf);
puts(c_szMsg);
putc('\n', stdout);
#else
if (isLogFile)
{
LogFile(c_szMsg);
LogFile("\n");
}
#endif
}
void Tracenf(const char* c_szFormat, ...)
{
va_list args;
va_start(args, c_szFormat);
char szBuf[DEBUG_STRING_MAX_LEN+2];
int len = _vsnprintf(szBuf, sizeof(szBuf)-1, c_szFormat, args);
if (len > 0)
{
szBuf[len] = '\n';
szBuf[len + 1] = '\0';
}
va_end(args);
#ifdef _DEBUG
OutputDebugString(szBuf);
printf("%s", szBuf);
#endif
if (isLogFile)
LogFile(szBuf);
}
void Tracef(const char* c_szFormat, ...)
{
char szBuf[DEBUG_STRING_MAX_LEN+1];
va_list args;
va_start(args, c_szFormat);
_vsnprintf(szBuf, sizeof(szBuf), c_szFormat, args);
va_end(args);
#ifdef _DEBUG
OutputDebugString(szBuf);
fputs(szBuf, stdout);
#endif
if (isLogFile)
LogFile(szBuf);
}
void TraceError(const char* c_szFormat, ...)
{
#ifndef _DISTRIBUTE
char szBuf[DEBUG_STRING_MAX_LEN+2];
strncpy(szBuf, "SYSERR: ", DEBUG_STRING_MAX_LEN);
int len = strlen(szBuf);
va_list args;
va_start(args, c_szFormat);
len = _vsnprintf(szBuf + len, sizeof(szBuf) - (len + 1), c_szFormat, args) + len;
va_end(args);
szBuf[len] = '\n';
szBuf[len + 1] = '\0';
time_t ct = time(0);
struct tm ctm = *localtime(&ct);
fprintf(stderr, "%02d%02d %02d:%02d:%05d :: %s",
ctm.tm_mon + 1,
ctm.tm_mday,
ctm.tm_hour,
ctm.tm_min,
ELTimer_GetMSec() % 60000,
szBuf + 8);
fflush(stderr);
#ifdef _DEBUG
OutputDebugString(szBuf);
fputs(szBuf, stdout);
#endif
if (isLogFile)
LogFile(szBuf);
#endif
}
void TraceErrorWithoutEnter(const char* c_szFormat, ...)
{
#ifndef _DISTRIBUTE
char szBuf[DEBUG_STRING_MAX_LEN];
va_list args;
va_start(args, c_szFormat);
_vsnprintf(szBuf, sizeof(szBuf), c_szFormat, args);
va_end(args);
time_t ct = time(0);
struct tm ctm = *localtime(&ct);
fprintf(stderr, "%02d%02d %02d:%02d:%05d :: %s",
ctm.tm_mon + 1,
ctm.tm_mday,
ctm.tm_hour,
ctm.tm_min,
ELTimer_GetMSec() % 60000,
szBuf + 8);
fflush(stderr);
#ifdef _DEBUG
OutputDebugString(szBuf);
fputs(szBuf, stdout);
#endif
if (isLogFile)
LogFile(szBuf);
#endif
}
void LogBoxf(const char* c_szFormat, ...)
{
va_list args;
va_start(args, c_szFormat);
char szBuf[2048];
_vsnprintf(szBuf, sizeof(szBuf), c_szFormat, args);
LogBox(szBuf);
}
void LogBox(const char* c_szMsg, const char * c_szCaption, HWND hWnd)
{
if (!hWnd)
hWnd = g_PopupHwnd;
MessageBox(hWnd, c_szMsg, c_szCaption ? c_szCaption : "LOG", MB_OK);
Tracen(c_szMsg);
}
void LogFile(const char * c_szMsg)
{
CLogFile::Instance().Write(c_szMsg);
}
void LogFilef(const char * c_szMessage, ...)
{
va_list args;
va_start(args, c_szMessage);
char szBuf[DEBUG_STRING_MAX_LEN+1];
_vsnprintf(szBuf, sizeof(szBuf), c_szMessage, args);
CLogFile::Instance().Write(szBuf);
}
void OpenLogFile(bool bUseLogFIle)
{
#ifndef _DISTRIBUTE
freopen("syserr.txt", "w", stderr);
if (bUseLogFIle)
{
isLogFile = true;
CLogFile::Instance().Initialize();
}
#endif
}
void OpenConsoleWindow()
{
AllocConsole();
freopen("CONOUT$", "a", stdout);
freopen("CONIN$", "r", stdin);
}

40
src/EterBase/Debug.h Normal file
View File

@ -0,0 +1,40 @@
#ifndef __INC_ETERLIB_DEBUG_H__
#define __INC_ETERLIB_DEBUG_H__
#include <windows.h>
extern void SetLogLevel(UINT uLevel);
extern void Log(UINT uLevel, const char* c_szMsg);
extern void Logn(UINT uLevel, const char* c_szMsg);
extern void Logf(UINT uLevel, const char* c_szFormat, ...);
extern void Lognf(UINT uLevel, const char* c_szFormat, ...);
extern void Trace(const char* c_szMsg);
extern void Tracen(const char* c_szMsg);
extern void Tracenf(const char* c_szFormat, ...);
extern void Tracef(const char* c_szFormat, ...);
extern void TraceError(const char* c_szFormat, ...);
extern void TraceErrorWithoutEnter(const char* c_szFormat, ...);
extern void LogBox(const char* c_szMsg, const char * c_szCaption = NULL, HWND hWnd = NULL);
extern void LogBoxf(const char* c_szMsg, ...);
extern void LogFile(const char* c_szMsg);
extern void LogFilef(const char * c_szMessage, ...);
extern void OpenConsoleWindow(void);
extern void CloseConsoleWindow();
extern void SetupLog(void);
extern void OpenLogFile(bool bUseLogFile = true);
extern void CloseLogFile();
extern HWND g_PopupHwnd;
#define CHECK_RETURN(flag, string) \
if (flag) \
{ \
LogBox(string); \
return; \
} \
#endif

View File

@ -0,0 +1,367 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.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="Distribute|Win32">
<Configuration>Distribute</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="MfcDebug|Win32">
<Configuration>MfcDebug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="MfcRelease|Win32">
<Configuration>MfcRelease</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="VTune|Win32">
<Configuration>VTune</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<ProjectName>EterBase</ProjectName>
<ProjectGuid>{678C47DC-B3EF-460E-A932-56F3208FC65E}</ProjectGuid>
<RootNamespace>EterBase</RootNamespace>
<SccProjectName>SAK</SccProjectName>
<SccAuxPath>SAK</SccAuxPath>
<SccLocalPath>SAK</SccLocalPath>
<SccProvider>SAK</SccProvider>
<Keyword>MFCProj</Keyword>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='VTune|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v143</PlatformToolset>
<UseOfMfc>false</UseOfMfc>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<UseOfMfc>false</UseOfMfc>
<CharacterSet>MultiByte</CharacterSet>
<PlatformToolset>v143</PlatformToolset>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='MfcDebug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v143</PlatformToolset>
<UseOfMfc>Static</UseOfMfc>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='MfcRelease|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v143</PlatformToolset>
<UseOfMfc>Static</UseOfMfc>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Distribute|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v143</PlatformToolset>
<UseOfMfc>false</UseOfMfc>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType>
<PlatformToolset>v143</PlatformToolset>
<UseOfMfc>false</UseOfMfc>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='VTune|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
</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" />
<Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='MfcDebug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='MfcRelease|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Distribute|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
</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" />
<Import Project="$(VCTargetsPath)Microsoft.CPP.UpgradeFromVC71.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>17.0.32203.90</_ProjectFileVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Distribute|Win32'">
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='MfcRelease|Win32'">
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='MfcDebug|Win32'">
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='VTune|Win32'">
<OutDir>$(SolutionDir)build\$(Configuration)\</OutDir>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
<VcpkgConfiguration>$(Configuration)</VcpkgConfiguration>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Distribute|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
<VcpkgConfiguration>$(Configuration)</VcpkgConfiguration>
</PropertyGroup>
<PropertyGroup Label="Vcpkg" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<VcpkgUseStatic>true</VcpkgUseStatic>
<VcpkgConfiguration>$(Configuration)</VcpkgConfiguration>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(SolutionDir)extern\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<PrecompiledHeaderOutputFile>.\Debug/eterBase.pch</PrecompiledHeaderOutputFile>
<AssemblerListingLocation>.\Debug/</AssemblerListingLocation>
<ObjectFileName>.\Debug/</ObjectFileName>
<ProgramDataBaseFileName>.\Debug/</ProgramDataBaseFileName>
<BrowseInformation />
<WarningLevel>Level4</WarningLevel>
<SuppressStartupBanner>true</SuppressStartupBanner>
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0412</Culture>
<IgnoreStandardIncludePath>true</IgnoreStandardIncludePath>
</ResourceCompile>
<Lib>
<AdditionalLibraryDirectories>../../../extern/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Distribute|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<AdditionalIncludeDirectories>$(SolutionDir)extern\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeaderOutputFile>.\Distribute/eterBase.pch</PrecompiledHeaderOutputFile>
<AssemblerOutput>All</AssemblerOutput>
<AssemblerListingLocation>.\Distribute/</AssemblerListingLocation>
<ObjectFileName>.\Distribute/</ObjectFileName>
<ProgramDataBaseFileName>.\Distribute/</ProgramDataBaseFileName>
<BrowseInformation />
<WarningLevel>Level4</WarningLevel>
<SuppressStartupBanner>true</SuppressStartupBanner>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0412</Culture>
</ResourceCompile>
<Lib>
<AdditionalLibraryDirectories>$(SolutionDir)Extern\lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='MfcRelease|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<AdditionalIncludeDirectories>../../extern/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeaderOutputFile>.\MfcRelease/eterBase.pch</PrecompiledHeaderOutputFile>
<AssemblerOutput>All</AssemblerOutput>
<AssemblerListingLocation>.\MfcRelease/</AssemblerListingLocation>
<ObjectFileName>.\MfcRelease/</ObjectFileName>
<ProgramDataBaseFileName>.\MfcRelease/</ProgramDataBaseFileName>
<BrowseInformation />
<WarningLevel>Level4</WarningLevel>
<SuppressStartupBanner>true</SuppressStartupBanner>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0412</Culture>
</ResourceCompile>
<Lib>
<OutputFile>.\MfcRelease\eterBase.lib</OutputFile>
<AdditionalLibraryDirectories>../../extern/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='MfcDebug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>../../extern/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
<RuntimeTypeInfo>true</RuntimeTypeInfo>
<PrecompiledHeaderOutputFile>.\MfcDebug/eterBase.pch</PrecompiledHeaderOutputFile>
<AssemblerListingLocation>.\MfcDebug/</AssemblerListingLocation>
<ObjectFileName>.\MfcDebug/</ObjectFileName>
<ProgramDataBaseFileName>.\MfcDebug/</ProgramDataBaseFileName>
<BrowseInformation />
<WarningLevel>Level4</WarningLevel>
<SuppressStartupBanner>true</SuppressStartupBanner>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>_DEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0412</Culture>
</ResourceCompile>
<Lib>
<OutputFile>.\MfcDebug\eterBase.lib</OutputFile>
<AdditionalLibraryDirectories>../../extern/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<AdditionalIncludeDirectories>$(SolutionDir)extern\include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeaderOutputFile>.\Release/eterBase.pch</PrecompiledHeaderOutputFile>
<AssemblerListingLocation>.\Release/</AssemblerListingLocation>
<ObjectFileName>.\Release/</ObjectFileName>
<ProgramDataBaseFileName>.\Release/</ProgramDataBaseFileName>
<BrowseInformation />
<WarningLevel>Level4</WarningLevel>
<SuppressStartupBanner>true</SuppressStartupBanner>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
<MultiProcessorCompilation>true</MultiProcessorCompilation>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0412</Culture>
</ResourceCompile>
<Lib>
<AdditionalLibraryDirectories>../../extern/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Lib>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='VTune|Win32'">
<ClCompile>
<AdditionalOptions>/Gs %(AdditionalOptions)</AdditionalOptions>
<Optimization>Disabled</Optimization>
<InlineFunctionExpansion>OnlyExplicitInline</InlineFunctionExpansion>
<FavorSizeOrSpeed>Size</FavorSizeOrSpeed>
<OmitFramePointers>true</OmitFramePointers>
<AdditionalIncludeDirectories>../../extern/include;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<StringPooling>true</StringPooling>
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
<PrecompiledHeaderOutputFile>.\VTune/eterBase.pch</PrecompiledHeaderOutputFile>
<AssemblerOutput>All</AssemblerOutput>
<AssemblerListingLocation>.\VTune/</AssemblerListingLocation>
<ObjectFileName>.\VTune/</ObjectFileName>
<ProgramDataBaseFileName>.\VTune/</ProgramDataBaseFileName>
<BrowseInformation />
<WarningLevel>Level4</WarningLevel>
<SuppressStartupBanner>true</SuppressStartupBanner>
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
<CompileAs>Default</CompileAs>
</ClCompile>
<ResourceCompile>
<PreprocessorDefinitions>NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<Culture>0x0412</Culture>
</ResourceCompile>
<Lib>
<OutputFile>.\VTune\eterBase.lib</OutputFile>
<AdditionalLibraryDirectories>../../extern/lib;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<SuppressStartupBanner>true</SuppressStartupBanner>
</Lib>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="CPostIt.cpp" />
<ClCompile Include="CRC32.cpp" />
<ClCompile Include="Debug.cpp" />
<ClCompile Include="error.cpp" />
<ClCompile Include="FileBase.cpp" />
<ClCompile Include="FileDir.cpp" />
<ClCompile Include="FileLoader.cpp" />
<ClCompile Include="lzo.cpp" />
<ClCompile Include="MappedFile.cpp" />
<ClCompile Include="poly\Base.cpp" />
<ClCompile Include="poly\Poly.cpp" />
<ClCompile Include="poly\Symbol.cpp" />
<ClCompile Include="poly\SymTable.cpp" />
<ClCompile Include="Random.cpp" />
<ClCompile Include="StdAfx.cpp" />
<ClCompile Include="Stl.cpp" />
<ClCompile Include="tea.cpp" />
<ClCompile Include="TempFile.cpp" />
<ClCompile Include="Timer.cpp" />
<ClCompile Include="Utils.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="CPostIt.h" />
<ClInclude Include="CRC32.h" />
<ClInclude Include="Debug.h" />
<ClInclude Include="error.h" />
<ClInclude Include="FileBase.h" />
<ClInclude Include="FileDir.h" />
<ClInclude Include="FileLoader.h" />
<ClInclude Include="Filename.h" />
<ClInclude Include="lzo.h" />
<ClInclude Include="MappedFile.h" />
<ClInclude Include="poly\Base.h" />
<ClInclude Include="poly\Poly.h" />
<ClInclude Include="poly\Symbol.h" />
<ClInclude Include="poly\SymTable.h" />
<ClInclude Include="Random.h" />
<ClInclude Include="ServiceDefs.h" />
<ClInclude Include="Singleton.h" />
<ClInclude Include="StdAfx.h" />
<ClInclude Include="Stl.h" />
<ClInclude Include="tea.h" />
<ClInclude Include="TempFile.h" />
<ClInclude Include="Timer.h" />
<ClInclude Include="Utils.h" />
<ClInclude Include="vk.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -0,0 +1,147 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Poly">
<UniqueIdentifier>{9bcae2cc-8267-44b5-ab62-a9883ac6d669}</UniqueIdentifier>
</Filter>
<Filter Include="Code">
<UniqueIdentifier>{4b55a5df-b2f4-4801-969c-73611f757946}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="poly\Base.cpp">
<Filter>Poly</Filter>
</ClCompile>
<ClCompile Include="poly\Poly.cpp">
<Filter>Poly</Filter>
</ClCompile>
<ClCompile Include="poly\Symbol.cpp">
<Filter>Poly</Filter>
</ClCompile>
<ClCompile Include="poly\SymTable.cpp">
<Filter>Poly</Filter>
</ClCompile>
<ClCompile Include="CPostIt.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="CRC32.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="Debug.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="error.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="FileBase.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="FileDir.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="FileLoader.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="lzo.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="MappedFile.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="Random.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="StdAfx.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="Stl.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="tea.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="TempFile.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="Timer.cpp">
<Filter>Code</Filter>
</ClCompile>
<ClCompile Include="Utils.cpp">
<Filter>Code</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="poly\Base.h">
<Filter>Poly</Filter>
</ClInclude>
<ClInclude Include="poly\Poly.h">
<Filter>Poly</Filter>
</ClInclude>
<ClInclude Include="poly\Symbol.h">
<Filter>Poly</Filter>
</ClInclude>
<ClInclude Include="poly\SymTable.h">
<Filter>Poly</Filter>
</ClInclude>
<ClInclude Include="CPostIt.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="CRC32.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="Debug.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="error.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="FileBase.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="FileDir.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="FileLoader.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="Filename.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="lzo.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="MappedFile.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="Random.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="ServiceDefs.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="Singleton.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="StdAfx.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="Stl.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="tea.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="TempFile.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="Timer.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="Utils.h">
<Filter>Code</Filter>
</ClInclude>
<ClInclude Include="vk.h">
<Filter>Code</Filter>
</ClInclude>
</ItemGroup>
</Project>

115
src/EterBase/FileBase.cpp Normal file
View File

@ -0,0 +1,115 @@
#include "StdAfx.h"
#include "FileBase.h"
CFileBase::CFileBase() : m_hFile(NULL), m_dwSize(0)
{
}
CFileBase::~CFileBase()
{
Destroy();
}
char * CFileBase::GetFileName()
{
return m_filename;
}
void CFileBase::Destroy()
{
Close();
m_dwSize = 0;
}
void CFileBase::Close()
{
if (m_hFile)
{
CloseHandle(m_hFile);
m_hFile = NULL;
}
}
BOOL CFileBase::Create(const char* filename, EFileMode mode)
{
Destroy();
strncpy(m_filename, filename, MAX_PATH);
DWORD dwMode, dwShareMode = FILE_SHARE_READ;
if (mode == FILEMODE_WRITE)
{
dwMode = GENERIC_READ | GENERIC_WRITE;
dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
}
else
dwMode = GENERIC_READ;
m_hFile = CreateFile(filename, // name of the file
dwMode, // desired access
dwShareMode, // share mode
NULL, // security attributes
mode == FILEMODE_READ ? OPEN_EXISTING : OPEN_ALWAYS, // creation disposition
FILE_ATTRIBUTE_NORMAL, // flags and attr
NULL); // template file
if (m_hFile != INVALID_HANDLE_VALUE)
{
m_dwSize = GetFileSize(m_hFile, NULL);
m_mode = mode;
return true;
}
/* char buf[256];
GetCurrentDirectory(256, buf);
DWORD dwErr = GetLastError();*/
m_hFile = NULL;
return false;
}
DWORD CFileBase::Size()
{
return (m_dwSize);
}
void CFileBase::SeekCur(DWORD size)
{
SetFilePointer(m_hFile, size, NULL, FILE_CURRENT);
}
void CFileBase::Seek(DWORD offset)
{
if (offset > m_dwSize)
offset = m_dwSize;
SetFilePointer(m_hFile, offset, NULL, FILE_BEGIN);
}
DWORD CFileBase::GetPosition()
{
return SetFilePointer(m_hFile, 0, NULL, FILE_CURRENT);
}
BOOL CFileBase::Write(const void* src, int bytes)
{
DWORD dwUseless;
BOOL ret = WriteFile(m_hFile, src, bytes, &dwUseless, NULL);
if (!ret)
return false;
m_dwSize = GetFileSize(m_hFile, NULL);
return true;
}
BOOL CFileBase::Read(void* dest, int bytes)
{
DWORD dwUseless;
return ReadFile(m_hFile, dest, bytes, &dwUseless, NULL);
}
BOOL CFileBase::IsNull()
{
return !m_hFile ? true : false;
}

40
src/EterBase/FileBase.h Normal file
View File

@ -0,0 +1,40 @@
#ifndef __INC_ETERBASE_FILEBASE_H__
#define __INC_ETERBASE_FILEBASE_H__
#include <windows.h>
class CFileBase
{
public:
enum EFileMode
{
FILEMODE_READ = (1 << 0),
FILEMODE_WRITE = (1 << 1)
};
CFileBase();
virtual ~CFileBase();
void Destroy();
void Close();
BOOL Create(const char* filename, EFileMode mode);
DWORD Size();
void SeekCur(DWORD size);
void Seek(DWORD offset);
DWORD GetPosition();
virtual BOOL Write(const void* src, int bytes);
BOOL Read(void* dest, int bytes);
char* GetFileName();
BOOL IsNull();
protected:
int m_mode;
char m_filename[MAX_PATH+1];
HANDLE m_hFile;
DWORD m_dwSize;
};
#endif

105
src/EterBase/FileDir.cpp Normal file
View File

@ -0,0 +1,105 @@
#include "StdAfx.h"
#include "FileDir.h"
#include <string>
CDir::CDir()
{
Initialize();
}
CDir::~CDir()
{
Destroy();
}
void CDir::Destroy()
{
if (m_hFind)
FindClose(m_hFind);
Initialize();
}
bool CDir::Create(const char * c_szFilter, const char* c_szPath, BOOL bCheckedExtension)
{
Destroy();
std::string stPath = c_szPath;
if (stPath.length())
{
char end = stPath[stPath.length() - 1];
if (end != '\\')
stPath+='\\';
}
std::string stQuery;
stQuery += stPath;
stQuery += "*.*";
m_wfd.dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
m_hFind = FindFirstFile(stQuery.c_str(), &m_wfd);
if (m_hFind == INVALID_HANDLE_VALUE)
return true;
do
{
if (*m_wfd.cFileName == '.')
continue;
if (IsFolder())
{
if (!OnFolder(c_szFilter, stPath.c_str(), m_wfd.cFileName))
return false;
}
else
{
const char * c_szExtension = strchr(m_wfd.cFileName, '.');
if (!c_szExtension)
continue;
// NOTE : <20>ӽ<EFBFBD> <20><><EFBFBD><EFBFBD> - [levites]
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>δ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> TRUE <20><><EFBFBD>·<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ʈ<EFBFBD><C6AE> CDir<69><72> <20><><EFBFBD><EFBFBD><EFBFBD>ϴ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> Extension<6F><6E> "wav", "gr2" <20>̷<EFBFBD><CCB7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ְԲ<D6B0> <20>Ѵ<EFBFBD>. - [levites]
if (bCheckedExtension)
{
std::string strFilter = c_szFilter;
int iPos = strFilter.find_first_of(';', 0);
if (iPos > 0)
{
std::string strFirstFilter = std::string(c_szFilter).substr(0, iPos);
std::string strSecondFilter = std::string(c_szFilter).substr(iPos+1, strlen(c_szFilter));
if (0 != strFirstFilter.compare(c_szExtension+1) && 0 != strSecondFilter.compare(c_szExtension+1))
continue;
}
else
{
if (0 != stricmp(c_szExtension+1, c_szFilter))
continue;
}
}
if (!OnFile(stPath.c_str(), m_wfd.cFileName))
return false;
}
}
while (FindNextFile(m_hFind, &m_wfd));
return true;
}
bool CDir::IsFolder()
{
if (m_wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
return true;
return false;
}
void CDir::Initialize()
{
memset(&m_wfd, 0, sizeof(m_wfd));
m_hFind = NULL;
}

30
src/EterBase/FileDir.h Normal file
View File

@ -0,0 +1,30 @@
#ifndef __ETER_FILE_DIR__
#define __ETER_FILE_DIR__
#include <windows.h>
class CDir
{
public:
CDir();
virtual ~CDir();
void Destroy();
bool Create(const char* c_szFilter, const char* c_szPath="", BOOL bCheckedExtension = FALSE);
protected:
virtual bool OnFolder(const char* c_szFilter, const char* c_szPath, const char* c_szName) = 0;
virtual bool OnFile(const char* c_szPath, const char* c_szName) = 0;
protected:
bool IsFolder();
void Initialize();
protected:
WIN32_FIND_DATA m_wfd;
HANDLE m_hFind;
};
#endif

288
src/EterBase/FileLoader.cpp Normal file
View File

@ -0,0 +1,288 @@
#include "StdAfx.h"
#include "FileLoader.h"
#include <assert.h>
CMemoryTextFileLoader::CMemoryTextFileLoader()
{
}
CMemoryTextFileLoader::~CMemoryTextFileLoader()
{
}
bool CMemoryTextFileLoader::SplitLineByTab(DWORD dwLine, CTokenVector* pstTokenVector)
{
pstTokenVector->reserve(10);
pstTokenVector->clear();
const std::string & c_rstLine = GetLineString(dwLine);
const int c_iLineLength = c_rstLine.length();
if (0 == c_iLineLength)
return false;
int basePos = 0;
do
{
int beginPos = c_rstLine.find_first_of("\t", basePos);
pstTokenVector->push_back(c_rstLine.substr(basePos, beginPos-basePos));
basePos = beginPos+1;
} while (basePos < c_iLineLength && basePos > 0);
return true;
}
int CMemoryTextFileLoader::SplitLine2(DWORD dwLine, CTokenVector* pstTokenVector, const char * c_szDelimeter)
{
pstTokenVector->reserve(10);
pstTokenVector->clear();
std::string stToken;
const std::string & c_rstLine = GetLineString(dwLine);
DWORD basePos = 0;
do
{
int beginPos = c_rstLine.find_first_not_of(c_szDelimeter, basePos);
if (beginPos < 0)
return -1;
int endPos;
if (c_rstLine[beginPos] == '"')
{
++beginPos;
endPos = c_rstLine.find_first_of("\"", beginPos);
if (endPos < 0)
return -2;
basePos = endPos + 1;
}
else
{
endPos = c_rstLine.find_first_of(c_szDelimeter, beginPos);
basePos = endPos;
}
pstTokenVector->push_back(c_rstLine.substr(beginPos, endPos - beginPos));
// <20>߰<EFBFBD> <20>ڵ<EFBFBD>. <20>ǵڿ<C7B5> <20><><EFBFBD><EFBFBD> <20>ִ<EFBFBD> <20><><EFBFBD>츦 üũ<C3BC>Ѵ<EFBFBD>. - [levites]
if (int(c_rstLine.find_first_not_of(c_szDelimeter, basePos)) < 0)
break;
} while (basePos < c_rstLine.length());
return 0;
}
bool CMemoryTextFileLoader::SplitLine(DWORD dwLine, CTokenVector* pstTokenVector, const char * c_szDelimeter)
{
pstTokenVector->reserve(10);
pstTokenVector->clear();
std::string stToken;
const std::string & c_rstLine = GetLineString(dwLine);
DWORD basePos = 0;
do
{
int beginPos = c_rstLine.find_first_not_of(c_szDelimeter, basePos);
if (beginPos < 0)
return false;
int endPos;
if (c_rstLine[beginPos] == '"')
{
++beginPos;
endPos = c_rstLine.find_first_of("\"", beginPos);
if (endPos < 0)
return false;
basePos = endPos + 1;
}
else
{
endPos = c_rstLine.find_first_of(c_szDelimeter, beginPos);
basePos = endPos;
}
pstTokenVector->push_back(c_rstLine.substr(beginPos, endPos - beginPos));
// <20>߰<EFBFBD> <20>ڵ<EFBFBD>. <20>ǵڿ<C7B5> <20><><EFBFBD><EFBFBD> <20>ִ<EFBFBD> <20><><EFBFBD>츦 üũ<C3BC>Ѵ<EFBFBD>. - [levites]
if (int(c_rstLine.find_first_not_of(c_szDelimeter, basePos)) < 0)
break;
} while (basePos < c_rstLine.length());
return true;
}
DWORD CMemoryTextFileLoader::GetLineCount()
{
return m_stLineVector.size();
}
bool CMemoryTextFileLoader::CheckLineIndex(DWORD dwLine)
{
if (dwLine >= m_stLineVector.size())
return false;
return true;
}
const std::string & CMemoryTextFileLoader::GetLineString(DWORD dwLine)
{
assert(CheckLineIndex(dwLine));
return m_stLineVector[dwLine];
}
void CMemoryTextFileLoader::Bind(int bufSize, const void* c_pvBuf)
{
m_stLineVector.reserve(128);
m_stLineVector.clear();
const char * c_pcBuf = (const char *)c_pvBuf;
std::string stLine;
int pos = 0;
while (pos < bufSize)
{
const char c = c_pcBuf[pos++];
if ('\n' == c || '\r' == c)
{
if (pos < bufSize)
if ('\n' == c_pcBuf[pos] || '\r' == c_pcBuf[pos])
++pos;
m_stLineVector.push_back(stLine);
stLine = "";
}
else if (c < 0)
{
stLine.append(c_pcBuf + (pos-1), 2);
++pos;
}
else
{
stLine += c;
}
}
m_stLineVector.push_back(stLine);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
int CMemoryFileLoader::GetSize()
{
return m_size;
}
int CMemoryFileLoader::GetPosition()
{
return m_pos;
}
bool CMemoryFileLoader::IsReadableSize(int size)
{
if (m_pos + size > m_size)
return false;
return true;
}
bool CMemoryFileLoader::Read(int size, void* pvDst)
{
if (!IsReadableSize(size))
return false;
memcpy(pvDst, GetCurrentPositionPointer(), size);
m_pos += size;
return true;
}
const char* CMemoryFileLoader::GetCurrentPositionPointer()
{
assert(m_pcBase != NULL);
return (m_pcBase + m_pos);
}
CMemoryFileLoader::CMemoryFileLoader(int size, const void* c_pvMemoryFile)
{
assert(c_pvMemoryFile != NULL);
m_pos = 0;
m_size = size;
m_pcBase = (const char *) c_pvMemoryFile;
}
CMemoryFileLoader::~CMemoryFileLoader()
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////
int CDiskFileLoader::GetSize()
{
return m_size;
}
bool CDiskFileLoader::Read(int size, void* pvDst)
{
assert(m_fp != NULL);
int ret = fread(pvDst, size, 1, m_fp);
if (ret <= 0)
return false;
return true;
}
bool CDiskFileLoader::Open(const char* c_szFileName)
{
Close();
if (!c_szFileName[0])
return false;
m_fp = fopen(c_szFileName, "rb");
if (!m_fp)
return false;
fseek(m_fp, 0, SEEK_END);
m_size = ftell(m_fp);
fseek(m_fp, 0, SEEK_SET);
return true;
}
void CDiskFileLoader::Close()
{
if (m_fp)
fclose(m_fp);
Initialize();
}
void CDiskFileLoader::Initialize()
{
m_fp = NULL;
m_size = 0;
}
CDiskFileLoader::CDiskFileLoader()
{
Initialize();
}
CDiskFileLoader::~CDiskFileLoader()
{
Close();
}

71
src/EterBase/FileLoader.h Normal file
View File

@ -0,0 +1,71 @@
#pragma once
#pragma warning(disable:4786) // character 255 <20>Ѿ<D1BE>°<EFBFBD> <20><><EFBFBD><EFBFBD>
#include <windows.h>
#include <vector>
#include <map>
#include "Stl.h"
class CMemoryTextFileLoader
{
public:
CMemoryTextFileLoader();
virtual ~CMemoryTextFileLoader();
void Bind(int bufSize, const void* c_pvBuf);
DWORD GetLineCount();
bool CheckLineIndex(DWORD dwLine);
bool SplitLine(DWORD dwLine, CTokenVector * pstTokenVector, const char * c_szDelimeter = " \t");
int SplitLine2(DWORD dwLine, CTokenVector * pstTokenVector, const char * c_szDelimeter = " \t");
bool SplitLineByTab(DWORD dwLine, CTokenVector* pstTokenVector);
const std::string & GetLineString(DWORD dwLine);
protected:
std::vector<std::string> m_stLineVector;
};
class CMemoryFileLoader
{
public:
CMemoryFileLoader(int size, const void * c_pvMemoryFile);
virtual ~CMemoryFileLoader();
bool Read(int size, void* pvDst);
int GetPosition();
int GetSize();
protected:
bool IsReadableSize(int size);
const char * GetCurrentPositionPointer();
protected:
const char * m_pcBase;
int m_size;
int m_pos;
};
//////////////////////////////////////////////////////////////////////////////////////////////////
class CDiskFileLoader
{
public:
CDiskFileLoader();
virtual ~CDiskFileLoader();
void Close();
bool Open(const char * c_szFileName);
bool Read(int size, void * pvDst);
int GetSize();
protected:
void Initialize();
protected:
FILE * m_fp;
int m_size;
};
typedef std::map<std::string, std::string> TStringMap;

254
src/EterBase/Filename.h Normal file
View File

@ -0,0 +1,254 @@
///////////////////////////////////////////////////////////////////////
// CFilename Class
//
// (c) 2003 IDV, Inc.
//
// *** INTERACTIVE DATA VISUALIZATION (IDV) PROPRIETARY INFORMATION ***
//
// This software is supplied under the terms of a license agreement or
// nondisclosure agreement with Interactive Data Visualization and may
// not be copied or disclosed except in accordance with the terms of
// that agreement.
//
// Copyright (c) 2001-2003 IDV, Inc.
// All Rights Reserved.
//
// IDV, Inc.
// 1233 Washington St. Suite 610
// Columbia, SC 29201
// Voice: (803) 799-1699
// Fax: (803) 931-0320
// Web: http://www.idvinc.com
//
#pragma once
#include <string>
///////////////////////////////////////////////////////////////////////
// CFilename Class
//class CFilename
//{
// public:
// CFilename() { }
// CFilename(const char* pFilename) { m_sRaw = pFilename; }
// CFilename(std::string strFilename) { m_sRaw = strFilename; }
//
// virtual ~CFilename() {}
//
// operator const string() const { return m_sRaw; }
// operator string&() { return m_sRaw; }
// CFilename& operator =(const CFilename& r) { m_sRaw = r.m_sRaw; return *this; }
// bool operator ==(const CFilename& r) const { return m_sRaw == r.m_sRaw; }
// CFilename operator +(const CFilename& r) const { return CFilename(m_sRaw + r.m_sRaw); }
// CFilename& operator +=(const CFilename& r) { m_sRaw += r.m_sRaw; return *this; }
// const char& operator[](size_t nIdx) const { return m_sRaw[nIdx]; }
// const char* c_str() const { return m_sRaw.c_str(); }
// size_t find(const char* pcszSrc) const { return m_sRaw.find(pcszSrc); }
// bool empty() const { return m_sRaw.empty(); }
// size_t size() const { return m_sRaw.size(); }
// size_t length() const { return m_sRaw.length(); }
//
// string& GetString() { return m_sRaw; }
//
// void ChangeDosPath()
// {
// size_t nLength = m_sRaw.length();
//
// for (size_t i = 0; i < nLength; ++i)
// {
// if (m_sRaw.at(i) == '/')
// m_sRaw.at(i) = '\\';
// }
// }
//
// void StringPath()
// {
// size_t nLength = m_sRaw.length();
//
// for (size_t i = 0; i<nLength; ++i)
// {
// if (m_sRaw.at(i) == '\\')
// m_sRaw.at(i) = '/';
// else
// m_sRaw.at(i) = (char)tolower(m_sRaw.at(i));
// }
// }
//
// CFilename GetName(void); // if filename is "/idv/code/file.cpp", it returns "file"
// CFilename GetExtension(void); // if filename is "/idv/code/file.cpp", it returns "cpp"
// CFilename GetPath(void); // if filename is "/idv/code/file.cpp", it returns "/idv/code"
// CFilename NoExtension(void); // if filename is "/idv/code/file.cpp", it returns "/idv/code/file"
// CFilename NoPath(void); // if filename is "/idv/code/file.cpp", it returns "file.cpp"
// string m_sRaw;
//};
///////////////////////////////////////////////////////////////////////
// CFileNameHelper Class
class CFileNameHelper
{
public:
static void ChangeDosPath(std::string& str) {
size_t nLength = str.length();
for (size_t i = 0; i < nLength; ++i)
{
if (str.at(i) == '/')
str.at(i) = '\\';
}
}
static void StringPath(std::string& str) {
size_t nLength = str.length();
for (size_t i = 0; i<nLength; ++i)
{
if (str.at(i) == '\\')
str.at(i) = '/';
else
str.at(i) = (char)tolower(str.at(i));
}
}
static std::string GetName(std::string& str); // if filename is "/idv/code/file.cpp", it returns "file"
static std::string GetExtension(std::string& str); // if filename is "/idv/code/file.cpp", it returns "cpp"
static std::string GetPath(std::string& str); // if filename is "/idv/code/file.cpp", it returns "/idv/code"
static std::string NoExtension(std::string& str); // if filename is "/idv/code/file.cpp", it returns "/idv/code/file"
static std::string NoPath(std::string& str); // if filename is "/idv/code/file.cpp", it returns "file.cpp"
};
///////////////////////////////////////////////////////////////////////
// CFileNameHelper::GetExtension
inline std::string CFileNameHelper::GetName(std::string& str)
{
std::string strName;
size_t nLength = str.length();
if (nLength > 0)
{
size_t iExtensionStartPos = nLength - 1;
for (size_t i = nLength - 1; i > 0; i--)
{
if (str[i] == '.')
{
iExtensionStartPos = i;
}
if (str[i] == '/')
{
strName = std::string(str.c_str() + i + 1);
strName.resize(iExtensionStartPos - i - 1);
break;
}
}
}
return strName;
}
///////////////////////////////////////////////////////////////////////
// CFilenameHelper::GetExtension
inline std::string CFileNameHelper::GetExtension(std::string& str)
{
std::string strExtension;
size_t nLength = str.length();
if (nLength > 0)
{
for (size_t i = nLength - 1; i > 0 && str[i] != '/'; i--)
if (str[i] == '.')
{
strExtension = std::string(str.c_str( ) + i + 1);
break;
}
}
return strExtension;
}
///////////////////////////////////////////////////////////////////////
// CFilenameHelper::GetPath
inline std::string CFileNameHelper::GetPath(std::string& str)
{
char szPath[1024];
szPath[0] = '\0';
size_t nLength = str.length();
if (nLength > 0)
{
for (size_t i = nLength - 1; i > 0; i--)
{
if (str[i] == '/' || str[i] == '\\')
{
for (size_t j = 0; j < i + 1; j++)
szPath[j] = str[j];
szPath[i+1] = '\0';
break;
}
if (0 == i)
break;
}
}
return szPath;
}
///////////////////////////////////////////////////////////////////////
// CFilenameHelper::NoExtension
inline std::string CFileNameHelper::NoExtension(std::string& str)
{
std::size_t npos = str.find_last_of('.');
if (std::string::npos != npos)
return std::string(str, 0, npos);
return str;
}
///////////////////////////////////////////////////////////////////////
// CFilenameHelper::NoPath
inline std::string CFileNameHelper::NoPath(std::string& str)
{
char szPath[1024];
szPath[0] = '\0';
size_t nLength = str.length();
if (nLength > 0)
{
strcpy(szPath, str.c_str());
for (size_t i = nLength - 1; i > 0; i--)
{
if (str[i] == '/' || str[i] == '\\')
{
int k = 0;
for (size_t j = i + 1; j < nLength; j++, k++)
szPath[k] = str[j];
szPath[k] = '\0';
break;
}
if (0 == i)
break;
}
}
return szPath;
}

259
src/EterBase/MappedFile.cpp Normal file
View File

@ -0,0 +1,259 @@
#include "StdAfx.h"
#include "MappedFile.h"
#include "Debug.h"
CMappedFile::CMappedFile() :
m_hFM(NULL),
m_lpMapData(NULL),
m_dataOffset(0),
m_mapSize(0),
m_seekPosition(0),
m_pLZObj(NULL),
m_pbBufLinkData(NULL),
m_dwBufLinkSize(0),
m_pbAppendResultDataBlock(NULL),
m_dwAppendResultDataSize(0)
{
}
CMappedFile::~CMappedFile()
{
Destroy();
}
BOOL CMappedFile::Create(const char * filename)
{
Destroy();
return CFileBase::Create(filename, FILEMODE_READ);
}
BOOL CMappedFile::Create(const char * filename, const void** dest, int offset, int size)
{
if (!CMappedFile::Create(filename))
return NULL;
int ret = Map(dest, offset, size);
return (ret) > 0;
}
LPCVOID CMappedFile::Get()
{
return m_lpData;
}
void CMappedFile::Link(DWORD dwBufSize, const void* c_pvBufData)
{
m_dwBufLinkSize=dwBufSize;
m_pbBufLinkData=(BYTE*)c_pvBufData;
}
void CMappedFile::BindLZObject(CLZObject * pLZObj)
{
assert(m_pLZObj == NULL);
m_pLZObj = pLZObj;
Link(m_pLZObj->GetSize(), m_pLZObj->GetBuffer());
}
void CMappedFile::BindLZObjectWithBufferedSize(CLZObject * pLZObj)
{
assert(m_pLZObj == NULL);
m_pLZObj = pLZObj;
Link(m_pLZObj->GetBufferSize(), m_pLZObj->GetBuffer());
}
BYTE* CMappedFile::AppendDataBlock( const void* pBlock, DWORD dwBlockSize )
{
if( m_pbAppendResultDataBlock )
{
delete []m_pbAppendResultDataBlock;
}
//realloc
m_dwAppendResultDataSize = m_dwBufLinkSize+dwBlockSize;
m_pbAppendResultDataBlock = new BYTE[m_dwAppendResultDataSize];
memcpy(m_pbAppendResultDataBlock, m_pbBufLinkData, m_dwBufLinkSize );
memcpy(m_pbAppendResultDataBlock + m_dwBufLinkSize, pBlock, dwBlockSize );
//redirect
Link(m_dwAppendResultDataSize, m_pbAppendResultDataBlock);
return m_pbAppendResultDataBlock;
}
void CMappedFile::Destroy()
{
if (m_pLZObj) // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>Ͱ<EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD>ͷ<EFBFBD> <20><><EFBFBD><EFBFBD> <20>ȴ<EFBFBD>
{
delete m_pLZObj;
m_pLZObj = NULL;
}
if (NULL != m_lpMapData)
{
Unmap(m_lpMapData);
m_lpMapData = NULL;
}
if (NULL != m_hFM)
{
CloseHandle(m_hFM);
m_hFM = NULL;
}
if( m_pbAppendResultDataBlock )
{
delete []m_pbAppendResultDataBlock;
m_pbAppendResultDataBlock = NULL;
}
m_dwAppendResultDataSize = 0;
m_pbBufLinkData = NULL;
m_dwBufLinkSize = 0;
m_seekPosition = 0;
m_dataOffset = 0;
m_mapSize = 0;
CFileBase::Destroy();
}
int CMappedFile::Seek(DWORD offset, int iSeekType)
{
switch (iSeekType)
{
case SEEK_TYPE_BEGIN:
if (offset > m_dwSize)
offset = m_dwSize;
m_seekPosition = offset;
break;
case SEEK_TYPE_CURRENT:
m_seekPosition = min(m_seekPosition + offset, Size());
break;
case SEEK_TYPE_END:
m_seekPosition = max(0, Size() - offset);
break;
}
return m_seekPosition;
}
// 2004.09.16.myevan.MemoryMappedFile 98/ME <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> üũ
//DWORD g_dwCount=0;
int CMappedFile::Map(const void **dest, int offset, int size)
{
m_dataOffset = offset;
if (size == 0)
m_mapSize = m_dwSize;
else
m_mapSize = size;
if (m_dataOffset + m_mapSize > m_dwSize)
return NULL;
SYSTEM_INFO SysInfo;
GetSystemInfo(&SysInfo);
DWORD dwSysGran = SysInfo.dwAllocationGranularity;
DWORD dwFileMapStart = (m_dataOffset / dwSysGran) * dwSysGran;
DWORD dwMapViewSize = (m_dataOffset % dwSysGran) + m_mapSize;
INT iViewDelta = m_dataOffset - dwFileMapStart;
m_hFM = CreateFileMapping(m_hFile, // handle
NULL, // security
PAGE_READONLY, // flProtect
0, // high
m_dataOffset + m_mapSize, // low
NULL); // name
if (!m_hFM)
{
OutputDebugString("CMappedFile::Map !m_hFM\n");
return NULL;
}
m_lpMapData = MapViewOfFile(m_hFM,
FILE_MAP_READ,
0,
dwFileMapStart,
dwMapViewSize);
if (!m_lpMapData) // Success
{
TraceError("CMappedFile::Map !m_lpMapData %lu", GetLastError());
return 0;
}
// 2004.09.16.myevan.MemoryMappedFile 98/ME <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> üũ
//g_dwCount++;
//Tracenf("MAPFILE %d", g_dwCount);
m_lpData = (char*) m_lpMapData + iViewDelta;
*dest = (char*) m_lpData;
m_seekPosition = 0;
Link(m_mapSize, m_lpData);
return (m_mapSize);
}
BYTE * CMappedFile::GetCurrentSeekPoint()
{
return m_pbBufLinkData+m_seekPosition;
//return m_pLZObj ? m_pLZObj->GetBuffer() + m_seekPosition : (BYTE *) m_lpData + m_seekPosition;
}
DWORD CMappedFile::Size()
{
return m_dwBufLinkSize;
/*
if (m_pLZObj)
return m_pLZObj->GetSize();
return (m_mapSize);
*/
}
DWORD CMappedFile::GetPosition()
{
return m_dataOffset;
}
BOOL CMappedFile::Read(void * dest, int bytes)
{
if (m_seekPosition + bytes > Size())
return FALSE;
memcpy(dest, GetCurrentSeekPoint(), bytes);
m_seekPosition += bytes;
return TRUE;
}
DWORD CMappedFile::GetSeekPosition(void)
{
return m_seekPosition;
}
void CMappedFile::Unmap(LPCVOID data)
{
if (UnmapViewOfFile(data))
{
// 2004.09.16.myevan.MemoryMappedFile 98/ME <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> üũ
//g_dwCount--;
//Tracenf("UNMAPFILE %d", g_dwCount);
}
else
{
TraceError("CMappedFile::Unmap - Error");
}
m_lpData = NULL;
}

59
src/EterBase/MappedFile.h Normal file
View File

@ -0,0 +1,59 @@
#ifndef __INC_MAPPEDFILE_H__
#define __INC_MAPPEDFILE_H__
#include "lzo.h"
#include "FileBase.h"
class CMappedFile : public CFileBase
{
public:
enum ESeekType
{
SEEK_TYPE_BEGIN,
SEEK_TYPE_CURRENT,
SEEK_TYPE_END
};
public:
CMappedFile();
virtual ~CMappedFile();
void Link(DWORD dwBufSize, const void* c_pvBufData);
BOOL Create(const char* filename);
BOOL Create(const char* filename, const void** dest, int offset, int size);
LPCVOID Get();
void Destroy();
int Seek(DWORD offset, int iSeekType = SEEK_TYPE_BEGIN);
int Map(const void **dest, int offset=0, int size=0);
DWORD Size();
DWORD GetPosition();
BOOL Read(void* dest, int bytes);
DWORD GetSeekPosition();
void BindLZObject(CLZObject * pLZObj);
void BindLZObjectWithBufferedSize(CLZObject * pLZObj);
BYTE* AppendDataBlock( const void* pBlock, DWORD dwBlockSize );
BYTE * GetCurrentSeekPoint();
private:
void Unmap(LPCVOID data);
private:
BYTE* m_pbBufLinkData;
DWORD m_dwBufLinkSize;
BYTE* m_pbAppendResultDataBlock;
DWORD m_dwAppendResultDataSize;
DWORD m_seekPosition;
HANDLE m_hFM;
DWORD m_dataOffset;
DWORD m_mapSize;
LPVOID m_lpMapData;
LPVOID m_lpData;
CLZObject * m_pLZObj;
};
#endif

View File

@ -0,0 +1,27 @@
#include "../StdAfx.h"
#include "Base.h"
CBase::CBase()
{
id = 0;
}
CBase::~CBase()
{
}
bool CBase::isNumber()
{
return (id & MID_NUMBER) != 0 ? true : false;
}
bool CBase::isVar()
{
return (id & MID_VARIABLE) != 0 ? true : false;
}
bool CBase::isSymbol()
{
return (id & MID_SYMBOL) != 0 ? true : false;
}

25
src/EterBase/Poly/Base.h Normal file
View File

@ -0,0 +1,25 @@
#ifndef __POLY_BASE_H__
#define __POLY_BASE_H__
#define MID_UNKNOWN 0
#define MID_NUMBER 256
#define MID_VARIABLE 512
#define MID_SYMBOL 1024
#define MID_LONG MID_NUMBER + 1
#define MID_SQRT MID_NUMBER + 2
#define MID_FRACTION MID_NUMBER + 3
class CBase
{
public:
bool isSymbol();
bool isVar();
bool isNumber();
int id;
CBase();
virtual ~CBase();
};
#endif

622
src/EterBase/Poly/Poly.cpp Normal file
View File

@ -0,0 +1,622 @@
#include "../StdAfx.h"
#include <string>
#include <assert.h>
#include "Poly.h"
#include <cmath>
#include <cctype>
#include <cstdlib>
using namespace std;
double _random()
{
return rand() / (RAND_MAX + 1.0);
}
void CPoly::SetRandom(int iRandomType)
{
m_iRandomType = iRandomType;
}
int CPoly::my_irandom(double start, double end)
{
switch (m_iRandomType)
{
case RANDOM_TYPE_FORCE_MIN:
return int(start);
break;
case RANDOM_TYPE_FORCE_MAX:
return int(end);
break;
}
// Make range as inclusive-exclusive
int is = int(start + 0.5);
int ie = int(end - start + 0.5) + 1;
return int(_random() * ie + is);
}
double CPoly::my_frandom(double start, double end)
{
return _random() * (end - start) + start;
}
CPoly::CPoly()
{
m_iRandomType = RANDOM_TYPE_FREELY;
uiLookPos = 0;
ErrorOccur = true;
lSymbol.clear();
STSize = 0;
MathSymbolCount = 0;
lSymbol.reserve(50);
init();
}
CPoly::~CPoly()
{
Clear();
}
void CPoly::SetStr(const string & str)
{
strData = str;
}
float CPoly::Eval()
{
int stNow;
double save[POLY_MAXSTACK],t;
int iSp=0;
if (ErrorOccur)
{
/*THROW(new CEvalException("Evaluate Error"));*/
return 0;
}
//TEST
//list<int>::iterator pos = tokenBase.begin();
//list<double>::iterator posn = numBase.begin();
vector<int>::iterator pos = tokenBase.begin();
vector<double>::iterator posn = numBase.begin();
while (pos != tokenBase.end())
{
stNow=*pos;
++pos;
switch (stNow)
{
case POLY_NUM:
save[iSp++]=*posn++; break;
case POLY_ID:
save[iSp++]=
lSymbol[ *pos ]->dVal;
pos++;
break;
//case '+':
case POLY_PLU:
iSp--;
save[iSp-1]+=save[iSp]; break;
//case '-':
case POLY_MIN:
iSp--;
save[iSp-1]-=save[iSp]; break;
//case '*':
case POLY_MUL:
iSp--;
save[iSp-1]*=save[iSp]; break;
//case '%':
case POLY_MOD:
iSp--;
if (save[iSp]==0)
{
//THROW(new CEvalException("Divide by 0"));
return 0;
}
save[iSp-1]=fmod(save[iSp-1],save[iSp]); break;
//case '/':
case POLY_DIV:
iSp--;
if (save[iSp]==0)
{
//THROW(new CEvalException("Divide by 0"));
return 0;
}
save[iSp-1]/=save[iSp]; break;
//case '^':
case POLY_POW:
iSp--;
save[iSp-1]=pow(save[iSp-1],save[iSp]); break;
case POLY_ROOT:
if (save[iSp-1]<0)
{
//THROW(new CEvalException("Negative in root"));
return 0;
}
save[iSp-1]=sqrt(save[iSp-1]); break;
case POLY_COS:
save[iSp-1]=cos(save[iSp-1]); break;
case POLY_SIN:
save[iSp-1]=sin(save[iSp-1]); break;
case POLY_TAN:
if (!(t=cos(save[iSp-1])))
{
//THROW (new CEvalException("Divide by 0"));
return 0;
}
save[iSp-1]=tan(save[iSp-1]); break;
case POLY_CSC:
if (!(t=sin(save[iSp-1])))
{
//THROW(new CEvalException("Divide by 0"));
return 0;
}
save[iSp-1]=1/t; break;
case POLY_SEC:
if (!(t=cos(save[iSp-1])))
{
//THROW(new CEvalException("Divide by 0"));
return 0;
}
save[iSp-1]=1/t; break;
case POLY_COT:
if (!(t=sin(save[iSp-1])))
{
//THROW(new CEvalException("Divide by 0"));
return 0;
}
save[iSp-1]=cos(save[iSp-1])/t; break;
case POLY_LN:
if (save[iSp-1]<=0)
{
//THROW( new CEvalException("Call Log with minus number"));
return 0;
}
save[iSp-1]=log(save[iSp-1]); break;
case POLY_LOG10:
if (save[iSp-1]<=0)
{
//THROW( new CEvalException("Call Log with minus number"));
return 0;
}
save[iSp-1]=log10(save[iSp-1]); break;
case POLY_LOG:
if (save[iSp-1]<=0)
{
//THROW( new CEvalException("Call Log with minus number"));
return 0;
}
if (save[iSp-2]<=0 || save[iSp-2]==1)
{
//THROW( new CEvalException("Call Log with minus number"));
return 0;
}
save[iSp-2]=log(save[iSp-1])/log(save[iSp-2]);
iSp--;
break;
case POLY_ABS:
save[iSp-1]=fabs(save[iSp-1]);
break;
case POLY_FLOOR:
save[iSp-1]=floor(save[iSp-1]);
break;
case POLY_IRAND:
save[iSp-2]=my_irandom(save[iSp-2],save[iSp-1]);
iSp--;
break;
case POLY_FRAND:
save[iSp-2]=my_frandom(save[iSp-2],save[iSp-1]);
iSp--;
break;
case POLY_MINF:
save[iSp-2]=(save[iSp-2]<save[iSp-1])?save[iSp-2]:save[iSp-1];
iSp--;
break;
case POLY_MAXF:
save[iSp-2]=(save[iSp-2]>save[iSp-1])?save[iSp-2]:save[iSp-1];
iSp--;
break;
/*case POLY_MOD:
save[iSp-2]=fmod(save[iSp-2],save[iSp-1]);
iSp--;
break;*/
default:
return 0;
//THROW(new CEvalException("Token Error"));
}
}
return float(save[iSp-1]);
}
int CPoly::Analyze(const char * pszStr)
{
if (pszStr)
SetStr(pszStr);
if (0 == strData.length())
return true;
//DisposeList();
ErrorOccur = false;
uiLookPos = 0;
iLookAhead = lexan();
expr();
if (tokenBase.empty())
{
//THROW(new CParseException("No Data"));
return false;
}
return !ErrorOccur;
}
void CPoly::Clear()
{
int i;
//while (!tokenBase.IsEmpty()) listBase.RemoveTail();
//while (!numBase.IsEmpty()) numBase.RemoveTail();
tokenBase.clear();
numBase.clear();
for (i = 0;i < STSize; ++i)
{
if (lSymbol[i]) delete lSymbol[i];
lSymbol[i]=NULL;
}
//lSymbol.FreeExtra();
lSymbol.clear();
SymbolIndex.clear();
STSize=0;
MathSymbolCount=0;
}
void CPoly::expr()
{
int t;
switch (iLookAhead)
{
case '+':
case '-':
uiLookPos--;
iLookAhead = POLY_NUM;
iNumToken = iToken = 0;
}
term();
while (!ErrorOccur)
{
switch (iLookAhead)
{
case '+':
case '-':
t=iLookAhead;
match(t);
term();
emit(t,POLY_NONE);
continue;
case POLY_EOS: case ')': case ',': return;
default:
error();
//THROW( new CParseException("Error Parsing"));
return;
}
}
}
void CPoly::error()
{
iErrorPos=uiLookPos;
ErrorOccur=true;
}
int CPoly::lexan()
{
int t;
double tt;
while (uiLookPos < strData.size())
{
if (strData[uiLookPos] == ' ' || strData[uiLookPos] == '\t')
;
else if (isdigit(strData[uiLookPos]))
{
t = 0;
for (;uiLookPos<strData.size();uiLookPos++)
{
if (isdigit(strData[uiLookPos]))
t = t * 10 + strData[uiLookPos] - '0';
else
break;
}
iToken=t;
tt=0.1;
iNumToken=0;
if (uiLookPos<strData.size() && strData[uiLookPos]=='.')
{
uiLookPos++;
for (;uiLookPos<strData.size();uiLookPos++,tt*=0.1)
{
if (isdigit(strData[uiLookPos]))
iNumToken+=tt*(strData[uiLookPos]-'0');
else
break;
}
}
iNumToken+=iToken;
return POLY_NUM;
}
else if (isalpha(strData[uiLookPos]))
{
string localSymbol("");
while (uiLookPos<strData.size() && isalpha(strData[uiLookPos]))
{
localSymbol+=strData[uiLookPos];
uiLookPos++;
}
iToken= find(localSymbol);
if (iToken==-1)
{
iToken=insert(localSymbol,POLY_ID);
}
return lSymbol[(/*FindIndex*/(iToken))]->token;
}
else
{
iToken=0;
return strData[uiLookPos++];
}
uiLookPos++;
}
return POLY_EOS;
}
void CPoly::term()
{
int t;
factor();
while (!ErrorOccur)
{
switch (iLookAhead)
{
case '*':
case '/':
case '%':
t=iLookAhead;
match(t);
factor();
emit(t,POLY_NONE);
continue;
default:
return;
}
}
}
void CPoly::factor()
{
int t;
expo();
while (!ErrorOccur)
{
switch (iLookAhead)
{
case '^':
t=iLookAhead;
match(t);
expo();
emit(t,POLY_NONE);
continue;
default:
return;
}
}
}
void CPoly::expo()
{
int t;
switch (iLookAhead)
{
case '(':
match('('); expr(); match(')'); break;
case POLY_NUM:
emit(POLY_NUM, iToken); match(POLY_NUM); break;
case POLY_ID:
emit(POLY_ID,(int)/*FindIndex*/(iToken)); match(POLY_ID); break;
case POLY_ROOT:
case POLY_SIN:
case POLY_COT:
case POLY_TAN:
case POLY_CSC:
case POLY_SEC:
case POLY_LN:
case POLY_LOG10:
case POLY_COS:
case POLY_ABS:
case POLY_FLOOR:
t=iLookAhead;
match(iLookAhead); match('('); expr(); match(')'); emit(t,iToken);
break;
case POLY_LOG:
case POLY_MINF:
case POLY_MAXF:
case POLY_IRAND:
case POLY_FRAND:
case POLY_MOD:
t=iLookAhead;
match(iLookAhead); match('('); expr(); match(','); expr(); match(')'); emit(t,iToken);
break;
case POLY_EOS:
break;
default:
error();
//THROW( new CParseException("Error Parsing"));
}
}
void CPoly::match(int t)
{
if (iLookAhead==t) iLookAhead=lexan(); else error();
}
void CPoly::emit(int t, int tval)
{
switch (t)
{
case '+':
tokenBase.push_back(POLY_PLU);
break;
case '-':
tokenBase.push_back(POLY_MIN);
break;
case '*':
tokenBase.push_back(POLY_MUL);
break;
case '/':
tokenBase.push_back(POLY_DIV);
break;
case '%':
tokenBase.push_back(POLY_MOD);
break;
case '^':
tokenBase.push_back(POLY_POW);
break;
case POLY_ROOT:
case POLY_SIN:
case POLY_TAN:
case POLY_COT:
case POLY_COS:
case POLY_CSC:
case POLY_SEC:
case POLY_LOG:
case POLY_LN:
case POLY_LOG10:
case POLY_ABS:
case POLY_MINF:
case POLY_MAXF:
case POLY_IRAND:
case POLY_FRAND:
case POLY_MOD:
case POLY_FLOOR:
tokenBase.push_back(t);
break;
case POLY_NUM:
tokenBase.push_back(t);
numBase.push_back(iNumToken);
break;
case POLY_ID:
tokenBase.push_back(t);
tokenBase.push_back(tval); break;
default:
error();
Clear();
//THROW( new CParseException("Error Parsing"));
return;
}
}
int CPoly::find(const string & s)
{
int l, m, r;
l = 0;
r = STSize - 1;
while (l <= r)
{
m = (l + r) >> 1;
if (lSymbol[SymbolIndex[m]]->strlex == s)
return SymbolIndex[m];
else if (lSymbol[SymbolIndex[m]]->strlex < s)
l = m + 1;
else
r = m - 1;
}
return -1;
}
int CPoly::insert(const string & s, int tok)
{
int i;
bool bAdded=false;
lSymbol.push_back(new CSymTable(tok,s));
for (i=0;i<STSize;i++)
{
if (s<lSymbol[SymbolIndex[i]]->strlex)
{
SymbolIndex.insert(SymbolIndex.begin()+i,STSize);
bAdded=true;
break;
}
}
if (!bAdded)
{
//SymbolIndex.SetAtGrow(STSize,STSize);
SymbolIndex.push_back(STSize);
}
STSize++;
return STSize-1;
}
int CPoly::SetVar(const string & strName, double dVar)
{
if (ErrorOccur) return false;
int index=find(strName);
if (index==-1) return false;
CSymTable* stVar = lSymbol[(/*FindIndex*/(index))];
stVar->dVal=dVar;
return true;
}
int CPoly::GetVarCount()
{
return lSymbol.size() - MathSymbolCount;
}
const char * CPoly::GetVarName(unsigned int dwIndex)
{
assert(dwIndex + MathSymbolCount < lSymbol.size());
return lSymbol[dwIndex + MathSymbolCount]->strlex.c_str();
}
void CPoly::init()
{
insert("min",POLY_MINF);
insert("max",POLY_MAXF);
insert("number", POLY_IRAND);
insert("irandom", POLY_IRAND);
insert("irand", POLY_IRAND);
insert("frandom",POLY_FRAND);
insert("frand",POLY_FRAND);
insert("rt",POLY_ROOT);
insert("sqrt",POLY_ROOT);
insert("cos",POLY_COS);
insert("sin",POLY_SIN);
insert("tan",POLY_TAN);
insert("cot",POLY_COT);
insert("csc",POLY_CSC);
insert("cosec",POLY_COSEC);
insert("sec",POLY_SEC);
insert("pi",POLY_PI);
SetVar("pi",3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068);
insert("e",POLY_EXP);
SetVar("e",2.718281828459045235360287471352662497757247093699959574966967627724076630353547594571382178525166427);
insert("log",POLY_LOG);
insert("ln",POLY_LN);
insert("log10",POLY_LOG10);
insert("abs",POLY_ABS);
insert("mod",POLY_MOD);
insert("floor",POLY_FLOOR);
MathSymbolCount = STSize;
}

106
src/EterBase/Poly/Poly.h Normal file
View File

@ -0,0 +1,106 @@
#ifndef __POLY_POLY_H__
#define __POLY_POLY_H__
#include "SymTable.h"
#pragma warning ( push, 3 )
#include <string>
#include <vector>
#include <list>
#pragma warning ( pop )
#define POLY_MAXVALUE 0
#define POLY_NONE POLY_MAXVALUE
#define POLY_ROOT POLY_MAXVALUE + 1
#define POLY_MUL POLY_MAXVALUE + 2
#define POLY_PLU POLY_MAXVALUE + 3
#define POLY_POW POLY_MAXVALUE + 4
#define POLY_MIN POLY_MAXVALUE + 5
#define POLY_DIV POLY_MAXVALUE + 6
#define POLY_OPEN POLY_MAXVALUE + 7
#define POLY_CLOSE POLY_MAXVALUE + 8
#define POLY_NUM POLY_MAXVALUE + 9
#define POLY_ID POLY_MAXVALUE + 10
#define POLY_EOS POLY_MAXVALUE + 11
#define POLY_COS POLY_MAXVALUE + 12
#define POLY_SIN POLY_MAXVALUE + 13
#define POLY_TAN POLY_MAXVALUE + 14
#define POLY_COSEC POLY_MAXVALUE + 15
#define POLY_CSC POLY_COSEC
#define POLY_SEC POLY_MAXVALUE + 16
#define POLY_COT POLY_MAXVALUE + 17
#define POLY_PI POLY_ID
#define POLY_EXP POLY_ID
#define POLY_LOG POLY_MAXVALUE + 18
#define POLY_LN POLY_MAXVALUE + 19
#define POLY_LOG10 POLY_MAXVALUE + 20
#define POLY_ABS POLY_MAXVALUE + 21
#define POLY_MINF POLY_MAXVALUE + 22
#define POLY_MAXF POLY_MAXVALUE + 23
#define POLY_IRAND POLY_MAXVALUE + 24
#define POLY_FRAND POLY_MAXVALUE + 25
#define POLY_MOD POLY_MAXVALUE + 26
#define POLY_FLOOR POLY_MAXVALUE + 27
#define POLY_MAXSTACK 100
class CPoly
{
public:
enum ERandomType
{
RANDOM_TYPE_FREELY,
RANDOM_TYPE_FORCE_MIN,
RANDOM_TYPE_FORCE_MAX,
};
public:
CPoly();
virtual ~CPoly();
int Analyze(const char * pszStr = NULL);
float Eval();
void SetRandom(int iRandomType);
void SetStr(const std::string & str);
int SetVar(const std::string & strName, double dVar);
int GetVarCount();
const char * GetVarName(unsigned int dwIndex);
void Clear();
protected:
int my_irandom(double start, double end);
double my_frandom(double start, double end);
void init();
int insert(const std::string & s, int tok);
int find(const std::string & s);
void emit(int t,int tval);
void match(int t);
void expo();
void factor();
void term();
int iToken;
double iNumToken;
int iLookAhead;
int lexan();
int iErrorPos;
void error();
void expr();
bool ErrorOccur;
unsigned int uiLookPos;
// NOTE: list is slight faster than vector, why?!
std::vector<int> tokenBase;
std::vector<double> numBase;
std::vector<CSymTable *> lSymbol;
std::vector<int> SymbolIndex;
int STSize;
int MathSymbolCount;
std::string strData;
int m_iRandomType;
};
#endif

View File

@ -0,0 +1,13 @@
#include "../StdAfx.h"
#include "SymTable.h"
using namespace std;
CSymTable::CSymTable(int aTok, string aStr) : dVal(0), token(aTok), strlex(aStr)
{
}
CSymTable::~CSymTable()
{
}

View File

@ -0,0 +1,17 @@
#ifndef __POLY_SYMTABLE_H__
#define __POLY_SYMTABLE_H__
#include <string>
class CSymTable
{
public:
CSymTable(int aTok, std::string aStr);
virtual ~CSymTable();
double dVal;
int token;
std::string strlex;
};
#endif

View File

@ -0,0 +1,50 @@
#include "../StdAfx.h"
#include "Symbol.h"
CSymbol::CSymbol()
{
id = MID_SYMBOL;
iType = ST_UNKNOWN;
}
CSymbol::~CSymbol()
{
}
bool CSymbol::Equal(CSymbol dif)
{
if (dif.iType/10 == iType/10) return true;
return false;
}
bool CSymbol::Less(CSymbol dif)
{
if (dif.iType/10 > iType/10) return true;
return false;
}
int CSymbol::GetType()
{
return iType;
}
void CSymbol::SetType(int Type)
{
iType=Type;
}
int CSymbol::issymbol(int ch)
{
switch(ch)
{
case SY_PLUS : return ST_PLUS;
case SY_MINUS : return ST_MINUS;
case SY_MULTIPLY: return ST_MULTIPLY;
case SY_DIVIDE : return SY_DIVIDE;
case SY_CARET : return SY_CARET;
case SY_OPEN : return SY_OPEN;
case SY_CLOSE : return ST_CLOSE;
}
return 0;
}

View File

@ -0,0 +1,39 @@
#ifndef __POLY_SYMBOL_H__
#define __POLY_SYMBOL_H__
#include "Base.h"
#define ST_UNKNOWN 0
#define ST_PLUS 11
#define ST_MINUS 12
#define ST_MULTIPLY 23
#define ST_DIVIDE 24
#define ST_CARET 35
#define ST_OPEN 06
#define ST_CLOSE 07
#define SY_PLUS '+'
#define SY_MINUS '-'
#define SY_MULTIPLY '*'
#define SY_DIVIDE '/'
#define SY_CARET '^'
#define SY_OPEN '('
#define SY_CLOSE ')'
class CSymbol : public CBase
{
private:
int iType;
public:
CSymbol();
virtual ~CSymbol();
static int issymbol(int ch);
void SetType(int Type);
int GetType();
bool Equal(CSymbol dif);
bool Less(CSymbol dif);
};
#endif

48
src/EterBase/Random.cpp Normal file
View File

@ -0,0 +1,48 @@
#include "StdAfx.h"
#include <assert.h>
static unsigned long randseed = 1;
void srandom(unsigned long seed)
{
randseed = seed;
}
/*
* Pseudo-random number generator for randomizing the profiling clock,
* and whatever else we might use it for. The result is uniform on
* [0, 2^31 - 1].
*/
unsigned long random()
{
register long x, hi, lo, t;
/*
* Compute x[n + 1] = (7^5 * x[n]) mod (2^31 - 1).
* From "Random number generators: good ones are hard to find",
* Park and Miller, Communications of the ACM, vol. 31, no. 10,
* October 1988, p. 1195.
*/
x = randseed;
hi = x / 127773;
lo = x % 127773;
t = 16807 * lo - 2836 * hi;
if (t <= 0)
t += 0x7fffffff;
randseed = t;
return (t);
}
float frandom(float flLow, float flHigh)
{
float fl = float(random()) / float(2147483648.0f); // float in [0,1)
return (fl * (flHigh - flLow)) + flLow; // float in [low,high)
}
long random_range(long from, long to)
{
assert(from <= to);
return ((random() % (to - from + 1)) + from);
}

9
src/EterBase/Random.h Normal file
View File

@ -0,0 +1,9 @@
#ifndef __INC_ETERBASE_RANDOM_H__
#define __INC_ETERBASE_RANDOM_H__
extern void srandom(unsigned long seed);
extern unsigned long random();
extern float frandom(float flLow, float flHigh);
extern long random_range(long from, long to);
#endif

View File

@ -0,0 +1,4 @@
#ifndef _EL_SERVICEDEFS_H_
#define _EL_SERVICEDEFS_H_
#endif //_EL_SERVICEDEFS_H_

85
src/EterBase/Singleton.h Normal file
View File

@ -0,0 +1,85 @@
#ifndef __INC_ETERLIB_SINGLETON_H__
#define __INC_ETERLIB_SINGLETON_H__
#include <assert.h>
template <typename T> class CSingleton
{
static T * ms_singleton;
public:
CSingleton()
{
assert(!ms_singleton);
int offset = (int) (T*) 1 - (int) (CSingleton <T>*) (T*) 1;
ms_singleton = (T*) ((int) this + offset);
}
virtual ~CSingleton()
{
assert(ms_singleton);
ms_singleton = 0;
}
__forceinline static T & Instance()
{
assert(ms_singleton);
return (*ms_singleton);
}
__forceinline static T * InstancePtr()
{
return (ms_singleton);
}
__forceinline static T & instance()
{
assert(ms_singleton);
return (*ms_singleton);
}
};
template <typename T> T * CSingleton <T>::ms_singleton = 0;
//
// singleton for non-hungarian
//
template <typename T> class singleton
{
static T * ms_singleton;
public:
singleton()
{
assert(!ms_singleton);
int offset = (int) (T*) 1 - (int) (singleton <T>*) (T*) 1;
ms_singleton = (T*) ((int) this + offset);
}
virtual ~singleton()
{
assert(ms_singleton);
ms_singleton = 0;
}
__forceinline static T & Instance()
{
assert(ms_singleton);
return (*ms_singleton);
}
__forceinline static T * InstancePtr()
{
return (ms_singleton);
}
__forceinline static T & instance()
{
assert(ms_singleton);
return (*ms_singleton);
}
};
template <typename T> T * singleton <T>::ms_singleton = 0;
#endif

6
src/EterBase/StdAfx.cpp Normal file
View File

@ -0,0 +1,6 @@
// stdafx.cpp : source file that includes just the standard includes
// eterBase.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"

55
src/EterBase/StdAfx.h Normal file
View File

@ -0,0 +1,55 @@
#pragma once
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#pragma warning(disable:4710) // not inlined
#pragma warning(disable:4786) // character 255 <20>Ѿ<D1BE>°<EFBFBD> <20><><EFBFBD><EFBFBD>
#pragma warning(disable:4244) // type conversion possible lose of data
#include <windows.h>
#include <assert.h>
#include <stdio.h>
#pragma warning ( disable : 4201 )
#include <mmsystem.h>
#pragma warning ( default : 4201 )
#include <imagehlp.h>
#include <time.h>
#pragma warning ( push, 3 )
#include <algorithm>
#include <string>
#include <vector>
#include <deque>
#include <list>
#include <map>
#pragma warning ( pop )
#if _MSC_VER >= 1400
#define stricmp _stricmp
#define strnicmp _strnicmp
#define strupt _strupr
#define strcmpi _strcmpi
#define fileno _fileno
//#define access _access_s
//#define _access _access_s
#define atoi _atoi64
#endif
// Armadillo nanomite protection
#if !defined(NANOBEGIN) && !defined(NANOEND)
#ifdef _DEBUG
#define NANOBEGIN
#define NANOEND
#else
#include <armadillo/SecuredSections.h>
#endif
#endif
#include "vk.h"
#include "filename.h"
#include "ServiceDefs.h"

92
src/EterBase/Stl.cpp Normal file
View File

@ -0,0 +1,92 @@
#include "StdAfx.h"
#include "stl.h"
static std::list<std::string> s_stList;
char korean_tolower(const char c)
{
char ret = c;
if (c >= 'A' && c <= 'Z')
ret = c - 'A' + 'a';
assert(ret == tolower(c));
return ret;
}
std::string& stl_static_string(const char * c_sz)
{
std::string str;
str.assign(c_sz);
s_stList.push_back(str);
return s_stList.back();
}
void stl_lowers(std::string& rstRet)
{
for (size_t i = 0; i < rstRet.length(); ++i)
rstRet[i] = korean_tolower(rstRet[i]);
}
int split_string(const std::string& input, const std::string& delimiter, std::vector<std::string>& results, bool includeEmpties)
{
int iPos = 0;
int newPos = -1;
UINT sizeS2 = delimiter.size();
UINT isize = input.size();
if ((isize == 0) || (sizeS2 == 0))
{
return 0;
}
std::vector<int> positions;
newPos = input.find(delimiter, 0);
if (newPos < 0)
return 0;
int numFound = 0;
while (newPos >= iPos)
{
numFound++;
positions.push_back(newPos);
iPos = newPos;
newPos = input.find(delimiter, iPos+sizeS2);
}
if (numFound == 0)
return 0;
for (UINT i = 0; i <= positions.size(); ++i)
{
std::string s("");
if (i == 0)
{
s = input.substr(i, positions[i]);
}
else
{
UINT offset = positions[i-1] + sizeS2;
if (offset < isize)
{
if (i == positions.size())
{
s = input.substr(offset);
}
else if (i > 0)
{
s = input.substr(positions[i-1] + sizeS2, positions[i] - positions[i-1] - sizeS2);
}
}
}
if (includeEmpties || (s.size() > 0))
{
results.push_back(s);
}
}
return numFound;
}

496
src/EterBase/Stl.h Normal file
View File

@ -0,0 +1,496 @@
#ifndef __INC_ETERBASE_STL_H__
#define __INC_ETERBASE_STL_H__
#pragma warning(disable:4786) // identifier was truncated to '255' characters in the browser information
#pragma warning(disable:4018) // signed <-> unsigned mismatch
#pragma warning(disable:4503) // decorated name length exceeded, name was truncated
#pragma warning(disable:4018) // '<' : signed/unsigned mismatch
#include <assert.h>
#pragma warning ( push, 3 )
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <functional>
#include <SSTREAM>
#pragma warning ( pop )
extern char korean_tolower(const char c);
extern std::string& stl_static_string(const char* c_sz);
extern void stl_lowers(std::string& rstRet);
extern int split_string(const std::string & input, const std::string & delimiter, std::vector<std::string>& results, bool includeEmpties);
namespace std
{
template <class _Ty>
class void_mem_fun_t
: public unary_function<_Ty *, void> {
public:
explicit void_mem_fun_t(void (_Ty::*_Pm)())
: _Ptr(_Pm) {}
void operator()(_Ty *_P) const
{((_P->*_Ptr)()); }
private:
void (_Ty::*_Ptr)();
};
template<class _Ty> inline
void_mem_fun_t<_Ty> void_mem_fun(void (_Ty::*_Pm)())
{return (void_mem_fun_t<_Ty>(_Pm)); }
template<class _Ty>
class void_mem_fun_ref_t : public unary_function<_Ty, void> {
public:
explicit void_mem_fun_ref_t(void (_Ty::*_Pm)())
: _Ptr(_Pm) {}
void operator()(_Ty& _X) const
{return ((_X.*_Ptr)()); }
private:
void (_Ty::*_Ptr)();
};
template<class _Ty> inline
void_mem_fun_ref_t<_Ty> void_mem_fun_ref(void (_Ty::*_Pm)())
{return (void_mem_fun_ref_t< _Ty>(_Pm)); }
// TEMPLATE CLASS mem_fun1_t
template<class _R, class _Ty, class _A>
class void_mem_fun1_t : public binary_function<_Ty *, _A, _R> {
public:
explicit void_mem_fun1_t(_R (_Ty::*_Pm)(_A))
: _Ptr(_Pm) {}
_R operator()(_Ty *_P, _A _Arg) const
{return ((_P->*_Ptr)(_Arg)); }
private:
_R (_Ty::*_Ptr)(_A);
};
// TEMPLATE FUNCTION mem_fun1
template<class _R, class _Ty, class _A> inline
void_mem_fun1_t<_R, _Ty, _A> void_mem_fun1(_R (_Ty::*_Pm)(_A))
{return (void_mem_fun1_t<_R, _Ty, _A>(_Pm)); }
}
struct stl_sz_less
{
bool operator() (char * const & left, char * const & right) const
{
return (strcmp(left, right) < 0);
}
};
template<typename TContainer>
inline void stl_wipe(TContainer& container)
{
for (TContainer::iterator i = container.begin(); i != container.end(); ++i)
{
delete *i;
*i = NULL;
}
container.clear();
}
template<typename TString>
inline int hex2dec(TString szhex)
{
int hex0 = toupper(szhex[0]);
int hex1 = toupper(szhex[1]);
return (hex1 >= 'A' ? hex1 - 'A' + 10 : hex1 - '0') +
(hex0 >= 'A' ? hex0 - 'A' + 10 : hex0 - '0') * 16;
}
template<typename TString>
inline unsigned long htmlColorStringToARGB(TString str)
{
unsigned long alp = hex2dec(str);
unsigned long red = hex2dec(str + 2);
unsigned long green = hex2dec(str + 4);
unsigned long blue = hex2dec(str + 6);
return (alp << 24 | red << 16 | green << 8 | blue);
}
template<typename TContainer>
inline void stl_wipe_second(TContainer& container)
{
for (TContainer::iterator i = container.begin(); i != container.end(); ++i)
{
delete i->second;
}
container.clear();
}
template<typename T>
inline void safe_release(T& rpObject)
{
if (!rpObject)
return;
rpObject->Release();
rpObject = NULL;
}
template <typename T>
void DeleteVectorItem(std::vector<T> * pVector, unsigned long dwIndex)
{
if (dwIndex >= pVector->size())
{
assert(!"Wrong index to delete!");
return;
}
if (1 == pVector->size())
{
pVector->clear();
return;
}
std::vector<T>::iterator itor = pVector->begin();
for (unsigned long i = 0; i < dwIndex; ++i)
++itor;
pVector->erase(itor);
}
template <typename T>
void DeleteVectorItem(T * pVector, unsigned long dwStartIndex, unsigned long dwEndIndex)
{
if (dwStartIndex >= pVector->size())
{
assert(!"Wrong start index to delete!");
return;
}
if (dwEndIndex >= pVector->size())
{
assert(!"Wrong end index to delete!");
return;
}
T::iterator itorStart = pVector->begin();
for (unsigned long i = 0; i < dwStartIndex; ++i)
++itorStart;
T::iterator itorEnd = pVector->begin();
for (unsigned long j = 0; j < dwEndIndex; ++j)
++itorEnd;
pVector->erase(itorStart, itorEnd);
}
template <typename T>
void DeleteVectorItem(std::vector<T> * pVector, T pItem)
{
std::vector<T>::iterator itor = pVector->begin();
for (; itor != pVector->end(); ++itor)
{
if (pItem == *itor)
{
if (1 == pVector->size())
{
pVector->clear();
}
else
{
pVector->erase(itor);
}
break;
}
}
}
template <typename T>
void DeleteListItem(std::list<T> * pList, T pItem)
{
std::list<T>::iterator itor = pList->begin();
for (; itor != pList->end(); ++itor)
{
if (pItem == *itor)
{
if (1 == pList->size())
{
pList->clear();
}
else
{
pList->erase(itor);
}
break;
}
}
}
template<typename T, typename F>
void stl_vector_qsort(std::vector<T>& rdataVector, F comp)
{
if (rdataVector.empty()) return;
qsort(&rdataVector[0], rdataVector.size(), sizeof(T), comp);
}
template<typename TData>
class stl_stack_pool
{
public:
stl_stack_pool()
{
m_pos = 0;
}
stl_stack_pool(int capacity)
{
m_pos = 0;
initialize(capacity);
}
virtual ~stl_stack_pool()
{
}
void initialize(int capacity)
{
m_dataVector.clear();
m_dataVector.resize(capacity);
}
void clear()
{
m_pos = 0;
}
TData * alloc()
{
assert(!m_dataVector.empty() && "stl_stack_pool::alloc you MUST run stl_stack_pool::initialize");
int max = m_dataVector.size();
if (m_pos >= max)
{
assert(!"stl_stack_pool::alloc OUT of memory");
m_pos = 0;
}
return &m_dataVector[m_pos++];
}
TData* base()
{
return &m_dataVector[0];
}
int size()
{
return m_pos;
}
private:
int m_pos;
std::vector<TData> m_dataVector;
};
template<typename TData, typename THandle=int>
class stl_circle_pool
{
public:
typedef bool TFlag;
public:
stl_circle_pool()
{
initialize();
}
virtual ~stl_circle_pool()
{
destroy();
}
void destroy()
{
if (m_datas)
{
delete [] m_datas;
m_datas=NULL;
}
if (m_flags)
{
delete [] m_flags;
m_flags=NULL;
}
}
void create(int size)
{
destroy();
initialize();
m_size=size;
m_datas=new TData[m_size];
m_flags=new TFlag[m_size];
for (int i=0; i<m_size; ++i)
m_flags[i]=false;
}
THandle alloc()
{
THandle max=m_size;
THandle loop=max;
while (loop--)
{
int cur=m_pos%max;++m_pos;
if (!m_flags[cur])
{
m_flags[cur]=true;
return cur;
}
}
assert(!"Out of Memory");
return 0;
}
void free(THandle handle)
{
assert(check(handle) && "Out of RANGE");
m_flags[handle]=false;
}
inline bool check(THandle handle)
{
if (handle>=m_size) return false;
return true;
}
inline int size()
{
return m_size;
}
inline TData& refer(THandle handle)
{
assert(check(handle) && "Out of RANGE");
return m_datas[handle];
}
protected:
void initialize()
{
m_datas=NULL;
m_flags=NULL;
m_pos=0;
m_size=0;
}
protected:
TData* m_datas;
TFlag* m_flags;
THandle m_size;
THandle m_pos;
};
typedef std::vector<std::string> CTokenVector;
typedef std::map<std::string, std::string> CTokenMap;
typedef std::map<std::string, CTokenVector> CTokenVectorMap;
//class CTokenVector : public std::vector<std::string>
//{
// public:
// CTokenVector() : std::vector<std::string> ()
// {
// }
// virtual ~CTokenVector()
// {
// }
//};
//
//class CTokenMap : public std::map<std::string, std::string>
//{
// public:
// CTokenMap() : std::map<std::string, std::string>()
// {
// }
// virtual ~CTokenMap()
// {
// }
//};
//
//class CTokenVectorMap : public std::map<std::string, CTokenVector>
//{
// public:
// CTokenVectorMap() : std::map<std::string, CTokenVector>()
// {
// }
// virtual ~CTokenVectorMap()
// {
// }
//
//};
/*
template <typename T1, typename T2>
class CMapIterator
{
public:
typedef std::map<T1, T2> TMapType;
public:
CMapIterator(TMapType & rMap)
{
m_it = rMap.begin();
m_itEnd = rMap.end();
}
inline T2 operator * () { return m_it->second; }
inline bool operator ++()
{
if (m_itEnd == m_it)
return false;
++m_it;
return m_itEnd != m_it;
}
inline T1 GetFirst() { return m_it->first; }
inline T2 GetSecond() { return m_it->second; }
private:
TMapType::iterator m_it;
TMapType::iterator m_itEnd;
};
*/
struct stringhash
{
size_t GetHash(const std::string & str) const
{
const unsigned char * s = (const unsigned char*) str.c_str();
const unsigned char * end = s + str.size();
size_t h = 0;
while (s < end)
{
h *= 16777619;
h ^= (unsigned char) *(unsigned char *) (s++);
}
return h;
}
size_t operator () (const std::string & str) const
{
return GetHash(str);
}
};
#endif

21
src/EterBase/TempFile.cpp Normal file
View File

@ -0,0 +1,21 @@
#include "StdAfx.h"
#include "TempFile.h"
#include "Utils.h"
#include "Debug.h"
CTempFile::~CTempFile()
{
Destroy();
DeleteFile(m_szFileName);
}
CTempFile::CTempFile(const char * c_pszPrefix)
{
strncpy(m_szFileName, CreateTempFileName(c_pszPrefix), MAX_PATH);
if (!Create(m_szFileName, CFileBase::FILEMODE_WRITE))
{
TraceError("CTempFile::CTempFile cannot create temporary file. (filename: %s)", m_szFileName);
return;
}
}

16
src/EterBase/TempFile.h Normal file
View File

@ -0,0 +1,16 @@
#ifndef __INC_ETERBASE_TEMPFILE_H__
#define __INC_ETERBASE_TEMPFILE_H__
#include "FileBase.h"
class CTempFile : public CFileBase
{
public:
CTempFile(const char * c_pszPrefix = NULL);
virtual ~CTempFile();
protected:
char m_szFileName[MAX_PATH+1];
};
#endif

156
src/EterBase/Timer.cpp Normal file
View File

@ -0,0 +1,156 @@
#include "StdAfx.h"
#include "Timer.h"
static LARGE_INTEGER gs_liTickCountPerSec;
static DWORD gs_dwBaseTime=0;
static DWORD gs_dwServerTime=0;
static DWORD gs_dwClientTime=0;
static DWORD gs_dwFrameTime=0;
#pragma comment(lib, "winmm.lib")
BOOL ELTimer_Init()
{
/*
gs_liTickCountPerSec.QuadPart=0;
if (!QueryPerformanceFrequency(&gs_liTickCountPerSec))
return 0;
LARGE_INTEGER liTickCount;
QueryPerformanceCounter(&liTickCount);
gs_dwBaseTime= (liTickCount.QuadPart*1000 / gs_liTickCountPerSec.QuadPart);
*/
gs_dwBaseTime = timeGetTime();
return 1;
}
DWORD ELTimer_GetMSec()
{
//assert(gs_dwBaseTime!=0 && "ELTimer_Init <20><> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ϼ<EFBFBD><CFBC><EFBFBD>");
//LARGE_INTEGER liTickCount;
//QueryPerformanceCounter(&liTickCount);
return timeGetTime() - gs_dwBaseTime; //(liTickCount.QuadPart*1000 / gs_liTickCountPerSec.QuadPart)-gs_dwBaseTime;
}
VOID ELTimer_SetServerMSec(DWORD dwServerTime)
{
NANOBEGIN
if (0 != dwServerTime) // nanomite<74><65> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> if
{
gs_dwServerTime = dwServerTime;
gs_dwClientTime = CTimer::instance().GetCurrentMillisecond();
}
NANOEND
}
DWORD ELTimer_GetServerMSec()
{
return CTimer::instance().GetCurrentMillisecond() - gs_dwClientTime + gs_dwServerTime;
//return ELTimer_GetMSec() - gs_dwClientTime + gs_dwServerTime;
}
DWORD ELTimer_GetFrameMSec()
{
return gs_dwFrameTime;
}
DWORD ELTimer_GetServerFrameMSec()
{
return ELTimer_GetFrameMSec() - gs_dwClientTime + gs_dwServerTime;
}
VOID ELTimer_SetFrameMSec()
{
gs_dwFrameTime = ELTimer_GetMSec();
}
CTimer::CTimer()
{
ELTimer_Init();
NANOBEGIN
if (this) // nanomite<74><65> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> if
{
m_dwCurrentTime = 0;
m_bUseRealTime = true;
m_index = 0;
m_dwElapsedTime = 0;
m_fCurrentTime = 0.0f;
}
NANOEND
}
CTimer::~CTimer()
{
}
void CTimer::SetBaseTime()
{
m_dwCurrentTime = 0;
}
void CTimer::Advance()
{
if (!m_bUseRealTime)
{
++m_index;
if (m_index == 1)
m_index = -1;
m_dwCurrentTime += 16 + (m_index & 1);
m_fCurrentTime = m_dwCurrentTime / 1000.0f;
}
else
{
DWORD currentTime = ELTimer_GetMSec();
if (m_dwCurrentTime == 0)
m_dwCurrentTime = currentTime;
m_dwElapsedTime = currentTime - m_dwCurrentTime;
m_dwCurrentTime = currentTime;
}
}
void CTimer::Adjust(int iTimeGap)
{
m_dwCurrentTime += iTimeGap;
}
float CTimer::GetCurrentSecond()
{
if (m_bUseRealTime)
return ELTimer_GetMSec() / 1000.0f;
return m_fCurrentTime;
}
DWORD CTimer::GetCurrentMillisecond()
{
if (m_bUseRealTime)
return ELTimer_GetMSec();
return m_dwCurrentTime;
}
float CTimer::GetElapsedSecond()
{
return GetElapsedMilliecond() / 1000.0f;
}
DWORD CTimer::GetElapsedMilliecond()
{
if (!m_bUseRealTime)
return 16 + (m_index & 1);
return m_dwElapsedTime;
}
void CTimer::UseCustomTime()
{
m_bUseRealTime = false;
}

41
src/EterBase/Timer.h Normal file
View File

@ -0,0 +1,41 @@
#pragma once
#include <windows.h>
#include "Singleton.h"
class CTimer : public CSingleton<CTimer>
{
public:
CTimer();
virtual ~CTimer();
void Advance();
void Adjust(int iTimeGap);
void SetBaseTime();
float GetCurrentSecond();
DWORD GetCurrentMillisecond();
float GetElapsedSecond();
DWORD GetElapsedMilliecond();
void UseCustomTime();
protected:
bool m_bUseRealTime;
DWORD m_dwBaseTime;
DWORD m_dwCurrentTime;
float m_fCurrentTime;
DWORD m_dwElapsedTime;
int m_index;
};
BOOL ELTimer_Init();
DWORD ELTimer_GetMSec();
VOID ELTimer_SetServerMSec(DWORD dwServerTime);
DWORD ELTimer_GetServerMSec();
VOID ELTimer_SetFrameMSec();
DWORD ELTimer_GetFrameMSec();

676
src/EterBase/Utils.cpp Normal file
View File

@ -0,0 +1,676 @@
#include "StdAfx.h"
#include <stdlib.h>
#include <direct.h>
#include <io.h>
#include <assert.h>
#include <sys/stat.h>
#include "Utils.h"
#include "filedir.h"
char korean_tolower(const char c);
const char * CreateTempFileName(const char * c_pszPrefix)
{
char szTempPath[MAX_PATH + 1];
static char szTempName[MAX_PATH + 1];
GetTempPath(MAX_PATH, szTempPath);
GetTempFileName(szTempPath, // directory for temp files
c_pszPrefix ? c_pszPrefix : "etb", // temp file name prefix
c_pszPrefix ? true : false, // create unique name
szTempName); // buffer for name
return (szTempName);
}
void GetFilePathNameExtension(const char * c_szFile, int len, std::string * pstPath, std::string * pstName, std::string * pstExt)
{
assert(pstPath != NULL);
assert(pstName != NULL);
assert(pstExt != NULL);
int ext = len;
int pos = len;
while (pos > 0)
{
--pos;
char c = c_szFile[pos];
if (ext == len && c == '.')
{
ext = pos;
break;
}
if (c == '/' || c == '\\')
break;
}
while (pos > 0)
{
--pos;
char c = c_szFile[pos];
if (c == '/' || c == '\\')
break;
}
if (pos)
{
++pos;
pstPath->append(c_szFile, pos);
}
if (ext > pos)
pstName->append(c_szFile + pos, ext - pos);
++ext;
if (len > ext)
pstExt->append(c_szFile + ext, len - ext);
}
void GetFileExtension(const char* c_szFile, int len, std::string* pstExt)
{
int ext = len;
int pos = len;
while (pos > 0)
{
--pos;
char c=c_szFile[pos];
if (ext==len && c=='.')
{
ext=pos;
break;
}
if (c=='/') break;
else if (c=='\\') break;
}
++ext;
if (len>ext)
pstExt->append(c_szFile+ext, len-ext);
}
void GetFileNameParts(const char* c_szFile, int len, char* pszPath, char* pszName, char* pszExt)
{
assert(pszPath!=NULL);
assert(pszName!=NULL);
assert(pszExt!=NULL);
int ext=len;
int pos=len;
while (pos>0)
{
--pos;
char c=c_szFile[pos];
if (ext==len && c=='.')
{
ext=pos;
break;
}
if (c=='/') break;
else if (c=='\\') break;
}
while (pos>0)
{
--pos;
char c=c_szFile[pos];
if (c=='/') break;
else if (c=='\\') break;
}
if (pos)
{
++pos;
for (int i = 0; i < pos; ++i)
{
pszPath[i] = c_szFile[i];
}
pszPath[pos] = '\0';
}
if (ext>pos)
{
int count = 0;
for (int i = pos; i < ext; ++i)
{
pszName[count++] = c_szFile[i];
}
pszName[count] = '\0';
}
++ext;
if (len > ext)
{
int count = 0;
for (int i = ext; i < len; ++i)
{
pszExt[count++] = c_szFile[i];
}
pszExt[count] = '\0';
}
}
void GetOldIndexingName(char * szName, int Index)
{
int dec, sign;
char Temp[512];
strcpy(Temp, _ecvt(Index, 256, &dec, &sign));
Temp[dec] = '\0';
strcat(szName, Temp);
}
void GetIndexingName(char * szName, DWORD Index)
{
sprintf(szName + strlen(szName), "%u", Index);
}
void GetOnlyFileName(const char * sz_Name, std::string & strFileName)
{
strFileName = "";
int i;
for (i=strlen(sz_Name)-1; i>=0; --i)
{
if ('\\' == sz_Name[i] || '/' == sz_Name[i])
{
++i;
break;
}
}
if (i == -1)
i = 0;
for (size_t j = i; j < strlen(sz_Name); ++j)
{
strFileName += sz_Name[j];
}
strFileName += "\0";
}
void GetExceptionPathName(const char * sz_Name, std::string & OnlyFileName)
{
GetOnlyFileName(sz_Name, OnlyFileName);
}
void GetOnlyPathName(const char * sz_Name, std::string & OnlyPathName)
{
int i;
for (i = strlen(sz_Name) - 1; i >= 0; --i)
{
if ('\\' == sz_Name[i] || '/' == sz_Name[i])
{
++i;
break;
}
}
if (i == -1)
i = 0;
OnlyPathName.reserve(strlen(sz_Name));
OnlyPathName = "";
for (int j=0; j<i; ++j)
{
OnlyPathName += sz_Name[j];
}
OnlyPathName += "\0";
}
const char * GetOnlyPathName(const char * c_szName)
{
static std::string strPathName;
GetOnlyPathName(c_szName, strPathName);
return strPathName.c_str();
}
bool GetLocalFileName(const char * c_szGlobalPath, const char * c_szFullPathFileName, std::string * pstrLocalFileName)
{
std::string strLocalFileName;
std::string strGlobalPath;
std::string strFullPathFileName;
StringPath(c_szGlobalPath, strGlobalPath);
StringPath(c_szFullPathFileName, strFullPathFileName);
if (strGlobalPath.length() >= strFullPathFileName.length())
return false;
DWORD length = min(strGlobalPath.length(), strFullPathFileName.length());
for (DWORD dwPos = 0; dwPos < length; ++dwPos)
{
if (strGlobalPath[dwPos] != strFullPathFileName[dwPos])
return false;
}
*pstrLocalFileName = &c_szFullPathFileName[length];
return true;
}
void GetWorkingFolder(std::string & strFileName)
{
char buf[128+1];
_getcwd(buf, 128);
strcat(buf, "/");
strFileName = buf;
}
void StringLowers(char * String)
{
for (DWORD i = 0; i < strlen(String); ++i)
{
String[i] = korean_tolower(String[i]);
}
}
void StringPath(std::string & rString)
{
for (DWORD i = 0; i < rString.length(); ++i)
{
if (rString[i] == '\\')
rString[i] = '/';
else
rString[i] = korean_tolower(rString[i]);
}
}
void StringPath(char * pString)
{
for (DWORD i = 0; i < strlen(pString); ++i)
{
if (pString[i] == '\\')
pString[i] = '/';
else
pString[i] = korean_tolower(pString[i]);
}
}
void StringPath(const char * c_szSrc, char * szDest)
{
for (DWORD i = 0; i < strlen(c_szSrc); ++i)
{
if (c_szSrc[i] == '\\')
szDest[i] = '/';
else
szDest[i] = korean_tolower(c_szSrc[i]);
}
}
void StringPath(const char * c_szSrc, std::string & rString)
{
rString = "";
rString.resize(strlen(c_szSrc));
for (DWORD i = 0; i < strlen(c_szSrc); ++i)
{
if (c_szSrc[i] == '\\')
rString[i] = '/';
else
rString[i] = korean_tolower(c_szSrc[i]);
}
}
#define ishprint(x) ((((x) & 0xE0) > 0x90) || isprint(x))
void PrintAsciiData(const void* void_data, int bytes)
{
int i, j, k;
const unsigned char* p;
const unsigned char* data;
data = (const unsigned char*) void_data;
fprintf(stdout, "------------------------------------------------------------------\n");
j = bytes;
while (1)
{
k = j >= 16 ? 16 : j;
p = data;
for (i = 0; i < 16; ++i)
{
if (i >= k)
fprintf(stdout, " ");
else
fprintf(stdout, "%02x ", *p);
p++;
}
fprintf(stdout, "| ");
p = data;
for (i = 0; i < k; ++i)
{
if (i >= k)
fprintf(stdout, " ");
else
fprintf(stdout, "%c", ishprint(*p) ? *p : '.');
p++;
}
fprintf(stdout, "\n");
j -= 16;
data += 16;
if (j <= 0)
break;
}
fprintf(stdout, "------------------------------------------------------------------\n");
}
int MIN(int a, int b)
{
return a < b ? a : b;
}
int MAX(int a, int b)
{
return a > b ? a : b;
}
int MINMAX(int min, int value, int max)
{
if (max < min)
return MAX(min, value);
register int tv;
tv = (min > value ? min : value);
return (max < tv) ? max : tv;
}
float fMIN(float a, float b)
{
return a < b ? a : b;
}
float fMAX(float a, float b)
{
return a > b ? a : b;
}
float fMINMAX(float min, float value, float max)
{
register float tv;
tv = (min > value ? min : value);
return (max < tv) ? max : tv;
}
bool IsFile(const char* filename)
{
return _access(filename, 0) == 0 ? true : false;
}
bool IsGlobalFileName(const char * c_szFileName)
{
return strchr(c_szFileName, ':') != NULL;
}
void MyCreateDirectory(const char* path)
{
if (!path || !*path)
return;
char * dir;
const char * p;
if (strlen(path) >= 3)
{
if (*(path + 1) == ':') // C:, D: <20><><EFBFBD><EFBFBD> <20><><EFBFBD>츦 üũ
path += 3;
}
p = path;
int len = strlen(path) + 1;
dir = new char[len];
while (*p)
{
if (*p == '/' || *p == '\\')
{
memset(dir, 0, len);
strncpy(dir, path, p - path);
CreateDirectory(dir, NULL);
}
++p;
}
delete [] dir;
}
class CDirRemover : public CDir
{
public:
CDirRemover()
{
}
virtual ~CDirRemover()
{
}
bool OnFolder(const char* c_szFilter, const char* c_szPathName, const char* c_szFileName)
{
std::string strFullPathName;
strFullPathName = c_szPathName;
strFullPathName += c_szFileName;
CDirRemover remover;
remover.Create(c_szFilter, strFullPathName.c_str());
std::string strWorkingFolder;
GetWorkingFolder(strWorkingFolder);
strWorkingFolder += strFullPathName;
strWorkingFolder += "/";
StringPath(strWorkingFolder);
ms_strDirectoryDeque.push_back(strWorkingFolder);
return true;
}
bool OnFile(const char* c_szPathName, const char* c_szFileName)
{
std::string strFullPathName;
strFullPathName = c_szPathName;
strFullPathName += c_szFileName;
_chmod(strFullPathName.c_str(), _S_IWRITE);
DeleteFile(strFullPathName.c_str());
return true;
}
static void RemoveAllDirectory()
{
for (std::deque<std::string>::iterator itor = ms_strDirectoryDeque.begin(); itor != ms_strDirectoryDeque.end(); ++itor)
{
const std::string & c_rstrDirectory = *itor;
RemoveDirectory(c_rstrDirectory.c_str());
}
ms_strDirectoryDeque.clear();
}
protected:
static std::deque<std::string> ms_strDirectoryDeque;
};
std::deque<std::string> CDirRemover::ms_strDirectoryDeque;
void RemoveAllDirectory(const char * c_szDirectoryName)
{
{
CDirRemover remover;
remover.Create("*.*", c_szDirectoryName);
CDirRemover::RemoveAllDirectory();
}
RemoveDirectory(c_szDirectoryName);
}
void StringExceptCharacter(std::string * pstrString, const char * c_szCharacter)
{
int icurPos = 0;
int iNextPos = 0;
while((iNextPos = pstrString->find_first_of(c_szCharacter, icurPos)) >= 0)
{
std::string strFront = pstrString->substr(icurPos, iNextPos - icurPos);
std::string strBack = pstrString->substr(iNextPos+1, pstrString->length() - iNextPos - 1);
*pstrString = strFront + strBack;
}
}
bool SplitLine(const char * c_szLine, const char * c_szDelimeter, std::vector<std::string> * pkVec_strToken)
{
pkVec_strToken->reserve(10);
pkVec_strToken->clear();
std::string strLine = c_szLine;
DWORD basePos = 0;
do
{
int beginPos = strLine.find_first_not_of(c_szDelimeter, basePos);
if (beginPos < 0)
return false;
int endPos;
if (strLine[beginPos] == '"')
{
++beginPos;
endPos = strLine.find_first_of("\"", beginPos);
if (endPos < 0)
return false;
basePos = endPos + 1;
}
else
{
endPos = strLine.find_first_of(c_szDelimeter, beginPos);
basePos = endPos;
}
pkVec_strToken->push_back(strLine.substr(beginPos, endPos - beginPos));
} while (basePos < strLine.length());
return true;
}
void GetExcutedFileName(std::string & r_str)
{
char szPath[MAX_PATH+1];
GetModuleFileName(NULL, szPath, MAX_PATH);
szPath[MAX_PATH] = '\0';
r_str = szPath;
}
const char * _getf(const char* c_szFormat, ...)
{
static char szBuf[256];
va_list args;
va_start(args, c_szFormat);
_vsnprintf(szBuf, sizeof(szBuf), c_szFormat, args);
va_end(args);
return szBuf;
}
PCHAR* CommandLineToArgv( PCHAR CmdLine, int* _argc )
{
PCHAR* argv;
PCHAR _argv;
ULONG len;
ULONG argc;
CHAR a;
ULONG i, j;
BOOLEAN in_QM;
BOOLEAN in_TEXT;
BOOLEAN in_SPACE;
len = strlen(CmdLine);
i = ((len+2)/2)*sizeof(PVOID) + sizeof(PVOID);
argv = (PCHAR*)GlobalAlloc(GMEM_FIXED,
i + (len+2)*sizeof(CHAR));
_argv = (PCHAR)(((PUCHAR)argv)+i);
argc = 0;
argv[argc] = _argv;
in_QM = FALSE;
in_TEXT = FALSE;
in_SPACE = TRUE;
i = 0;
j = 0;
while( a = CmdLine[i] ) {
if(in_QM) {
if(a == '\"') {
in_QM = FALSE;
} else {
_argv[j] = a;
j++;
}
} else {
switch(a) {
case '\"':
in_QM = TRUE;
in_TEXT = TRUE;
if(in_SPACE) {
argv[argc] = _argv+j;
argc++;
}
in_SPACE = FALSE;
break;
case ' ':
case '\t':
case '\n':
case '\r':
if(in_TEXT) {
_argv[j] = '\0';
j++;
}
in_TEXT = FALSE;
in_SPACE = TRUE;
break;
default:
in_TEXT = TRUE;
if(in_SPACE) {
argv[argc] = _argv+j;
argc++;
}
_argv[j] = a;
j++;
in_SPACE = FALSE;
break;
}
}
i++;
}
_argv[j] = '\0';
argv[argc] = NULL;
(*_argc) = argc;
return argv;
}

218
src/EterBase/Utils.h Normal file
View File

@ -0,0 +1,218 @@
#ifndef __INC_ETER2_ETERBASE_UTILS_H__
#define __INC_ETER2_ETERBASE_UTILS_H__
#include <windows.h>
#include <vector>
#include <string>
#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if (p) { delete (p); (p) = NULL; } }
#endif
#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p) = NULL; } }
#endif
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = NULL; } }
#endif
#ifndef SAFE_FREE_GLOBAL
#define SAFE_FREE_GLOBAL(p) { if (p) { ::GlobalFree(p); (p) = NULL; } }
#endif
#ifndef SAFE_FREE_LIBRARY
#define SAFE_FREE_LIBRARY(p) { if (p) { ::FreeLibrary(p); (p) = NULL; } }
#endif
#define AssertLog(str) TraceError(str); assert(!str)
#ifndef MAKEFOURCC
#define MAKEFOURCC(ch0, ch1, ch2, ch3) \
((DWORD)(BYTE) (ch0 ) | ((DWORD)(BYTE) (ch1) << 8) | \
((DWORD)(BYTE) (ch2) << 16) | ((DWORD)(BYTE) (ch3) << 24))
#endif // defined(MAKEFOURCC)
#ifndef IS_SET
#define IS_SET(flag,bit) ((flag) & (bit))
#endif
#ifndef SET_BIT
#define SET_BIT(var,bit) ((var) |= (bit))
#endif
#ifndef REMOVE_BIT
#define REMOVE_BIT(var,bit) ((var) &= ~(bit))
#endif
#ifndef TOGGLE_BIT
#define TOGGLE_BIT(var,bit) ((var) = (var) ^ (bit))
#endif
extern const char * CreateTempFileName(const char * c_pszPrefix = NULL);
extern void GetFilePathNameExtension(const char* c_szFile, int len, std::string* pstPath, std::string* pstName, std::string* pstExt);
extern void GetFileExtension(const char* c_szFile, int len, std::string* pstExt);
extern void GetFileNameParts(const char* c_szFile, int len, char* pszPath, char* pszName, char* pszExt);
extern void GetOldIndexingName(char * szName, int Index);
extern void GetIndexingName(char * szName, DWORD Index);
extern void stl_lowers(std::string& rstRet);
extern void GetOnlyFileName(const char * sz_Name, std::string & strFileName);
extern void GetOnlyPathName(const char * sz_Name, std::string & OnlyPathName);
extern const char * GetOnlyPathName(const char * c_szName);
bool GetLocalFileName(const char * c_szGlobalPath, const char * c_szFullPathFileName, std::string * pstrLocalFileName);
extern void GetExceptionPathName(const char * sz_Name, std::string & OnlyFileName);
extern void GetWorkingFolder(std::string & strFileName);
extern void StringLowers(char * pString);
extern void StringPath(std::string & rString);
extern void StringPath(char * pString); // <20><><EFBFBD><EFBFBD> <20>ҹ<EFBFBD><D2B9>ڷ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, \<5C><> /<2F><> <20>ٲ۴<D9B2>.
extern void StringPath(const char * c_szSrc, char * szDest); // <20><><EFBFBD><EFBFBD> <20>ҹ<EFBFBD><D2B9>ڷ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, \<5C><> /<2F><> <20>ٲ۴<D9B2>.
extern void StringPath(const char * c_szSrc, std::string & rString); // <20><><EFBFBD><EFBFBD> <20>ҹ<EFBFBD><D2B9>ڷ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, \<5C><> /<2F><> <20>ٲ۴<D9B2>.
extern void PrintAsciiData(const void* data, int bytes);
bool IsFile(const char* filename);
bool IsGlobalFileName(const char * c_szFileName);
int MIN(int a, int b);
int MAX(int a, int b);
int MINMAX(int min, int value, int max);
float fMIN(float a, float b);
float fMAX(float a, float b);
float fMINMAX(float min, float value, float max);
void MyCreateDirectory(const char* path);
void RemoveAllDirectory(const char * c_szDirectoryName);
bool SplitLine(const char * c_szLine, const char * c_szDelimeter, std::vector<std::string> * pkVec_strToken);
const char * _getf(const char* c_szFormat, ...);
PCHAR* CommandLineToArgv( PCHAR CmdLine, int* _argc );
template<typename T>
T EL_DegreeToRadian(T degree)
{
const T PI = T(3.141592);
return T(PI*degree/180.0f);
}
template<typename T>
void ELPlainCoord_GetRotatedPixelPosition(T centerX, T centerY, T distance, T rotDegree, T* pdstX, T* pdstY)
{
T rotRadian=EL_DegreeToRadian(rotDegree);
*pdstX=centerX+distance*T(sin((double)rotRadian));
*pdstY=centerY+distance*T(cos((double)rotRadian));
}
template<typename T>
T EL_SignedDegreeToUnsignedDegree(T fSrc)
{
if (fSrc<0.0f)
return T(360.0+T(fmod(fSrc, 360.0)));
return T(fmod(fSrc, 360.0));
}
template<typename T>
T ELRightCoord_ConvertToPlainCoordDegree(T srcDegree)
{
return T(fmod(450.0 - srcDegree, 360.0));
}
template<typename C>
void string_join(const std::string& sep, const C& container, std::string* ret)
{
unsigned int capacity = sep.length() * container.size() - 1;
// calculate string sequence
{
for (C::const_iterator i = container.begin(); i != container.end(); ++i)
capacity += (*i).length();
}
std::string buf;
buf.reserve(capacity);
// join strings
{
C::const_iterator cur = container.begin();
C::const_iterator end = container.end();
--end;
while (cur != end)
{
buf.append(*cur++);
buf.append(sep);
}
buf.append(*cur);
}
swap(*ret, buf);
}
__forceinline int htoi(const wchar_t *s, int size)
{
const wchar_t *t = s;
int x = 0, y = 1;
s += size;
while (t <= --s)
{
if (L'0' <= *s && *s <= L'9')
x += y * (*s - L'0');
else if (L'a' <= *s && *s <= L'f')
x += y * (*s - L'a' + 10);
else if (L'A' <= *s && *s <= L'F')
x += y * (10 + *s - L'A');
else
return -1; /* invalid input! */
y <<= 4;
}
return x;
}
__forceinline int htoi(const char *s, int size)
{
const char *t = s;
int x = 0, y = 1;
s += size;
while (t <= --s)
{
if ('0' <= *s && *s <= '9')
x += y * (*s - '0');
else if ('a' <= *s && *s <= 'f')
x += y * (*s - 'a' + 10);
else if ('A' <= *s && *s <= 'F')
x += y * (10 + *s - 'A');
else
return -1; /* invalid input! */
y <<= 4;
}
return x;
}
__forceinline int htoi(const char *s)
{
const char *t = s;
int x = 0, y = 1;
s += strlen(s);
while (t <= --s)
{
if ('0' <= *s && *s <= '9')
x += y * (*s - '0');
else if ('a' <= *s && *s <= 'f')
x += y * (*s - 'a' + 10);
else if ('A' <= *s && *s <= 'F')
x += y * (10 + *s - 'A');
else
return -1; /* invalid input! */
y <<= 4;
}
return x;
}
typedef std::vector<std::string> TTokenVector;
void StringExceptCharacter(std::string * pstrString, const char * c_szCharacter);
extern void GetExcutedFileName(std::string & r_str);
#endif

208
src/EterBase/error.cpp Normal file
View File

@ -0,0 +1,208 @@
#include "StdAfx.h"
#include <stdio.h>
#include <time.h>
#include <winsock.h>
#include <imagehlp.h>
FILE * fException;
/*
static char __msg[4000], __cmsg[4000];
static int __idx;
CLZObject __l;
*/
/*
typedef BOOL
(CALLBACK *PENUMLOADED_MODULES_CALLBACK)(
__in PCSTR ModuleName,
__in ULONG ModuleBase,
__in ULONG ModuleSize,
__in_opt PVOID UserContext
);
*/
#if _MSC_VER >= 1400
BOOL CALLBACK EnumerateLoadedModulesProc(PCSTR ModuleName, ULONG ModuleBase, ULONG ModuleSize, PVOID UserContext)
#else
BOOL CALLBACK EnumerateLoadedModulesProc(PSTR ModuleName, ULONG ModuleBase, ULONG ModuleSize, PVOID UserContext)
#endif
{
DWORD offset = *((DWORD*)UserContext);
if (offset >= ModuleBase && offset <= ModuleBase + ModuleSize)
{
fprintf(fException, "%s", ModuleName);
//__idx += sprintf(__msg+__idx, "%s", ModuleName);
return FALSE;
}
else
return TRUE;
}
LONG __stdcall EterExceptionFilter(_EXCEPTION_POINTERS* pExceptionInfo)
{
HANDLE hProcess = GetCurrentProcess();
HANDLE hThread = GetCurrentThread();
fException = fopen("ErrorLog.txt", "wt");
if (fException)
{
char module_name[256];
time_t module_time;
HMODULE hModule = GetModuleHandle(NULL);
GetModuleFileName(hModule, module_name, sizeof(module_name));
module_time = (time_t)GetTimestampForLoadedLibrary(hModule);
fprintf(fException, "Module Name: %s\n", module_name);
fprintf(fException, "Time Stamp: 0x%08x - %s\n", module_time, ctime(&module_time));
fprintf(fException, "\n");
fprintf(fException, "Exception Type: 0x%08x\n", pExceptionInfo->ExceptionRecord->ExceptionCode);
fprintf(fException, "\n");
/*
{
__idx+=sprintf(__msg+__idx,"Module Name: %s\n", module_name);
__idx+=sprintf(__msg+__idx, "Time Stamp: 0x%08x - %s\n", module_time, ctime(&module_time));
__idx+=sprintf(__msg+__idx, "\n");
__idx+=sprintf(__msg+__idx, "Exception Type: 0x%08x\n", pExceptionInfo->ExceptionRecord->ExceptionCode);
__idx+=sprintf(__msg+__idx, "\n");
}
*/
CONTEXT& context = *pExceptionInfo->ContextRecord;
fprintf(fException, "eax: 0x%08x\tebx: 0x%08x\n", context.Eax, context.Ebx);
fprintf(fException, "ecx: 0x%08x\tedx: 0x%08x\n", context.Ecx, context.Edx);
fprintf(fException, "esi: 0x%08x\tedi: 0x%08x\n", context.Esi, context.Edi);
fprintf(fException, "ebp: 0x%08x\tesp: 0x%08x\n", context.Ebp, context.Esp);
fprintf(fException, "\n");
/*
{
__idx+=sprintf(__msg+__idx, "eax: 0x%08x\tebx: 0x%08x\n", context.Eax, context.Ebx);
__idx+=sprintf(__msg+__idx, "ecx: 0x%08x\tedx: 0x%08x\n", context.Ecx, context.Edx);
__idx+=sprintf(__msg+__idx, "esi: 0x%08x\tedi: 0x%08x\n", context.Esi, context.Edi);
__idx+=sprintf(__msg+__idx, "ebp: 0x%08x\tesp: 0x%08x\n", context.Ebp, context.Esp);
__idx+=sprintf(__msg+__idx, "\n");
}
*/
STACKFRAME stackFrame = {0,};
stackFrame.AddrPC.Offset = context.Eip;
stackFrame.AddrPC.Mode = AddrModeFlat;
stackFrame.AddrStack.Offset = context.Esp;
stackFrame.AddrStack.Mode = AddrModeFlat;
stackFrame.AddrFrame.Offset = context.Ebp;
stackFrame.AddrFrame.Mode = AddrModeFlat;
for (int i=0; i < 512 && stackFrame.AddrPC.Offset; ++i)
{
if (StackWalk(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &stackFrame, &context, NULL, NULL, NULL, NULL) != FALSE)
{
fprintf(fException, "0x%08x\t", stackFrame.AddrPC.Offset);
//__idx+=sprintf(__msg+__idx, "0x%08x\t", stackFrame.AddrPC.Offset);
EnumerateLoadedModules(hProcess, (PENUMLOADED_MODULES_CALLBACK) EnumerateLoadedModulesProc, &stackFrame.AddrPC.Offset);
fprintf(fException, "\n");
//__idx+=sprintf(__msg+__idx, "\n");
}
else
{
break;
}
}
fprintf(fException, "\n");
//__idx+=sprintf(__msg+__idx, "\n");
/*
BYTE* stack = (BYTE*)(context.Esp);
fprintf(fException, "stack %08x - %08x\n", context.Esp, context.Esp+1024);
//__idx+=sprintf(__msg+__idx, "stack %08x - %08x\n", context.Esp, context.Esp+1024);
for(i=0; i<16; ++i)
{
fprintf(fException, "%08X : ", context.Esp+i*16);
//__idx+=sprintf(__msg+__idx, "%08X : ", context.Esp+i*16);
for(int j=0; j<16; ++j)
{
fprintf(fException, "%02X ", stack[i*16+j]);
//__idx+=sprintf(__msg+__idx, "%02X ", stack[i*16+j]);
}
fprintf(fException, "\n");
//__idx+=sprintf(__msg+__idx, "\n");
}
fprintf(fException, "\n");
//__idx+=sprintf(__msg+__idx, "\n");
*/
fflush(fException);
fclose(fException);
fException = NULL;
//WinExec()
/*CreateProcess("cmd.exe",NULL,NULL,NULL,FALSE,
CREATE_NEW_PROCESS_GROUP|DETACHED_PROCESS,NULL,NULL,NULL,NULL);
MessageBox(NULL,"<22><><EFBFBD><EFBFBD> <20><><EFBFBD>࿡ ġ<><C4A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>߻<EFBFBD><DFBB>Ͽ<EFBFBD><CFBF><EFBFBD><EFBFBD>ϴ<EFBFBD>.\n<><6E><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ϰ<EFBFBD> <20><><EFBFBD><EFBFBD> <20>α׸<CEB1> <20><><EFBFBD><EFBFBD><EFBFBD>ϴ<EFBFBD>.\n<><6E><EFBFBD><EFBFBD> <20>α׸<CEB1> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ðڽ<C3B0><DABD>ϱ<EFBFBD>?","<22><><EFBFBD><EFBFBD> <20>߻<EFBFBD>!",MB_YESNO);*/
/*
__l.BeginCompressInBuffer(__msg,__idx,__cmsg);
if (__l.Compress())
{
//fprintf(fException,"Compress printing\n");
// send this to server
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
ioctlsocket(s,FIONBIO,0);
if (s==INVALID_SOCKET)
{
//fprintf(fException,"INVALID %X\n",WSAGetLastError());
}
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(19294);
sa.sin_addr.s_addr = inet_addr("147.46.127.42");
if (connect(s,(sockaddr*)&sa,sizeof(sa)))
{
//fprintf(fException,"%X\n",WSAGetLastError());
}
int total = 0;
int ret=0;
while(1)
{
//ret = send(s,(char*)__msg+total,__idx-total,0);
ret = send(s,(char*)__l.GetBuffer()+total,__l.GetSize()-total,0);
//fprintf(fException,"send %d\n",ret);
if (ret<0)
{
//fprintf(fException,"%X\n",WSAGetLastError());
break;
}
total+=ret;
if (total>=__idx)
//if (total>=__l.GetSize())
break;
}
//__l.GetBuffer();
Sleep(500);
closesocket(s);
}*/
WinExec("errorlog.exe",SW_SHOW);
}
return EXCEPTION_EXECUTE_HANDLER;
}
void SetEterExceptionHandler()
{
SetUnhandledExceptionFilter(EterExceptionFilter);
}

2
src/EterBase/error.h Normal file
View File

@ -0,0 +1,2 @@
#pragma once
extern void SetEterExceptionHandler();

410
src/EterBase/lzo.cpp Normal file
View File

@ -0,0 +1,410 @@
#include "StdAfx.h"
#include <stdlib.h>
#include "lzo.h"
#include "tea.h"
#include "debug.h"
#define dbg_printf
static class LZOFreeMemoryMgr
{
public:
enum
{
REUSING_CAPACITY = 64*1024,
};
public:
~LZOFreeMemoryMgr()
{
std::vector<BYTE*>::iterator i;
for (i = m_freeVector.begin(); i != m_freeVector.end(); ++i)
delete *i;
m_freeVector.clear();
}
BYTE* Alloc(unsigned capacity)
{
assert(capacity > 0);
if (capacity < REUSING_CAPACITY)
{
if (!m_freeVector.empty())
{
BYTE* freeMem = m_freeVector.back();
m_freeVector.pop_back();
dbg_printf("lzo.reuse_alloc\t%p(%d) free\n", freeMem, capacity);
return freeMem;
}
BYTE* newMem = new BYTE[REUSING_CAPACITY];
dbg_printf("lzo.reuse_alloc\t%p(%d) real\n", newMem, capacity);
return newMem;
}
BYTE* newMem = new BYTE[capacity];
dbg_printf("lzo.real_alloc\t%p(%d)\n", newMem, capacity);
return newMem;
}
void Free(BYTE* ptr, unsigned capacity)
{
assert(ptr != NULL);
assert(capacity > 0);
if (capacity < REUSING_CAPACITY)
{
dbg_printf("lzo.reuse_free\t%p(%d)\n", ptr, capacity);
m_freeVector.push_back(ptr);
return;
}
dbg_printf("lzo.real_free\t%p(%d)\n", ptr, capacity);
delete [] ptr;
}
private:
std::vector<BYTE*> m_freeVector;
} gs_freeMemMgr;
DWORD CLZObject::ms_dwFourCC = MAKEFOURCC('M', 'C', 'O', 'Z');
CLZObject::CLZObject()
{
Initialize();
}
void CLZObject::Initialize()
{
m_bInBuffer = false;
m_pbBuffer = NULL;
m_dwBufferSize = 0;
m_pHeader = NULL;
m_pbIn = NULL;
m_bCompressed = false;
}
void CLZObject::Clear()
{
if (m_pbBuffer && !m_bInBuffer)
gs_freeMemMgr.Free(m_pbBuffer, m_dwBufferSize);
if (m_dwBufferSize > 0)
{
dbg_printf("lzo.free %d\n", m_dwBufferSize);
}
Initialize();
}
CLZObject::~CLZObject()
{
Clear();
}
DWORD CLZObject::GetSize()
{
assert(m_pHeader);
if (m_bCompressed)
{
if (m_pHeader->dwEncryptSize)
return sizeof(THeader) + sizeof(DWORD) + m_pHeader->dwEncryptSize;
else
return sizeof(THeader) + sizeof(DWORD) + m_pHeader->dwCompressedSize;
}
else
return m_pHeader->dwRealSize;
}
void CLZObject::BeginCompress(const void * pvIn, UINT uiInLen)
{
m_pbIn = (const BYTE *) pvIn;
// sizeof(SHeader) +
// <20><>ȣȭ<C8A3><C8AD> <20><><EFBFBD><EFBFBD> fourCC 4<><34><EFBFBD><EFBFBD>Ʈ
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20>ִ<EFBFBD> <20>ִ<EFBFBD> <20>뷮 +
// <20><>ȣȭ<C8A3><C8AD> <20><><EFBFBD><EFBFBD> 8 <20><><EFBFBD><EFBFBD>Ʈ
m_dwBufferSize = sizeof(THeader) + sizeof(DWORD) + (uiInLen + uiInLen / 64 + 16 + 3) + 8;
m_pbBuffer = gs_freeMemMgr.Alloc(m_dwBufferSize);
memset(m_pbBuffer, 0, m_dwBufferSize);
m_pHeader = (THeader *) m_pbBuffer;
m_pHeader->dwFourCC = ms_dwFourCC;
m_pHeader->dwEncryptSize = m_pHeader->dwCompressedSize = m_pHeader->dwRealSize = 0;
m_pHeader->dwRealSize = uiInLen;
}
void CLZObject::BeginCompressInBuffer(const void * pvIn, UINT uiInLen, void * /*pvOut*/)
{
m_pbIn = (const BYTE *) pvIn;
// sizeof(SHeader) +
// <20><>ȣȭ<C8A3><C8AD> <20><><EFBFBD><EFBFBD> fourCC 4<><34><EFBFBD><EFBFBD>Ʈ
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20>ִ<EFBFBD> <20>ִ<EFBFBD> <20>뷮 +
// <20><>ȣȭ<C8A3><C8AD> <20><><EFBFBD><EFBFBD> 8 <20><><EFBFBD><EFBFBD>Ʈ
m_dwBufferSize = sizeof(THeader) + sizeof(DWORD) + (uiInLen + uiInLen / 64 + 16 + 3) + 8;
m_pbBuffer = gs_freeMemMgr.Alloc(m_dwBufferSize);
memset(m_pbBuffer, 0, m_dwBufferSize);
m_pHeader = (THeader *) m_pbBuffer;
m_pHeader->dwFourCC = ms_dwFourCC;
m_pHeader->dwEncryptSize = m_pHeader->dwCompressedSize = m_pHeader->dwRealSize = 0;
m_pHeader->dwRealSize = uiInLen;
m_bInBuffer = true;
}
bool CLZObject::Compress()
{
UINT iOutLen;
BYTE * pbBuffer;
pbBuffer = m_pbBuffer + sizeof(THeader);
*(DWORD *) pbBuffer = ms_dwFourCC;
pbBuffer += sizeof(DWORD);
#if defined( LZO1X_999_MEM_COMPRESS )
int r = lzo1x_999_compress((BYTE *) m_pbIn, m_pHeader->dwRealSize, pbBuffer, (lzo_uint*) &iOutLen, CLZO::Instance().GetWorkMemory());
#else
int r = lzo1x_1_compress((BYTE *) m_pbIn, m_pHeader->dwRealSize, pbBuffer, (lzo_uint*) &iOutLen, CLZO::Instance().GetWorkMemory());
#endif
if (LZO_E_OK != r)
{
TraceError("LZO: lzo1x_999_compress failed");
return false;
}
m_pHeader->dwCompressedSize = iOutLen;
m_bCompressed = true;
return true;
}
bool CLZObject::BeginDecompress(const void * pvIn)
{
THeader * pHeader = (THeader *) pvIn;
if (pHeader->dwFourCC != ms_dwFourCC)
{
TraceError("LZObject: not a valid data");
return false;
}
m_pHeader = pHeader;
m_pbIn = (const BYTE *) pvIn + (sizeof(THeader) + sizeof(DWORD));
/*
static unsigned sum = 0;
static unsigned count = 0;
sum += pHeader->dwRealSize;
count++;
printf("decompress cur: %d, ave: %d\n", pHeader->dwRealSize, sum/count);
*/
m_dwBufferSize = pHeader->dwRealSize;
m_pbBuffer = gs_freeMemMgr.Alloc(m_dwBufferSize);
memset(m_pbBuffer, 0, pHeader->dwRealSize);
return true;
}
class DecryptBuffer
{
public:
enum
{
LOCAL_BUF_SIZE = 8 * 1024,
};
public:
DecryptBuffer(unsigned size)
{
static unsigned count = 0;
static unsigned sum = 0;
static unsigned maxSize = 0;
sum += size;
count++;
maxSize = max(size, maxSize);
if (size >= LOCAL_BUF_SIZE)
{
m_buf = new char[size];
dbg_printf("DecryptBuffer - AllocHeap %d max(%d) ave(%d)\n", size, maxSize/1024, sum/count);
}
else
{
dbg_printf("DecryptBuffer - AllocStack %d max(%d) ave(%d)\n", size, maxSize/1024, sum/count);
m_buf = m_local_buf;
}
}
~DecryptBuffer()
{
if (m_local_buf != m_buf)
{
dbg_printf("DecruptBuffer - FreeHeap\n");
delete [] m_buf;
}
else
{
dbg_printf("DecruptBuffer - FreeStack\n");
}
}
void* GetBufferPtr()
{
return m_buf;
}
private:
char* m_buf;
char m_local_buf[LOCAL_BUF_SIZE];
};
bool CLZObject::Decompress(DWORD * pdwKey)
{
UINT uiSize;
int r;
if (m_pHeader->dwEncryptSize)
{
DecryptBuffer buf(m_pHeader->dwEncryptSize);
BYTE* pbDecryptedBuffer = (BYTE*)buf.GetBufferPtr();
__Decrypt(pdwKey, pbDecryptedBuffer);
if (*(DWORD *) pbDecryptedBuffer != ms_dwFourCC)
{
TraceError("LZObject: key incorrect");
return false;
}
if (LZO_E_OK != (r = lzo1x_decompress(pbDecryptedBuffer + sizeof(DWORD), m_pHeader->dwCompressedSize, m_pbBuffer, (lzo_uint*) &uiSize, NULL)))
{
TraceError("LZObject: Decompress failed(decrypt) ret %d\n", r);
return false;
}
}
else
{
uiSize = m_pHeader->dwRealSize;
//if (LZO_E_OK != (r = lzo1x_decompress_safe(m_pbIn, m_pHeader->dwCompressedSize, m_pbBuffer, (lzo_uint*) &uiSize, NULL)))
if (LZO_E_OK != (r = lzo1x_decompress(m_pbIn, m_pHeader->dwCompressedSize, m_pbBuffer, (lzo_uint*) &uiSize, NULL)))
{
TraceError("LZObject: Decompress failed : ret %d, CompressedSize %d\n", r, m_pHeader->dwCompressedSize);
return false;
}
}
if (uiSize != m_pHeader->dwRealSize)
{
TraceError("LZObject: Size differs");
return false;
}
return true;
}
bool CLZObject::Encrypt(DWORD * pdwKey)
{
if (!m_bCompressed)
{
assert(!"not compressed yet");
return false;
}
BYTE * pbBuffer = m_pbBuffer + sizeof(THeader);
m_pHeader->dwEncryptSize = tea_encrypt((DWORD *) pbBuffer, (const DWORD *) pbBuffer, pdwKey, m_pHeader->dwCompressedSize + 19);
return true;
}
bool CLZObject::__Decrypt(DWORD * key, BYTE* data)
{
assert(m_pbBuffer);
tea_decrypt((DWORD *) data, (const DWORD *) (m_pbIn - sizeof(DWORD)), key, m_pHeader->dwEncryptSize);
return true;
}
void CLZObject::AllocBuffer(DWORD dwSrcSize)
{
if (m_pbBuffer && !m_bInBuffer)
gs_freeMemMgr.Free(m_pbBuffer, m_dwBufferSize);
m_pbBuffer = gs_freeMemMgr.Alloc(dwSrcSize);
m_dwBufferSize = dwSrcSize;
}
/*
void CLZObject::CopyBuffer(const char* pbSrc, DWORD dwSrcSize)
{
AllocBuffer(dwSrcSize);
memcpy(m_pbBuffer, pbSrc, dwSrcSize);
}
*/
CLZO::CLZO() : m_pWorkMem(NULL)
{
if (lzo_init() != LZO_E_OK)
{
TraceError("LZO: cannot initialize");
return;
}
#if defined( LZO1X_999_MEM_COMPRESS )
m_pWorkMem = (BYTE *) malloc(LZO1X_999_MEM_COMPRESS);
#else
m_pWorkMem = (BYTE *) malloc(LZO1X_1_MEM_COMPRESS);
#endif
if (NULL == m_pWorkMem)
{
TraceError("LZO: cannot alloc memory");
return;
}
}
CLZO::~CLZO()
{
if (m_pWorkMem)
{
free(m_pWorkMem);
m_pWorkMem = NULL;
}
}
bool CLZO::CompressMemory(CLZObject & rObj, const void * pIn, UINT uiInLen)
{
rObj.BeginCompress(pIn, uiInLen);
return rObj.Compress();
}
bool CLZO::CompressEncryptedMemory(CLZObject & rObj, const void * pIn, UINT uiInLen, DWORD * pdwKey)
{
rObj.BeginCompress(pIn, uiInLen);
if (rObj.Compress())
{
if (rObj.Encrypt(pdwKey))
return true;
return false;
}
return false;
}
bool CLZO::Decompress(CLZObject & rObj, const BYTE * pbBuf, DWORD * pdwKey)
{
if (!rObj.BeginDecompress(pbBuf))
return false;
if (!rObj.Decompress(pdwKey))
return false;
return true;
}
BYTE * CLZO::GetWorkMemory()
{
return m_pWorkMem;
}

74
src/EterBase/lzo.h Normal file
View File

@ -0,0 +1,74 @@
#ifndef __INC_METIN_II_371GNFBQOCJ_LZO_H__
#define __INC_METIN_II_371GNFBQOCJ_LZO_H__
#include <windows.h>
#include <lzo/lzo1x.h>
#include "Singleton.h"
class CLZObject
{
public:
#pragma pack(4)
typedef struct SHeader
{
DWORD dwFourCC;
DWORD dwEncryptSize; // <20><>ȣȭ<C8A3><C8AD> ũ<><C5A9>
DWORD dwCompressedSize; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ũ<><C5A9>
DWORD dwRealSize; // <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ũ<><C5A9>
} THeader;
#pragma pack()
CLZObject();
~CLZObject();
void Clear();
void BeginCompress(const void * pvIn, UINT uiInLen);
void BeginCompressInBuffer(const void * pvIn, UINT uiInLen, void * pvOut);
bool Compress();
bool BeginDecompress(const void * pvIn);
bool Decompress(DWORD * pdwKey = NULL);
bool Encrypt(DWORD * pdwKey);
bool __Decrypt(DWORD * key, BYTE* data);
const THeader & GetHeader() { return *m_pHeader; }
BYTE * GetBuffer() { return m_pbBuffer; }
DWORD GetSize();
void AllocBuffer(DWORD dwSize);
DWORD GetBufferSize() { return m_dwBufferSize; }
//void CopyBuffer(const char* pbSrc, DWORD dwSrcSize);
private:
void Initialize();
BYTE * m_pbBuffer;
DWORD m_dwBufferSize;
THeader * m_pHeader;
const BYTE * m_pbIn;
bool m_bCompressed;
bool m_bInBuffer;
public:
static DWORD ms_dwFourCC;
};
class CLZO : public CSingleton<CLZO>
{
public:
CLZO();
virtual ~CLZO();
bool CompressMemory(CLZObject & rObj, const void * pIn, UINT uiInLen);
bool CompressEncryptedMemory(CLZObject & rObj, const void * pIn, UINT uiInLen, DWORD * pdwKey);
bool Decompress(CLZObject & rObj, const BYTE * pbBuf, DWORD * pdwKey = NULL);
BYTE * GetWorkMemory();
private:
BYTE * m_pWorkMem;
};
#endif

101
src/EterBase/tea.cpp Normal file
View File

@ -0,0 +1,101 @@
/*
* Filename: tea.c
* Description: TEA <20><>ȣȭ <20><><EFBFBD><EFBFBD>
*
* Author: <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> (aka. <20><><EFBFBD><EFBFBD>, Cronan), <20>ۿ<EFBFBD><DBBF><EFBFBD> (aka. myevan, <20><><EFBFBD>ڷ<EFBFBD>)
*/
#include "StdAfx.h"
#include "tea.h"
#include <memory.h>
/*
* TEA Encryption Module Instruction
* Edited by <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> aka. <20><><EFBFBD><EFBFBD>, Cronan
*
* void tea_code(const unsigned long sz, const unsigned long sy, const unsigned long *key, unsigned long *dest)
* void tea_decode(const unsigned long sz, const unsigned long sy, const unsigned long *key, unsigned long *dest)
* 8<><38><EFBFBD><EFBFBD>Ʈ<EFBFBD><C6AE> <20><>ȣ/<2F><>ȣȭ <20>Ҷ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>ȴ<EFBFBD>. key <20><> 16 <20><><EFBFBD><EFBFBD>Ʈ<EFBFBD><C6AE><EFBFBD><EFBFBD> <20>Ѵ<EFBFBD>.
* sz, sy <20><> 8<><38><EFBFBD><EFBFBD>Ʈ<EFBFBD><C6AE> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>Ѵ<EFBFBD>.
*
* int tea_decrypt(unsigned long *dest, const unsigned long *src, const unsigned long *key, int size);
* int tea_encrypt(unsigned long *dest, const unsigned long *src, const unsigned long *key, int size);
* <20>Ѳ<EFBFBD><D1B2><EFBFBD><EFBFBD><EFBFBD> 8 <20><><EFBFBD><EFBFBD>Ʈ <20>̻<EFBFBD><CCBB><EFBFBD> <20><>ȣ/<2F><>ȣȭ <20>Ҷ<EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>Ѵ<EFBFBD>. <20><><EFBFBD><EFBFBD> size <20><>
* 8<><38> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20>ƴϸ<C6B4> 8<><38> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ũ<>⸦ "<22>÷<EFBFBD><C3B7><EFBFBD>" <20><>ȣȭ <20>Ѵ<EFBFBD>.
*
* ex. tea_code(pdwSrc[1], pdwSrc[0], pdwKey, pdwDest);
* tea_decrypt(pdwDest, pdwSrc, pdwKey, nSize);
*/
#define TEA_ROUND 32 // 32 <20><> <20><><EFBFBD><EFBFBD><EFBFBD>ϸ<EFBFBD>, <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>.
#define DELTA 0x9E3779B9 // DELTA <20><> <20>ٲ<EFBFBD><D9B2><EFBFBD> <20><><EFBFBD><EFBFBD>.
void tea_code(const unsigned long sz, const unsigned long sy, const unsigned long *key, unsigned long *dest)
{
register unsigned long y = sy, z = sz, sum = 0;
unsigned long n = TEA_ROUND;
while (n-- > 0)
{
y += ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
sum += DELTA;
z += ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
}
*(dest++) = y;
*dest = z;
}
void tea_decode(const unsigned long sz, const unsigned long sy, const unsigned long *key, unsigned long *dest)
{
#pragma warning(disable:4307)
register unsigned long y = sy, z = sz, sum = DELTA * TEA_ROUND;
#pragma warning(default:4307)
unsigned long n = TEA_ROUND;
while (n-- > 0)
{
z -= ((y << 4 ^ y >> 5) + y) ^ (sum + key[sum >> 11 & 3]);
sum -= DELTA;
y -= ((z << 4 ^ z >> 5) + z) ^ (sum + key[sum & 3]);
}
*(dest++) = y;
*dest = z;
}
int tea_encrypt(unsigned long *dest, const unsigned long *src, const unsigned long * key, int size)
{
int i;
int resize;
if (size % 8 != 0)
{
resize = size + 8 - (size % 8);
memset((char *) src + size, 0, resize - size);
}
else
resize = size;
for (i = 0; i < resize >> 3; i++, dest += 2, src += 2)
tea_code(*(src + 1), *src, key, dest);
return (resize);
}
int tea_decrypt(unsigned long *dest, const unsigned long *src, const unsigned long * key, int size)
{
int i;
int resize;
if (size % 8 != 0)
resize = size + 8 - (size % 8);
else
resize = size;
for (i = 0; i < resize >> 3; i++, dest += 2, src += 2)
tea_decode(*(src + 1), *src, key, dest);
return (resize);
}

19
src/EterBase/tea.h Normal file
View File

@ -0,0 +1,19 @@
#ifdef __cplusplus
extern "C" {
#endif
/* TEA is a 64-bit symmetric block cipher with a 128-bit key, developed
by David J. Wheeler and Roger M. Needham, and described in their
paper at <URL:http://www.cl.cam.ac.uk/ftp/users/djw3/tea.ps>.
This implementation is based on their code in
<URL:http://www.cl.cam.ac.uk/ftp/users/djw3/xtea.ps> */
#define TEA_KEY_LENGTH 16
int tea_encrypt(unsigned long *dest, const unsigned long *src, const unsigned long *key, int size);
int tea_decrypt(unsigned long *dest, const unsigned long *src, const unsigned long *key, int size);
#ifdef __cplusplus
};
#endif

45
src/EterBase/vk.h Normal file
View File

@ -0,0 +1,45 @@
#ifndef __VK_H__
#define __VK_H__
#ifndef VK_0
#define VK_0 0x30
#define VK_1 0x31
#define VK_2 0x32
#define VK_3 0x33
#define VK_4 0x34
#define VK_5 0x35
#define VK_6 0x36
#define VK_7 0x37
#define VK_8 0x38
#define VK_9 0x39
#endif
#ifndef VK_A
#define VK_A 0x41
#define VK_B 0x42
#define VK_C 0x43
#define VK_D 0x44
#define VK_E 0x45
#define VK_F 0x46
#define VK_G 0x47
#define VK_H 0x48
#define VK_I 0x49
#define VK_J 0x4A
#define VK_K 0x4B
#define VK_L 0x4C
#define VK_M 0x4D
#define VK_N 0x4E
#define VK_O 0x4F
#define VK_P 0x50
#define VK_Q 0x51
#define VK_R 0x52
#define VK_S 0x53
#define VK_T 0x54
#define VK_U 0x55
#define VK_V 0x56
#define VK_W 0x57
#define VK_X 0x58
#define VK_Y 0x59
#define VK_Z 0x5A
#endif
#endif