первый

This commit is contained in:
2024-11-01 12:23:13 +05:00
parent 801d9d33fa
commit 0688c46a7e
226 changed files with 162921 additions and 0 deletions

299
lib/WTools.cpp Normal file
View File

@ -0,0 +1,299 @@
//---------------------------------------------------------------------------
//#pragma hdrstop
//#include "stdafx.h"
//---------------------------------------------------------------------------
#include "ShlObj.h"
#include "WTools.h"
#include "stdTools.h"
#include <sstream>
//#include <WinBase.h>
#include <atlbase.h>
//---------------------------------------------------------------------------
int getIntVal(VARIANT *pvarPropVal)
{
if(pvarPropVal->vt==VT_BOOL) return pvarPropVal->boolVal==0 ? 0 : 1; else
if(pvarPropVal->vt==VT_I2) return pvarPropVal->bVal; else
if(pvarPropVal->vt==VT_I4) return pvarPropVal->intVal; else
if(pvarPropVal->vt==VT_R4) return (int)pvarPropVal->fltVal; else
if(pvarPropVal->vt==VT_R8) return (int)pvarPropVal->dblVal; else
if(pvarPropVal->vt==VT_BSTR) return Utility::fromString<int>(getSTDStr(pvarPropVal->bstrVal)); else
return 0;
}
//---------------------------------------------------------------------------
char getCharVal(VARIANT *pvarPropVal)
{
if(pvarPropVal->vt==VT_BOOL) return pvarPropVal->boolVal==0 ? 0 : 1; else
if(pvarPropVal->vt==VT_I2) return pvarPropVal->bVal; else
if(pvarPropVal->vt==VT_I4) return pvarPropVal->intVal; else
if(pvarPropVal->vt==VT_R4) return (int)pvarPropVal->fltVal; else
if(pvarPropVal->vt==VT_R8) return (int)pvarPropVal->dblVal; else
if(pvarPropVal->vt==VT_BSTR)
{
std::string str = getSTDStr(pvarPropVal->bstrVal);
if(str.size()>0) return str[0]; else return 0;
}else
return 0;
}
//---------------------------------------------------------------------------
bool getBoolVal(VARIANT *pvarPropVal)
{
if(pvarPropVal->vt==VT_BOOL) return pvarPropVal->boolVal==0 ? false : true; else
if(pvarPropVal->vt==VT_I2) return pvarPropVal->bVal==0 ? false : true; else
if(pvarPropVal->vt==VT_I4) return pvarPropVal->intVal==0 ? false : true; else
if(pvarPropVal->vt==VT_R4) return pvarPropVal->fltVal==0 ? false : true; else
if(pvarPropVal->vt==VT_R8) return pvarPropVal->dblVal==0 ? false : true; else
if(pvarPropVal->vt==VT_BSTR)
{
std::string str = getSTDStr(pvarPropVal->bstrVal);
if(Utility::lowerCaseENG(str)=="true" || str=="1")
return true; else return false;
}
return false;
}
//---------------------------------------------------------------------------
float getFloatVal(VARIANT *pvarPropVal)
{
if(pvarPropVal->vt==VT_BOOL) return pvarPropVal->boolVal==0 ? 0.0f : 1.0f; else
if(pvarPropVal->vt==VT_I2) return pvarPropVal->bVal; else
if(pvarPropVal->vt==VT_I4) return (float)pvarPropVal->intVal; else
if(pvarPropVal->vt==VT_R4) return pvarPropVal->fltVal; else
if(pvarPropVal->vt==VT_R8) return (float)pvarPropVal->dblVal; else
if(pvarPropVal->vt==VT_BSTR) return Utility::fromString<float>(getSTDStr(pvarPropVal->bstrVal)); else
return 0;
}
//---------------------------------------------------------------------------
double getDoubleVal(VARIANT *pvarPropVal)
{
if(pvarPropVal->vt==VT_BOOL) return pvarPropVal->boolVal==0 ? 0 : 1; else
if(pvarPropVal->vt==VT_I2) return pvarPropVal->bVal; else
if(pvarPropVal->vt==VT_I4) return (double)pvarPropVal->intVal; else
if(pvarPropVal->vt==VT_R4) return pvarPropVal->fltVal; else
if(pvarPropVal->vt==VT_R8) return (double)pvarPropVal->dblVal; else
if(pvarPropVal->vt==VT_BSTR) return Utility::fromString<float>(getSTDStr(pvarPropVal->bstrVal)); else
return 0;
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
std::string getStringVal(VARIANT *pvarPropVal)
{
if(pvarPropVal->vt==VT_BOOL) return Utility::IntToStdStr(pvarPropVal->boolVal==0 ? 0 : 1); else
if(pvarPropVal->vt==VT_I2) return Utility::IntToStdStr(pvarPropVal->bVal); else
if(pvarPropVal->vt==VT_I4) return Utility::IntToStdStr(pvarPropVal->intVal); else
if(pvarPropVal->vt==VT_R4) return Utility::FloatToStdStr(pvarPropVal->fltVal); else
if(pvarPropVal->vt==VT_R8) return Utility::FloatToStdStr(pvarPropVal->dblVal); else
if(pvarPropVal->vt==VT_BSTR) return getSTDStr(pvarPropVal->bstrVal); else
return "";
}
//---------------------------------------------------------------------------
std::wstring getWStringVal(VARIANT *pvarPropVal)
{
std::wstring result;
if (pvarPropVal->vt == VT_BSTR) {
result=getSTDWStr(pvarPropVal->bstrVal);
}
else {
std::string str = getStringVal(pvarPropVal);
result = Utility::StringToWString(str, std::locale(""));
}
return result;
}
//---------------------------------------------------------------------------
//#pragma package(smart_init)
//---------------------------------------------------------------------------
BSTR stdStrToBSTR(const std::string& s)
{
BSTR str=NULL;
#if defined( _ATL )
str=CComBSTR(s.c_str()).Detach();
#endif
return str;
}
//---------------------------------------------------------------------------
BSTR stdWStrToBSTR(const std::wstring& s)
{
BSTR str=NULL;
#if defined( _ATL )
return CComBSTR(s.c_str()).Detach();
#endif
return str;
}
//---------------------------------------------------------------------------
/*std::string from_variant(VARIANT& vt)
{
_bstr_t bs(vt);
return std::string(static_cast<const char*>(bs));
}*/
//---------------------------------------------------------------------------
///<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> Unicode BSTR <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> ANSI <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> std::string
std::string getSTDStr(const BSTR& unicodestr)
{
std::string str="";
char *ansistr;
int lenW = ::SysStringLen(unicodestr);
int lenA = ::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, 0, 0, NULL, NULL);
if (lenA > 0)
{
ansistr = new char[lenA + 1]; // allocate a final null terminator as well
::WideCharToMultiByte(CP_ACP, 0, unicodestr, lenW, ansistr, lenA, NULL, NULL);
ansistr[lenA] = 0; // Set the null terminator yourself
str=ansistr;
delete[] ansistr;
}
return str;
}
//---------------------------------------------------------------------------
std::wstring getSTDWStr(const BSTR& unicodestr)
{
if(unicodestr==NULL) return L"";
return unicodestr;
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> ini <20><><EFBFBD><EFBFBD>
bool IniWriteW(std::wstring filename,std::wstring section,std::wstring key,std::wstring data)
{
std::wstring str= Utility::BeforeWLast(filename,L'\\');
CreateDirectory(str.c_str(), NULL); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
return WritePrivateProfileString(
(LPCWSTR)section.c_str(),
(LPCWSTR)key.c_str(),
(LPCWSTR)data.c_str(),
(LPCWSTR)filename.c_str()
)==TRUE;
}
//---------------------------------------------------------------------------
std::wstring IniReadW(std::wstring filename,std::wstring section,std::wstring key)
{
wchar_t *out = new wchar_t[512];
GetPrivateProfileString(
(LPCWSTR)section.c_str(),
(LPCWSTR)key.c_str(),
NULL,
out,
200,
(LPCWSTR)filename.c_str()
);
return out;
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD> <20> "Application Data" <20><><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::wstring getCommonAppPathW()
{
wchar_t szPath[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath);
return szPath;
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD> <20> "Application Data" <20><><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::string getCommonAppPathA()
{
char szPath[MAX_PATH];
SHGetFolderPathA(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szPath);
return szPath;
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD> <20> "Application Data" <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/*std::wstring getDefaultAppPathW()
{
wchar_t szPath[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_DEFAULT_APPDATA, NULL, 0, szPath);
return szPath;
}*/
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD> <20> "Application Data" <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::wstring getAppDataPathW()
{
wchar_t szPath[MAX_PATH];
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, szPath);
return szPath;
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD> <20> "Application Data" <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::string getAppDataPathA()
{
char szPath[MAX_PATH];
SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, szPath);
return szPath;
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
bool shoot(bool reboot, bool force)
{
/*
OSVERSIONINFO ver;
ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&ver);
if (ver.dwPlatformId == VER_PLATFORM_WIN32_NT) // <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> NT <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> SE_SHUTDOWN_NAME
{
HANDLE hToken;
TOKEN_PRIVILEGES* NewState;
OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES,&hToken);
NewState=(TOKEN_PRIVILEGES*)malloc(sizeof(TOKEN_PRIVILEGES) + sizeof (LUID_AND_ATTRIBUTES));
NewState->PrivilegeCount = 1;
LookupPrivilegeValue(NULL,SE_SHUTDOWN_NAME,&NewState->Privileges[0].Luid);
NewState->Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, NewState, NULL, NULL,NULL);
free(NewState);
CloseHandle(hToken);
}
UINT mode = 0;
if (reboot)
mode += EWX_REBOOT;
else
mode += EWX_POWEROFF;
if (force) mode += EWX_FORCE;
ExitWindowsEx(mode ,0);
*/
return true;
}
//---------------------------------------------------------------------------
std::string getCurrentFilePath()
{
char path[MAX_PATH];
GetModuleFileNameA(NULL, path, 2048);
return path;
/*
char path[MAX_PATH];
HMODULE hm = NULL;
if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR) &localFunc, &hm))
{
int ret = GetLastError();
fprintf(stderr, "GetModuleHandle returned %d\n", ret);
}
GetModuleFileNameA(hm, path, sizeof(path));
*/
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
std::string getFileVersion( std::wstring path )
{
DWORD dwHandle, sz = GetFileVersionInfoSizeW( path.c_str(), & dwHandle );
if ( 0 == sz )
{
return "";
}
std::vector< unsigned char > buf( sz );
if ( !GetFileVersionInfoW( path.c_str(), dwHandle, sz, & buf[ 0 ] ) )
{
return "";
}
VS_FIXEDFILEINFO * pvi;
sz = sizeof( VS_FIXEDFILEINFO );
if ( !VerQueryValueA( & buf[ 0 ], "\\", (LPVOID*)&pvi, (unsigned int*)&sz ) )
{
return "";
}
char ver[ 142 ];
sprintf( ver, "%d.%d.%d.%d"
, pvi->dwProductVersionMS >> 16
, pvi->dwFileVersionMS & 0xFFFF
, pvi->dwFileVersionLS >> 16
, pvi->dwFileVersionLS & 0xFFFF
);
return ver;
}

40
lib/WTools.h Normal file
View File

@ -0,0 +1,40 @@
//---------------------------------------------------------------------------
#ifndef WToolsH
#define WToolsH
//---------------------------------------------------------------------------
//#include "WTools.h"
#include <string>
//---------------------------------------------------------------------------
typedef unsigned int uint4;
//---------------------------------------------------------------------------
//<2F><><EFBFBD> Windows <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
//---------------------------------------------------------------------------
//std::string getHDDSerial(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD>
//void cpuid (int output[4], int functionnumber);
std::string getSTDStr(const BSTR& unicodestr);
std::wstring getSTDWStr(const BSTR& unicodestr);
BSTR stdStrToBSTR(const std::string& s);
BSTR stdWStrToBSTR(const std::wstring& s);
std::wstring getCommonAppPathW(); //<2F><><EFBFBD><EFBFBD> <20> "Application Data"
std::string getCommonAppPathA();
std::wstring getAppDataPathW(); //<2F><><EFBFBD><EFBFBD> <20> "Application Data" <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::string getAppDataPathA(); //<2F><><EFBFBD><EFBFBD> <20> "Application Data" <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::string getCurrentFilePath(); //<2F><><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> DLL
std::string getFileVersion( std::wstring path );
std::wstring IniReadW(std::wstring filename,std::wstring section,std::wstring key);
bool IniWriteW(std::wstring filename,std::wstring section,std::wstring key,std::wstring data);
int getIntVal(VARIANT *pvarPropVal);
char getCharVal(VARIANT *pvarPropVal);
bool getBoolVal(VARIANT *pvarPropVal);
float getFloatVal(VARIANT *pvarPropVal);
double getDoubleVal(VARIANT *pvarPropVal);
std::string getStringVal(VARIANT *pvarPropVal);
std::wstring getWStringVal(VARIANT *pvarPropVal);
bool shoot(bool reboot, bool force); //<<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
//------------------------------------------------------------------------------
#endif

1145
lib/ascii.cpp Normal file

File diff suppressed because it is too large Load Diff

11
lib/ascii.h Normal file
View File

@ -0,0 +1,11 @@
#include <string>
std::wstring fromKAZASCII(const std::string str);
std::string toKAZASCII(const std::wstring str);
//http://www.programva.com/ru/html-kody-tablicy-simvoly-kodirovka/CP866
//http://www.celitel.info/klad/tabsim.htm
std::string fromDOStoASCII(const std::string str); //<2F><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::string fromASCIItoDOS(const std::string str); //<2F><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>

80
lib/crc32.cpp Normal file
View File

@ -0,0 +1,80 @@
/*
* crc32.cpp
*
* Created on: 20.12.2014
* Author: igor
*/
#include <stdio.h>
#include <string>
//#include <sys/param.h>
//#include <sys/systm.h>
static unsigned int crc32_tab[] = {
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
};
unsigned int crc32(const char *buf, size_t size)
{
unsigned int crc = 0xffffffff;
while (size--)
crc = crc32_tab[(crc ^ *buf++) & 0xFF] ^ (crc >> 8);
return crc ^ 0xffffffff;
}
//Чтобы CRC32 ножно было на вход заново подать
unsigned int crc32m(const char *buf, size_t size, unsigned int crc)
{
while (size--)
crc = crc32_tab[(crc ^ *buf++) & 0xFF] ^ (crc >> 8);
return crc;
}
unsigned int crc32s(std::string str)
{
return crc32(str.c_str(),str.size());
}

17
lib/crc32.h Normal file
View File

@ -0,0 +1,17 @@
/*
* crc32.h
*
* Created on: 20.12.2014
* Author: igor
*/
#ifndef CRC32_H_
#define CRC32_H_
#include <string>
unsigned int crc32(const char *buf, size_t size);
unsigned int crc32m(const char *buf, size_t size, unsigned int crc);
unsigned int crc32s(std::string str);
#endif /* CRC32_H_ */

75
lib/crc8.cpp Normal file
View File

@ -0,0 +1,75 @@
/*
* crc8.cpp
*
* Created on: 26.01.2015
* Author: igor
*/
//#include "stdafx.h"
#include <stdio.h>
/*
Name : CRC-8
Poly : 0x31 x^8 + x^5 + x^4 + 1
Init : 0xFF
Revert: false
XorOut: 0x00
Check : 0xF7 ("123456789")
MaxLen: 15 áàéò (127 áèò) - îáíàðóæåíèå îäèíàðíûõ, äâîéíûõ, òðîéíûõ è âñåõ íå÷åòíûõ îøèáîê
*/
const unsigned char Crc8Table[256] = {
0x00, 0x31, 0x62, 0x53, 0xC4, 0xF5, 0xA6, 0x97,
0xB9, 0x88, 0xDB, 0xEA, 0x7D, 0x4C, 0x1F, 0x2E,
0x43, 0x72, 0x21, 0x10, 0x87, 0xB6, 0xE5, 0xD4,
0xFA, 0xCB, 0x98, 0xA9, 0x3E, 0x0F, 0x5C, 0x6D,
0x86, 0xB7, 0xE4, 0xD5, 0x42, 0x73, 0x20, 0x11,
0x3F, 0x0E, 0x5D, 0x6C, 0xFB, 0xCA, 0x99, 0xA8,
0xC5, 0xF4, 0xA7, 0x96, 0x01, 0x30, 0x63, 0x52,
0x7C, 0x4D, 0x1E, 0x2F, 0xB8, 0x89, 0xDA, 0xEB,
0x3D, 0x0C, 0x5F, 0x6E, 0xF9, 0xC8, 0x9B, 0xAA,
0x84, 0xB5, 0xE6, 0xD7, 0x40, 0x71, 0x22, 0x13,
0x7E, 0x4F, 0x1C, 0x2D, 0xBA, 0x8B, 0xD8, 0xE9,
0xC7, 0xF6, 0xA5, 0x94, 0x03, 0x32, 0x61, 0x50,
0xBB, 0x8A, 0xD9, 0xE8, 0x7F, 0x4E, 0x1D, 0x2C,
0x02, 0x33, 0x60, 0x51, 0xC6, 0xF7, 0xA4, 0x95,
0xF8, 0xC9, 0x9A, 0xAB, 0x3C, 0x0D, 0x5E, 0x6F,
0x41, 0x70, 0x23, 0x12, 0x85, 0xB4, 0xE7, 0xD6,
0x7A, 0x4B, 0x18, 0x29, 0xBE, 0x8F, 0xDC, 0xED,
0xC3, 0xF2, 0xA1, 0x90, 0x07, 0x36, 0x65, 0x54,
0x39, 0x08, 0x5B, 0x6A, 0xFD, 0xCC, 0x9F, 0xAE,
0x80, 0xB1, 0xE2, 0xD3, 0x44, 0x75, 0x26, 0x17,
0xFC, 0xCD, 0x9E, 0xAF, 0x38, 0x09, 0x5A, 0x6B,
0x45, 0x74, 0x27, 0x16, 0x81, 0xB0, 0xE3, 0xD2,
0xBF, 0x8E, 0xDD, 0xEC, 0x7B, 0x4A, 0x19, 0x28,
0x06, 0x37, 0x64, 0x55, 0xC2, 0xF3, 0xA0, 0x91,
0x47, 0x76, 0x25, 0x14, 0x83, 0xB2, 0xE1, 0xD0,
0xFE, 0xCF, 0x9C, 0xAD, 0x3A, 0x0B, 0x58, 0x69,
0x04, 0x35, 0x66, 0x57, 0xC0, 0xF1, 0xA2, 0x93,
0xBD, 0x8C, 0xDF, 0xEE, 0x79, 0x48, 0x1B, 0x2A,
0xC1, 0xF0, 0xA3, 0x92, 0x05, 0x34, 0x67, 0x56,
0x78, 0x49, 0x1A, 0x2B, 0xBC, 0x8D, 0xDE, 0xEF,
0x82, 0xB3, 0xE0, 0xD1, 0x46, 0x77, 0x24, 0x15,
0x3B, 0x0A, 0x59, 0x68, 0xFF, 0xCE, 0x9D, 0xAC
};
//unsigned char Crc8(unsigned char *pcBlock, unsigned char len)
unsigned char calcCRC8(unsigned char *data, unsigned int len, unsigned char crc = 0xff)
{
while (len--)
crc = Crc8Table[crc ^ *data++];
return crc;
}
unsigned char calcCRC8(const char *data, unsigned int len, unsigned char crc = 0xff)
{
return calcCRC8((unsigned char *)data, len, crc);
}
unsigned char calcCRC8(unsigned char data, unsigned char crc)
{
return calcCRC8(&data, sizeof(data), crc);
}

15
lib/crc8.h Normal file
View File

@ -0,0 +1,15 @@
/*
* crc8.h
*
* Created on: 26.01.2015
* Author: igor
*/
#ifndef CRC8_H_
#define CRC8_H_
unsigned char calcCRC8(unsigned char *data, unsigned int len, unsigned char crc);
unsigned char calcCRC8(const char *data, unsigned int len, unsigned char crc);
unsigned char calcCRC8(unsigned char data, unsigned char crc);
#endif /* CRC8_H_ */

2
lib/glTools.cpp Normal file
View File

@ -0,0 +1,2 @@
//#include <GL/glew.h>
//#include <GL/glu.h>

1
lib/glTools.h Normal file
View File

@ -0,0 +1 @@
#pragma once

475
lib/inifile.cpp Normal file
View File

@ -0,0 +1,475 @@
/*
* inifile.cpp
*
* Created on: 17 дек. 2014 г.
* Author: ivanov.i
*/
#ifdef _ATL_DLL
#include "stdafx.h"
#endif
#include <list>
#include <string> // std::string, std::stol
#include <iostream>
#include <fstream> // std::ifstream
#include <sstream>
#include "inifile.h"
#include "stdTools.h"
#include "ascii.h" //Зачем коментил потом раскоментил? (раскоментил потому что буква "я" не конвертируется функцией WStringToString)
//******************************************************************************
TIniFile::TIniFile()
{
path="";
first=NULL;
last=NULL;
}
//------------------------------------------------------------------------------
TIniFile::~TIniFile()
{
TIniWStruct* inistrdel;
TIniWStruct* inistr = first;
while (inistr!=NULL)
{
inistrdel=inistr;
inistr=inistr->next;
delete inistrdel;
}
}
//------------------------------------------------------------------------------
bool TIniFile::Load(std::wstring path)
{
return Load(Utility::WStringToString(path, std::locale("")));
}
//------------------------------------------------------------------------------
bool TIniFile::Load(std::string path)
{
this->path = path;
first = NULL;
std::ifstream fin(path.c_str());
if (fin.is_open())
{
std::string str;
std::wstring section;
while (std::getline(fin, str))
{
if (str.find('[') != std::string::npos)
{
section = Utility::convUTF8ToUTF16(Utility::BeforeLast(Utility::AfterFirst(str, '['), ']'));
}
if (str.find('=') != std::string::npos)
{
TIniWStruct* inistr = new TIniWStruct();
inistr->next = NULL;
inistr->section = section;
inistr->ident = Utility::convUTF8ToUTF16(Utility::BeforeFirst(str, '='));
Utility::TrimW(inistr->ident);
inistr->value = Utility::convUTF8ToUTF16(Utility::AfterFirst(str, '='));
Utility::TrimW(inistr->value);
if (first == NULL)
{
first = inistr;
last = inistr;
}
else
{
last->next = inistr;
last = inistr;
}
}
}
fin.close();
}
else
return false;
return true;
}
//------------------------------------------------------------------------------
bool TIniFile::getSection(std::string Section) //Есть ли заданая секция в iti файле
{
TIniWStruct* inistr = first;
while (inistr!=NULL)
{
if (inistr->section==Utility::StringToWString(Section,std::locale("")))
{
return true;
}
inistr=inistr->next;
}
return false;
}
//------------------------------------------------------------------------------^M
//Получить список идентификаторов по секции^M
std::list<std::string> TIniFile::getIdents(std::string Section)
{
std::list<std::string> list;
TIniWStruct* inistr = first;
while (inistr!=NULL)
{
if (inistr->section==Utility::StringToWString(Section,std::locale("")))
{
list.push_back(Utility::WStringToString(inistr->ident, std::locale("")));
}
inistr=inistr->next;
}
return list;
}
//------------------------------------------------------------------------------
std::wstring TIniFile::ReadString(std::wstring Section, std::wstring Ident, std::wstring Default)
{
TIniWStruct* inistr = first;
while (inistr != NULL)
{
if ((inistr->section == Section) && (inistr->ident == Ident))
{
return inistr->value;
}
inistr = inistr->next;
}
return Default;
}
//------------------------------------------------------------------------------
std::string TIniFile::ReadString(std::string Section,std::string Ident,std::string Default)
{
TIniWStruct* inistr = first;
while (inistr!=NULL)
{
if ((inistr->section==Utility::StringToWString(Section, std::locale(""))) && (inistr->ident==Utility::StringToWString(Ident, std::locale(""))))
{
return Utility::WStringToString(inistr->value, std::locale(""));
}
inistr=inistr->next;
}
return Default;
}
//------------------------------------------------------------------------------
long TIniFile::ReadLong(std::string Section,std::string Ident,std::string Default)
{
long result;
std::stringstream ss;
ss << ReadString(Section,Ident,Default);
ss >> result;
return result;
}
//------------------------------------------------------------------------------
long TIniFile::ReadLong(const char* Section, const char* Ident, const char* Default)
{
return ReadLong(std::string(Section), std::string(Ident), std::string(Default));
}
//------------------------------------------------------------------------------
unsigned int TIniFile::ReadUInt(std::string Section,std::string Ident,std::string Default)
{
unsigned int result;
std::stringstream ss;
ss << ReadString(Section,Ident,Default);
ss >> result;
return result;
}
//------------------------------------------------------------------------------
void TIniFile::WriteUInt(std::string Section,std::string Ident,unsigned int Value)
{
std::stringstream ss;
ss << Value;
WriteString(Section,Ident,ss.str());
}
//------------------------------------------------------------------------------
float TIniFile::ReadFloat(std::string Section,std::string Ident,std::string Default)
{
float result;
std::stringstream ss;
ss << ReadString(Section,Ident,Default);
ss >> result;
return result;
}
//------------------------------------------------------------------------------
//Default: "0" или "1"
bool TIniFile::ReadBool(std::string Section,std::string Ident,std::string Default)
{
std::string rez=ReadString(Section,Ident,Default);
if(rez=="1") return true;
if(rez=="0") return false;
return false;
}
//------------------------------------------------------------------------------
void TIniFile::WriteString(std::string Section,std::string Ident,std::string Value)
{
//ищем старое значение в заданной секции
bool b=false;
TIniWStruct* lastSel = NULL;
TIniWStruct* inistr = first;
while (inistr!=NULL)
{
if(inistr->section==Utility::StringToWString(Section, std::locale("")))
{
lastSel=inistr;
if(inistr->ident==Utility::StringToWString(Ident, std::locale("")))
{ inistr->value=Utility::StringToWString(Value, std::locale(""));
b=true;
}
}
inistr=inistr->next;
}
//если не найденно то добавляем новое значение
if (!b)
{
TIniWStruct* inistr= new TIniWStruct;
inistr->next=NULL;
inistr->section= Utility::StringToWString(Section, std::locale(""));
inistr->ident= Utility::StringToWString(Ident, std::locale(""));
inistr->value= Utility::StringToWString(Value, std::locale(""));
if (first==NULL)
{
first=inistr;
last=inistr;
}else
{
if(lastSel==NULL)
{
last->next=inistr;
last=inistr;
}
else
{
if(last==lastSel){
last=inistr;
}
inistr->next=lastSel->next;
lastSel->next=inistr;
}
}
}
}
//------------------------------------------------------------------------------
void TIniFile::WriteString(std::wstring Section, std::wstring Ident, std::wstring Value)
{
//Пробегаемся по структуре и пытаемся заменить старое значение в секции
bool b = false;
TIniWStruct* lastSel = NULL;
TIniWStruct* inistr = first;
while (inistr != NULL)
{
if (inistr->section == Section)
{
lastSel = inistr;
if (inistr->ident == Ident)
{
inistr->value = Value;
b = true;
}
}
inistr = inistr->next;
}
//если не найденно то добавляем новое значение
if (!b)
{
TIniWStruct* inistr = new TIniWStruct;
inistr->next = NULL;
inistr->section = Section;
inistr->ident = Ident;
inistr->value = Value;
if (first == NULL)
{
first = inistr;
last = inistr;
}
else
{
if (lastSel == NULL)
{
last->next = inistr;
last = inistr;
}
else
{
inistr->next = lastSel->next;
lastSel->next = inistr;
}
}
}
}
//------------------------------------------------------------------------------
bool TIniFile::Save()
{
bool result=false;
try
{
FILE *file = fopen(path.c_str(), "w");
if(file)
{
std::wstring LastSection=L"";
TIniWStruct* inistr = first;
while (inistr!=NULL)
{
if (inistr->section!=LastSection)
{
fputs("[",file);
fputs(Utility::convUTF16ToUTF8(inistr->section).c_str(), file);
fputs("]\n",file);
LastSection=inistr->section;
}
fputs(Utility::convUTF16ToUTF8(inistr->ident).c_str(),file);
fputs("=",file);
fputs(Utility::convUTF16ToUTF8(inistr->value).c_str(),file);
fputs("\n",file);
inistr=inistr->next;
}
fclose(file);
result=true;
}
}catch(...)
{}
return result;
}
//------------------------------------------------------------------------------
void TIniFile::WriteLong(std::string Section,std::string Ident,long Value)
{
std::stringstream ss;
ss << Value;
WriteString(Section,Ident,ss.str());
}
//------------------------------------------------------------------------------
void TIniFile::WriteBool(std::string Section, std::string Ident, bool Value)
{
std::string v;
if (Value) v = "1"; else v = "0";
WriteString(Section, Ident, v);
}
//------------------------------------------------------------------------------
// Save binary data by converting it to Base64 beforehand.
void TIniFile::WriteBase64(std::string Section, std::string Ident, char* Value, int Size)
{
std::string base64;
}
//------------------------------------------------------------------------------
void TIniFile::WriteFloat(std::string Section,std::string Ident,float Value)
{
std::stringstream ss;
ss.precision(7); //Поменял с 4 на 6 так как сохраняю широту и долготу
ss << std::fixed << Value;
WriteString(Section,Ident,ss.str());
}
//------------------------------------------------------------------------------
void TIniFile::WriteDouble(std::string Section,std::string Ident,double Value){
std::stringstream ss;
ss.precision(7); //Поменял с 4 на 6 так как сохраняю широту и долготу
ss << std::fixed << Value;
WriteString(Section,Ident,ss.str());
}
//------------------------------------------------------------------------------
JSON::JSON(std::wstring data)
{
first = NULL;
last = NULL;
while (true)
{
//std::cout << data << std::endl;;
Utility::CutBeforeWFirst(data, '"');
std::wstring ident = Utility::CutBeforeWFirst(data, '"');
std::wstring value;
size_t startpos = data.find_first_not_of(L" :\t\f\n\r");
if (startpos != std::string::npos)
{
//Если следующий символ это " то это строка
if (data[startpos] == '"')
{
//Читаем и вырезаем строку
size_t i;
for (i = startpos + 1; i<data.size(); i++)
{
if (data[i] != '"') value += data[i];
else if (data[i - 1] == '\\') value[value.size() - 1] = '"';
else break;
}
data.erase(0, i + 1);
}
else
{
//Читаем и вырезаем циферки
Utility::CutBeforeWFirst(data, ':');
value = Utility::CutBeforeWFirst(data, ',');
Utility::TrimW(value);
}
//std::cout << "(" <<ident << "=" << value << ")" << std::endl;;
if (ident != L"")
{
TIniWStruct* inistr = new TIniWStruct;
inistr->next = NULL;
inistr->section = L"";
inistr->ident = ident;
inistr->value = value;
if (first == NULL)
{
first = inistr;
last = inistr;
}
else
{
last->next = inistr;
last = inistr;
}
}
}
else
{
break;
}
}
}
//------------------------------------------------------------------------------
std::string JSON::ReadAString(std::wstring Ident,std::wstring Default)
{
std::wstring str = ReadString(Ident,Default);
//std::string rez = Utility::WStringToString(str, std::locale("")); //en_US.UTF-8 я не конвертирует поэтому использую самодельную функцию
std::string rez = toKAZASCII(str);
return rez;
}
//------------------------------------------------------------------------------
std::wstring JSON::ReadString(std::wstring Ident,std::wstring Default)
{
TIniWStruct* inistr = first;
while (inistr!=NULL)
{
if (inistr->ident==Ident)
{
return inistr->value;
}
inistr=inistr->next;
}
return Default;
}
//------------------------------------------------------------------------------
long JSON::ReadLong(std::wstring Ident,std::wstring Default)
{
long result;
std::wstringstream ss;
ss << ReadString(Ident,Default);
ss >> result;
return result;
}
//------------------------------------------------------------------------------
char JSON::ReadChar(std::wstring Ident,std::wstring Default)
{
return (char)ReadString(Ident,Default)[0];
}
//------------------------------------------------------------------------------
double JSON::ReadDouble(std::wstring Ident,std::wstring Default)
{
double result;
std::wstringstream ss;
ss << ReadString(Ident,Default);
ss >> result;
return result;
}
//------------------------------------------------------------------------------

87
lib/inifile.h Normal file
View File

@ -0,0 +1,87 @@
/*
* inifile.h
*
* Created on: 17 дек. 2014 г.
* Author: ivanov.i
*/
#ifndef INIFILE_H_
#define INIFILE_H_
#include <list>
#include <string>
//------------------------------------------------------------------------------
//чтение и запись ini файлов
/*struct TIniStruct
{
TIniStruct *next;
std::string section;
std::string ident;
std::string value;
};*/
//------------------------------------------------------------------------------
//чтение и запись ini файлов
struct TIniWStruct
{
TIniWStruct *next;
std::wstring section;
std::wstring ident;
std::wstring value;
};
//------------------------------------------------------------------------------
class TIniFile
{
private:
std::string path; //Полный путь к файлу
TIniWStruct *first;
TIniWStruct *last;
public:
TIniFile();
virtual ~TIniFile();
TIniWStruct* getFirst() { return first; };
bool Load(std::string path);
bool Load(std::wstring path);
bool Save(); //Сортировка и сохранение
bool getSection(std::string Section); //Есть ли заданая секция в iti файле
std::list<std::string> getIdents(std::string Section);
std::wstring ReadString(std::wstring Section, std::wstring Ident, std::wstring Default);
std::string ReadString(std::string Section, std::string Ident, std::string Default);
std::string ReadString(const char* Section, const char* Ident, const char* Default) { return ReadString(std::string(Section), std::string(Ident), std::string(Default)); };
long ReadLong(std::string Section, std::string Ident, std::string Default);
long ReadLong(const char* Section, const char* Ident, const char* Default);
unsigned int ReadUInt(std::string Section, std::string Ident, std::string Default);
unsigned int ReadUInt(const char* Section, const char* Ident, const char* Default) { return ReadUInt(std::string(Section), std::string(Ident), std::string(Default)); };
float ReadFloat(std::string Section, std::string Ident, std::string Default);
bool ReadBool(std::string Section, std::string Ident, std::string Default); //Default: "0" или "1"
void WriteString(std::string Section, std::string Ident, std::string Value);
void WriteString(std::wstring Section, std::wstring Ident, std::wstring Value);
void WriteString(const char* Section, const char* Ident, const char* Value) { WriteString(std::string(Section), std::string(Ident), std::string(Value)); };
void WriteUInt(std::string Section, std::string Ident, unsigned int Value);
void WriteUInt(const char* Section, const char* Ident, unsigned int Value) { WriteUInt(std::string(Section), std::string(Ident), Value); };
void WriteLong(std::string Section, std::string Ident, long Value);
void WriteBool(std::string Section, std::string Ident, bool Value);
void WriteBase64(std::string Section, std::string Ident, char* Value, int size);
void WriteFloat(std::string Section,std::string Ident,float Value);
void WriteDouble(std::string Section,std::string Ident,double Value);
};
//------------------------------------------------------------------------------
//Простой JSON парсер без вложенности
class JSON
{
private:
TIniWStruct *first;
TIniWStruct *last;
public:
JSON(std::wstring data);
std::wstring ReadString(std::wstring Ident,std::wstring Default);
std::string ReadAString(std::wstring Ident,std::wstring Default);
char ReadChar(std::wstring Ident,std::wstring Default);
long ReadLong(std::wstring Ident,std::wstring Default);
double ReadDouble(std::wstring Ident,std::wstring Default);
};
#endif /* INIFILE_H_ */

1021
lib/loader3ds.cpp Normal file

File diff suppressed because it is too large Load Diff

14
lib/loader3ds.h Normal file
View File

@ -0,0 +1,14 @@
//---------------------------------------------------------------------------
#ifndef loader3dsH
#define loader3dsH
#include "object3d.h"
#include "wxTools.h"
#include <wx/zipstrm.h>
bool Load3DS (TTriangles * Triangles, char *filename);
bool Load3DSFromZIP (TTrianglesList *MultyMesh,TFileList *fl);
#endif

160
lib/logger.cpp Normal file
View File

@ -0,0 +1,160 @@
//---------------------------------------------------------------------------
#include "logger.h"
#include "stdTools.h"
#include <cstring>
#include <iomanip>
#include <ctime>
#include <iostream>
#include <sstream>
#include <filesystem>
#include <sys/stat.h>
//---------------------------------------------------------------------------
Logger::Logger(std::string fileName){
this->fileName = fileName;
this->stop = false;
std::string folder = Utility::BeforeLast(fileName,Utility::separator());
if (!Utility::createFolder(folder)) {
std::cerr << "Error create folder: " << folder << std::endl;
}
openLogFile();
logThread = std::thread(&Logger::processQueue, this);
};
//---------------------------------------------------------------------------
Logger::~Logger() {
{
std::unique_lock<std::mutex> lock(queueMutex);
stop = true;
}
queueCondition.notify_all();
logThread.join();
};
//---------------------------------------------------------------------------
//Сервисная функция
std::string Logger::getCurrentDateTime() {
std::time_t now = std::time(nullptr);
std::tm* nowTm = std::localtime(&now);
std::ostringstream timeStream;
timeStream << std::put_time(nowTm, "%Y-%m-%dT%H:%M:%S");
return timeStream.str();
}
//---------------------------------------------------------------------------
void Logger::log(std::string thread, std::string level, std::string data, bool cout)
{
{
std::unique_lock<std::mutex> lock(queueMutex);
LogRec rec;
rec.thread = thread;
rec.level = level;
rec.data = data;
rec.cout = cout;
logQueue.push(rec);
}
queueCondition.notify_one();
}
//---------------------------------------------------------------------------
void Logger::processQueue() {
while (true) {
{
std::unique_lock<std::mutex> lock(queueMutex);
// Ждем до 1 минуты или пока условие не выполнится
queueCondition.wait_for(lock, std::chrono::minutes(1), [this] { return !logQueue.empty() || stop; });
if (stop && logQueue.empty()){
break;
}
if(!logQueue.empty()){
LogRec rec = std::move(logQueue.front());
logQueue.pop();
writeLog(rec.thread,rec.level,rec.data,rec.cout);
}
//Всё что ниже для переименовывания старого файла
if(!std::filesystem::exists(fileName)){
continue;
}
// Получаем время создания файла (st_ctime)
struct stat fileInfo;
if (stat(fileName.c_str(), &fileInfo) != 0) {
std::cerr << "Error getting file info: " << fileName << std::endl;
continue;
}
std::time_t creationTime = fileInfo.st_ctime;
std::tm* creation_tm = std::localtime(&creationTime);
// Получаем текущее время
auto now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::tm* now_tm = std::localtime(&now_c);
//Если даты не совпадают то переименовываю файл в с датой создания и переоткрываю новый файл
if( (now_tm->tm_year != creation_tm->tm_year) ||
(now_tm->tm_mon != creation_tm->tm_mon) ||
(now_tm->tm_mday != creation_tm->tm_mday)){
if(file.is_open()) {
file.close();
}
char buffer[11]; // Длина строки "YYYY-MM-DD" + '\0'
std::memset(buffer, 0, sizeof(buffer));
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d", creation_tm);
std::ostringstream newFileName;
newFileName << Utility::BeforeLast(fileName,'.') << "_" << buffer << "." << Utility::AfterLast(fileName,'.');
std::string newName = newFileName.str();
try {
std::filesystem::rename(fileName, newName);
} catch (const std::filesystem::filesystem_error& e) {
std::cerr << "Error renaming file: " << e.what() << std::endl;
}
//Удаляю старые файлы
std::string folder = Utility::BeforeLast(fileName,Utility::separator());
Utility::deleteOldFiles(folder,10);
}
}
}
}
//---------------------------------------------------------------------------
void Logger::openLogFile() {
file.open(fileName, std::ios::out | std::ios::app);
if (!file.is_open()) {
std::cerr << "Error open file: " << fileName << std::endl;
}
}
//---------------------------------------------------------------------------
void Logger::writeLog(std::string thread, std::string level, std::string data, bool cout)
{
if (!file.is_open()){
openLogFile();
}
//Записываем лог
if (file.is_open())
{
std::stringstream str(std::stringstream::out | std::stringstream::binary);
std::string dateTime = getCurrentDateTime();
thread = Utility::escape_json(thread);
level = Utility::escape_json(level);
data = Utility::escape_json(data);
str << "{\"timestamp\":\"" << dateTime << "\", \"thread\":\"" <<thread<<"\", \"level\":\""<<level<<"\", \"message\":\"" << data <<"\"}" << std::endl;
if (cout)
std::cout << "[" << dateTime << "] " << data << std::endl; //Повтор лога в консоль
file.write(str.str().c_str(), str.str().length());
file.flush();
}
}
//---------------------------------------------------------------------------
//std::string Logger::getCurrentDate() {
// std::time_t now = std::time(nullptr);
// std::tm* nowTm = std::localtime(&now);
// std::ostringstream timeStream;
// timeStream << std::put_time(nowTm, "%Y-%m-%d");
// return timeStream.str();
//}
//---------------------------------------------------------------------------

54
lib/logger.h Normal file
View File

@ -0,0 +1,54 @@
//---------------------------------------------------------------------------
#ifndef logRotateH
#define logRotateH
//---------------------------------------------------------------------------
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <ctime>
#include <sys/time.h>
#include <atomic>
#include <cstdio>
//---------------------------------------------------------------------------
struct LogRec{
std::string thread;
std::string level;
std::string data;
bool cout;
};
//---------------------------------------------------------------------------
class Logger {
private:
std::ofstream file;
std::string fileName;
std::string date;
std::atomic<bool> stop;
std::mutex queueMutex;
std::queue<LogRec> logQueue;
std::condition_variable queueCondition;
std::thread logThread;
void processQueue();
void writeLog(std::string thread, std::string level, std::string data, bool cout);
void rotateLogFile();
void openLogFile();
std::string getCurrentDate();
std::string getCurrentDateTime();
public:
Logger(std::string fileName);
~Logger();
void log(std::string thread, std::string level, std::string data, bool cout=false);
};
//---------------------------------------------------------------------------
#endif

1608
lib/mathTools.cpp Normal file

File diff suppressed because it is too large Load Diff

108
lib/mathTools.h Normal file
View File

@ -0,0 +1,108 @@
//---------------------------------------------------------------------------
#ifndef mathToolsH
#define mathToolsH
//---------------------------------------------------------------------------
#include "structs.h"
//---------------------------------------------------------------------------
#ifndef PI
#define PI 3.1415926535897932384626433832795
#endif
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
//---------------------------------------------------------------------------
typedef unsigned int uint4;
typedef unsigned char uint1;
//---------------------------------------------------------------------------
int hexCharToInt(char input); //Шеснадцатеричный символ в число
bool testBit(const unsigned char *mas,const unsigned char pos); //проверка значения бита
void setBit(unsigned char *mas,const unsigned char pos,bool val);//установить заданный бит в 1 или в 0
uint1 setBitVal(uint1 bit,uint1 pos,bool val); //<Установит знначение бита в заданную позицию
bool getBitVal(uint1 bit,uint1 pos); //<Вернёт значение бита на заданной позиции
long getBaudRate(long s);
int MaxI4(int v1,int v2);
//Побайтное шифрование
void Encrypt(unsigned char* key, unsigned short keylen, unsigned char* data, unsigned short datalen); //Шифровать
void Decrypt(unsigned char* key, unsigned short keylen, unsigned char* data, unsigned short datalen); //Дешифровать
unsigned char CRC8(const char *pcBlock, unsigned char len, unsigned char crc = 0x0); //Простое вычисление CRC (как для GPS)
unsigned short Crc16(unsigned char ch, unsigned short crc = 0xFFFF);
unsigned short Crc16(const char *pcBlock, unsigned short len, unsigned short crc = 0xFFFF);
float sqr(float val);
double sqr(double val);
void CalcNormals(float x0, float y0, float z0, float x1, float y1, float z1, float x2, float y2, float z2, float &xr, float &yr, float &zr);
void fnCalcCircle(RfPointXYZ p1, RfPointXYZ p2, RfPointXYZ p3, float &a, float &b, float &r); //по 3 точкам в пространстве узнать коэфициенты уравнения шара
void NormalInPolar3d(float x, float y, float z, float &AngleH, float &AngleV, float &r); //результат в радианах
void NormalInPolar2d(float x, float y, float &Angle, float &r);
void PolarInNormal3d(double AngleH, double AngleV, double r, float &x, float &y, float &z);
void PolarInNormal3d(double AngleH, double AngleV, double r, double &x, double &y, double &z);
float Max(float val1, float val2);
float Min(float val1, float val2);
RfPointXYZ getMaxPoint(RfPointXYZ point1, RfPointXYZ point2, RfPointXYZ point3);
RfPointXYZ getMinPoint(RfPointXYZ point1, RfPointXYZ point2, RfPointXYZ point3);
double DegToRad(double deg);
double RadToDeg(double deg);
double CorrectAngleRad(double angle);
RfPointXYZ ApproachPoint3d(RfPointXYZ PointXYZ1, RfPointXYZ PointXYZ2, float Distans);
RfPointXYZ setDistancePoint3d(RfPointXYZ PointXYZ1, RfPointXYZ PointXYZ2, float Distans);
float fnGetAngle(RfPointXY CenterPoint, RfPointXY ResearchedPoint);
float fnGetAngleXY(RfPointXYZ CenterPoint, RfPointXYZ ResearchedPoint);
bool Tessellated2d(unsigned int inPos, unsigned int count, RfPointXYZ *PointsXYZ, unsigned int outPos, RsFacesABC *Vector3i);
void TrianglesDeloneXY(unsigned int countP, RfPointXYZ *ListPoint, TSimpleList<RTriangle*>* ListEdge); //триангуляция по делоне
float fnGetDistans2d(RfPointXY PointXY1, RfPointXY PointXY2);
float fnGetDistans(RfPointXYZ p);
float fnGetDistans3d(RfPointXYZ PointXYZ1, RfPointXYZ PointXYZ2);
void Distance(float r, float cx, float cy, float lx1, float ly1, float lx2, float ly2, bool& Coincides, float& x, float& y);
void MovePointOnAngle(float Angle, RfPointXY CenterPointXY, RfPointXY PointXY, RfPointXY & RezPointXY);
RfPointXY ApproachPoint2d(RfPointXY PointXY1, RfPointXY PointXY2, float Distans);
int roundf2(float val);
int RandInt(int a, int b);
bool inBox(RfPointXYZ pMin, RfPointXYZ pMax, RfPointXYZ p);//Находиться ли точка в нутри куба заданного минимальной и максимальной точками
bool inBox(RfPointXYZ pMin, RfPointXYZ pMax, RdPointXYZ p);//Находиться ли точка в нутри куба заданного минимальной и максимальной точками
void CalcPlane(RfPointXYZ P0, RfPointXYZ P1, RfPointXYZ P2, float &a, float &b, float &c, float &d); //уравнение плоскости по 3м точкам
void CalcPlane2(RfPointXYZ v, RfPointXYZ p, float &a, float &b, float &c, float &d); //уравнение плоскости по вектору и точке на плоскости
void CalcPlane2(RdPointXYZ v, RdPointXYZ p, double &a, double &b, double &c, double &d); //уравнение плоскости по вектору и точке на плоскости
//пересичение геометрических фигур
bool CrossingLine(RfPointXY PHead0, RfPointXY PTail0, RfPointXY PHead1, RfPointXY PTail1, RfPointXY & PRez); //Пересичение 2х линий на плоскости
bool CrossingLineXY(RfPointXYZ PHead0, RfPointXYZ PTail0, RfPointXYZ PHead1, RfPointXYZ PTail1, RfPointXYZ & PRez); //Пересичение линий в плоскости XY
bool CrossingLineAndSphere(double r, RdPointXYZ p0, RdPointXYZ p1, RdPointXYZ p2, RdPointXYZ &rp1, RdPointXYZ &rp2); //пересичение сферы и линии
bool CrossingLineAndSphere(float r, RfPointXYZ p0, RfPointXYZ p1, RfPointXYZ p2, RfPointXYZ &rp1, RfPointXYZ &rp2); //пересичение сферы и линии
RfPointXYZ CrossingLineAndPlane(RfPointXYZ p1, RfPointXYZ p2, float a, float b, float c, float d); //пересичении линии и плоскости (линия заданна 2мя точками)
RdPointXYZ CrossingLineAndPlane(RdPointXYZ p1, RdPointXYZ p2, double a, double b, double c, double d); //пересичении линии и плоскости (линия заданна 2мя точками)
RfPointXYZ CrossingPlanes(RfPlaneABCD p1, RfPlaneABCD p2, RfPlaneABCD p3); //точка пересичения 3х плоскостей
//работа с векторами
float ScalarProduct(RfPointXYZ t, RfPointXYZ p); //Умножение векторов
void normalized(RfPointXYZ &p); //В еденичный
void normalized(RdPointXYZ &p); //В еденичный
RfPointXYZ CrossProduct(RfPointXYZ p, RfPointXYZ t);
RdPointXYZ CrossProduct(RdPointXYZ p, RdPointXYZ t);
RfPointXYZ dotProduct(RfPointXYZ p, float t);
float pythagoreanlength(RfPointXYZ p);
//построение геометрических обьектов
void buildIcosahedron(double r, TSimpleList2<RdPointXYZ>* Points, TSimpleList2<RsFacesABC>* Faces); //Икосаэдр
void buildOctahedron(double r, TSimpleList2<RdPointXYZ>* Points, TSimpleList2<RsFacesABC>* Faces); //Октаэдр
//работа с матрицами
void quatnext(float* dest, float* left, float* right); //умножение матриц 4x4
void quatnext(double* dest, double* left, double* right); //умножение матриц 4x4
void quatidentity(float* q); //сделать еденичной матрицу q[16]
void quatidentity(double* q); //сделать еденичной матрицу q[16]
RfPointXYZ MultPointOnRotArray(RfPointXYZ point, double* mas); //умножить точку на матрицу поворота 4x4
RdPointXYZ MultPointOnRotArray(RdPointXYZ point, double* mas);
void TransposeRotMat(double* q); //транспонировать только матрицу вращения
void LookAt(RfPointXYZ vecEye, RfPointXYZ vecTop, double* q);//заполнить матрицу поворота по заданному вектору q[16]
TSimpleList2<RcPointXYZ>* Line3D(signed long int xDis, signed long int yDis, signed long int zDis);
#endif

76
lib/mathTools.~cpp Normal file
View File

@ -0,0 +1,76 @@
//---------------------------------------------------------------------------
//#pragma hdrstop //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
//#include "stdafx.h"
#include "mathTools.h"
//---------------------------------------------------------------------------
int MaxI4(int v1,int v2)
{ if(v1>v2) return v1; else return v2;
}
//---------------------------------------------------------------------------
int MaxI4_2(int v1,int v2)
{ if(v1>v2) return v1; else return v2;
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> (<28><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD>) pos - 0..n
bool testBit(const unsigned char *mas,const unsigned char pos)
{
unsigned char mask=128;
unsigned char loc=pos/8;
mask=mask >> (pos-loc*8);
return (mask & mas[loc])==mask;
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20> 1 <20><><EFBFBD> <20> 0
void setBit(unsigned char *mas,const unsigned char pos,bool val)
{
unsigned char mask=128;
unsigned char loc=pos/8;
mask=mask >> (pos-loc*8);
if(val) mas[loc]=mas[loc] | mask;
else
{
mask=! mask;
mas[loc]=mas[loc] & mask;
}
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
///pos - <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 7..0
uint1 setBitVal(uint1 bit,uint1 pos,bool val)
{
uint1 v=1;
v=0x1<<pos;
if(val)
{
bit=bit | v;
}else
{
v=v ^ 0xFF;
bit=bit & v;
}
return bit;
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
///pos - <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 7..0
bool getBitVal(uint1 bit,uint1 pos)
{
uint1 v=1;
v=v<<pos;
return (bit & v) == v;
}
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
long getBaudRate(long s)
{
if(s==0) return 1200;
if(s==1) return 2400;
if(s==2) return 4800;
if(s==3) return 9600;
if(s==4) return 19200;
if(s==5) return 38400;
if(s==6) return 57600;
if(s==7) return 115200;
return 0;
}
//---------------------------------------------------------------------------

16
lib/mathTools.~h Normal file
View File

@ -0,0 +1,16 @@
//---------------------------------------------------------------------------
#ifndef mathToolsH
#define mathToolsH
//---------------------------------------------------------------------------
typedef unsigned int uint4;
typedef unsigned char uint1;
//---------------------------------------------------------------------------
bool testBit(const unsigned char *mas,const unsigned char pos); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
void setBit(unsigned char *mas,const unsigned char pos,bool val);//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20> 1 <20><><EFBFBD> <20> 0
uint1 setBitVal(uint1 bit,uint1 pos,bool val); //<<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
bool getBitVal(uint1 bit,uint1 pos); //<<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
long getBaudRate(long s);
int MaxI4_2(int v1,int v2);
//------------------------------------------------------------------------------
#endif

362
lib/md5.cpp Normal file
View File

@ -0,0 +1,362 @@
/* MD5
converted to C++ class by Frank Thilo (thilo@unix-ag.org)
for bzflag (http://www.bzflag.org)
based on:
md5.h and md5.c
reference implemantion of RFC 1321
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
/* interface header */
#include "md5.h"
/* system implementation headers */
#include <cstdio>
// Constants for MD5Transform routine.
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
///////////////////////////////////////////////
// F, G, H and I are basic MD5 functions.
inline MD5::uint4 MD5::F(uint4 x, uint4 y, uint4 z) {
return x&y | ~x&z;
}
inline MD5::uint4 MD5::G(uint4 x, uint4 y, uint4 z) {
return x&z | y&~z;
}
inline MD5::uint4 MD5::H(uint4 x, uint4 y, uint4 z) {
return x^y^z;
}
inline MD5::uint4 MD5::I(uint4 x, uint4 y, uint4 z) {
return y ^ (x | ~z);
}
// rotate_left rotates x left n bits.
inline MD5::uint4 MD5::rotate_left(uint4 x, int n) {
return (x << n) | (x >> (32-n));
}
// FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4.
// Rotation is separate from addition to prevent recomputation.
inline void MD5::FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
a = rotate_left(a+ F(b,c,d) + x + ac, s) + b;
}
inline void MD5::GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
a = rotate_left(a + G(b,c,d) + x + ac, s) + b;
}
inline void MD5::HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
a = rotate_left(a + H(b,c,d) + x + ac, s) + b;
}
inline void MD5::II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac) {
a = rotate_left(a + I(b,c,d) + x + ac, s) + b;
}
//////////////////////////////////////////////
// default ctor, just initailize
MD5::MD5()
{
init();
}
//////////////////////////////////////////////
// nifty shortcut ctor, compute MD5 for string and finalize it right away
MD5::MD5(const std::string &text)
{
init();
update(text.c_str(), text.length());
finalize();
}
//////////////////////////////
void MD5::init()
{
finalized=false;
count[0] = 0;
count[1] = 0;
// load magic initialization constants.
state[0] = 0x67452301;
state[1] = 0xefcdab89;
state[2] = 0x98badcfe;
state[3] = 0x10325476;
}
//////////////////////////////
// decodes input (unsigned char) into output (uint4). Assumes len is a multiple of 4.
void MD5::decode(uint4 output[], const uint1 input[], size_type len)
{
for (unsigned int i = 0, j = 0; j < len; i++, j += 4)
output[i] = ((uint4)input[j]) | (((uint4)input[j+1]) << 8) |
(((uint4)input[j+2]) << 16) | (((uint4)input[j+3]) << 24);
}
//////////////////////////////
// encodes input (uint4) into output (unsigned char). Assumes len is
// a multiple of 4.
void MD5::encode(uint1 output[], const uint4 input[], size_type len)
{
for (size_type i = 0, j = 0; j < len; i++, j += 4) {
output[j] = input[i] & 0xff;
output[j+1] = (input[i] >> 8) & 0xff;
output[j+2] = (input[i] >> 16) & 0xff;
output[j+3] = (input[i] >> 24) & 0xff;
}
}
//////////////////////////////
// apply MD5 algo on a block
void MD5::transform(const uint1 block[blocksize])
{
uint4 a = state[0], b = state[1], c = state[2], d = state[3], x[16];
decode (x, block, blocksize);
/* Round 1 */
FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
/* Round 3 */
HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
/* Round 4 */
II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
// Zeroize sensitive information.
memset(x, 0, sizeof x);
}
//////////////////////////////
// MD5 block update operation. Continues an MD5 message-digest
// operation, processing another message block
void MD5::update(const unsigned char input[], size_type length)
{
// compute number of bytes mod 64
size_type index = count[0] / 8 % blocksize;
// Update number of bits
if ((count[0] += (length << 3)) < (length << 3))
count[1]++;
count[1] += (length >> 29);
// number of bytes we need to fill in buffer
size_type firstpart = 64 - index;
size_type i;
// transform as many times as possible.
if (length >= firstpart)
{
// fill buffer first, transform
memcpy(&buffer[index], input, firstpart);
transform(buffer);
// transform chunks of blocksize (64 bytes)
for (i = firstpart; i + blocksize <= length; i += blocksize)
transform(&input[i]);
index = 0;
}
else
i = 0;
// buffer remaining input
memcpy(&buffer[index], &input[i], length-i);
}
//////////////////////////////
// for convenience provide a verson with signed char
void MD5::update(const char input[], size_type length)
{
update((const unsigned char*)input, length);
}
//////////////////////////////
// MD5 finalization. Ends an MD5 message-digest operation, writing the
// the message digest and zeroizing the context.
MD5& MD5::finalize()
{
static unsigned char padding[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
if (!finalized) {
// Save number of bits
unsigned char bits[8];
encode(bits, count, 8);
// pad out to 56 mod 64.
size_type index = count[0] / 8 % 64;
size_type padLen = (index < 56) ? (56 - index) : (120 - index);
update(padding, padLen);
// Append length (before padding)
update(bits, 8);
// Store state in digest
encode(digest, state, 16);
// Zeroize sensitive information.
memset(buffer, 0, sizeof buffer);
memset(count, 0, sizeof count);
finalized=true;
}
return *this;
}
//////////////////////////////
// return hex representation of digest as string
std::string MD5::hexdigest() const
{
if (!finalized)
return "";
char buf[33];
for (int i=0; i<16; i++)
sprintf(buf+i*2, "%02x", digest[i]);
buf[32]=0;
return std::string(buf);
}
//////////////////////////////
/*std::ostream& operator<<(std::ostream& out, MD5 md5)
{
return out << md5.hexdigest();
}*/
//////////////////////////////
std::string md5(const std::string str)
{
MD5 md5 = MD5(str);
return md5.hexdigest();
}

93
lib/md5.h Normal file
View File

@ -0,0 +1,93 @@
/* MD5
converted to C++ class by Frank Thilo (thilo@unix-ag.org)
for bzflag (http://www.bzflag.org)
based on:
md5.h and md5.c
reference implementation of RFC 1321
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
#ifndef BZF_MD5_H
#define BZF_MD5_H
#include <cstring>
#include <iostream>
// a small class for calculating MD5 hashes of strings or byte arrays
// it is not meant to be fast or secure
//
// usage: 1) feed it blocks of uchars with update()
// 2) finalize()
// 3) get hexdigest() string
// or
// MD5(std::string).hexdigest()
//
// assumes that char is 8 bit and int is 32 bit
class MD5
{
public:
typedef unsigned int size_type; // must be 32bit
MD5();
MD5(const std::string& text);
void update(const unsigned char *buf, size_type length);
void update(const char *buf, size_type length);
MD5& finalize();
std::string hexdigest() const;
//friend std::ostream& operator<<(std::ostream&, MD5 md5);
private:
void init();
typedef unsigned char uint1; // 8bit
typedef unsigned int uint4; // 32bit
enum {blocksize = 64}; // VC6 won't eat a const static int here
void transform(const uint1 block[blocksize]);
static void decode(uint4 output[], const uint1 input[], size_type len);
static void encode(uint1 output[], const uint4 input[], size_type len);
bool finalized;
uint1 buffer[blocksize]; // bytes that didn't fit in last 64 byte chunk
uint4 count[2]; // 64bit counter for number of bits (lo, hi)
uint4 state[4]; // digest so far
uint1 digest[16]; // the result
// low level logic operations
static inline uint4 F(uint4 x, uint4 y, uint4 z);
static inline uint4 G(uint4 x, uint4 y, uint4 z);
static inline uint4 H(uint4 x, uint4 y, uint4 z);
static inline uint4 I(uint4 x, uint4 y, uint4 z);
static inline uint4 rotate_left(uint4 x, int n);
static inline void FF(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
static inline void GG(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
static inline void HH(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
static inline void II(uint4 &a, uint4 b, uint4 c, uint4 d, uint4 x, uint4 s, uint4 ac);
};
std::string md5(const std::string str);
#endif

35
lib/mem.cpp Normal file
View File

@ -0,0 +1,35 @@
/*
============================================================================
Name : mem.cpp
Author : irigm@mail.ru
Version :
Copyright : Your copyright notice
Description : Для работы с паматью и со строками в памяти
============================================================================
*/
//------------------------------------------------------------------------------
//Копировать первую строку во вторую
void strcat2( char * destptr, const char * srcptr )
{
int pos1=strLen2(destptr); //Позиция 0ля первой строки
int pos2=strLen2(srcptr); //Позиция 0ля втрой строки
for(int i=0;i<pos2;i++)
{
destptr[pos1+i]=srcptr[i];
}
}
//------------------------------------------------------------------------------
//Длина строки до 0ля
int strLen2(char * str)
{
int result=0;
for(int i=0;i<255;i++) //Позиция 0ля первой строки
{
if(str[i]==0){
result=i;
break;
}
}
return result;
}

3
lib/mem.hpp Normal file
View File

@ -0,0 +1,3 @@
void strcat2( char * destptr, const char * srcptr ); //Копировать первую строку во вторую
int strLen2(char * str); //Длина строки до 0ля

20
lib/mstream.cpp Normal file
View File

@ -0,0 +1,20 @@
/*
* mstream.cpp
*
* Created on: 10 дек. 2014 г.
* Author: ivanov.i
*/
#include "mstream.hpp"
namespace tls
{
/*
unsigned char MStream::readUInt1()
{
unsigned char result=m_data[m_pos];
m_pos++;
return result;
}
*/
}

241
lib/mstream.hpp Normal file
View File

@ -0,0 +1,241 @@
#ifndef MSTREAM_HPP_
#define MSTREAM_HPP_
#include <stddef.h>
#include <string>
namespace tls
{
//------------------------------------------------------------------------------
//To avoid writing the cursor position in the array at each step
class MStream
{
private:
char* m_data;
unsigned short m_pos;
bool m_owner;
public:
MStream(){ m_data=NULL; m_pos=0; m_owner=false;};
MStream(char* data, unsigned short pos, bool owner){ m_data=data; m_pos=pos; m_owner=owner; };
MStream(unsigned char* data, unsigned short pos, bool owner){ m_data=(char*)data; m_pos=pos; m_owner=owner; };
~MStream(){ if(m_owner) delete m_data; };
unsigned short getPos(){ return m_pos; };
void setPos(unsigned short pos){ m_pos = pos; };
char* getData(){ return m_data; };
void setData(char* data){ m_data = data; };
void setOwner(bool val){m_owner=val;};
bool getOwner(bool val){ return m_owner;};
bool write(char val){ *((char*)&m_data[m_pos]) = val; m_pos+=1; return true; };
bool write(signed char val){ *((signed char*)&m_data[m_pos]) = val; m_pos+=1; return true; };
bool write(unsigned char val){ *((unsigned char*)&m_data[m_pos]) = val; m_pos+=1; return true; };
bool write(signed short int val){ *((signed short int*)&m_data[m_pos]) = val; m_pos+=2; return true; };
bool write(unsigned short val){ *((unsigned short*)&m_data[m_pos]) = val; m_pos+=2; return true; };
bool write(signed int val){ *((signed int*)&m_data[m_pos]) = val; m_pos+=4; return true; };
bool write(unsigned int val){ *((unsigned int*)&m_data[m_pos]) = val; m_pos+=4; return true; };
//Не С++ стиль а "big endian"
bool writeR(char val){ *((char*)&m_data[m_pos]) = val; m_pos+=1; return true; };
bool writeR(signed char val){ *((signed char*)&m_data[m_pos]) = val; m_pos+=1; return true; };
bool writeR(unsigned char val){ *((unsigned char*)&m_data[m_pos]) = val; m_pos+=1; return true; };
bool writeR(signed short int val){
m_data[m_pos] = ((char*)&val)[0];
m_data[m_pos+1] = ((char*)&val)[1];
m_pos+=2;
return true;
};
bool writeR(unsigned short val){
m_data[m_pos] = ((char*)&val)[1];
m_data[m_pos+1] = ((char*)&val)[0];
m_pos+=2;
return true;
};
bool writeR(signed int val)
{
m_data[m_pos] = ((char*)&val)[3];
m_pos++;
m_data[m_pos] = ((char*)&val)[2];
m_pos++;
m_data[m_pos] = ((char*)&val)[1];
m_pos++;
m_data[m_pos] = ((char*)&val)[0];
m_pos++;
return true;
};
bool writeR(unsigned int val)
{
m_data[m_pos] = ((char*)&val)[3];
m_pos++;
m_data[m_pos] = ((char*)&val)[2];
m_pos++;
m_data[m_pos] = ((char*)&val)[1];
m_pos++;
m_data[m_pos] = ((char*)&val)[0];
m_pos++;
return true;
};
bool write(char* val, int len){ for(int i=0;i<len;i++) { m_data[m_pos+i]=val[i];} m_pos+=len; return true; };
bool write(const char* val, int len){ return write((char*)val,len); };
bool write(std::string str){ return write((char*)str.c_str(),str.length()); };
bool writeStrZZ(char* val){ int pos=0; while(true){ m_data[m_pos+pos]=val[pos]; if(val[pos]==0) break; pos++; } m_pos+=pos; return true; }; //Переписать строку с ноликом на конце
bool writeStrZ(char* val){ int pos=0; while(true){ if(val[pos]==0) break; m_data[m_pos+pos]=val[pos]; pos++; } m_pos+=pos; return true; }; //Переписать строку без нолика на конце
bool writeStr2r(std::string str) //Первых 2 байта под длину
{
if(str.length()>=65535) return false;
unsigned short size=str.length();
m_data[m_pos] = ((uint8_t*)&size)[1];
m_pos++;
m_data[m_pos] = ((uint8_t*)&size)[0];
m_pos++;
write(str.c_str(),str.length());
return true;
}//Для MQTT протокола (2 первых байта длина строки)
std::string readStr2r() //Первых 2 байта под длину (Для MQTT протокола)
{
std::string result;
unsigned short len;
((uint8_t*)&len)[1] = m_data[m_pos];
m_pos++;
((uint8_t*)&len)[0] = m_data[m_pos];
m_pos++;
result.append((char *)&m_data[m_pos], len);
m_pos+=len;
return result;
}
unsigned char readUInt1()
{
unsigned char result=m_data[m_pos];
m_pos++;
return result;
};
char readInt1(){ char result=m_data[m_pos]; m_pos+=1; return result; };
unsigned short readUInt2() { unsigned short result=*((unsigned short*)&m_data[m_pos]); m_pos+=2; return result; };
short readInt2() { short result=*((short*)&m_data[m_pos]); m_pos+=2; return result; };
short readInt2R() //Байты в обратном порядке
{
short result;
result = *((unsigned char*)&m_data[m_pos]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+1]);
m_pos+=2;
return result;
};
unsigned short readUInt2R() //Байты в обратном порядке (big endian)
{
unsigned short result;
result = *((unsigned char*)&m_data[m_pos]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+1]);
m_pos+=2;
return result;
};
unsigned int readUInt3() //Читаем 3 байта
{
unsigned int result = 0;
((unsigned char*)&result)[0] = m_data[m_pos];
((unsigned char*)&result)[1] = m_data[m_pos+1];
((unsigned char*)&result)[2] = m_data[m_pos+2];
m_pos+=3;
return result;
}
unsigned int readUInt3R() //Читаем 3 байта
{
unsigned int result = 0;
((unsigned char*)&result)[0] = m_data[m_pos+2];
((unsigned char*)&result)[1] = m_data[m_pos+1];
((unsigned char*)&result)[2] = m_data[m_pos];
m_pos+=3;
return result;
}
unsigned int readUInt4() { unsigned int result=*((unsigned int*)&m_data[m_pos]); m_pos+=4; return result; };
unsigned int readUInt4R() // Байты в обратном порядке
{
unsigned int result;
result = *((unsigned char*)&m_data[m_pos]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+1]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+2]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+3]);
m_pos+=4;
return result;
};
int readInt4() { int result=*((int*)&m_data[m_pos]); m_pos+=4; return result; };
unsigned long long readUInt7()
{
char buf[8]={0,0,0,0,0,0,0,0};
for(int ch=0;ch<7;ch++)
buf[ch]=m_data[m_pos+ch];
unsigned long long result=*((unsigned long long*)buf);
m_pos+=7;
return result;
};
unsigned long long readUInt7R() //014135835392AB = 353173069075115
{
char buf[8]={0,0,0,0,0,0,0,0};
for(int ch=0;ch<7;ch++)
{
buf[ch]=m_data[m_pos+6-ch];
}
unsigned long long result=*((unsigned long long*)buf);
m_pos+=7;
return result;
};
unsigned long long readUInt8() { unsigned long long result=*((unsigned long long*)&m_data[m_pos]); m_pos+=8; return result; };
unsigned long long readUInt8R()
{
unsigned long long result;
result = *((unsigned char*)&m_data[m_pos]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+1]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+2]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+3]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+4]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+5]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+6]);
result = result << 8;
result = result | *((unsigned char*)&m_data[m_pos+7]);
m_pos+=8;
return result;
};
bool Read(void* val, int len)
{
for(int i=0;i<len;i++)
{
((char*)val)[i]=m_data[m_pos];
m_pos+=1;
}
return true;
};
std::string readString(int len){
std::string result;
if(len>0)
{
result.assign(&m_data[m_pos], len);
m_pos+=len;
}
return result;
}
};
}
#endif //MSTREAM_HPP_

579
lib/object3d.cpp Normal file
View File

@ -0,0 +1,579 @@
//#pragma hdrstop
#include <GL/glew.h> //Должен стоять до "wx/gl...h"
#include <GL/glu.h>
#include <wx/glcanvas.h>
#include <wx/string.h>
#include "object3d.h"
#include "texture.h"
#include "mathTools.h"
//#include "tools/debug.h"
//---------------------------------------------------------------------------
TTriMat::TTriMat()
{
textureid=0;
ColorAmbientRGB.r=0.2f; // 0.2 по умолчанию в OpenGL
ColorAmbientRGB.g=0.2f;
ColorAmbientRGB.b=0.2f;
ColorAmbientRGB.a=1.0f;
ColorDiffuseRGB.r=0.8f; // 0.8 по умолчанию в OpenGL
ColorDiffuseRGB.g=0.8f;
ColorDiffuseRGB.b=0.8f;
ColorDiffuseRGB.a=1.0f;
ColorSpecularRGB.r=0.0f; // 0.0 по умолчанию в OpenGL
ColorSpecularRGB.g=0.0f;
ColorSpecularRGB.b=0.0f;
ColorSpecularRGB.a=1.0f;
USCALE=1.0f;
VSCALE=1.0f;
}
//---------------------------------------------------------------------------
void TTriMat::Release()
{
//прозрачность
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (float*)&ColorAmbientRGB);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, (float*)&ColorDiffuseRGB);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, (float*)&ColorSpecularRGB);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100.0f); //яркость источника цвета от 0 до 128
//если текстурированна
if(textureid!=0)
{
glBindTexture(GL_TEXTURE_2D, textureid);
glEnable(GL_TEXTURE_2D);
//чтобы цвет не воздействовал на текстуру если она есть
glEnable(GL_COLOR_MATERIAL);
glColor4f(1,1,1,ColorDiffuseRGB.a);
glDisable(GL_COLOR_MATERIAL);
} else glDisable(GL_TEXTURE_2D);
}
//---------------------------------------------------------------------------
TTriangles::TTriangles()
{
del=false;
bSmooth=false;
CountVertex=0;
CountFaces=0;
//countMapPoint=0;
Vertices=NULL;
SmoothNormals=NULL;
faces=NULL;
TexVertices=NULL;
SmoothG=NULL;
bInit=false;
//разбивка по материалам
countMF=0;
MatFaces=NULL;
//материал (после разбивки)
TriMat=NULL;
}
//------------------------------------------------------------------------------
TTriangles::~TTriangles()
{
if (Vertices!=NULL) delete[] Vertices;
Vertices=NULL;
if (SmoothNormals!=NULL) delete[] SmoothNormals;
SmoothNormals=NULL;
if (faces!=NULL) delete[] faces;
faces=NULL;
if (TexVertices!=NULL) delete[] TexVertices;
TexVertices=NULL;
if (SmoothG!=NULL) delete[] SmoothG;
SmoothG=NULL;
if (bInit)
{
glDeleteBuffersARB(1,&vbov);
glDeleteBuffersARB(1,&vbot);
glDeleteBuffersARB(1,&vbon);
glDeleteBuffersARB(1,&vbof);
}
for(unsigned int i=0;i<countMF;i++)
{
delete[] MatFaces[i].name;
delete[] MatFaces[i].faces;
}
if(MatFaces!=NULL) delete[] MatFaces;
MatFaces=NULL;
}
//------------------------------------------------------------------------------
//TODO предусмотреть загрузку в видео память как 1го объекта так и группы (если группой то здесь сохраняется указатель и смещение к нужному объекту)
void TTriangles::render()
{
if(TexVertices==NULL) TexVertices = new RfPointXY[CountVertex];
//if(Material!=NULL) Material.Release();
if(!bSmooth) glShadeModel(GL_FLAT); else glShadeModel(GL_SMOOTH);
//передаём указатели на массивы и рендерим
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
/*RdPointXYZ *d=new RdPointXYZ[CountVertex];
for(unsigned int i=0;i<CountVertex;i++)
{
d[i].x=Vertices[i].x;
d[i].y=Vertices[i].y;
d[i].z=Vertices[i].z;
}
glVertexPointer(3,GL_DOUBLE,0,&d[0]);*/
glVertexPointer(3,GL_FLOAT,0,&Vertices[0]);
glNormalPointer(GL_FLOAT, 0, &SmoothNormals[0]);
glTexCoordPointer(2,GL_FLOAT, 0, &TexVertices[0]);
glDrawElements(GL_TRIANGLES, CountFaces*3, GL_UNSIGNED_SHORT, &faces[0]);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
//delete[] d;
/**/
/*if (!bInit)
{
//огромные переделки:
//однотипные обьекты должны храниться в одном vbov значит рендеринг должен быть преобразован в другой вид а именно
//с начала идет цикл по всем созданным VBO он биндиться потом цикл по моделям(смещениям) в этом VBO здесь применяеться механизм отсечения потом
//потом применяеться подходящяя текстура потом собственно glDrawElements
glGenBuffersARB(1,&vbov);
glBindBufferARB( GL_ARRAY_BUFFER_ARB, vbov );
glBufferDataARB( GL_ARRAY_BUFFER_ARB, VertexCount*sizeof(RfPointXYZ), &fPointXYZ[0], GL_STATIC_DRAW_ARB);
glGenBuffersARB(1,&vbot);
glBindBufferARB( GL_ARRAY_BUFFER_ARB, vbot );
glBufferDataARB( GL_ARRAY_BUFFER_ARB, VertexCount*sizeof(RfPointXY), &fMapPointXY[0], GL_STATIC_DRAW_ARB );
glGenBuffersARB(1,&vbon);
glBindBufferARB( GL_ARRAY_BUFFER_ARB, vbon );
glBufferDataARB( GL_ARRAY_BUFFER_ARB, VertexCount*sizeof(RfPointXYZ), &fNormalXYZ[0], GL_STATIC_DRAW_ARB );
glGenBuffersARB(1,&vbof);
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, vbof);
glBufferDataARB(GL_ELEMENT_ARRAY_BUFFER_ARB, p_object->faces*sizeof(RsFacesABC), &face[0], GL_STATIC_DRAW_ARB);
bInit=true;
}
// vbov,vbon,vbot,vbof :TGLuint; //вершины,нормали,текстура,рёбра
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState( GL_NORMAL_ARRAY );
glEnableClientState( GL_TEXTURE_COORD_ARRAY );
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbov);
glVertexPointer( 3, GL_FLOAT, 0, (char *) NULL );
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbot);
glTexCoordPointer( 2, GL_FLOAT, 0, (char *) NULL );
glBindBufferARB(GL_ARRAY_BUFFER_ARB, vbon);
glNormalPointer( GL_FLOAT, 0, (char *) NULL );
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB, vbof);
glDrawElements(GL_TRIANGLES, p_object->faces*3 ,GL_UNSIGNED_SHORT, NULL);
//биндим нулевой буфер
glBindBufferARB(GL_ARRAY_BUFFER_ARB,0);
glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB,0);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
/**/
}
//------------------------------------------------------------------------------
void TTriangles::CalcMinMaxPoint()
{
if(CountVertex>0)
{
MaxPointXYZ.x=Vertices[0].x;
MaxPointXYZ.y=Vertices[0].y;
MaxPointXYZ.z=Vertices[0].z;
MinPointXYZ.x=Vertices[0].x;
MinPointXYZ.y=Vertices[0].y;
MinPointXYZ.z=Vertices[0].z;
}
for(unsigned int i=1;i<CountVertex;i++)
{
if(MaxPointXYZ.x<Vertices[i].x) MaxPointXYZ.x=Vertices[i].x;
if(MaxPointXYZ.y<Vertices[i].y) MaxPointXYZ.y=Vertices[i].y;
if(MaxPointXYZ.z<Vertices[i].z) MaxPointXYZ.z=Vertices[i].z;
if(MinPointXYZ.x>Vertices[i].x) MinPointXYZ.x=Vertices[i].x;
if(MinPointXYZ.y>Vertices[i].y) MinPointXYZ.y=Vertices[i].y;
if(MinPointXYZ.z>Vertices[i].z) MinPointXYZ.z=Vertices[i].z;
}
PointXYZCenter.x=(MinPointXYZ.x+MaxPointXYZ.x)/2.0f;
PointXYZCenter.y=(MinPointXYZ.y+MaxPointXYZ.y)/2.0f;
PointXYZCenter.z=(MinPointXYZ.z+MaxPointXYZ.z)/2.0f;
/* //DOTO есть такие параметры как сдвиг вращения масштаб я здесь учитываю только масштаб и сдвиг
MaxPointXYZ.x=(MaxPointXYZ.x*ScaleXYZ.x)+ShiftXYZ.x;
MaxPointXYZ.y=(MaxPointXYZ.y*ScaleXYZ.y)+ShiftXYZ.y;
MaxPointXYZ.z=(MaxPointXYZ.z*ScaleXYZ.z)+ShiftXYZ.z;
MinPointXYZ.x=(MinPointXYZ.x*ScaleXYZ.x)+ShiftXYZ.x;
MinPointXYZ.y=(MinPointXYZ.y*ScaleXYZ.y)+ShiftXYZ.y;
MinPointXYZ.z=(MinPointXYZ.z*ScaleXYZ.z)+ShiftXYZ.z;
//так как выделяем обьект по попаданию точки в нутырь куба для плоских обьектов немного расширем пространиство
MaxPointXYZ.x=MaxPointXYZ.x+0.001;
MaxPointXYZ.y=MaxPointXYZ.y+0.001;
MaxPointXYZ.z=MaxPointXYZ.z+0.001;
MinPointXYZ.x=MinPointXYZ.x-0.001;
MinPointXYZ.y=MinPointXYZ.y-0.001;
MinPointXYZ.z=MinPointXYZ.z-0.001;*/
}
//------------------------------------------------------------------------------
//просчитать сглаживающие нормали к поверхности
void TTriangles::CalcSmoothNormals()
{
unsigned int j;
if(SmoothNormals==NULL) SmoothNormals=new RfPointXYZ[CountVertex]; //память под нормали к точке
//если отключенно сглаживание то учитываеться только последний вектор к грани
if(!bSmooth)
{
for(j=0;j<CountVertex;j++)
{
SmoothNormals[j].x=0;
SmoothNormals[j].y=0;
SmoothNormals[j].z=0;
}
for(j=0;j<CountFaces;j++)
{
CalcNormals(Vertices[faces[j].a].x,Vertices[faces[j].a].y,Vertices[faces[j].a].z,Vertices[faces[j].b].x,Vertices[faces[j].b].y,Vertices[faces[j].b].z,Vertices[faces[j].c].x,Vertices[faces[j].c].y,Vertices[faces[j].c].z,SmoothNormals[faces[j].c].x,SmoothNormals[faces[j].c].y,SmoothNormals[faces[j].c].z);
}
}else
{
for(j=0;j<CountVertex;j++)
{
SmoothNormals[j].x=0;
SmoothNormals[j].y=0;
SmoothNormals[j].z=0;
}
unsigned int *mas=new unsigned int[CountVertex];
for(j=0;j<CountVertex;j++) mas[j]=0; //для усреднения
//подсчитываем нормали для каждой точки
RfPointXYZ point;
for(j=0;j<CountFaces;j++)
{
CalcNormals(Vertices[faces[j].a].x,Vertices[faces[j].a].y,Vertices[faces[j].a].z,Vertices[faces[j].b].x,Vertices[faces[j].b].y,Vertices[faces[j].b].z,Vertices[faces[j].c].x,Vertices[faces[j].c].y,Vertices[faces[j].c].z,point.x,point.y,point.z);
SmoothNormals[faces[j].a].x=SmoothNormals[faces[j].a].x+point.x;
SmoothNormals[faces[j].a].y=SmoothNormals[faces[j].a].y+point.y;
SmoothNormals[faces[j].a].z=SmoothNormals[faces[j].a].z+point.z;
mas[faces[j].a]++;
SmoothNormals[faces[j].b].x=SmoothNormals[faces[j].b].x+point.x;
SmoothNormals[faces[j].b].y=SmoothNormals[faces[j].b].y+point.y;
SmoothNormals[faces[j].b].z=SmoothNormals[faces[j].b].z+point.z;
mas[faces[j].b]++;
SmoothNormals[faces[j].c].x=SmoothNormals[faces[j].c].x+point.x;
SmoothNormals[faces[j].c].y=SmoothNormals[faces[j].c].y+point.y;
SmoothNormals[faces[j].c].z=SmoothNormals[faces[j].c].z+point.z;
mas[faces[j].c]++;
}
//нормализуем нормали
for(j=0;j<CountVertex;j++)
{
SmoothNormals[j].x=SmoothNormals[j].x/mas[j];
SmoothNormals[j].y=SmoothNormals[j].y/mas[j];
SmoothNormals[j].z=SmoothNormals[j].z/mas[j];
normalized(SmoothNormals[j]); //приведу к еденичной длине
}
delete[] mas;
}
}
//------------------------------------------------------------------------------
void TTriangles::cutOnSmoothGroup()
{
/*if(SmoothG==NULL)
{*/
//груп сглаживания нет то каждая грань имеет единоличные точки
RfPointXYZ *vbuf=new RfPointXYZ[CountFaces*3];
RfPointXY *tbuf=new RfPointXY[CountFaces*3];
unsigned short count=0;
for(unsigned int i=0;i<CountFaces;i++)
{
vbuf[count]=Vertices[faces[i].a];
if(TexVertices!=NULL) tbuf[count]=TexVertices[faces[i].a];
faces[i].a=count; //сохраняем новый номер точки
count++;
vbuf[count]=Vertices[faces[i].b];
if(TexVertices!=NULL) tbuf[count]=TexVertices[faces[i].b];
faces[i].b=count; //сохраняем новый номер точки
count++;
vbuf[count]=Vertices[faces[i].c];
if(TexVertices!=NULL) tbuf[count]=TexVertices[faces[i].c];
faces[i].c=count; //сохраняем новый номер точки
count++;
}
delete[] Vertices;
Vertices=vbuf;
CountVertex=CountFaces*3;
if(TexVertices!=NULL) delete[] TexVertices;
TexVertices=tbuf;
/*}else
{
}*/
CalcSmoothNormals(); //просчитываем сглаживающие нормали к точкам
delete[] SmoothG;
SmoothG=NULL;
}
//------------------------------------------------------------------------------
//добавить материал
//название материала,колво элементов, список фейсов с этим материалом
void TTriangles::AddMaterial(char *name,unsigned short count,unsigned short *faces)
{
RMatFaces *buf=new RMatFaces[countMF+1];
for(unsigned int i=0;i<countMF;i++) buf[i]=MatFaces[i];
buf[countMF].name=name;
buf[countMF].count=count;
buf[countMF].faces=faces;
if(MatFaces!=NULL) delete[] MatFaces;
MatFaces=buf;
countMF++;
}
//******************************************************************************
TTrianglesList::TTrianglesList()
{
count=0;
List=NULL;
countMat=0; //количество материалов
ListMat=NULL; //массив материалов
}
//------------------------------------------------------------------------------
TTrianglesList::~TTrianglesList()
{
for(unsigned int i=0;i<count;i++) delete List[i];
if(List!=NULL) delete[] List;
count=4294967295; //на всяк.
for(unsigned int i=0;i<countMat;i++) delete ListMat[i];
if(ListMat!=NULL) delete[] ListMat;
countMat=4294967295; //на всяк.
}
//------------------------------------------------------------------------------
TTriangles* TTrianglesList::Add()
{
TTriangles **buf = new TTriangles*[count+1];
for(unsigned int i=0;i<count;i++) buf[i]=List[i];
buf[count]=new TTriangles();
if(List!=NULL) delete[] List;
List=buf;
return List[count++];
}
//------------------------------------------------------------------------------
//удалить обьект из массива
void TTrianglesList::DelTri(TTriangles* tri)
{
for(unsigned int i=0;i<count;i++)
{
if(List[i]==tri)
{
TTriangles **buf = new TTriangles*[count-1];
unsigned int pos=0;
for(unsigned int j=0;j<count;j++)
{
if(i!=j){buf[pos]=List[j]; pos++;}
}
delete[] List;
delete tri;
List=buf;
count--;
break;
}
}
}
//------------------------------------------------------------------------------
//добавить новый метериал
TTriMat* TTrianglesList::AddMat()
{
TTriMat **buf = new TTriMat*[countMat+1];
for(unsigned int i=0;i<countMat;i++) buf[i]=ListMat[i];
buf[countMat]=new TTriMat();
if(ListMat!=NULL) delete[] ListMat;
ListMat=buf;
return ListMat[countMat++];
}
//------------------------------------------------------------------------------
void TTrianglesList::render()
{
for(unsigned int i=0;i<count;i++)
{
TTriangles *tri=List[i];
if(tri->TriMat!=NULL) tri->TriMat->Release();
tri->render();
}
}
//------------------------------------------------------------------------------
void TTrianglesList::CalcMinMaxPoint()
{
for(unsigned int i=0;i<count;i++)
{
TTriangles *tri=List[i];
tri->CalcMinMaxPoint();
if(i==0) MinPointXYZ=tri->MinPointXYZ; else
{
if(MinPointXYZ.x>tri->MinPointXYZ.x) MinPointXYZ.x=tri->MinPointXYZ.x;
if(MinPointXYZ.y>tri->MinPointXYZ.y) MinPointXYZ.y=tri->MinPointXYZ.y;
if(MinPointXYZ.z>tri->MinPointXYZ.z) MinPointXYZ.z=tri->MinPointXYZ.z;
}
if(i==0) MaxPointXYZ=tri->MaxPointXYZ; else
{
if(MaxPointXYZ.x<tri->MaxPointXYZ.x) MaxPointXYZ.x=tri->MaxPointXYZ.x;
if(MaxPointXYZ.y<tri->MaxPointXYZ.y) MaxPointXYZ.y=tri->MaxPointXYZ.y;
if(MaxPointXYZ.z<tri->MaxPointXYZ.z) MaxPointXYZ.z=tri->MaxPointXYZ.z;
}
}
CenterPointXYZ.x=(MaxPointXYZ.x+MinPointXYZ.x)/2.0f;
CenterPointXYZ.y=(MaxPointXYZ.y+MinPointXYZ.y)/2.0f;
CenterPointXYZ.z=(MaxPointXYZ.z+MinPointXYZ.z)/2.0f;
}
//------------------------------------------------------------------------------
void TTrianglesList::CalcSmoothNormals()
{
for(unsigned int i=0;i<count;i++)
{
TTriangles *tri=List[i];
tri->CalcSmoothNormals();
}
}
//------------------------------------------------------------------------------
void TTrianglesList::cutOnSmoothGroup()
{
for(unsigned int i=0;i<count;i++)
{
TTriangles *tri=List[i];
tri->cutOnSmoothGroup();
}
}
//------------------------------------------------------------------------------
TTriMat *TTrianglesList::FindMatOnName(char *name)
{
for(unsigned int i=0;i<countMat;i++)
{
if(wxString::FromAscii(ListMat[i]->name).Lower()==wxString::FromAscii(name).Lower()) return ListMat[i];
}
return NULL;
}
//------------------------------------------------------------------------------
//разбить обьект по списку материалов (сколько материалов столшько и объектов будет)
//применять после разбения по группам сглаживания и просчёта нормалей а то на границе между разными материалами не будет сглаживания
void TTrianglesList::cutOnMaterials()
{
for(unsigned int i=0;i<count;i++)
{
TTriangles *tri=List[i];
if(tri->countMF==1)
{
tri->TriMat=FindMatOnName(tri->MatFaces[0].name);
}else
if(tri->countMF>1) //если несколько материалов то размножаем объекты
{
//в списке фейсов для этого материала раздные точки
//составляем список уникальных точек затем копируем их
//память выделяем под самый плохой вариант
unsigned short *buf=new unsigned short[tri->CountVertex*2]; //уникальные номера точек
for(unsigned int j=0;j<tri->countMF;j++)
{
//создаём новый объект и копируем туда точки в соответствии с материалом
unsigned int cnt=0;
for(unsigned int k=0;k<tri->MatFaces[j].count;k++)
{
if(tri->MatFaces[j].faces[k]>=tri->CountFaces)
return;
bool b=false;
for(unsigned int q=0;q<cnt;q++)
if(buf[q]==tri->faces[tri->MatFaces[j].faces[k]].a)
{
b=true;
break;
}
if(!b){buf[cnt]=tri->faces[tri->MatFaces[j].faces[k]].a; cnt++;}
b=false;
for(unsigned int q=0;q<cnt;q++)
if(buf[q]==tri->faces[tri->MatFaces[j].faces[k]].b)
{
b=true;
break;
}
if(!b){buf[cnt]=tri->faces[tri->MatFaces[j].faces[k]].b; cnt++;}
b=false;
for(unsigned int q=0;q<cnt;q++)
if(buf[q]==tri->faces[tri->MatFaces[j].faces[k]].c)
{
b=true;
break;
}
if(!b){buf[cnt]=tri->faces[tri->MatFaces[j].faces[k]].c; cnt++;}
}
//выбрали список точек нужных для нового обьекта теперь копируем
TTriangles* newTri=Add();
newTri->TriMat=FindMatOnName(tri->MatFaces[j].name);
newTri->CountVertex=cnt;
newTri->Vertices=new RfPointXYZ[newTri->CountVertex];
newTri->TexVertices=new RfPointXY[newTri->CountVertex];
newTri->SmoothNormals=new RfPointXYZ[newTri->CountVertex];
newTri->CountFaces=tri->MatFaces[j].count;
newTri->faces=new RsFacesABC[newTri->CountFaces];
for(unsigned int k=0;k<cnt;k++) //копируем точки
{
newTri->Vertices[k]=tri->Vertices[buf[k]];
newTri->TexVertices[k]=tri->TexVertices[buf[k]];
newTri->SmoothNormals[k]=tri->SmoothNormals[buf[k]];
}
for(unsigned int k=0;k<tri->MatFaces[j].count;k++)
{
newTri->faces[k]=tri->faces[tri->MatFaces[j].faces[k]];
//ищем номер точки
bool b=true;
for(unsigned int q=0;q<cnt;q++){ if(newTri->faces[k].a==buf[q]) {newTri->faces[k].a=q; b=false; break;} }
if(b||newTri->faces[k].a>=cnt)
return;
b=true;
for(unsigned int q=0;q<cnt;q++){ if(newTri->faces[k].b==buf[q]) {newTri->faces[k].b=q; b=false; break;} }
if(b||newTri->faces[k].b>=cnt)
return;
b=true;
for(unsigned int q=0;q<cnt;q++){ if(newTri->faces[k].c==buf[q]) {newTri->faces[k].c=q; b=false; break;} }
if(b||newTri->faces[k].c>=cnt)
return;
}
}
tri->del=true;
delete[] buf;
}
}
unsigned int i=0;
while(i<count)
{
TTriangles *tri=List[i];
//tri->CountVertex;
if(tri->del)
DelTri(tri);
else i++;
}
//домножаем текущие координаты материала на USCALE и VSCALE текущего материала
for(unsigned int i=0;i<count;i++)
{
TTriangles *tri=List[i];
if(tri->TriMat!=NULL)
for(unsigned int j=0;j<tri->CountVertex;j++)
{
tri->TexVertices[j].x*=tri->TriMat->USCALE;
tri->TexVertices[j].y*=tri->TriMat->VSCALE;
}
}
}
//------------------------------------------------------------------------------

104
lib/object3d.h Normal file
View File

@ -0,0 +1,104 @@
//------------------------------------------------------------------------------
#ifndef object3dH
#define object3dH
//------------------------------------------------------------------------------
//#include <Classes.hpp>
//#include <Controls.hpp>
//#include <StdCtrls.hpp>
//#include <Forms.hpp>
//#include <GL/glu.h>
//#include "texture.h"
#include "structs.h"
//------------------------------------------------------------------------------
//Материал для фейсов
class TTriMat
{
private:
protected:
public:
char name[20];
char imgpath[20];
unsigned int textureid;
RfColorRGBA ColorAmbientRGB;
RfColorRGBA ColorDiffuseRGB;
RfColorRGBA ColorSpecularRGB;
float USCALE,VSCALE;
TTriMat();
void Release();
};
//------------------------------------------------------------------------------
//для разбивки объекта по материалам
struct RMatFaces
{
char *name; //название материала
unsigned short count; //кол-во
unsigned short *faces; //номера фейсов принадлежащие данному материалу
};
//------------------------------------------------------------------------------
//3d модель из треугольников
class TTriangles
{
private:
protected:
public:
unsigned short countMF;
RMatFaces *MatFaces;
bool del;
RfPointXYZ MinPointXYZ,MaxPointXYZ,PointXYZCenter; //координаты краёв параллелипипида (для отсечения в плоскости XY)
TTriMat* TriMat;
char name[20]; //название обьекта ASCII
bool bInit,bSmooth;
unsigned int vbov,vbon,vbot,vbof; //вершины,нормали,текстура,рёбра
RfPointXYZ *Vertices; //массив точек
RfPointXYZ *SmoothNormals; // Массив сглаживающих нормалей (для каждой точки)
RfPointXY *TexVertices; //координаты текстуры для каждой точки
RsFacesABC *faces; //3х угольник из граней
unsigned int *SmoothG; //массив сглаживающих групп (их всего 32 по количеству бит в беззнаковом int)
unsigned int CountVertex; //количество вершин (и координат текстуры и нормалей)
unsigned int CountFaces; //количество граней
//unsigned int countMapPoint;
TTriangles();//конструктор
virtual ~TTriangles();
void render();
void CalcSmoothNormals(); //просчитать сглаживающие нармали к поверхности
void CalcMinMaxPoint();
void cutOnSmoothGroup(); //добавить(разрезать) точки по номеру сглаживающей группы
//резка обьекта по материалу будет производиться родителем потому что создаються новые обьекты TTriangles
void AddMaterial(char *name,unsigned short wnum,unsigned short *faces); //название материала,колво элементов, список фейсов с этим материалом
};
//------------------------------------------------------------------------------
//набор 3d моделей из 3х угольников
class TTrianglesList
{
private:
protected:
unsigned int count;
TTriangles **List;
unsigned int countMat;
TTriMat **ListMat;
public:
RfPointXYZ MinPointXYZ,MaxPointXYZ,CenterPointXYZ;
TTrianglesList();//конструктор
virtual ~TTrianglesList();
TTriangles* Add();
void DelTri(TTriangles* tri);
TTriMat* AddMat();
void render();
void CalcSmoothNormals();
void CalcMinMaxPoint();
void cutOnSmoothGroup();
void cutOnMaterials(); //разркзать обьект по материалу
TTriMat *FindMatOnName(char *name);
};
//------------------------------------------------------------------------------
#endif

2261
lib/stdTools.cpp Normal file

File diff suppressed because it is too large Load Diff

244
lib/stdTools.h Normal file
View File

@ -0,0 +1,244 @@
//---------------------------------------------------------------------------
#ifndef stdToolsH
#define stdToolsH
//---------------------------------------------------------------------------
#include <cstdint>
#include <string>
#include <cerrno>
#include <stdexcept>
#include <vector>
#include <list>
#if defined(WIN32) || defined(_WINDOWS) || defined(_BORLAND) || defined(__BORLANDC__)
#include <stdint.h>
#else
#include <iconv.h>
#endif
//---------------------------------------------------------------------------
/*class converter
{
public:
converter(const std::string& in_encode, const std::string& out_encode, bool ignore_error = false, size_t buf_size = 1024) : ignore_error_(ignore_error), buf_size_(buf_size)
{
if (buf_size == 0)
{
throw std::runtime_error("buffer size must be greater than zero");
}
iconv_t conv = ::iconv_open(out_encode.c_str(), in_encode.c_str());
if (conv == (iconv_t)-1)
{
if (errno == EINVAL)
throw std::runtime_error("not supported from " + in_encode + " to " + out_encode);
else
throw std::runtime_error("unknown error");
}
iconv_ = conv;
}
~converter()
{
iconv_close(iconv_);
}
void convert(const std::string& input, std::string& output) const
{
// copy the string to a buffer as iconv function requires a non-const char pointer
std::vector<char> in_buf(input.begin(), input.end());
char* src_ptr = &in_buf[0];
size_t src_size = input.size();
std::vector<char> buf(buf_size_);
std::string dst;
while (0 < src_size)
{
char* dst_ptr = &buf[0];
size_t dst_size = buf.size();
size_t res = ::iconv(iconv_, &src_ptr, &src_size, &dst_ptr, &dst_size);
if (res == (size_t)-1)
{
if (errno == E2BIG)
{
// ignore this error
}
else if (ignore_error_)
{
// skip character
++src_ptr;
--src_size;
}
else
{
check_convert_error();
}
}
dst.append(&buf[0], buf.size() - dst_size);
}
dst.swap(output);
}
private:
void check_convert_error() const
{
switch (errno)
{
case EILSEQ:
throw std::runtime_error("invalid multibyte chars");
case EINVAL:
throw std::runtime_error("invalid multibyte chars");
default:
throw std::runtime_error("unknown error");
}
}
iconv_t iconv_;
bool ignore_error_;
const size_t buf_size_;
};*/
//---------------------------------------------------------------------------
//template <typename T>
//std::string toStdStr(T val);
namespace Utility
{
char separator();
std::string escape_json(const std::string& input);
void strcat2( char * destptr, const char * srcptr );
int strLen2(char * str);
std::string sp3();
std::string base64_encode(const std::string &in);
std::string base64_decode(const std::string &in);
bool seekToLEBOM(FILE* fp);
std::wstring readUTF16LEString(FILE* fp);
std::string readString(FILE* fp,char ch);
int readFile(FILE* fp,char* data,int len);
std::string readFileToString(std::string fName);
bool deleteFile(std::string fileName);
bool deleteOldFiles(std::string path,int days);
void getFiles(std::list<std::string>& fileList, std::string directory);
long getFileDateModiff(std::string file);
bool logrotate(std::string fileName, std::string thread, std::string level, std::string data, bool cout=false, int size=10);
bool logrotateW(std::wstring fileName, std::wstring data);
bool logrotateUTF8(std::wstring fileName, std::wstring data);
bool fileExists(std::string name);
bool dirExists(std::string path);
bool createFolder(std::string directory,mode_t mode=0776); //Создать директорию
long getFileSize(std::string filename);
//std::string FloatToStdStr(float val);
std::string UIntToStdStr(unsigned int val);
std::string IntToStdStr(int val); //Вырезает из строки не цифры
std::string FloatToStdStr(double val, int digits = -1,char sep = 0);
std::wstring FloatToStdWStr(double val,int digits = -1);
template <typename T>
std::wstring toStdWStr(T val);
std::wstring IntToStdWStr(int val);
template <typename T>
std::string toStringHex(T val);
std::string toStringHex2(int val);
std::string toHexString(unsigned char* mas,int len);
bool hexStringToArray(std::string val, char* mas);
unsigned int hexStdStrToUInt(std::string& str);
unsigned int hexStringToInt(std::string val, bool ord = true);
uint16_t hexString2ToUint(std::string &str, int pos, bool cut = false);
uint32_t hexString4ToUint(std::string &str, int pos, bool cut = false);
uint64_t hexString6ToUint(std::string &str, int pos, bool cut = false);
template<typename T>
T fromString(const std::string& s);
int StdStrToInt(std::string& str, bool cutInt = false, int def = 0);
int StdStrToUInt(std::string& str, bool cutInt = false);
float StdStrToFloat(std::string& str);
double StdStrToDouble(std::string& str,double defval = 0);
double StdWStrToDouble(std::wstring str, double defval = 0);
template<typename T>
T fromWString(const std::wstring& s);
int StdWStrToInt(const std::wstring& str, bool cutInt = false);
int StdWStrToUInt(const std::wstring& str, bool cutInt = false);
//Конвертация строк
std::string CodeBSD(std::string str); ///<Закодировать число в двоично десятичный формат
std::string CodeBSD(int val,int len = 0); ///<Закодировать число в двоично десятичный формат
int BSDToInt(char chr); //Двоично десятичный символ в int
int BSDToInt(std::string str, size_t start = 0, size_t len = 0); //Двоично десятичную строку в int
std::string DecodeBSD(char chr); //1 символ в BSD число
std::string DecodeBSD(std::string str, size_t start = 0, size_t len = 0); //Раскодироваьт из двоично десятичного формата
std::string lowerCaseENG(std::string str); //Только для англ языка
//std::wstring StringToWString(const std::string& in, const std::locale &loc = std::locale("")); // = std::locale("") //Конвертация из одно байтного в мульти и обратно
std::wstring StringToWString(const std::string& in, const std::locale &loc);
//std::string WStringToString(const std::wstring &s, const std::locale &loc = std::locale(""), char default_char = '?'); // = std::locale("")
std::string WStringToString(const std::wstring &wstr, const std::locale &loc, char default_char = '?'); // = std::locale("")
//std::wstring s2ws(const std::string& s); //В c++ buildere это работало а StringToWString нет
std::string ws2s(const std::wstring& s);
//char * CodeCharSet(char* in, const char* in_set, const char* out_set);
std::string iConvert(const std::string& instr,const char* fromCode,const char* toCode); //Через iconf
std::string convUTF16ToUTF8(const std::wstring& widestring); //Конвертация из UTF16LE в UTF8
std::wstring convUTF8ToUTF16(const std::string& str); //Конвертация из UTF8 в UTF16LE
std::string UnicodeToDOS886(std::wstring str); //Конвертим из Unicode в DOS 866 кодировку
std::wstring DOS886ToUnicode(std::string str); //Конвертим из DOS 866 в Unicode кодировку
void printToPos(std::wstring& line, std::wstring data, char align); //Запись в право, лево, центр строки line
void replaseChars(std::string& str,char oldCh,char newCh); //Заменить 1 символ другим
// std::string replace(std::string text, std::string s, std::string d);
// std::string getExePath();
std::wstring UpperCase(const std::wstring& str); ///<К верхнему регистру строку (долго работает)
std::string BeforeLast(std::string str,char ch);
std::string BeforeFirst(std::string str,const unsigned char ch);
std::string BeforeFirst(std::string str,const char ch);
std::wstring BeforeWLast(std::wstring str,wchar_t ch);
std::wstring BeforeWFirst(std::wstring str,const wchar_t ch);
std::string AfterFirst(std::string str,const char ch);
std::wstring AfterWFirst(std::wstring str,const wchar_t ch);
std::string AfterLast(std::string str,const char ch);
std::string CutAfterFirst(std::string& str,std::string br);
std::string CutAfterLast(std::string& str,const unsigned char ch); //Если не найдёт нужный символ то вернёт всю строку
std::string CutBeforeFirst(std::string& str,const char ch);
std::string CutBeforeFirst(std::string& str,const std::string br);
std::wstring CutBeforeWFirst(std::wstring& str,const wchar_t ch);
std::string replaceStrings(std::string sors,std::string find,std::string repl);
std::wstring replaceStrings(std::wstring sors,std::wstring find,std::wstring repl);
void replaceAll(std::wstring& str, const std::wstring from, const std::wstring to);
void replaceAll(std::string& str, const std::string from, const std::string to);
std::string trim(const std::string & s); //Удалить пробелы в начале и конце строки
void Trim(std::string& s);
void TrimW(std::wstring& s);
void TrimLeft(std::string& s);
void TrimRight(std::string& s);
void TrimWLeft(std::wstring& s);
void TrimWRight(std::wstring& s);
std::string printToPos(std::string str,int pos, std::string txt);
std::vector<std::wstring> split(const std::wstring& str, wchar_t delimiter);
std::string add0(std::string str); //Добавить 0 в начало строоки если 1 символ для даты нужно
std::string getStrDate();
std::wstring getWStrDate();
std::string getDateTime();
unsigned int getTime1(std::string date); //Преобразую строку вида 02-10-18 20:51:40 в unix time
std::string getExePathA(bool add = true); //Путь к DLL либо к EXE
std::wstring getExePathW(bool add = true); //Путь к DLL
std::string getAppPath(); //Путь к дирректории приложений (если линукс то к томайней директории пользователя)
void killProcessByName(const wchar_t *filename);
std::string intToString(int val);
std::string uintToString(unsigned int val);
std::string ullintToString(unsigned long long int val);
}
//------------------------------------------------------------------------------
#endif

BIN
lib/stdTools.obj Normal file

Binary file not shown.

1041
lib/stdTools.~cpp Normal file

File diff suppressed because it is too large Load Diff

111
lib/stdTools.~h Normal file
View File

@ -0,0 +1,111 @@
//---------------------------------------------------------------------------
#ifndef stdToolsH
#define stdToolsH
//---------------------------------------------------------------------------
#include <string>
//---------------------------------------------------------------------------
//template <typename T>
//std::string toStdStr(T val);
//std::string FloatToStdStr(float val);
std::string IntToStdStr(int val); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD>
std::string FloatToStdStr(double val,int digits = -1);
template <typename T>
std::wstring toStdWStr(T val);
std::wstring IntToStdWStr(int val);
template <typename T>
std::string toStringHex(T val);
std::string toStringHex2(int val);
template<typename T>
T fromString(const std::string& s);
int StdStrToInt(std::string& str, bool cutInt = false);
int StdStrToUInt(std::string& str, bool cutInt = false);
float StdStrToFloat(std::string& str);
double StdStrToDouble(std::string& str);
template<typename T>
T fromWString(const std::wstring& s);
int StdWStrToInt(const std::wstring& s);
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
std::string CodeBSD(std::string str); ///<<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::string CodeBSD(int val,int len = 0); ///<<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int BSDToInt(char chr); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> int
int BSDToInt(std::string str, size_t start = 0, size_t len = 0); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> int
std::string DecodeBSD(char chr); //1 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> BSD <20><><EFBFBD><EFBFBD><EFBFBD>
std::string DecodeBSD(std::string str, size_t start = 0, size_t len = 0); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::wstring StringToWString(const std::string& in, const std::locale &loc); // = std::locale("rus") //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::string WStringToString(const std::wstring &s, const std::locale &loc, char default_char = '?'); // = std::locale("rus")
std::wstring s2ws(const std::string& s); //<2F> c++ buildere <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> StringToWString <20><><EFBFBD>
std::string ws2s(const std::wstring& s);
std::string convUTF16ToUTF8(const std::wstring& widestring); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> UTF16LE <20> UTF8
std::wstring convUTF8ToUTF16(const std::string& str); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> UTF8 <20> UTF16LE
std::string UnicodeToDOS886(std::wstring str); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> Unicode <20> DOS 866 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::wstring DOS886ToUnicode(std::string str); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> DOS 866 <20> Unicode <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
void replaseChars(std::string& str,char oldCh,char newCh); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 1 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
// std::string replace(std::string text, std::string s, std::string d);
// std::string getExePath();
std::wstring UpperCase(const std::wstring& str); ///<<3C> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> (<28><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)
std::string BeforeLast(std::string str,char ch);
std::wstring BeforeWLast(std::wstring str,wchar_t ch);
std::string BeforeFirst(std::string str,const char ch);
std::wstring BeforeWFirst(std::wstring str,const wchar_t ch);
std::string AfterFirst(std::string str,const char ch);
std::wstring AfterWFirst(std::wstring str,const wchar_t ch);
std::string AfterLast(std::string str,const char ch);
std::string CutBeforeFirst(std::string& str,const char ch);
std::wstring CutBeforeWFirst(std::wstring& str,const wchar_t ch);
std::string replaceStrings(std::string sors,std::string find,std::string repl);
std::wstring replaceStrings(std::wstring sors,std::wstring find,std::wstring repl);
std::string trim(const std::string & s); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::string add0(std::string str); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 0 <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> 1 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
std::string getStrDate();
std::wstring getWStrDate();
std::string getDateTime();
std::string getAppPathA(); //<2F><><EFBFBD><EFBFBD> <20> DLL <20><><EFBFBD><EFBFBD> <20> EXE
std::wstring getAppPathW(); //<2F><><EFBFBD><EFBFBD> <20> DLL
//------------------------------------------------------------------------------
/*struct TIniStructSTD
{
TIniStructSTD *next; //<2F><><EFBFBD><EFBFBD>. <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::wstring section; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::wstring ident; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
std::wstring value; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
};
class TIniFileSTD
{
private:
std::wstring path;
TIniStructSTD *first; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
TIniStructSTD *last;
public:
TIniFileSTD(std::wstring path);
virtual ~TIniFileSTD();
std::string ReadString(std::string Section,std::string Ident,std::string Default);
//float ReadFloat(std::wstring Section,std::wstring Ident,float Default);
//long ReadLong(std::wstring Section,std::wstring Ident,long Default);
//unsigned long ReadULong(std::wstring Section,std::wstring Ident,unsigned long Default);
//bool ReadBool(std::wstring Section,std::wstring Ident,bool Default);
void WriteString(std::string Section,std::string Ident,std::string Value);
//void WriteFloat(std::wstring Section,std::wstring Ident,float Value);
//void WriteLong(std::wstring Section,std::wstring Ident,long Value);
//void WriteULong(std::wstring Section,std::wstring Ident,unsigned long Value);
//void WriteBool(std::wstring Section,std::wstring Ident,bool Value);
void Save(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD>
};*/
//------------------------------------------------------------------------------
#endif

370
lib/structs.h Normal file
View File

@ -0,0 +1,370 @@
#ifndef structsH
#define structsH
//------------------------------------------------------------------------------
#include "stdio.h"
//------------------------------------------------------------------------------
typedef unsigned char uint1;
//------------------------------------------------------------------------------
//цвет с прозрачностью
struct RfColorRGBA
{
float r,g,b,a;
};
//------------------------------------------------------------------------------
//Плоскость (a,b,c,d - коэфициенты уравнения плоскости)
struct RfPlaneABCD
{ float a,b,c,d;
};
//------------------------------------------------------------------------------
//точка в 3d (если в 0,0,0 начало а это конец то можно назвать вектором)
struct RfPointXYZ
{ float x,y,z;
};
//------------------------------------------------------------------------------
//точка в 3d (если в 0,0,0 начало а это конец то можно назвать вектором)
struct RcPointXYZ
{ signed char x,y,z;
};
//------------------------------------------------------------------------------
//точка в 2d
struct RfPointXY
{ float x,y;
};
//------------------------------------------------------------------------------
struct RfPointXYZA
{ RfPointXYZ Point;
float angle;
};
//------------------------------------------------------------------------------
struct RdPointXYZ
{ double x,y,z;
};
//------------------------------------------------------------------------------
struct RdPointXY
{ double x,y;
};
//------------------------------------------------------------------------------
struct RiPointXY
{ signed int x,y;
};
//------------------------------------------------------------------------------
struct RuiPointXY
{ unsigned int x,y;
};
//------------------------------------------------------------------------------
struct RiPointXYZ
{ int x,y,z;
};
//------------------------------------------------------------------------------
//рёбра для трёх угольника
struct RiFacesABC
{ unsigned int a,b,c;
};
//------------------------------------------------------------------------------
//рёбра для трёх угольника 16 бит макс 65535 точек
struct RsFacesABC
{ unsigned short a,b,c;
};
//------------------------------------------------------------------------------
//рёбра для четырёх угольника 16 бит макс 65535 точек
struct RsFacesABCD
{ unsigned short a,b,c,d;
};
//------------------------------------------------------------------------------
//использую при разбиении точек по сглаж группе ребра
struct RbFaceABC
{
bool a,b,c;
};
//------------------------------------------------------------------------------
//вектор (нормаль)
struct TVector
{ float x,y,z;
};
//------------------------------------------------------------------------------
/* struct TGooglePoint
{
int x,y;
//unsigned int mat;
RfPointXYZ p1,p2,p3,p4; //координаты краёв квадрата (север в верху против часовой с левого нижнего угла)
RfPointXYZ pn; //нормаль
RfPointXY pm1,pm2,pm3,pm4; //координаты материала для каждой точки
};*/
//------------------------------------------------------------------------------
//Элемент односвязного списка
struct RListOne
{
RListOne* next; //ссылка на следующий
unsigned size; //размер данных
unsigned char* data; //данные
};
//------------------------------------------------------------------------------
//номер точки и угол для делоне
struct RSotrPoint
{
int n;
float angle;
};
//------------------------------------------------------------------------------
//треугольник для делоне
struct RTriangle
{
bool del;
int pnt[3]; //номера точек из списка для построения рёбер
double cr[3]; //растояния до центральной точки
RfPointXYZ center; //центральная точка круга при преобразовании по Делоне
float r;
//ниже идут переменные ни как не относящиеся к триангуляции Делоне
// centerMAP :RfPointXYZ; //центральная точка по картовым
RfPointXYZ centerGPS; //центральная точка по GPS
};
//------------------------------------------------------------------------------
/*class TCheckData
{
public:
void OnTime();
};*/
//------------------------------------------------------------------------------
//Расширяемый массив элементов, может выступать в качестве родителя те. удалять элементы при уничтожении списка или при удалении элемента из списка
//Если заданна потоко безопасность то все действия помещаются в критическую секцию
template <class T> class TSimpleList
{
private:
T* f_NULL; //Чтобы вернуть NULL если вышел за пределы массива
T* List; //массив элементов
unsigned int f_size;//размер массива (без учёта занятых позиций)
unsigned int f_count;//количество элементов
unsigned int f_step;//шаг увеличения массива
//wxCriticalSection* f_critsect;
public:
bool f_owner; //являеться ли владельцем элементов данный списк
TSimpleList(unsigned int step=10,bool owner=false/*,bool crit*/)
{
if(step==0)step=1;
f_step=step;
List=new T[f_step];
f_size=f_step;
f_count=0;
f_owner=owner;
//if (crit) f_critsect=new wxCriticalSection(); else f_critsect=NULL;
f_NULL=NULL;
};
~TSimpleList()
{
if(f_owner)
for(unsigned int i=0;i<f_count;i++)
delete List[i];
delete[] List;
};
void setSize(unsigned int size) //Заранее задать размер массива
{
if(size>f_size)
{
T* buf=new T[size];
for(unsigned int i=0;i<f_count;i++) buf[i]=List[i];
T* buf0=List; //На всякслучай
List=buf;
f_size=size;
delete buf0;
}
};
unsigned int count()
{
return f_count;
};
//Добавить элемент в конец массива
T add(T item)
{
if(f_count<f_size) List[f_count++]=item;
else
{
T* buf=new T[f_size+=f_step];
for(unsigned int i=0;i<=f_count;i++) buf[i]=List[i];
T* buf0=List;
List=buf;
delete[] buf0;
List[f_count++]=item;
}
return item;
};
T insert(T item,unsigned int pos) //pos - 0..XXX
{
if(pos>=f_count)
{
if(pos<f_size){List[pos]=item; f_count=pos+1;} //в пустую область
else //в не выделенную область
{
T* buf=new T[pos+1];
for(unsigned int i=0;i<=f_count;i++) buf[i]=List[i];
T* buf0=List;
List=buf;
delete[] buf0;
List[pos]=item;
f_count=pos+1;
}
}else//сдвинуть имеющиеся
{
add(List[f_count-1]);
for(unsigned int i=f_count-2;i>pos;i--)
List[i]=List[i-1];
List[pos]=item;
}
return item;
};
void del(T item) //удаляем элемент и сдвигаем все элементы на 1 в лево
{
unsigned int cnt=0;
bool b=false;
for(unsigned int i=0;i<f_count;i++)
{
//if(List[i]==item){cnt--; b=true;}
if(List[i]==item){b=true; continue;}
List[cnt]=List[i];
cnt++;
}
if(b)
{
f_count--;
if(f_owner)delete item;
}
};
bool del(unsigned int pos) //удаляем элемент и сдвигаем все элементы на 1 в лево
{
if(pos>=f_count)return false;
f_count--;
if(f_owner) delete List[pos];
for(unsigned int i=pos;i<f_count;i++) List[i]=List[i+1];
return true;
};
bool rem(unsigned int pos) { //Исключить из списка без попытки удаления
if (pos >= f_count)return false;
f_count--;
//if (f_owner) delete List[pos];
for (unsigned int i = pos; i<f_count; i++) List[i] = List[i + 1];
return true;
}
T& get(unsigned int i)
{ if(i>=f_count) {return (T&)f_NULL;}
return List[i];
};
T& operator[](unsigned int i)
{ if(i>=f_count) {return (T&)f_NULL;}
return List[i];
};
bool Pos(T item,unsigned int &pos) //Узнать позицию элемента в массиве
{
for(unsigned int i=0;i<f_count;i++)
if(List[i]==item) { pos=i; return true; }
return false;
};
//Очистить массив с уменьшением размерности до одного шага увеличения массива (если владелец удалить элементы)
void clear()
{
unsigned int cnt=f_count;
f_count=0;
if(f_owner) for(unsigned int i=0;i<cnt;i++) delete List[i];
T* tmp=List;
f_size=f_step;
List=new T[f_step];
delete[] tmp;
};
};
//------------------------------------------------------------------------------
//простой список не являющийся владельцем своих элементов (можно задавать реальные обьекты а не ссылки)
template <class T> class TSimpleList2
{
private:
T* List; //массив элементов
unsigned int f_size;//размер массива
unsigned int f_count;//количество элементов
unsigned int f_step;//шаг увеличения массива
public:
TSimpleList2() //Для использования конструктора по умолчанию
{
f_step=10;
List=new T[f_step];
f_size=f_step;
f_count=0;
};
TSimpleList2(unsigned int step)
{
if(step==0)step=1;
f_step=step;
List=new T[f_step];
f_size=f_step;
f_count=0;
};
~TSimpleList2()
{
delete[] List;
};
unsigned int count()
{
return f_count;
};
void add(T item)
{
if(f_count<f_size)
{
List[f_count]=item;
f_count++;
}
else
{
T* buf=new T[f_size+=f_step];
for(unsigned int i=0;i<=f_count;i++) buf[i]=List[i];
T* buf0=List;
List=buf;
delete[] buf0;
List[f_count]=item;
f_count++;
}
};
void del(T item) //удаляем элемент и сдвигаем все элементы на 1 в лево
{
unsigned int cnt=0;
bool b=false;
for(unsigned int i=0;i<f_count;i++)
{
//if(List[i]==item){cnt--; b=true;}
if(List[i]==item){b=true; continue;}
List[cnt]=List[i];
cnt++;
}
if(b)
{
f_count--;
}
};
bool del(unsigned int pos) //удаляем элемент и сдвигаем все элементы на 1 в лево
{
if(pos>=f_count)return false;
f_count--;
for(unsigned int i=pos;i<f_count;i++) List[i]=List[i+1];
return true;
};
T& get(unsigned int i){return List[i];};
T& operator[](unsigned int i){return List[i];};
bool Position(T item, unsigned int &pos) //Найти позицию элемента в списке перебором
{
for(unsigned int i=0;i<f_count;i++)
if(List[i]==item) { pos=i; return true; }
return false;
};
void clear()
{
unsigned int cnt=f_count;
f_count=0;
T* tmp=List;
f_size=f_step;
List=new T[f_step];
delete[] tmp;
};
};
//------------------------------------------------------------------------------
#endif

191
lib/strutil.cpp Normal file
View File

@ -0,0 +1,191 @@
////////////////////////////////////////////////////////////////////////////////
// @(#) strutil.cpp
// Utilities for std::string
// defined in namespace strutil
// by James Fancy
////////////////////////////////////////////////////////////////////////////////
#include "strutil.h"
#include <algorithm>
namespace strutil {
using namespace std;
string trimLeft(const string& str) {
string t = str;
string::iterator i;
for (i = t.begin(); i != t.end(); i++) {
if (!isspace(*i)) {
break;
}
}
if (i == t.end()) {
t.clear();
} else {
t.erase(t.begin(), i);
}
return t;
}
string trimRight(const string& str) {
if (str.begin() == str.end()) {
return str;
}
string t = str;
string::iterator i;
for (i = t.end() - 1; ;i--) {
if (!isspace(*i)) {
t.erase(i + 1, t.end());
break;
}
if (i == t.begin()) {
t.clear();
break;
}
}
return t;
}
string trim(const string& str) {
string t = str;
string::iterator i;
for (i = t.begin(); i != t.end(); i++) {
if (!isspace(*i)) {
break;
}
}
if (i == t.end()) {
t.clear();
return t;
} else {
t.erase(t.begin(), i);
}
for (i = t.end() - 1; ;i--) {
if (!isspace(*i)) {
t.erase(i + 1, t.end());
break;
}
if (i == t.begin()) {
t.clear();
break;
}
}
return t;
}
string toLower(const string& str) {
string t = str;
transform(t.begin(), t.end(), t.begin(), tolower);
return t;
}
string toUpper(const string& str) {
string t = str;
transform(t.begin(), t.end(), t.begin(), toupper);
return t;
}
string repeat(char c, int n) {
ostringstream s;
s << setw(n) << setfill(c) << "";
return s.str();
}
string repeat(const string& str, int n) {
string s;
for (int i = 0; i < n; i++) {
s += str;
}
return s;
}
bool startsWith(const string& str, const string& substr) {
return str.find(substr) == 0;
}
bool endsWith(const string& str, const string& substr) {
size_t i = str.rfind(substr);
return (i != string::npos) && (i == (str.length() - substr.length()));
}
bool equalsIgnoreCase(const string& str1, const string& str2) {
return toLower(str1) == toLower(str2);
}
template<bool>
bool parseString(const std::string& str) {
bool value;
std::istringstream iss(str);
iss >> boolalpha >> value;
return value;
}
string toString(const bool& value) {
ostringstream oss;
oss << boolalpha << value;
return oss.str();
}
vector<string> split(const string& str, const string& delimiters) {
vector<string> ss;
Tokenizer tokenizer(str, delimiters);
while (tokenizer.nextToken()) {
ss.push_back(tokenizer.getToken());
}
return ss;
}
}
namespace strutil {
const string Tokenizer::DEFAULT_DELIMITERS(" \t\n\r");
Tokenizer::Tokenizer(const std::string& str)
: m_String(str), m_Offset(0), m_Delimiters(DEFAULT_DELIMITERS) {}
Tokenizer::Tokenizer(const std::string& str, const std::string& delimiters)
: m_String(str), m_Offset(0), m_Delimiters(delimiters) {}
bool Tokenizer::nextToken() {
return nextToken(m_Delimiters);
}
bool Tokenizer::nextToken(const std::string& delimiters) {
// find the start charater of the next token.
size_t i = m_String.find_first_not_of(delimiters, m_Offset);
if (i == string::npos) {
m_Offset = m_String.length();
return false;
}
// find the end of the token.
size_t j = m_String.find_first_of(delimiters, i);
if (j == string::npos) {
m_Token = m_String.substr(i);
m_Offset = m_String.length();
return true;
}
// to intercept the token and save current position
m_Token = m_String.substr(i, j - i);
m_Offset = j;
return true;
}
const string Tokenizer::getToken() const {
return m_Token;
}
void Tokenizer::reset() {
m_Offset = 0;
}
}

103
lib/strutil.h Normal file
View File

@ -0,0 +1,103 @@
////////////////////////////////////////////////////////////////////////////////
// @(#) strutil.h
// Utilities for std::string
// defined in namespace strutil
// by James Fancy
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>
// declaration
namespace strutil {
std::string trimLeft(const std::string& str);
std::string trimRight(const std::string& str);
std::string trim(const std::string& str);
std::string toLower(const std::string& str);
std::string toUpper(const std::string& str);
std::string repeat(char c, int n);
std::string repeat(const std::string& str, int n);
bool startsWith(const std::string& str, const std::string& substr);
bool endsWith(const std::string& str, const std::string& substr);
bool equalsIgnoreCase(const std::string& str1, const std::string& str2);
template<class T> T parseString(const std::string& str);
template<class T> T parseHexString(const std::string& str);
template<bool> bool parseString(const std::string& str);
template<class T> std::string toString(const T& value);
template<class T> std::string toHexString(const T& value, int width = 0);
std::string toString(const bool& value);
std::vector<std::string> split(const std::string& str, const std::string& delimiters);
}
// Tokenizer class
namespace strutil {
class Tokenizer {
public:
static const std::string DEFAULT_DELIMITERS;
Tokenizer(const std::string& str);
Tokenizer(const std::string& str, const std::string& delimiters);
bool nextToken();
bool nextToken(const std::string& delimiters);
const std::string getToken() const;
/**
* to reset the tokenizer. After reset it, the tokenizer can get
* the tokens from the first token.
*/
void reset();
protected:
size_t m_Offset;
const std::string m_String;
std::string m_Token;
std::string m_Delimiters;
};
}
// implementation of template functions
namespace strutil {
template<class T> T parseString(const std::string& str) {
T value;
std::istringstream iss(str);
iss >> value;
return value;
}
template<class T> T parseHexString(const std::string& str) {
T value;
std::istringstream iss(str);
iss >> hex >> value;
return value;
}
template<class T> std::string toString(const T& value) {
std::ostringstream oss;
oss << value;
return oss.str();
}
template<class T> std::string toHexString(const T& value, int width) {
std::ostringstream oss;
oss << hex;
if (width > 0) {
oss << setw(width) << setfill('0');
}
oss << value;
return oss.str();
}
}

20
lib/tcDebug.h Normal file
View File

@ -0,0 +1,20 @@
#ifndef debugH
#define debugH
#if defined( __WXMSW__ )
/*
//#define _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#ifdef _DEBUG
#ifdef _CRTDBG_MAP_ALLOC
#define new new(_NORMAL_BLOCK, __FILE__, __LINE__)
#endif // _CRTDBG_MAP_ALLOC
#endif // _DEBUG
*/
#endif // __WXMSW__
//-------------------------------------------------------------------------
#endif

275
lib/texture.cpp Normal file
View File

@ -0,0 +1,275 @@
#include "texture.h"
//#include "globalvar.h"
#include <GL/glew.h>
#include <GL/glu.h>
#include <wx/image.h>
#include <wx/zipstrm.h>
#include <wx/archive.h>
#include <wx/fs_zip.h>
#include <wx/wfstream.h>
#include <wx/mstream.h>
#include <wx/glcanvas.h>
#include <stdio.h>
//#include "tools/debug.h"
//загрузить текстуру из потока
unsigned int glLoadBitmap0(int mip,wxInputStream &mis,wxString ext)
{
if(mis.IsSeekable()) mis.SeekI(0,wxFromStart);
unsigned int texName=0;
glEnable(GL_TEXTURE_2D);
//glPixelStorei(GL_UNPACK_ALIGNMENT,1);
glGenTextures(1,&texName);
glBindTexture(GL_TEXTURE_2D,texName);
// glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE, GL_REPLACE);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); //Texture blends with object background
// glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); //Texture does NOT blend with object background
//Select a filtering type. BiLinear filtering produces very good results with little performance impact
// GL_NEAREST - Basic texture (grainy looking texture)
// GL_LINEAR - BiLinear filtering
// GL_LINEAR_MIPMAP_NEAREST - Basic mipmapped texture
// GL_LINEAR_MIPMAP_LINEAR - BiLinear Mipmapped texture
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_LINEAR);//GL_NEAREST GL_LINEAR
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, GL_LINEAR);
//int mip=2;
if(mip==0)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // only first two can be used
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // all of the above can be used
}else
if(mip==1)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // only first two can be used
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); // all of the above can be used
} else
if(mip==2)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST); // only first two can be used
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST); // all of the above can be used
} else
if(mip==3)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); // only first two can be used
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // all of the above can be used
}
//unsigned short Format=GL_RGB;
wxImage *m_Image;
if(ext.Lower()==_T("jpg"))
m_Image = new wxImage( mis, wxBITMAP_TYPE_JPEG, -1 );
else
if(ext.Lower()==_T("bmp"))
m_Image = new wxImage( mis ,wxBITMAP_TYPE_BMP, -1 );
else
if(ext.Lower()==_T("tga"))
{
m_Image = new wxImage( mis ,wxBITMAP_TYPE_TGA, -1 );
}else
if(ext.Lower()==_T("png"))
{
m_Image = new wxImage( mis ,wxBITMAP_TYPE_PNG, -1 );
}else return 0;
if(!m_Image->IsOk()) //если плохой рисунок выходим
{
delete m_Image;
return 0;
}
wxImage glImage = m_Image->Mirror(false); //because GL reads textures with 0,0 being the lower-left, we have to flip each image vertically
if(glImage.HasMask()) glImage.InitAlpha();
//изза того что в wxImage альфа канал храниться отделтно перебираем данные текстуры
//free(data);
unsigned char* data = (unsigned char*)malloc(glImage.GetWidth() * glImage.GetHeight() * 4);
unsigned int d = 0;
for (int y = 0; y < glImage.GetHeight(); y++)
{
for (int x = 0; x < glImage.GetWidth(); x++)
{
data[d++] = glImage.GetRed(x, y);
data[d++] = glImage.GetGreen(x, y);
data[d++] = glImage.GetBlue(x, y);
if(glImage.HasAlpha())
{
unsigned char a=glImage.GetAlpha(x, y);
data[d++] = a;
}
else
data[d++] = 255;
}
}
if((mip==0)||(mip==1))
glTexImage2D(GL_TEXTURE_2D, 0, 4, glImage.GetWidth(), glImage.GetHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
else
gluBuild2DMipmaps(GL_TEXTURE_2D, 4, glImage.GetWidth(), glImage.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, data);
free(data);
delete m_Image;
return texName; // Returns the current texture OpenGL ID
}
//------------------------------------------------------------------------------
//загрузить текстуру из файла
unsigned int glLoadBitmap(int mip,wxString filename)
{
if(!wxFile::Exists(filename)) return 0;
wxFileInputStream mis(filename);
return glLoadBitmap0(mip,mis,filename.AfterLast(_T('.')));
}
//------------------------------------------------------------------------------
/*TMaterial::TMaterial(TEmptySetPoints *parent):TEmptyPoint(parent)
{
textureid=0;
ColorAmbientRGB.r=0.2f; // 0.2 по умолчанию в OpenGL
ColorAmbientRGB.g=0.2f;
ColorAmbientRGB.b=0.2f;
ColorAmbientRGB.a=1.0f;
ColorDiffuseRGB.r=0.8f; // 0.8 по умолчанию в OpenGL
ColorDiffuseRGB.g=0.8f;
ColorDiffuseRGB.b=0.8f;
ColorDiffuseRGB.a=1.0f;
ColorSpecularRGB.r=0.0f; // 0.0 по умолчанию в OpenGL
ColorSpecularRGB.g=0.0f;
ColorSpecularRGB.b=0.0f;
ColorSpecularRGB.a=1.0f;
data=NULL;
}
//------------------------------------------------------------------------------
TMaterial::~TMaterial()
{
if(data!=NULL) free(data);
}
//------------------------------------------------------------------------------
//загрузить рисунок из буфера
void TMaterial::LoadImage()
{
if(imgpath!=_T(""))
{
wxMemoryInputStream mis(data,size);
textureid=glLoadBitmap0(2,mis,imgpath.AfterLast('.'));
free(data);
data=NULL;
}
}
//------------------------------------------------------------------------------
void TMaterial::LoadS(wxInputStream *is)
{
is->Read(&date,4); //read date
is->Read(&del,1); //read del
is->Read(&ObjectID,4); //read ObjectID
if(!del)
{
is->Read(&ColorDiffuseRGB.r,4);
is->Read(&ColorDiffuseRGB.g,4);
is->Read(&ColorDiffuseRGB.b,4);
is->Read(&ColorDiffuseRGB.a,4);
is->Read(&Lighting,1);
is->Read(&blend,1);
name=loadUTF8String(is); //загрузим название материала
imgpath=loadUTF8String(is); //загрузим название текстуры
//загрузим данные текстуры bmp,jpg,tif,png
is->Read(&size,4);
if(size>0)
{
data = (unsigned char*)malloc(size); //временно в поток потому что текстуру загружать в потоке отличном от контекста нельзя
is->Read(data,size);
LoadImage(); //загрузить текстуру и освободить память
}
}
}
//------------------------------------------------------------------------------
//устанавливаем материал перед вызовом обьекта
void TMaterial::Release()
{
//прозрачность
if(blend)
{
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
} else glDisable(GL_BLEND);
if(Lighting) //со светом
{
glEnable(GL_LIGHTING);
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (float*)&ColorAmbientRGB);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, (float*)&ColorDiffuseRGB);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, (float*)&ColorSpecularRGB);
}else
{//без света
glDisable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColor4f(ColorDiffuseRGB.r,ColorDiffuseRGB.g,ColorDiffuseRGB.b,ColorDiffuseRGB.a);
glDisable(GL_COLOR_MATERIAL);
}
//если текстурированна
if(textureid!=0)
{
glBindTexture(GL_TEXTURE_2D, textureid);
glEnable(GL_TEXTURE_2D);
//чтобы цвет не воздействовал на текстуру если она есть
glEnable(GL_COLOR_MATERIAL);
glColor4f(1,1,1,ColorDiffuseRGB.a);
glDisable(GL_COLOR_MATERIAL);
} else glDisable(GL_TEXTURE_2D);
}
//------------------------------------------------------------------------------
TMaterials::TMaterials(TCity *parent) :TEmptySetPoints(parent)
{
ext=_T("mat");
fid=11347;
}
//------------------------------------------------------------------------------
TMaterials::~TMaterials()
{
}
//------------------------------------------------------------------------------
void TMaterials::LoadS(wxInputStream *is)
{
if(is==NULL) return;
unsigned int i,count;
is->Read(&i,4); if(i!=fid) return; //проверка на id файла
is->Read(&version,4); //версия файла
is->Read(&fMaxObjectID,4); //максимальный id для этого файла
is->Read(&fdatesrv,4); //время последнего обновления с сервера сек с 2000
is->Read(&count,4); //кол во дорог
List = new TEmptyPoint*[count];
for(i=0;i<count;i++)
{
TMaterial *Material = new TMaterial(this);
Material->LoadS(is);
List[i]=Material;
m_count++;
}
}
//------------------------------------------------------------------------------
void TMaterials::MouseLUp(RfPointXYZ fGLMLUpXYZ)
{
}
//------------------------------------------------------------------------------
void TMaterials::MouseRUp(RfPointXYZ fGLMLUpXYZ)
{
}
//------------------------------------------------------------------------------
void TMaterials::MouseMove(RfPointXYZ fGLMLUpXYZ)
{
}
//------------------------------------------------------------------------------
void TMaterials::OnMouseWhell(float f)
{
}
//------------------------------------------------------------------------------
void TMaterials::LoadComplete()
{
}*/
//------------------------------------------------------------------------------

56
lib/texture.h Normal file
View File

@ -0,0 +1,56 @@
#ifndef textureH
#define textureH
#include <wx/wx.h>
#include <wx/file.h>
//#include <GL/glew.h>
//#include <GL/glu.h>
#include <stdio.h>
//#include "graph_factory.h"
unsigned int glLoadBitmap(int mip,wxString filename);
unsigned int glLoadBitmap0(int mip,wxInputStream &mis,wxString ext);
/*class TMaterial : public TEmptyPoint
{ private:
protected:
unsigned int size; //размер буфера
unsigned char* data; //временный буфер для загрузки изображения
public:
RfColorRGBA ColorDiffuseRGB;
RfColorRGBA ColorAmbientRGB;
RfColorRGBA ColorSpecularRGB;
bool Lighting;
bool blend;
wxString imgpath; //название изображения
unsigned int textureid; //id загруженного изображения
TMaterial(TEmptySetPoints *parent);
virtual ~TMaterial();
void LoadS(wxInputStream *is);
void Render(){};
void Release(); //применить текстуру
void LoadImage(); //загрузить рисунок из буфера
};
//------------------------------------------------------------------------------
//фабрика материалов (для каждого города своё)
class TMaterials : public TEmptySetPoints
{
private:
protected:
public:
unsigned int fid;
TMaterials(TCity *parent);
virtual ~TMaterials();
//void Load(const wxString path);
void LoadS(wxInputStream *is);
void Render(){};
void MouseLUp(RfPointXYZ fGLMLUpXYZ);
void MouseRUp(RfPointXYZ fGLMLUpXYZ);
void MouseMove(RfPointXYZ fGLMLUpXYZ);
void OnMouseWhell(float f);
void LoadComplete();
};*/
//------------------------------------------------------------------------------
#endif

1455
lib/tiptopbd.cpp Normal file

File diff suppressed because it is too large Load Diff

490
lib/tiptopbd.h Normal file
View File

@ -0,0 +1,490 @@
//---------------------------------------------------------------------------
#ifndef TIPTOPBD_H_
#define TIPTOPBD_H_
//---------------------------------------------------------------------------
#include <math.h>
#include <wx/string.h>
#include <wx/wfstream.h>
#include <wx/mstream.h> //Поток в память
#include <wx/stream.h> //Поток буф
#include "structs.h"
#include "tcDebug.h"
//---------------------------------------------------------------------------
typedef unsigned char uint1;
typedef unsigned short uint2;
typedef unsigned int uint4;
typedef unsigned __int64 uint8;
typedef char int1;
typedef short int2;
typedef int int4;
typedef __int64 int8;
//---------------------------------------------------------------------------
const uint2 file_id=65500;//*((uint2*)"TB");//16980 id файла базы данных и таблицы 2 байта
const uint2 file_version=1; //текущая версия файла базы данных 2 байта
//---------------------------------------------------------------------------
//типы данных которые можно хранить в базе под них 1 байт
#define BD_UINT1 0 //1 байт без знаковый
#define BD_UINT2 1 //2 байт без знаковый
//#define BD_UINT3 2 //3 байт без знаковый
#define BD_UINT4 3 //4 байт без знаковый
//#define BD_UINT5 4 //5 байт без знаковый
//#define BD_UINT6 5 //6 байт без знаковый
//#define BD_UINT7 6 //7 байт без знаковый
#define BD_UINT8 7 //8 байт без знаковый
#define BD_INT1 10 //1 байт со знаковый
#define BD_INT2 11 //2 байт со знаковый
//#define BD_INT3 12 //3 байт со знаковый
#define BD_INT4 13 //4 байт со знаковый
//#define BD_INT5 14 //5 байт со знаковый
//#define BD_INT6 15 //6 байт со знаковый
//#define BD_INT7 16 //7 байт со знаковый
#define BD_INT8 17 //8 байт со знаковый
#define BD_FLOAT4 20 //17 - float 4_байта
//#define BD_FLOAT6 21 //18 - real 6_байт
#define BD_FLOAT8 22 //19 - double 8_байт
#define BD_BOOL 30 //1 байт 0-false 1-true
#define BD_UTF8_1 100 //100 - utf8_1 string 1й байт размер строки в байтах
#define BD_UTF8_2 101 //101 - utf8_2 string 1х 2 байта размер строки в байтах
//#define BD_UTF8_4 102 //101 - utf8_2 string 1х 4 байта размер строки в байтах
//#define BD_ASCII_1 110 //102 - asci_1 строка 1й байт размер строки в байтах
//#define BD_ASCII_2 112 //103 - asci_2 строка 1х 2 байта размер строки в байтах
//-#define BD_ASCII_0 120 //Строка с 0 на конце
//для этих двоичных объектов в начале передаются не данные а только размер потом обновляют запись по id записи
#define BD_GPS_4 130 //250 - GPS коордионаты в формате: uint4 количество байт,float,float (широта lat,долгота lon в WGS-84)
#define BD_GPS_8 131 //251 - GPS коордионаты в формате: uint4 количество байт, double,double (широта lat,долгота lon в WGS-84 )
#define BD_GPSS_8 132 //252 - GPS координаты в формате: uint4 количество байт, uint4 количество сегментов, uint4 количество точек в первом сегменте,(double,double точки первого сегмента)
//#define BD_BLOB_1 140 //254 - двоичные данные uint1 количество байт
//#define BD_BLOB_2 141 //254 - двоичные данные uint2 количество байт
//#define BD_BLOB_3 142 //254 - двоичные данные uint3 количество байт
#define BD_BLOB_4 143 //254 - двоичные данные uint4 количество байт
//#define BD_BLOB_8 144 //255 - двоичные данные uint8 количество байт
//---------------------------------------------------------------------------
//"Типа" свой поток для записи в память либо в файл
class TiptopStream
{
private:
uint4 m_posRead; //Текущая позиция при записи
uint4 m_posWrite; //Текущая позиция при чтении
uint4 m_size; //Размер данных
//список страниц базы данных
unsigned int m_pageSize; //Размер страницы данных
TSimpleList<unsigned char*>* m_pages; //список страниц данных
public:
TiptopStream(){ m_pageSize=1024;/*4096;*/ m_pages=new TSimpleList<unsigned char*>(10,true); m_posRead=0; m_posWrite=0; m_size=0; };
~TiptopStream(){ delete m_pages; };
void Clear()
{ m_pages->clear();
}
uint4 GetSize(){ return m_size; };
void Read(const void* buf, unsigned int size) //Прочитать данные в buffer размером
{
unsigned char* buffer=(unsigned char*)buf;
while(size>0)
{
unsigned int b=(m_posRead / (float)m_pageSize); //Блок
unsigned int p=m_posRead - b * m_pageSize; //Позиция в блоке
unsigned char* ch=m_pages->get(b) + p; //Буфер на нужной позиции
unsigned int s = m_pageSize - p; //сколько можно и нужно прочитать из блока
if(s > size) s=size;
memcpy(buffer, ch, s);
buffer+=s;
size-=s;
m_posRead+=s;
}
};
void Read(wxOutputStream* os) //Записать все данные в os
{
uint4 s=m_size;
for(uint4 i=0;i<m_pages->count();i++)
{
unsigned char* ch=m_pages->get(i);
if(s>m_pageSize)
{ s-=m_pageSize;
os->Write(ch,m_pageSize);
}
else os->Write(ch,s);
}
}
void Write(const void* buf, unsigned int size)
{
unsigned char* buffer=(unsigned char*)buf;
if(m_posWrite+size>m_pages->count()*m_pageSize) //Расширить память
{
unsigned int s=ceil((m_posWrite+size) / (float)m_pageSize);
if(s>m_pages->count())
{ s-=m_pages->count();
for(unsigned int i=0;i<s;i++) m_pages->add( new unsigned char[m_pageSize] );
}
}
while(size>0)
{
unsigned int b=floor(m_posWrite / (float)m_pageSize); //Находим нужный блок памяти
unsigned int p=m_posWrite - b * m_pageSize; //Позиция с начала блока памяти
unsigned char* ch=m_pages->get(b) + p;
unsigned int s = m_pageSize - p;
if(s > size) s=size;
memcpy(ch, buffer, s);
buffer+=s;
size-=s;
m_posWrite+=s;
}
if(m_size<m_posWrite+size) m_size=m_posWrite+size;
};
void Write(wxInputStream* s)
{
unsigned char* buf=new unsigned char[1024];
while(true)
{
s->Read(buf,1024);
unsigned int r=s->LastRead();
if(r==0) break;
Write(buf,r);
}
delete buf;
};
void SeekRead(uint4 pos){ m_posRead=pos; };
uint4 TellRead(){ return m_posRead; };
void SeekWrite(uint4 pos) { m_posWrite=pos; }
uint4 TellWrite(){ return m_posWrite; };
};
//---------------------------------------------------------------------------
//Преобразовать значние в соответствии с типом если int и пустая строка то NULL
wxString getSQLValue(wxString t,wxString v);
//---------------------------------------------------------------------------
class TiptopTable;
//---------------------------------------------------------------------------
/*
//http://slady.net/java/bt/view.php?w=1024&h=768
//узел двоичного дерева фиксированной длины (высчитать размер надо чтоб с диска читалось примерно по 512 байта)
//По определению, двоичное дерево называется АВЛ деревом в том и только в том случае, когда высоты двух поддеревьев каждой из вершин дерева отличаются не более, чем на единицу
class BTreeNode
{
private:
public:
int1 balance; //Баланс для АВЛ дерева -1 - левое длиней, 0 - сбалансированно, 1 - правое длиней
uint4 val; //размеры свободного пространства
uint4 pos; //позиции в файле для размера
uint4 fllink,frlink; //ссылки на дочерние узлы в файле
BTreeNode *llink,*rlink; //ссылки на дочерние узлы в памяти
BTreeNode *parent; //родительмкий узел дла нормализации
BTreeNode(){llink=NULL; rlink=NULL;};
~BTreeNode(){};
};
//Индекс пустых мест в таблице создаётся для каждой таблицы (потом наверно и для всего файла надо будет сделать)
//отсортированно по возрастанию свободного места "кол-во места->позиция в файле"
/*class TiptopIndexFreeSpase
{
private:
// TiptopTable* m_table;
uint4 m_count; //количество элементов
wxFFile* m_file; //чтение и запись
bool LLRotation(BTreeNode* p0,BTreeNode* p1,BTreeNode* p2); //Одинарный LL-поворот.
bool RRRotation(BTreeNode* p0,BTreeNode* p1,BTreeNode* p2); //Одинарный RR-поворот.
bool LRRotation(BTreeNode* p0,BTreeNode* p1,BTreeNode* p2); //Двойной LR-поворот.
bool RLRotation(BTreeNode* p0,BTreeNode* p1,BTreeNode* p2); //Двойной RL-поворот.
public:
TiptopIndexFreeSpase(TiptopTable* table);
~TiptopIndexFreeSpase();
uint4 findFree(uint4 size); //найти позицию в файле с минимальным подходящим размером для записи
bool setUseSpace(uint4 pos,uint4 size); //сообщить что данная позиция занята
bool setFreeSpase(uint4 pos,uint4 size); //сообщить что данные освободились
void updateLast(); //обновить размер по данным поледнего вызова findFree
};
//Есть 4 варианта нарушения балансировки АВЛ-дерева
//Одинарный LL-поворот. Выполняется, когда <перевес> идет по пути L-L от узла с нарушенной балансировкой.
bool TiptopIndexFreeSpase::LLRotation(BTreeNode* p0,BTreeNode* p1,BTreeNode* p2)
{
p1 := p^.llink;
p^.llink := p1^.rlink;
p1^.rlink := p;
p := p1;
}
//Одинарный RR-поворот. Выполняется, когда <перевес> идет по пути R-R от узла с нарушенной балансировкой.
bool TiptopIndexFreeSpase::RRRotation(BTreeNode* p0,BTreeNode* p1,BTreeNode* p2)
{
p1 := p^.rlink;
p^.rlink := p1^.llink;
p1^.llink := p;
p := p1;
}
//Двойной LR-поворот. Выполняется, когда <перевес> идет по пути L-R от узла с нарушенной балансировкой.
bool TiptopIndexFreeSpase::LRRotation(BTreeNode* p0,BTreeNode* p1,BTreeNode* p2)
{
p1 := p^.llink;
p2 := p1^.rlink;
p1^.rlink := p2^.llink;
p2^.llink := p1;
p^.llink := p2^.rlink;
p2^.rlink := p;
p := p2;
}
//Двойной RL-поворот. Выполняется, когда <перевес> идет по пути R-L от узла с нарушенной балансировкой.
bool TiptopIndexFreeSpase::RLRotation(BTreeNode* p0,BTreeNode* p1,BTreeNode* p2)
{
p1 := p^.rlink;
p2 := p1^.llink;
p1^.llink := p2^.rlink;
p2^.rlink := p1;
p^.rlink := p2^.llink;
p2^.llink := p;
p := p2;
}
*/
//---------------------------------------------------------------------------
class TiptopField;
//---------------------------------------------------------------------------
//числовой индекс базы данных (для id поля он обязателен)
//Создаётся файл вида "id таблицы_id поля.i" (если id поля = 0 то это индекс свободных мест)
class TiptopIndex
{
private:
uint4 m_type; //Тип индекса (1 - самый простой)
uint4 m_count; //количество элементов
wxFFile* m_file; //чтение и запись
public:
TiptopField* m_fl; //Поле таблицы для которого строится индекс
TiptopIndex(TiptopField* fl);
~TiptopIndex();
void add(uint4 pos,uint4 id);
bool getPos(uint4 val,uint4& pos,int4& num); //Поиск значения среди упорядоченного списка
};
//---------------------------------------------------------------------------
struct RuiPointPS
{ unsigned int pos; //позиция в файле
unsigned int size; //Размер
};
//---------------------------------------------------------------------------
//Индекс пустых мест пока как таблица (потом переделать в двоичный список)
class TiptopIndexFreeSize
{
private:
TSimpleList<RuiPointPS*>* m_Pos; ///<Массив позиции
public:
TiptopIndexFreeSize()
{ m_Pos=new TSimpleList<RuiPointPS*>(10,true);
};
~TiptopIndexFreeSize(){ delete m_Pos; };
void add(unsigned int pos, unsigned int size) //Добавить "пустое место" в список
{ RuiPointPS* p=new RuiPointPS;
p->pos=pos; p->size=size;
m_Pos->add(p);
};
bool del(unsigned int pos) //Удалить из списка свободных мест
{ for(uint4 i=0;i<m_Pos->count();i++)
if(m_Pos->get(i)->pos==pos) { return m_Pos->del(i); }
return false;
};
bool upd(unsigned int pos, unsigned int size) //Сдвинуть позицию на заданый размер и уменьшить размер
{
for(uint4 i=0;i<m_Pos->count();i++)
{
if(m_Pos->get(i)->pos==pos)
{
unsigned int s=m_Pos->get(i)->size;
if(s==size)
{ m_Pos->del(i);
break;
}
if(s<size) return false;
else
{ m_Pos->get(i)->pos+=size;
m_Pos->get(i)->size-=size;
}
break;
}
}
return false;
};
bool get(unsigned int size,unsigned int &pos) //Получить позицию подходящую под заданный размер
{ bool b=false;
unsigned int min=0xffffffff;
for(unsigned int i=0;i<m_Pos->count();i++)
{
if(m_Pos->get(i)->size>=size && m_Pos->get(i)->size<min)
{ pos=m_Pos->get(i)->pos;
min=m_Pos->get(i)->size;
b=true;
}
}
return b;
};
};
//---------------------------------------------------------------------------
class TiptopTable;
//---------------------------------------------------------------------------
//поле базы данных
class TiptopField
{
private:
//Для 1 го поля 1н индекс
public:
TiptopTable* m_tb; //Если NULL то поле не присоединено к таблице
void* m_value; //ссылка на данные (может быть NULL)
uint4 m_size; //размер данных (Если 0 то в базе NULL)
wxString m_name; //название поля
uint1 m_type_id; //id типа данных
bool m_NULL; //может ли быть пустым
bool m_index; //Нужен ли индекс для этого поля (не используется, может быть: первичным, вторичным, уникальным, просто индексом для поиска)
TiptopIndex* m_idx; //Индекс поля (пока только для поля id)
TiptopField(TiptopTable* tb); //Конструктор задаётся какой таблице принадлежит
~TiptopField();
void setValue(void* value,uint4 size); //Данные копируются
void setValue(TiptopStream* is,uint4 size); //Записать данные
void setValue(int value);
void setValue(wxString value); //Прочитать данные из строки в соответствии с типом
void setValue(bool value); //Присвоить bool значение
void setValue(double value); //Присвоить double значение
TiptopField* cloneNode(); ///< Клонировать узел
uint4 getSize()
{ if(m_value==NULL) return 0;
return m_size;
}; ///<Размер без учёта размера под данные
uint4 getAllSize(); ///<Размер с учётом типа поля
//Функции для взятия значений
bool getBoolVal();
uint4 getUint4Val();
int4 getIntVal();
double getDblVal();
wxString getStrVal();
wxString getStrSQLVal();
};
//---------------------------------------------------------------------------
class TiptopBD;
//---------------------------------------------------------------------------
//таблица данных может быть присоединённой к данным а может и отдельно волятся...
//Если отдельно то для неё не предназначенны вторичные ключи только 1 первичный и индексы...
class TiptopTable
{
private:
uint1 m_Type; //Тип таблицы 0-Плотная(Индекс не обязателен последовательный доступ) 1-Жидкая (Индекс обязателен)
//wxOutputStream* m_os; ///<Для записи заголовка и данных данных
//wxMemoryOutputStream* m_os; ///<Для записи заголовка и данных
//bool m_osOwner; ///<Владелец ли m_os смотри деструктор
//bool m_ok; //выполнилась ли последняя операция успешно
//wxString m_path; //Путь к файлу таблицы
int4 getNumFieldOnName(wxString name); //вернуть позицию поля по имени нумерация с 0, если -1 то нет такого
TSimpleList2<uint8> m_Pos; ///<Массив позиции полей от начала файла либо потока
TiptopIndexFreeSize* m_IndexFreeSize; //Индекс свободного пространства
bool buildPosIndex(); ///<Построить индекс позиций прочитав таблацу он начала до конца
public:
//wxFileOutputStream* m_fos; //для записи в файл таблицы
//wxFileInputStream* m_fis; //для чтения из файла таблицы
//wxInputStream* m_is; ///<Для чтения заголовка таблицы и данных
wxFFile* m_file; //чтение и запись
TiptopStream* m_stream; ///<С этим потоком работает таблица для чтения и записи
uint1* m_Null;//Массив байт для чтения и записи NULL значений (равно количеству столбцов не зависимо возможно ли NULL)
uint1 m_NullSize;//количество байт для NULL, подсчитываются = cell(count fields/8)
uint4 m_RecSize; ///<Размер последней прочитанной записи в байтах с учётом null и типов
uint4 m_RecPos; ///<Позиция последней прочитаной записи
TSimpleList<TiptopField*>* fields; //список столбцов владелец (идут попорядку id поля нет есть позиция)
TiptopBD* m_bd; //Если NULL то таблица не присоединена к базе данных
uint4 m_id; //id таблицы в нутри базы (или запроса)
wxString m_name; //Название таблицы (читается из файла)
int m_count; //Количество записей (заранее неизвестно если нет индекса)
//uint4 rCount; //Количество записей в таблице (Информационное поле)
TiptopTable(TiptopBD* bd,uint4 id);
~TiptopTable();
//bool isOk();
bool AddField(TiptopField* fl); ///<Добавить поле к таблице становится владельцем (без записи в поток)
TiptopField* AddField(wxString name,uint1 type_id); ///<Добавить поле к таблице (без записи в поток)
TiptopField* AddField(wxString name,wxString type); ///<Добавить поле к таблице (без записи в поток)
bool OpenTable(); //открыть таблицу (если обьект TiptopTable не в базе если таблица не открылась то результат false а путь к файлу сохраниться)
//bool OpenTable(wxInputStream* is); //Подгрузить таблицу из потока (Читает только заголовок)
bool OpenTable(wxString path); //Прочитать из файла
// bool SetOutputStream(wxMemoryOutputStream* os, bool owner=false);
// const wxMemoryOutputStream* GetOutputStream(){return m_os;};
bool ReadTableToMem(wxInputStream* is); ///<Прочитать таблицу из потока в оперативную память
bool CreateTable(wxString SQL); //Создать файл таблицы через SQL запрос
bool InsertInto(wxString SQL); //Добавить запись в таблицу и в индексы через SQL запрос
bool UpdateTable(wxString SQL); //"простое" обновление записей через SQL запрос
wxFFile* getStream(uint4 id,wxString field); //TODO надо сделать свой защищённый "поток"
//wxMemoryInputStream* GetInputStream(); ///<Создаёт новый поток в который помещяет таблицу с данными для чтения (TiptopTable не остаётся владельцем)
TiptopField* getField(wxString name); //Получить поле по имени (Для того чтобы получить по индексу используй TSimpleList)
uint4 findFreeSize(uint4 size = 0); //Найти позицию с свободным местом для записи данных (из индекса свободных мест)
bool FindFirstRecord(TiptopField* fl,uint4 &pos,uint4 &num); ///<Найти позицию первой попавшейся записи с заданными значениями поля, результат позиция записи в памяти.
bool SeekToStart(); //Переместить курсор чтения на первую запись (чтоб потом можно было последовательно прочитать всю таблицу)
bool ReadRecord(wxString field,uint4 val); //найти и прочитать запись
bool ReadRecord(TiptopStream* is); //Позиция на нужном месте читаем запись из потока
bool ReadRecord(int4 pos); //Перемещяем курсор в заданную позицию и читаем запись
bool ReadNextRecord(bool savePos = false); //Прочитать следующую запись из таблицы
bool ReadRecordByNum(uint4 num); //Читать запись по её порядковому номеру (должны заранее знать позиции записей)
bool WriteHeader(); ///<Записать заголовок таблицы в поток m_os (Используется при создании таблицы)
bool WriteRecord(bool savePos , bool findPos); ///<Записать 1 запись в конец m_os из полей (TODO как сделаю findFreeSize то в пустую позицию)
bool WriteRecord(); //Записать запись в текущее положение потока m_os
//bool WriteTableToStream(wxOutputStream* os); ///<Записать заголовок и тело таблицы в предоставленный поток
void addRecPos(uint8 pos) //Добавить позицию записи в памяти
{ m_Pos.add(pos);
};
bool delRecPos(uint8 pos); //Удалить позицию записи в памяти
//uint4 getNumByRecPos(uint8 pos)//Получить порядковый номер записи по позиции
/*uint4 GetRecPos(uint4 num) //Получить адрес записи по позиции
{ if(m_Pos.count()==0) rerturn 0; //TODO исправить добавить bool к параметрам либо возвращять -1
return m_Pos.get(num);
};*/
bool AppendTable(TiptopTable* tb, bool spw, bool spr); //Добавить записи из заданной в текущую (поля должны совпадать по имени и по типу)
bool UpdateTable(TiptopTable* tb); //Обновить записи из заданной в текущую (поля должны совпадать по имени и по типу)
bool UpdateRecord(); ///<Обновить 1 запись удаляем потом пишем
};
//---------------------------------------------------------------------------
//база данных (набор таблиц)
class TiptopBD
{
private:
wxFileOutputStream* m_fos; //поток чтения из файла
wxFileInputStream* m_fis; //поток записи в файл
TSimpleList<TiptopTable*>* list;//список таблиц
uint4 m_maxid; //макс id таблиц (нумерация с 1)
bool m_ok; //Нормально ли открылась база
public:
wxString m_path; //путь к папке с файлами базы
TiptopBD();
~TiptopBD();
bool Open(wxString path); //задаётся путь к папке где лежит bd.bd файл
bool TableExist(wxString name); //существует ли таблица
//bool AddTable(wxString file); //добавить существующую таблицу в базу данных
TiptopTable* getTable(wxString name); //Получить объект таблицы по её имени
bool ExecSQL(wxString SQL); //выполнить SQL запрос без результата
bool addTable(uint4 id); //Добавить таблицу в базу под заданным id
};
//---------------------------------------------------------------------------
#endif

1450
lib/utility.cpp Normal file

File diff suppressed because it is too large Load Diff

365
lib/utility.h Normal file
View File

@ -0,0 +1,365 @@
/*
* utility.h
*
* Created on: 10 дек. 2014 г.
* Author: ivanov.i
*/
#ifndef UTILITY_H_
#define UTILITY_H_
#include <string>
#include <vector>
#include <list>
#ifdef __linux__
#include <inttypes.h>
#elif _WIN32
#include <windows.h>
#include <stdint.h> //C++Builder
#else
#endif
namespace UtilityW
{
#ifdef _WIN32
void UnixTimeToFileTime(time_t t, LPFILETIME pft);
void UnixTimeToSystemTime(time_t t, LPSYSTEMTIME pst);
#endif
//time_t g_file_name_cnt_time;
//int g_file_name_cnt;
std::string getNextFileName(); //Генерировать уникальное имя файла на основе времени и порядкового номера из глобавльной переменной
char separator();
bool checkPort(const char *hostname,int portno,int timeout); //Проверяем открыт ли сокет
uint8_t CRC8(const signed char *pcBlock, unsigned char len, unsigned char crc);
bool DeCrypt(std::string strKey, std::string fNameIn, std::string fNameOut);
unsigned char setBitVal(unsigned char bit,unsigned char pos,bool val); //Установит знначение бита в заданную позицию pos - Позиция 7..0
bool getBitVal(unsigned char bit,unsigned char pos); //Вернёт значение бита на заданной позиции, pos - Позиция 7..0
unsigned int getMSecTime();
std::string urlEncode(const std::string &url);
std::string urlDecode(const std::string &encoded);
std::string charToHex(unsigned char c);
std::string shortToHex(unsigned short c);
std::string uintToHex(unsigned int val,char size);
unsigned char hexToChar(const std::string &str);
unsigned char bitStrToChar(std::string str);
unsigned int HexStdStrToUInt(std::string& str);
bool hexStrToArray(const std::string &str,char* arr);
bool arrayToHexStr(char* arr,unsigned int len,std::string &str);
bool vectorToHexStr(std::vector < unsigned char >& arr,std::string &str);
bool initPin(std::string pinnum); //Инициализируем ножку чтоб в неё можно записывать 0 или 1 как в файл (Документация GPIO: http://www.avrfreaks.net/wiki/index.php/Documentation:Linux/GPIO)
bool setPinDir(std::string pinnum, bool dir); //Задать направление чтения или записи (сейчас вывод) dit=true на вывод, dit=false на ввод, pull - подтяжка к 0 или к 1 питания.
bool setPinVal(std::string pinnum, bool val); //Задаём напряжение для ножки
char getPinVal(std::string pinnum); //Получить значение ножки
std::string doubleToString(double val);
std::string intToString(signed int val);
std::string ullintToString(unsigned long long int val);
std::string uintToString(unsigned int val);
std::string AfterFirst(std::string str,const char ch);
std::string DecToBinStr(int N,int cnt=0);
std::string DecToBinStr(unsigned int N,int cnt=0);
std::string addZero(std::string str,int count,char ch='0');
std::string addZero(int val,int count,char ch='0');
std::string escape_json(const std::string& input);
std::string AfterLast(std::string str,const unsigned char ch);
std::string BeforeFirst(std::string str,const unsigned char ch);
std::string BeforeLast(std::string str,char ch);
std::string CutBeforeFirst(std::string& str,const unsigned char ch);
std::string CutBeforeFirst(std::string& str,std::string br);
std::string CutAfterLast(std::string& str,const unsigned char ch);
std::string CutAfterFirst(std::string& str,std::string br);
void Trim(std::string& s);
void TrimLeft(std::string& s);
void TrimRight(std::string& s);
double StdStrToDouble(std::string& str);
float StdStrToFloat(std::string& str);
bool StdStrToFloat(std::string& str,float& val);
int StdStrToInt(std::string& str);
unsigned int StdStrToUInt(std::string& str);
unsigned long long StdStrToULLInt(std::string& str);
long getMaxFileSize(std::string path); //Получить размер самого большого файла в каталоге
long getAllFSSize(std::string anyfile);
long getFreeFSSize(std::string anyfile);
long getFileSize(std::string file);
long getFileDateModiff(std::string file);
int readFile(std::string file, char* data, int size);
bool dirExists(std::string path);
bool fileExists(std::string name);
void GetFiles(std::list<std::string>& fileList, std::string directory); //Получить список файлов в директории (в том числе и в подпапках)
void GetFolders(std::list<std::string>& folderList, std::string directory); //Получить список папок в директории (без подпапок)
bool createFolder(std::string directory,int mode); //Создать папку
void delString(std::vector<std::string> *mas, int pos);
std::string unixTimeToDate(double time);
//bool logrotate(int cnt,int size, std::string name, std::string data); //Сохранение лог файла в 2 версии по 10 мегабайт
bool logrotate(std::string fileName,std::string name,std::string level, std::string data,bool cout=false,int size=10); //Сохранение лог файла в 2 версии по 10 мегабайт
void Distance(float r, float cx, float cy, float lx1, float ly1, float lx2, float ly2, bool& Coincides, float& x, float& y);
bool parseGPRMC(std::string ans,time_t& utime,double& lon,double& lat,float& speed,float& angle); //На вход строка вида: $GPRMC,074353.0,A,4315.286297,N,07651.391112,E,0.0,255.3,191214,,,A*68
void sleep2(int sec); //В секундах
bool deleteFile(std::string fileName); //Удалить файл
bool deleteOldFiles(std::string path,int days); //Удалить файлы старше заданного количества дней
bool deleteOldFile(std::string path); //Удалить 1 последний файл
}
//------------------------------------------------------------------------------
//Расширяемый массив элементов, может выступать в качестве родителя те. удалять элементы при уничтожении списка или при удалении элемента из списка
template <class T> class TSimpleList
{
private:
T* f_NULL; //При выходе за пределы массива выдаётся этот элемент
T* List; //массив элементов
unsigned int f_size; //размер массива (без учёта занятых позиций)
unsigned int f_count; //количество элементов
unsigned int f_step; //шаг увеличения массива
public:
bool f_owner; //являеться ли владельцем элементов данный списк (нужно ли удалять элементы списка)
explicit TSimpleList(unsigned int step=10,bool owner=false)
{
if(step==0)step=1;
f_step=step;
List=new T[f_step];
f_size=f_step;
f_count=0;
f_owner=owner;
f_NULL=NULL;
};
~TSimpleList()
{
if(f_owner)
for(unsigned int i=0;i<f_count;i++)
delete List[i];
delete[] List;
};
unsigned int count()
{
return f_count;
};
unsigned int size() //количество элементов
{
return f_count;
};
//Добавить элемент в конец массива
T add(T item)
{
if(f_count<f_size)
{
List[f_count]=item;
f_count++;
}else
{
T* buf=new T[f_size+=f_step];
for(unsigned int i=0;i<=f_count;i++) buf[i]=List[i];
T* buf0=List;
List=buf;
delete[] buf0;
List[f_count++]=item;
}
return item;
};
void push_back(T item) {add(item);};
void insert(T item, unsigned int pos) //pos - 0..N
{
if(pos>=f_count)
{
if(pos<f_size){List[pos]=item; f_count=pos+1;} //в пустую область
else //в не выделенную область
{
T* buf=new T[pos+1];
for(unsigned int i=0;i<=f_count;i++) buf[i]=List[i];
T* buf0=List;
List=buf;
delete[] buf0;
List[pos]=item;
f_count=pos+1;
}
}else//сдвинуть имеющиеся
{
add(List[f_count-1]);
for(unsigned int i=f_count-2;i>pos;i--)
List[i]=List[i-1];
List[pos]=item;
}
};
void del(T item) //удаляем элемент и сдвигаем все элементы на 1 в лево
{
unsigned int cnt=0;
bool b=false;
for(unsigned int i=0;i<f_count;i++)
{
//if(List[i]==item){cnt--; b=true;}
if(List[i]==item){b=true; continue;}
List[cnt]=List[i];
cnt++;
}
if(b)
{
f_count--;
if(f_owner)delete item;
}
};
bool del(unsigned int pos) //удаляем элемент и сдвигаем все элементы на 1 в лево
{
if(pos>=f_count)return false;
f_count--;
if(f_owner) delete List[pos];
for(unsigned int i=pos;i<f_count;i++) List[i]=List[i+1];
return true;
};
T& get(unsigned int i)
{ if(i>=f_count) {return (T&)f_NULL;}
return List[i];
};
T& operator[](unsigned int i)
{ if(i>=f_count) {return (T&)f_NULL;}
return List[i];
};
bool Pos(T item,unsigned int &pos) //Узнать позицию элемента в массиве
{
for(unsigned int i=0;i<f_count;i++)
if(List[i]==item) { pos=i; return true; }
return false;
};
//Очистить массив с уменьшением размерности до одного шага увеличения массива
void clear()
{
unsigned int cnt=f_count;
f_count=0;
if(f_owner) for(unsigned int i=0;i<cnt;i++) delete List[i];
T* tmp=List;
f_size=f_step;
List=new T[f_step];
delete[] tmp;
};
};
//------------------------------------------------------------------------------
//простой список не являющийся владельцем своих элементов (можно задавать реальные обьекты а не ссылки)
template <class T> class TSimpleList2
{
private:
T* List; //массив элементов
unsigned int f_size;//размер массива
unsigned int f_count;//количество элементов
unsigned int f_step;//шаг увеличения массива
public:
explicit TSimpleList2() //Для использования конструктора по умолчанию
{
f_step=10;
List=new T[f_step];
f_size=f_step;
f_count=0;
};
TSimpleList2(unsigned int step)
{
if(step==0)step=1;
f_step=step;
List=new T[f_step];
f_size=f_step;
f_count=0;
};
~TSimpleList2()
{
delete[] List;
};
unsigned int count() //количество элементов
{
return f_count;
};
unsigned int size() //количество элементов
{
return f_count;
};
//Добавить элемент в конец массива
void add(T item)
{
if(f_count<f_size)
{
List[f_count]=item;
f_count++;
}
else
{
T* buf=new T[f_size+=f_step];
for(unsigned int i=0;i<=f_count;i++) buf[i]=List[i];
T* buf0=List;
List=buf;
delete[] buf0;
List[f_count]=item;
f_count++;
}
};
void push_back(T item){add(item);};
void del(T item) //удаляем элемент и сдвигаем все элементы на 1 в лево
{
unsigned int cnt=0;
bool b=false;
for(unsigned int i=0;i<f_count;i++)
{
//if(List[i]==item){cnt--; b=true;}
if(List[i]==item){b=true; continue;}
List[cnt]=List[i];
cnt++;
}
if(b)
{
f_count--;
}
};
bool del(unsigned int pos) //удаляем элемент и сдвигаем все элементы на 1 в лево
{
if(pos>=f_count)return false;
f_count--;
for(unsigned int i=pos;i<f_count;i++) List[i]=List[i+1];
return true;
};
bool pop_front(){ return del(0); };
T& front(){return List[0];};
T& get(unsigned int i){return List[i];};
T& operator[](unsigned int i){return List[i];};
bool Position(T item, unsigned int &pos) //Найти позицию элемента в списке перебором
{
for(unsigned int i=0;i<f_count;i++)
if(List[i]==item) { pos=i; return true; }
return false;
};
void clear()
{
unsigned int cnt=f_count;
f_count=0;
T* tmp=List;
f_size=f_step;
List=new T[f_step];
delete[] tmp;
};
};
//------------------------------------------------------------------------------
#endif /* UTILITY_H_ */

427
lib/wxCairo.cpp Normal file
View File

@ -0,0 +1,427 @@
/***************************************************************
* Name: wxCairo.cpp
* Purpose: Code for Application Frame
* Author: Igor I (info@tiptopcity.com)
* Created: 2009-05-24
* Copyright: Igor I (www.tiptopcity.com)
* License:
**************************************************************/
#ifdef WX_PRECOMP
#include "wx_pch.h"
#endif
//------------------------------------------------------------------------------
//#include <cairo/cairo-svg.h>
//#include <librsvg/rsvg.h>
//#include <librsvg/rsvg-cairo.h>
#if defined(_WIN32) || defined(_WINDOWS) || defined(_BORLAND) || defined(__BORLANDC__)
#include <cairo/cairo-win32.h>
#else
#endif
#include <cairo/cairo.h>
//#include <librsvg/rsvg.h>
//#include <librsvg/rsvg-cairo.h>
//#include <svg_cairo.c>
#include <math.h>
#include <string.h>
#include "wxCairo.h"
#include "stdTools.h"
//#include "wxgui/debug.h"
//------------------------------------------------------------------------------
struct stdword{
std::string str;
int width;
};
//------------------------------------------------------------------------------
wxCairo::wxCairo()
{
glId=0;
m_buffer=NULL;
m_surface=NULL;
m_cr=NULL;
m_format = CAIRO_FORMAT_RGB24;
m_width=0; m_height=0;
}
//------------------------------------------------------------------------------
wxCairo::~wxCairo()
{
if(m_buffer!=NULL) delete m_buffer;
if(m_surface!=NULL) cairo_surface_destroy(m_surface);
if(m_cr!=NULL) cairo_destroy(m_cr);
}
//------------------------------------------------------------------------------
unsigned char* wxCairo::CreateBuffer(int width,int height)
{
if(width!=m_width || m_height!=height)
{
if(m_buffer!=NULL) delete m_buffer;
m_width=width; m_height=height;
m_buffer = new unsigned char[width*height*4]; //RGBA
memset(m_buffer, 0, width*height*4); //Обнулим массив
Init();
return m_buffer;
}else
{
memset(m_buffer, 0, width*height*4); //Обнулим(отчистим) массив
return m_buffer;
}
}
//------------------------------------------------------------------------------
bool wxCairo::Init()
{
if(m_surface!=NULL) cairo_surface_destroy(m_surface);
if(m_cr!=NULL) cairo_destroy(m_cr);
m_surface = cairo_image_surface_create_for_data(m_buffer, m_format, m_width, m_height, m_width*4);
m_cr = cairo_create(m_surface);
cairo_set_antialias(m_cr, CAIRO_ANTIALIAS_NONE);
return true;
}
//------------------------------------------------------------------------------
/*void wxCairo::Draw(wxPaintDC& dc)
{
// Convert from Cairo RGB24 format to wxImage BGR format.
unsigned char *dRGB = new unsigned char[m_width*m_height*3];
//unsigned char *dA = new unsigned char[m_width*m_height];
for(int y=0;y<m_height;y++)
{
for(int x=0;x<m_width;x++)
{
dRGB[x*3+y*m_width*3] = m_buffer[x*4+2+y*m_width*4];
dRGB[x*3+1+y*m_width*3] = m_buffer[x*4+1+y*m_width*4];
dRGB[x*3+2+y*m_width*3] = m_buffer[x*4+y*m_width*4];
//dA[x*y] = 255;
}
}
// Blit final image to the screen.
//wxImage img=wxImage(m_width, m_height, dRGB, dA, true);
wxImage img=wxImage(m_width, m_height, dRGB, true);
//if(img.HasAlpha())
//{
wxBitmap m_bitmap(img);
dc.DrawBitmap(m_bitmap, 0, 0, true);
//}
delete dRGB;
//delete dA;
}*/
//------------------------------------------------------------------------------
//Нарисуем чтонибудь для примера в текущем буфере
bool wxCairo::Test()
{
// White background.
//cairo_set_source_rgb(m_cr, 1.0, 1.0, 1.0);
//cairo_rectangle(m_cr, 0, 0, m_width, m_height);
//cairo_fill(m_cr);
//draw stuff
cairo_select_font_face(m_cr, "serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(m_cr, 32.0);
cairo_set_source_rgb(m_cr, 0.0, 0.0, 1.0);
cairo_move_to(m_cr, 10.0, 50.0);
std::string str="Привет мир!";
//const wxCharBuffer buff = str.mb_str(wxConvUTF8);
cairo_show_text (m_cr, str.c_str());
//Curve
double x=25.6, y=128.0;
double x1=102.4, y1=230.4,
x2=153.6, y2=25.6,
x3=230.4, y3=128.0;
cairo_move_to (m_cr, x, y);
cairo_curve_to (m_cr, x1, y1, x2, y2, x3, y3);
cairo_set_line_width (m_cr, 10.0);
cairo_stroke (m_cr);
cairo_set_source_rgba (m_cr, 1, 0.2, 0.2, 0.6);
cairo_set_line_width (m_cr, 6.0);
cairo_move_to (m_cr,x,y); cairo_line_to (m_cr,x1,y1);
cairo_move_to (m_cr,x2,y2); cairo_line_to (m_cr,x3,y3);
cairo_stroke (m_cr);
//SVG
/*cairo_surface_t *surface;
//cairo_t *cr;
surface = cairo_svg_surface_create("Svg.svg", 390, 60);
cr = cairo_create(surface);
cairo_set_source_rgb(m_cr, 0, 0, 0);
cairo_select_font_face (m_cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size (m_cr, 40.0);
cairo_move_to(m_cr, 10.0, 50.0);
cairo_show_text(m_cr, "Disziplin ist Macht.");
cairo_surface_destroy(surface);
//cairo_destroy(cr);*/
/*double IMAGE_WIDTH = 256;
double IMAGE_HEIGHT = 256;
cairo_surface_t* surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, IMAGE_WIDTH, IMAGE_HEIGHT);
cairo_t* cr = cairo_create(surface);
cairo_scale(cr, IMAGE_WIDTH, IMAGE_HEIGHT);
svg_cairo_t* svgc;
svg_cairo_create(&svgc);
gtk_init(&argc, &argv); // 1) doesn't work
svg_cairo_parse(svgc, "data/home.svg");
// gtk_init(&argc, &argv); // 2) works
unsigned w, h;
svg_cairo_get_size(svgc, &w, &h);
cairo_scale(cr, 1.0 / w, 1.0 / h);
svg_cairo_render(svgc, cr);
svg_cairo_destroy(svgc);
cairo_surface_write_to_png(surface, "out.png");
cairo_destroy(cr);
cairo_surface_destroy(surface);
return 0;*/
return true;
}
//------------------------------------------------------------------------------
void wxCairo::MoveTo(double x, double y)
{
cairo_move_to(m_cr,x,y);
}
//------------------------------------------------------------------------------
void wxCairo::LineTo(double x, double y)
//void wxCairo::LineTo(double y, double x)
{
cairo_line_to(m_cr,x,y);
}
//------------------------------------------------------------------------------
void wxCairo::SetLineWidth(double width)
{
cairo_set_line_width(m_cr, width);
}
//------------------------------------------------------------------------------
void wxCairo::ShowText(std::wstring& str)
{
std::string utf8=convUTF16ToUTF8(str);
cairo_show_text (m_cr, utf8.c_str());
}
//------------------------------------------------------------------------------
void wxCairo::SetSourceRGBA(double red, double green, double blue, double alpha)
{
cairo_set_source_rgba(m_cr, red, green, blue, alpha);
}
//------------------------------------------------------------------------------
void wxCairo::SetSourceRGB(double red, double green, double blue)
{ cairo_set_source_rgb(m_cr, red, green, blue);
}
//------------------------------------------------------------------------------
void wxCairo::Rectangle (double x, double y, double width, double height)
{ cairo_rectangle (m_cr, x, y, width, height);
}
//------------------------------------------------------------------------------
//Не рисовать то что не входит в последний геом объект
void wxCairo::Clip()
{ cairo_clip(m_cr);
}
//------------------------------------------------------------------------------
void wxCairo::ResetClip()
{ cairo_reset_clip(m_cr);
}
//------------------------------------------------------------------------------
void wxCairo::Fill()
{ cairo_fill(m_cr);
}
//------------------------------------------------------------------------------
//Обводка
//Операция cairo_stroke() применяет виртуальный карандаш вдоль контура.Это позволяет источнику передать через маску тонкую(или толстую) линию вдоль контура, в соответствие с карандашной толщиной линии, стилем точек, и наконечниками линии.
void wxCairo::Stroke()
{ cairo_stroke(m_cr);
}
//------------------------------------------------------------------------------
//Преобразовать рисунок в битовый массив
void wxCairo::toBitArray(unsigned char* bitArray)
{
int pos = 0;
for (int y = 0; y<m_height; y++)
{
for (int x = 0; x<m_width; x++)
{
unsigned char r = m_buffer[x * 4 + 2 + y*m_width * 4];
unsigned char g = m_buffer[x * 4 + 1 + y*m_width * 4];
unsigned char b = m_buffer[x * 4 + y*m_width * 4];
unsigned char px = (r + g + b) / 3.0f;
int posB=floor(pos / 8.0f); //Номер байта
if (px < 127) //Чёрный это 1
{
setBit(&bitArray[posB], pos - posB * 8, true);
//
}else //Белый это 0
{
setBit(&bitArray[posB], pos - posB * 8, false);
}
pos++;
}
}
}
//------------------------------------------------------------------------------
void wxCairo::setBit(unsigned char *mas, const unsigned char pos, bool val)
{
unsigned char mask = 128;
unsigned char loc = pos / 8;
mask = mask >> (pos - loc * 8);
if (val) mas[loc] = mas[loc] | mask;
else
{
mask = ~mask; //Отрицание
mas[loc] = mas[loc] & mask;
}
}
//------------------------------------------------------------------------------
void wxCairo::setFontface(std::string family,bool slant,bool weight)
{
cairo_font_slant_t s;
if (slant) s = CAIRO_FONT_SLANT_ITALIC; else s = CAIRO_FONT_SLANT_NORMAL;
cairo_font_weight_t w;
if (weight) w = CAIRO_FONT_WEIGHT_BOLD; else w = CAIRO_FONT_WEIGHT_NORMAL;
cairo_select_font_face(m_cr,family.c_str(),s,w);
}
//------------------------------------------------------------------------------
void wxCairo::setFontface(const char *family, cairo_font_slant_t slant, cairo_font_weight_t weight)
{
cairo_select_font_face(m_cr, family, slant, weight);
}
//------------------------------------------------------------------------------
//the new font size, in user space units
void wxCairo::setFontSize(double size)
{
cairo_set_font_size(m_cr,size);
}
//------------------------------------------------------------------------------
void wxCairo::seveToPNG(std::string filePath)
{
cairo_surface_write_to_png(m_surface, filePath.c_str());
}
//------------------------------------------------------------------------------
//Ширина текста в пикселях
double wxCairo::getTextWidth(std::wstring& str)
{
std::string utf8 = convUTF16ToUTF8(str);
cairo_text_extents_t ext;
cairo_text_extents(m_cr, utf8.c_str(), &ext);
return ext.width;
}
//------------------------------------------------------------------------------
//Высота текста в пикселях
double wxCairo::getTextHeight(std::wstring& str)
{
std::string utf8 = convUTF16ToUTF8(str);
cairo_text_extents_t ext;
cairo_text_extents(m_cr, utf8.c_str(), &ext);
return ext.height;
}
//------------------------------------------------------------------------------
//Вывести текст по центру области
void wxCairo::ShowTextCenter(std::wstring& str, int xStart, int xEnd, int y)
{
std::string utf8 = convUTF16ToUTF8(str);
cairo_text_extents_t ext;
cairo_text_extents(m_cr, utf8.c_str(), &ext);
ext.width = xStart + (((xEnd - xStart) / 2.0f) - (ext.width / 2.0f));
cairo_move_to(m_cr, ext.width, y);
cairo_show_text(m_cr, utf8.c_str());
}
//------------------------------------------------------------------------------
//Вывести текст с переносом на следующую строку с выравниванием по словам, высота символов однирна
//xStart начало для вычисления центра
//xEnd конец для вычисления центра
//y высота
void wxCairo::ShowTextBR(std::wstring& str, int xStart, int xEnd, int y)
{
/*stdword line;
std::vector<stdword> parts;
int maxH=0;
std::vector<std::wstring> array =split(str,L' ');
for (std::vector<std::wstring>::iterator it = array.begin() ; it != array.end(); ++it)
{
std::wstring s=*it;
line.word = convUTF16ToUTF8(s);
cairo_text_extents(m_cr, line.word.c_str(), &line.ext);
line.ext.width+=line.ext.width/s.length(); //Так как пробел почемуто обрезается при расчёте ширины
parts.push_back(line);
if(maxH<line.ext.height) maxH=line.ext.height;
}
int w=xStart;
for (std::vector<stdword>::iterator it = parts.begin() ; it != parts.end(); ++it)
{
line=*it;
if(w+line.ext.width<xEnd)
{
cairo_move_to(m_cr, w, y);
w+=line.ext.width;
}else
{
w=xStart;
y+=maxH;
cairo_move_to(m_cr, w, y);
w+=line.ext.width;
}
cairo_show_text(m_cr, line.word.c_str());
}*/
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Вывести текст с переносом на следующую строку с выравниванием по словам, высота символов однирна
//xStart начало для вычисления центра
//xEnd конец для вычисления центра
//y высота
void wxCairo::ShowTextCenterBR(std::wstring& str, int xStart, int xEnd, int y)
{
std::vector<std::wstring> array =split(str,L' '); //Для разбивки на слова
int height=0; //Высота символов
std::vector<stdword> parts; //Для разбивки на строки
stdword line;
line.width=0;
line.str="";
for (std::vector<std::wstring>::iterator it = array.begin() ; it != array.end(); ++it)
{
std::wstring s=*it;
std::string word = convUTF16ToUTF8(s);
cairo_text_extents_t ext;
cairo_text_extents(m_cr, word.c_str(), &ext);
ext.width+=ext.width/s.length(); //Так как пробел почемуто обрезается при расчёте ширины
if(height<ext.height) height=ext.height; //Высота символов
if(line.width+ext.width<xEnd-xStart)
{
line.width+=ext.width;
line.str+=word+' ';
}else
{
parts.push_back(line);
line.width=0;
line.str="";
}
}
parts.push_back(line);
//Отображаю текст по центру
for (std::vector<stdword>::iterator it = parts.begin() ; it != parts.end(); ++it)
{
stdword line=*it;
int width = xStart + (((xEnd - xStart) / 2.0f) - (line.width / 2.0f));
cairo_move_to(m_cr, width, y);
cairo_show_text(m_cr, line.str.c_str());
y+=height;
}
}
//------------------------------------------------------------------------------

63
lib/wxCairo.h Normal file
View File

@ -0,0 +1,63 @@
/***************************************************************
* Name: wxCairo.h
* Purpose: Defines Application Frame
* Author: Igor I (info@tiptopcity.com)
* Created: 2010-11-14
* Copyright: Igor I (tiptopcity.com)
* License: http://wikipedia.org/wiki/LGPL
**************************************************************/
#ifndef _WX_CAIRO_H_
#define _WX_CAIRO_H_
//#include <wx/wx.h>
#include <cairo/cairo.h>
#include <string>
class wxCairo
{
private:
int m_width,m_height; //Размер буфера
cairo_t* m_cr;
cairo_surface_t* m_surface;
cairo_format_t m_format;
void setBit(unsigned char *mas, const unsigned char pos, bool val);
public:
unsigned int glId; //Идентификатор GL материала
unsigned char* m_buffer; //Рисунок RGBA
wxCairo();
~wxCairo();
cairo_t* getCairo() { return m_cr; };
unsigned char* CreateBuffer(int w,int h); //Создаст буфер если изменились его размеры
bool Init();
bool Test();
//void Draw(wxPaintDC& dc); //Вывести на экран
void Fill();
void Stroke(); //Обводка
void MoveTo(double x, double y);
void LineTo(double x, double y);
void SetLineWidth(double width);
void SetSourceRGBA(double red, double green, double blue, double alpha);
void SetSourceRGB(double red, double green, double blue);
void Rectangle (double x, double y, double width, double height);
void Clip();
void ResetClip();
void ShowText(std::wstring& utf8);
void ShowTextCenter(std::wstring& utf8,int xStart,int xEnd,int y);
void ShowTextBR(std::wstring& str, int xStart, int xEnd, int y);
void ShowTextCenterBR(std::wstring& str, int xStart, int xEnd, int y);
void setFontface(const char *family, cairo_font_slant_t slant, cairo_font_weight_t weight);
void setFontface(std::string family, bool slant, bool weight);
void setFontSize(double size);
double getTextWidth(std::wstring& str);
double getTextHeight(std::wstring& str);
void toBitArray(unsigned char* bitArray);
void seveToPNG(std::string filePath);
};
#endif

822
lib/wxTools.cpp Normal file
View File

@ -0,0 +1,822 @@
//---------------------------------------------------------------------------
#pragma hdrstop
//#include "stdafx.h"
#include <wx/msw/msvcrt.h>
#include "wxTools.h"
//#include <sstream>
#include <Math.h>
//#include <iostream>
//#include <locale>
//#include <string>
//#include <vector>
//#include <WinBase.h>
//#include <time.h>
#if defined( _VC )
#include < ctime >
#endif
#if defined( _BORLAND )
#include <vcl.h>
#endif
#include <tchar.h>
#include <wx/msgdlg.h>
#include <wx/stdpaths.h>
#include <wx/txtstrm.h>
#include <wx/filename.h>
#include <wx/zipstrm.h>
#include <sys/stat.h>
#include <wx/string.h>
#include <wx/intl.h>
#include <wx/textfile.h>
#include <wx/url.h>
//#include <openssl/md5.h>
#include <sstream>
#include "tcDebug.h"
//---------------------------------------------------------------------------
//#pragma package(smart_init)
//---------------------------------------------------------------------------
//#if defined( _WX )
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned char* getDataFromURL(const wxString url,unsigned int* size)
{
RListOne* first=NULL,* next=NULL; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned int bufSize=512; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> (<28> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)
*size=0; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
wxURL murl(url);
if (murl.GetError() == wxURL_NOERR)
{
wxInputStream* is = murl.GetInputStream();
if(is)
{
unsigned char* buf=new unsigned char[bufSize];
first=new RListOne;
first->next=NULL; first->size=0; first->data=new unsigned char[bufSize];
next=first;
for(;;)
{
is->Read(buf, bufSize);
size_t n = is->LastRead();
if ( n == 0 ) break;
*size+=n;
for(size_t i=0;i<n;i++) //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> "memcpy(newbuf, buf, sz)"
{
if(next->size==bufSize)
{
next->next=new RListOne;
next=next->next;
next->next=NULL; next->size=0; next->data=new unsigned char[bufSize];
}
next->data[next->size]=buf[i];
next->size++;
}
}
delete[] buf;
delete is;
};
};
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned char* data=NULL;
if(*size==0) return data;
data=new unsigned char[*size];
unsigned int pos=0;
while(first!=NULL)
{
memcpy(&data[pos],first->data,first->size);
pos+=first->size;
next=first;
first=first->next;
delete[] next->data; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
delete next; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
}
return data;
}
//------------------------------------------------------------------------------
wxString getStringOnUrl(const wxString path)
{
//size_t iRead=0;
wxString res = _T("");
wxURL url(path);
((wxProtocol&)url.GetProtocol()).SetTimeout(100);
//url->SetProxy(wxT("proxy.localdomain:80"));
if (url.GetError() == wxURL_NOERR)
{
wxInputStream *in_stream = url.GetInputStream();
if( in_stream )
{
size_t st=102400; //<2F><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 100 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
size_t sz=st; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned int pos=0;
char* buf = new char[sz];
do
{
//<2F><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
if(pos>=sz)
{
char* newbuf = new char[sz+st];
memcpy (newbuf, buf, sz);
delete[] buf;
buf=newbuf;
sz+=st;
}
buf[pos]=in_stream->GetC();
pos++;
}
while (in_stream->LastRead()>0);
res = wxString::FromUTF8(buf,pos-1);
delete[] buf;
delete in_stream;
}
}
//delete url;
return res;
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> url <20> <20><><EFBFBD><EFBFBD> path
bool getFileOnWebServer(const wxString url,const wxString path)
{
bool res=true;
wxURL murl(url);
if (murl.GetError() == wxURL_NOERR)
{
wxInputStream* is = murl.GetInputStream();
if(is)
{
wxFileName fn(path);
if(!wxFileName::DirExists(fn.GetPath())) wxFileName::Mkdir(fn.GetPath());
wxFile fOut(path, wxFile::write);
if(fOut.IsOpened())
{
char buf[1000];
for(;;)
{
is->Read(buf, 1000);
size_t n = is->LastRead();
if ( n == 0 ) break;
fOut.Write(buf, n);
}
}else res=false;
delete is;
}else res=false;
}else res=false;
return res;
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> md5 <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/*wxString md5String(wxString val)
{
if(val==_T("")) return _T("");
wxString result=_T("");
unsigned char md5digest[MD5_DIGEST_LENGTH];
wxCharBuffer cb=val.ToAscii();
size_t len=strlen((const char*)cb);
const unsigned char* buf=(const unsigned char*)(const char*)cb;
MD5(buf,len, md5digest);
for(unsigned int i=0;i<MD5_DIGEST_LENGTH;i++)
{
result.Printf(result+_T("%02x"),md5digest[i]);
};
return result;
}*/
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> 2<><32> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
wxString getSubString(wxString str, wxString bracket1, wxString bracket2)
{
int pos1=str.Find(bracket1);
int pos2=str.Find(bracket2);
if((pos1!=wxNOT_FOUND)&&(pos2!=wxNOT_FOUND))
return str.SubString(pos1+bracket1.Len(),pos2-1);
return _T("");
}
//------------------------------------------------------------------------------
/*wxString getExecutablePath()
{
wxString path=_T("");
wxStandardPaths *StandardPaths = new wxStandardPaths();
path = StandardPaths->GetExecutablePath();
delete StandardPaths;
return path;
return "";
}*/
//------------------------------------------------------------------------------
wxString getAfterFirst(wxString str,wxString separator)
{
int p=str.Find(separator);
if(p!=wxNOT_FOUND)
{
return str.SubString(p+separator.Len(),str.Len()-1);
}
return _T("");
}
//------------------------------------------------------------------------------
wxString getAfterLast(wxString str,wxChar separator)
{
return str.AfterLast(separator);
}
//------------------------------------------------------------------------------
wxString getBeforeFirst(wxString str,wxString separator)
{
int p=str.Find(separator);
if(p!=wxNOT_FOUND) return str.SubString(0,p-1);
return _T("");
}
//------------------------------------------------------------------------------
wxString getBeforeLast(wxString str,wxChar separator)
{
return str.BeforeLast(separator);
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> find <20> sors <20><> repl (wxString::Replace)
wxString replaceStrings(wxString sors,wxString find,wxString repl)
{
if(find==repl) return sors;
wxString rez=_T("");
int p=sors.Find(find);
while(p!=wxNOT_FOUND)
{
rez+=sors.SubString(0,p-1)+repl;
sors=sors.SubString(p+find.Len(),sors.Len()-1);
p=sors.Find(find);
}
rez+=sors;
return rez;
}
//------------------------------------------------------------------------------
void replaseChars(wxString& str,wxChar oldCh,wxChar newCh)
{
str.Replace(&oldCh,&newCh,true);
}
//------------------------------------------------------------------------------
wxString IntToStr(unsigned long i)
{
wxString str=_T("");
str.Printf(_T("%u"),i);
return str;
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> float <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
wxString getFloatString(wxString str)
{
wxString res=_T("");
for(unsigned int i=0;i<str.length();i++)
{
if(str[i]==_T('-') || str[i]==_T('0') ||str[i]==_T('1') ||str[i]==_T('2') ||str[i]==_T('3') ||str[i]==_T('4') ||str[i]==_T('5') ||str[i]==_T('6') ||str[i]==_T('7') ||str[i]==_T('8') || str[i]==_T('9') || str[i]==_T('.'))
res+=str[i];
}
return res;
}
//------------------------------------------------------------------------------
wxString FloatToStr(float f, int numdigits)
{
wxString Result;
if (numdigits <= 0)
{
Result = Result.Format(_T("%f"),f);
}
else
{
wxString strNumFormat = wxString::Format(_T("%%0.%df"),numdigits);
Result = Result.Format(strNumFormat,f);
}
return Result;
}
//------------------------------------------------------------------------------
//<2F><> double <20> String
wxString DoubleToStr(double d, int numdigits)
{
wxString Result;
Result = Result.Format(_T("%.15f"),d);
Result.Replace(wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT,wxLOCALE_CAT_NUMBER),wxT(".")); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
if(numdigits>0)
{
size_t pos=Result.Find(_T('.'));
if(pos!=wxNOT_FOUND)
{
Result=Result.Remove(pos+numdigits+1);
for(size_t i=Result.length();i>pos;i--)
if(Result[i-1]==_T('0'))
Result=Result.Remove(i-1);
else
break; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if(Result.length()==pos+1)
Result=Result.Remove(pos); //<2F><><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
}
}else
if(numdigits==0)
{ size_t pos=Result.Find(_T('.'));
Result=Result.Remove(pos);
}
return Result;
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> UTF8 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 256 <20><><EFBFBD><EFBFBD>
void saveUTF8String(wxOutputStream *os, wxString str)
{
const wxCharBuffer buff = str.mb_str(wxConvUTF8);
size_t len0 = strlen(buff);
unsigned char len1=0;
if(len0<=256) len1=(unsigned char)len0;
os->Write(&len1,1);
if(len1>0) os->Write(buff,len1);
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> UTF8 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 256 <20><><EFBFBD><EFBFBD>
void saveUTF8String(wxFFile *os, wxString str)
{
const wxCharBuffer buff = str.mb_str(wxConvUTF8);
size_t len0 = strlen(buff);
unsigned char len1=0;
if(len0<=256) len1=(unsigned char)len0;
os->Write(&len1,1);
if(len1>0) os->Write(buff,len1);
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> UTF8 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> 65535 <20><><EFBFBD><EFBFBD>
void saveUTF8String2(wxOutputStream *os, wxString str)
{
const wxCharBuffer buff = str.mb_str(wxConvUTF8);
size_t len0 = strlen(buff);
unsigned short len1=0;
if(len0<=65535) len1=(unsigned short)len0;
os->Write(&len1,2);
if(len1>0) os->Write(buff,len1);
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> (<28><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)
wxString cutFirstSubStr(wxString &string,wxChar separator)
{
wxString str=string.BeforeFirst(separator);
string=string.AfterFirst(separator);
return str;
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
wxString cutFirstSubStr(wxString &string,char ch)
{
wxString str=string.BeforeFirst(ch);
string=string.AfterFirst(ch);
return str;
}
//------------------------------------------------------------------------------
int StrToInt(wxString str)
{
long dblVal;
str.ToLong(&dblVal);
return dblVal;
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int StrFullToInt(wxString str)
{
wxString tmp;
for(int i=0;i<(int)str.length();i++)
{
if(str[i]=='-' ||str[i]=='.' || str[i]=='0' || str[i]=='1' || str[i]=='2' || str[i]=='3' || str[i]=='4' || str[i]=='5' || str[i]=='6' || str[i]=='7' || str[i]=='8' || str[i]=='9')
{
tmp+=str[i];
}
}
long dblVal;
tmp.ToLong(&dblVal);
return dblVal;
}
//------------------------------------------------------------------------------
unsigned int StrFullToUInt(wxString str)
{
wxString tmp;
for(int i=0;i<(int)str.length();i++)
{
if(str[i]=='.' || str[i]=='0' || str[i]=='1' || str[i]=='2' || str[i]=='3' || str[i]=='4' || str[i]=='5' || str[i]=='6' || str[i]=='7' || str[i]=='8' || str[i]=='9')
{
tmp+=str[i];
}
}
unsigned long dblVal;
tmp.ToULong(&dblVal);
return dblVal;
}
//------------------------------------------------------------------------------
double StrToDouble(wxString str)
{
double val;
str.ToDouble(&val);
return val;
}
//******************************************************************************
wxHtmlOpeningStatus MyHtmlWindow::OnOpeningURL(wxHtmlURLType WXUNUSED(type),
const wxString& WXUNUSED(url),
wxString *WXUNUSED(redirect)) const
{
return wxHTML_OPEN;
}
//------------------------------------------------------------------------------
void MyHtmlWindow::OnLinkClicked(const wxHtmlLinkInfo& link)
{
wxLaunchDefaultBrowser(link.GetHref());
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
TTask::TTask(int delay):wxThread(wxTHREAD_DETACHED)
{ critsectA=new wxCriticalSection();
critsectR=new wxCriticalSection();
listAnswer=new TSimpleList<RClientData*>(10,false);
listRequest=new TSimpleList<RClientData*>(10,false);
m_Cancel=false;
m_delay=delay;
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
if( Create() != wxTHREAD_NO_ERROR )
{ //wxLogError(_T("Can<61>t create thread!"));
}else Run();
}
//------------------------------------------------------------------------------
void* TTask::Entry() //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
{ RClientData* d;
while(!m_Cancel)
{
d=getTask();
if(d)
{ //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if(d->url!=_T(""))
d->data=getDataFromURL(d->url,&d->size);
addAnswer(d);
}
Sleep(m_delay);
}
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
d=getTask();
while(d!=NULL)
{ delete d;
d=getTask();
}
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
d=getAnswer();
while(d!=NULL)
{ delete d;
d=getAnswer();
}
return NULL;
}
//------------------------------------------------------------------------------
wxString TAMas::getAt(wxString id)
{
size_t i=0;
while(m_id.Count()>i)
{
if(m_id.Item(i)==id) return m_val.Item(i);
i++;
}
return _T("");
}
//------------------------------------------------------------------------------
void TAMas::setAt(wxString id,wxString val)
{
m_id.Add(id);
m_val.Add(val);
}
//------------------------------------------------------------------------------
void TAMas::Copy(TAMas& res)
{
for(unsigned int i=0;i<res.m_id.Count();i++)
{
setAt(res.m_id.Item(i),res.m_val.Item(i));
}
}
//------------------------------------------------------------------------------
//******************************************************************************
TIniFile::TIniFile(wxString path)
{
this->path=path;
first=NULL;
if (wxFileExists(path))
{
wxTextFile* TextFile = new wxTextFile();
TextFile->Open(path);
if (TextFile->Eof())
{
TextFile->Close();
delete TextFile;
}else
{
wxString str;
wxString section;
str = TextFile->GetFirstLine();
while(true)
{
if (str.Find('[')>=0)
{
section=str.AfterFirst('[').BeforeLast(']');
}
if (str.Find('=')>=0)
{
TIniStruct* inistr= new TIniStruct;
inistr->next=NULL;
inistr->section=section;
inistr->ident=str.BeforeFirst('=');
inistr->value=str.AfterFirst('=');
if (first==NULL)
{
first=inistr;
last=inistr;
}else
{
last->next=inistr;
last=inistr;
}
}
if (TextFile->Eof()) break;
str = TextFile->GetNextLine();
}
TextFile->Close();
delete TextFile;
}
}
}
//------------------------------------------------------------------------------
TIniFile::~TIniFile()
{
TIniStruct* inistrdel;
TIniStruct* inistr = first;
while (inistr!=NULL)
{
inistrdel=inistr;
inistr=inistr->next;
delete inistrdel;
}
}
//------------------------------------------------------------------------------
wxString TIniFile::ReadString(wxString Section,wxString Ident,wxString Default)
{
TIniStruct* inistr = first;
while (inistr!=NULL)
{
if ((inistr->section==Section) && (inistr->ident==Ident))
{
return inistr->value;
}
inistr=inistr->next;
}
return Default;
}
//------------------------------------------------------------------------------
float TIniFile::ReadFloat(wxString Section,wxString Ident,float Default)
{
wxString Result;
Result = Result.Format(_T("%f"),Default);
Result=ReadString(Section,Ident,Result);
double dblVal;
Result.Replace(wxT("."), wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT,wxLOCALE_CAT_NUMBER));
if(Result.ToDouble(&dblVal)) return dblVal;
else return 0;
}
//------------------------------------------------------------------------------
long TIniFile::ReadLong(wxString Section,wxString Ident,long Default)
{
wxString Result;
Result = Result.Format(_T("%d"),Default);
Result=ReadString(Section,Ident,Result);
long dblVal;
Result.ToLong(&dblVal);
return dblVal;
}
//------------------------------------------------------------------------------
unsigned long TIniFile::ReadULong(wxString Section,wxString Ident,unsigned long Default)
{
wxString Result;
Result = Result.Format(_T("%u"),Default);
Result=ReadString(Section,Ident,Result);
unsigned long dblVal;
Result.ToULong(&dblVal);
return dblVal;
}
//------------------------------------------------------------------------------
bool TIniFile::ReadBool(wxString Section,wxString Ident,bool Default)
{
wxString Result;
if(Default) Result = _T("1"); else Result = _T("0");
Result=ReadString(Section,Ident,Result);
if(Result==_T("1")) return true; else return false;
}
//------------------------------------------------------------------------------
void TIniFile::WriteString(wxString Section,wxString Ident,wxString Value)
{
//<2F><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
bool b=false;
TIniStruct* lastSel = NULL; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
TIniStruct* inistr = first;
while (inistr!=NULL)
{
if(inistr->section==Section)
{
lastSel=inistr;
if(inistr->ident==Ident)
{ inistr->value=Value;
b=true;
break;
}
}
inistr=inistr->next;
}
//<2F><><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (!b)
{
TIniStruct* inistr= new TIniStruct;
inistr->next=NULL;
inistr->section=Section;
inistr->ident=Ident;
inistr->value=Value;
if (first==NULL)
{
first=inistr;
last=inistr;
}else
{
if(lastSel==NULL)
{
last->next=inistr;
last=inistr;
}
else
{
inistr->next=lastSel->next;
lastSel->next=inistr;
}
}
}
}
//------------------------------------------------------------------------------
void TIniFile::WriteFloat(wxString Section,wxString Ident,float Value)
{
wxString Result;
Result = Result.Format(_T("%f"),Value);
Result.Replace(wxLocale::GetInfo(wxLOCALE_DECIMAL_POINT,wxLOCALE_CAT_NUMBER),wxT("."));
WriteString(Section,Ident,Result);
}
//------------------------------------------------------------------------------
void TIniFile::WriteLong(wxString Section,wxString Ident,long Value)
{
wxString Result;
Result = Result.Format(_T("%d"),Value);
WriteString(Section,Ident,Result);
}
//------------------------------------------------------------------------------
void TIniFile::WriteULong(wxString Section,wxString Ident,unsigned long Value)
{
wxString Result;
Result = Result.Format(_T("%u"),Value);
WriteString(Section,Ident,Result);
}
//------------------------------------------------------------------------------
void TIniFile::WriteBool(wxString Section,wxString Ident,bool Value)
{
wxString Result;
if(Value) Result =_T("1"); else Result =_T("0");
WriteString(Section,Ident,Result);
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD>
void TIniFile::Save()
{
wxTextFile* TextFile = new wxTextFile();
if(!wxFileExists(path)) TextFile->Create(path);
TextFile->Open(path);
if(TextFile->IsOpened())
{
TextFile->Clear();
wxString LastSection=_T("");
TIniStruct* inistr = first;
while (inistr!=NULL)
{
if (inistr->section!=LastSection)
{
TextFile->AddLine(_T("[")+inistr->section+_T("]"));
LastSection=inistr->section;
}
TextFile->AddLine(inistr->ident+_T("=")+inistr->value);
inistr=inistr->next;
}
TextFile->Write();
TextFile->Close();
}
delete TextFile;
}
//******************************************************************************
TFileList::TFileList()
{
size=20;
List = new LStream*[size];
count=0;
}
//------------------------------------------------------------------------------
TFileList::~TFileList()
{
for(unsigned int i=0;i<count;i++)
{
delete List[i]->is;
free(List[i]->data);
delete List[i];
}
delete[] List;
}
//------------------------------------------------------------------------------
void TFileList::add(wxInputStream *is,wxString name)
{
if(count>=size)return;
LStream *ls=new LStream;
ls->name=name;
ls->size=(unsigned int)is->GetSize();
ls->data=(char*)malloc(ls->size); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
is->Read(ls->data,ls->size);
ls->is=new wxMemoryInputStream(ls->data,ls->size);
List[count]=ls;
count++;
}
//------------------------------------------------------------------------------
wxInputStream* TFileList::get(wxString name)
{
for(unsigned int i=0;i<count;i++)
{
if(List[i]->name.Lower()==name.Lower()) return List[i]->is;
}
return NULL;
}
//------------------------------------------------------------------------------
unsigned int TFileList::getCount()
{
return count;
}
//------------------------------------------------------------------------------
LStream* TFileList::item(unsigned int i)
{
return List[i];
}
//******************************************************************************
//------------------------------------------------------------------------------
//THTTPDownload <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> delete <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> wxTHREAD_DETACHED
THTTPDownload::THTTPDownload(wxEvtHandler *parent,wxString url,int userInt,wxString userStr,void* userData,MyFuncPtrType userFun):wxThread(wxTHREAD_DETACHED)
{
m_Parent=parent;
m_CD=new RClientData;
m_CD->url=url;
m_CD->clientInt=userInt;
m_CD->clientStr=userStr;
m_CD->clientData=userData;
m_CD->clientFun=userFun;
m_CD->size=0;
m_CD->data=NULL;
m_Cancel=false;
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
if( Create() != wxTHREAD_NO_ERROR )
{ //wxLogError(_T("Can<61>t create thread!"));
}else Run();
}
//------------------------------------------------------------------------------
THTTPDownload::~THTTPDownload()
{
}
//------------------------------------------------------------------------------
void* THTTPDownload::Entry()
{
m_CD->data=getDataFromURL(m_CD->url,&m_CD->size);
//<2F><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if(m_CD->clientFun!=NULL)
{
MyFuncPtrType my_func_ptr=m_CD->clientFun;
(*my_func_ptr)(m_CD->size,m_CD->data,m_CD->clientData);
}
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
if (m_Parent)
{
wxCommandEvent e(wxEVT_COMMAND_BUTTON_CLICKED,wxID_ANY);
e.SetClientData(m_CD);
m_Parent->AddPendingEvent(e); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
}
return NULL;
}
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
/*void THTTPDownload::Cancel()
{
m_Cancel=true;
}*/
//------------------------------------------------------------------------------
//#endif

232
lib/wxTools.h Normal file
View File

@ -0,0 +1,232 @@
//---------------------------------------------------------------------------
#ifndef wxToolsH
#define wxToolsH
//---------------------------------------------------------------------------
#include <wx/string.h>
#include <wx/stream.h>
#include <wx/ffile.h>
#include <wx/html/htmlwin.h>
#include <wx/mstream.h>
#include <wx/msw/msvcrt.h>
#include "structs.h"
//---------------------------------------------------------------------------
typedef unsigned int uint4;
typedef unsigned char uint1;
//---------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
//#if defined( _WX )
//wxString getExecutablePath();
wxString getStringOnUrl(const wxString path); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
bool getFileOnWebServer(const wxString url,const wxString path); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned char* getDataFromURL(const wxString url,unsigned int* size); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> <20> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> (<28><><EFBFBD><EFBFBD>!=NULL <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> uint4 <20><><EFBFBD>-<2D><> <20><><EFBFBD><EFBFBD>)
wxString getBeforeFirst(wxString str,wxString separator);
wxString getBeforeLast(wxString str,wxChar separator);
wxString getAfterFirst(wxString str,wxString separator);
wxString getAfterLast(wxString str,wxChar separator);
wxString getSubString(wxString str, wxString bracket1,wxString bracket2);
wxString replaceStrings(wxString sors,wxString find,wxString repl); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> find <20> sors <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> repl
void replaseChars(wxString& str,wxChar oldCh,wxChar newCh); ///<<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD>
wxString cutFirstSubStr(wxString &string,wxChar separator); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
wxString cutFirstSubStr(wxString &string,char ch); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
wxString getFloatString(wxString str); ///<<3C><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD>
wxString IntToStr(unsigned long i);
wxString FloatToStr(float f, int numdigits = -1);
wxString DoubleToStr(double d, int numdigits = -1);
int StrToInt(wxString str);
int StrFullToInt(wxString str); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned int StrFullToUInt(wxString str); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
double StrToDouble(wxString str);
wxString md5String(wxString val);
wxString loadUTF8String(wxInputStream *is);
wxString loadUTF8String(wxFFile *is);
void saveUTF8String(wxOutputStream *os, wxString str);
void saveUTF8String(wxFFile *os, wxString str);
void saveUTF8String2(wxOutputStream *os, wxString str); //2 <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
//#endif
//------------------------------------------------------------------------------
class MyHtmlWindow : public wxHtmlWindow
{
public:
MyHtmlWindow(wxWindow *parent) : wxHtmlWindow( parent, -1, wxPoint(10,10), wxSize(200,200) ) { }
virtual wxHtmlOpeningStatus OnOpeningURL(wxHtmlURLType WXUNUSED(type),
const wxString& WXUNUSED(url),
wxString *WXUNUSED(redirect)) const;
virtual void OnLinkClicked(const wxHtmlLinkInfo& link);
private:
DECLARE_NO_COPY_CLASS(MyHtmlWindow)
};
//------------------------------------------------------------------------------
typedef float (*MyFuncPtrType)(unsigned int, unsigned char*, void*);
struct RClientData //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
{
wxString url; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
int clientInt; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
wxString clientStr; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
void* clientData; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
MyFuncPtrType clientFun; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> (<28> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>)
//<2F> <20><><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned int size; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned char* data; //<2F><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
};
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD> - <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class TTask: public wxThread
{
protected:
wxCriticalSection* critsectA; //<2F><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
wxCriticalSection* critsectR; //<2F><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
TSimpleList<RClientData*>* listAnswer; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
TSimpleList<RClientData*>* listRequest; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
bool m_Cancel;
int m_delay; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
public:
TTask(int delay);
~TTask()
{
delete critsectA;
delete critsectR;
delete listAnswer;
delete listRequest;
};
void addTask(RClientData* task) //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
{
critsectR->Enter();
listRequest->add(task);
critsectR->Leave();
};
RClientData* getTask() //<2F><><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
{ RClientData* result=NULL;
critsectR->Enter();
if(listRequest->count()>0)
{
result=listRequest->get(0);
listRequest->del((unsigned int)0);
}
critsectR->Leave();
return result;
};
void addAnswer(RClientData* answer)
{
critsectA->Enter();
listAnswer->add(answer);
critsectA->Leave();
};
RClientData* getAnswer() //<2F><><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
{ RClientData* result=NULL;
critsectA->Enter();
if(listAnswer->count()>0)
{
result=listAnswer->get(0);
listAnswer->del((unsigned int)0);
}
critsectA->Leave();
return result;
};
virtual void* Entry(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
void Cancel(){m_Cancel=true;};
};
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
struct TAssoStruct
{
wxString ident;
wxString value;
};
class TAMas
{
public:
wxString getAt(wxString id);
void setAt(wxString id,wxString val);
//void del(wxString id);
void Copy(TAMas& res);
//wxString operator [](int i) { return m_val[i]; };
private:
wxString str;
wxArrayString m_id,m_val;
};
//------------------------------------------------------------------------------
struct TIniStruct
{
TIniStruct *next; //<2F><><EFBFBD><EFBFBD>. <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
wxString section; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
wxString ident; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
wxString value; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
};
class TIniFile
{
private:
wxString path;
TIniStruct *first; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
TIniStruct *last;
public:
TIniFile(wxString path);
virtual ~TIniFile();
wxString ReadString(wxString Section,wxString Ident,wxString Default);
float ReadFloat(wxString Section,wxString Ident,float Default);
long ReadLong(wxString Section,wxString Ident,long Default);
unsigned long ReadULong(wxString Section,wxString Ident,unsigned long Default);
bool ReadBool(wxString Section,wxString Ident,bool Default);
void WriteString(wxString Section,wxString Ident,wxString Value);
void WriteFloat(wxString Section,wxString Ident,float Value);
void WriteLong(wxString Section,wxString Ident,long Value);
void WriteULong(wxString Section,wxString Ident,unsigned long Value);
void WriteBool(wxString Section,wxString Ident,bool Value);
void Save(); //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD>
};
//------------------------------------------------------------------------------
//<2F><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
struct LStream
{
wxMemoryInputStream *is;
wxString name; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>
char *data; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> wxMemoryInputStream <20><> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned int size; //<2F><> <20><><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
};
//------------------------------------------------------------------------------
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
class TFileList
{
private:
LStream **List; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned int count; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
unsigned int size; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> List
public:
TFileList();
~TFileList();
void add(wxInputStream *is,wxString name);
wxInputStream* get(wxString name);
unsigned int getCount();
LStream* item(unsigned int i);
};
//------------------------------------------------------------------------------
extern const wxEventType wxID_DOWNLOAD_COMPLETE;
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> http
class THTTPDownload: public wxThread
{
private:
protected:
wxEvtHandler *m_Parent; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
RClientData* m_CD; //<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
bool m_Cancel;
public:
THTTPDownload(wxEvtHandler *parent,wxString url,int userInt,wxString userStr,void* userData,MyFuncPtrType userFun);
~THTTPDownload();
virtual void* Entry();
//void Cancel();
};
//------------------------------------------------------------------------------
#endif

132
lib/xmlTools.cpp Normal file
View File

@ -0,0 +1,132 @@
//------------------------------------------------------------------------------
#include "xmltools.h"
#include "wxTools.h"
#include "tcDebug.h"
//------------------------------------------------------------------------------
wxXmlNode* findNode(wxXmlNode* node,wxString nodename)
{
if(node==NULL) return NULL;
wxXmlNode* iNode;
iNode=node->GetChildren();
while (iNode != NULL)
{
wxString name=iNode->GetName();
if(name==nodename) return iNode;
iNode=iNode->GetNext();
}
return NULL;
}
//------------------------------------------------------------------------------
wxXmlNode* findNodeOnAttribute(wxXmlNode* node,wxString nodename,wxString Attribute,wxString val)
{
/*wxXmlNode* iNode;
iNode=node->GetChildren();
while (iNode != NULL)
{
if((iNode->GetName()==nodename)&&(iNode->GetPropVal(Attribute,_T(""))==val)) return iNode;
iNode=iNode->GetNext();
}*/
return NULL;
}
//------------------------------------------------------------------------------
wxXmlNode* findFirstNode(wxXmlNode* node,wxString nodename)
{
wxXmlNode* mas[10]; //макс уровень вложенности
int pos=0;
mas[pos] = node->GetChildren();
while (mas[pos] != NULL)
{
if(mas[pos]->GetName()==nodename) return mas[pos];
if(mas[pos]->GetChildren()!=NULL)
{
pos++;
mas[pos]=mas[pos-1]->GetChildren();
} else
{
//если не идёт дальше пытаемся подняться в верх по дереву
while (true)
{
mas[pos] = mas[pos]->GetNext();
if(mas[pos]==NULL)
{
if(pos>0) pos--; else break;
} else
{
break;
}
}
}
}
return NULL;
}
//------------------------------------------------------------------------------
//Найти первый узел с заданным атрибутом без рекурсии
wxXmlNode* findFirstNodeOnAttribute(wxXmlNode* node,wxString nodename,wxString Attribute,wxString val)
{
/*
wxXmlNode* mas[10]; //макс уровень вложенности
int pos=0;
mas[pos] = node->GetChildren();
while (mas[pos] != NULL)
{
if((mas[pos]->GetName()==nodename)&&(mas[pos]->GetPropVal(Attribute,_T(""))==val)) return mas[pos];
if(mas[pos]->GetChildren()!=NULL)
{
pos++;
mas[pos]=mas[pos-1]->GetChildren();
} else
{
//если не идёт дальше пытаемся подняться в верх по дереву
while (true)
{
mas[pos] = mas[pos]->GetNext();
if(mas[pos]==NULL)
{
if(pos>0) pos--; else break;
} else
{
break;
}
}
}
}
*/
return NULL;
}
//------------------------------------------------------------------------------
//поиск узла по пути "type->objects->list->filter->column"
wxXmlNode* findNodeOnPath(wxXmlNode* node,wxString path)
{
if(node==NULL) return NULL;
path=path+_T("->");
while(true)
{
wxString name=getBeforeFirst(path,_T("->"));
node=findNode(node,name);
if(node==NULL) return NULL;
path=getAfterFirst(path,_T("->"));
if(path==_T("")) break;
}
return node;
}
//------------------------------------------------------------------------------
//Ищет первый CDATA и возврещяет его содержимое
wxString getCdataValue(wxXmlNode* node)
{
if(node==NULL) return _T("");
wxXmlNode* cdata=findNode(node,_T("cdata"));
if(cdata==NULL) return _T("");
return cdata->GetContent();
}
//------------------------------------------------------------------------------
//Присвоить значение первому CDATA узлу если его нет то создать
void setCdataValue(wxXmlNode* node,wxString val)
{
if(node==NULL) return;
wxXmlNode* cdata=findNode(node,_T("cdata"));
if(cdata==NULL) cdata=new wxXmlNode(node,wxXML_CDATA_SECTION_NODE, wxS("cdata"), wxS(""));
cdata->SetContent(val);
}
//------------------------------------------------------------------------------

16
lib/xmlTools.h Normal file
View File

@ -0,0 +1,16 @@
//------------------------------------------------------------------------------
#ifndef xmltoolasH
#define xmltoolasH
//------------------------------------------------------------------------------
#include <wx/xml/xml.h>
wxXmlNode* findNode(wxXmlNode* node,wxString nodename);
wxXmlNode* findNodeOnAttribute(wxXmlNode* node,wxString nodename,wxString Attribute,wxString val);
wxXmlNode* findFirstNode(wxXmlNode* node,wxString nodename);
wxXmlNode* findFirstNodeOnAttribute(wxXmlNode* node,wxString nodename,wxString Attribute,wxString val);
wxXmlNode* findNodeOnPath(wxXmlNode* node,wxString path);
wxString getCdataValue(wxXmlNode* node);
void setCdataValue(wxXmlNode* node,wxString val);
//------------------------------------------------------------------------------
#endif