blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16bf4785ddf37629aaca79966c09b35be848761d | f13f46fbe8535a7573d0f399449c230a35cd2014 | /JelloMan/LoadModelFromFile.cpp | a38179c51412f75dd5d60333033e4c74212b7fb5 | []
| no_license | fangsunjian/jello-man | 354f1c86edc2af55045d8d2bcb58d9cf9b26c68a | 148170a4834a77a9e1549ad3bb746cb03470df8f | refs/heads/master | 2020-12-24T16:42:11.511756 | 2011-06-14T10:16:51 | 2011-06-14T10:16:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,182 | cpp | #include "LoadModelFromFile.h"
#include "ContentManager.h"
#include "SimpleObject.h"
#include "RenderContext.h"
// CONSTRUCTOR - DESTRUCTOR
LoadModelFromFile::LoadModelFromFile() : m_pbtnUseNormalMap(0),
m_pbtnLoadModel(0),
m_ModelPath(_T("")),
m_PhysXModelPath(_T("")),
m_NormalPath(_T("")),
m_DiffusePath(_T("")),
m_SpecPath(_T("")),
m_GlossPath(_T("")),
m_WorkingDirectory(_T(""))
{
m_LoadPathBitmaps.push_back(Content->LoadImage(_T("../Content/Images/Editor/add_small_normal.png")));
m_LoadPathBitmaps.push_back(Content->LoadImage(_T("../Content/Images/Editor/add_small_hover.png")));
m_LoadModelBitmaps.push_back(Content->LoadImage(_T("../Content/Images/Editor/load_normal.png")));
m_LoadModelBitmaps.push_back(Content->LoadImage(_T("../Content/Images/Editor/load_hover.png")));
m_pbtnLoadModel = new Button(150, 600, 36, 36);
m_pbtnLoadModel->SetNormalState(m_LoadModelBitmaps[0]);
m_pbtnLoadModel->SetHoverState(m_LoadModelBitmaps[1]);
m_pbtnLoadModel->SetDownState(m_LoadModelBitmaps[1]);
for (int i = 0; i < 6; ++i)
{
Button* pButton = new Button(150,122 + (i*80),15,15);
pButton->SetNormalState(m_LoadPathBitmaps[0]);
pButton->SetHoverState(m_LoadPathBitmaps[1]);
pButton->SetDownState(m_LoadPathBitmaps[1]);
m_Buttons.push_back(pButton);
}
TCHAR Buffer[256];
GetCurrentDirectory(256, Buffer);
m_WorkingDirectory = Buffer;
m_pFont = Content->LoadTextFormat(_T("Verdana"),12, false,false);
}
LoadModelFromFile::~LoadModelFromFile()
{
delete m_pbtnUseNormalMap;
delete m_pbtnLoadModel;
for (vector<Button*>::iterator it = m_Buttons.begin(); it != m_Buttons.end(); ++it)
delete (*it);
for (vector<TextBox*>::iterator it = m_TextBoxes.begin(); it != m_TextBoxes.end(); ++it)
delete (*it);
}
// GENERAL
void LoadModelFromFile::Tick()
{
if (m_TextBoxes.size() == 0)
{
for (int i = 0; i < 6; ++i)
{
TextBox* pTextBox = new TextBox();
pTextBox->SetBounds(20, 120 + (i*80),120,20);
m_TextBoxes.push_back(pTextBox);
}
}
for (vector<Button*>::iterator it = m_Buttons.begin(); it != m_Buttons.end(); ++it)
{
(*it)->Tick();
}
m_pbtnLoadModel->Tick();
if (m_Buttons[0]->Clicked())
{
m_ModelPath = GetPath(_T("Load Model"), L"OBJ Files\0*.binobj;*.obj*\0\0");
m_ModelPath = StripPath(m_ModelPath);
m_TextBoxes[0]->SetText(m_ModelPath);
SetCurrentDirectory(m_WorkingDirectory.c_str());
}
if (m_Buttons[1]->Clicked())
{
m_PhysXModelPath = GetPath(_T("Load PhysX Model"), L"NX Files\0*.nxconvex;*.nxconcave*;*.nxsoftbody\0\0");
m_PhysXModelPath = StripPath(m_PhysXModelPath);
m_TextBoxes[1]->SetText(m_PhysXModelPath);
SetCurrentDirectory(m_WorkingDirectory.c_str());
}
if (m_Buttons[2]->Clicked())
{
m_NormalPath = GetPath(_T("Load Normal Map"), L"Image Files\0*.png\0\0");
m_NormalPath = StripPath(m_NormalPath);
m_TextBoxes[2]->SetText(m_NormalPath);
SetCurrentDirectory(m_WorkingDirectory.c_str());
}
if (m_Buttons[3]->Clicked())
{
m_DiffusePath = GetPath(_T("Load Diffuse map"), L"Image Files\0*.png\0\0");
m_DiffusePath = StripPath(m_DiffusePath);
m_TextBoxes[3]->SetText(m_DiffusePath);
SetCurrentDirectory(m_WorkingDirectory.c_str());
}
if (m_Buttons[4]->Clicked())
{
m_SpecPath = GetPath(_T("Load Specular Map"), L"Image Files\0*.png\0\0");
m_SpecPath = StripPath(m_SpecPath);
m_TextBoxes[4]->SetText(m_SpecPath);
SetCurrentDirectory(m_WorkingDirectory.c_str());
}
if (m_Buttons[5]->Clicked())
{
m_GlossPath = GetPath(_T("Load Glossiness Map"), L"Image Files\0*.png\0\0");
m_GlossPath = StripPath(m_GlossPath);
m_TextBoxes[5]->SetText(m_GlossPath);
SetCurrentDirectory(m_WorkingDirectory.c_str());
}
/*if (m_pbtnLoadModel->Clicked())
{
if (m_ModelPath != _T("") && m_PhysXModelPath != _T(""))
{
bool rigid = false;
int ret = MessageBoxA(0, "Load as staticmesh?", "Loading: ", MB_ICONQUESTION | MB_YESNO);
switch (ret)
{
case IDYES: rigid = false; break;
default: rigid = true; break;
}
SimpleObject* pObj = new SimpleObject();
pObj->SetNormalPath(m_NormalPath);
pObj->SetModelPath(m_ModelPath);
pObj->SetPhysXModel(m_PhysXModelPath);
pObj->SetDiffusePath(m_DiffusePath);
pObj->SetSpecPath(m_SpecPath);
pObj->SetGlossPath(m_GlossPath);
pObj->SetRigid(rigid);
Vector3 vLook = m_pRenderContext->GetCamera()->GetLook();
vLook.Normalize();
pObj->Init(m_pPhysXEngine);
pObj->Translate(m_pRenderContext->GetCamera()->GetPosition() + vLook * 10);
m_pLevel->AddLevelObject(pObj);
}
}*/
if (m_TextBoxes[0]->Entered())
{
m_ModelPath = m_TextBoxes[0]->GetText();
m_TextBoxes[0]->LoseFocus();
}
if (m_TextBoxes[1]->Entered())
{
m_PhysXModelPath = m_TextBoxes[1]->GetText();
m_TextBoxes[1]->LoseFocus();
}
if (m_TextBoxes[2]->Entered())
{
m_NormalPath = m_TextBoxes[2]->GetText();
m_TextBoxes[2]->LoseFocus();
}
if (m_TextBoxes[3]->Entered())
{
m_DiffusePath = m_TextBoxes[3]->GetText();
m_TextBoxes[3]->LoseFocus();
}
if (m_TextBoxes[4]->Entered())
{
m_SpecPath = m_TextBoxes[4]->GetText();
m_TextBoxes[4]->LoseFocus();
}
if (m_TextBoxes[5]->Entered())
{
m_GlossPath = m_TextBoxes[5]->GetText();
m_TextBoxes[5]->LoseFocus();
}
}
void LoadModelFromFile::Show()
{
BX2D->SetColor(255, 255, 255);
BX2D->SetFont(m_pFont);
BX2D->DrawString(_T("Load new model from file") ,10,60);
BX2D->DrawString(_T("Model path:") ,10,100);
BX2D->DrawString(_T("PhysX Model path:") ,10,180);
BX2D->DrawString(_T("Normal Map path:") ,10,260);
BX2D->DrawString(_T("Diffuse Map path:") ,10,340);
BX2D->DrawString(_T("Specular Map path:") ,10,420);
BX2D->DrawString(_T("Glossiness Map path:") ,10,500);
for (vector<Button*>::iterator it = m_Buttons.begin(); it != m_Buttons.end(); ++it)
{
(*it)->Show();
}
for (vector<TextBox*>::iterator it = m_TextBoxes.begin(); it != m_TextBoxes.end(); ++it)
{
(*it)->Show();
}
m_pbtnLoadModel->Show();
}
void LoadModelFromFile::HideTextBoxes()
{
for (vector<TextBox*>::iterator it = m_TextBoxes.begin(); it != m_TextBoxes.end(); ++it)
{
(*it)->Hide();
}
}
tstring LoadModelFromFile::GetPath(const tstring& title, LPWSTR filter)
{
wchar_t filePath[256];
OPENFILENAME opf;
opf.hwndOwner = 0;
opf.lpstrFilter = filter;
opf.lpstrCustomFilter = 0;
opf.nMaxCustFilter = 0L;
opf.nFilterIndex = 1L;
opf.lpstrFile = filePath;
opf.lpstrFile[0] = '\0';
opf.nMaxFile = 255;
opf.lpstrFileTitle = 0;
opf.nMaxFileTitle=50;
opf.lpstrInitialDir = 0;
opf.lpstrTitle = title.c_str();
opf.nFileOffset = 0;
opf.nFileExtension = 2;
opf.lpstrDefExt = L"*.*";
opf.lpfnHook = NULL;
opf.lCustData = 0;
opf.Flags = OFN_PATHMUSTEXIST | OFN_OVERWRITEPROMPT;
opf.lStructSize = sizeof(OPENFILENAMEW);
GetOpenFileName(&opf);
return opf.lpstrFile;
}
void LoadModelFromFile::Clear()
{
m_GlossPath = m_SpecPath = m_DiffusePath = m_NormalPath = m_PhysXModelPath = m_ModelPath = _T("");
for (int i = 0; i < 6; ++i)
{
if (m_TextBoxes.size() > 0)
m_TextBoxes[i]->SetText(_T(""));
}
}
tstring LoadModelFromFile::StripPath(const tstring& path)
{
if (path == _T(""))
return _T("");
tstring workingDirectoryBuffer = m_WorkingDirectory.substr(0, m_WorkingDirectory.find(_T("\\bin")));
tstring relativePath = path.substr(workingDirectoryBuffer.size(), path.size() - 1);
tstringstream stream;
stream << _T("..") << relativePath;
relativePath = stream.str();
return relativePath;
}
vector<tstring> LoadModelFromFile::GetPaths() const
{
vector<tstring> paths;
paths.push_back(m_ModelPath);
paths.push_back(m_PhysXModelPath);
paths.push_back(m_NormalPath);
paths.push_back(m_DiffusePath);
paths.push_back(m_SpecPath);
paths.push_back(m_GlossPath);
return paths;
} | [
"[email protected]",
"bastian.damman@0fb7bab5-1bf9-c5f3-09d9-7611b49293d6"
]
| [
[
[
1,
2
],
[
5,
16
],
[
19,
19
],
[
22,
49
],
[
51,
91
],
[
93,
143
],
[
154,
154
],
[
156,
156
],
[
159,
159
],
[
163,
163
],
[
165,
319
]
],
[
[
3,
4
],
[
17,
18
],
[
20,
21
],
[
50,
50
],
[
92,
92
],
[
144,
153
],
[
155,
155
],
[
157,
158
],
[
160,
162
],
[
164,
164
]
]
]
|
6774a5ffabec219352ca780dd70e0d02d322840f | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhnetsdk/TPLayer_IOCP/Demo/TcpClient.h | 0a3b0d202b76a03bca6113c949c14fbfe22729a3 | []
| no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 986 | h | // TcpClient.h: interface for the CTcpClient class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_TCPCLIENT_H__0BE8B2BE_A838_4CEB_BDD6_A5188E644376__INCLUDED_)
#define AFX_TCPCLIENT_H__0BE8B2BE_A838_4CEB_BDD6_A5188E644376__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "../TPLayer/TPTCPClient.h"
class CTcpClient : public TPTCPClient, public ITPListener
{
public:
CTcpClient();
virtual ~CTcpClient();
public:
virtual int onData(int engineId, int connId, const char* data, int len);
virtual int onConnect(int engineId, int connId, const char* ip, int port);
virtual int onClose(int engineId, int connId);
virtual int onDisconnect(int engineId, int connId);
virtual int onReconnect(int engineId, int connId);
virtual int onSendDataAck(int engineId, int connId, int id);
};
#endif // !defined(AFX_TCPCLIENT_H__0BE8B2BE_A838_4CEB_BDD6_A5188E644376__INCLUDED_)
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
34
]
]
]
|
08f9cd67119ed45fa9e1e065422b7bbedfc09d7d | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Interpolation/WmlIntpTricubic3.cpp | 4568eeb1cb2d8e9c2ce9a2147c3ae42abf8f6159 | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,724 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlIntpTricubic3.h"
#include "WmlMath.h"
using namespace Wml;
//----------------------------------------------------------------------------
template <class Real>
IntpTricubic3<Real>::IntpTricubic3 (int iXBound, int iYBound, int iZBound,
Real fXMin, Real fXSpacing, Real fYMin, Real fYSpacing, Real fZMin,
Real fZSpacing, Real*** aaafF, bool bCatmullRom)
{
// At least a 4x4x4 block of data points are needed to construct the
// tricubic interpolation.
assert( iXBound >= 4 && iYBound >= 4 && iZBound >= 4 && aaafF );
assert( fXSpacing > (Real)0.0 && fYSpacing > (Real)0.0
&& fZSpacing > (Real)0.0 );
m_iXBound = iXBound;
m_iYBound = iYBound;
m_iZBound = iZBound;
m_iQuantity = iXBound*iYBound*iZBound;
m_fXMin = fXMin;
m_fXSpacing = fXSpacing;
m_fInvXSpacing = ((Real)1.0)/fXSpacing;
m_fXMax = fXMin + fXSpacing*(iXBound-1);
m_fYMin = fYMin;
m_fYSpacing = fYSpacing;
m_fInvYSpacing = ((Real)1.0)/fYSpacing;
m_fYMax = fYMin + fYSpacing*(iYBound-1);
m_fZMin = fZMin;
m_fZSpacing = fZSpacing;
m_fInvZSpacing = ((Real)1.0)/fZSpacing;
m_fZMax = fYMin + fZSpacing*(iZBound-1);
m_aaafF = aaafF;
m_aafBlend = ( bCatmullRom ? ms_aafCRBlend : ms_aafBSBlend );
}
//----------------------------------------------------------------------------
template <class Real>
int IntpTricubic3<Real>::GetXBound () const
{
return m_iXBound;
}
//----------------------------------------------------------------------------
template <class Real>
int IntpTricubic3<Real>::GetYBound () const
{
return m_iYBound;
}
//----------------------------------------------------------------------------
template <class Real>
int IntpTricubic3<Real>::GetZBound () const
{
return m_iZBound;
}
//----------------------------------------------------------------------------
template <class Real>
int IntpTricubic3<Real>::GetQuantity () const
{
return m_iQuantity;
}
//----------------------------------------------------------------------------
template <class Real>
Real*** IntpTricubic3<Real>::GetF () const
{
return m_aaafF;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::GetXMin () const
{
return m_fXMin;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::GetXMax () const
{
return m_fXMax;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::GetXSpacing () const
{
return m_fXSpacing;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::GetYMin () const
{
return m_fYMin;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::GetYMax () const
{
return m_fYMax;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::GetYSpacing () const
{
return m_fYSpacing;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::GetZMin () const
{
return m_fZMin;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::GetZMax () const
{
return m_fZMax;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::GetZSpacing () const
{
return m_fZSpacing;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::operator() (Real fX, Real fY, Real fZ) const
{
// compute x-index and clamp to image
Real fXIndex = (fX - m_fXMin)*m_fInvXSpacing;
int iX = (int)fXIndex;
if ( iX < 0 || iX > m_iXBound - 1 )
return Math<Real>::MAX_REAL;
// compute y-index and clamp to image
Real fYIndex = (fY - m_fYMin)*m_fInvYSpacing;
int iY = (int)fYIndex;
if ( iY < 0 || iY > m_iYBound - 1 )
return Math<Real>::MAX_REAL;
// compute z-index and clamp to image
Real fZIndex = (fZ - m_fZMin)*m_fInvZSpacing;
int iZ = (int)fZIndex;
if ( iZ < 0 || iZ > m_iZBound - 1 )
return Math<Real>::MAX_REAL;
Real afU[4];
afU[0] = (Real)1.0;
afU[1] = fXIndex - iX;
afU[2] = afU[1]*afU[1];
afU[3] = afU[1]*afU[2];
Real afV[4];
afV[0] = (Real)1.0;
afV[1] = fYIndex - iY;
afV[2] = afV[1]*afV[1];
afV[3] = afV[1]*afV[2];
Real afW[4];
afW[0] = (Real)1.0;
afW[1] = fZIndex - iZ;
afW[2] = afW[1]*afW[1];
afW[3] = afW[1]*afW[2];
// compute P = M*U, Q = M*V, R = M*W
Real afP[4], afQ[4], afR[4];
int iRow, iCol;
for (iRow = 0; iRow < 4; iRow++)
{
afP[iRow] = (Real)0.0;
afQ[iRow] = (Real)0.0;
afR[iRow] = (Real)0.0;
for (iCol = 0; iCol < 4; iCol++)
{
afP[iRow] += m_aafBlend[iRow][iCol]*afU[iCol];
afQ[iRow] += m_aafBlend[iRow][iCol]*afV[iCol];
afR[iRow] += m_aafBlend[iRow][iCol]*afW[iCol];
}
}
// compute the tensor product (M*U)(M*V)(M*W)*D where D is the 4x4x4
// subimage containing (x,y,z)
iX--;
iY--;
iZ--;
Real fResult = (Real)0.0;
for (int iSlice = 0; iSlice < 4; iSlice++)
{
int iZClamp = iZ + iSlice;
if ( iZClamp < 0 )
iZClamp = 0;
else if ( iZClamp > m_iZBound - 1 )
iZClamp = m_iZBound - 1;
for (iRow = 0; iRow < 4; iRow++)
{
int iYClamp = iY + iRow;
if ( iYClamp < 0 )
iYClamp = 0;
else if ( iYClamp > m_iYBound - 1 )
iYClamp = m_iYBound - 1;
for (iCol = 0; iCol < 4; iCol++)
{
int iXClamp = iX + iCol;
if ( iXClamp < 0 )
iXClamp = 0;
else if ( iXClamp > m_iXBound - 1 )
iXClamp = m_iXBound - 1;
fResult += afP[iCol]*afQ[iRow]*afR[iSlice]*
m_aaafF[iZClamp][iYClamp][iXClamp];
}
}
}
return fResult;
}
//----------------------------------------------------------------------------
template <class Real>
Real IntpTricubic3<Real>::operator() (int iXOrder, int iYOrder, int iZOrder,
Real fX, Real fY, Real fZ) const
{
// compute x-index and clamp to image
Real fXIndex = (fX - m_fXMin)*m_fInvXSpacing;
int iX = (int)fXIndex;
if ( iX < 0 || iX > m_iXBound - 1 )
return Math<Real>::MAX_REAL;
// compute y-index and clamp to image
Real fYIndex = (fY - m_fYMin)*m_fInvYSpacing;
int iY = (int)fYIndex;
if ( iY < 0 || iY > m_iYBound - 1 )
return Math<Real>::MAX_REAL;
// compute z-index and clamp to image
Real fZIndex = (fZ - m_fZMin)*m_fInvZSpacing;
int iZ = (int)fZIndex;
if ( iZ < 0 || iZ > m_iZBound - 1 )
return Math<Real>::MAX_REAL;
Real afU[4], fDX, fXMult;
switch ( iXOrder )
{
case 0:
fDX = fXIndex - iX;
afU[0] = (Real)1.0;
afU[1] = fDX;
afU[2] = fDX*afU[1];
afU[3] = fDX*afU[2];
fXMult = (Real)1.0;
break;
case 1:
fDX = fXIndex - iX;
afU[0] = (Real)0.0;
afU[1] = (Real)1.0;
afU[2] = ((Real)2.0)*fDX;
afU[3] = ((Real)3.0)*fDX*fDX;
fXMult = m_fInvXSpacing;
break;
case 2:
fDX = fXIndex - iX;
afU[0] = (Real)0.0;
afU[1] = (Real)0.0;
afU[2] = (Real)2.0;
afU[3] = ((Real)6.0)*fDX;
fXMult = m_fInvXSpacing*m_fInvXSpacing;
break;
case 3:
afU[0] = (Real)0.0;
afU[1] = (Real)0.0;
afU[2] = (Real)0.0;
afU[3] = (Real)6.0;
fXMult = m_fInvXSpacing*m_fInvXSpacing*m_fInvXSpacing;
break;
default:
return (Real)0.0;
}
Real afV[4], fDY, fYMult;
switch ( iYOrder )
{
case 0:
fDY = fYIndex - iY;
afV[0] = (Real)1.0;
afV[1] = fDY;
afV[2] = fDY*afV[1];
afV[3] = fDY*afV[2];
fYMult = (Real)1.0;
break;
case 1:
fDY = fYIndex - iY;
afV[0] = (Real)0.0;
afV[1] = (Real)1.0;
afV[2] = ((Real)2.0)*fDY;
afV[3] = ((Real)3.0)*fDY*fDY;
fYMult = m_fInvYSpacing;
break;
case 2:
fDY = fYIndex - iY;
afV[0] = (Real)0.0;
afV[1] = (Real)0.0;
afV[2] = (Real)2.0;
afV[3] = ((Real)6.0)*fDY;
fYMult = m_fInvYSpacing*m_fInvYSpacing;
break;
case 3:
afV[0] = (Real)0.0;
afV[1] = (Real)0.0;
afV[2] = (Real)0.0;
afV[3] = (Real)6.0;
fYMult = m_fInvYSpacing*m_fInvYSpacing*m_fInvYSpacing;
break;
default:
return (Real)0.0;
}
Real afW[4], fDZ, fZMult;
switch ( iZOrder )
{
case 0:
fDZ = fZIndex - iZ;
afW[0] = (Real)1.0;
afW[1] = fDZ;
afW[2] = fDZ*afW[1];
afW[3] = fDZ*afW[2];
fZMult = (Real)1.0;
break;
case 1:
fDZ = fZIndex - iZ;
afW[0] = (Real)0.0;
afW[1] = (Real)1.0;
afW[2] = ((Real)2.0)*fDZ;
afW[3] = ((Real)3.0)*fDZ*fDZ;
fZMult = m_fInvZSpacing;
break;
case 2:
fDZ = fZIndex - iZ;
afW[0] = (Real)0.0;
afW[1] = (Real)0.0;
afW[2] = (Real)2.0;
afW[3] = ((Real)6.0)*fDZ;
fZMult = m_fInvZSpacing*m_fInvZSpacing;
break;
case 3:
afW[0] = (Real)0.0;
afW[1] = (Real)0.0;
afW[2] = (Real)0.0;
afW[3] = (Real)6.0;
fZMult = m_fInvZSpacing*m_fInvZSpacing*m_fInvZSpacing;
break;
default:
return (Real)0.0;
}
// compute P = M*U, Q = M*V, and R = M*W
Real afP[4], afQ[4], afR[4];
int iRow, iCol;
for (iRow = 0; iRow < 4; iRow++)
{
afP[iRow] = (Real)0.0;
afQ[iRow] = (Real)0.0;
afR[iRow] = (Real)0.0;
for (iCol = 0; iCol < 4; iCol++)
{
afP[iRow] += m_aafBlend[iRow][iCol]*afU[iCol];
afQ[iRow] += m_aafBlend[iRow][iCol]*afV[iCol];
afR[iRow] += m_aafBlend[iRow][iCol]*afW[iCol];
}
}
// compute the tensor product (M*U)(M*V)(M*W)*D where D is the 4x4x4
// subimage containing (x,y,z)
iX--;
iY--;
iZ--;
Real fResult = (Real)0.0;
for (int iSlice = 0; iSlice < 4; iSlice++)
{
int iZClamp = iZ + iSlice;
if ( iZClamp < 0 )
iZClamp = 0;
else if ( iZClamp > m_iZBound - 1 )
iZClamp = m_iZBound - 1;
for (iRow = 0; iRow < 4; iRow++)
{
int iYClamp = iY + iRow;
if ( iYClamp < 0 )
iYClamp = 0;
else if ( iYClamp > m_iYBound - 1 )
iYClamp = m_iYBound - 1;
for (iCol = 0; iCol < 4; iCol++)
{
int iXClamp = iX + iCol;
if ( iXClamp < 0 )
iXClamp = 0;
else if ( iXClamp > m_iXBound - 1 )
iXClamp = m_iXBound - 1;
fResult += afP[iCol]*afQ[iRow]*afR[iSlice]*
m_aaafF[iZClamp][iYClamp][iXClamp];
}
}
}
fResult *= fXMult*fYMult*fZMult;
return fResult;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template class WML_ITEM IntpTricubic3<float>;
const float IntpTricubic3f::ms_aafCRBlend[4][4] =
{
{ 0.0f, -0.5f, 1.0f, -0.5f },
{ 1.0f, 0.0f, -2.5f, 1.5f },
{ 0.0f, 0.5f, 2.0f, -1.5f },
{ 0.0f, 0.0f, -0.5f, 0.5f }
};
const float IntpTricubic3f::ms_aafBSBlend[4][4] =
{
{ 1.0f/6.0f, -3.0f/6.0f, 3.0f/6.0f, -1.0f/6.0f },
{ 4.0f/6.0f, 0.0f/6.0f, -6.0f/6.0f, 3.0f/6.0f },
{ 1.0f/6.0f, 3.0f/6.0f, 3.0f/6.0f, -3.0f/6.0f },
{ 0.0f/6.0f, 0.0f/6.0f, 0.0f/6.0f, 1.0f/6.0f }
};
template class WML_ITEM IntpTricubic3<double>;
const double IntpTricubic3d::ms_aafCRBlend[4][4] =
{
{ 0.0, -0.5, 1.0, -0.5 },
{ 1.0, 0.0, -2.5, 1.5 },
{ 0.0, 0.5, 2.0, -1.5 },
{ 0.0, 0.0, -0.5, 0.5 }
};
const double IntpTricubic3d::ms_aafBSBlend[4][4] =
{
{ 1.0/6.0, -3.0/6.0, 3.0/6.0, -1.0/6.0 },
{ 4.0/6.0, 0.0/6.0, -6.0/6.0, 3.0/6.0 },
{ 1.0/6.0, 3.0/6.0, 3.0/6.0, -3.0/6.0 },
{ 0.0/6.0, 0.0/6.0, 0.0/6.0, 1.0/6.0 }
};
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
460
]
]
]
|
d0d5c59c58ea0238ca835f1bc6484cba387a046f | 9426ad6e612863451ad7aac2ad8c8dd100a37a98 | /ULLib/include/ULRebarCtrl.h | abf687283e852287f259ee6748d1a07c156ddac3 | []
| no_license | piroxiljin/ullib | 61f7bd176c6088d42fd5aa38a4ba5d4825becd35 | 7072af667b6d91a3afd2f64310c6e1f3f6a055b1 | refs/heads/master | 2020-12-28T19:46:57.920199 | 2010-02-17T01:43:44 | 2010-02-17T01:43:44 | 57,068,293 | 0 | 0 | null | 2016-04-25T19:05:41 | 2016-04-25T19:05:41 | null | WINDOWS-1251 | C++ | false | false | 2,212 | h | ///\file ULRebarCtrl.h
///\brief Заголовочный файл класса ребара размещенного на плавающей панельке(31.08.2008)
#pragma once
#ifndef __UL_ULREBARCTRL_H__
#define __UL_ULREBARCTRL_H__
#include "ULRebar.h"
#include "ULWndCtrl.h"
namespace ULWnds
{
namespace ULWndCtrls
{
///\class CULRebarCtrl
///\brief Класс ребара размещенного на плавающей панельке(31.08.2008)
class CULRebarCtrl :
public CULWndCtrl
{
private:
bool m_fAutoSize;
protected:
///\brief Непосредственно сам тулбар
ULBars::CULRebar m_Rebar;
///\brief Функция окна
static LRESULT ClientWndProc(HWND hWnd , UINT uMsg , WPARAM wParam , LPARAM lParam);
///\brief Функция окна необходимая для сабклассирования дочерними контролами
WNDPROC m_lpSubClassWndProc;
public:
//================================================
///\brief Конструктор
//================================================
CULRebarCtrl(void);
///\brief Конструктор копирования
CULRebarCtrl(CULRebarCtrl&);
///\brief Деструктор
virtual ~CULRebarCtrl(void);
///\brief оператор копирования
void operator=(CULRebarCtrl&);
///\brief Функция возвращает ссылку на тулбар
inline ULBars::CULRebar& GetRebar(){return m_Rebar;};
///\brief Функция создания тулбарконтрола
///\param hParentWnd - хендл родителя(носителя)
///\param nXPos,nYPos - позиция тулбарконтрола при создании в
/// плавающем состоянии
///\param dwDockedState - назначение стыковки на момент создания
BOOL CreateRebarCtrl(HWND hParentWnd,
int nXPos,
int nYPos,
DWORD dwDockedState);
protected:
///\brief Обработчик WM_SIZE
virtual LRESULT OnSize(WPARAM nType,LPARAM point);
};
}
}
#endif //__UL_ULREBARCTRL_H__
| [
"UncleLab@a8b69a72-a546-0410-9fb4-5106a01aa11f"
]
| [
[
[
1,
54
]
]
]
|
17c949ef9a643a46bc51d82cae7f8edbcb9a2dce | 5f0b8d4a0817a46a9ae18a057a62c2442c0eb17e | /Include/event/ChangeEvent.cpp | 9de20e874987a0ea55d8926b506a3d3f35e78eb2 | [
"BSD-3-Clause"
]
| permissive | gui-works/ui | 3327cfef7b9bbb596f2202b81f3fc9a32d5cbe2b | 023faf07ff7f11aa7d35c7849b669d18f8911cc6 | refs/heads/master | 2020-07-18T00:46:37.172575 | 2009-11-18T22:05:25 | 2009-11-18T22:05:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,733 | cpp | /*
* Copyright (c) 2003-2006, Bram Stein
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "./ChangeEvent.h"
namespace ui
{
namespace event
{
ChangeEvent::ChangeEvent(Component* sourceComponent, int id)
: Event(sourceComponent, id)
{
}
}
}
| [
"bs@bram.(none)"
]
| [
[
[
1,
39
]
]
]
|
3b570bdf14f00a96f4ddbb5f11dcdba15247527c | 77aa13a51685597585abf89b5ad30f9ef4011bde | /dep/src/boost/boost/fusion/functional/adapter/detail/pow2_explode.hpp | 2e5b8cf8880a749dee96b042336c8e4c8396f18e | [
"BSL-1.0"
]
| permissive | Zic/Xeon-MMORPG-Emulator | 2f195d04bfd0988a9165a52b7a3756c04b3f146c | 4473a22e6dd4ec3c9b867d60915841731869a050 | refs/heads/master | 2021-01-01T16:19:35.213330 | 2009-05-13T18:12:36 | 2009-05-14T03:10:17 | 200,849 | 8 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 4,132 | hpp | /*=============================================================================
Copyright (c) 2006-2007 Tobias Schwinger
Use modification and distribution are subject to the Boost Software
License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
==============================================================================*/
#if !defined(BOOST_PP_IS_ITERATING)
# error "This file has to be included by a preprocessor loop construct!"
#elif BOOST_PP_ITERATION_DEPTH() == 1
# if !defined(BOOST_FUSION_FUNCTIONAL_ADAPTER_DETAIL_POW2_EXPLODE_HPP_INCLUDED)
# include <boost/preprocessor/config/limits.hpp>
# include <boost/preprocessor/slot/slot.hpp>
# include <boost/preprocessor/arithmetic/dec.hpp>
# define BOOST_FUSION_FUNCTIONAL_ADAPTER_DETAIL_POW2_EXPLODE_HPP_INCLUDED
# endif
# define BOOST_PP_VALUE 0
# include BOOST_PP_ASSIGN_SLOT(1)
# define BOOST_PP_FILENAME_2 \
<boost/fusion/functional/adapter/detail/pow2_explode.hpp>
# define BOOST_PP_VALUE (1 << N) >> 4
# if BOOST_PP_VALUE > BOOST_PP_LIMIT_ITERATION
# error "Preprocessor limit exceeded."
# endif
# include BOOST_PP_ASSIGN_SLOT(2)
# define BOOST_PP_ITERATION_LIMITS (0,BOOST_PP_DEC(BOOST_PP_SLOT_2()))
# include BOOST_PP_ITERATE()
#elif BOOST_PP_ITERATION_DEPTH() == 2
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# if BOOST_PP_SLOT_1() < 1 << N
# include BOOST_PP_INDIRECT_SELF
# define BOOST_PP_VALUE BOOST_PP_SLOT_1() + 1
# include BOOST_PP_ASSIGN_SLOT(1)
# endif
# endif
# endif
# endif
# endif
# endif
# endif
# endif
# endif
# endif
# endif
# endif
# endif
# endif
# endif
# endif
#endif
| [
"pepsi1x1@a6a5f009-272a-4b40-a74d-5f9816a51f88"
]
| [
[
[
1,
118
]
]
]
|
4cd961c353fd84cc3ec0727f5b3c5169f64cf578 | ec593cdbcb75afa0e1d49a9d5f992d929f5b131b | /UiSwitchOption.cpp | 7ffc6a6759e006c2d3b5c8c4214a5befa5a2f785 | []
| no_license | jemyzhang/MzCommon_deprecated | 10873a31b4c240bcdb8d31f7cf7d546c193b59a7 | 99f44847355882edf40329bc17420a5414a59389 | refs/heads/master | 2016-09-01T17:09:08.785822 | 2010-01-18T02:09:09 | 2010-01-18T02:09:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 547 | cpp | #include "UiSwitchOption.h"
#include "MzCommon.h"
#include "MzCommonResource.h"
using namespace MzCommon;
MZ_IMPLEMENT_DYNAMIC(UiSwitchOption)
#define MZ_IDC_OPTION_LIST 101
#define MZ_IDC_BTN_OK 102
#define MZ_IDC_BTN_CANCEL 103
UiSwitchOption::UiSwitchOption(void)
{
SetTextOffset2(120);
SetButtonType(MZC_BUTTON_LINE_BOTTOM);
SetTextMaxLen(0);
m_Switch.SetButtonType(MZC_BUTTON_SWITCH);
m_Switch.SetButtonMode(MZC_BUTTON_MODE_HOLD);
AddChild(&m_Switch);
}
UiSwitchOption::~UiSwitchOption(void)
{
}
| [
"jemyzhang@53aff7d1-dc1e-0346-9cbd-63131b65f07d"
]
| [
[
[
1,
25
]
]
]
|
b1ca647ced98e8a90ebec116e6e61fb89fbec94e | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Shared/src/UserDefinedBitMapFeature.cpp | 96cbb3b9ef6e8943d420500f1c0ebf2da2ca6637 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,926 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include <string.h>
#include "UserDefinedBitMapFeature.h"
UserDefinedBitMapFeature::
UserDefinedBitMapFeature( const ScreenOrWorldCoordinate& center,
const char* serverBitMapName,
bool shouldScale )
: UserDefinedFeature( UserDefinedFeature::bitmap,
std::vector<MC2Point>(1, MC2Point(0,0)),
center ),
m_shouldScale(shouldScale)
{
m_widthPixels = 0;
m_heightPixels = 0;
// Default should be 2d.
m_always2d = true;
if ( serverBitMapName ) {
m_bitMapName = new char[strlen(serverBitMapName) + 1];
strcpy(m_bitMapName, serverBitMapName);
} else {
m_bitMapName = NULL;
}
}
UserDefinedBitMapFeature::~UserDefinedBitMapFeature()
{
delete [] m_bitMapName;
}
const char*
UserDefinedBitMapFeature::getBitMapName() const
{
return m_bitMapName;
}
int UserDefinedBitMapFeature::getWidth() const
{
return m_widthPixels;
}
int UserDefinedBitMapFeature::getHeight() const
{
return m_heightPixels;
}
void UserDefinedBitMapFeature::setDimensions(int widthPixels, int heightPixels)
{
m_widthPixels = widthPixels;
m_heightPixels = heightPixels;
}
bool UserDefinedBitMapFeature::shouldScale() const
{
return m_shouldScale;
}
| [
"[email protected]"
]
| [
[
[
1,
73
]
]
]
|
aae189a2074194154e63cafab4021320a978290b | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /WallPaper/include/WallPaperPreviewDlg.h | 6680e197f1b72bbdadb814ce62c61ca95cee863d | []
| no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10T13:11:23.176481 | 2011-04-14T11:04:17 | 2011-04-14T11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,710 | h | /*
WallPaperPreviewDlg.h
Dialogo per il preview.
Luca Piergentili, 08/09/03
[email protected]
WallPaper (alias crawlpaper) - the hardcore of Windows desktop
http://www.crawlpaper.com/
copyright © 1998-2004 Luca Piergentili, all rights reserved
crawlpaper is a registered name, all rights reserved
This is a free software, released under the terms of the BSD license. Do not
attempt to use it in any form which violates the license or you will be persecuted
and charged for this.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
- Neither the name of "crawlpaper" nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _WALLPAPERPREVIEWDLG_H
#define _WALLPAPERPREVIEWDLG_H 1
#include "window.h"
#include "CDialogEx.h"
#include "CDibCtrl.h"
#include "CWndLayered.h"
#include "CDialogHeader.h"
#include "WallPaperConfig.h"
#define IDS_DIALOG_PREVIEW_TITLE " Wallpaper preview "
/*
CWallPaperPreviewDlg
*/
class CWallPaperPreviewDlg : public CDialogEx
{
DECLARE_DYNCREATE(CWallPaperPreviewDlg)
protected: // provide default constructor only for dynamic creation, private/protected to prevent it from being called from outside the class implementation
CWallPaperPreviewDlg() {::MessageBox(NULL,"PANIC! This shouldn't happen!","CWallPaperPreviewDlg()",MB_OK|MB_ICONERROR|MB_TASKMODAL|MB_SETFOREGROUND|MB_TOPMOST);}
public:
CWallPaperPreviewDlg(HWND hWndParent);
~CWallPaperPreviewDlg() {}
private:
void DoDataExchange (CDataExchange*);
BOOL OnInitDialog (void);
BOOL OnInitDialogEx (UINT = -1,LPCSTR = NULL) {return(FALSE);}
void OnSysCommand (UINT nID,LPARAM lParam);
BOOL OnQueryNewPalette (void);
void OnPaletteChanged (CWnd* pFocusWnd);
void OnSetFocus (CWnd* pOldWnd);
void OnExit (void) {CDialogEx::OnExit();}
LONG OnSetConfig (UINT wParam,LONG lParam);
LONG OnPreviewMinmaximize(UINT wParam,LONG lParam);
LONG OnPreviewForceFocus (UINT wParam,LONG lParam);
LONG OnPreviewEnabled (UINT wParam,LONG lParam);
LONG OnPreviewDisabled (UINT wParam,LONG lParam);
HWND m_hWndParent;
BOOL m_bForceFocus;
CWallPaperConfig* m_pConfig;
CDialogHeader m_wndHeader;
char m_szItem[_MAX_PATH+1];
CDibCtrl m_wndStaticDib;
CWndLayered m_wndLayered;
DECLARE_MESSAGE_MAP()
};
#endif // _WALLPAPERPREVIEWDLG_H
| [
"[email protected]"
]
| [
[
[
1,
94
]
]
]
|
84ef38f15cc9b2ab86c5e36dbf52564c5425d91b | 57c3ef7177f9bf80874fbd357fceb8625e746060 | /Personal_modle_file/Dean_Zhang/Client/BroadcastSeachServer/ui_BroadcastSeachServer.h | 870620c39dd85538ae2c9cb141833669eb747973 | []
| no_license | kref/mobileim | 0c33cc01b312704d71e74db04c4ba9b624b4ff73 | 15894fa006095428727b0530e9337137262818ac | refs/heads/master | 2016-08-10T08:33:27.761030 | 2011-08-13T13:15:37 | 2011-08-13T13:15:37 | 45,781,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,225 | h | /********************************************************************************
** Form generated from reading UI file 'BroadcastSeachServer.ui'
**
** Created: Sun Jun 27 16:52:21 2010
** by: Qt User Interface Compiler version 4.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_BROADCASTSEACHSERVER_H
#define UI_BROADCASTSEACHSERVER_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QHeaderView>
#include <QtGui/QPushButton>
#include <QtGui/QTextBrowser>
QT_BEGIN_NAMESPACE
class Ui_BroadcastSeachServer
{
public:
QTextBrowser *textBrowser;
QPushButton *pushButton;
void setupUi(QDialog *BroadcastSeachServer)
{
if (BroadcastSeachServer->objectName().isEmpty())
BroadcastSeachServer->setObjectName(QString::fromUtf8("BroadcastSeachServer"));
BroadcastSeachServer->resize(400, 300);
textBrowser = new QTextBrowser(BroadcastSeachServer);
textBrowser->setObjectName(QString::fromUtf8("textBrowser"));
textBrowser->setGeometry(QRect(0, 10, 256, 281));
textBrowser->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
pushButton = new QPushButton(BroadcastSeachServer);
pushButton->setObjectName(QString::fromUtf8("pushButton"));
pushButton->setGeometry(QRect(280, 30, 75, 23));
retranslateUi(BroadcastSeachServer);
QMetaObject::connectSlotsByName(BroadcastSeachServer);
} // setupUi
void retranslateUi(QDialog *BroadcastSeachServer)
{
BroadcastSeachServer->setWindowTitle(QApplication::translate("BroadcastSeachServer", "BroadcastSeachServer", 0, QApplication::UnicodeUTF8));
pushButton->setText(QApplication::translate("BroadcastSeachServer", "Broadcast", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class BroadcastSeachServer: public Ui_BroadcastSeachServer {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_BROADCASTSEACHSERVER_H
| [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
005637263c6e700ab6c788b0516c6fed0f9a1fcc | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/MyGUIEngine/include/MyGUI_MaskPickInfo.h | 1b4eb182e0c703863a6c1434fcc4a9a22e4fea99 | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,524 | h | /*!
@file
@author Albert Semenov
@date 12/2007
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_MASK_PICK_INFO_H__
#define __MYGUI_MASK_PICK_INFO_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_Types.h"
namespace MyGUI
{
class MYGUI_EXPORT MaskPickInfo
{
public:
MaskPickInfo() : width(0), height(0) { }
bool load(const std::string& _file);
bool pick(const IntPoint& _point, const IntCoord& _coord) const
{
if ((0 == _coord.width) || (0 == _coord.height)) return false;
int x = ((_point.left * width) - 1) / _coord.width;
int y = ((_point.top * height) - 1) / _coord.height;
return 0 != data[(size_t)(y * width + x)];
}
bool empty() const
{
return data.empty();
}
private:
std::vector<uint8> data;
int width, height;
};
} // namespace MyGUI
#endif // __MYGUI_MASK_PICK_INFO_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
60
]
]
]
|
849ffc76e50e48217082f6f3d296f17a6d36ef1f | 23ac9facec8a0b73fa3f90a71dcacf9f1ec3ab81 | /title.hpp | 74394ba65a5fd93b48fe56861a33eb7493426e00 | [
"MIT"
]
| permissive | baguette/Asteroids | 686befb4709caa75fe726c3bc8aeadb7d8176dcb | e15daac32dc5ea747e2c9d25546183885122236c | refs/heads/master | 2020-06-03T21:00:17.961767 | 2011-03-25T03:26:25 | 2011-03-25T03:26:25 | 1,524,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,162 | hpp | #ifndef _TITLE_HPP
#define _TITLE_HPP
#include "common.h"
#include "vector.hpp"
#include "scene.hpp"
#include "bitmap.hpp"
class Title : public Scene {
int btn[3];
int keys[3];
int ttime;
int recharge;
bool gc, mouse_control;
int mouse_x, mouse_y;
Vector world_mouse;
int xold, yold;
bool done;
static const int RECHARGE = 7;
float color[4];
/* entity ranges */
static const int ship = 0; /* just one ship */
static const int laser = 1; /* maximum of (ast - laser) lasers... 4 in this case */
static const int ast = 5; /* maximum of (end - ast) asteroids */
int end; /* end of entities... one past the last entity */
Bitmap *title;
public:
Title();
~Title();
virtual Scene *next_scene();
virtual void display();
virtual void timer(int value);
virtual void keyboard(unsigned char key, int x, int y);
virtual void unkeyboard(unsigned char key, int x, int y);
virtual void special(int key, int x, int y);
virtual void unspecial(int key, int x, int y);
virtual void menu(int id);
virtual void mouse(int b, int state, int x, int y);
virtual void motion(int x, int y);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
47
]
]
]
|
9c7726efc9174ebecb5c6ce0335b2808b4479d42 | 7476d2c710c9a48373ce77f8e0113cb6fcc4c93b | /vaultserver/Timer.h | 42f41c094a190e328a11cb413f69640f292c8ba9 | []
| no_license | CmaThomas/Vault-Tec-Multiplayer-Mod | af23777ef39237df28545ee82aa852d687c75bc9 | 5c1294dad16edd00f796635edaf5348227c33933 | refs/heads/master | 2021-01-16T21:13:29.029937 | 2011-10-30T21:58:41 | 2011-10-30T22:00:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | h | #ifndef TIMER_H
#define TIMER_H
#include <map>
#include <string>
#include "boost/any.hpp"
#include "ScriptFunction.h"
#include "Script.h"
#include "PAWN.h"
#include "../vaultmp.h"
#include "../Debug.h"
#include "../Network.h"
#include "../RakNet/gettimeofday.h"
#include "../RakNet/NetworkIDObject.h"
using namespace std;
using namespace RakNet;
/**
* \brief Create timers to be used in scripts
*/
class Timer : public ScriptFunction, public NetworkIDObject
{
private:
~Timer();
unsigned int ms;
unsigned int interval;
vector<boost::any> args;
bool markdelete;
static map<NetworkID, Timer*> timers;
static unsigned int msecs();
public:
Timer( ScriptFunc timer, string def, vector<boost::any> args, unsigned int interval );
Timer( ScriptFuncPAWN timer, AMX* amx, string def, vector<boost::any> args, unsigned int interval );
/**
* \brief Called from the dedicated server main thread
*
* Calls timer functions
*/
static void GlobalTick();
/**
* \brief Terminates a timer
*/
static void Terminate( NetworkID id );
/**
* \brief Terminates all timers
*/
static void TerminateAll();
};
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
26
],
[
57,
59
]
],
[
[
27,
56
]
]
]
|
b52fd020d4ae2bf617e8dbea93fdcfcb7d0aac06 | af96c6474835be2cc34ef21b0c2a45e950bb9148 | /media/libdrm/mobile2/src/util/xml/XMLDocumentImpl.cpp | c1fbc79d3036bf748f72a519e532f7b77511d073 | [
"Apache-2.0",
"LicenseRef-scancode-unicode"
]
| permissive | zsol/android_frameworks_base | 86abe37fcd4136923cab2d6677e558826f087cf9 | 8d18426076382edaaea68392a0298d2c32cfa52e | refs/heads/donut | 2021-07-04T17:24:05.847586 | 2010-01-13T19:24:55 | 2010-01-13T19:24:55 | 469,422 | 14 | 12 | NOASSERTION | 2020-10-01T18:05:31 | 2010-01-12T21:20:20 | Java | UTF-8 | C++ | false | false | 1,496 | cpp | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <util/xml/XMLDocumentImpl.h>
#include <util/xml/XMLElementImpl.h>
/** see XMLDocumentImpl.h */
XMLDocumentImpl::XMLDocumentImpl()
{}
/** see XMLDocumentImpl.h */
XMLDocumentImpl::~XMLDocumentImpl()
{}
/** see XMLDocumentImpl.h */
ElementImpl* XMLDocumentImpl::getDocumentElement() const
{
XMLElementImpl *element = (XMLElementImpl *)(this->getFirstChild());
return element;
}
/** see XMLDocumentImpl.h */
ElementImpl* XMLDocumentImpl::createElement(const DOMString* tagName) const throw (DOMException)
{
if (tagName)
{
XMLElementImpl *element = new XMLElementImpl(tagName);
return element;
}
return NULL;
}
/** see XMLDocumentImpl.h */
TextImpl* XMLDocumentImpl::createTextNode(const DOMString* data) const
{
if (data)
{
TextImpl *text = new TextImpl(data);
return text;
}
return NULL;
}
| [
"[email protected]"
]
| [
[
[
1,
55
]
]
]
|
260337d72270e2161175966d03fb1e0f76a31405 | 847cccd728e768dc801d541a2d1169ef562311cd | /src/Utils/StateMachine.h | 81300e679384058cd2cb3453e5c13ded278d2adf | []
| no_license | aadarshasubedi/Ocerus | 1bea105de9c78b741f3de445601f7dee07987b96 | 4920b99a89f52f991125c9ecfa7353925ea9603c | refs/heads/master | 2021-01-17T17:50:00.472657 | 2011-03-25T13:26:12 | 2011-03-25T13:26:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,931 | h | /// @file
/// Implementation of a basic finite state machine.
#ifndef StateMachine_h__
#define StateMachine_h__
namespace Utils
{
/// Implementation of a basic finite state machine.
/// State type must be given by the template parameter T.
template<typename T> class StateMachine
{
public:
/// Constructs the state machine and sets the initial state.
StateMachine(T initialState): mState(initialState), mNextState(initialState), mLocked(false) {}
/// Default virtual destructor.
virtual ~StateMachine() {}
/// Returns the current state of the machine.
inline T GetState() { return mState; }
/// Immediately changes the state.
void ForceStateChange(T newState)
{
RequestStateChange(newState);
UpdateState();
}
/// Requests a change of state of the machine.
/// The state will be changed after the machine is updated.
/// If lock is set to true all subsequent requests to state change will be discarded until the machine is either
/// unlocked or updated.
bool RequestStateChange(T newState, bool lock = false)
{
if (mLocked)
return false;
mNextState = newState;
mLocked = lock;
return true;
}
/// Unlocks the current state if it's locked. The given state must match the state which was locked.
bool UnlockState(T lockState)
{
if (mNextState != lockState)
return false;
mLocked = false;
return true;
}
/// Updates the machine and changes its state if needed.
void UpdateState()
{
if (mState != mNextState)
{
T oldState = mState;
mState = mNextState;
mLocked = false;
StateChanged(oldState, mState);
}
}
/// Callback to all derived classes. It's called whenever the state changes.
virtual void StateChanged(T /* oldState */, T /* newState */) {}
private:
T mState, mNextState;
bool mLocked;
};
}
#endif // StateMachine_h__
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
49
],
[
51,
65
],
[
67,
74
]
],
[
[
50,
50
],
[
66,
66
]
]
]
|
d1aebb7e83b75b7808a3d5d1b767fd14663b1409 | e9fd4c467daf2eb42d34e0c29ac52b0fd1dad8d6 | /cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp | b7eae23b3897e9f5a72902d5d592f0219fa7d077 | [
"MIT"
]
| permissive | MoSyncLabs/cocos2d-x | 159b24748fb889140e80dbf5c338d02490027538 | 5cc18d0fec01685c61c7e654d71ef084e926a9c5 | refs/heads/master | 2020-12-24T15:14:50.939929 | 2011-11-18T10:56:35 | 2011-11-18T10:56:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,145 | cpp | /****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2009 Jason Booth
Copyright (c) 2009 Robert J Payne
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "cocoa/CCNS.h"
#include "ccMacros.h"
#include "CCTextureCache.h"
#include "CCSpriteFrameCache.h"
#include "CCSpriteFrame.h"
#include "CCSprite.h"
#include "support/TransformUtils.h"
#include "CCFileUtils.h"
#include "CCString.h"
namespace cocos2d {
static CCSpriteFrameCache *pSharedSpriteFrameCache = NULL;
CCSpriteFrameCache* CCSpriteFrameCache::sharedSpriteFrameCache(void)
{
if (! pSharedSpriteFrameCache)
{
pSharedSpriteFrameCache = new CCSpriteFrameCache();
pSharedSpriteFrameCache->init();
}
return pSharedSpriteFrameCache;
}
void CCSpriteFrameCache::purgeSharedSpriteFrameCache(void)
{
CC_SAFE_RELEASE_NULL(pSharedSpriteFrameCache);
}
bool CCSpriteFrameCache::init(void)
{
m_pSpriteFrames= new CCDictionary<std::string, CCSpriteFrame*>();
m_pSpriteFramesAliases = new CCDictionary<std::string, CCString*>();
return true;
}
CCSpriteFrameCache::~CCSpriteFrameCache(void)
{
CC_SAFE_RELEASE(m_pSpriteFrames);
CC_SAFE_RELEASE(m_pSpriteFramesAliases);
}
void CCSpriteFrameCache::addSpriteFramesWithDictionary(CCDictionary<std::string, CCObject*> *dictionary, CCTexture2D *pobTexture)
{
/*
Supported Zwoptex Formats:
ZWTCoordinatesFormatOptionXMLLegacy = 0, // Flash Version
ZWTCoordinatesFormatOptionXML1_0 = 1, // Desktop Version 0.0 - 0.4b
ZWTCoordinatesFormatOptionXML1_1 = 2, // Desktop Version 1.0.0 - 1.0.1
ZWTCoordinatesFormatOptionXML1_2 = 3, // Desktop Version 1.0.2+
*/
CCDictionary<std::string, CCObject*> *metadataDict = (CCDictionary<std::string, CCObject*>*)dictionary->objectForKey(std::string("metadata"));
CCDictionary<std::string, CCObject*> *framesDict = (CCDictionary<std::string, CCObject*>*)dictionary->objectForKey(std::string("frames"));
int format = 0;
// get the format
if(metadataDict != NULL)
{
format = atoi(valueForKey("format", metadataDict));
}
// check the format
assert(format >=0 && format <= 3);
framesDict->begin();
std::string key = "";
CCDictionary<std::string, CCObject*> *frameDict = NULL;
while( (frameDict = (CCDictionary<std::string, CCObject*>*)framesDict->next(&key)) )
{
CCSpriteFrame *spriteFrame = m_pSpriteFrames->objectForKey(key);
if (spriteFrame)
{
continue;
}
if(format == 0)
{
float x = (float)atof(valueForKey("x", frameDict));
float y = (float)atof(valueForKey("y", frameDict));
float w = (float)atof(valueForKey("width", frameDict));
float h = (float)atof(valueForKey("height", frameDict));
float ox = (float)atof(valueForKey("offsetX", frameDict));
float oy = (float)atof(valueForKey("offsetY", frameDict));
int ow = atoi(valueForKey("originalWidth", frameDict));
int oh = atoi(valueForKey("originalHeight", frameDict));
// check ow/oh
if(!ow || !oh)
{
CCLOG("cocos2d: WARNING: originalWidth/Height not found on the CCSpriteFrame. AnchorPoint won't work as expected. Regenrate the .plist");
}
// abs ow/oh
ow = abs(ow);
oh = abs(oh);
// create frame
spriteFrame = new CCSpriteFrame();
spriteFrame->initWithTexture(pobTexture,
CCRectMake(x, y, w, h),
false,
CCPointMake(ox, oy),
CCSizeMake((float)ow, (float)oh)
);
}
else if(format == 1 || format == 2)
{
CCRect frame = CCRectFromString(valueForKey("frame", frameDict));
bool rotated = false;
// rotation
if (format == 2)
{
rotated = atoi(valueForKey("rotated", frameDict)) == 0 ? false : true;
}
CCPoint offset = CCPointFromString(valueForKey("offset", frameDict));
CCSize sourceSize = CCSizeFromString(valueForKey("sourceSize", frameDict));
// create frame
spriteFrame = new CCSpriteFrame();
spriteFrame->initWithTexture(pobTexture,
frame,
rotated,
offset,
sourceSize
);
} else
if (format == 3)
{
// get values
CCSize spriteSize = CCSizeFromString(valueForKey("spriteSize", frameDict));
CCPoint spriteOffset = CCPointFromString(valueForKey("spriteOffset", frameDict));
CCSize spriteSourceSize = CCSizeFromString(valueForKey("spriteSourceSize", frameDict));
CCRect textureRect = CCRectFromString(valueForKey("textureRect", frameDict));
bool textureRotated = atoi(valueForKey("textureRotated", frameDict)) == 0 ? false : true;
// get aliases
CCMutableArray<CCString*> *aliases = (CCMutableArray<CCString*> *) (frameDict->objectForKey(std::string("aliases")));
CCMutableArray<CCString*>::CCMutableArrayIterator iter;
CCString * frameKey = new CCString(key.c_str());
for (iter = aliases->begin(); iter != aliases->end(); ++iter)
{
std::string oneAlias = ((CCString*) (*iter))->m_sString;
if (m_pSpriteFramesAliases->objectForKey(oneAlias))
{
CCLOG("cocos2d: WARNING: an alias with name %s already exists", oneAlias.c_str());
}
m_pSpriteFramesAliases->setObject(frameKey, oneAlias);
}
frameKey->release();
// create frame
spriteFrame = new CCSpriteFrame();
spriteFrame->initWithTexture(pobTexture,
CCRectMake(textureRect.origin.x, textureRect.origin.y, spriteSize.width, spriteSize.height),
textureRotated,
spriteOffset,
spriteSourceSize);
}
// add sprite frame
m_pSpriteFrames->setObject(spriteFrame, key);
spriteFrame->release();
}
}
void CCSpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist, CCTexture2D *pobTexture)
{
const char *pszPath = CCFileUtils::fullPathFromRelativePath(pszPlist);
CCDictionary<std::string, CCObject*> *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(pszPath);
addSpriteFramesWithDictionary(dict, pobTexture);
dict->release();
}
void CCSpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* textureFileName)
{
assert(textureFileName);
CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage(textureFileName);
if (texture)
{
addSpriteFramesWithFile(plist, texture);
}
else
{
CCLOG("cocos2d: CCSpriteFrameCache: couldn't load texture file. File not found %s", textureFileName);
}
}
void CCSpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist)
{
const char *pszPath = CCFileUtils::fullPathFromRelativePath(pszPlist);
CCDictionary<std::string, CCObject*> *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(pszPath);
string texturePath("");
CCDictionary<std::string, CCObject*>* metadataDict = (CCDictionary<std::string, CCObject*>*)dict->objectForKey(string("metadata"));
if (metadataDict)
{
// try to read texture file name from meta data
texturePath = string(valueForKey("textureFileName", metadataDict));
}
if (! texturePath.empty())
{
// build texture path relative to plist file
texturePath = CCFileUtils::fullPathFromRelativeFile(texturePath.c_str(), pszPath);
}
else
{
// build texture path by replacing file extension
texturePath = pszPath;
// remove .xxx
size_t startPos = texturePath.find_last_of(".");
texturePath = texturePath.erase(startPos);
// append .png
texturePath = texturePath.append(".png");
CCLOG("cocos2d: CCSpriteFrameCache: Trying to use file %s as texture", texturePath.c_str());
}
CCTexture2D *pTexture = CCTextureCache::sharedTextureCache()->addImage(texturePath.c_str());
if (pTexture)
{
addSpriteFramesWithDictionary(dict, pTexture);
}
else
{
CCLOG("cocos2d: CCSpriteFrameCache: Couldn't load texture");
}
dict->release();
}
void CCSpriteFrameCache::addSpriteFrame(CCSpriteFrame *pobFrame, const char *pszFrameName)
{
m_pSpriteFrames->setObject(pobFrame, std::string(pszFrameName));
}
void CCSpriteFrameCache::removeSpriteFrames(void)
{
m_pSpriteFrames->removeAllObjects();
m_pSpriteFramesAliases->removeAllObjects();
}
void CCSpriteFrameCache::removeUnusedSpriteFrames(void)
{
m_pSpriteFrames->begin();
std::string key = "";
CCSpriteFrame *spriteFrame = NULL;
while( (spriteFrame = m_pSpriteFrames->next(&key)) )
{
if( spriteFrame->retainCount() == 1 )
{
CCLOG("cocos2d: CCSpriteFrameCache: removing unused frame: %s", key.c_str());
m_pSpriteFrames->removeObjectForKey(key);
}
}
m_pSpriteFrames->end();
}
void CCSpriteFrameCache::removeSpriteFrameByName(const char *pszName)
{
// explicit nil handling
if( ! pszName )
{
return;
}
// Is this an alias ?
CCString *key = (CCString*)m_pSpriteFramesAliases->objectForKey(string(pszName));
if (key)
{
m_pSpriteFrames->removeObjectForKey(key->m_sString);
m_pSpriteFramesAliases->removeObjectForKey(key->m_sString);
}
else
{
m_pSpriteFrames->removeObjectForKey(std::string(pszName));
}
}
void CCSpriteFrameCache::removeSpriteFramesFromFile(const char* plist)
{
const char* path = CCFileUtils::fullPathFromRelativePath(plist);
CCDictionary<std::string, CCObject*>* dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(path);
removeSpriteFramesFromDictionary((CCDictionary<std::string, CCSpriteFrame*>*)dict);
dict->release();
}
void CCSpriteFrameCache::removeSpriteFramesFromDictionary(CCDictionary<std::string, CCSpriteFrame*> *dictionary)
{
CCDictionary<std::string, CCObject*>* framesDict = (CCDictionary<std::string, CCObject*>*)dictionary->objectForKey(string("frames"));
vector<string> keysToRemove;
framesDict->begin();
std::string key = "";
CCDictionary<std::string, CCObject*> *frameDict = NULL;
while( (frameDict = (CCDictionary<std::string, CCObject*>*)framesDict->next(&key)) )
{
if (m_pSpriteFrames->objectForKey(key))
{
keysToRemove.push_back(key);
}
}
framesDict->end();
vector<string>::iterator iter;
for (iter = keysToRemove.begin(); iter != keysToRemove.end(); ++iter)
{
m_pSpriteFrames->removeObjectForKey(*iter);
}
}
void CCSpriteFrameCache::removeSpriteFramesFromTexture(CCTexture2D* texture)
{
vector<string> keysToRemove;
m_pSpriteFrames->begin();
std::string key = "";
CCDictionary<std::string, CCObject*> *frameDict = NULL;
while( (frameDict = (CCDictionary<std::string, CCObject*>*)m_pSpriteFrames->next(&key)) )
{
CCSpriteFrame *frame = m_pSpriteFrames->objectForKey(key);
if (frame && (frame->getTexture() == texture))
{
keysToRemove.push_back(key);
}
}
m_pSpriteFrames->end();
vector<string>::iterator iter;
for (iter = keysToRemove.begin(); iter != keysToRemove.end(); ++iter)
{
m_pSpriteFrames->removeObjectForKey(*iter);
}
}
CCSpriteFrame* CCSpriteFrameCache::spriteFrameByName(const char *pszName)
{
CCSpriteFrame *frame = m_pSpriteFrames->objectForKey(std::string(pszName));
if (! frame)
{
// try alias dictionary
CCString *key = (CCString*)m_pSpriteFramesAliases->objectForKey(string(pszName));
if (key)
{
frame = m_pSpriteFrames->objectForKey(key->m_sString);
if (! frame)
{
CCLOG("cocos2d: CCSpriteFrameCahce: Frame '%s' not found", pszName);
}
}
}
return frame;
}
const char * CCSpriteFrameCache::valueForKey(const char *key, CCDictionary<std::string, CCObject*> *dict)
{
if (dict)
{
CCString *pString = (CCString*)dict->objectForKey(std::string(key));
return pString ? pString->m_sString.c_str() : "";
}
return "";
}
}//namespace cocos2d
| [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
1
],
[
7,
28
],
[
30,
38
],
[
40,
58
],
[
60,
61
],
[
64,
73
],
[
77,
79
],
[
81,
82
],
[
103,
105
],
[
194,
198
],
[
200,
201
],
[
203,
223
],
[
225,
238
],
[
240,
243
],
[
245,
252
],
[
254,
271
],
[
273,
276
],
[
278,
282
],
[
292,
293
],
[
295,
334
],
[
340,
347
],
[
349,
357
],
[
364,
371
],
[
373,
379
],
[
395,
397
],
[
401,
401
],
[
405,
405
]
],
[
[
2,
5
],
[
39,
39
],
[
59,
59
],
[
63,
63
],
[
74,
76
],
[
80,
80
],
[
83,
98
],
[
100,
102
],
[
106,
163
],
[
165,
166
],
[
189,
193
],
[
253,
253
],
[
272,
272
],
[
277,
277
],
[
283,
285
],
[
287,
291
],
[
294,
294
],
[
335,
337
],
[
339,
339
],
[
358,
360
],
[
362,
363
],
[
380,
394
],
[
398,
400
],
[
402,
404
],
[
406,
406
]
],
[
[
6,
6
],
[
29,
29
],
[
62,
62
],
[
164,
164
],
[
167,
170
],
[
172,
188
],
[
199,
199
],
[
202,
202
],
[
224,
224
],
[
239,
239
],
[
244,
244
]
],
[
[
99,
99
],
[
286,
286
],
[
338,
338
],
[
361,
361
]
],
[
[
171,
171
],
[
348,
348
],
[
372,
372
]
]
]
|
b0c8aa552343a3415f080bfc0e0a84406abffddd | 89d2197ed4531892f005d7ee3804774202b1cb8d | /GWEN/include/Gwen/Controls/DockedTabControl.h | 2150f69d1bf0696e5bbcd50d48d971eb6a6455d4 | [
"MIT",
"Zlib"
]
| permissive | hpidcock/gbsfml | ef8172b6c62b1c17d71d59aec9a7ff2da0131d23 | e3aa990dff8c6b95aef92bab3e94affb978409f2 | refs/heads/master | 2020-05-30T15:01:19.182234 | 2010-09-29T06:53:53 | 2010-09-29T06:53:53 | 35,650,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | h | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#pragma once
#include "Gwen/Controls/Base.h"
#include "Gwen/Controls/TabControl.h"
namespace Gwen
{
namespace Controls
{
class GWEN_EXPORT DockedTabControl : public TabControl
{
public:
GWEN_CONTROL( DockedTabControl, TabControl );
void SetShowTitlebar( bool bShow ){ m_pTitleBar->SetHidden( !bShow ); }
void Layout( Skin::Base* skin );
void UpdateTitleBar();
virtual void DragAndDrop_StartDragging( Gwen::DragAndDrop::Package* pPackage, int x, int y );
virtual void DragAndDrop_EndDragging( bool bSuccess, int x, int y );
void MoveTabsTo( DockedTabControl* pTarget );
private:
TabTitleBar* m_pTitleBar;
Base* m_WindowControl;
};
}
}
| [
"haza55@5bf3a77f-ad06-ad18-b9fb-7d0f6dabd793"
]
| [
[
[
1,
38
]
]
]
|
b265ba6e0b3c613298dd9345b314bb4a3e1ad0b9 | d752d83f8bd72d9b280a8c70e28e56e502ef096f | /FugueDLL/Virtual Machine/Operations/Flow/Invoke.cpp | 8a61d06487f1723b610bea247f15434f58ee1139 | []
| no_license | apoch/epoch-language.old | f87b4512ec6bb5591bc1610e21210e0ed6a82104 | b09701714d556442202fccb92405e6886064f4af | refs/heads/master | 2021-01-10T20:17:56.774468 | 2010-03-07T09:19:02 | 2010-03-07T09:19:02 | 34,307,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,719 | cpp | //
// The Epoch Language Project
// FUGUE Virtual Machine
//
// Operation for invoking a function at runtime
//
#include "pch.h"
#include "Virtual Machine/Operations/Flow/Invoke.h"
#include "Virtual Machine/Core Entities/Function.h"
#include "Virtual Machine/Core Entities/Scopes/ScopeDescription.h"
#include "Virtual Machine/SelfAware.inl"
using namespace VM;
using namespace VM::Operations;
//
// Construct a function invocation operation
//
Invoke::Invoke(FunctionBase* function, bool cleanupfunction)
: Function(function),
CleanUpFunction(cleanupfunction)
{
}
//
// Destruct and clean up a function invocation operation
//
Invoke::~Invoke()
{
if(CleanUpFunction)
delete Function;
}
//
// Invoke the bound Epoch function
//
RValuePtr Invoke::ExecuteAndStoreRValue(ExecutionContext& context)
{
return Function->Invoke(context);
}
void Invoke::ExecuteFast(ExecutionContext& context)
{
Function->Invoke(context);
}
//
// Retrieve the function's return type
//
EpochVariableTypeID Invoke::GetType(const ScopeDescription& scope) const
{
return Function->GetType(scope);
}
size_t Invoke::GetNumParameters(const VM::ScopeDescription& scope) const
{
return Function->GetParams().GetNumMembers();
}
template <typename TraverserT>
void Invoke::TraverseHelper(TraverserT& traverser)
{
traverser.TraverseNode(*this);
VM::Function* func = dynamic_cast<VM::Function*>(Function);
if(func)
func->Traverse(traverser);
}
void Invoke::Traverse(Validator::ValidationTraverser& traverser)
{
TraverseHelper(traverser);
}
void Invoke::Traverse(Serialization::SerializationTraverser& traverser)
{
// We do NOT want to traverse into the child when serializing, as other logic will
// ensure that the called function is serialized in the correct location.
traverser.TraverseNode(*this);
}
Traverser::Payload Invoke::GetNodeTraversalPayload(const VM::ScopeDescription* scope) const
{
Traverser::Payload payload;
payload.SetValue(scope->GetFunctionName(Function).c_str());
payload.ParameterCount = GetNumParameters(*scope);
payload.InvokesFunction = true;
return payload;
}
//
// Invoke the bound Epoch function
//
RValuePtr InvokeIndirect::ExecuteAndStoreRValue(ExecutionContext& context)
{
return context.Scope.GetFunction(FunctionName)->Invoke(context);
}
void InvokeIndirect::ExecuteFast(ExecutionContext& context)
{
context.Scope.GetFunction(FunctionName)->Invoke(context);
}
//
// Retrieve the function's return type
//
EpochVariableTypeID InvokeIndirect::GetType(const ScopeDescription& scope) const
{
return scope.GetFunctionType(FunctionName);
}
//
// Determine how many parameters are passed to the function
//
size_t InvokeIndirect::GetNumParameters(const VM::ScopeDescription& scope) const
{
return scope.GetFunctionSignature(FunctionName).GetParamTypes().size();
}
template <typename TraverserT>
void InvokeIndirect::TraverseHelper(TraverserT& traverser)
{
traverser.TraverseNode(*this);
VM::ScopeDescription* scope = traverser.GetCurrentScope();
if(scope)
{
if(scope->HasFunction(FunctionName))
{
VM::Function* func = dynamic_cast<VM::Function*>(scope->GetFunction(FunctionName));
if(func)
func->Traverse(traverser);
}
}
}
void InvokeIndirect::Traverse(Validator::ValidationTraverser& traverser)
{
TraverseHelper(traverser);
}
void InvokeIndirect::Traverse(Serialization::SerializationTraverser& traverser)
{
// We do NOT want to traverse into the child when serializing, as other logic will
// ensure that the called function is serialized in the correct location.
traverser.TraverseNode(*this);
}
| [
"[email protected]",
"don.apoch@localhost"
]
| [
[
[
1,
42
],
[
44,
44
],
[
46,
47
],
[
49,
49
],
[
51,
86
],
[
88,
89
],
[
93,
98
],
[
100,
100
],
[
102,
103
],
[
105,
105
],
[
107,
152
]
],
[
[
43,
43
],
[
45,
45
],
[
48,
48
],
[
50,
50
],
[
87,
87
],
[
90,
92
],
[
99,
99
],
[
101,
101
],
[
104,
104
],
[
106,
106
]
]
]
|
388c79c1d096c0eb793fa2b5cd1274bc35677980 | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Graphic/Renderer/D3D9XMesh.cpp | f85ef64daca86d4253e30c39719520561e83b19e | []
| no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,024 | cpp | #include "D3D9XMesh.h"
#include "D3D9RenderWindow.h"
#include "../Main/Texture.h"
#include "../Main/BoundingBox.h"
namespace Flagship
{
D3D9XMesh::D3D9XMesh()
{
m_iClassType = Base::Mesh_XMesh;
m_pD3D9Mesh = NULL;
m_pBound = new BoundingBox;
}
D3D9XMesh::~D3D9XMesh()
{
SAFE_RELEASE( m_pD3D9Mesh );
SAFE_DELETE( m_pBound );
}
bool D3D9XMesh::ComputeMeshInfo()
{
// 获取D3D9设备指针
LPDIRECT3DDEVICE9 pD3D9Device = ( ( D3D9RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice();
//====================================================================//
// Check if the old declaration contains normals, tangents, binormals //
//====================================================================//
bool bHadNormal = false;
bool bHadTangent = false;
bool bHadBinormal = false;
D3DVERTEXELEMENT9 vertexOldDecl[ MAX_FVF_DECL_SIZE ];
if ( m_pD3D9Mesh && SUCCEEDED( m_pD3D9Mesh->GetDeclaration( vertexOldDecl ) ) )
{
// Go through the declaration and look for the right channels, hoping for a match:
for( UINT iChannelIndex = 0; iChannelIndex < D3DXGetDeclLength( vertexOldDecl ); iChannelIndex++ )
{
if( vertexOldDecl[iChannelIndex].Usage == D3DDECLUSAGE_NORMAL )
{
bHadNormal = true;
}
if( vertexOldDecl[iChannelIndex].Usage == D3DDECLUSAGE_TANGENT )
{
bHadTangent = true;
}
if( vertexOldDecl[iChannelIndex].Usage == D3DDECLUSAGE_BINORMAL )
{
bHadBinormal = true;
}
}
}
if ( bHadNormal && bHadTangent && bHadBinormal )
{
return true;
}
const D3DVERTEXELEMENT9 vertexDecl[] =
{
{ 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 },
{ 0, 12, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
{ 0, 20, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 },
{ 0, 32, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 },
{ 0, 44, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 },
D3DDECL_END()
};
LPD3DXMESH pTempMesh = NULL;
// Clone mesh to match the specified declaration:
if ( FAILED( m_pD3D9Mesh->CloneMesh( m_pD3D9Mesh->GetOptions(), vertexDecl, pD3D9Device, &pTempMesh ) ))
{
SAFE_RELEASE( pTempMesh );
return false;
}
if ( pTempMesh == NULL )
{
// We failed to clone the mesh and we need the tangent space for our effect:
return false;
}
//==============================================================//
// Generate normals / tangents / binormals if they were missing //
//==============================================================//
SAFE_RELEASE( m_pD3D9Mesh );
m_pD3D9Mesh = pTempMesh;
if( ! bHadNormal )
{
// Compute normals in case the meshes have them
D3DXComputeNormals( m_pD3D9Mesh, NULL );
}
DWORD *rgdwAdjacency = NULL;
rgdwAdjacency = new DWORD[ m_pD3D9Mesh->GetNumFaces() * 3 ];
if( rgdwAdjacency == NULL )
{
return false;
}
m_pD3D9Mesh->GenerateAdjacency( 1e-6f, rgdwAdjacency );
// Optimize the mesh for this graphics card's vertex cache
// so when rendering the mesh's triangle list the vertices will
// cache hit more often so it won't have to re-execute the vertex shader
// on those vertices so it will improve perf.
m_pD3D9Mesh->OptimizeInplace( D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, NULL, NULL, NULL );
if ( ! bHadTangent || ! bHadBinormal )
{
ID3DXMesh* pNewMesh;
// Compute tangents, which are required for normal mapping
if ( FAILED( D3DXComputeTangentFrameEx( m_pD3D9Mesh, D3DDECLUSAGE_TEXCOORD, 0, D3DDECLUSAGE_TANGENT, 0, D3DDECLUSAGE_BINORMAL, 0,
D3DDECLUSAGE_NORMAL, 0, 0, rgdwAdjacency, -1.01f,
-0.01f, -1.01f, &pNewMesh, NULL ) ) )
{
return false;
}
SAFE_RELEASE( m_pD3D9Mesh );
m_pD3D9Mesh = pNewMesh;
}
SAFE_DELETE_ARRAY( rgdwAdjacency );
return true;
}
bool D3D9XMesh::Create()
{
// 获取D3D9设备指针
LPDIRECT3DDEVICE9 pD3D9Device = ( ( D3D9RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice();
// 创建D3D9模型对象
HRESULT hr = D3DXLoadMeshFromX( m_szPathName.c_str(), D3DXMESH_MANAGED, pD3D9Device, NULL, NULL, NULL, NULL, &m_pD3D9Mesh );
if ( FAILED( hr ) )
{
char szLog[10240];
char szFile[256];
wcstombs( szFile, m_szPathName.c_str(), 256 );
sprintf( szLog, "D3D9XMesh::Load() Fail! File:%s", szFile );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
// 获取模型格式描述
D3DVERTEXELEMENT9 VertexDecls[MAX_FVF_DECL_SIZE];
m_pD3D9Mesh->GetDeclaration( VertexDecls );
hr = pD3D9Device->CreateVertexDeclaration( VertexDecls, &m_pD3D9VertexDecl );
if ( FAILED( hr ) )
{
char szLog[10240];
char szFile[256];
wcstombs( szFile, m_szPathName.c_str(), 256 );
sprintf( szLog, "D3D9XMesh::Load():CreateVertexDeclaration() Fail! File:%s", szFile );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
// ComputeMeshInfo();
// D3DXSaveMeshToX( L"G:\\Test.x", m_pD3D9Mesh, NULL, NULL, NULL, 0, D3DXF_FILEFORMAT_TEXT );
return true;
}
void D3D9XMesh::Destory()
{
SAFE_RELEASE( m_pD3D9VertexDecl );
SAFE_RELEASE( m_pD3D9Mesh );
}
bool D3D9XMesh::Cache()
{
if ( ! Mesh::Cache() )
{
return false;
}
// 获取缓冲
m_pD3D9Mesh->GetVertexBuffer( &m_pD3D9VertexBuffer );
m_pD3D9Mesh->GetIndexBuffer( &m_pD3D9IndexBuffer );
// 获取缓冲信息
m_dwNumTrangle = m_pD3D9Mesh->GetNumFaces();
m_dwNumVertex = m_pD3D9Mesh->GetNumVertices();
m_dwVertexSize = m_pD3D9Mesh->GetNumBytesPerVertex();
// 设置标记
m_bReady = true;
return true;
}
void D3D9XMesh::UnCache()
{
Mesh::UnCache();
SAFE_RELEASE( m_pD3D9VertexBuffer );
SAFE_RELEASE( m_pD3D9IndexBuffer );
}
} | [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
]
| [
[
[
1,
208
]
]
]
|
8dc18e83a18b377e90228e11c3d7c1efc19335e8 | 4497c10f3b01b7ff259f3eb45d0c094c81337db6 | /Retargeting/Shifmap/Version01/EnergyFunction.cpp | 24044bfd15705a769aadc746c3a0073aef13797e | []
| no_license | liuguoyou/retarget-toolkit | ebda70ad13ab03a003b52bddce0313f0feb4b0d6 | d2d94653b66ea3d4fa4861e1bd8313b93cf4877a | refs/heads/master | 2020-12-28T21:39:38.350998 | 2010-12-23T16:16:59 | 2010-12-23T16:16:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,252 | cpp | #include "StdAfx.h"
#include "EnergyFunction.h"
// this function is the interface with the paper
int ShifmapDataFunction(CvPoint point, CvPoint shift, IplImage* saliency)
{
CvScalar value = cvGet2D(saliency, point.y + shift.y, point.x + shift.x);
return value.val[0] + value.val[1] + value.val[2];
}
int dataFunctionShiftmapH(int pixel, int label, void *extraData)
{
ForDataFunctionH *data = (ForDataFunctionH *) extraData;
CvPoint origin_label = GetMappedPointInitialGuess(pixel, label, data->outputSize, data->shiftSize, data->initialGuess);
if(IsOutside(origin_label, data->inputSize))
return 100000;
double saliency = 0;
//// force the 2 left-most & right-most col to be in the output
//CvPoint pixelPoint = GetPoint(pixel, data->outputSize);
//if(pixelPoint.x == 0 && origin_label.x == 0 && pixelPoint.y == origin_label.y)
// saliency += 100;
//else
// if(pixelPoint.x == data->outputSize.width - 1 && origin_label.x == data->inputSize.width - 1 && pixelPoint.y == origin_label.y)
// saliency += 0;
//else
// saliency += 10000;
CvScalar value = cvGet2D(data->saliency, origin_label.y, origin_label.x);
saliency += value.val[0] + value.val[1] + value.val[2];
return saliency ;
}
int dataFunctionShiftmap(int pixel, int label, void *extraData)
{
ForDataFunction *data = (ForDataFunction *) extraData;
// position of output pixel
CvPoint origin_label = GetMappedPoint(pixel, label, data->outputSize, data->shiftSize);
if(IsOutside(origin_label, data->inputSize))
return 100000;
double saliency = 0;
//// force the 2 left-most & right-most col to be in the output
//CvPoint pixelPoint = GetPoint(pixel, data->outputSize);
//if(pixelPoint.x == 0 && origin_label.x == 0 && pixelPoint.y == origin_label.y)
// saliency += 100;
//else
// if(pixelPoint.x == data->outputSize.width - 1 && origin_label.x == data->inputSize.width - 1 && pixelPoint.y == origin_label.y)
// saliency += 0;
//else
// saliency += 10000;
CvScalar value = cvGet2D(data->saliency, origin_label.y, origin_label.x);
saliency += (value.val[0] + value.val[1] + value.val[2]);
return saliency ;
}
int smoothFunctionShiftmapH(int pixel1, int pixel2, int label1, int label2, void* extraData)
{
ForSmoothFunctionH *data = (ForSmoothFunctionH *) extraData;
CvPoint pixelPoint1 = GetPoint(pixel1, data->outputSize);
CvPoint labelPoint1 = GetMappedPointInitialGuess(pixel1, label1, data->outputSize, data->shiftSize, data->initialGuess);
CvPoint pixelPoint2 = GetPoint(pixel2, data->outputSize);
CvPoint labelPoint2 = GetMappedPointInitialGuess(pixel2, label2, data->outputSize, data->shiftSize, data->initialGuess);
if(IsOutside(labelPoint1, data->inputSize) || IsOutside(labelPoint2, data->inputSize))
return 100000; // prevent mapping outside image
//return 50;
// pre-compute variables:
CvPoint neighbor1 = GetNeighbor(pixelPoint1, pixelPoint2, labelPoint1); // neighbor of label1
CvPoint neighbor2 = GetNeighbor(pixelPoint2, pixelPoint1, labelPoint2); // neighbor of label2
int energy = 0;
energy += SquareColorDifference(labelPoint1, neighbor2, data->image);
energy += SquareColorDifference(labelPoint2, neighbor1, data->image);
// gradient different term
energy += 2 * SquareColorDifference(labelPoint2, neighbor1, data->gradient);
energy += 2 * SquareColorDifference(labelPoint1, neighbor2, data->gradient);
return energy;
}
int smoothFunctionShiftmap(int pixel1, int pixel2, int label1, int label2, void* extraData)
{
ForSmoothFunction *data = (ForSmoothFunction *) extraData;
CvPoint pixelPoint1 = GetPoint(pixel1, data->outputSize);
CvPoint labelPoint1 = GetMappedPoint(pixel1, label1, data->outputSize, data->shiftSize);
CvPoint pixelPoint2 = GetPoint(pixel2, data->outputSize);
CvPoint labelPoint2 = GetMappedPoint(pixel2, label2, data->outputSize, data->shiftSize);
if(IsOutside(labelPoint1, data->inputSize) || IsOutside(labelPoint2, data->inputSize))
return 100000; // prevent mapping outside image
//return 50;
// pre-compute variables:
CvPoint neighbor1 = GetNeighbor(pixelPoint1, pixelPoint2, labelPoint1); // neighbor of label1
CvPoint neighbor2 = GetNeighbor(pixelPoint2, pixelPoint1, labelPoint2); // neighbor of label2
int energy = 0;
energy += SquareColorDifference(labelPoint1, neighbor2, data->image);
energy += SquareColorDifference(labelPoint2, neighbor1, data->image);
// gradient different term
energy += 2 * SquareColorDifference(labelPoint2, neighbor1, data->gradient);
energy += 2 * SquareColorDifference(labelPoint1, neighbor2, data->gradient);
return energy;
}
CvScalar ColorDiffenrece(CvPoint point1, CvPoint point2, IplImage* image)
{
if(!IsInsideImage(point1, image->width, image->height) || !IsInsideImage(point2, image->width, image->height))
return cvScalar(0,0,0,0);
CvScalar value1 = cvGet2D(image, point1.y, point1.x);
CvScalar value2 = cvGet2D(image, point2.y, point2.x);
return cvScalar(value1.val[0] - value2.val[0], value1.val[1] - value2.val[1], value1.val[2] - value2.val[2]);
}
int SquareColorDifference(CvPoint point1, CvPoint point2, IplImage* image)
{
if(!IsInsideImage(point1, image->width, image->height) || !IsInsideImage(point2, image->width, image->height))
return 1000000;
CvScalar value1 = cvGet2D(image, point1.y, point1.x);
CvScalar value2 = cvGet2D(image, point2.y, point2.x);
return SquareDifference(value1, value2);
}
int SquareDifference(CvScalar value1, CvScalar value2)
{
return pow(value1.val[0]-value2.val[0], 2) + pow(value1.val[1]-value2.val[1], 2) + pow(value1.val[2]-value2.val[2], 2);
}
bool IsNeighbor(CvPoint point1, CvPoint point2)
{
if(abs(point1.x - point2.x) <= 1 && abs(point2.y - point1.y) <=1)
return true;
else
return false;
}
CvPoint GetNeighbor(CvPoint pixel1, CvPoint pixel2, CvPoint label)
{
return cvPoint(label.x - pixel1.x + pixel2.x, label.y - pixel1.y + pixel2.y);
}
bool IsInsideImage(CvPoint point, int width, int height)
{
if(point.x < 0 || point.y < 0 || point.x + 1 > width || point.y + 1 > height)
return false;
return true;
} | [
"kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a"
]
| [
[
[
1,
173
]
]
]
|
fa81e8c55889d481742c4fa99b6a4186f99e3569 | f0c08b3ddefc91f1fa342f637b0e947a9a892556 | /branches/develop/cppreflect/include/BuiltinTypeTraits.h | b22d624adc146fc61491e9fa676c1c54275035cf | []
| no_license | BackupTheBerlios/coffeestore-svn | 1db0f60ddb85ccbbdfeb9b3271a687b23e29fc8f | ddee83284fe9875bf0d04e6b7da7a2113e85a040 | refs/heads/master | 2021-01-01T05:30:22.345767 | 2009-10-11T08:55:35 | 2009-10-11T08:55:35 | 40,725,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | h | #ifndef _REFLECT_BUILTIN_TYPE_TRAITS_H_
#define _REFLECT_BUILTIN_TYPE_TRAITS_H_
namespace reflect
{
template <typename T>
class BuiltinTypeTraits
{
template <typename U>
struct IsBool
{
enum { value = false };
};
template <>
struct IsBool<bool>
{
enum { value = true };
};
template <typename U>
struct IsChar
{
enum { value = false };
};
template <>
struct IsChar<char>
{
enum { value = true };
};
template <typename U>
struct IsInt
{
enum { value = false };
};
template <>
struct IsInt<int>
{
enum { value = true };
};
template <typename U>
struct IsFloat
{
enum { value = false };
};
template <>
struct IsFloat<float>
{
enum { value = true };
};
template <typename U>
struct IsDouble
{
enum { value = false };
};
template <>
struct IsDouble<double>
{
enum { value = true };
};
public:
static bool isBool()
{
return IsBool<T>::value;
}
static bool isChar()
{
return IsChar<T>::value;
}
static bool isInt()
{
return IsInt<T>::value;
}
static bool isFloat()
{
return IsFloat<T>::value;
}
static bool isDouble()
{
return IsDouble<T>::value;
}
};
} // namespace reflect
#endif
| [
"fabioppp@e591b805-c13a-0410-8b2d-a75de64125fb"
]
| [
[
[
1,
100
]
]
]
|
796dd2727165da6c468f69bc80fa239faaa2b474 | d08c381305e3e675c3f8253ce88fafd5111b103c | /8_8_2008/curve_-project/doc/arm_curve_going/arm_curve_3/display.h | 836bb770c2d09f880307c91c19985167b3d5d58a | []
| no_license | happypeter/tinylion | 07ea77febf6dff84089eddd6e1e47cd2ae032eb2 | 2f802f291ff43c568f9ef5eb846719efca03cc80 | refs/heads/master | 2020-06-03T09:14:19.682005 | 2010-10-19T09:12:56 | 2010-10-19T09:12:56 | 914,128 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 892 | h | #ifndef DISPLAY_H
#define DISPLAY_H
#ifndef QT_H
#include <qwidget.h>
#endif // QT_H
class QTimer;
class Screen;
class QStringList;
class QString;
class QLineEdit;
class QPushButton;
class DisplayWidget : public QWidget {
Q_OBJECT
public:
DisplayWidget( QWidget *parent=0, const char *name=0 );
QSize sizeHint() const;
double readCurveDate();
void readFile();
void run();
protected:
//virtual void showEvent ( QShowEvent * );
private slots:
void start();
void stop();
private:
Screen *screen1;
Screen *screen2;
Screen *screen3;
QLineEdit *lineEdit;
QPushButton *startButton, *stopButton;
QTimer *timer;
enum { Margin = 40};
QString str;
int time;
double yval;
};
#endif // PLOT_H
| [
"[email protected]"
]
| [
[
[
1,
44
]
]
]
|
442be410a40bf65fd16d1eccf0dd85ce0646365f | 1d2705c9be9ee0f974c224eb794f2f8a9e9a3d50 | /exploring_machine/exploration_machine.h | 677285d0f16fdc1f08b6c9560a4cec403e0ca80e | []
| no_license | llvllrbreeze/alcorapp | dfe2551f36d346d73d998f59d602c5de46ef60f7 | 3ad24edd52c19f0896228f55539aa8bbbb011aac | refs/heads/master | 2021-01-10T07:36:01.058011 | 2008-12-16T12:51:50 | 2008-12-16T12:51:50 | 47,865,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,827 | h | /////////////////////////////////////////////////////////////////////////////
// Name: exploration_machine.h
// Purpose:
// Author: Andrea Carbone
// Modified by:
// Created: 23/03/2007 02:33:06
// RCS-ID:
// Copyright: Alcor
// Licence:
/////////////////////////////////////////////////////////////////////////////
#ifndef _EXPLORATION_MACHINE_H_
#define _EXPLORATION_MACHINE_H_
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma interface "exploration_machine.h"
#endif
/*!
* Includes
*/
////@begin includes
#include "wx/image.h"
#include "exploration_machine_gui.h"
////@end includes
/*!
* Forward declarations
*/
////@begin forward declarations
////@end forward declarations
/*!
* Control identifiers
*/
////@begin control identifiers
////@end control identifiers
/*!
* Exploration_machineApp class declaration
*/
class Exploration_machineApp: public wxApp
{
DECLARE_CLASS( Exploration_machineApp )
DECLARE_EVENT_TABLE()
public:
/// Constructor
Exploration_machineApp();
/// Initialises member variables
void Init();
/// Initialises the application
virtual bool OnInit();
/// Called on exit
virtual int OnExit();
////@begin Exploration_machineApp event handler declarations
////@end Exploration_machineApp event handler declarations
////@begin Exploration_machineApp member function declarations
////@end Exploration_machineApp member function declarations
////@begin Exploration_machineApp member variables
////@end Exploration_machineApp member variables
};
/*!
* Application instance declaration
*/
////@begin declare app
DECLARE_APP(Exploration_machineApp)
////@end declare app
#endif
// _EXPLORATION_MACHINE_H_
| [
"andrea.carbone@1ffd000b-a628-0410-9a29-793f135cad17"
]
| [
[
[
1,
85
]
]
]
|
acd81297563026172313edd8cf6f7e8bad0aad18 | 09f09cd06656848ed80f132c7073568c4ce87bd5 | /BMP2TIF/BmpToTif.h | 2a4afe0c605e0147e7dc9bdc626da65bbb41c101 | []
| no_license | cyb3727/annrecognition | 90ecf3af572f8b629b276a06af51785f656ca2be | 6e4f200e1119196eba5e7fe56efa93e3ed978bc1 | refs/heads/master | 2021-01-17T11:31:39.865232 | 2011-07-10T13:50:44 | 2011-07-10T13:50:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,701 | h | // BmpToTif.h : main header file for the BMPTOTIF application
//
// this is your duty to fill value according to u...
// any problem? let me know...I may help u...
// w w w . p e c i n t . c o m (remove space & place in internet & get my con tact)
// sumit(under-score)kapoor1980(at)hot mail(dot) com
// sumit (under-score) kapoor1980(at)ya hoo(dot) com
// sumit (under-score) kapoor1980(at)red iff mail(dot) com
#if !defined(AFX_BMPTOTIF_H__46CA0AC5_3A15_11D8_A667_0050BA8B6949__INCLUDED_)
#define AFX_BMPTOTIF_H__46CA0AC5_3A15_11D8_A667_0050BA8B6949__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifndef __AFXWIN_H__
#error include 'stdafx.h' before including this file for PCH
#endif
#include "resource.h" // main symbols
/////////////////////////////////////////////////////////////////////////////
// CBmpToTifApp:
// See BmpToTif.cpp for the implementation of this class
//
class CBmpToTifApp : public CWinApp
{
public:
CBmpToTifApp();
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CBmpToTifApp)
public:
virtual BOOL InitInstance();
//}}AFX_VIRTUAL
// Implementation
//{{AFX_MSG(CBmpToTifApp)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BMPTOTIF_H__46CA0AC5_3A15_11D8_A667_0050BA8B6949__INCLUDED_)
| [
"damoguyan8844@2e4fddd8-cc6a-11de-b393-33af5e5426e5"
]
| [
[
[
1,
55
]
]
]
|
930ecd9dd04861258a91625fad37d5bdfb12483a | edc5deb5739fdae8494f72380b2d931ec271ebfe | /src/imocapdata.h | e395b169d8a32f9afd319f09379d39b1a60030fc | []
| no_license | shuncox/mocapfileimporter | 0d1f5f00ed8b5637261b00bd07f7d57dfbd04245 | ae8a9b45826c81680ff159beb0a9a185843d27c8 | refs/heads/master | 2021-01-10T22:28:27.250839 | 2009-01-08T15:13:57 | 2009-01-08T15:13:57 | 33,865,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,519 | h | ////////////////////////////////////////////////////////////////////////////
//
// MoCap File Importer
// Copyright(c) Shun Cox ([email protected])
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//
////////////////////////////////////////////////////////////////////////////
//
// $Id: imocapdata.h,v 1.3 2006/05/26 07:18:59 zhangshun Exp $
//
////////////////////////////////////////////////////////////////////////////
#ifndef __IMOCAPDATA_H__
#define __IMOCAPDATA_H__
#define REQUIRE_IOSTREAM
#include <maya/MIOStream.h>
#include <string>
#include <vector>
#include "iskeleton.h"
#include "iconverter.h"
using namespace std;
// postfix for effectors
const string effectorPostfix("_Effector");
// horizontal line
const string horizontalLine(40, '=');
// replacement of space character
const string replacementOfSpace("_");
// max words in joint name
const unsigned int maxWordsJointName = 10;
// max number of joints
const unsigned int maxNumJoints = 1000;
// max frame rate
const unsigned int maxFrameRate = 1000;
// max number of frames
const unsigned int maxNumFrames = 100000;
// motion translation threshold
const double motionThreshold = 0.001;
///////////////////////////////////////////////////////////////////////////////
// class for frames
//
//class iMotionFrames {
//public:
//
// iMotionFrames() {};
//
// // frames are accessible through operator[]
// iFrame &operator[](unsigned int idx) {
// if (idx >= frames.size()) throw badIndex("Frame index out of bounds");
// return frames[idx];
// }
// iFrame operator[](unsigned int idx) const {
// if (idx >= frames.size()) throw badIndex("const Frame index out of bounds");
// return frames[idx];
// }
//private:
// vector<iFrame> frames;
//};
///////////////////////////////////////////////////////////////////////////////
// base class for mocap data
//
class iMocapData {
protected:
istream *input;
iSkeleton *skeleton;
public:
// constructor
iMocapData() : input(NULL), skeleton(NULL) {}
iMocapData(istream *in, iSkeleton *sk) : input(in), skeleton(sk) {}
// attach input stream and skeleton
int attach(istream *in, iSkeleton *sk);
// load mocap data
int load();
protected:
virtual int parsing() { return 0; };
};
#endif // #ifndef __IMOCAPDATA_H__
| [
"shuncox@50fdbc7c-dc67-11dd-9759-139c9ab14fc6"
]
| [
[
[
1,
88
]
]
]
|
d915fd5fed7c9d2f34822c7e6548fe12704f17ae | 41371839eaa16ada179d580f7b2c1878600b718e | /UVa/Volume I/00186.cpp | 5397fd4037b8e4bc3a53f5b2299ce07abdd2f1d4 | []
| no_license | marinvhs/SMAS | 5481aecaaea859d123077417c9ee9f90e36cc721 | 2241dc612a653a885cf9c1565d3ca2010a6201b0 | refs/heads/master | 2021-01-22T16:31:03.431389 | 2009-10-01T02:33:01 | 2009-10-01T02:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,645 | cpp | /////////////////////////////////
// 00186 - Trip Routing
/////////////////////////////////
#include<cstring>
#include<cstdlib>
#include<cstdio>
char hashc[101][21];
char hashe[201][11];
char temp[101];
int adj[101][101];
int adj2[101][101];
int a,b,c,d,indexc, index2;
bool visitado[27];
int dist[27];
int anterior[27];
int total;
const int oo = 1<<30;
void mostrarRota(int S)
{
if(S==anterior[S]) return;
mostrarRota(anterior[S]);
total+=adj[anterior[S]][S];
printf("%-20s %-20s %-10s %5d\n",hashc[anterior[S]],hashc[S],hashe[adj2[anterior[S]][S]],adj[anterior[S]][S]);
}
int hash(bool type, char* str)
{
if(type){
int i;
for(i=1; i<=indexc; i++){
if(strcmp(hashc[i], str)==0) return i;
}
strcpy(hashc[++indexc], str);
return indexc;
}
else{
int i;
for(i=1; i<=index2; i++){
if(strcmp(hashe[i], str)==0) return i;
}
strcpy(hashe[++index2], str);
return index2;
}
}
int main()
{
int i, j;
for(i = 1; i < 100; i++){
for(j = 1; j < 100; j++){
adj[i][j]=oo;
}
}
while(gets(temp)){
if(strlen(temp)==0) break;
a=hash(1, strtok(temp, ","));
b=hash(1, strtok(NULL, ","));
c=hash(0, strtok(NULL, ","));
d=atoi(strtok(NULL, "\n"));
if(d < adj[a][b]){
adj[a][b]=adj[b][a]=d;
adj2[a][b]=adj2[b][a]=c;
}
}
while(gets(temp)){
int inicio=hash(1, strtok(temp, ","));
int fim=hash(1, strtok(NULL, "\n"));
for(i=1; i< 27; dist[i] = oo,i++) visitado[i] = anterior[i] = 0;
visitado[inicio]=1;
for(i=1; i< 27; i++){
dist[i]=adj[inicio][i];
anterior[i]=inicio;
}
while(true){
int min=oo, valormin;
for(i = 1; i< 27; i++){
if(dist[i]<min&&!visitado[i]){
min = dist[i];
valormin = i;
}
}
visitado[valormin]=1;
for(i = 1; i< 27; i++){
if(dist[i]>dist[valormin]+adj[valormin][i]&&!visitado[i]){
dist[i]=dist[valormin]+adj[valormin][i];
anterior[i]=valormin;
}
}
if(valormin==fim){
total=0;
printf("\n\n%-20s %-20s %-10s %-5s\n","From","To","Route","Miles");
printf("-------------------- -------------------- ---------- -----\n");
mostrarRota(valormin);
printf("%58s\n","-----");
printf("%47s %10d\n","Total", total);
break;
}
}
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
99
]
]
]
|
2548d98c23ae6ad81a4e7cd563eba3efd6c3f29d | d54d8b1bbc9575f3c96853e0c67f17c1ad7ab546 | /hlsdk-2.3-p3/singleplayer/ricochet/cl_dll/GameStudioModelRenderer.cpp | 365bf35b6abc047f1997909eb276563300576de8 | []
| no_license | joropito/amxxgroup | 637ee71e250ffd6a7e628f77893caef4c4b1af0a | f948042ee63ebac6ad0332f8a77393322157fa8f | refs/heads/master | 2021-01-10T09:21:31.449489 | 2010-04-11T21:34:27 | 2010-04-11T21:34:27 | 47,087,485 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,505 | cpp | #include <assert.h>
#include "hud.h"
#include "cl_util.h"
#include "const.h"
#include "com_model.h"
#include "studio.h"
#include "entity_state.h"
#include "cl_entity.h"
#include "dlight.h"
#include "triangleapi.h"
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include "studio_util.h"
#include "r_studioint.h"
#include "StudioModelRenderer.h"
#include "GameStudioModelRenderer.h"
void Ricochet_GetSequence( int *seq, int *gaitseq );
void Ricochet_GetOrientation( float *o, float *a );
float g_flStartScaleTime;
int iPrevRenderState;
int iRenderStateChanged;
// Global engine <-> studio model rendering code interface
extern engine_studio_api_t IEngineStudio;
typedef struct
{
vec3_t origin;
vec3_t angles;
vec3_t realangles;
float animtime;
float frame;
int sequence;
int gaitsequence;
float framerate;
int m_fSequenceLoops;
int m_fSequenceFinished;
byte controller[ 4 ];
byte blending[ 2 ];
latchedvars_t lv;
} client_anim_state_t;
static client_anim_state_t g_state;
static client_anim_state_t g_clientstate;
// The renderer object, created on the stack.
CGameStudioModelRenderer g_StudioRenderer;
/*
====================
CGameStudioModelRenderer
====================
*/
CGameStudioModelRenderer::CGameStudioModelRenderer( void )
{
// If you want to predict animations locally, set this to TRUE
// NOTE: The animation code is somewhat broken, but gives you a sense for how
// to do client side animation of the predicted player in a third person game.
m_bLocal = false;
}
/*
====================
StudioSetupBones
====================
*/
void CGameStudioModelRenderer::StudioSetupBones ( void )
{
int i;
double f;
mstudiobone_t *pbones;
mstudioseqdesc_t *pseqdesc;
mstudioanim_t *panim;
static float pos[MAXSTUDIOBONES][3];
static vec4_t q[MAXSTUDIOBONES];
float bonematrix[3][4];
static float pos2[MAXSTUDIOBONES][3];
static vec4_t q2[MAXSTUDIOBONES];
static float pos3[MAXSTUDIOBONES][3];
static vec4_t q3[MAXSTUDIOBONES];
static float pos4[MAXSTUDIOBONES][3];
static vec4_t q4[MAXSTUDIOBONES];
// Use default bone setup for nonplayers
if ( !m_pCurrentEntity->player )
{
CStudioModelRenderer::StudioSetupBones();
return;
}
// Bound sequence number.
if ( m_pCurrentEntity->curstate.sequence >= m_pStudioHeader->numseq )
{
m_pCurrentEntity->curstate.sequence = 0;
}
pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->curstate.sequence;
if ( m_pPlayerInfo && m_pPlayerInfo->gaitsequence != 0 )
{
f = m_pPlayerInfo->gaitframe;
}
else
{
f = StudioEstimateFrame( pseqdesc );
}
// Discwar knows how to do three way blending
if ( pseqdesc->numblends == 3 )
{
float s;
// Get left anim
panim = StudioGetAnim( m_pRenderModel, pseqdesc );
// Blending is 0-127 == Left to Middle, 128 to 255 == Middle to right
if ( m_pCurrentEntity->curstate.blending[0] <= 127 )
{
StudioCalcRotations( pos, q, pseqdesc, panim, f );
// Scale 0-127 blending up to 0-255
s = m_pCurrentEntity->curstate.blending[0];
s = ( s * 2.0 );
}
else
{
// Skip ahead to middle
panim += m_pStudioHeader->numbones;
StudioCalcRotations( pos, q, pseqdesc, panim, f );
// Scale 127-255 blending up to 0-255
s = m_pCurrentEntity->curstate.blending[0];
s = 2.0 * ( s - 127.0 );
}
// Normalize interpolant
s /= 255.0;
// Go to middle or right
panim += m_pStudioHeader->numbones;
StudioCalcRotations( pos2, q2, pseqdesc, panim, f );
// Spherically interpolate the bones
StudioSlerpBones( q, pos, q2, pos2, s );
}
else
{
panim = StudioGetAnim( m_pRenderModel, pseqdesc );
StudioCalcRotations( pos, q, pseqdesc, panim, f );
}
// Are we in the process of transitioning from one sequence to another.
if ( m_fDoInterp &&
m_pCurrentEntity->latched.sequencetime &&
( m_pCurrentEntity->latched.sequencetime + 0.2 > m_clTime ) &&
( m_pCurrentEntity->latched.prevsequence < m_pStudioHeader->numseq ))
{
// blend from last sequence
static float pos1b[MAXSTUDIOBONES][3];
static vec4_t q1b[MAXSTUDIOBONES];
float s;
// Blending value into last sequence
unsigned char prevseqblending = m_pCurrentEntity->latched.prevseqblending[ 0 ];
// Point at previous sequenece
pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->latched.prevsequence;
// Know how to do three way blends
if ( pseqdesc->numblends == 3 )
{
float s;
// Get left animation
panim = StudioGetAnim( m_pRenderModel, pseqdesc );
if ( prevseqblending <= 127 )
{
// Set up bones based on final frame of previous sequence
StudioCalcRotations( pos1b, q1b, pseqdesc, panim, m_pCurrentEntity->latched.prevframe );
s = prevseqblending;
s = ( s * 2.0 );
}
else
{
// Skip to middle blend
panim += m_pStudioHeader->numbones;
StudioCalcRotations( pos1b, q1b, pseqdesc, panim, m_pCurrentEntity->latched.prevframe );
s = prevseqblending;
s = 2.0 * ( s - 127.0 );
}
// Normalize
s /= 255.0;
panim += m_pStudioHeader->numbones;
StudioCalcRotations( pos2, q2, pseqdesc, panim, m_pCurrentEntity->latched.prevframe );
// Interpolate bones
StudioSlerpBones( q1b, pos1b, q2, pos2, s );
}
else
{
panim = StudioGetAnim( m_pRenderModel, pseqdesc );
// clip prevframe
StudioCalcRotations( pos1b, q1b, pseqdesc, panim, m_pCurrentEntity->latched.prevframe );
}
// Now blend last frame of previous sequence with current sequence.
s = 1.0 - (m_clTime - m_pCurrentEntity->latched.sequencetime) / 0.2;
StudioSlerpBones( q, pos, q1b, pos1b, s );
}
else
{
m_pCurrentEntity->latched.prevframe = f;
}
// Now convert quaternions and bone positions into matrices
pbones = (mstudiobone_t *)((byte *)m_pStudioHeader + m_pStudioHeader->boneindex);
for (i = 0; i < m_pStudioHeader->numbones; i++)
{
QuaternionMatrix( q[i], bonematrix );
bonematrix[0][3] = pos[i][0];
bonematrix[1][3] = pos[i][1];
bonematrix[2][3] = pos[i][2];
if (pbones[i].parent == -1)
{
if ( IEngineStudio.IsHardware() )
{
ConcatTransforms ((*m_protationmatrix), bonematrix, (*m_pbonetransform)[i]);
ConcatTransforms ((*m_protationmatrix), bonematrix, (*m_plighttransform)[i]);
}
else
{
ConcatTransforms ((*m_paliastransform), bonematrix, (*m_pbonetransform)[i]);
ConcatTransforms ((*m_protationmatrix), bonematrix, (*m_plighttransform)[i]);
}
// Apply client-side effects to the transformation matrix
StudioFxTransform( m_pCurrentEntity, (*m_pbonetransform)[i] );
}
else
{
ConcatTransforms ((*m_pbonetransform)[pbones[i].parent], bonematrix, (*m_pbonetransform)[i]);
ConcatTransforms ((*m_plighttransform)[pbones[i].parent], bonematrix, (*m_plighttransform)[i]);
}
}
}
/*
====================
StudioEstimateGait
====================
*/
void CGameStudioModelRenderer::StudioEstimateGait( entity_state_t *pplayer )
{
float dt;
vec3_t est_velocity;
dt = (m_clTime - m_clOldTime);
dt = max( 0.0, dt );
dt = min( 1.0, dt );
if (dt == 0 || m_pPlayerInfo->renderframe == m_nFrameCount)
{
m_flGaitMovement = 0;
return;
}
// VectorAdd( pplayer->velocity, pplayer->prediction_error, est_velocity );
if ( m_fGaitEstimation )
{
VectorSubtract( m_pCurrentEntity->origin, m_pPlayerInfo->prevgaitorigin, est_velocity );
VectorCopy( m_pCurrentEntity->origin, m_pPlayerInfo->prevgaitorigin );
m_flGaitMovement = Length( est_velocity );
if (dt <= 0 || m_flGaitMovement / dt < 5)
{
m_flGaitMovement = 0;
est_velocity[0] = 0;
est_velocity[1] = 0;
}
}
else
{
VectorCopy( pplayer->velocity, est_velocity );
m_flGaitMovement = Length( est_velocity ) * dt;
}
if (est_velocity[1] == 0 && est_velocity[0] == 0)
{
float flYawDiff = m_pCurrentEntity->angles[YAW] - m_pPlayerInfo->gaityaw;
flYawDiff = flYawDiff - (int)(flYawDiff / 360) * 360;
if (flYawDiff > 180)
flYawDiff -= 360;
if (flYawDiff < -180)
flYawDiff += 360;
if (dt < 0.25)
flYawDiff *= dt * 4;
else
flYawDiff *= dt;
m_pPlayerInfo->gaityaw += flYawDiff;
m_pPlayerInfo->gaityaw = m_pPlayerInfo->gaityaw - (int)(m_pPlayerInfo->gaityaw / 360) * 360;
m_flGaitMovement = 0;
}
else
{
m_pPlayerInfo->gaityaw = (atan2(est_velocity[1], est_velocity[0]) * 180 / M_PI);
if (m_pPlayerInfo->gaityaw > 180)
m_pPlayerInfo->gaityaw = 180;
if (m_pPlayerInfo->gaityaw < -180)
m_pPlayerInfo->gaityaw = -180;
}
}
/*
====================
StudioProcessGait
====================
*/
void CGameStudioModelRenderer::StudioProcessGait( entity_state_t *pplayer )
{
mstudioseqdesc_t *pseqdesc;
float dt;
float flYaw; // view direction relative to movement
pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + m_pCurrentEntity->curstate.sequence;
m_pCurrentEntity->angles[PITCH] = 0;
m_pCurrentEntity->latched.prevangles[PITCH] = m_pCurrentEntity->angles[PITCH];
dt = (m_clTime - m_clOldTime);
dt = max( 0.0, dt );
dt = min( 1.0, dt );
StudioEstimateGait( pplayer );
// calc side to side turning
flYaw = m_pCurrentEntity->angles[YAW] - m_pPlayerInfo->gaityaw;
flYaw = fmod( flYaw, 360.0 );
if (flYaw < -180)
{
flYaw = flYaw + 360;
}
else if (flYaw > 180)
{
flYaw = flYaw - 360;
}
float maxyaw = 120.0;
if (flYaw > maxyaw)
{
m_pPlayerInfo->gaityaw = m_pPlayerInfo->gaityaw - 180;
m_flGaitMovement = -m_flGaitMovement;
flYaw = flYaw - 180;
}
else if (flYaw < -maxyaw)
{
m_pPlayerInfo->gaityaw = m_pPlayerInfo->gaityaw + 180;
m_flGaitMovement = -m_flGaitMovement;
flYaw = flYaw + 180;
}
float blend_yaw = ( flYaw / 90.0 ) * 128.0 + 127.0;
blend_yaw = min( 255.0, blend_yaw );
blend_yaw = max( 0.0, blend_yaw );
blend_yaw = 255.0 - blend_yaw;
m_pCurrentEntity->curstate.blending[0] = (int)(blend_yaw);
m_pCurrentEntity->latched.prevblending[0] = m_pCurrentEntity->curstate.blending[0];
m_pCurrentEntity->latched.prevseqblending[0] = m_pCurrentEntity->curstate.blending[0];
m_pCurrentEntity->angles[YAW] = m_pPlayerInfo->gaityaw;
if (m_pCurrentEntity->angles[YAW] < -0)
{
m_pCurrentEntity->angles[YAW] += 360;
}
m_pCurrentEntity->latched.prevangles[YAW] = m_pCurrentEntity->angles[YAW];
pseqdesc = (mstudioseqdesc_t *)((byte *)m_pStudioHeader + m_pStudioHeader->seqindex) + pplayer->gaitsequence;
// Calc gait frame
if (pseqdesc->linearmovement[0] > 0)
{
m_pPlayerInfo->gaitframe += (m_flGaitMovement / pseqdesc->linearmovement[0]) * pseqdesc->numframes;
}
else
{
m_pPlayerInfo->gaitframe += pseqdesc->fps * dt * m_pCurrentEntity->curstate.framerate;
}
// Do modulo
m_pPlayerInfo->gaitframe = m_pPlayerInfo->gaitframe - (int)(m_pPlayerInfo->gaitframe / pseqdesc->numframes) * pseqdesc->numframes;
if (m_pPlayerInfo->gaitframe < 0)
{
m_pPlayerInfo->gaitframe += pseqdesc->numframes;
}
}
/*
==============================
SavePlayerState
For local player, in third person, we need to store real render data and then
setup for with fake/client side animation data
==============================
*/
void CGameStudioModelRenderer::SavePlayerState( entity_state_t *pplayer )
{
client_anim_state_t *st;
cl_entity_t *ent = IEngineStudio.GetCurrentEntity();
assert( ent );
if ( !ent )
return;
st = &g_state;
st->angles = ent->curstate.angles;
st->origin = ent->curstate.origin;
st->realangles = ent->angles;
st->sequence = ent->curstate.sequence;
st->gaitsequence = pplayer->gaitsequence;
st->animtime = ent->curstate.animtime;
st->frame = ent->curstate.frame;
st->framerate = ent->curstate.framerate;
memcpy( st->blending, ent->curstate.blending, 2 );
memcpy( st->controller, ent->curstate.controller, 4 );
st->lv = ent->latched;
}
void GetSequenceInfo( void *pmodel, client_anim_state_t *pev, float *pflFrameRate, float *pflGroundSpeed )
{
studiohdr_t *pstudiohdr;
pstudiohdr = (studiohdr_t *)pmodel;
if (! pstudiohdr)
return;
mstudioseqdesc_t *pseqdesc;
if (pev->sequence >= pstudiohdr->numseq)
{
*pflFrameRate = 0.0;
*pflGroundSpeed = 0.0;
return;
}
pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex) + (int)pev->sequence;
if (pseqdesc->numframes > 1)
{
*pflFrameRate = 256 * pseqdesc->fps / (pseqdesc->numframes - 1);
*pflGroundSpeed = sqrt( pseqdesc->linearmovement[0]*pseqdesc->linearmovement[0]+ pseqdesc->linearmovement[1]*pseqdesc->linearmovement[1]+ pseqdesc->linearmovement[2]*pseqdesc->linearmovement[2] );
*pflGroundSpeed = *pflGroundSpeed * pseqdesc->fps / (pseqdesc->numframes - 1);
}
else
{
*pflFrameRate = 256.0;
*pflGroundSpeed = 0.0;
}
}
int GetSequenceFlags( void *pmodel, client_anim_state_t *pev )
{
studiohdr_t *pstudiohdr;
pstudiohdr = (studiohdr_t *)pmodel;
if ( !pstudiohdr || pev->sequence >= pstudiohdr->numseq )
return 0;
mstudioseqdesc_t *pseqdesc;
pseqdesc = (mstudioseqdesc_t *)((byte *)pstudiohdr + pstudiohdr->seqindex) + (int)pev->sequence;
return pseqdesc->flags;
}
float StudioFrameAdvance ( client_anim_state_t *st, float framerate, float flInterval )
{
if (flInterval == 0.0)
{
flInterval = (gEngfuncs.GetClientTime() - st->animtime);
if (flInterval <= 0.001)
{
st->animtime = gEngfuncs.GetClientTime();
return 0.0;
}
}
if (!st->animtime)
flInterval = 0.0;
st->frame += flInterval * framerate * st->framerate;
st->animtime = gEngfuncs.GetClientTime();
if (st->frame < 0.0 || st->frame >= 256.0)
{
if ( st->m_fSequenceLoops )
st->frame -= (int)(st->frame / 256.0) * 256.0;
else
st->frame = (st->frame < 0.0) ? 0 : 255;
st->m_fSequenceFinished = TRUE; // just in case it wasn't caught in GetEvents
}
return flInterval;
}
/*
==============================
SetupClientAnimation
Called to set up local player's animation values
==============================
*/
void CGameStudioModelRenderer::SetupClientAnimation( entity_state_t *pplayer )
{
static double oldtime;
double curtime, dt;
client_anim_state_t *st;
float fr, gs;
cl_entity_t *ent = IEngineStudio.GetCurrentEntity();
assert( ent );
if ( !ent )
return;
curtime = gEngfuncs.GetClientTime();
dt = curtime - oldtime;
dt = min( 1.0, max( 0.0, dt ) );
oldtime = curtime;
st = &g_clientstate;
st->framerate = 1.0;
int oldseq = st->sequence;
Ricochet_GetSequence( &st->sequence, &st->gaitsequence );
Ricochet_GetOrientation( (float *)&st->origin, (float *)&st->angles );
st->realangles = st->angles;
if ( st->sequence != oldseq )
{
st->frame = 0.0;
st->lv.prevsequence = oldseq;
st->lv.sequencetime = st->animtime;
memcpy( st->lv.prevseqblending, st->blending, 2 );
memcpy( st->lv.prevcontroller, st->controller, 4 );
}
void *pmodel = (studiohdr_t *)IEngineStudio.Mod_Extradata( ent->model );
GetSequenceInfo( pmodel, st, &fr, &gs );
st->m_fSequenceLoops = ((GetSequenceFlags( pmodel, st ) & STUDIO_LOOPING) != 0);
StudioFrameAdvance( st, fr, dt );
ent->angles = st->realangles;
ent->curstate.angles = st->angles;
ent->curstate.origin = st->origin;
ent->curstate.sequence = st->sequence;
pplayer->gaitsequence = st->gaitsequence;
ent->curstate.animtime = st->animtime;
ent->curstate.frame = st->frame;
ent->curstate.framerate = st->framerate;
memcpy( ent->curstate.blending, st->blending, 2 );
memcpy( ent->curstate.controller, st->controller, 4 );
ent->latched = st->lv;
}
/*
==============================
RestorePlayerState
Called to restore original player state information
==============================
*/
void CGameStudioModelRenderer::RestorePlayerState( entity_state_t *pplayer )
{
client_anim_state_t *st;
cl_entity_t *ent = IEngineStudio.GetCurrentEntity();
assert( ent );
if ( !ent )
return;
st = &g_clientstate;
st->angles = ent->curstate.angles;
st->origin = ent->curstate.origin;
st->realangles = ent->angles;
st->sequence = ent->curstate.sequence;
st->gaitsequence = pplayer->gaitsequence;
st->animtime = ent->curstate.animtime;
st->frame = ent->curstate.frame;
st->framerate = ent->curstate.framerate;
memcpy( st->blending, ent->curstate.blending, 2 );
memcpy( st->controller, ent->curstate.controller, 4 );
st->lv = ent->latched;
st = &g_state;
ent->curstate.angles = st->angles;
ent->curstate.origin = st->origin;
ent->angles = st->realangles;
ent->curstate.sequence = st->sequence;
pplayer->gaitsequence = st->gaitsequence;
ent->curstate.animtime = st->animtime;
ent->curstate.frame = st->frame;
ent->curstate.framerate = st->framerate;
memcpy( ent->curstate.blending, st->blending, 2 );
memcpy( ent->curstate.controller, st->controller, 4 );
ent->latched = st->lv;
}
/*
==============================
StudioDrawPlayer
==============================
*/
int CGameStudioModelRenderer::StudioDrawPlayer( int flags, entity_state_t *pplayer )
{
int iret = 0;
bool isLocalPlayer = false;
// Set up for client?
if ( m_bLocal && IEngineStudio.GetCurrentEntity() == gEngfuncs.GetLocalPlayer() )
{
isLocalPlayer = true;
}
if ( isLocalPlayer )
{
// Store original data
SavePlayerState( pplayer );
// Copy in client side animation data
SetupClientAnimation( pplayer );
}
// Call real draw function
iret = _StudioDrawPlayer( flags, pplayer );
// Restore for client?
if ( isLocalPlayer )
{
// Restore the original data for the player
RestorePlayerState( pplayer );
}
return iret;
}
/*
====================
_StudioDrawPlayer
====================
*/
int CGameStudioModelRenderer::_StudioDrawPlayer( int flags, entity_state_t *pplayer )
{
alight_t lighting;
vec3_t dir;
m_pCurrentEntity = IEngineStudio.GetCurrentEntity();
IEngineStudio.GetTimes( &m_nFrameCount, &m_clTime, &m_clOldTime );
IEngineStudio.GetViewInfo( m_vRenderOrigin, m_vUp, m_vRight, m_vNormal );
IEngineStudio.GetAliasScale( &m_fSoftwareXScale, &m_fSoftwareYScale );
m_nPlayerIndex = pplayer->number - 1;
if (m_nPlayerIndex < 0 || m_nPlayerIndex >= gEngfuncs.GetMaxClients())
return 0;
m_pRenderModel = IEngineStudio.SetupPlayerModel( m_nPlayerIndex );
if (m_pRenderModel == NULL)
return 0;
m_pStudioHeader = (studiohdr_t *)IEngineStudio.Mod_Extradata (m_pRenderModel);
IEngineStudio.StudioSetHeader( m_pStudioHeader );
IEngineStudio.SetRenderModel( m_pRenderModel );
if (pplayer->gaitsequence)
{
vec3_t orig_angles;
m_pPlayerInfo = IEngineStudio.PlayerInfo( m_nPlayerIndex );
VectorCopy( m_pCurrentEntity->angles, orig_angles );
StudioProcessGait( pplayer );
m_pPlayerInfo->gaitsequence = pplayer->gaitsequence;
m_pPlayerInfo = NULL;
StudioSetUpTransform( 0 );
VectorCopy( orig_angles, m_pCurrentEntity->angles );
}
else
{
m_pCurrentEntity->curstate.controller[0] = 127;
m_pCurrentEntity->curstate.controller[1] = 127;
m_pCurrentEntity->curstate.controller[2] = 127;
m_pCurrentEntity->curstate.controller[3] = 127;
m_pCurrentEntity->latched.prevcontroller[0] = m_pCurrentEntity->curstate.controller[0];
m_pCurrentEntity->latched.prevcontroller[1] = m_pCurrentEntity->curstate.controller[1];
m_pCurrentEntity->latched.prevcontroller[2] = m_pCurrentEntity->curstate.controller[2];
m_pCurrentEntity->latched.prevcontroller[3] = m_pCurrentEntity->curstate.controller[3];
m_pPlayerInfo = IEngineStudio.PlayerInfo( m_nPlayerIndex );
m_pPlayerInfo->gaitsequence = 0;
StudioSetUpTransform( 0 );
}
if (flags & STUDIO_RENDER)
{
// see if the bounding box lets us trivially reject, also sets
if (!IEngineStudio.StudioCheckBBox ())
return 0;
(*m_pModelsDrawn)++;
(*m_pStudioModelCount)++; // render data cache cookie
if (m_pStudioHeader->numbodyparts == 0)
return 1;
}
m_pPlayerInfo = IEngineStudio.PlayerInfo( m_nPlayerIndex );
StudioSetupBones( );
StudioSaveBones( );
m_pPlayerInfo->renderframe = m_nFrameCount;
m_pPlayerInfo = NULL;
if (flags & STUDIO_EVENTS)
{
StudioCalcAttachments( );
IEngineStudio.StudioClientEvents( );
// copy attachments into global entity array
if ( m_pCurrentEntity->index > 0 )
{
cl_entity_t *ent = gEngfuncs.GetEntityByIndex( m_pCurrentEntity->index );
memcpy( ent->attachment, m_pCurrentEntity->attachment, sizeof( vec3_t ) * 4 );
}
}
if (flags & STUDIO_RENDER)
{
/*
if (m_pCvarHiModels->value && m_pRenderModel != m_pCurrentEntity->model )
{
// show highest resolution multiplayer model
m_pCurrentEntity->curstate.body = 255;
}
if (!(m_pCvarDeveloper->value == 0 && gEngfuncs.GetMaxClients() == 1 ) && ( m_pRenderModel == m_pCurrentEntity->model ) )
{
m_pCurrentEntity->curstate.body = 1; // force helmet
}
*/
lighting.plightvec = dir;
IEngineStudio.StudioDynamicLight(m_pCurrentEntity, &lighting );
IEngineStudio.StudioEntityLight( &lighting );
// model and frame independant
IEngineStudio.StudioSetupLighting (&lighting);
m_pPlayerInfo = IEngineStudio.PlayerInfo( m_nPlayerIndex );
// get remap colors
m_nTopColor = m_pPlayerInfo->topcolor;
if (m_nTopColor < 0)
m_nTopColor = 0;
if (m_nTopColor > 360)
m_nTopColor = 360;
m_nBottomColor = m_pPlayerInfo->bottomcolor;
if (m_nBottomColor < 0)
m_nBottomColor = 0;
if (m_nBottomColor > 360)
m_nBottomColor = 360;
IEngineStudio.StudioSetRemapColors( m_nTopColor, m_nBottomColor );
StudioRenderModel( );
m_pPlayerInfo = NULL;
if (pplayer->weaponmodel)
{
cl_entity_t saveent = *m_pCurrentEntity;
model_t *pweaponmodel = IEngineStudio.GetModelByIndex( pplayer->weaponmodel );
m_pStudioHeader = (studiohdr_t *)IEngineStudio.Mod_Extradata (pweaponmodel);
IEngineStudio.StudioSetHeader( m_pStudioHeader );
StudioMergeBones( pweaponmodel);
IEngineStudio.StudioSetupLighting (&lighting);
StudioRenderModel( );
StudioCalcAttachments( );
*m_pCurrentEntity = saveent;
}
}
return 1;
}
/*
====================
Studio_FxTransform
====================
*/
void CGameStudioModelRenderer::StudioFxTransform( cl_entity_t *ent, float transform[3][4] )
{
switch( ent->curstate.renderfx )
{
case kRenderFxDistort:
case kRenderFxHologram:
if ( gEngfuncs.pfnRandomLong(0,49) == 0 )
{
int axis = gEngfuncs.pfnRandomLong(0,1);
if ( axis == 1 ) // Choose between x & z
axis = 2;
VectorScale( transform[axis], gEngfuncs.pfnRandomFloat(1,1.484), transform[axis] );
}
else if ( gEngfuncs.pfnRandomLong(0,49) == 0 )
{
float offset;
int axis = gEngfuncs.pfnRandomLong(0,1);
if ( axis == 1 ) // Choose between x & z
axis = 2;
offset = gEngfuncs.pfnRandomFloat(-10,10);
transform[gEngfuncs.pfnRandomLong(0,2)][3] += offset;
}
break;
case kRenderFxExplode:
{
if ( iRenderStateChanged )
{
g_flStartScaleTime = m_clTime;
iRenderStateChanged = FALSE;
}
// Make the Model continue to shrink
float flTimeDelta = m_clTime - g_flStartScaleTime;
if ( flTimeDelta > 0 )
{
float flScale = 0.001;
// Goes almost all away
if ( flTimeDelta <= 2.0 )
flScale = 1.0 - (flTimeDelta / 2.0);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
transform[i][j] *= flScale;
}
}
}
break;
}
}
////////////////////////////////////
// Hooks to class implementation
////////////////////////////////////
/*
====================
R_StudioDrawPlayer
====================
*/
int R_StudioDrawPlayer( int flags, entity_state_t *pplayer )
{
return g_StudioRenderer.StudioDrawPlayer( flags, pplayer );
}
/*
====================
R_StudioDrawModel
====================
*/
int R_StudioDrawModel( int flags )
{
return g_StudioRenderer.StudioDrawModel( flags );
}
/*
====================
R_StudioInit
====================
*/
void R_StudioInit( void )
{
g_StudioRenderer.Init();
}
// The simple drawing interface we'll pass back to the engine
r_studio_interface_t studio =
{
STUDIO_INTERFACE_VERSION,
R_StudioDrawModel,
R_StudioDrawPlayer,
};
/*
====================
HUD_GetStudioModelInterface
Export this function for the engine to use the studio renderer class to render objects.
====================
*/
#define DLLEXPORT __declspec( dllexport )
extern "C" int DLLEXPORT HUD_GetStudioModelInterface( int version, struct r_studio_interface_s **ppinterface, struct engine_studio_api_s *pstudio )
{
if ( version != STUDIO_INTERFACE_VERSION )
return 0;
// Point the engine to our callbacks
*ppinterface = &studio;
// Copy in engine helper functions
memcpy( &IEngineStudio, pstudio, sizeof( IEngineStudio ) );
// Initialize local variables, etc.
R_StudioInit();
// Success
return 1;
}
| [
"joropito@23c7d628-c96c-11de-a380-73d83ba7c083"
]
| [
[
[
1,
982
]
]
]
|
2841fe40ba665100f7ab2b83a67d82f2199c8496 | 6581dacb25182f7f5d7afb39975dc622914defc7 | /QQHideWnd/QQHideWnd.cpp | c57b965c464af71376466932b749ee80a7dd18c5 | []
| no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,139 | cpp | // QQHideWnd.cpp : Defines the class behaviors for the application.
//Download by http://www.newxing.com
#include "stdafx.h"
#include "QQHideWnd.h"
#include "QQHideWndDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CQQHideWndApp
BEGIN_MESSAGE_MAP(CQQHideWndApp, CWinApp)
//{{AFX_MSG_MAP(CQQHideWndApp)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CQQHideWndApp construction
CQQHideWndApp::CQQHideWndApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CQQHideWndApp object
CQQHideWndApp theApp;
/////////////////////////////////////////////////////////////////////////////
// CQQHideWndApp initialization
BOOL CQQHideWndApp::InitInstance()
{
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
CQQHideWndDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
]
| [
[
[
1,
74
]
]
]
|
c48ab3941ee4e4896ea7aed6b8fbd4475718ae0c | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/wheel/MyWheelController/include/WheelEngine.h | 16413828888ab4b835f0a2a981a2a0b1369768a0 | []
| no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 665 | h | #ifndef __Orz_WheelEngine_h__
#define __Orz_WheelEngine_h__
#include "WheelControllerConfig.h"
#include "WheelEngineInterface.h"
namespace Orz
{
class _OrzMyWheelControlleExport WheelEngine:public WheelEngineInterface
{
public:
WheelEngine(Orz::EventWorld * world);
virtual ~WheelEngine(void);
private:
virtual void startGame(size_t time);
//virtual void pushRate(void);
virtual void runGame(void);
//virtual void clickButton(int id, int button);
virtual TimeType getTime(void) const;
Orz::EventWorld * _world;
WheelEngineListener * _listener;
TimeType _time;
// Accounts _acc;
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
febe98d0b5d7eba9c28377e41ba4a40c050906ae | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/zombie/tutorials/src/signals_tutorial/receiverscript_cmds.cc | c22c0c2e2f8668a5d4806a75535a25360c5554b1 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,655 | cc | //-----------------------------------------------------------------------------
// receiverscript_cmds.cc
// (C) 2005 Conjurer Services, S.A.
//-----------------------------------------------------------------------------
#include "signals_tutorial/receiverscript.h"
static void n_trigger( void *, nCmd * );
static void n_onint( void *, nCmd * );
//------------------------------------------------------------------------------
/**
@scriptclass
receiverscript
@cppclass
ReceiverScript
@superclass
nroot
@classinfo
Test Receiver of signals.
*/
void
n_initcmds_ReceiverScript( nClass * cl )
{
cl->BeginCmds();
cl->AddCmd( "v_trigger_v", 'TRIG', n_trigger );
cl->AddCmd( "v_onint_i", 'OINT', n_onint );
cl->EndCmds();
}
//------------------------------------------------------------------------------
/**
@cmd
trigger
@input
v
@output
v
@info
Test command.
*/
static void n_trigger( void *o, nCmd * /*cmd*/ )
{
ReceiverScript *self = static_cast<ReceiverScript *>( o );
self->Trigger();
}
//------------------------------------------------------------------------------
/**
@cmd
onint
@input
i
@output
v
@info
Test command with parameter.
*/
static void n_onint( void *o, nCmd * cmd )
{
ReceiverScript *self = static_cast<ReceiverScript *>( o );
self->OnInt( cmd->In()->GetI() );
}
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
68
]
]
]
|
6eea0a4e53c2801b83b5978bc16db353a2e837cb | b7b58c5e83ae0e868414e8a6900b92fcfa87b4b1 | /Tools/TBLlib/TableReader.cpp | 8018000d064ef7e55050b2f1707bcc5238b53b26 | []
| no_license | dailongao/cheat-fusion | 87df8bd58845f30808600b72167ff6c778a36245 | ab7cd0fe56df0edabb9064da70b93a2856df7fac | refs/heads/master | 2021-01-10T12:42:37.958692 | 2010-12-31T13:42:51 | 2010-12-31T13:42:51 | 51,513,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,031 | cpp | //#include "stdafx.h" // Needed for MSVC++ Precompiled Headers option
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <list>
#include <cctype>
#include "TableReader.h"
const char* HexAlphaNum = "ABCDEFabcdef0123456789";
TBL_ERROR err;
TableReader::TableReader(const TableReaderType type)
{
DefAutoFill = "00";
DefAlignFill = "00";
DefEndLine = "{N}";
DefEndString = "{end}";
LongestHex = 1;
memset(LongestText, 0, 256*4);
ReaderType = type;
LineNumber = 0;
if(type == ReadTypeInsert)
InitHexTable();
}
TableReader::~TableReader()
{
// Clear the maps
if(!LookupText.empty())
LookupText.clear();
if(!LookupHex.empty())
LookupHex.clear();
if(!LinkedEntries.empty())
LinkedEntries.clear();
}
bool TableReader::OpenTable(const char* TableFilename)
{
list<string> EntryList;
string Line;
ifstream tablefile(TableFilename);
if(!tablefile.is_open())
{
err.LineNumber = -1;
err.Description = "Table file cannot be opened";
TableErrors.push_back(err);
return false;
}
// Gather text into the list
while(!tablefile.eof())
{
getline(tablefile, Line);
EntryList.push_back(Line);
}
tablefile.close();
for(list<string>::iterator i = EntryList.begin(); i != EntryList.end(); i++)
{
LineNumber++;
if(i->length() == 0) // Blank line
continue;
switch((*i)[0]) // first character of the line
{
case '$':
break;
case '(': // Bookmark (not implemented)
break;
case '[': // Script dump (not implemented)
break;
case '{': // Script insert (not implemented)
break;
case '@': //insert auto fill char
parseautofill(*i);
break;
case '~': //insert test alignment fill char
break;
case '/': // End string value
break;
case '*': // End line value
break;
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': // Normal entry value
parseentry(*i);
break;
default:
err.LineNumber = LineNumber;
err.Description = "First character of the line is not a recognized table character";
TableErrors.push_back(err);
break;
}
}
if(TableErrors.empty())
return true;
else
return false;
}
//-----------------------------------------------------------------------------
// GetTextValue() - Returns a Text String from a Hexstring from the table
//-----------------------------------------------------------------------------
bool TableReader::GetTextValue(const string& CapitalHexString, string& RetTextString, int& linkbytes)
{
//string s = HexString;
//transform(HexString.begin(), HexString.end(), s.begin(), (int(*)(int))toupper);
linkbytes = 0;
StringPairMapIt it = LookupText.find(CapitalHexString);
if(it != LookupText.end()) // Found
{
RetTextString = it->second;
return true;
}
LinkedEntryMapIt linkit = LinkedEntries.find(CapitalHexString);
if(linkit != LinkedEntries.end())
{
RetTextString = linkit->second.Text;
linkbytes = linkit->second.Number;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
// GetHexValue() - Returns a Hex value from a Text string from the table
//-----------------------------------------------------------------------------
bool TableReader::GetHexValue(const string& Textstring, string& RetHexString)
{
StringPairMapIt it = LookupHex.find(Textstring);
if(it != LookupHex.end()) // Found
{
RetHexString = it->second;
return true;
}
return false;
}
bool TableReader::OutputError(const char* filename)
{
ofstream logtxt(filename, ios::out);
vector<TBL_ERROR>::iterator it;
for(it = TableErrors.begin();it!=TableErrors.end();it++)
logtxt<<"line"<<it->LineNumber<<":"<<it->Description<<"\n";
logtxt.close();
}
bool TableReader::OutputError()
{
vector<TBL_ERROR>::iterator it;
for(it = TableErrors.begin();it!=TableErrors.end();it++)
cout<<"line"<<it->LineNumber<<":"<<it->Description<<"\n";
}
//-----------------------------------------------------------------------------
// AddToMaps() - Adds an entry to the table, if there aren't duplicates
//-----------------------------------------------------------------------------
inline bool TableReader::AddToMaps(string& HexString, string& TextString)
{
string ModString = TextString;
if(ReaderType == ReadTypeDump) // Check for multiple HexString entries (Dumping confliction)
{
transform(HexString.begin(), HexString.end(), HexString.begin(), (int(*)(int))toupper);
StringPairMapIt it = LookupText.lower_bound(HexString);
if(it != LookupText.end() && !(LookupText.key_comp()(HexString, it->first))) // Multiple entry
{
err.LineNumber = LineNumber;
err.Description = "Hex token part of the string is already in the table.";
TableErrors.push_back(err);
return false;
}
else // Dumpers only need to look up text
LookupText.insert(it, StringPairMap::value_type(HexString, ModString));
}
if(ReaderType == ReadTypeInsert) // Check for multiple TextString entries (Insertion confliction)
{
StringPairMapIt it = LookupHex.lower_bound(ModString);
if(it != LookupHex.end() && !(LookupHex.key_comp()(ModString, it->first))) // Multiple entry
{
err.LineNumber = LineNumber;
err.Description = "Text token part of the string is already in the table.";
TableErrors.push_back(err);
return false;
}
else // Inserters only need to look up hex values
LookupHex.insert(it, StringPairMap::value_type(ModString, HexString));
}
// Update hex/text lengths
if(LongestHex < (int)HexString.length())
LongestHex = (int)HexString.length();
if(ModString.length() > 0)
{
if(LongestText[(unsigned char)ModString[0]] < (int)ModString.length())
LongestText[(unsigned char)ModString[0]] = (int)ModString.length();
}
return true;
}
//-----------------------------------------------------------------------------
// InitHexTable() - Adds the <$XX> strings for insertion
//-----------------------------------------------------------------------------
inline void TableReader::InitHexTable()
{
char textbuf[16];
char hexbuf[16];
// Add capital case <$XX> entries to the lookup map
for(unsigned int i = 0; i < 0x100; i++)
{
sprintf(textbuf, "<$%02X>", i);
sprintf(hexbuf, "%02X", i);
LookupHex.insert(map<string, string>::value_type(string(textbuf), string(hexbuf)));
}
// Add lower case <$xx> entries to the lookup map
for(unsigned int i = 0x0A; i < 0x100; i += 0x10)
{
for(unsigned int j = 0; j < 6; j++)
{
sprintf(textbuf, "<$%02x>", i+j);
sprintf(hexbuf, "%02X", i+j);
LookupHex.insert(map<string, string>::value_type(string(textbuf), string(hexbuf)));
}
}
}
//-----------------------------------------------------------------------------
// parseautofill() - parses a auto fill table value: ex, @00
//-----------------------------------------------------------------------------
inline bool TableReader::parseautofill(string line)
{
line.erase(0, 1);
size_t pos = line.find_first_not_of(HexAlphaNum, 0);
string hexstr;
hexstr = line.substr(0, pos);
if((hexstr.length() % 2) != 0)
{
err.LineNumber = LineNumber;
err.Description = "Hex token length is not a multiple of 2";
TableErrors.push_back(err);
return false;
}
DefAutoFill = hexstr;
return true;
}
//-----------------------------------------------------------------------------
// parseentry() - parses a hex=text line
//-----------------------------------------------------------------------------
inline bool TableReader::parseentry(string line)
{
size_t pos = line.find_first_not_of(HexAlphaNum, 0);
if(pos == string::npos)
{
err.LineNumber = LineNumber;
err.Description = "Entry only contains hex values";
TableErrors.push_back(err);
return false;
}
string hexstr = line.substr(0, pos);
if((hexstr.length() % 2) != 0)
{
err.LineNumber = LineNumber;
err.Description = "Hex token length is not a multiple of 2";
TableErrors.push_back(err);
return false;
}
string textstr;
pos = line.find_first_of("=", 0);
if(pos == line.length() - 1) // End of the line, blank entry means it's an error
{
err.LineNumber = LineNumber;
err.Description = "Contains a blank entry";
TableErrors.push_back(err);
return false;
}
line.erase(0, pos+1);
pos = line.find_first_of(":",0);
if(pos == string::npos)
{
textstr = line;
}
else
{
int lpos = line.find_first_of("{",0);
int rpos = line.find_first_not_of("0123456789}", pos+1);
if(lpos!=string::npos && rpos==string::npos){
line.replace(pos, 1, "}");
textstr = line.substr(0, pos+1);
if(ReaderType == ReadTypeDump){
line.erase(0, pos+1);
LINKED_ENTRY l;
l.Text = textstr;
l.Number = strtoul(line.c_str(), NULL, 10);
transform(hexstr.begin(), hexstr.end(), hexstr.begin(), (int(*)(int))toupper);
LinkedEntryMapIt it = LinkedEntries.lower_bound(hexstr);
if(it != LinkedEntries.end() && !(LinkedEntries.key_comp()(hexstr, it->first))) // Multiple entries
{
err.LineNumber = LineNumber;
err.Description = "Hex token part of the linked entry is already in the table.";
TableErrors.push_back(err);
return false;
}
else // Inserters only need to look up hex values
LinkedEntries.insert(it, LinkedEntryMap::value_type(hexstr, l));
if(LongestHex < (int)hexstr.length())
LongestHex = (int)hexstr.length();
return true;
}
}
else{
err.LineNumber = LineNumber;
err.Description = "Link CtrlCode format error";
TableErrors.push_back(err);
return false;
}
}
return AddToMaps(hexstr, textstr);
}
| [
"forbbsneo@1e91e87a-c719-11dd-86c2-0f8696b7b6f9"
]
| [
[
[
1,
347
]
]
]
|
e730cfcce2cfdba87bb21adf8949ca94c5de15f8 | 37426b6752e2a3f0a254f76168f55fed549594da | /amf3_tests/amf3_uint29_tests.cpp | 05406e810fd0dcda98f922de01eea067422c859f | []
| no_license | Over-Zero/amf3lib | 09c3db95b3b60bcdd78791e282a9803fc6e2cfee | 527c3e1c66b5fb858a859c4bc631733e23c91132 | refs/heads/master | 2021-01-22T03:01:28.063344 | 2011-11-08T15:42:04 | 2011-11-08T15:42:04 | 2,732,494 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,207 | cpp | #include "amf3_tests_pch.h"
#include "amf3_uint29.h"
#include <UnitTest++.h>
SUITE(UInt29)
{
using namespace AMF3;
TEST(Value0)
{
std::ostringstream os;
os << UInt29(0);
UInt29 result;
std::istringstream is(os.str());
is >> result;
CHECK_EQUAL(0u, result.GetValue());
}
TEST(Value7F)
{
std::ostringstream os;
os << UInt29(0x7F);
UInt29 result;
std::istringstream is(os.str());
is >> result;
CHECK_EQUAL(0x7Fu, result.GetValue());
}
TEST(Value80)
{
std::ostringstream os;
os << UInt29(0x7F);
UInt29 result;
std::istringstream is(os.str());
is >> result;
CHECK_EQUAL(0x7Fu, result.GetValue());
}
TEST(Value3FFF)
{
std::ostringstream os;
os << UInt29(0x3FFF);
UInt29 result;
std::istringstream is(os.str());
is >> result;
CHECK_EQUAL(0x3FFFu, result.GetValue());
}
TEST(Value4000)
{
std::ostringstream os;
os << UInt29(0x4000);
UInt29 result;
std::istringstream is(os.str());
is >> result;
CHECK_EQUAL(0x4000u, result.GetValue());
}
TEST(Value1FFFFF)
{
std::ostringstream os;
os << UInt29(0x1FFFFF);
UInt29 result;
std::istringstream is(os.str());
is >> result;
CHECK_EQUAL(0x1FFFFFu, result.GetValue());
}
TEST(Value200000)
{
std::ostringstream os;
os << UInt29(0x200000);
UInt29 result;
std::istringstream is(os.str());
is >> result;
CHECK_EQUAL(0x200000u, result.GetValue());
}
TEST(Value1FFFFFFF)
{
std::ostringstream os;
os << UInt29(0x1FFFFFFF);
UInt29 result;
std::istringstream is(os.str());
is >> result;
CHECK_EQUAL(0x1FFFFFFFu, result.GetValue());
}
TEST(Value20000000)
{
std::ostringstream os;
CHECK_THROW(os << UInt29(0x20000000), const char*);
}
}
| [
"[email protected]"
]
| [
[
[
1,
110
]
]
]
|
3dcd2d5c21ef02f2e28a50bfcf2ef912e2e048fa | 032ea9816579a9869070a285d0224f95ba6a767b | /3dProject/trunk/Bunker.cpp | 381d630563ccb198b4f1e15b7b745027a33e7719 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | sennheiser1986/oglproject | 3577bae81c0e0b75001bde57b8628d59c8a5c3cf | d975ed5a4392036dace4388e976b88fc4280a116 | refs/heads/master | 2021-01-13T17:05:14.740056 | 2010-06-01T15:48:38 | 2010-06-01T15:48:38 | 39,767,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,894 | cpp | /*
* 3dProject
* Geert d'Hoine
* (c) 2010
*/
#include "Bunker.h"
#include "Map.h"
#include <math.h>
#include <iostream>
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
using namespace std;
Bunker::Bunker(float wIn, float hIn, float xIn, float yIn, float zIn, int* inTex)
: StaticObject(xIn, yIn, zIn) {
w = wIn;
h = hIn;
textures = inTex;
Map * instance = Map::getInstance();
int cellSide = instance->getCellSide();
int * minMapCoord = instance->convertWorldCoordToMapCoord(x-w/2-cellSide,z-w/2-cellSide);
int minRow = minMapCoord[0];
int minCol = minMapCoord[1];
int * maxMapCoord = instance->convertWorldCoordToMapCoord(x+w/2+cellSide,z+w/2+cellSide);
int maxRow = maxMapCoord[0];
int maxCol = maxMapCoord[1];
int width = maxCol - minCol;
int height = maxRow - minRow;
instance->markBlock(minRow, minCol, height, width, 9);
}
float Bunker::getWidth() {
return w;
}
float Bunker::getHeight() {
return h;
}
void Bunker::changeTexture(int texture, int index) {
textures[index] = texture;
}
Bunker::Bunker() {};
Bunker::~Bunker() {};
void Bunker::draw() {
// index: 0 => front, 1 => right, 2 => back, 3 => left,
int _textureFront, _textureRight, _textureBack, _textureLeft;
_textureFront = textures[0];
_textureRight = textures[1];
_textureBack = textures[2];
_textureLeft = textures[3];
glPushMatrix();
glTranslatef(x, y + (h / 2), z);
//glRotatef(0.0f, 1.0f, 0.0f, 0.0f);
//glRotatef(0.0f, 0.0f, 1.0f, 0.0f);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER,0.1f);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//Top face
//glBindTexture(GL_TEXTURE_2D, _textureTop);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//glBegin(GL_QUADS);
//glNormal3f(0.0, 1.0f, 0.0f);
//glTexCoord2f(0.0f, 1.0f);
//glVertex3f(-HORI_SIZE / 2, VERTI_SIZE / 2, -HORI_SIZE / 2);
//glTexCoord2f(0.0f, 0.0f);
//glVertex3f(-HORI_SIZE / 2, VERTI_SIZE / 2, HORI_SIZE / 2);
//glTexCoord2f(1.0f, 1.0f);
//glVertex3f(HORI_SIZE / 2, VERTI_SIZE / 2, HORI_SIZE / 2);
//glTexCoord2f(1.0f, 1.0f);
//glVertex3f(HORI_SIZE / 2, VERTI_SIZE / 2, -HORI_SIZE / 2);
//Bottom face
glNormal3f(0.0, -1.0f, 0.0f);
glVertex3f(-w / 2, -h / 2, -w / 2);
glVertex3f(w / 2, -h / 2, -w / 2);
glVertex3f(w / 2, -h / 2, w / 2);
glVertex3f(-w / 2, -h / 2, w / 2);
//Left face
glEnd();
glBindTexture(GL_TEXTURE_2D, _textureLeft);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBegin(GL_QUADS);
glNormal3f(-1.0, 0.0f, 0.0f);
// x y z
// -1 -1 -1 = bottom left
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-w / 2, -h / 2, -w / 2);
// -1 -1 1 = bottom right
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-w / 2, -h / 2, w / 2);
// -1 1 1 = top right
glTexCoord2f(1.0f, 1.0f);
glVertex3f(-w / 2, h / 2, w / 2);
// -1 1 -1 = top left
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-w / 2, h / 2, -w / 2);
//Right face
glEnd();
glBindTexture(GL_TEXTURE_2D, _textureRight);
//glTexParameteri(GL_TEzxxXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBegin(GL_QUADS);
glNormal3f(1.0, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f);
// x y z
// 1 -1 -1 = bottom right
glVertex3f(w / 2, -h / 2, -w / 2);
glTexCoord2f(1.0f, 1.0f);
// 1 1 -1 = top right
glVertex3f(w / 2, h / 2, -w / 2);
glTexCoord2f(0.0f, 1.0f);
// 1 1 1 = top left
glVertex3f(w / 2, h / 2, w / 2);
glTexCoord2f(0.0f, 0.0f);
// 1 -1 1 = bottom left
glVertex3f(w / 2, -h / 2, w / 2);
glEnd();
//Front face
glBindTexture(GL_TEXTURE_2D, _textureFront);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBegin(GL_QUADS);
glNormal3f(0.0, 0.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f);
// -1 -1 1 = bottom left
glVertex3f(-w / 2, -h / 2, w / 2);
glTexCoord2f(1.0f, 0.0f);
// 1 -1 1 = bottom right
glVertex3f(w / 2, -h / 2, w / 2);
glTexCoord2f(1.0f, 1.0f);
// 1 1 1 = top right
glVertex3f(w / 2, h / 2, w / 2);
glTexCoord2f(0.0f, 1.0f);
// -1 1 1 = top left
glVertex3f(-w / 2, h / 2, w / 2);
glEnd();
//Back face
glBindTexture(GL_TEXTURE_2D, _textureBack);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
///glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBegin(GL_QUADS);
glNormal3f(0.0, 0.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f);
// -1 -1 -1
glVertex3f(-w / 2, -h / 2, -w / 2);
glTexCoord2f(1.0f, 1.0f);
// -1 1 -1
glVertex3f(-w / 2, h / 2, -w / 2);
glTexCoord2f(0.0f, 1.0f);
// 1 1 -1
glVertex3f(w / 2, h / 2, -w / 2);
glTexCoord2f(0.0f, 0.0f);
// 1 -1 -1
glVertex3f(w / 2, -h / 2, -w / 2);
glEnd();
glDisable(GL_TEXTURE_2D);
glPopMatrix();
}
| [
"fionnghall@444a4038-2bd8-11df-954b-21e382534593"
]
| [
[
[
1,
207
]
]
]
|
e051636ec231b3fb44924076fc6caa15741cd5d6 | 2f72d621e6ec03b9ea243a96e8dd947a952da087 | /include/Level.h | 1012f67adcd6fffbdb51743af9bd57c1a2b2841b | []
| no_license | gspu/lol4fg | 752358c3c3431026ed025e8cb8777e4807eed7a0 | 12a08f3ef1126ce679ea05293fe35525065ab253 | refs/heads/master | 2023-04-30T05:32:03.826238 | 2011-07-23T23:35:14 | 2011-07-23T23:35:14 | 364,193,504 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 28,727 | h | #ifndef __praLevel
#define __praLevel
/*
Klasse für alles rund ums level
*/
#include <Ogre.h>
#include <OgreNewt.h>
//#include "tinyxml.h"
#include <tinyxml.h>
#include "FwDec.h"
#include "defines.h"
//#include "GameObject.h"
//#include "OgrePagingLandScapeListenerManager.h"
#include "StandardApplication.h"
#include <map>
#include "vector2d.h"
//#include <boost/multi_array.hpp>
//#include "GameObject.h"
#include "SoundManager.h"
#include "Sound.h"
//#include "ETTerrainManager.h"
//#include "ETTerrainInfo.h"
//#include "ETBrush.h"
//#include "ETSplattingManager.h"
#include "ZipSaveFile.h"
#include <LevelTerrainPrereqs.h>
/**/
//test
using namespace SimpleSound;
class Level
{
public:
#ifdef __editor
friend class EditorApp;
#else
friend class GameApp;
#endif
//typedef gamedata_char gamedata_char;
//typedef gamedata_item gamedata_item;
//typedef gamedata_obj_static gamedata_obj_static;
//struct obj_container
//{
// Ogre::String ObjId;
// OgreNewt::Body *NewtonBody;
// void *ptr;
// short type;
//};
//for storing entrances
// typedef ObjType ObjType;
struct Page
{
Page()
{
x=0;
z=0;
loaded=false;
}
int x;
int z;
bool loaded;
};
struct OrientedPoint
{
Ogre::Vector3 pos;
Ogre::Quaternion orient;
};
enum LevelType
{
lvtGeneric,
//lvtBSP,
// lvtPaginglandscape
};
struct TerrainData
{
//this is the size of one "terrain" object alongside it's edge, in vertices
//must be 2^n+1
Ogre::uint16 terrainSize;
//either the size of one page, or the size of all pages together. further testing needed
Ogre::Real worldSize;
};
TerrainData mTerrainData;
typedef std::map<int,GameObject*> SaveableObjectList;
typedef std::map<int,TiXmlElement*> SaveableXmlList;
SaveableXmlList preloadedObjects;
ObjectList mObjects;
ObjectList objectsToDelete;
SaveableObjectList saveableObjects;
GameObject *getObjectBySGID(int sgid);
/*std::vector<GameObject*> mObjects;
std::vector<GameObject*> objectsToDelete;
std::vector<GameObject*> objectsToRegister;*/
//this is for chars only (for update)
//std::vector<GameChar*> charVector;
//stellen, wo man das level betreten kann. DoorMarker in morrowind
std::map<Ogre::String, OrientedPoint> entrances;
//sav ist das SG zum daraus laden, wenn es NULL ist, dann wird es nicht benutzt
Level(Ogre::String filename,ZipSaveFile *sav = NULL);
~Level();
//saves this entire level to XML file
void saveToFileOld(Ogre::String filename);
/*beim savegamemodus werden keine statics gespeichert,
wenn SGIDs = true, werden die SGIDs mitgespeichert*/
Ogre::String getSavegameXML();
void saveToFile(Ogre::String filename);
//adding time to this level. it takes care of newton, anims etc itself
void update(Ogre::Real time);
//das kümmert sich um das "löschen im nächsten Frame"
void updateDelete();
bool getDestructorCalled()
{
return destructorCalled;
}
void placePlayer(Ogre::Vector3 pos,Ogre::Quaternion ornt = Ogre::Quaternion::IDENTITY,GameChar *oldPlayer = NULL);
void placePlayer(Ogre::String entranceName,GameChar *oldPlayer = NULL);
//place something
/*void placeObject(int objectType,Ogre::String objectID,Ogre::Vector3 pos,Ogre::Quaternion ornt,
Ogre::Vector3 modScale,DoorData mData);
void placeObject(int objectType,Ogre::String objectID,Ogre::Vector3 pos,Ogre::Quaternion ornt = Ogre::Quaternion::IDENTITY,
Ogre::Vector3 modScale = Ogre::Vector3::UNIT_SCALE);*/
//creates an object using type and objectID
//provides some additional functions, like, placing statics
GameObject* placeObject(ObjType objectType,Ogre::String objectID,Ogre::Vector3 pos,Ogre::Quaternion ornt = Ogre::Quaternion::IDENTITY,
Ogre::Vector3 modScale = Ogre::Vector3::UNIT_SCALE,WorldArtType staticType = WT_NONE);
//places an object using it's gamedata
GameObject* placeObject(gamedata *data,Ogre::Vector3 pos,Ogre::Quaternion ornt = Ogre::Quaternion::IDENTITY,
Ogre::Vector3 modScale = Ogre::Vector3::UNIT_SCALE);
//same, but by ID
GameObject* placeObject(Ogre::String id,Ogre::Vector3 pos,Ogre::Quaternion ornt = Ogre::Quaternion::IDENTITY,
Ogre::Vector3 modScale = Ogre::Vector3::UNIT_SCALE);
//wenn bool fromLevelFile=true, wird bei allen geladenen Objekten isInLevelFile auf true gesetzt
void loadObjects(TiXmlElement *elem, Ogre::Vector3 positionOffset = Ogre::Vector3::ZERO,bool fromLevelFile = true);
//lädt ein einzelnes objekt
void loadObject(TiXmlElement *elem, Ogre::Vector3 positionOffset = Ogre::Vector3::ZERO,bool fromLevelFile = true);
void startObjectListener()
{
objectListenerUse = true;
objectListenerList.clear();
}
ObjectList finishObjectListener()
{
objectListenerUse = false;
return objectListenerList;
}
//überladen... irgendwie
/*void removeObject(Ogre::SceneNode *sNode);
void removeObject(Ogre::String nodeName);
void removeObject(GameObject *obj);*/
inline Ogre::Real getGravity()
{
return gravity;
}
inline Ogre::Camera *getMainCam()
{
return mCam;
}
inline OgreNewt::World *getWorld()
{
return mWorld;
}
inline Ogre::SceneManager *getSceneManager()
{
return mSceneMgr;
}
void showNewtonDebugLines(bool show);
//static function to retrieve the current one
static inline Level *getCurrent()
{
return StandardApplication::getSingletonPtr()->getCurrentLevel();
}
/*GameObject *getObject(Ogre::String nodeName);
GameObject *getObject(Ogre::SceneNode *nod);*/
//!!warnung!!
//warscheinlich LAAAANGSAM!!!
GameObject *findObject(Ogre::SceneNode *nod);
inline GameChar *getPlayer()
{
return player;
}
void setPlayerControl(GameChar *target);
void restorePlayerControl();
inline Ogre::String getFileName()
{
return mFileName;
}
inline Ogre::String getBaseFileName()
{
Ogre::String base, ext;
Ogre::StringUtil::splitBaseFilename(mFileName,base,ext);
return base;
}
inline Ogre::String getName()
{
return mName;
}
Ogre::String getUniqueEntranceName(Ogre::String base="entr");
bool isEntranceNameUnique(Ogre::String name);
/*skyPlaneDist = 3000;
skyBoxDist = 5000;
skyDomeDist = 4000;*/
void setSkyBox(Ogre::String material, Ogre::Quaternion orientation=Ogre::Quaternion::IDENTITY,Ogre::Real distance = 5000);
void removeSkyBox();
void setSkyDome(Ogre::String material, Ogre::Real curvature=10, Ogre::Real tiling=8, int xseg=16,int yseg=16, Ogre::Quaternion orientation = Ogre::Quaternion::IDENTITY, Ogre::Real distance = 4000);
void removeSkyDome();
void setSkyPlane(Ogre::String material, Ogre::Real scale=1000, Ogre::Real tiling=10, Ogre::Real bow=0, int xseg=1,int yseg=1, Ogre::Real distance = 3000);
void removeSkyPlane();
void registerObject(GameObject *obj);
void unregisterObject(GameObject *obj);
void LevelForceCallback( OgreNewt::Body* bod );
//void tileLoaded(PagingLandscapeEvent* e);
//void tileUnLoaded(PagingLandscapeEvent* e);
//void pageLoaded(PagingLandscapeEvent *e);
//void pageUnLoaded(PagingLandscapeEvent *e);
/*Aufräumfunktion, die das Löschen des Levels vorbereitet,
unter anderem werden Leveleigene Buffer und PLSM-Callbacks gelöscht.
Objekte bleiben vorerst erhalten, sie werden erst durch den richtigen Destruktor
gelöscht.
nachdem diese Funktion aufgerufen wurde, bricht Level::update()
sofort nach dem Aufrufen ab.
Wird keepBuffers auf true gesetzt, werden die Buffer beibehalten, zB für den Fall, dass
das gleiche Level nochmal geladen wird*/
void prepareForDestruction(bool keepBuffers = false);
void destroyAllObjects();
inline Ogre::Quaternion getNorthOrientation()
{
return northOrientation;
}
void enableFog(bool enable)
{
if(enable)
{
mSceneMgr->setFog(mFogMode,mFogColor,mFogDensity,mFogStart,mFogEnd);
//StandardApplication::getSingletonPtr()->getRenderWindow()->getViewport(0)->setBackgroundColour(mFogColor);
}
else
mSceneMgr->setFog(Ogre::FOG_NONE);
}
/*void spawnMissile(GameChar *caster,MissileData mData, Ogre::Vector3 pos, Ogre::Quaternion ornt, Damage dmg);*/
////level aktivieren... hm
//void setActive();
////und deaktivieren?
//void setInactive();
//naja später irgendwie
//materialzeug
OgreNewt::MaterialID
*charMaterial,
*projMaterial,
*matGlass,
*matWood,
*matMetal,
*matStone;
/*const OgreNewt::MaterialID *defaultMaterialID;*/
void deleteObject(GameObject *obj);
void debugShowPoint(Ogre::Vector3 pos);
void debugShowPlane(Ogre::Plane pl);
void debugShowLine(Ogre::Vector3 p1, Ogre::Vector3 p2);
Ogre::SceneNode *debugNode;
Ogre::SceneNode *debugNode2;
Ogre::SceneNode *debugNode3;
Buffer *getBuffer(Ogre::String filename);
Source *createSource(SimpleSound::Buffer *buffer = NULL, int type = 0, bool loop = false, bool relativeToListener = false, bool stream = false);
void destroySource(Source *src);
void playSound(Ogre::Vector3 position,Ogre::String filename);
//Hilfsfunktionen für das neu erzeugen von Covmaps
Ogre::PixelFormat numChannelsToPixelFormat(int channels)
{
switch (channels)
{
case 1: return Ogre::PF_BYTE_A;
case 2: return Ogre::PF_BYTE_LA;
case 3: return Ogre::PF_BYTE_RGB;
case 4: return Ogre::PF_BYTE_RGBA;
case -1: return Ogre::PF_BYTE_A;
case -2: return Ogre::PF_BYTE_LA;
case -3: return Ogre::PF_BYTE_BGR;
case -4: return Ogre::PF_BYTE_BGRA;
default: return Ogre::PF_UNKNOWN;
}
}
int pixelFormatToNumChannels(Ogre::PixelFormat format)
{
switch (format)
{
case Ogre::PF_BYTE_A: return 1;
case Ogre::PF_BYTE_LA: return 2;
case Ogre::PF_BYTE_RGB: return 3;
case Ogre::PF_BYTE_RGBA: return 4;
/*case PF_BYTE_A: return -1;
case PF_BYTE_LA: return -2;
case PF_BYTE_BGR: return -3;
case PF_BYTE_BGRA: return -4;*/
default: return 0;
}
}
int covmapNrFromTextureIndex(int texture,int nrOfChannels)
{
return Ogre::Math::IFloor(float(texture)/float(nrOfChannels));
}
int channelNrFromTextureIndex(int texture,int nrOfChannels)
{
return texture % nrOfChannels;
}
/*int getOldTextureIndex(Ogre::String name)
{
for(unsigned int i=0;i<terrainTextures.size();i++)
{
if(terrainTextures[i] == name)
return i;
}
return -1;
}*/
void initBuffer(Ogre::uchar *buffer,unsigned int size,Ogre::uchar value=0)
{
for(unsigned int i=0;i<size;i++)
{
buffer[i]=value;
}
}
//void add
// //gibt es holes?
//bool hasHoleMap()
//{
// if(terrainTextures[0] == "hole.png")
// return true;
// return false;
//}
//
//liste der texuren updaten
//void updateTextureList(Ogre::StringVector newList);
//diese nimmt jetzt folgendes an:
//-ambient entspricht der ambienteinstellung des levels
//-shadowed ist immer true
//somit müssen nur noch lightDir und etLightColor gespeichert werden. und width und height
//void updateTerrainLightmap();
//erstellt das Material für das Terrain anhand von ETTerrainMaterialBase
//void createETMaterial();
//erzeugt anhand von terrainTextures und mSplatMgr->getNumMaps()
//Pässe für eine technik. sollte nur von createETMaterial aufgerufen werden
//der pass sollte vertex_program_ref und fragment_program_ref beinhalten
//erzeugt auch den lightmap pass
//texturesPerPass ist die anzahl der texturen, ohne coverage maps, muss zwischen 0 und 12 sein
//wenn texturesPerPass = 0, dann ist es die fallback technique
//es wird als 3 angesehen, und der fallback shader wird benutzt
//void createETMaterialPasses(Ogre::Technique *tech,unsigned int texturesPerPass);
//inline Ogre::MaterialPtr getTerrainMaterial()
//{
// return terrainMaterial;
//}
void getSkyPlaneParams(Ogre::SceneManager::SkyPlaneGenParameters &genParams,Ogre::String &material, Ogre::Real &distance)
{
genParams = skyPlaneParams;
material = skyBoxMaterial;
distance = skyPlaneDist;
}
void getSkyDomeParams(Ogre::SceneManager::SkyDomeGenParameters &genParams,Ogre::String &material)
{
genParams = skyDomeParams;
material = skyBoxMaterial;
}
void getSkyBoxParams(Ogre::SceneManager::SkyBoxGenParameters &genParams,Ogre::String &material)
{
genParams = skyBoxParams;
material = skyBoxMaterial;
}
/* void getHeightmapDimensions(Ogre::uint &width,Ogre::uint &height)
{
width = hmWidth;
height= hmHeight;
}
void getLightmapDimensions(Ogre::uint &width,Ogre::uint &height)
{
width = lmWidth;
height= lmHeight;
}
void getSplattingDimensions(Ogre::uint &width,Ogre::uint &height)
{
width = splatWidth;
height= splatHeight;
}*/
/*unsigned int getNumSplatChannels()
{
return splatChannels;
}*/
//entfernt das terrain
void removeTerrain();
//erzeugt ein leeres terrain, das mit default.png bedeckt ist
void addBlankTerrain(unsigned int heightmapWidth,unsigned int heightmapHeight,unsigned int lightmapWidth,unsigned int lightmapHeight,unsigned int splattingWidth,unsigned int splattingHeight);
//inline Ogre::AxisAlignedBox getTerrainExtends()
//{
// return terrainExtends;
//}
//inline Ogre::Vector3 getTerrainScale()
//{
// //return mTerrainInfo->getScaling();
// Ogre::Vector3 hmSize(hmWidth-1,1,hmHeight-1);
// return terrainExtends.getSize()/hmSize;
//}
//inline Ogre::Vector3 getCovmapScale()
//{
// Ogre::Vector3 size(splatWidth,1,splatHeight);
// return terrainExtends.getSize()/size;
//}
//inline Ogre::Vector3 toTerrainPosition(Ogre::Vector3 ogrePosition)
//{
// return Ogre::Vector3(mTerrainInfo->posToVertexX(ogrePosition.x),0,mTerrainInfo->posToVertexZ(ogrePosition.z));
//}
//inline Ogre::Vector3 toOgrePosition(Ogre::Vector3 terrainPosition,bool useCovmapScale = false)
//{
// if(useCovmapScale)
// return terrainPosition * getCovmapScale() + getTerrainExtends().getMinimum();
// else
// return terrainPosition * getTerrainScale() + getTerrainExtends().getMinimum();
// //return Ogre::Vector3(mTerrainInfo->posToVertexX(ogrePosition.x),0,mTerrainInfo->posToVertexZ(ogrePosition.z));
//}
//void generateTerrainCollision();
inline Ogre::SceneNode *getCamHeadNode()
{
return CamHeadNode;
}
inline Ogre::SceneNode *getCamNode()
{
return CamNode;
}
/** OGRE TERRAIN/PAGING STUFF **/
bool hasTerrain()
{
return has_terrain;
//return (mTerrainGroup != NULL);
//return true;//TODO
}
LevelPagedWorld *mPagedWorld;
LevelPagedWorld *getPagedWorld()
{
return mPagedWorld;
}
////helper functions
////converts a length in world dimensions to terrain dimensions
//Ogre::Real lengthWorldToTerrain(Ogre::Real worldLength);
////converts a length in terrain dimensions to world dimensions
//Ogre::Real lengthTerrainToWorld(Ogre::Real terrainLength);
/*Ogre::TerrainGlobalOptions* mTerrainGlobals;
Ogre::TerrainGroup* mTerrainGroup;
bool mPaging;
Ogre::TerrainPaging* mTerrainPaging;
Ogre::PageManager* mPageManager;*/
/*
Ogre::Light *terrainLight;
void defineTerrain(long x, long y);
void initBlendMaps(Ogre::Terrain* terrain);
void configureTerrainDefaults();
//gets
Ogre::Real getCombinedBlendValue(Ogre::Terrain *terrain, Ogre::uint8 layer, size_t x, size_t y);
void setCombinedBlendValue(Ogre::Terrain *terrain, Ogre::uint8 layer, size_t x, size_t y, Ogre::Real val);
*/
//now, my own stuff:
void loadTerrain();
/*
Ogre::DataStreamPtr getTerrainForPage(long x, long y);
void defineTerrainForSection(LevelPagedWorldSection* section, long x, long y);
*/
//experiment to do the decal using frustum
//void addDecalPasses();
/** TERRAIN STUFF END **/
/*/// This class just pretends to provide prcedural page content to avoid page loading
class DummyPageProvider : public PageProvider
{
public:
bool prepareProceduralPage(Page* page, PagedWorldSection* section) { return true; }
bool loadProceduralPage(Page* page, PagedWorldSection* section) { return true; }
bool unloadProceduralPage(Page* page, PagedWorldSection* section) { return true; }
bool unprepareProceduralPage(Page* page, PagedWorldSection* section) { return true; }
};
DummyPageProvider mDummyPageProvider;*/
//if true, pages will be automatically loaded and unloaded according to camera
//void setAutoPaging(bool set);
private:
//Ogre::Vector3 getTerrainVertex(size_t x,size_t z);
//das ist die ZIP-Datei, aus der das Lvl geladen wird..
ZipSaveFile *levelSGfile;
SimpleSound::SoundManager::BufferList mBuffers;
SimpleSound::SoundManager::SourceList mSources;
SimpleSound::SoundManager::SourceList mTempSources;
bool objectListenerUse;
ObjectList objectListenerList;
int lastSGID;
// unsigned int levelVersion; //das ist für abwärtskompatibilität
/*
version 1:
<type>
<id pos="x y z" ... />
</type>
version 2:
<objects>
<type id="foobar" pos=" ... />
</objects>
*/
//Ladefunktionen. um sie mal auszulagern
void processSGID(GameObject *obj);
void loadFile(ZipSaveFile *sav = NULL);
void loadVersion1(TiXmlDocument *doc);
void loadVersion2(TiXmlDocument *doc);
//diese Funktion funktioniert wie loadObjects, lädt aber erstmal nur statische Objekte, die anderen werden
//als TiXmlElement in die preloadedObjects geschrieben
void loadSavegamePrepare(TiXmlElement *curXml);
//aktualisiert preloadedObjects vom savegame, und lädt es
void loadFromSavegame(ZipSaveFile *sav);
void processLevelSettings(TiXmlElement *elem);
void processAudioSettings(TiXmlElement *elem);
void processStatics(TiXmlElement *elem);
void processDoors(TiXmlElement *elem);
void processItems(TiXmlElement *elem);
void processCharacters(TiXmlElement *elem);
void processLights(TiXmlElement *elem);
void processEntrances(TiXmlElement *elem);
void processSpecial(TiXmlElement *elem);
void processContainers(TiXmlElement *elem);
//Ogre::String getSplattingBasename()
//{
// return splattingBasename;
//}
void loadDotScene(TiXmlElement *elem);
void saveDotScene();
void createCamera();
void createCameraNodes();
void createNewtonWorld();
//void createGeometry(); //das wird später editor only
//void createCollisionFromPage(unsigned int page_x, unsigned int page_z);
//void processPage();
//void loadTerrainGeometry(Ogre::SceneNode* tileNode, Ogre::Vector3* vertices, int numVertices, Ogre::IndexData* indexData);
typedef std::vector<SimpleSound::Buffer*> BufferVector;
/* void getTerrainLightSettings(Ogre::ColourValue &lightColor, Ogre::ColourValue &ambientColor, Ogre::Vector3 &lightDirection)
{
lightColor = etLightColor;
ambientColor = etAmbientColor;
lightDirection = etLightDirection;
}
void setTerrainExtends(Ogre::AxisAlignedBox extends);
void setTerrainLightSettings(Ogre::ColourValue lightColor, Ogre::ColourValue ambientColor, Ogre::Vector3 lightDirection)
{
etLightColor = lightColor;
etAmbientColor = ambientColor;
etLightDirection = lightDirection;
updateTerrainLightmap();
}*/
protected:
Ogre::SceneNode *CamNode, *CamHeadNode;//die kameranodes
void setMusic(bool battle=false);
void setAmbientLoop();
void setAmbientRandom();
void preloadMusic();
bool musicPreloaded;
BufferVector musicExpPreloaded;
BufferVector musicBatPreloaded;
BufferVector ambientLoopPreloaded;
BufferVector ambientRandomPreloaded;
Ogre::Quaternion northOrientation;
//hintergrundfarbe:
Ogre::ColourValue backgroundColour;
//für sounds
Ogre::StringVector musicExplore;
Ogre::StringVector musicBattle;
Ogre::StringVector ambientLoop; //wind/regengeräusche o.ä.
Ogre::StringVector ambientRandom; //normale random ambients
Ogre::Real wait_min, wait_max; //wie lange zwischen 2 random ambientsounds warten.
//wait_min=0 => kann auch sofort
//wait_max=0 => nach oben unbegrenzt. hm kann nicht 0 sein. sagen wir, maxwert = 10 sekunden
Ogre::Real timeSinceLastAmbient;
Ogre::Real timeAmbientWait;
bool hasMusicExplore, hasMusicBattle, hasAmbientLoop, hasAmbientRandom; //um abfragen, ob verctoren leer, vorzubeugen
size_t lastExIndex; //damit nicht 2x das gleiche hintereinander kommt^^
size_t lastBaIndex;
LevelType mLvlType;
Ogre::String worldGeometryFile;
//PagingLandscapeDelegate *loadTileDelegate;
/*PagingLandscapeDelegate *loadPageDelegate;
PagingLandscapeDelegate *unLoadPageDelegate;*/
//std::map<Ogre::SceneNode*,OgreNewt::Body*> tilesBodies;
bool destructorCalled;
bool destructionPrepared;
bool isConstructing;
////ob dieses level paging verwendet
//bool paging;
////also folgendermaßen:
///* anzahl d. pages wird als unendlich angesehen,
//wenn nötig, prüft das level, ob es die datei gibt
//erstmal wie morrowind, 9 pages um den spieler rum laden
// Z
// | | | | | |
//-+-----+-----+-----+-----+-----+---
// | | |0/+1 | | |
//-+-----+-----+-----+-----+-----+---
// | |-1/0 | 0 |+1/0 | | X
//-+-----+-----+-----+-----+-----+---
// | | |0/-1 | | |
// -+-----+-----+-----+-----+-----+---
// | | | | | |
//*/
//Page mLoadedPages[9];
//void loadPage(int x,int z);
//void unloadPage(int x, int z);
//bool isPageNeighbour(int main_x, int main_z,int x, int z);
//bool isPageLoaded(int x, int z);
//void setPageLoaded(int x, int z,bool set);
////das BERECHNET, wo der spieler grad nicht. hat nix mit den curPage_ vars zu tun
////wenn useBorders = false, dann wird die exakte Position zurückgegeben, ohne
////die grenzunschärfe zu beachten
//void getPlayerPage(int &x, int &z,bool useBorders = true);
////schaut nach was geladen/entladen werden muss und lädt/entlädt
//void updatePaging();
//int curPage_x; //X-wert der aktuellen page, wo der spieler drin ist
//int curPage_z; //Z-wert der aktuellen page, da in der XZ-ebene
//Ogre::Vector3 pageStartOffset; // koordinaten der mitte der (0,0)-page
//Ogre::Real pageSize; //länge/breite einer page, quadratisch
//Ogre::Real pagingBorder; //das ist die "unschärfe" der Grenze
ContCallback *mCallback;
//Ogre::Real mWorldUpdate, mWorldElapsed; //for world updating
//Ogre::Real mWorldWaitTime; //test
//sky stuff
Ogre::SceneManager::SkyBoxGenParameters skyBoxParams;
Ogre::SceneManager::SkyDomeGenParameters skyDomeParams;
Ogre::SceneManager::SkyPlaneGenParameters skyPlaneParams;
Ogre::String skyBoxMaterial, skyDomeMaterial, skyPlaneMaterial;
Ogre::Real skyPlaneDist, skyBoxDist, skyDomeDist;
//fog stuff
Ogre::FogMode mFogMode;
Ogre::ColourValue mFogColor;
Ogre::Real mFogDensity;
Ogre::Real mFogStart;
Ogre::Real mFogEnd;
/***terrain stuff***/
bool has_terrain;
// bool getAutoPaging();
/*
//TERRAIN PAGING STUFF
//Ogre::TerrainPaging* mTerrainPaging;
LevelPaging* mTerrainPaging;
LevelPagedWorld* mTerrainPagedWorld;
LevelPageManager* mPageManager;
LevelPagingListener *mPagingListener;
*/
//class LevelPageProvider : public Ogre::PageProvider
//{
//public:
// LevelPageProvider(Level *parent)
// {
// mLevel = parent;
// }
// /** Give a provider the opportunity to prepare page content procedurally.
// @remarks
// This call may well happen in a separate thread so it should not access
// GPU resources, use loadProceduralPage for that
// @returns true if the page was populated, false otherwise
// */
// bool prepareProceduralPage(Ogre::Page* page, Ogre::PagedWorldSection* section);
// /** Give a provider the opportunity to load page content procedurally.
// @remarks
// This call will happen in the main render thread so it can access GPU resources.
// Use prepareProceduralPage for background preparation.
// @returns true if the page was populated, false otherwise
// */
// bool loadProceduralPage(Ogre::Page* page, Ogre::PagedWorldSection* section);
// /** Give a provider the opportunity to unload page content procedurally.
// @remarks
// You should not call this method directly. This call will happen in
// the main render thread so it can access GPU resources. Use _unprepareProceduralPage
// for background preparation.
// @returns true if the page was populated, false otherwise
// */
// bool unloadProceduralPage(Ogre::Page* page, Ogre::PagedWorldSection* section);
// /** Give a provider the opportunity to unprepare page content procedurally.
// @remarks
// You should not call this method directly. This call may well happen in
// a separate thread so it should not access GPU resources, use _unloadProceduralPage
// for that
// @returns true if the page was unpopulated, false otherwise
// */
// bool unprepareProceduralPage(Ogre::Page* page, Ogre::PagedWorldSection* section);
//protected:
// Level *mLevel;
//};
//LevelPageProvider *mPageProvider;
OgreNewt::Body *terrainBody;
OgreNewt::CollisionPrimitives::TreeCollision *terrainCollision;
// const unsigned int splatChannels;
///*ET::TerrainManager *mTerrainMgr;
//ET::SplattingManager* mSplatMgr;*/
//Ogre::String splattingBasename;
//Ogre::StringVector terrainTextures;
///*const ET::TerrainInfo *mTerrainInfo;
//Ogre::MaterialPtr terrainMaterial;
//Ogre::TexturePtr terrainLightmap;*/
// Ogre::ColourValue etLightColor, etAmbientColor;
// Ogre::Vector3 etLightDirection;
// Ogre::AxisAlignedBox terrainExtends;
// //heightmap dimensions
// unsigned int hmWidth;
//unsigned int hmHeight;
// //lightmap dimensions
// unsigned int lmWidth;
//unsigned int lmHeight;
// //coverage/splatting map dimensions
// unsigned int splatWidth;
//unsigned int splatHeight;
///***terrain stuff end***/
//player stores the pointer to the char currently under player control
//origPlayer is for backupping, here is always a pointer to the
//char the player is normally supposed to control
GameChar *origPlayer, *player;
//pointer to the app. StandardApplication, weil der editor das auch verwenden soll
StandardApplication *app;
//Gravity. Why not custom grav for each level?
Ogre::Real gravity;
//filename of the level file
Ogre::String mFileName;
//name of the level
Ogre::String mName;
/****PLSM STUFF*****/
//unsigned int max_adjacent_pages;
//Ogre::String plsm2MapName;
//typedef boost::multi_array<OgreNewt::Body*, 2> body2d;
//vector2d<OgreNewt::Body*> plsm2Bodies;
//vector2d<bool> plsm2collisionCreated;
//body2d plsm2Bodies;
//bool plsm2CreatingCollision;
//Ogre::Vector2 plsm2curPageToParse;
/****DOTSCENE STUFF*/
//dotScene filename
/*Ogre::String dotSceneFileName;
Ogre::Vector3 dotScenePos;
Ogre::Vector3 dotSceneScale;
Ogre::Quaternion dotSceneOrient;*/
//Newton world of this lvl
OgreNewt::World *mWorld;
//Ogre Scene manager
Ogre::SceneManager *mSceneMgr;
//die hauptcam des levels
Ogre::Camera *mCam;
//objektinfos bleiben in der GameApp,
//aber die std::maps für dei tatsächlichen objekte kommen hierhin
void createStandardMaterials();
void processTerrainSettings(TiXmlElement *elem);
Ogre::String objectToXml(GameObject *obj);
//diese funktion nimmt ein XML-element, welches die einzelnen objekte als kinder hat
//zerparst es und erstellt objekte, mit posOffset als Versatz vom ursprung
/*
<objects> <!-- das ist dann das, was man an die funktion übergeben soll -->
<static pos="0 4.5 0" filename="ogrehead.mesh" type="mesh" scale="0.0584188 0.0584188 0.0584188" />
</objects>
*/
void XmlToObjects(TiXmlElement *objNode, Ogre::Vector3 posOffset = Ogre::Vector3::ZERO);
};
#endif | [
"praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac"
]
| [
[
[
1,
908
]
]
]
|
f1ba745e599481cf4b8b00e6cc3ff1d3fbf7d32c | 453607cc50d8e248e83472e81e8254c5d6997f64 | /packet/include/invpacktree.h | 855d59b07a58489afad830cc1027d84d06c5f15d | []
| no_license | wbooze/test | 9242ba09b65547d422defec34405b843b289053f | 29e20eae9f1c1900bf4bb2433af43c351b9c531e | refs/heads/master | 2016-09-05T11:23:41.471171 | 2011-02-10T10:08:59 | 2011-02-10T10:08:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,284 | h |
#ifndef _INVPACKTREE_H_
#define _INVPACKTREE_H_
/** \file
The documentation in this file is formatted for doxygen
(see www.doxygen.org).
<h4>
Copyright and Use
</h4>
<p>
You may use this source code without limitation and without
fee as long as you include:
</p>
<blockquote>
This software was written and is copyrighted by Ian Kaplan, Bear
Products International, www.bearcave.com, 2002.
</blockquote>
<p>
This software is provided "as is", without any warranty or
claim as to its usefulness. Anyone who uses this source code
uses it at their own risk. Nor is any support provided by
Ian Kaplan and Bear Products International.
<p>
Please send any bug fixes or suggested source changes to:
<pre>
[email protected]
</pre>
@author Ian Kaplan
*/
#include "liftbase.h"
#include "list.h"
#include "packcontainer.h"
#include "packdata.h"
#include "packdata_list.h"
/**
Inverse wavelet packet transform
The invpacktree constructor is passed a packdata_list object and a
wavelet transform object. It calculates the inverse wavelet
packet transform, using the data in the packdata_list object
and the inverse wavelet transform step function of the wavelet
transform object. The best basis data is destroyed in calculating
the inverse transform.
The packdata_list object contains the "best basis" result from a
wavelet packet transform. The wavelet packet transform should have
been calculated with the same wavelet transform as the object passed
to this constructor.
After the constructor completes, the data result can be
obtained by calling the getData() function.
The wavelet transforms used by this object are all derived
from the liftbase class and are "lifting scheme" wavelet
transforms.
I have found the wavelet literature difficult, in general. When it
comes to the wavelet packet transform I have found most of it
impossible to understand. Impossible, that it until I got the book
<i>Ripples in Mathematics</i> by Jensen and la Cour-Harbo, Springer
Verlag, 2001. The wavelet packet transform, for which this class
is the inverse, is heavily based on Chapter 8 of <i>Ripples in
Mathematics</i>.
I have found very little material on the actual implementation of
the inverse wavelet packet transform. This algorithm is my own
design.
\author Ian Kaplan
*/
class invpacktree {
public:
/** wavelet transform object */
liftbase<packcontainer, double> *waveObj;
/** disallow the copy constructor */
invpacktree( const invpacktree &rhs ) {}
/** inverse wavelet packet transform calculation stack */
LIST<packcontainer *> stack;
/** pointer to the inverse transform result */
const double *data;
/** length of data */
size_t N;
public:
void new_level( packdata<double> *elem );
void add_elem( packdata<double> *elem );
void reduce();
public:
invpacktree( packdata_list<double> &list,
liftbase<packcontainer, double> *w );
/** The destructor does nothing */
~invpacktree() {}
/** Get the result of the inverse packet transform */
const double *getData() { return data; }
void pr();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
114
]
]
]
|
c5d654dad9d66c450625e42a3f42c6fa48632bda | 96e96a73920734376fd5c90eb8979509a2da25c0 | /C3DE/Sprite.cpp | 7f55e56217aa9d6a387da8b6a132959ebb71e81a | []
| no_license | lianlab/c3de | 9be416cfbf44f106e2393f60a32c1bcd22aa852d | a2a6625549552806562901a9fdc083c2cacc19de | refs/heads/master | 2020-04-29T18:07:16.973449 | 2009-11-15T10:49:36 | 2009-11-15T10:49:36 | 32,124,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | cpp | #include "Sprite.h"
#include "DebugMemory.h"
Sprite::Sprite(Image *image, int frameWidth, int frameHeight, int numFrames, int numColumns, int numRows, int frameDuration)
{
m_image = image;
m_frameWidth = frameWidth;
m_frameHeight = frameHeight;
m_numFrames = numFrames;
m_frameDuration = frameDuration;
m_angle = 0;
m_x = 0;
m_y = 0;
m_xScale = 1.0f;
m_yScale = 1.0f;
m_angle = 0.0f;
m_numColumns = numColumns;
m_numRows = numRows;
m_currentFrameTime = 0;
m_currentFrame = 0;
}
void Sprite::Update(int deltaTime)
{
m_currentFrameTime += deltaTime;
int framesToAdvance = m_currentFrameTime / m_frameDuration;
m_currentFrame = ((m_currentFrame + framesToAdvance) % m_numFrames);
m_currentFrameTime = (m_currentFrameTime % m_frameDuration);
}
void Sprite::SetX(int x)
{
m_x = x;
}
void Sprite::SetY(int y)
{
m_y = y;
}
void Sprite::SetXScale(float xScale)
{
m_xScale = xScale;
}
void Sprite::SetYScale(float yScale)
{
m_yScale = yScale;
}
void Sprite::SetRotation(float angle)
{
m_angle = angle;
}
Sprite::~Sprite()
{
} | [
"caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158"
]
| [
[
[
1,
67
]
]
]
|
7711364eb034e4c76faa4b2ad55e2f04038046aa | 17083b919f058848c3eb038eae37effd1a5b0759 | /SimpleGL/sgl/GL/GLProgram.h | c8faf89f08d2eee50c0079bf1d067d2321cabd9e | []
| no_license | BackupTheBerlios/sgl | e1ce68dfc2daa011bdcf018ddce744698cc7bc5f | 2ab6e770dfaf5268c1afa41a77c04ad7774a70ed | refs/heads/master | 2021-01-21T12:39:59.048415 | 2011-10-28T16:14:29 | 2011-10-28T16:14:29 | 39,894,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,131 | h | #ifndef SIMPLE_GL_GL_PROGRAM_H
#define SIMPLE_GL_GL_PROGRAM_H
#include "GLCommon.h"
#include "GLShader.h"
#include "../Program.h"
namespace sgl {
template<typename T>
class GLUniform;
template<typename T>
class GLSamplerUniform;
/* Wraps gl function for working with shader programs */
class GLProgram :
public ResourceImpl<Program>
{
private:
typedef scoped_ptr<AbstractUniform> uniform_ptr;
typedef ref_ptr<GLShader> shader_ptr;
typedef std::vector<shader_ptr> shader_vector;
struct attribute
{
unsigned index;
unsigned size;
std::string name;
sgl::SCALAR_TYPE type;
// convert to ATTRIBUTE
ATTRIBUTE to_ATTRIBUTE() const
{
ATTRIBUTE attr;
attr.index = index;
attr.size = size;
attr.name = name.c_str();
attr.type = type;
return attr;
}
};
typedef std::vector<attribute> attribute_vector;
private:
AbstractUniform* CreateUniform( GLProgram* program,
const char* name,
GLuint glIndex,
GLuint glLocation,
GLenum glUniformType,
size_t size );
public:
GLProgram(GLDevice* deviceState);
~GLProgram();
// Override Program
SGL_HRESULT SGL_DLLCALL AddShader(Shader* shader);
bool SGL_DLLCALL RemoveShader(Shader* shader);
bool SGL_DLLCALL IsDirty() const { return dirty; }
SGL_HRESULT SGL_DLLCALL Dirty(bool force = false);
const char* SGL_DLLCALL CompilationLog() const;
void SGL_DLLCALL Clear();
SGL_HRESULT SGL_DLLCALL Bind() const;
void SGL_DLLCALL Unbind() const;
// Attributes
SGL_HRESULT SGL_DLLCALL BindAttributeLocation(const char* name, unsigned index);
int SGL_DLLCALL AttributeLocation(const char* name) const;
unsigned SGL_DLLCALL NumAttributes() const { return attributes.size(); }
ATTRIBUTE SGL_DLLCALL Attribute(unsigned index) const;
// Geometry shaders
void SGL_DLLCALL SetGeometryNumVerticesOut(unsigned int maxNumVertices);
void SGL_DLLCALL SetGeometryInputType(PRIMITIVE_TYPE inputType);
void SGL_DLLCALL SetGeometryOutputType(PRIMITIVE_TYPE outputType);
unsigned int SGL_DLLCALL GeometryNumVerticesOut() const { return numVerticesOut; }
PRIMITIVE_TYPE SGL_DLLCALL GeometryInputType() const { return inputType; }
PRIMITIVE_TYPE SGL_DLLCALL GeometryOutputType() const { return outputType; }
// Uniforms
AbstractUniform* SGL_DLLCALL GetUniform(const char* name) const;
template<typename T>
GLUniform<T>* GetUniform(const char* name) const
{
return dynamic_cast< GLUniform<T>* >( GetUniform(name) );
}
template<typename T>
GLSamplerUniform<T>* GetSamplerUniform(const char* name) const
{
return dynamic_cast< GLSamplerUniform<T>* >( GetUniform(name) );
}
/* Create int uniform */
UniformI* SGL_DLLCALL GetUniformI(const char* name) const;
Uniform2I* SGL_DLLCALL GetUniform2I(const char* name) const;
Uniform3I* SGL_DLLCALL GetUniform3I(const char* name) const;
Uniform4I* SGL_DLLCALL GetUniform4I(const char* name) const;
/* Create float uniform */
UniformF* SGL_DLLCALL GetUniformF(const char* name) const;
Uniform2F* SGL_DLLCALL GetUniform2F(const char* name) const;
Uniform3F* SGL_DLLCALL GetUniform3F(const char* name) const;
Uniform4F* SGL_DLLCALL GetUniform4F(const char* name) const;
/* Create matrix uniform */
Uniform2x2F* SGL_DLLCALL GetUniform2x2F(const char* name) const;
Uniform3x3F* SGL_DLLCALL GetUniform3x3F(const char* name) const;
Uniform4x4F* SGL_DLLCALL GetUniform4x4F(const char* name) const;
/* Create texture uniforms */
SamplerUniform1D* SGL_DLLCALL GetSamplerUniform1D(const char* name) const;
SamplerUniform2D* SGL_DLLCALL GetSamplerUniform2D(const char* name) const;
SamplerUniform3D* SGL_DLLCALL GetSamplerUniform3D(const char* name) const;
SamplerUniformCube* SGL_DLLCALL GetSamplerUniformCube(const char* name) const;
/** Get OpenGL program handle */
GLuint SGL_DLLCALL Handle() const { return glProgram; }
private:
GLDevice* device;
shader_vector shaders;
attribute_vector attributes;
uniform_ptr* uniforms;
// geometry shaders
unsigned int numActiveUniforms;
unsigned int numVerticesOut;
PRIMITIVE_TYPE inputType;
PRIMITIVE_TYPE outputType;
// data
GLuint glProgram;
bool dirty;
// log
std::string compilationLog;
};
} // namespaec sgl
#endif // SIMPLE_GL_GL_PROGRAM_H
| [
"devnull@localhost"
]
| [
[
[
1,
149
]
]
]
|
a5d9a9032cef298dfabc8b34b94f4e2a6f12450c | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Modules/UiCtrl/AudioCtrlFi.h | 6d6ec5244fd8477e8566de34d78c3be6cfabf8fe | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,425 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef AUDIO_CONTROL_Fi_H
#define AUDIO_CONTROL_Fi_H
#include "AudioCtrlStd.h"
namespace isab{
class AudioCtrlLanguageFi : public AudioCtrlLanguageStd
{
public:
AudioCtrlLanguageFi();
static class AudioCtrlLanguage* New();
virtual int newCameraSoundList(
DistanceInfo &deadlines,
SoundClipsList &soundClips);
private:
void ActionAndWhen();
void Distance();
void WhenNormalAction();
void WhenAtDestination();
void RoundaboutExit();
void NumberedExit();
void Now(bool nowIsTassa);
virtual void Action();
virtual void FirstCrossing();
virtual void AdditionalCrossing();
virtual void genericDeviatedFromRoute();
virtual void genericReachedDest();
}; /* AudioCtrlLanguage */
} /* namespace isab */
#endif
| [
"[email protected]"
]
| [
[
[
1,
51
]
]
]
|
cf58a90bf111a86492c08f773788b7a3a84d5245 | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/refactor/src_root/include/ireon_client/interface/window.h | 9f1d0fd63acc5d65d7b6d0cf8c1d59e586e6810d | []
| no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15T00:22:02.905112 | 2010-01-07T20:31:07 | 2010-01-07T20:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,400 | h | /* Copyright (C) 2005 ireon.org developers council
* $Id: window.h 433 2005-12-20 20:19:15Z zak $
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* @file window.h
* Interface window class
*/
#ifndef _WINDOW_H
#define _WINDOW_H
#include <OgreNoMemoryMacros.h>
#include <CEGUI/elements/CEGUIStaticText.h>
#include <CEGUI/CEGUIForwardRefs.h>
#include <OgreMemoryMacros.h>
struct WindowEvent;
class CWindow
{
friend class CInterface;
protected:
CWindow(CEGUI::Window* win);
public:
virtual ~CWindow();
virtual bool init();
virtual void deInit();
// CEGUI::Window* win() {return m_window;}
uint getChildCount() const {return (uint)m_children.size();}
WndPtr getChildAtIdx(size_t s) const {return m_children[s];}
void addChildWindow(const WndPtr& win);
void removeChild(size_t s);
void disable();
void enable();
bool isVisible();
void setVisible(bool);
bool isActive();
void activate();
float getAlpha();
void setAlpha(float);
String getName();
Vector2 getPosition();
void setPosition(const Vector2& p);
Vector2 getAbsolutePosition();
void setAbsolutePosition(const Vector2& p);
Vector2 getSize();
void setSize(const Vector2&);
/** Set unified width
* see CEGUI documentation for details about unified
* coords
*/
void setUWidth(const Vector2&);
/** Set unified height
* see CEGUI documentation for details about unified
* coords
*/
void setUHeight(const Vector2&);
/** Get unified width
*/
Vector2 getUWidth();
/** Get unified height
*/
Vector2 getUHeight();
/** Set unified X coordinate
*/
void setUX(const Vector2& x);
/** Get unified X coordinate
*/
Vector2 getUX();
/** Set unified Y coordinate
*/
void setUY(const Vector2& y);
/** Get unified Y coordinate
*/
Vector2 getUY();
String getText();
void setText(const String&);
void setAlwaysOnTop(bool);
void subscribeEvent(const CEGUI::String& type, const WindowEvent& evt);
void subscribeEvent(const CEGUI::String& type, const WindowKeyEvent& evt);
CInterface::WinType type() {return m_type;}
bool active() {return m_active;}
protected:
CEGUI::Window* m_window;
std::vector<WndPtr> m_children;
std::vector<WndPtr>::iterator it;
CInterface::WinType m_type;
///Window was created, so can be destroyed
bool m_created;
///Is window in tree?
bool m_active;
};
class CFrameWindow : public CWindow
{
friend class CInterface;
protected:
CFrameWindow(CEGUI::Window* win): CWindow(win) {}
public:
void setCloseButtonEnabled(bool);
void setDragMovingEnabled(bool);
void setFrameEnabled(bool);
void setSizingEnabled(bool);
};
class CMultiListWindow : public CWindow
{
friend class CInterface;
protected:
CMultiListWindow(CEGUI::Window* win);
public:
bool init();
void deInit();
CEGUI::MultiColumnList* win() {return (CEGUI::MultiColumnList*)m_window;}
///Clear list
void reset();
///Set number of cols
void setCol(byte col);
///Set column widths
void setWidth(std::vector<byte> &vec);
///Insert row with values
uint insertRow(StringVector values, int id = -1);
///Get value at cell
String getValue(uint row, uint col);
///Get row count
uint getRowCount();
///Get col count
uint getColCount() {return m_colCount;}
void setHead(uint idx, const String& str);
///Get first selected item's id
int getFirstSelected();
protected:
byte m_colCount;
};
class CStaticTextWindow : public CWindow
{
friend class CInterface;
protected:
CStaticTextWindow(CEGUI::Window* win):CWindow(win){};
public:
void setFormatting(CEGUI::StaticText::HorzFormatting, CEGUI::StaticText::VertFormatting);
void setBackgroundEnabled(bool);
void setVerticalScrollbarEnabled(bool);
void setFrameEnabled(bool);
void setTextColour(CEGUI::colour col);
};
class CCheckBox : public CWindow
{
friend class CInterface;
protected:
CCheckBox(CEGUI::Window* win):CWindow(win){};
public:
bool isChecked();
void setChecked(bool);
};
class CListBox: public CWindow
{
friend class CInterface;
protected:
CListBox(CEGUI::Window* win):CWindow(win){};
public:
void addRow(const String& str, CEGUI::colour col);
void removeRow(uint num);
void clear();
void clearSelection();
};
class CScrollBar : public CWindow
{
friend class CInterface;
protected:
CScrollBar(CEGUI::Window* win):CWindow(win){};
public:
/// Is scrollbar at the end of document
bool atEnd();
/// Set scrollbar position to the end of document
void toEnd();
/// Set scrollbar position
void setScrollPosition(float pos);
};
#endif | [
"[email protected]"
]
| [
[
[
1,
250
]
]
]
|
89d8af5314e6c811ae8d057edea9b3d03b5074ec | 59066f5944bffb953431bdae0482a2abfb75f49a | /trunk/tools/ogrewizard71/Files/Templates/include/BaseApplication.h | bdff00ade3c0fd162f6bae95dd5d55a778da52d3 | []
| no_license | BackupTheBerlios/conglomerate-svn | 5b1afdea5fbcdd8b3cdcc189770b1ad0f8027c58 | bbecac90353dca2ae2114d40f5a6697b18c435e5 | refs/heads/master | 2021-01-01T18:37:56.730293 | 2006-05-21T03:12:39 | 2006-05-21T03:12:39 | 40,668,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,747 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2005 The OGRE Team
Also see acknowledgements in Readme.html
You may use this sample code for anything you like, it is not covered by the
LGPL like the rest of the engine.
-----------------------------------------------------------------------------
*/
/*
-----------------------------------------------------------------------------
Filename: BaseApplication.h
Description: A place for me to try out stuff with OGRE.
-----------------------------------------------------------------------------
*/
#ifndef __BaseApplication_h_
#define __BaseApplication_h_
#include <ogre.h>
#include <OgreKeyEvent.h>
#include <OgreEventListeners.h>
#include <OgreStringConverter.h>
#include <OgreException.h>
using namespace Ogre;
[!if CEGUI_YES]
#include <OgreNoMemoryMacros.h>
#include <CEGUI.h>
#include <CEGUISystem.h>
#include <CEGUISchemeManager.h>
#include <OgreCEGUIRenderer.h>
#include <OgreMemoryMacros.h>
[!endif]
[!if LOADINGBAR_YES]
class LoadingBar;
[!endif]
[!if CEGUI_YES]
class BaseApplication : public Ogre::Singleton<BaseApplication>, public FrameListener, public KeyListener, public MouseMotionListener, public MouseListener
[!else]
class BaseApplication : public Ogre::Singleton<BaseApplication>, public FrameListener, public KeyListener
[!endif]
{
public:
BaseApplication(void);
virtual ~BaseApplication(void);
virtual void go(void);
protected:
virtual bool setup();
virtual bool configure(void);
virtual void chooseSceneManager(void);
virtual void createCamera(void);
virtual void createFrameListener(void);
virtual void createScene(void) = 0; // Override me!
virtual void destroyScene(void);
virtual void createViewports(void);
virtual void setupResources(void);
virtual void createResourceListener(void);
virtual void loadResources(void);
virtual void updateStats(void);
virtual bool processUnbufferedKeyInput(const FrameEvent& evt);
virtual bool processUnbufferedMouseInput(const FrameEvent& evt);
virtual void moveCamera();
virtual bool frameStarted(const FrameEvent& evt);
virtual bool frameEnded(const FrameEvent& evt);
void showDebugOverlay(bool show);
void switchMouseMode();
void switchKeyMode();
void keyClicked(KeyEvent* e);
void keyPressed(KeyEvent* e);
void keyReleased(KeyEvent* e);
[!if CEGUI_YES]
void requestShutdown(void);
void mouseMoved (MouseEvent* e);
void mouseDragged (MouseEvent* e);
void mousePressed (MouseEvent* e);
void mouseReleased (MouseEvent* e);
void mouseClicked(MouseEvent* e);
void mouseEntered(MouseEvent* e);
void mouseExited(MouseEvent* e);
void setupEventHandlers(void);
bool handleQuit(const CEGUI::EventArgs& e);
[!endif]
Root *mRoot;
Camera* mCamera;
SceneManager* mSceneMgr;
RenderWindow* mWindow;
[!if LOADINGBAR_YES]
LoadingBar* mLoadingBar;
[!endif]
[!if CEGUI_YES]
CEGUI::System* mGUISystem;
CEGUI::Renderer* mGUIRenderer;
bool mShutdownRequested;
[!endif]
int mSceneDetailIndex ;
Real mMoveSpeed;
Degree mRotateSpeed;
Overlay* mDebugOverlay;
EventProcessor* mEventProcessor;
InputReader* mInputDevice;
Vector3 mTranslateVector;
bool mStatsOn;
bool mUseBufferedInputKeys, mUseBufferedInputMouse, mInputTypeSwitchingOn;
unsigned int mNumScreenShots;
float mMoveScale;
Degree mRotScale;
Real mTimeUntilNextToggle; // just to stop toggles flipping too fast
Radian mRotX, mRotY;
TextureFilterOptions mFiltering;
int mAniso;
};
#endif // #ifndef __BaseApplication_h_
| [
"jacmoe@4fa2dde5-35f3-0310-a95e-e112236e8438"
]
| [
[
[
1,
126
]
]
]
|
ecde98de86e6d3f08dea3d43bf87527caa116d00 | 0429e2b2a1a09254b5182e15835da188f7d44a3d | /tags/v03/tests/room/troom.h | dce2fba2fb4f666c3bf887d2c7c9b205c20bce44 | []
| no_license | TheolZacharopoulos/tl2hotel | 0b5af731aa022b04fc7b894b4fad6ce0b1121744 | 87ff9c75250d702c49d62f43e494cf549ea700b7 | refs/heads/master | 2020-03-30T05:41:55.498410 | 2011-04-25T22:24:44 | 2011-04-25T22:24:44 | 42,362,513 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 245 | h | #include <QtTest>
#include "room.h"
class TRoom : public QObject {
Q_OBJECT
private slots:
void testConstructor ();
void testFree ();
void testRoomNumber ();
void testRoomFloor ();
void testCapacity ();
}; | [
"delis89@fb7cbe1a-da42-76e9-2caa-fedf319af631"
]
| [
[
[
1,
14
]
]
]
|
fdd92476bdf334bf982f35efc93addf20d55c792 | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/SHAHashSet.h | bec7db7cf29f43d476333ba9b9d80893c1567e20 | []
| no_license | mikezhoubill/emule-gifc | e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60 | 46979cf32a313ad6d58603b275ec0b2150562166 | refs/heads/master | 2021-01-10T20:37:07.581465 | 2011-08-13T13:58:37 | 2011-08-13T13:58:37 | 32,465,033 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 11,372 | h | //this file is part of eMule
//Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
/*
SHA haset basically exists of 1 Tree for all Parts (9.28MB) + n Trees
for all blocks (180KB) while n is the number of Parts.
This means it is NOT a complete hashtree, since the 9.28MB is a given level, in order
to be able to create a hashset format similar to the MD4 one.
If the number of elements for the next level are odd (for example 21 blocks to spread into 2 hashs)
the majority of elements will go into the left branch if the parent node was a left branch
and into the right branch if the parent node was a right branch. The first node is always
taken as a left branch.
Example tree:
FileSize: 19506000 Bytes = 18,6 MB
X (18,6) MasterHash
/ \
X (18,55) \
/ \ \
X(9,28) x(9,28) X (0,05MB) PartHashs
/ \ / \ \
X(4,75) X(4,57) X(4,57) X(4,75) \
[...............]
X(180KB) X(180KB) [...] X(140KB) | X(180KB) X(180KB [...] BlockHashs
v
Border between first and second Part (9.28MB)
HashsIdentifier:
When sending hashs, they are send with a 16bit identifier which specifies its postion in the
tree (so StartPosition + HashDataSize would lead to the same hash)
The identifier basically describes the way from the top of the tree to the hash. a set bit (1)
means follow the left branch, a 0 means follow the right. The highest bit which is set is seen as the start-
postion (since the first node is always seend as left).
Example
x 0000000000000001
/ \
x \ 0000000000000011
/ \ \
x _X_ x 0000000000000110
Version 2 of AICH also supports 32bit identifiers to support large files, check CAICHRecoveryHashSet::CreatePartRecoveryData
*/
#pragma once
#define HASHSIZE 20
#define KNOWN2_MET_FILENAME _T("known2_64.met")
#define OLD_KNOWN2_MET_FILENAME _T("known2.met")
#define KNOWN2_MET_VERSION 0x02
#define KNOWN2_UNSHARED_MET_FILENAME _T("known2_unshared.met") //zz_fly :: known2 split
enum EAICHStatus {
AICH_ERROR = 0,
AICH_EMPTY,
AICH_UNTRUSTED,
AICH_TRUSTED,
AICH_VERIFIED,
AICH_HASHSETCOMPLETE
};
class CFileDataIO;
class CKnownFile;
class CSafeMemFile;
class CPartFile;
class CUpDownClient;
/////////////////////////////////////////////////////////////////////////////////////////
///CAICHHash
class CAICHHash
{
public:
~CAICHHash() {;}
CAICHHash() { ZeroMemory(m_abyBuffer, HASHSIZE); }
CAICHHash(CFileDataIO* file) { Read(file); }
CAICHHash(uchar* data) { Read(data); }
CAICHHash(const CAICHHash& k1) { *this = k1; }
CAICHHash& operator=(const CAICHHash& k1) { memcpy(m_abyBuffer, k1.m_abyBuffer, HASHSIZE); return *this; }
friend bool operator==(const CAICHHash& k1,const CAICHHash& k2) { return memcmp(k1.m_abyBuffer, k2.m_abyBuffer, HASHSIZE) == 0;}
friend bool operator!=(const CAICHHash& k1,const CAICHHash& k2) { return !(k1 == k2); }
void Read(CFileDataIO* file);
void Write(CFileDataIO* file) const;
void Read(uchar* data) { memcpy(m_abyBuffer, data, HASHSIZE); }
CString GetString() const;
uchar* GetRawHash() { return m_abyBuffer; }
const uchar* GetRawHashC() const { return m_abyBuffer; }
static int GetHashSize() { return HASHSIZE;}
private:
uchar m_abyBuffer[HASHSIZE];
};
template<> inline UINT AFXAPI HashKey(const CAICHHash& key){
uint32 hash = 1;
for (int i = 0;i != HASHSIZE;i++)
hash += (key.GetRawHashC()[i]+1)*((i*i)+1);
return hash;
};
/////////////////////////////////////////////////////////////////////////////////////////
///CAICHHashAlgo
class CAICHHashAlgo
{
public:
virtual void Reset() = 0;
virtual void Add(LPCVOID pData, DWORD nLength) = 0;
virtual void Finish(CAICHHash& Hash) = 0;
virtual void GetHash(CAICHHash& Hash) = 0;
};
/////////////////////////////////////////////////////////////////////////////////////////
///CAICHHashTree
class CAICHHashTree
{
friend class CAICHHashTree;
friend class CAICHRecoveryHashSet;
public:
CAICHHashTree(uint64 nDataSize, bool bLeftBranch, uint64 nBaseSize);
~CAICHHashTree();
//zz_fly :: known2 buffer // helper method of CList
CAICHHashTree() {;}
CAICHHashTree(const CAICHHashTree& k1) { *this = k1; }
CAICHHashTree& operator=(const CAICHHashTree& k1);
friend bool operator==(const CAICHHashTree& k1,const CAICHHashTree& k2) { return (k1.m_Hash == k2.m_Hash);}
friend bool operator!=(const CAICHHashTree& k1,const CAICHHashTree& k2) { return !(k1 == k2); }
//zz_fly :: end
void SetBlockHash(uint64 nSize, uint64 nStartPos, CAICHHashAlgo* pHashAlg);
bool ReCalculateHash(CAICHHashAlgo* hashalg, bool bDontReplace );
bool VerifyHashTree(CAICHHashAlgo* hashalg, bool bDeleteBadTrees);
CAICHHashTree* FindHash(uint64 nStartPos, uint64 nSize) {uint8 buffer = 0; return FindHash(nStartPos, nSize, &buffer);}
const CAICHHashTree* FindExistingHash(uint64 nStartPos, uint64 nSize) const {uint8 buffer = 0; return FindExistingHash(nStartPos, nSize, &buffer);}
uint64 GetBaseSize() const;
void SetBaseSize(uint64 uValue);
//zz_fly :: known2 buffer
void ClearSubTree(); //a safe way to clear subtrees
void MarkBuffered(); //marked the subtrees as buffered
void MarkUnBuffered(); //marked the subtrees as unbuffered
//zz_fly :: end
protected:
CAICHHashTree* FindHash(uint64 nStartPos, uint64 nSize, uint8* nLevel);
const CAICHHashTree* FindExistingHash(uint64 nStartPos, uint64 nSize, uint8* nLevel) const;
bool CreatePartRecoveryData(uint64 nStartPos, uint64 nSize, CFileDataIO* fileDataOut, uint32 wHashIdent, bool b32BitIdent);
void WriteHash(CFileDataIO* fileDataOut, uint32 wHashIdent, bool b32BitIdent) const;
bool WriteLowestLevelHashs(CFileDataIO* fileDataOut, uint32 wHashIdent, bool bNoIdent, bool b32BitIdent) const;
bool LoadLowestLevelHashs(CFileDataIO* fileInput);
bool SetHash(CFileDataIO* fileInput, uint32 wHashIdent, sint8 nLevel = (-1), bool bAllowOverwrite = true);
bool ReduceToBaseSize(uint64 nBaseSize);
CAICHHashTree* m_pLeftTree;
CAICHHashTree* m_pRightTree;
public:
CAICHHash m_Hash;
uint64 m_nDataSize; // size of data which is covered by this hash
bool m_bIsLeftBranch; // left or right branch of the tree
bool m_bHashValid; // the hash is valid and not empty
private:
// BaseSize: to save ressources we use a bool to store the basesize as currently only two values are used
// keep the original number based calculations and checks in the code through, so it can easily be adjusted in case we want to use hashsets with different basesizes
bool m_bBaseSize; // blocksize on which the lowest hash is based on
bool m_bIsBuffered; //zz_fly :: known2 buffer //is this tree in buffer
};
/////////////////////////////////////////////////////////////////////////////////////////
///CAICHUntrustedHashs
class CAICHUntrustedHash {
public:
CAICHUntrustedHash& operator=(const CAICHUntrustedHash& k1) { m_adwIpsSigning.Copy(k1.m_adwIpsSigning); m_Hash = k1.m_Hash ; return *this; }
bool AddSigningIP(uint32 dwIP, bool bTestOnly);
CAICHHash m_Hash;
CArray<uint32, uint32> m_adwIpsSigning;
};
/////////////////////////////////////////////////////////////////////////////////////////
///CAICHUntrustedHashs
class CAICHRequestedData {
public:
CAICHRequestedData() {m_nPart = 0; m_pPartFile = NULL; m_pClient= NULL;}
CAICHRequestedData& operator=(const CAICHRequestedData& k1) { m_nPart = k1.m_nPart; m_pPartFile = k1.m_pPartFile; m_pClient = k1.m_pClient; return *this; }
uint16 m_nPart;
CPartFile* m_pPartFile;
CUpDownClient* m_pClient;
};
/////////////////////////////////////////////////////////////////////////////////////////
///CAICHRecoveryHashSet
class CAICHRecoveryHashSet
{
public:
CAICHRecoveryHashSet(CKnownFile* pOwner, EMFileSize nSize = (uint64)0);
~CAICHRecoveryHashSet(void);
bool CreatePartRecoveryData(uint64 nPartStartPos, CFileDataIO* fileDataOut, bool bDbgDontLoad = false);
bool ReadRecoveryData(uint64 nPartStartPos, CSafeMemFile* fileDataIn);
bool ReCalculateHash(bool bDontReplace = false);
bool VerifyHashTree(bool bDeleteBadTrees);
void UntrustedHashReceived(const CAICHHash& Hash, uint32 dwFromIP);
bool IsPartDataAvailable(uint64 nPartStartPos);
void SetStatus(EAICHStatus bNewValue) {m_eStatus = bNewValue;}
EAICHStatus GetStatus() const {return m_eStatus;}
void SetOwner(CKnownFile* val) {m_pOwner = val;}
void FreeHashSet();
void SetFileSize(EMFileSize nSize);
const CAICHHash& GetMasterHash() const {return m_pHashTree.m_Hash;}
void SetMasterHash(const CAICHHash& Hash, EAICHStatus eNewStatus);
bool HasValidMasterHash() {return m_pHashTree.m_bHashValid;}
bool GetPartHashs(CArray<CAICHHash>& rResult) const;
const CAICHHashTree* FindPartHash(uint16 nPart);
bool SaveHashSet();
bool LoadHashSet(); // Loading from known2.met
static CAICHHashAlgo* GetNewHashAlgo();
static void ClientAICHRequestFailed(CUpDownClient* pClient);
static void RemoveClientAICHRequest(const CUpDownClient* pClient);
static bool IsClientRequestPending(const CPartFile* pForFile, uint16 nPart);
static CAICHRequestedData GetAICHReqDetails(const CUpDownClient* pClient);
static void AddStoredAICHHash(CAICHHash Hash);
void DbgTest();
CAICHHashTree m_pHashTree;
static CList<CAICHRequestedData> m_liRequestedData;
static CMutex m_mutKnown2File;
//zz_fly :: known2 buffer
//do not update known2.met until we have buffered enough hashsets. reduce the diskio during hashing.
static bool SaveHashSetToFile(bool forced); //this method also called in uploadtimer.
static CMutex m_mutSaveHashSet; //make sure there is only one saving process in progress.
//zz_fly :: end
private:
static CList<CAICHHash> m_liAICHHashsStored; // contains all AICH hahses stored in known2*.met
CKnownFile* m_pOwner;
EAICHStatus m_eStatus;
CArray<CAICHUntrustedHash> m_aUntrustedHashs;
//zz_fly :: known2 buffer
static CList<CAICHHashTree> m_liBufferedHashTree; //the hashsets we have buffered
static uint32 m_nLastSaved; //last time we saved the hashsets
static uint64 m_uBufferedSize; //buffered hashsets size
//zz_fly :: end
}; | [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b",
"[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b"
]
| [
[
[
1,
61
],
[
63,
72
],
[
74,
137
],
[
139,
141
],
[
149,
152
],
[
154,
155
],
[
161,
163
],
[
165,
184
],
[
186,
192
],
[
194,
210
],
[
213,
214
],
[
217,
229
],
[
231,
232
],
[
235,
236
],
[
238,
238
],
[
240,
243
],
[
245,
249
],
[
255,
255
],
[
257,
259
],
[
265,
265
]
],
[
[
62,
62
],
[
73,
73
],
[
138,
138
],
[
142,
148
],
[
153,
153
],
[
156,
160
],
[
164,
164
],
[
185,
185
],
[
193,
193
],
[
211,
212
],
[
215,
216
],
[
230,
230
],
[
233,
234
],
[
237,
237
],
[
239,
239
],
[
244,
244
],
[
250,
254
],
[
256,
256
],
[
260,
264
]
]
]
|
8d50922265b11f497e3281883ef91b5c0dd35326 | 1cc5720e245ca0d8083b0f12806a5c8b13b5cf98 | /v107/e/c.cpp | 7cf3ba6dc03b0c4771378918ff4e8aff132b29a5 | []
| no_license | Emerson21/uva-problems | 399d82d93b563e3018921eaff12ca545415fd782 | 3079bdd1cd17087cf54b08c60e2d52dbd0118556 | refs/heads/master | 2021-01-18T09:12:23.069387 | 2010-12-15T00:38:34 | 2010-12-15T00:38:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 619 | cpp | #include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int coins, c[100],deslen;
void start() {
int maxi[100];
int i,j,k,mz = 0;
int maior = 0;
for(i=0;i!=coins;i++) {
maxi[i] = deslen - (deslen % c[i]);
if(maxi[i] <= deslen && maxi[i]> maior) { maior = maxi[i]; mz = i; }
}
if(mz==0) maior = maxi[0];
}
int main () {
int dlen,i;
while(true) {
cin >> coins >> dlen;
if(!coins && !dlen) return 0;
for(i=0;i!=coins;i++) cin >> c[i];
for(i=0;i!=dlen;i++) {
cin >> deslen;
start();
}
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
38
]
]
]
|
feaabbbf980fcf87e587df5f675299dd02ff0453 | ef25bd96604141839b178a2db2c008c7da20c535 | /src/src/Engine/Renderer/D3DApp/d3dutil.h | da9b856f87fb2a5bf047e45f13a23d4efaa89ddb | []
| no_license | OtterOrder/crock-rising | fddd471971477c397e783dc6dd1a81efb5dc852c | 543dc542bb313e1f5e34866bd58985775acf375a | refs/heads/master | 2020-12-24T14:57:06.743092 | 2009-07-15T17:15:24 | 2009-07-15T17:15:24 | 32,115,272 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 12,706 | h | #pragma once
//===========================================================================//
// Include //
//===========================================================================//
#include <D3D9.h>
#include <D3DX9Math.h>
//===========================================================================//
// Initialise une structure D3DMATERIAL9 avec une couleur diffuse et ambiante//
//===========================================================================//
VOID D3DUtil_InitMaterial( D3DMATERIAL9& mtrl, FLOAT r=0.0f, FLOAT g=0.0f,
FLOAT b=0.0f, FLOAT a=1.0f );
//===========================================================================//
// Initialise une structure D3DLIGHT avec une position //
//===========================================================================//
VOID D3DUtil_InitLight( D3DLIGHT9 & light, D3DLIGHTTYPE ltType,
FLOAT x=0.0f, FLOAT y=0.0f, FLOAT z=0.0f );
//===========================================================================//
// Fonction d'aide pour créer une texture //
//===========================================================================//
HRESULT D3DUtil_CreateTexture( LPDIRECT3DDEVICE9 pd3dDevice, TCHAR* strTexture,
LPDIRECT3DTEXTURE9* ppTexture,
D3DFORMAT d3dFormat = D3DFMT_UNKNOWN );
//===========================================================================//
// Retourne une matrice de vue pour le rendu d'une face d'un cubemap //
//===========================================================================//
D3DXMATRIX D3DUtil_GetCubeMapViewMatrix( DWORD dwFace );
//===========================================================================//
// Retourne un quaternion pour la rotation faire par la rotation du curseur //
//===========================================================================//
D3DXQUATERNION D3DUtil_GetRotationFromCursor( HWND hWnd,
FLOAT fTrackBallRadius=1.0f );
//===========================================================================//
// Construit et met un curseur pour le d3d device grâce au hCursor //
//===========================================================================//
HRESULT D3DUtil_SetDeviceCursor( LPDIRECT3DDEVICE9 pd3dDevice, HCURSOR hCursor,
BOOL bAddWatermark );
//===========================================================================//
// Retourne le string pour le D3DFORMAT donné //
//===========================================================================//
TCHAR* D3DUtil_D3DFormatToString( D3DFORMAT format, bool bWithPrefix = true );
enum D3DUtil_CameraKeys
{
CAM_STRAFE_LEFT = 0,
CAM_STRAFE_RIGHT,
CAM_MOVE_FORWARD,
CAM_MOVE_BACKWARD,
CAM_MOVE_UP,
CAM_MOVE_DOWN,
CAM_RESET,
CAM_CONTROLDOWN,
CAM_MAX_KEYS,
CAM_UNKNOWN = 0xFF
};
#define KEY_WAS_DOWN_MASK 0x80
#define KEY_IS_DOWN_MASK 0x01
#define MOUSE_LEFT_BUTTON 0x01
#define MOUSE_MIDDLE_BUTTON 0x02
#define MOUSE_RIGHT_BUTTON 0x04
#define MOUSE_WHEEL 0x08
//===========================================================================//
// Classe abstraite pour une caméra de base : rotations et mouvements //
//===========================================================================//
class CBaseCamera
{
public:
CBaseCamera();
//===========================================================================//
// Fonctions à appeler par l'utilisateur //
//===========================================================================//
virtual LRESULT HandleMessages( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
virtual void FrameMove( FLOAT fElapsedTime ) = 0;
//===========================================================================//
// Fonctions pour spécifier les paramètres des matrices //
//===========================================================================//
virtual void Reset();
virtual void SetViewParams( D3DXVECTOR3* pvEyePt, D3DXVECTOR3* pvLookatPt );
virtual void SetProjParams( FLOAT fFOV, FLOAT fAspect, FLOAT fNearPlane, FLOAT fFarPlane );
//===========================================================================//
// Fonctions pour changer les comportements //
//===========================================================================//
virtual void SetDragRect( RECT &rc ) { m_rcDrag = rc; }
void SetInvertPitch( bool bInvertPitch ) { m_bInvertPitch = bInvertPitch; }
void SetDrag( bool bMovementDrag, FLOAT fTotalDragTimeToZero = 0.25f ) { m_bMovementDrag = bMovementDrag; m_fTotalDragTimeToZero = fTotalDragTimeToZero; }
void SetEnableYAxisMovement( bool bEnableYAxisMovement ) { m_bEnableYAxisMovement = bEnableYAxisMovement; }
void SetEnablePositionMovement( bool bEnablePositionMovement ) { m_bEnablePositionMovement = bEnablePositionMovement; }
void SetClipToBoundary( bool bClipToBoundary, D3DXVECTOR3* pvMinBoundary, D3DXVECTOR3* pvMaxBoundary ) { m_bClipToBoundary = bClipToBoundary; if( pvMinBoundary ) m_vMinBoundary = *pvMinBoundary; if( pvMaxBoundary ) m_vMaxBoundary = *pvMaxBoundary; }
void SetScalers( FLOAT fRotationScaler = 0.01f, FLOAT fMoveScaler = 5.0f ) { m_fRotationScaler = fRotationScaler; m_fMoveScaler = fMoveScaler; }
void SetNumberOfFramesToSmoothMouseData( int nFrames ) { if( nFrames > 0 ) m_fFramesToSmoothMouseData = (float)nFrames; }
void SetResetCursorAfterMove( bool bResetCursorAfterMove ) { m_bResetCursorAfterMove = bResetCursorAfterMove; }
//===========================================================================//
// Obtention des états //
//===========================================================================//
const D3DXMATRIX* GetViewMatrix() const { return &m_mView; }
const D3DXMATRIX* GetProjMatrix() const { return &m_mProj; }
const D3DXVECTOR3* GetEyePt() const { return &m_vEye; }
const D3DXVECTOR3* GetLookAtPt() const { return &m_vLookAt; }
float GetNearClip() const { return m_fNearPlane; }
float GetFarClip() const { return m_fFarPlane; }
bool IsBeingDragged() const { return (m_bMouseLButtonDown || m_bMouseMButtonDown || m_bMouseRButtonDown); }
bool IsMouseLButtonDown() const { return m_bMouseLButtonDown; }
bool IsMouseMButtonDown() const { return m_bMouseMButtonDown; }
bool IsMouseRButtonDown() const { return m_bMouseRButtonDown; }
protected:
//===========================================================================//
// Fonctions pour mapper le WM_KEYDOWN pour un enum D3DUtil_CameraKeys //
//===========================================================================//
virtual D3DUtil_CameraKeys MapKey( UINT nKey );
bool IsKeyDown( BYTE key ) const { return( (key & KEY_IS_DOWN_MASK) == KEY_IS_DOWN_MASK ); }
bool WasKeyDown( BYTE key ) const { return( (key & KEY_WAS_DOWN_MASK) == KEY_WAS_DOWN_MASK ); }
void ConstrainToBoundary( D3DXVECTOR3* pV );
void UpdateMouseDelta();
void UpdateVelocity( float fElapsedTime );
void GetInput( bool bGetKeyboardInput, bool bGetMouseInput, bool bGetGamepadInput, bool bResetCursorAfterMove );
D3DXMATRIX m_mView; // Matrice de vue
D3DXMATRIX m_mProj; // Matrice de projection
int m_cKeysDown; // Nombre de touches appuyées
BYTE m_aKeys[CAM_MAX_KEYS]; // Etat de l'entrée - KEY_WAS_DOWN_MASK|KEY_IS_DOWN_MASK
D3DXVECTOR3 m_vKeyboardDirection; // Vecteur de direction de l'entrée clavier
POINT m_ptLastMousePosition; // Dernière position absolue du curseur
bool m_bMouseLButtonDown; // Vrai si le bouton gauche est appuyé
bool m_bMouseMButtonDown; // Vrai si le bouton du milieu est appuyé
bool m_bMouseRButtonDown; // Vrai si le bouton droit est appuyé
int m_nCurrentButtonMask; // Masque pour savoir quel bouton est appuyé
int m_nMouseWheelDelta; // Niveau de la molette
D3DXVECTOR2 m_vMouseDelta; // Delta relatif de la souris lissé sur quelques frames
float m_fFramesToSmoothMouseData; // Nombre de frames à lisser
D3DXVECTOR3 m_vDefaultEye; // Position caméra par défaut
D3DXVECTOR3 m_vDefaultLookAt; // LookAt par défaut
D3DXVECTOR3 m_vEye; // Position caméra
D3DXVECTOR3 m_vLookAt; // LookAt
float m_fCameraYawAngle; // Yaw angle
float m_fCameraPitchAngle; // Pitch angle
RECT m_rcDrag; // Rectangle où l'on peut initialiser le glissement
D3DXVECTOR3 m_vVelocity; // Vitesse caméra
bool m_bMovementDrag; // Si vrai, alors le mouvement de caméra s'arrête
D3DXVECTOR3 m_vVelocityDrag; // Force glissement
FLOAT m_fDragTimer; // Timer décompte pour appliquer le glissement
FLOAT m_fTotalDragTimeToZero; // Temps prit pour que la vitesse aille de 0 à son max
D3DXVECTOR2 m_vRotVelocity; // Vitesse caméra
float m_fFOV; // FOV
float m_fAspect; // Aspect ratio
float m_fNearPlane; // Near plane
float m_fFarPlane; // Far plane
float m_fRotationScaler; // Scaler rotation
float m_fMoveScaler; // Scaler mouvement
bool m_bInvertPitch; // Invertion pitch axis
bool m_bEnablePositionMovement; // Si vrai, alors l'utilisateur peut translater la camera
bool m_bEnableYAxisMovement; // Si vrai, alors la camera peut bouger sur l'axe des y
bool m_bClipToBoundary; // Si vrai, alors la caméra sera clippée
D3DXVECTOR3 m_vMinBoundary; // Point minimum
D3DXVECTOR3 m_vMaxBoundary; // Poinr maximum
bool m_bResetCursorAfterMove; // Si vrai, la classe redémarerra la position du curseur
};
//===========================================================================//
// Classe caméra vue à la première personne. //
//===========================================================================//
class CFirstPersonCamera : public CBaseCamera
{
public:
CFirstPersonCamera();
//===========================================================================//
// A appeler par l'utilisateur //
//===========================================================================//
virtual void FrameMove( FLOAT fElapsedTime );
//===========================================================================//
// Fonctions pour changer le comportement //
//===========================================================================//
void SetRotateButtons( bool bLeft, bool bMiddle, bool bRight, bool bRotateWithoutButtonDown = false );
//===========================================================================//
// Fonctions pour obtenir les états //
//===========================================================================//
D3DXMATRIX* GetWorldMatrix() { return &m_mCameraWorld; }
const D3DXVECTOR3* GetWorldRight() const { return (D3DXVECTOR3*)&m_mCameraWorld._11; }
const D3DXVECTOR3* GetWorldUp() const { return (D3DXVECTOR3*)&m_mCameraWorld._21; }
const D3DXVECTOR3* GetWorldAhead() const { return (D3DXVECTOR3*)&m_mCameraWorld._31; }
const D3DXVECTOR3* GetEyePt() const { return (D3DXVECTOR3*)&m_mCameraWorld._41; }
protected:
D3DXMATRIX m_mCameraWorld; // Matrice monde de la caméra
int m_nActiveButtonMask; // Masque pour savoir quel bouton est appuyé
bool m_bRotateWithoutButtonDown;
}; | [
"mathieu.chabanon@7c6770cc-a6a4-11dd-91bf-632da8b6e10b"
]
| [
[
[
1,
217
]
]
]
|
f18b3b3ea0c9445598c82104049b5aba3486c518 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/AIGoalAnimate.cpp | 9bf0709a78931a7246de5c000e9dda7452928ec7 | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,258 | cpp | // ----------------------------------------------------------------------- //
//
// MODULE : AIGoalAnimate.cpp
//
// PURPOSE : AIGoalAnimate implementation
//
// CREATED : 7/30/01
//
// (c) 2001 Monolith Productions, Inc. All Rights Reserved
// ----------------------------------------------------------------------- //
#include "stdafx.h"
#include "AIGoalAnimate.h"
#include "AIHumanState.h"
#include "AIGoalMgr.h"
#include "AI.h"
#include "AIUtils.h"
DEFINE_AI_FACTORY_CLASS_SPECIFIC(Goal, CAIGoalAnimate, kGoal_Animate);
// ----------------------------------------------------------------------- //
//
// ROUTINE: CAIGoalAnimate::Con/destructor
//
// PURPOSE: Factory Con/destructor
//
// ----------------------------------------------------------------------- //
CAIGoalAnimate::CAIGoalAnimate()
{
m_bLoop = LTFALSE;
m_hstrAnim = LTNULL;
m_bResetAnim= LTTRUE;
}
CAIGoalAnimate::~CAIGoalAnimate()
{
FREE_HSTRING(m_hstrAnim);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CAIGoalAnimate::Save / Load
//
// PURPOSE: Save / Load
//
// ----------------------------------------------------------------------- //
void CAIGoalAnimate::Save(ILTMessage_Write *pMsg)
{
super::Save(pMsg);
SAVE_BOOL( m_bLoop );
SAVE_HSTRING( m_hstrAnim );
SAVE_BOOL( m_bResetAnim );
}
void CAIGoalAnimate::Load(ILTMessage_Read *pMsg)
{
super::Load(pMsg);
LOAD_BOOL( m_bLoop );
LOAD_HSTRING( m_hstrAnim );
LOAD_BOOL( m_bResetAnim );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CAIGoalAnimate::ActivateGoal
//
// PURPOSE: Activate goal.
//
// ----------------------------------------------------------------------- //
void CAIGoalAnimate::ActivateGoal()
{
super::ActivateGoal();
AIASSERT(m_hstrAnim != LTNULL, m_pAI->m_hObject, "CAIGoalAnimate::ActivateGoal: Anim is NULL.");
m_pGoalMgr->LockGoal(this);
m_pAI->SetState( kState_HumanAnimate );
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CAIGoalAnimate::UpdateGoal
//
// PURPOSE: Update goal.
//
// ----------------------------------------------------------------------- //
void CAIGoalAnimate::UpdateGoal()
{
CAIState* pState = m_pAI->GetState();
switch(pState->GetStateType())
{
case kState_HumanAnimate:
HandleStateAnimate();
break;
// Unexpected State.
default: AIASSERT(0, m_pAI->m_hObject, "CAIGoalAnimate::UpdateGoal: Unexpected State.");
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CAIGoalAnimate::HandleStateAnimate
//
// PURPOSE: Determine what to do when in state Animate.
//
// ----------------------------------------------------------------------- //
void CAIGoalAnimate::HandleStateAnimate()
{
switch( m_pAI->GetState()->GetStateStatus() )
{
case kSStat_Initialized:
if( m_bResetAnim )
{
CAIHumanStateAnimate* pStateAnimate = (CAIHumanStateAnimate*)(m_pAI->GetState());
pStateAnimate->SetAnimation(m_hstrAnim, m_bLoop);
m_bResetAnim = LTFALSE;
}
break;
case kSStat_StateComplete:
m_pGoalMgr->UnlockGoal(this);
m_fCurImportance = 0.f;
break;
// Unexpected StateStatus.
default: AIASSERT(0, m_pAI->m_hObject, "CAIGoalAnimate::HandleStateAnimate: Unexpected State Status.");
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CAIGoalAnimate::HandleNameValuePair
//
// PURPOSE: Handles getting a name/value pair.
//
// ----------------------------------------------------------------------- //
LTBOOL CAIGoalAnimate::HandleNameValuePair(const char *szName, const char *szValue)
{
AIASSERT(szName && szValue, m_pAI->m_hObject, "CAIGoalAnimate::HandleNameValuePair: Missing name or value.");
if ( !_stricmp(szName, "ANIM") )
{
FREE_HSTRING(m_hstrAnim);
m_hstrAnim = g_pLTServer->CreateString((char*)szValue);
m_bResetAnim = LTTRUE;
return LTTRUE;
}
else if ( !_stricmp(szName, "LOOP") )
{
m_bLoop = IsTrueChar(szValue[0]);
m_bResetAnim = LTTRUE;
return LTTRUE;
}
return LTFALSE;
}
| [
"[email protected]"
]
| [
[
[
1,
167
]
]
]
|
70cf4e17e124467d10407caed17814b72ff6f31f | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/common/src/Utilities/pxWindowTextWriter.cpp | dee9d6b9be1338df9fbcac2e2f3613914c6a39ff | []
| no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,701 | cpp | /* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 is free software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#include "wxGuiTools.h"
// --------------------------------------------------------------------------------------
// pxWindowTextWriter Implementations
// --------------------------------------------------------------------------------------
pxWindowTextWriter::pxWindowTextWriter( wxDC& dc )
: m_dc( dc )
{
m_curpos = wxPoint();
m_align = wxALIGN_CENTER;
m_leading = 0;
OnFontChanged();
}
void pxWindowTextWriter::OnFontChanged()
{
}
pxWindowTextWriter& pxWindowTextWriter::SetWeight( int weight )
{
wxFont curfont( m_dc.GetFont() );
curfont.SetWeight( weight );
m_dc.SetFont( curfont );
return *this;
}
pxWindowTextWriter& pxWindowTextWriter::SetStyle( int style )
{
wxFont curfont( m_dc.GetFont() );
curfont.SetStyle( style );
m_dc.SetFont( curfont );
return *this;
}
pxWindowTextWriter& pxWindowTextWriter::Normal()
{
wxFont curfont( m_dc.GetFont() );
curfont.SetStyle( wxNORMAL );
curfont.SetWeight( wxNORMAL );
m_dc.SetFont( curfont );
return *this;
}
pxWindowTextWriter& pxWindowTextWriter::SetPos( const wxPoint& pos )
{
m_curpos = pos;
return *this;
}
pxWindowTextWriter& pxWindowTextWriter::MovePos( const wxSize& delta )
{
m_curpos += delta;
return *this;
}
pxWindowTextWriter& pxWindowTextWriter::SetY( int ypos )
{
m_curpos.y = ypos;
return *this;
}
pxWindowTextWriter& pxWindowTextWriter::MoveY( int ydelta )
{
m_curpos.y += ydelta;
return *this;
}
void pxWindowTextWriter::_DoWriteLn( const wxChar* msg )
{
pxAssume( msg );
int tWidth, tHeight;
m_dc.GetMultiLineTextExtent( msg, &tWidth, &tHeight );
wxPoint dispos( m_curpos );
if( m_align & wxALIGN_CENTER_HORIZONTAL )
{
dispos.x = (m_dc.GetSize().GetWidth() - tWidth) / 2;
}
else if( m_align & wxALIGN_RIGHT )
{
dispos.x = m_dc.GetSize().GetWidth() - tWidth;
}
m_dc.DrawText( msg, dispos );
m_curpos.y += tHeight + m_leading;
}
// Splits incoming multi-line strings into pieces, and dispatches each line individually
// to the text writer.
void pxWindowTextWriter::_DoWrite( const wxChar* msg )
{
pxAssume( msg );
wxArrayString parts;
SplitString( parts, msg, L'\n' );
for( size_t i=0; i<parts.GetCount(); ++i )
_DoWriteLn( parts[i] );
}
pxWindowTextWriter& pxWindowTextWriter::SetFont( const wxFont& font )
{
m_dc.SetFont( font );
return *this;
}
pxWindowTextWriter& pxWindowTextWriter::Align( const wxAlignment& align )
{
m_align = align;
m_curpos.x = 0;
return *this;
}
pxWindowTextWriter& pxWindowTextWriter::WriteLn()
{
_DoWriteLn( L"" );
return *this;
}
pxWindowTextWriter& pxWindowTextWriter::WriteLn( const wxChar* fmt )
{
_DoWrite( fmt );
return *this;
}
pxWindowTextWriter& pxWindowTextWriter::FormatLn( const wxChar* fmt, ... )
{
va_list args;
va_start(args,fmt);
_DoWrite( pxsFmtV(fmt, args) );
va_end(args);
return *this;
}
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
]
| [
[
[
1,
155
]
]
]
|
05299a00fa83e4509bf448346229e8eef6896116 | e03ee4538dce040fe16fc7bb48d495735ac324f4 | /Stable/Main/InfluenceMap.cpp | 9aaf381c367ffc717b83e3858ee87b93018fa47e | []
| no_license | vdelgadov/itcvideogame | dca6bcb084c5dde25ecf29ab1555dbe8b0a9a441 | 5eac60e901b29bff4d844f34cd52f97f4d1407b5 | refs/heads/master | 2020-05-16T23:43:48.956373 | 2009-12-01T02:09:08 | 2009-12-01T02:09:08 | 42,265,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 995 | cpp | #include "../InfluenceMaps/InfluenceMap.h"
#include "CObjectMesh.cpp"
//#include "../AIController/Actor.h"
void InfluenceMap::update(double time){
list<CObjectMesh*>::iterator it = this->m_lActors.begin();
int c, r;
for(c=0; c<this->m_iMapHeight; c++)
for(r=0;r<this->m_iMapWidth; r++)
this->m_dMap[r][c] = 0;
for(; it != this->m_lActors.end(); ++it){
this->mapCoords((*it)->getVehicle()->getPos(), &c, &r);
int inf_rad = (*it)->getController()->getInfluenceRadius();
double influence = pow(-1.0, (*it)->getController()->getCategory());
int up, down, left, right;
up = r-inf_rad;
down = r+inf_rad;
left = c-inf_rad;
right = c+inf_rad;
while(down >= this->m_iMapHeight)
down--;
while(up< 0)
up++;
while(left < 0)
left++;
while(right >= this->m_iMapWidth)
right--;
for(int i=up; i<=down; i++)
for(int j=left; j<=right; j++)
this->m_dMap[i][j] += influence;
}
} | [
"leamsi.setroc@972b8bf6-92a2-11de-b72a-e7346c8bff7a",
"mrjackinc@972b8bf6-92a2-11de-b72a-e7346c8bff7a"
]
| [
[
[
1,
1
],
[
4,
5
],
[
7,
39
]
],
[
[
2,
3
],
[
6,
6
]
]
]
|
ed11631da38df7cfe9f1ecfafe4437511226165d | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Animation/Animation/Playback/Cache/Default/hkaDefaultChunkCache.inl | f72728a25c132bfec0dd652d911025d6ffefcaea | []
| no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,695 | inl | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
/* Hashing function : ( very simple for now )
h(k) = k mod m ( m = bucket size )
*/
inline hkBool hkaDefaultChunkCache::hashKey( struct hashKeyInfo& info )
{
//
// run the key through the hashing function ( each pool has its own modulus value == bucket size )
//
// which cache pool are we dealing with?
for( hkUint32 i = 0; i < m_numberOfCachePools; i++ )
{
if( info.m_chunkSize < m_cachePools[i].m_chunkSize )
{
info.m_cachePool = i;
break;
}
}
if( info.m_cachePool == -1 )
{
// invalid cache pool
// add this request to the list of unavailable chunks
#if defined( HK_CACHE_STATS )
// check if the array already has this chunk
for( hkInt32 i = 0; i < m_unavailableChunks.getSize(); i++ )
{
if( m_unavailableChunks[i].m_chunkSize == info.m_chunkSize )
{
// update frequency
m_unavailableChunks[i].m_frequency++;
return false;
}
}
// pushback a new unavailable chunk
struct unavailableChunk uChunk;
uChunk.m_chunkSize = info.m_chunkSize;
uChunk.m_frequency = 1;
m_unavailableChunks.pushBack( uChunk );
#endif
// warn that chunk size is unavailable (Ps2 gcc doesn't like the static guard variable in HK_WARN_ONCE)
HK_WARN_ONCE( 0x1cc3730c, "No cache pool enabled to deal with chunk size!" );
// failure
return false;
}
// hash the key and store result
info.m_bucket = ( info.m_key % m_cachePools[ info.m_cachePool ].m_buckets );
// success
return true;
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
90
]
]
]
|
456719e26253b70124c201ec5d6c5b80a5966247 | ffe0a7d058b07d8f806d610fc242d1027314da23 | /V3e/dev/IRCDcc.h | 7b2716fe998cc17b6cbabcfd6719c3956af06db4 | []
| no_license | Cybie/mangchat | 27bdcd886894f8fdf2c8956444450422ea853211 | 2303d126245a2b4778d80dda124df8eff614e80e | refs/heads/master | 2016-09-11T13:03:57.386786 | 2009-12-13T22:09:37 | 2009-12-13T22:09:37 | 32,145,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | h | #ifndef _MC_IRC_DCC_H
#define _MC_IRC_DCC_H
#include "ServerSocket.h"
class IRCDcc
{
public:
IRCDcc(){};
~IRCDcc(){};
void run();
private:
ServerSocket *Sock;
};
#endif
| [
"cybraxcyberspace@dfcbb000-c142-0410-b1aa-f54c88fa44bd"
]
| [
[
[
1,
17
]
]
]
|
ed81a49b32ed5e33dd724ad6966067e2924b8096 | 4275e8a25c389833c304317bdee5355ed85c7500 | /KylTek/Ai_Cop.cpp | b2c82befc9118e35b171d7ef4a30b428e38d3a04 | []
| no_license | kumorikarasu/KylTek | 482692298ef8ff501fd0846b5f41e9e411afe686 | be6a09d20159d0a320abc4d947d4329f82d379b9 | refs/heads/master | 2021-01-10T07:57:40.134888 | 2010-07-26T12:10:09 | 2010-07-26T12:10:09 | 55,943,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,366 | cpp | #include "Main.h"
#include "CGlobal.h"
#include "Ai_Cop.h"
#include "CollisionManager.h"
#include "Debug.h"
#include <math.h>
Ai_Cop::Ai_Cop(ENTITY_PARAMS* params){
Init(params);
m_friction = Vector2(0.03f,0.03f);
m_pCollider-> SetCollisionType(Dynamic);
m_pCollider-> SetSize(Vector2(64,64));
Global-> pColMan->AddICol(m_pCollider);
/*
m_phitboxhead = new ICol_AABB(this);
m_phitboxhead-> SetCollisionType(HitBox);
m_phitboxhead-> m_h = 50;
m_phitboxhead-> m_w = 50;
m_phitboxhead-> m_hy = 25;
m_phitboxhead-> m_hx = 25;
*/
m_prevpos = m_pos;
}
Ai_Cop::~Ai_Cop(){
}
void Ai_Cop::Step(CDeviceHandler* DH){
//Global->pColMan->getQT()->RemoveEntity(m_pCollider);
if(m_animationa>=360)
m_animationa=0;
if(m_animationa<=-360)
m_animationa=0;
m_animationa+=m_accel.x/2;
m_animationb+=0.05f;
Verlet();
if (m_pos.x<0) m_pos.x=0;
if (m_pos.x>Global->LEVEL_WIDTH) m_pos.x=Global->LEVEL_WIDTH;
if (m_pos.y<0)
m_state |= Dead;
if (m_pos.y>Global->LEVEL_HEIGHT)
m_state |= Dead;
m_pCollider -> UpdatePos();
};
void Ai_Cop::Draw(CGraphicsHandler *g){
/*
g->DrawSprite(
g->SprList->Char->ME->Feet,
0,
Vector2(m_pos.x-sin(m_animationa)*8,m_pos.y+6-(m_pos.y-m_prevpos.y)),
Vector2(m_scale.x*m_dir, m_scale.y),
((m_pos.y-m_prevpos.y)*6)*m_dir,
CLR_WHITE);
g->DrawSprite(
g->SprList->Char->ME->Feet,
0,
Vector2(m_pos.x+sin(m_animationa)*8+(3*m_dir),m_pos.y+6-(m_pos.y-m_prevpos.y)),
Vector2(m_scale.x*m_dir, m_scale.y),
((m_pos.y-m_prevpos.y)*6)*m_dir,
CLR_WHITE);
g->DrawSprite(
g->SprList->Char->ME->FullHead,
0,
Vector2(m_pos.x+(((m_pos.x-m_prevpos.x)/1.2f)),m_pos.y-39-sin(m_animationb)*2),
Vector2(m_scale.x*m_dir, m_scale.y),
D3DXToDegree(atan2(MOUSE.x-m_pos.x, MOUSE.y-m_pos.y))-(90*m_dir),
CLR_WHITE);
*/
// g->DrawSprite(
// g->SprList->Char->ME->Torso,
// 0,
// Vector2(m_pos.x,m_pos.y-46));
};
void Ai_Cop::DebugDraw(CGraphicsHandler *g){
if(Debug->CheckFlag(CDebug::HitBoxes)){
// g->DrawRect( Vector2(m_pos.x,m_pos.y), getWidth(), getHeight(), D3DCOLOR_RGBA(255,0,0,0), 1, D3DCOLOR_RGBA(255,0,0,255));
// g->DrawRect( Vector2(m_pos.x,m_pos.y), (int)m_phitboxhead->m_w, (int)m_phitboxhead->m_h, D3DCOLOR_RGBA(255,0,0,0), 1, D3DCOLOR_RGBA(255,255,0,255));
}
} | [
"Sean Stacey@localhost"
]
| [
[
[
1,
94
]
]
]
|
b3946e0076d145fbbcc16a429c9fe3813b716357 | 54cacc105d6bacdcfc37b10d57016bdd67067383 | /trunk/source/level/objects/messages/MsgObjectPredestroyed.h | a820bf646dc8a7aa9554b63d19039636a676f5ad | []
| no_license | galek/hesperus | 4eb10e05945c6134901cc677c991b74ce6c8ac1e | dabe7ce1bb65ac5aaad144933d0b395556c1adc4 | refs/heads/master | 2020-12-31T05:40:04.121180 | 2009-12-06T17:38:49 | 2009-12-06T17:38:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 937 | h | /***
* hesperus: MsgObjectPredestroyed.h
* Copyright Stuart Golodetz, 2009. All rights reserved.
***/
#ifndef H_HESP_MSGOBJECTPREDESTROYED
#define H_HESP_MSGOBJECTPREDESTROYED
#include <source/level/objects/base/Message.h>
#include <source/level/objects/base/ObjectID.h>
namespace hesp {
/**
An 'object predestroyed' message is sent prior to object destruction to allow
owned/contained objects to be destroyed first.
*/
class MsgObjectPredestroyed : public Message
{
//#################### PRIVATE VARIABLES ####################
private:
ObjectID m_id;
//#################### CONSTRUCTORS ####################
public:
explicit MsgObjectPredestroyed(const ObjectID& id);
//#################### PUBLIC METHODS ####################
public:
void dispatch(MessageHandlerBase *handler) const;
const ObjectID& object_id() const;
std::set<ObjectID> referenced_objects() const;
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
51f12b6213605ae2f93b6faa4714099ab5a93088 | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/Src/CItem.cpp | d58a4e5b6746981a172d09d43556f4428f06a958 | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,000 | cpp | #include "CItem.h"
namespace Nebula {
CItem::CItem()
{
mComponentID = "CItem";
}
CItem::CItem(const CItemDesc& desc) : IPickableItem()
{
mComponentID = "CItem";
mDesc = desc;
}
CItem::~CItem()
{
}
void CItem::update() {
}
void CItem::setup() {
}
void CItem::OnItemInventoryActivate() {
}
void CItem::OnItemPick() {
callLuaFunction("OnItemPick");
}
void CItem::OnItemDrop() {
callLuaFunction("OnItemDrop");
}
void CItem::OnItemMenuStartDrag() {
callLuaFunction("OnItemMenuStartDrag");
}
void CItem::OnItemMenuFinishDrag() {
callLuaFunction("OnItemMenuFinishDrag");
}
void CItem::callLuaFunction(const std::string func ) {
luabind::object componentState = getOwnerObject()->getTemplateObject();
if(componentState) {
luabind::object CallBack = componentState[func];
if(CallBack)
luabind::call_function<void>(CallBack,this->getOwnerObject()); // this
}
}
} //end namespace
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
57
]
]
]
|
2b62406915749fe5a6381f82ceab3795ca99c828 | d235b8143a573107d81ea4f0d1ed78e853b6dd06 | /RobotFindDoor/mainwindow.h | b099a701f74f15446223114598446ade93773c49 | []
| no_license | joshuaeckroth/Robot-Find-Door | e9ff4cdf0f7f34c2abad2d98ee5597ac91127f36 | beddc08c73287055f78230b42ebfca39b81b000d | refs/heads/master | 2021-01-02T23:07:36.643436 | 2010-05-30T17:19:18 | 2010-05-30T17:19:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 561 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
class LogDialog;
class Manager;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
void changeEvent(QEvent *e);
private slots:
void setSeed();
void newSeed(int);
void go();
void reset();
void solutionComplete();
private:
Ui::MainWindow *ui;
LogDialog *logDialog;
Manager *m;
};
#endif // MAINWINDOW_H
| [
"[email protected]"
]
| [
[
[
1,
35
]
]
]
|
cb3081d5932564968a6da6213d0e038a5097b045 | e947bc69d8ee60ab0f1ccf28c9943027fa43f397 | /YJCalendarCtrlHeader.h | a365faa2aefabe0ac5750f2dcea23b8868f1284f | []
| no_license | losywee/yjui | fc33d8034d707a6663afef6cb8b55b1483992fc5 | caeea083b91597f7f3c46cb9e69dcb009258649a | refs/heads/master | 2021-01-10T07:35:15.909900 | 2010-04-01T09:14:23 | 2010-04-01T09:14:23 | 45,093,947 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 895 | h | #pragma once
#include "YJCalendarCtrl.h"
#include "YJButton.h"
class AFX_EXT_CLASS CYJCalendarCtrlHeader : public CWnd
{
DECLARE_DYNAMIC(CYJCalendarCtrlHeader)
private:
CYJCalendarCtrl* m_pCalendar;
COLORREF m_clrDate;
COLORREF m_clrBackground;
HFONT m_hFontDate;
CYJButton m_btnNextMonth;
CYJButton m_btnNextYear;
CYJButton m_btnPrevMonth;
CYJButton m_btnPrevYear;
protected:
DECLARE_MESSAGE_MAP()
public:
CYJCalendarCtrlHeader();
virtual ~CYJCalendarCtrlHeader();
BOOL SetCalendarCtrl(CYJCalendarCtrl* pWnd);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint();
afx_msg LRESULT OnMonthChanged(WPARAM wParam,LPARAM lParam);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnNextMonth();
afx_msg void OnPrevMonth();
afx_msg void OnNextYear();
afx_msg void OnPrevYear();
}; | [
"Caiyj.84@3d1e88fc-ca97-11de-9d4f-f947ee5921c8"
]
| [
[
[
1,
38
]
]
]
|
6b650ea62636a4752c458c79e97d7bdabc618fff | fcdddf0f27e52ece3f594c14fd47d1123f4ac863 | /terralib/src/terralib/drivers/Firebird/TeFirebird.cpp | ab117f8fe385135e2d0de1b121b7bf6c76c3b919 | []
| no_license | radtek/terra-printer | 32a2568b1e92cb5a0495c651d7048db6b2bbc8e5 | 959241e52562128d196ccb806b51fda17d7342ae | refs/heads/master | 2020-06-11T01:49:15.043478 | 2011-12-12T13:31:19 | 2011-12-12T13:31:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 84,577 | cpp | /************************************************************************************
TerraLib - a library for developing GIS applications.
Copyright � 2001-2007 INPE and Tecgraf/PUC-Rio.
This code is part of the TerraLib library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
You should have received a copy of the GNU Lesser General Public
License along with this library.
The authors reassure the license terms regarding the warranties.
They specifically disclaim any warranties, including, but not limited to,
the implied warranties of merchantability and fitness for a particular purpose.
The library provided hereunder is on an "as is" basis, and the authors have no
obligation to provide maintenance, support, updates, enhancements, or modifications.
In no event shall INPE and Tecgraf / PUC-Rio be held liable to any party for direct,
indirect, special, incidental, or consequential damages arising out of the use
of this library and its documentation.
*************************************************************************************/
#include "TeFirebird.h"
#include <stdio.h>
#include <sys/types.h>
#include <TeProject.h>
#include <cstring>
#ifndef MAX
#define MAX(a,b) ((a>b)?a:b)
#endif
#ifndef MIN
#define MIN(a,b) ((a<b)?a:b)
#endif
void convertChar2Blob(char* buffer, const int& size, IBPP::Blob& blob)
{
int bufferSize = 10240,
segments = size / bufferSize;
char* aux = buffer;
blob->Create();
for(int i=0; i<segments; i++)
{
blob->Write(aux, bufferSize);
aux += bufferSize;
}
int resto = size - (segments*bufferSize);
if(resto > 0)
{
blob->Write(aux, resto);
}
}
void convertBlob2Char(const IBPP::Blob& blob, char*& buffer, int& size)
{
blob->Open();
int bufferSize,
segments;
blob->Info(&size, &bufferSize, &segments);
buffer = new char[size];
segments = size/bufferSize;
char* aux = buffer;
for(int i=0; i<segments; i++)
{
blob->Read(aux, bufferSize);
aux += bufferSize;
}
int resto = size - bufferSize*segments;
if(resto > 0)
{
blob->Read(aux, resto);
}
}
void teRing2Buffer(const TeLinearRing& line, char*& buffer, int& bufferSize)
{
double* points = NULL;
TeLinearRing::iterator it;
points = new double[2*line.size()];
int iac = 0;
for(unsigned int i = 0; i < line.size(); i++)
{
points[iac++]=line[i].x();
points[iac++]=line[i].y();
}
bufferSize = 2*sizeof(double)*line.size();
buffer = (char*)(points);
}
void buffer2TeRing(const char* buffer, const int& numCoords, TeLinearRing& line)
{
for(int i=0; i<numCoords; i++)
{
double x,
y;
memcpy(&x, buffer+((2*i)*sizeof(double)),sizeof(double));
memcpy(&y, buffer+((2*i+1)*sizeof(double)),sizeof(double));
line.add(TeCoord2D(x, y));
}
}
void loadFromBlob(IBPP::Statement& st, TeLinearRing& ring)
{
int nc;
st->Get("num_coords", nc);
IBPP::Blob blob = IBPP::BlobFactory(st->DatabasePtr(), st->TransactionPtr());
st->Get("spatial_data", blob);
int size;
char* buffer;
convertBlob2Char(blob, buffer, size);
buffer2TeRing(buffer, size/(2*sizeof(double)), ring);
blob->Close();
delete []buffer;
}
void saveLineInBlob(IBPP::Blob& blob, TeLinearRing& ring)
{
int bLen = 0; //Buffer size.
char* buffer;
teRing2Buffer(ring, buffer, bLen);
convertChar2Blob(buffer, bLen, blob);
blob->Close();
delete []buffer;
}
bool generateLablesForPolygonal(IBPP::Database db, TeTheme* theme, const TeGeomRep& geomType,
std::string& errorMsg, const std::string& objId)
{
std::string collTable = theme->collectionTable(),
geomTable = theme->layer()->tableName(geomType),
query = "SELECT object_id, lower_x, lower_y, upper_x, upper_y FROM " + geomTable;
TeDatabasePortal* portal = theme->layer()->database()->getPortal();
bool res = true;
if(!portal->query(query))
{
throw TeException(UNKNOWN_ERROR_TYPE, "Error on query:\n" + portal->errorMessage());
}
if(!portal->fetchRow())
{
return res;
}
IBPP::Transaction tr = IBPP::TransactionFactory(db);
try
{
query = "UPDATE " + collTable + " SET label_x=?, label_y=? WHERE c_object_id=?";
if(!objId.empty())
{
query += " AND c_object_id=?";
}
tr->Start();
IBPP::Statement st = IBPP::StatementFactory(db, tr);
st->Prepare(query);
do
{
TeBox box(portal->getDouble(1), portal->getDouble(2), portal->getDouble(3), portal->getDouble(4));
std::string oId = portal->getData(0);
st->Set(1, box.center().x());
st->Set(2, box.center().y());
st->Set(3, oId);
if(!objId.empty())
{
st->Set(4, objId);
}
st->Execute();
} while(portal->fetchRow());
tr->Commit();
}
catch(IBPP::SQLException& e)
{
tr->Rollback();
errorMsg = e.ErrorMessage();
res = false;
}
catch(IBPP::LogicException& e)
{
tr->Rollback();
errorMsg = e.ErrorMessage();
res = false;
}
delete portal;
return res;
}
void createGeneratorTrigger(TeFirebird* db)
{
TeDatabasePortal* portal = db->getPortal();
std::string sql = "SELECT RDB$TRIGGER_NAME FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'REM_AUTO_INCR'";
if(!portal->query(sql))
{
throw;
}
bool exists = portal->fetchRow();
delete portal;
if(exists)
{
sql = "DELETE FROM RDB$TRIGGERS WHERE RDB$TRIGGER_NAME = 'REM_AUTO_INCR'";
if(!db->execute(sql))
{
throw TeException(UNKNOWN_ERROR_TYPE, ("Error removing trigger REM_AUTO_INCR!"));
}
}
sql = "CREATE TRIGGER REM_AUTO_INCR FOR RDB$GENERATORS ";
sql += "ACTIVE BEFORE INSERT POSITION 0 ";
sql += "AS BEGIN ";
sql += " IF (EXISTS (SELECT RDB$GENERATOR_NAME FROM RDB$GENERATORS WHERE RDB$GENERATOR_NAME = NEW.RDB$GENERATOR_NAME)) THEN ";
sql += " DELETE FROM RDB$GENERATORS WHERE RDB$GENERATOR_NAME = NEW.RDB$GENERATOR_NAME;";
sql += "END ";
if(!db->execute(sql))
{
throw TeException(UNKNOWN_ERROR_TYPE, ("Error creating trigger to remove generators!"));
}
}
TeFirebird::TeFirebird() :
TeDatabase()
{
isConnected_ = false;
dbmsName_ = "Firebird";
}
TeFirebird::~TeFirebird()
{
if (isConnected_)
close ();
}
IBPP::Database TeFirebird::getIBPPFirebird()
{
return firebird_;
}
void
TeFirebird::close()
{
if(firebird_ == NULL)
{
return;
}
if(firebird_->Connected())
{
if(transaction_->Started())
{
transaction_->Commit();
}
firebird_->Disconnect();
}
}
bool TeFirebird::beginTransaction()
{
transaction_->Start();
return true;
}
bool TeFirebird::commitTransaction()
{
if(transaction_->Started())
{
transaction_->Commit();
}
return true;
}
bool TeFirebird::rollbackTransaction()
{
if(transaction_->Started())
{
transaction_->Rollback();
}
return true;
}
std::string TeFirebird::mapToFirebirdType(const TeAttribute& teRep) const
{
std::string type;
switch(teRep.rep_.type_)
{
case TeREAL:
type = "DOUBLE PRECISION";
break;
case TeINT:
case TeUNSIGNEDINT:
type = "INTEGER ";
break;
case TeCHARACTER:
type = "CHAR(1) ";
break;
case TeDATETIME:
type = "TIMESTAMP "; //time
break;
case TeBOOLEAN:
type = "SMALLINT ";
break;
case TeBLOB:
type = "BLOB SUB_TYPE 0";
break;
case TePOINTTYPE:
case TePOINTSETTYPE:
type += "x DOUBLE PRECISION DEFAULT 0.0";
type += ", y DOUBLE PRECISION DEFAULT 0.0";
break;
case TeLINE2DTYPE:
case TeLINESETTYPE:
type += "num_coords INTEGER NOT NULL,";
type += "lower_x DOUBLE PRECISION NOT NULL,";
type += "lower_y DOUBLE PRECISION NOT NULL,";
type += "upper_x DOUBLE PRECISION NOT NULL,";
type += "upper_y DOUBLE PRECISION NOT NULL,";
type += "ext_max DOUBLE PRECISION NOT NULL, ";
type += "spatial_data BLOB NOT NULL";
break;
case TePOLYGONTYPE:
case TePOLYGONSETTYPE:
type += "num_coords INTEGER NOT NULL,";
type += "num_holes INTEGER NOT NULL,";
type += "parent_id INTEGER NOT NULL,";
type += "lower_x DOUBLE PRECISION NOT NULL,";
type += "lower_y DOUBLE PRECISION NOT NULL,";
type += "upper_x DOUBLE PRECISION NOT NULL,";
type += "upper_y DOUBLE PRECISION NOT NULL,";
type += "ext_max DOUBLE PRECISION NOT NULL,";
type += "spatial_data BLOB NOT NULL";
break;
case TeCELLTYPE:
case TeCELLSETTYPE:
type += "lower_x DOUBLE PRECISION NOT NULL,";
type += "lower_y DOUBLE PRECISION NOT NULL,";
type += "upper_x DOUBLE PRECISION NOT NULL,";
type += "upper_y DOUBLE PRECISION NOT NULL,";
type += "col_number INTEGER NOT NULL,";
type += "row_number INTEGER NOT NULL ";
break;
case TeRASTERTYPE:
type += "lower_x DOUBLE PRECISION NOT NULL, ";
type += "lower_y DOUBLE PRECISION NOT NULL, ";
type += "upper_x DOUBLE PRECISION NOT NULL, ";
type += "upper_y DOUBLE PRECISION NOT NULL, ";
type += "band_id INTEGER NOT NULL, ";
type += "resolution_factor INTEGER, ";
type += "subband INTEGER,";
type += "spatial_data BLOB NOT NULL, ";
type += "block_size INTEGER NOT NULL ";
break;
case TeNODETYPE:
case TeNODESETTYPE:
type += "x DOUBLE PRECISION DEFAULT 0.0";
type += ", y DOUBLE PRECISION DEFAULT 0.0";
break;
case TeTEXTTYPE:
case TeTEXTSETTYPE:
case TeSTRING:
default:
if(teRep.rep_.numChar_ > 0)
{
type = "VARCHAR(" + Te2String(teRep.rep_.numChar_) + ") ";
}
else
{
type = "VARCHAR(4096)"; //de forma que possam ser usadas ate 8 colunas deste tamanho. o tamanho de uma linha = 64K
}
break;
}
return type;
}
bool
TeFirebird::getIndexesFromTable(const string& tableName, std::vector<TeDatabaseIndex>& vecIndexes)
{
std::vector<TeDatabaseIndex> indexes;
string dbName = this->databaseName();
string query1 = "select I.RDB$INDEX_NAME as INDEX_NAME, S.RDB$FIELD_NAME as COLUMN_NAME ";
query1 += "from RDB$INDICES I, RDB$INDEX_SEGMENTS S ";
query1 += "where I.RDB$RELATION_NAME = '"+tableName+"' and I.RDB$INDEX_NAME = S.RDB$INDEX_NAME ";
query1 += "and I.RDB$INDEX_NAME not in ( select RDB$INDEX_NAME from RDB$RELATION_CONSTRAINTS ";
query1 += "where RDB$INDEX_NAME IS NOT NULL)";
TeDatabasePortal* portal = getPortal();
std::vector<std::string> names;
std::vector<std::string> cols;
std::set<std::string> idxNames;
std::multimap<std::string, std::string> idxAttrs;
if(portal->query(query1))
{
while(portal->fetchRow())
{
std::string idxName = portal->getData("INDEX_NAME");
std::string attrName = portal->getData("COLUMN_NAME");
idxAttrs.insert(std::pair<std::string, std::string>(idxName, attrName));
idxNames.insert(idxName);
}
}else
{
delete portal;
return false;
}
portal->freeResult();
delete portal;
portal = NULL;
std::set<std::string>::iterator it = idxNames.begin();
while(it != idxNames.end())
{
std::string idxName = *it;
TeDatabaseIndex idxx;
idxx.setIndexName(idxName);
idxx.setIsPrimaryKey(false);
std::vector<string> attNames;
std::pair<std::multimap<std::string, std::string>::iterator, std::multimap<std::string, std::string>::iterator> itAttrs = idxAttrs.equal_range(idxName);
std::multimap<std::string, std::string>::iterator itA;
for (itA=itAttrs.first; itA!=itAttrs.second; ++itA)
{
std::string attrName = itA->second;
attNames.push_back(attrName);
}
idxx.setColumns(attNames);
indexes.push_back(idxx);
++it;
}
vecIndexes = indexes;
return true;
}
bool TeFirebird::createAutoIncrement(const std::string& table, const std::string& column)
{
/** Needs to create a generator for firebird to do auto increment. **/
/** The name of the generator is composed by the name of table and the column name. **/
std::string gen = "CREATE GENERATOR ",
genName = ((table.size() <= 28) ? table : table.substr(0, 27))+ "_tr";
gen += genName + "; \n";
if(!execute(gen))
{
return false;
}
gen = "SET GENERATOR " + genName + " TO 0";
if(!execute(gen))
{
return false;
}
gen = "CREATE TRIGGER " + genName + " FOR " + table + " ACTIVE BEFORE ";
gen += "INSERT POSITION 0 AS \n"
+ std::string("BEGIN \n ")
+ "if((NEW." + column + " is NULL) OR (NEW." + column + "<=0)) then "
+ "NEW." + column + " = GEN_ID(" + genName + ", 1); \n END";
if(!execute(gen))
{
return false;
}
return true;
}
int TeFirebird::getLastGeneratedAutoNumber(const std::string& table)
{
int id = -1;
std::string genName = ((table.size() <= 21) ? table : table.substr(0, 20))+ "_tr";
genName = TeConvertToUpperCase(genName);
std::string sql = "SELECT GEN_ID(" + genName + ",1) FROM RDB$GENERATORS WHERE RDB$GENERATOR_NAME='" + genName + "'";
TeDatabasePortal* portal = getPortal();
if(portal->query(sql) && portal->fetchRow())
{
id = portal->getInt(0);
}
delete portal;
sql = "SET GENERATOR " + genName + " TO " + Te2String(id-1);
execute(sql);
return id;
}
bool TeFirebird::newDatabase(const string& database, const string& user, const string& password, const string& host, const int & port, bool terralibModel, const std::string& characterSet)
{
try
{
#ifdef WIN32
DeleteFile((const TCHAR*) database.c_str());
#else
DeleteFile(database.c_str());
#endif
firebird_ = IBPP::DatabaseFactory(host, database, user, password, "", "", "PAGE_SIZE = 8192");
firebird_->Create(3); // 3 is the dialect of the database (could have been 1)
IBPP::Service svc = IBPP::ServiceFactory(host, user, password);
svc->Connect();
svc->SetPageBuffers(database, 256); // Instead of default 2048
svc->SetSweepInterval(database, 5000); // instead of 20000 by default
svc->SetReadOnly(database, false); // That's the default anyway
svc->Disconnect();
if(!connect(host, user, password, database, port))
{
firebird_->Drop();
return false;
}
if(terralibModel)
{
//create conceptual model
if(!createConceptualModel())
{
firebird_->Drop();
return false;
}
}
}
catch(IBPP::LogicException& e)
{
errorMessage_ = e.ErrorMessage();
return false;
}
catch(IBPP::SQLException& e)
{
errorMessage_ = e.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebird::connect (const string& host, const string& user, const string& password, const string& database, int port)
{
try
{
firebird_ = IBPP::DatabaseFactory(host, database, user, password);
firebird_->Connect();
isConnected_ = firebird_->Connected();
if(!isConnected_)
{
return false;
}
// The following transaction configuration values are the defaults and
// those parameters could have as well be omitted to simplify writing.
transaction_ = IBPP::TransactionFactory(firebird_, IBPP::amWrite, IBPP::ilConcurrency, IBPP::lrWait);
user_ = user;
host_ = host;
password_ = password;
database_ = database;
portNumber_ = port;
createGeneratorTrigger(this);
}
catch(IBPP::SQLException& e)
{
errorMessage_ = e.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e)
{
errorMessage_ = e.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebird::showDatabases (const string&/* host*/, const string&/* user*/, const string& /*password*/, vector<string>& /*dbNames*/, int /*port*/)
{
/** There is function for this method in Firebird DBMS. It can't list its own databases. **/
return true;
}
bool
TeFirebird::execute (const string &q)
{
try
{
bool started = true;
if(!transaction_->Started())
{
transaction_->Start();
started = false;
}
IBPP::Statement st = IBPP::StatementFactory(firebird_, transaction_);
st->ExecuteImmediate(q);
(started) ? transaction_->CommitRetain() : transaction_->Commit();
}
catch(IBPP::SQLException& e)
{
transaction_->Rollback();
errorMessage_ = e.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e)
{
transaction_->Rollback();
errorMessage_ = e.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebird::createTable(const string& table, TeAttributeList &attr)
{
string createStr = " CREATE TABLE " + table + " (";
string type;
string pkeys,
autoNumColumn;
for(unsigned int i = 0; i < attr.size(); i++)
{
if(i>0)
{
createStr += ",";
}
type = "";
string name = attr[i].rep_.name_;
bool complexType = (attr[i].rep_.type_ == TePOINTTYPE) ||
(attr[i].rep_.type_ == TePOINTSETTYPE) ||
(attr[i].rep_.type_ == TeLINE2DTYPE) ||
(attr[i].rep_.type_ == TeLINESETTYPE) ||
(attr[i].rep_.type_ == TePOLYGONTYPE) ||
(attr[i].rep_.type_ == TePOLYGONSETTYPE) ||
(attr[i].rep_.type_ == TeCELLTYPE) ||
(attr[i].rep_.type_ == TeCELLSETTYPE) ||
(attr[i].rep_.type_ == TeRASTERTYPE) ||
(attr[i].rep_.type_ == TeNODETYPE) ||
(attr[i].rep_.type_ == TeNODESETTYPE);
createStr += (!complexType) ? name + " " + mapToFirebirdType(attr[i]) : mapToFirebirdType(attr[i]);
if(!(attr[i].rep_.defaultValue_.empty()) && !complexType)
{
type = " DEFAULT '" + attr[i].rep_.defaultValue_ + "' ";
}
if(!(attr[i].rep_.null_) && !complexType)
{
type = " NOT NULL ";
}
if(attr[i].rep_.isAutoNumber_)
{
autoNumColumn = attr[i].rep_.name_;
}
createStr += " " + type;
// check if column is part of primary key
if((attr[i].rep_.isPrimaryKey_) && (attr[i].rep_.type_ != TeBLOB))
{
if(!pkeys.empty())
pkeys += ",";
pkeys += attr[i].rep_.name_;
}
}
if(!pkeys.empty())
createStr += ",PRIMARY KEY (" + pkeys + ") ";
createStr += ")";
if(!execute(createStr))
{
return false;
}
if(!autoNumColumn.empty())
{
if(!createAutoIncrement(table, autoNumColumn))
{
return false;
}
}
return true;
}
bool
TeFirebird::tableExist(const string& table)
{
TeDatabasePortal* portal = getPortal();
bool res = true;
try
{
std::string sql = "SELECT RDB$RELATION_NAME FROM RDB$RELATIONS WHERE RDB$RELATION_NAME='"
+ TeConvertToUpperCase(table) + "'";
if(!portal->query(sql))
{
throw TeException(UNKNOWN_ERROR_TYPE, "Error on query statement.");
}
if(!portal->fetchRow())
{
res = false;
}
}
catch(TeException& e)
{
errorMessage_ = e.message();
res = false;
}
delete portal;
return res;
}
bool
TeFirebird::columnExist(const string& table, const string& column ,TeAttribute& /*attr*/)
{
TeDatabasePortal* portal = getPortal();
bool res = true;
try
{
std::string sql = "SELECT RDB$FIELD_NAME FROM RDB$RELATION_FIELDS";
sql += " WHERE RDB$RELATION_NAME='" + TeConvertToUpperCase(table) + "'";
sql += " AND RDB$FIELD_NAME='" + TeConvertToUpperCase(column) + "'";
if(!portal->query(sql))
{
throw TeException(UNKNOWN_ERROR_TYPE, "Error on query statement.");
}
if(!portal->fetchRow())
{
res = false;
}
}
catch(TeException& e)
{
errorMessage_ = e.message();
res = false;
}
delete portal;
return res;
}
bool TeFirebird::addColumn (const string& table, TeAttributeRep &rep)
{
string q ="ALTER TABLE " + table +" ADD ";
//string type;
string field = TeGetExtension(rep.name_.c_str());
if(field.empty())
field = rep.name_;
bool complexType = (rep.type_ == TePOINTTYPE) ||
(rep.type_ == TePOINTSETTYPE) ||
(rep.type_ == TeLINE2DTYPE) ||
(rep.type_ == TeLINESETTYPE) ||
(rep.type_ == TePOLYGONTYPE) ||
(rep.type_ == TePOLYGONSETTYPE) ||
(rep.type_ == TeCELLTYPE) ||
(rep.type_ == TeCELLSETTYPE) ||
(rep.type_ == TeRASTERTYPE) ||
(rep.type_ == TeNODETYPE) ||
(rep.type_ == TeNODESETTYPE);
TeAttribute attr;
attr.rep_ = rep;
q += (!complexType) ? field + " " + mapToFirebirdType(attr) : mapToFirebirdType(attr);
if (execute(q))
{
alterTableInfoInMemory(table);
return true;
}
return false;
}
bool
TeFirebird::alterTable(const string& tableName, TeAttributeRep& rep, const string& oldColName)
{
if(!tableExist(tableName))
return false;
string tab;
if(oldColName.empty())
{
tab = " ALTER TABLE " + tableName + " ALTER ";
}
else
{
tab = " ALTER TABLE " + tableName + " ALTER ";
tab += oldColName + " ";
}
bool complexType = (rep.type_ == TePOINTTYPE) ||
(rep.type_ == TePOINTSETTYPE) ||
(rep.type_ == TeLINE2DTYPE) ||
(rep.type_ == TeLINESETTYPE) ||
(rep.type_ == TePOLYGONTYPE) ||
(rep.type_ == TePOLYGONSETTYPE) ||
(rep.type_ == TeCELLTYPE) ||
(rep.type_ == TeCELLSETTYPE) ||
(rep.type_ == TeRASTERTYPE) ||
(rep.type_ == TeNODETYPE) ||
(rep.type_ == TeNODESETTYPE);
if(!complexType)
{
tab += rep.name_ +" ";
}
tab += "TYPE ";
TeAttribute attr;
attr.rep_ = rep;
tab += mapToFirebirdType(attr);
if(!execute(tab))
{
if(errorMessage_.empty())
errorMessage_ = "Error alter table " + tableName + " !";
return false;
}
string tableId;
TeDatabasePortal* portal = getPortal();
string sql = "SELECT table_id FROM te_layer_table WHERE attr_table = '" + tableName + "'";
if(portal->query(sql) && portal->fetchRow())
tableId = portal->getData(0);
delete portal;
if(tableId.empty() == false)
{
if(oldColName.empty() == false) // column name changed
{
// update relation
sql = "UPDATE te_tables_relation SET related_attr = '" + rep.name_ + "'";
sql += " WHERE related_table_id = " + tableId;
sql += " AND related_attr = '" + oldColName + "'";
if(execute(sql) == false)
return false;
sql = "UPDATE te_tables_relation SET external_attr = '" + rep.name_ + "'";
sql += " WHERE external_table_name = '" + tableName + "'";
sql += " AND external_attr = '" + oldColName + "'";
if(execute(sql) == false)
return false;
// update grouping
sql = "UPDATE te_grouping SET grouping_attr = '" + tableName + "." + rep.name_ + "'";
sql += " WHERE grouping_attr = '" + tableName + "." + oldColName + "'";
if(execute(sql) == false)
return false;
}
else // column type changed
{
// delete relation
sql = "DELETE FROM te_tables_relation WHERE (related_table_id = " + tableId;
sql += " AND related_attr = '" + rep.name_ + "')";
sql += " OR (external_table_name = '" + tableName + "'";
sql += " AND external_attr = '" + rep.name_ + "')";
if(execute(sql) == false)
return false;
// delete grouping
TeDatabasePortal* portal = getPortal();
sql = "SELECT theme_id FROM te_grouping WHERE grouping_attr = '" + tableName + "." + oldColName + "'";
if(portal->query(sql) && portal->fetchRow())
{
string themeId = portal->getData(0);
sql = "DELETE FROM te_legend WHERE theme_id = " + themeId + " AND group_id >= 0";
if(execute(sql) == false)
{
delete portal;
return false;
}
}
delete portal;
sql = "DELETE FROM te_grouping";
sql += " WHERE grouping_attr = '" + tableName + "." + oldColName + "'";
if(execute(sql) == false)
return false;
}
}
alterTableInfoInMemory(tableName);
return true;
}
TeDatabasePortal*
TeFirebird::getPortal ()
{
return new TeFirebirdPortal (this);
}
string TeFirebird::getConcatFieldsExpression(const vector<string>& fNamesVec)
{
std::string value;
for(unsigned int i = 0; i < fNamesVec.size(); i++)
{
if(i > 0)
{
value += " || ";
}
value += fNamesVec[i];
}
return value;
}
TeFirebirdPortal::TeFirebirdPortal (TeFirebird* firebird) :
TeDatabasePortal(),
currRow_(0)
{
firebird_ = firebird->getIBPPFirebird();
numRows_ = 0;
numFields_ = 0;
db_ = firebird;
}
TeFirebirdPortal::TeFirebirdPortal ( const TeFirebirdPortal& p) :
TeDatabasePortal(),
currRow_(p.currRow_)
{
firebird_ = p.firebird_;
numRows_ = 0;
numFields_ = 0;
}
TeFirebirdPortal::~TeFirebirdPortal ()
{
freeResult ();
}
string
TeFirebird::escapeSequence(const string& from)
{
int fa = 0;
std::string to = from;
to.insert(0, " ");
std::string::iterator it = to.begin();
while(it != to.end())
{
int f = to.find("'", fa);
if(f > fa)
{
to.insert(f, "'");
fa = f + 2;
}
else
break;
}
to = to.substr(1, to.size() - 1);
return to;
}
bool TeFirebirdPortal::query (const string &q, TeCursorLocation /*l*/, TeCursorType /*t*/, TeCursorEditType e, TeCursorDataType /*dt*/)
{
currRow_ = 0;
try
{
attList_.clear ();
IBPP::TAM tam = (e == TeREADONLY) ? IBPP::amRead : IBPP::amWrite;
transaction_ = IBPP::TransactionFactory(firebird_, tam, IBPP::ilConcurrency, IBPP::lrWait);
transaction_->Start();
result_ = IBPP::StatementFactory(firebird_, transaction_);
result_->Execute(q);
numFields_ = result_->Columns();
query_ = q;
for(int i = 1; i <= numFields_; i++)
{
TeAttribute att;
IBPP::SDT ftype = result_->ColumnType(i);
switch(ftype)
{
case IBPP::sdInteger :
case IBPP::sdLargeint:
att.rep_.type_ = TeINT;
att.rep_.numChar_ = result_->ColumnSize(i);
att.rep_.name_ = result_->ColumnName(i);
break;
case IBPP::sdDouble :
case IBPP::sdFloat :
att.rep_.type_ = TeREAL;
att.rep_.decimals_ = result_->ColumnScale(i);
att.rep_.numChar_ = result_->ColumnSize(i);
break;
case IBPP::sdDate :
case IBPP::sdTime:
case IBPP::sdTimestamp :
att.rep_.type_ = TeDATETIME;
att.dateTimeFormat_ = "YYYYsMMsDDsHHsmmsSS24";
att.dateChronon_ = TeSECOND;
break;
case IBPP::sdSmallint :
att.rep_.type_ = TeBOOLEAN;
break;
case IBPP::sdBlob :
if(result_->ColumnSubtype(i) == 0)
{
att.rep_.type_ = TeBLOB;
}
else
{
att.rep_.type_ = TeSTRING;
}
break;
case IBPP::sdString :
att.rep_.type_ = TeSTRING;
att.rep_.numChar_ = result_->ColumnSize(i);
break;
default:
att.rep_.type_ = TeUNKNOWN;
break;
}
att.rep_.name_ = result_->ColumnAlias(i);
attList_.push_back(att);
}
}
catch(IBPP::SQLException& e)
{
errorMessage_ = e.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e)
{
errorMessage_ = e.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebirdPortal::fetchRow ()
{
bool res = true;
try
{
res = result_->Fetch();
if(res)
{
numRows_++;
currRow_++;
}
}
catch(IBPP::LogicException& e)
{
errorMessage_ = e.ErrorMessage();
res = false;
}
return res;
}
bool
TeFirebirdPortal::fetchRow (int i)
{
bool res = true;
if(query_.empty())
{
return false;
}
if(i == currRow_+1)
{
res = fetchRow();
currRow_++;
}
else
{
try
{
if(!transaction_->Started())
{
transaction_->Start();
}
int pos = query_.find("SELECT");
if(pos < 0)
{
return false;
}
std::string sql = "SELECT SKIP " + Te2String(i) + query_.substr(pos + 6);
result_ = IBPP::StatementFactory(firebird_, transaction_);
result_->Execute(sql);
numFields_ = result_->Columns();
res = fetchRow();
if(res)
{
currRow_ = i;
}
}
catch(IBPP::LogicException& e)
{
errorMessage_ = e.ErrorMessage();
res = false;
}
catch(IBPP::SQLException& e)
{
errorMessage_ = e.ErrorMessage();
res = false;
}
}
return res;
}
void TeFirebirdPortal::freeResult ()
{
numRows_ = 0;
numFields_= 0;
result_ = IBPP::StatementFactory(firebird_, transaction_);
}
bool TeFirebird::insertProjection (TeProjection *proj)
{
TeProjectionParams par = proj->params();
int id = getLastGeneratedAutoNumber("te_projection");
string insert = "INSERT INTO te_projection (projection_id, name, long0, lat0,";
insert += " offx, offy, stlat1, stlat2, unit, scale, hemis, datum, ";
insert += " radius, flattening, dx , dy, dz ) VALUES ( ";
insert += Te2String(proj->id());
insert += ", '" + escapeSequence(par.name) + "'";
insert += ", " + Te2String(par.lon0*TeCRD,10);
insert += ", " + Te2String(par.lat0*TeCRD,10);
insert += ", " + Te2String(par.offx,10);
insert += ", " + Te2String(par.offy,10);
insert += ", " + Te2String(par.stlat1*TeCRD,10);
insert += ", " + Te2String(par.stlat2*TeCRD,10);
insert += ", '" + escapeSequence(par.units) + "'";
insert += ", " + Te2String(par.scale,10);
insert += ", " + Te2String(par.hemisphere);
insert += ", '" + escapeSequence(par.datum.name()) + "'";
insert += ", " + Te2String(par.datum.radius(),10);
insert += ", " + Te2String(par.datum.flattening(),10);
insert += ", " + Te2String(par.datum.xShift(),10);
insert += ", " + Te2String(par.datum.yShift(),10);
insert += ", " + Te2String(par.datum.zShift(),10);
insert += ")";
if (!execute(insert))
{
return false;
}
proj->id(id);
return true;
}
bool TeFirebird::updateProjection (TeProjection *proj)
{
if (proj->id() <= 0)
return false;
string sql;
sql = "UPDATE te_projection SET ";
sql += "name='" + proj->name() + "',";
sql += " long0=" + Te2String(proj->params().lon0*TeCRD)+ ",";
sql += " lat0=" + Te2String(proj->params().lat0*TeCRD) + ",";
sql += " offx=" +Te2String(proj->params().offx) + ",";
sql += " offy=" +Te2String(proj->params().offy) + ",";
sql += " stlat1="+ Te2String(proj->params().stlat1*TeCRD) + ",";
sql += " stlat2=" +Te2String(proj->params().stlat2*TeCRD) + ",";
sql += " unit='" + proj->params().units + "',";
sql += " scale=" + Te2String(proj->params().scale) + ",";
sql += " hemis=" + Te2String(proj->params().hemisphere) + ",";
sql += " datum='" + proj->datum().name() + "',";
sql += " radius=" + Te2String(proj->datum().radius()) + ",";
sql += " flattening=" + Te2String(proj->datum().flattening()) + ",";
sql += " dx=" + Te2String(proj->datum().xShift()) + ",";
sql += " dy=" + Te2String(proj->datum().yShift()) + ",";
sql += " dz=" + Te2String(proj->datum().zShift()) ;
sql += " WHERE projection_id = " + Te2String(proj->id());
return execute(sql);
}
bool
TeFirebird::insertView (TeView *view)
{
std::string ins;
int id = getLastGeneratedAutoNumber("te_view");
TeProjection* proj = view->projection();
if ( !proj || !insertProjection(proj))
{
errorMessage_ = "N�o � poss�vel inserir vista sem proje��o";
return false;
}
ins = "INSERT INTO te_view (view_id, projection_id, name, user_name, visibility)";
ins += " VALUES (";
ins += Te2String(view->id());
ins += ", " + Te2String(proj->id());
ins += ", '" + escapeSequence(view->name ()) + "'";
ins += ", '" + escapeSequence(view->user ()) + "'";
ins += ", " + Te2String((int)view->isVisible());
ins += " )";
if(!execute (ins))
{
if(errorMessage_.empty())
errorMessage_ = "Error inserting in the table te_view!";
return false;
}
int size = view->size();
for (int th=0; th<size; th++)
{
TeViewNode* node = view->get(th);
if (node->type() == TeTHEME)
{
TeTheme *theme = (TeTheme*) node;
insertTheme (theme);
}
else
{
TeViewTree* tree = (TeViewTree*)node;
insertViewTree (tree);
}
}
view->id(id);
// Insert view in the view map
viewMap()[view->id()] = view;
return true;
}
bool
TeFirebird::insertViewTree (TeViewTree *tree)
{
int id = getLastGeneratedAutoNumber("te_theme");
string save;
save = "INSERT INTO te_theme (name,node_type,view_id,parent_id,priority) VALUES('";
save += tree->name() + "'," + Te2String((int)tree->type()) + "," + Te2String(tree->view()) +
"," + Te2String(tree->parentId()) + "," + Te2String(tree->priority()) + ")";
if (!execute(save))
return false;
tree->id(id);
return true;
}
bool
TeFirebird::insertTheme (TeAbstractTheme *tem)
{
string save;
save = "INSERT INTO te_theme ";
save += "(layer_id, view_id, name, parent_id, priority, node_type, min_scale, max_scale, ";
save += "generate_attribute_where, generate_spatial_where, generate_temporal_where, ";
save += "collection_table, visible_rep, enable_visibility, lower_x, lower_y, upper_x, upper_y, creation_time) ";
save += " VALUES(";
if(tem->type()==TeTHEME)
save += Te2String(static_cast<TeTheme*>(tem)->layerId()) +", " ;
else
save += " NULL, ";
save += Te2String(tem->view()) +", ";
save += "'" + escapeSequence(tem->name()) + "', ";
save += Te2String(tem->parentId()) +", ";
save += Te2String(tem->priority()) +", ";
save += Te2String(tem->type()) +", ";
save += Te2String(tem->minScale()) +", ";
save += Te2String(tem->maxScale()) +", ";
save += "'" + escapeSequence(tem->attributeRest()) + "', ";
save += "'" + escapeSequence(tem->spatialRest()) + "', ";
save += "'" + escapeSequence(tem->temporalRest()) + "', ";
if(tem->type()==TeTHEME)
save += " '" + escapeSequence(static_cast<TeTheme*>(tem)->collectionTable()) + "', ";
else
save += " '', ";
save += Te2String(tem->visibleRep()) +", ";
save += Te2String(tem->visibility()) +", ";
save += Te2String(tem->box().x1(), 10) +", ";
save += Te2String(tem->box().y1(), 10) +", ";
save += Te2String(tem->box().x2(), 10) +", ";
save += Te2String(tem->box().y2(), 10) +", ";
TeTime creationTime = tem->getCreationTime();
save += getSQLTime(creationTime);
save += " ) ";
int id = getLastGeneratedAutoNumber("te_theme");
if (!execute(save))
return false;
tem->id(id);
if((tem->type()==TeTHEME || tem->type()==TeEXTERNALTHEME)&& static_cast<TeTheme*>(tem)->collectionTable().empty())
{
string colTab = "te_collection_" + Te2String(tem->id());
static_cast<TeTheme*>(tem)->collectionTable(colTab);
save = "UPDATE te_theme SET collection_table='" + colTab + "' WHERE theme_id=" ;
save += Te2String(tem->id());
execute(save);
}
if(tem->parentId() == 0)
{
std::string sql = "UPDATE te_theme SET";
sql += " parent_id = " + Te2String(tem->id());
sql += " WHERE theme_id = ";
sql += Te2String(tem->id());
tem->parentId(tem->id());
if(!this->execute(sql))
return false;
}
bool status;
// insert grouping
int numSlices = 0;
if(tem->grouping().groupMode_ != TeNoGrouping)
{
if(!insertGrouping (tem->id(), tem->grouping()))
return false;
numSlices = tem->grouping().groupNumSlices_;
}
tem->outOfCollectionLegend().group(-1);
tem->outOfCollectionLegend().theme(tem->id());
status = insertLegend (&(tem->outOfCollectionLegend()));
if (!status)
return status;
tem->withoutDataConnectionLegend().group(-2);
tem->withoutDataConnectionLegend().theme(tem->id());
status = insertLegend (&(tem->withoutDataConnectionLegend()));
if (!status)
return status;
tem->defaultLegend().group(-3);
tem->defaultLegend().theme(tem->id());
status = insertLegend (&(tem->defaultLegend()));
if (!status)
return status;
tem->pointingLegend().group(-4);
tem->pointingLegend().theme(tem->id());
status = insertLegend (&(tem->pointingLegend()));
if (!status)
return status;
tem->queryLegend().group(-5);
tem->queryLegend().theme(tem->id());
status = insertLegend (&(tem->queryLegend()));
if (!status)
return status;
tem->queryAndPointingLegend().group(-6);
tem->queryAndPointingLegend().theme(tem->id());
status = insertLegend (&(tem->queryAndPointingLegend()));
if (!status)
return status;
for (int i = 0; i < numSlices; i++)
{
tem->legend()[i].group(i);
tem->legend()[i].theme(tem->id());
status = insertLegend (&(tem->legend()[i]));
if (!status)
return status;
}
if (!status)
return status;
//insert metadata theme
if(!tem->saveMetadata(this))
return false;
themeMap()[tem->id()] = tem;
if(tem->type()==TeTHEME && !updateThemeTable(static_cast<TeTheme*>(tem)))
return false;
return true;
}
bool
TeFirebird::insertThemeGroup (TeViewTree* tree)
{
string save;
save = "INSERT INTO te_theme ";
save += "(name,parent_id,node_type,view_id,priority) ";
save += " VALUES ('" + tree->name() + "',1,1, ";
save += Te2String(tree->view()) +", ";
save += Te2String(tree->priority()) +") ";
int id = getLastGeneratedAutoNumber("te_theme");
if (!execute(save))
return false;
tree->id(id);
return true;
}
bool
TeFirebird::generateLabelPositions (TeTheme *theme, const std::string& objectId)
{
std::string collTable = theme->collectionTable();
if((collTable.empty()) || (!tableExist(collTable)))
{
return false;
}
if (theme->layer()->hasGeometry(TeLINES))
{
generateLablesForPolygonal(firebird_, theme, TeLINES, errorMessage_, objectId);
}
if (theme->layer()->hasGeometry(TePOINTS))
{
std::string geomTable = theme->layer()->tableName(TePOINTS),
query = "SELECT object_id, x, y FROM " + geomTable;
TeDatabasePortal* portal = theme->layer()->database()->getPortal();
if(!portal->query(query))
{
throw TeException(UNKNOWN_ERROR_TYPE, "Error on query:\n" + portal->errorMessage());
}
if(!portal->fetchRow())
{
return true;
}
IBPP::Transaction tr = IBPP::TransactionFactory(firebird_);
try
{
query = "UPDATE " + collTable + " SET label_x=?, label_y=? WHERE c_object_id=?";
if(!objectId.empty())
{
query += " AND c_object_id=?";
}
tr->Start();
IBPP::Statement st = IBPP::StatementFactory(firebird_, tr);
st->Prepare(query);
do
{
double x = portal->getDouble(1),
y = portal->getDouble(2);
std::string oId = portal->getData(0);
st->Set(1, x);
st->Set(2, y);
st->Set(3, oId);
if(!objectId.empty())
{
st->Set(4, objectId);
}
st->Execute();
} while(portal->fetchRow());
tr->Commit();
delete portal;
}
catch(IBPP::SQLException& e)
{
tr->Rollback();
errorMessage_ = e.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e)
{
tr->Rollback();
errorMessage_ = e.ErrorMessage();
return false;
}
return true;
}
if (theme->layer()->hasGeometry(TePOLYGONS))
{
return generateLablesForPolygonal(firebird_, theme, TePOLYGONS, errorMessage_, objectId);
}
if(theme->layer()->hasGeometry(TeCELLS))
{
return generateLablesForPolygonal(firebird_, theme, TeCELLS, errorMessage_, objectId);
}
return true;
}
bool TeFirebird::layerExist (string layerName)
{
if(layerName.size() > 31)
{
layerName.erase(30, layerName.size());
}
return TeDatabase::layerExist(layerName);
}
bool
TeFirebird::insertLayer (TeLayer* layer)
{
std::string ins;
char value[1024];
TeProjection* proj = layer->projection();
if (!proj || !insertProjection(proj))
{
errorMessage_ = "N�o � poss�vel inserir layer sem proje��o";
return false;
}
if(layer->name().size() > 31)
{
std::string name = layer->name();
name.erase(30, name.size());
layer->name(name);
}
ins = "INSERT INTO te_layer (projection_id, name ";
ins += ", lower_x, lower_y, upper_x, upper_y, edition_time) ";
ins += " VALUES ( ";
ins += Te2String(proj->id());
ins += ", '" + escapeSequence(layer->name()) + "'";
sprintf(value,",%g,%g,%g,%g",layer->box().x1(),layer->box().y1(),layer->box().x2(),layer->box().y2());
ins +=value;
TeTime editionTime = layer->getEditionTime();
ins += ", " + getSQLTime(editionTime) + ")";
int id = getLastGeneratedAutoNumber("te_layer");
if(!execute(ins))
{
if(errorMessage_.empty())
errorMessage_ = "Error inserting in the table te_layer!";
return false;
}
layer->id(id);
layerMap()[layer->id()] = layer;
return true;
}
bool TeFirebird::updateLayer(TeLayer *layer)
{
if (!layer)
return false;
if (layer->projection())
updateProjection(layer->projection());
string sql;
sql = "UPDATE te_layer SET ";
sql += "name = '" + layer->name() + "' ";
if (layer->box().isValid())
{
sql += ", lower_x = " + Te2String(layer->box().x1()) + " ";
sql += ", lower_y = " + Te2String(layer->box().y1()) + " ";
sql += ", upper_x = " + Te2String(layer->box().x2()) + " ";
sql += ", upper_y = " + Te2String(layer->box().y2()) + " ";
}else
{
sql += ", lower_x = " + Te2String(layer->box().x1()) + " ";
sql += ", lower_y = " + Te2String(layer->box().y1()) + " ";
sql += ", upper_x = " + Te2String(layer->box().x2()) + " ";
sql += ", upper_y = " + Te2String(layer->box().y2()) + " ";
}
if(layer->getEditionTime().isValid())
{
TeTime editionTime = layer->getEditionTime();
sql += ", edition_time = " + this->getSQLTime(editionTime);
}
sql += " WHERE layer_id = " + Te2String(layer->id());
return (this->execute (sql));
}
bool TeFirebird::insertProject (TeProject* project)
{
if (!project)
return false;
string save = "INSERT INTO te_project (project_id, name, description, current_view) VALUES(0,";
save += "'" + project->name() + "', ";
save += "'" + project->description() + "', ";
save += Te2String(project->getCurrentViewId())+ ")";
int id = getLastGeneratedAutoNumber("te_project");
// if layer insertion fails remove projection
if (!execute (save))
return false;
project->setId(id);
projectMap()[project->id()] = project;
for (unsigned int i=0; i<project->getViewVector().size(); i++)
insertProjectViewRel(project->id(), project->getViewVector()[i]);
return true;
}
bool TeFirebird::updateRepresentation (int layerId, TeRepresentation& rep)
{
if (layerId <= 0)
return false;
string sql;
sql = "UPDATE te_representation SET ";
sql += " lower_x= " + Te2String(rep.box_.x1());
sql += ", lower_y= " + Te2String(rep.box_.y1());
sql += ", upper_x= " + Te2String(rep.box_.x2());
sql += ", upper_y= " + Te2String(rep.box_.y2());
sql += ", description= '" + rep.description_ + "'";
sql += ", res_x= " + Te2String(rep.resX_);
sql += ", res_y= " + Te2String(rep.resY_);
sql += ", num_cols=" + Te2String(rep.nCols_);
sql += ", num_rows=" + Te2String(rep.nLins_);
if (rep.geomRep_ != TeTEXT)
sql += ", geom_table='" + rep.tableName_ + "'";
sql += " WHERE layer_id=" + Te2String(layerId);
sql += " AND geom_type= " + Te2String(rep.geomRep_);
if (rep.geomRep_ == TeTEXT)
sql += " AND geom_table='" + rep.tableName_ + "'";
return execute(sql);
}
bool TeFirebird::insertRasterGeometry(const string& tableName, TeRasterParams& par, const string& objectId)
{
if (tableName.empty())
return false;
string objId;
if (objectId.empty())
objId = "O1";
else
objId = objectId;
//------ this check is made for compatibility reasons with old versions of TerraLib databases
TeAttributeRep attrRep;
attrRep.name_ = "tiling_type";
attrRep.type_ = TeINT;
TeAttribute att;
if(!columnExist(tableName, attrRep.name_,att))
{
addColumn (tableName, attrRep);
string sql = "UPDATE " + tableName + " SET tiling_type = " + Te2String(static_cast<int>(TeRasterParams::TeExpansible));
this->execute(sql);
}
//------
// finds the name of the raster geometry table
TeDatabasePortal* portal = getPortal();
//if(!portal)
// return false;
TeBox box = par.boundingBox();
string ins = "INSERT INTO " + tableName + " (object_id, raster_table, lut_table, ";
ins += "res_x, res_y, num_bands, num_cols, num_rows, block_height, block_width, ";
ins += "lower_x, lower_y, upper_x, upper_y, tiling_type) ";
ins += " VALUES ('" + objId + "', '" + par.fileName_+ "', '" + par.lutName_ + "', ";
ins += Te2String(par.resx_) + ", " + Te2String(par.resy_) + ", ";
ins += Te2String(par.nBands()) + ", " + Te2String(par.ncols_) + ", " + Te2String(par.nlines_) + ", ";
ins += Te2String(par.blockHeight_) + ", " + Te2String(par.blockWidth_) + ", ";
ins += Te2String(box.x1_) +", " + Te2String(box.y1_) + ", ";
ins += Te2String(box.x2_) +", " + Te2String(box.y2_) + ", ";
ins += Te2String(par.tiling_type_) + ")";
if (!this->execute(ins))
{
delete portal;
return false;
}
// save the pallete associated to the raster
// if it doesn?t exist yet
if (par.photometric_[0] == TeRasterParams::TePallete && !par.lutName_.empty())
{
if (!this->tableExist(par.lutName_))
{
if (this->createLUTTable(par.lutName_))
{
for (unsigned int i=0; i<par.lutb_.size(); i++)
{
string sql = "INSERT INTO " + par.lutName_ + " VALUES(";
sql += Te2String(i) + ", ";
sql += Te2String(par.lutr_[i]) + ", ";
sql += Te2String(par.lutg_[i]) + ", ";
sql += Te2String(par.lutb_[i]) + ", '";
sql += par.lutClassName_[i] + "')";
this->execute(sql);
}
}
}
}
ins = "SELECT geom_id FROM " + tableName + " WHERE object_id='" + objId + "'";
ins += " AND raster_table='" + par.fileName_+ "'";
if(!portal->query(ins) || !portal->fetchRow())
{
delete portal;
return false;
}
int geomId = atoi(portal->getData(0));
delete portal;
string metadataTableName = tableName+"_metadata";
insertRasterMetadata(metadataTableName, geomId,par);
return true;
}
bool TeFirebird::updateRasterRepresentation(int layerId, TeRasterParams& par, const string& objectId)
{
TeDatabasePortal* portal = this->getPortal();
if(!portal)
return false;
string sql = "SELECT repres_id, lower_x, lower_y, upper_x, upper_y, geom_table ";
sql += " FROM te_representation WHERE layer_id= " + Te2String(layerId);
sql += " AND geom_type= " + Te2String(TeRASTER);
if(!portal->query(sql) || !portal->fetchRow())
{
delete portal;
return false;
}
TeBox box (portal->getDouble(1),portal->getDouble(2),
portal->getDouble(3),portal->getDouble(4));
int represId = atoi(portal->getData(0));
string rasterrep = portal->getData(5);
portal->freeResult();
updateBox(box,par.boundingBox());
sql = "UPDATE te_representation SET lower_x = " + Te2String(box.x1_);
sql += ", lower_y = " + Te2String(box.y1_) + ", upper_x = " + Te2String(box.x2_);
sql += ", upper_y = " + Te2String(box.y2_);
if(par.date_.isValid())
{
std::string sqlTime = getSQLTime(par.date_);
if(!sqlTime.empty())
{
sql += ", initial_time = " + sqlTime;
sql += ", final_time = " + sqlTime;
}
}
sql += " WHERE repres_id=" + Te2String(represId);
if(!execute(sql))
{
delete portal;
return false;
}
string objId;
if (objectId.empty())
objId = "O1";
else
objId = objectId;
box = par.boundingBox();
sql = "UPDATE " + rasterrep + " SET lut_table ='" + par.lutName_ + "'";
sql += ", res_x= " + Te2String(par.resx_) + ", res_y=" + Te2String(par.resy_);
sql += ", num_bands=" + Te2String(par.nBands()) + ", num_cols=" + Te2String(par.ncols_);
sql += ", num_rows=" + Te2String(par.nlines_) + ", block_height=" + Te2String(par.blockHeight_);
sql += ", block_width= " + Te2String(par.blockWidth_) + ", lower_x = " + Te2String(box.x1_);
sql += ", lower_y = " + Te2String(box.y1_) + ", upper_x = " + Te2String(box.x2_);
sql += ", upper_y = " + Te2String(box.y2_);
sql += " WHERE object_id='" + objId + "' AND raster_table='" + par.fileName_ + "'";
if (!this->execute(sql))
{
delete portal;
return false;
}
sql = "SELECT geom_id FROM " + rasterrep + " WHERE object_id='" + objId + "'";
sql+= " AND raster_table='" + par.fileName_+ "'";
if(!portal->query(sql) || !portal->fetchRow())
{
delete portal;
return false;
}
// save the pallete associated to the raster
// if it doesn�t exist yet
if (par.photometric_[0] == TeRasterParams::TePallete && !par.lutName_.empty())
{
if (!this->tableExist(par.lutName_))
{
if (this->createLUTTable(par.lutName_))
{
for (unsigned int i=0; i<par.lutb_.size(); i++)
{
string sql = "INSERT INTO " + par.lutName_ + " VALUES(";
sql += Te2String(i) + ", ";
sql += Te2String(par.lutr_[i]) + ", ";
sql += Te2String(par.lutg_[i]) + ", ";
sql += Te2String(par.lutb_[i]) + ", '";
sql += par.lutClassName_[i] + "')";
if (!this->execute(sql) )
{
delete portal;
return false;
}
}
}
}
}
int geomId = atoi(portal->getData(0));
delete portal;
string metadatatabel = rasterrep + "_metadata";
return updateRasterMetadata(metadatatabel,geomId,par);
}
bool TeFirebird::insertLegend (TeLegendEntry *legend)
{
// if(legend->id())
string ins = "INSERT INTO te_legend (legend_id, theme_id, group_id, ";
ins += " num_objs, lower_value, upper_value, label) VALUES (0";
// ins += Te2String(legend->id());
ins += ", " + Te2String(legend->theme());
ins += ", " + Te2String(legend->group());
ins += ", " + Te2String(legend->count());
ins += ", '" + escapeSequence(legend->from()) + "'";
ins += ", '" + escapeSequence(legend->to()) + "'";
ins += ", '" + escapeSequence(legend->label()) + "'";
ins += ")";
int id = getLastGeneratedAutoNumber("te_legend");
if (!execute(ins))
{
if(errorMessage_.empty())
errorMessage_ = "Error inserting in the table te_legend!";
return false;
}
legend->id(id);
legendMap()[legend->id()] = legend;
return insertVisual(legend);
}
bool
TeFirebird::insertRepresentation (int layerId, TeRepresentation& rep)
{
if (layerId <= 0)
return false;
string ins;
try
{
char value[1024];
ins = " INSERT INTO te_representation (repres_id, layer_id, geom_type, geom_table, ";
ins += " description, lower_x, lower_y, upper_x, upper_y, res_x, res_y, num_cols, ";
ins += " num_rows) VALUES (";
ins += Te2String(rep.id_);
ins += ", " + Te2String(layerId);
ins += ", " + Te2String(static_cast<int>(rep.geomRep_));
ins += ", '" + escapeSequence(rep.tableName_) + "'";
ins += ", '" + escapeSequence(rep.description_) + "'";
sprintf(value,",%g,%g,%g,%g",rep.box_.x1(),rep.box_.y1(),rep.box_.x2(),rep.box_.y2());
ins += value;
ins += ", " + Te2String(rep.resX_,10);
ins += ", " + Te2String(rep.resY_,10);
ins += ", " + Te2String(rep.nCols_);
ins += ", " + Te2String(rep.nLins_);
ins += ")";
int id = getLastGeneratedAutoNumber("te_representation");
if(!execute(ins))
{
if(errorMessage_.empty())
errorMessage_ = "Error inserting in the table te_representation!";
return false;
}
rep.id_ = id;
}
catch(IBPP::SQLException& e)
{
errorMessage_ = "Error inserting in the table te_representation.\n";
errorMessage_ += e.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e)
{
errorMessage_ = "Error inserting in the table te_representation.\n";
errorMessage_ += e.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebird::insertRelationInfo(const int tableId, const string& tField,
const string& eTable, const string& eField, int& relId)
{
//// check if relation already exists
TeDatabasePortal* portal = getPortal();
relId = -1;
string sel = "SELECT relation_id FROM te_tables_relation WHERE";
sel += " related_table_id = " + Te2String(tableId);
sel += " AND related_attr = '" + tField + "'";
sel += " AND external_table_name = '" + eTable + "'";
sel += " AND external_attr = '" + eField + "'";
if (!portal->query(sel))
{
delete portal;
return false;
}
if (portal->fetchRow())
{
relId = atoi(portal->getData(0));
delete portal;
return true;
}
delete portal;
string sql = "INSERT INTO te_tables_relation(related_table_id, related_attr, external_table_name, external_attr) ";
sql += " VALUES( ";
sql += Te2String(tableId);
sql += ",'" + tField + "'";
sql += ",'" + eTable + "'";
sql += ",'" + eField + "')";
relId = getLastGeneratedAutoNumber("te_tables_relation");
if (!execute(sql))
return false;
return true;
}
bool
TeFirebird::insertTable(TeTable &table)
{
string tableName = table.name();
int size = table.size();
TeAttributeList att = table.attributeList();
TeAttributeList::iterator it = att.begin();
TeAttributeList::iterator itEnd = att.end();
TeTableRow row;
int realMaxSize = 15; //limitacao do firebird. 18 digitos, sem contar o separador decimal
if(firebird_->Dialect() == 3)
{
realMaxSize = 18;
}
if (!beginTransaction())
return false;
int i;
unsigned int j;
for ( i = 0; i < size; i++ )
{
row = table[i];
it = att.begin();
string attrs;
string values;
j = 1;
unsigned int jj = 0;
while ( it != itEnd )
{
TeAttributeRep rep = (*it).rep_;
if ((jj>=row.size()) || row[jj].empty() || (*it).rep_.isAutoNumber_)
{
++it;
j++;
jj++;
continue;
}
if (!values.empty())
{
attrs += ", ";
values += ", ";
}
attrs += (*it).rep_.name_;
std::string strValue,
temp_dt;
TeTime t;
int maxSizeToUse = realMaxSize;
switch ((*it).rep_.type_)
{
case TeSTRING:
values += "'"+ escapeSequence( row[jj] ) +"'";
break;
case TeREAL:
strValue = row[jj];
replace(strValue.begin(), strValue.end(), ',', '.');
if((int)strValue.size() > realMaxSize)
{
basic_string <char>::size_type index;
if ( (index=strValue.find(".")) != string::npos )
{
maxSizeToUse += 1;// caso tenha separador decinal, podemos usar mais um caractere
}
strValue = strValue.substr(0, maxSizeToUse);
}
else
{
strValue = row[jj];
}
values += strValue;
break;
case TeINT:
values += row[jj];
break;
case TeDATETIME:
temp_dt = string(row[jj].c_str());
t = TeTime(temp_dt, (*it).dateChronon_, (*it).dateTimeFormat_, (*it).dateSeparator_, (*it).timeSeparator_, (*it).indicatorPM_);
values += getSQLTime(t);
break;
case TeCHARACTER:
values += "'" + escapeSequence(row[jj]) + "'";
break;
case TeBOOLEAN:
{
std::string value = "0";
if(row[jj] == "1" || TeConvertToLowerCase(row[jj]) == "t" || TeConvertToLowerCase(row[jj]) == "true")
{
value = "1";
}
values += value;
}
break;
case TeBLOB:
values += "'" + escapeSequence(row[jj]) + "'";
break;
default:
values += "'"+ escapeSequence(row[jj]) +"'";
}
++it;
j++;
jj++;
}
if (values.empty())
continue;
string q = "INSERT INTO "+tableName + " ("+ attrs+") " + " VALUES ("+values+") ";
if (!execute(q))
continue;
}
if (!commitTransaction())
{
rollbackTransaction();
return false;
}
return true;
}
bool
TeFirebird::updateTable(TeTable &table)
{
TeAttributeList& att = table.attributeList();
unsigned int i;
string uniqueVal;
bool isUniqueValString = false;
if (!beginTransaction())
return false;
string uniqueName = table.uniqueName(); // primary key explicitly defined or
if (table.uniqueName().empty()) // check in the attribute list
{
for (i=0; i<att.size(); ++i)
if (att[i].rep_.isPrimaryKey_)
{
uniqueName = att[i].rep_.name_;
table.setUniqueName(uniqueName);
break;
}
}
TeAttributeList::iterator it;
TeTableRow row;
unsigned int j;
bool useComma = false;
for (i = 0; i < table.size(); i++ )
{
row = table[i];
it = att.begin();
string q;
j = 1;
int jj = 0;
while ( it != att.end() )
{
if (uniqueName != (*it).rep_.name_)
{
if ((*it).rep_.isAutoNumber_)
{
++it;
j++;
jj++;
continue;
}
if(useComma == true)
{
q += ", ";
}
else
{
useComma = true;
}
q += (*it).rep_.name_ + " = ";
if(row[jj].empty())
{
q += " null";
++it;
j++;
jj++;
continue;
}
switch ((*it).rep_.type_)
{
case TeSTRING:
q += "'"+escapeSequence(row[jj])+"'";
break;
case TeREAL:
{
std::string value = row[jj];
replace(value.begin(), value.end(), ',', '.');
q += value;
}
break;
case TeINT:
q += row[jj];
break;
case TeDATETIME:
{
const string temp_dt = string(row[jj].c_str());
TeTime t(temp_dt, (*it).dateChronon_, (*it).dateTimeFormat_, (*it).dateSeparator_, (*it).timeSeparator_, (*it).indicatorPM_);
q += this->getSQLTime(t);
}
break;
case TeCHARACTER:
q += "'" + escapeSequence(row[jj]) + "'";
break;
case TeBLOB:
q += "'" + escapeSequence(row[jj]) + "'";
break;
default:
q += "'"+escapeSequence(row[jj])+"'";
break;
}
}
else
{
uniqueVal = row[jj];
isUniqueValString = ((*it).rep_.type_ == TeSTRING);
}
++it;
j++;
jj++;
}
if (q.empty())
continue;
if (!uniqueName.empty() && !uniqueVal.empty())
{
if(isUniqueValString)
q += " WHERE " + uniqueName + " = '" + uniqueVal +"'";
else
q += " WHERE " + uniqueName + " = " + uniqueVal;
}
string sql = "UPDATE "+ table.name() + " SET " + q;
if (!execute(sql))
{
rollbackTransaction();
return false;
}
}
if (!commitTransaction())
{
rollbackTransaction();
return false;
}
return true;
}
bool
TeFirebird::insertTableInfo (int layerId, TeTable &table, const string& user)
{
string sql;
sql = "INSERT INTO te_layer_table (unique_id, attr_link,attr_initial_time, attr_final_time, attr_time_unit,attr_table_type, ";
sql += " user_name, attr_table ";
if (layerId > 0)
sql += ",layer_id";
sql += ") VALUES( ";
sql += "'" + table.uniqueName() + "', ";
sql += "'" + table.linkName() + "', ";
sql += "'" + table.attInitialTime() + "', ";
sql += "'" + table.attFinalTime() + "', ";
sql += "" + Te2String(table.attTimeUnit()) + ", ";
sql += ""+ Te2String(table.tableType()) + ", ";
sql += "'" + user + "','" + table.name() +"'";
if (layerId > 0)
sql += ", " + Te2String(layerId) ;
sql += ")";
int id = getLastGeneratedAutoNumber("te_layer_table");
if (!execute(sql))
return false;
table.setId(id);
return true;
}
bool
TeFirebird::updateTheme (TeAbstractTheme *theme)
{
string sql;
if (theme->id() <= 0 ) // theme doesn?t exist in the database yet
{
return this->insertTheme(theme);
}
// update theme metadata
sql = "UPDATE te_theme SET ";
if(theme->type()==TeTHEME)
{
sql += " layer_id=" + Te2String (static_cast<TeTheme*>(theme)->layerId());
sql += ", ";
}
sql += " view_id=" + Te2String (theme->view());
sql += ", name='" + escapeSequence(theme->name())+"'";
sql += ", parent_id=" + Te2String (theme->parentId());
sql += ", priority=" + Te2String (theme->priority());
sql += ", node_type=" + Te2String (theme->type());
sql += ", min_scale=" + Te2String (theme->minScale());
sql += ", max_scale=" + Te2String (theme->maxScale());
sql += ", generate_attribute_where='" + escapeSequence(theme->attributeRest())+"'";
sql += ", generate_spatial_where='" + escapeSequence(theme->spatialRest())+"'";
sql += ", generate_temporal_where='" + escapeSequence(theme->temporalRest())+"'";
if(theme->type()==TeTHEME || theme->type()==TeEXTERNALTHEME )
sql += ", collection_table='" + static_cast<TeTheme*>(theme)->collectionTable() + "'";
sql += ", visible_rep= " + Te2String(theme->visibleRep ());
sql += ", enable_visibility= " + Te2String(theme->visibility());
sql += ", lower_x = " + Te2String(theme->box().x1());
sql += ", lower_y = " + Te2String(theme->box().y1());
sql += ", upper_x = " + Te2String(theme->box().x2());
sql += ", upper_y = " + Te2String(theme->box().y2());
if(theme->getCreationTime().isValid())
{
TeTime creationTime = theme->getCreationTime();
sql += ", creation_time = " + this->getSQLTime(creationTime);
}
sql += " WHERE theme_id=" + Te2String (theme->id());
if (!this->execute (sql))
return false;
//delete grouping
sql = "DELETE FROM te_grouping WHERE theme_id= "+ Te2String(theme->id());
this->execute (sql);
if(theme->grouping().groupMode_ != TeNoGrouping)
{
if(!insertGrouping(theme->id(), theme->grouping()))
return false;
}
// update each of its legends
bool status = true;
if(theme->legend().size() == 0)
{
if(!deleteLegend(theme->id()))
return false;
}
else
{
status = updateLegend(theme->legend());
if (!status)
return status;
}
status = updateLegend(&(theme->withoutDataConnectionLegend()));
if (!status)
return status;
status = updateLegend(&(theme->outOfCollectionLegend()));
if (!status)
return status;
status = updateLegend(&(theme->defaultLegend()));
if (!status)
return status;
status = updateLegend(&(theme->pointingLegend()));
if (!status)
return status;
status = updateLegend(&(theme->queryLegend()));
if (!status)
return status;
status = updateLegend(&(theme->queryAndPointingLegend()));
if (!status)
return status;
//insert metadata theme
if(!theme->saveMetadata(this))
return false;
// theme tables
if(theme->type()==TeTHEME && !updateThemeTable(static_cast<TeTheme*>(theme)))
return false;
return true;
}
bool
TeFirebird::insertThemeTable (int themeId, int tableId, int relationId, int tableOrder)
{
string relId;
if (relationId > 0)
relId = Te2String(relationId);
else
relId = "NULL";
string sql = "INSERT INTO te_theme_table VALUES (0,";
sql += Te2String(themeId) + "," + Te2String(tableId) + ",";
sql += relId + "," + Te2String(tableOrder) + ")";
if (!execute(sql))
return false;
return true;
}
bool
TeFirebird::insertPolygon (const string& table, TePolygon &poly )
{
try
{
IBPP::Blob blob = IBPP::BlobFactory(firebird_, transaction_);
// insert data
std::string ins = "INSERT INTO " + table + " ( ";
ins += "object_id, num_coords, num_holes, ";
ins += " parent_id, lower_x, lower_y, upper_x, upper_y, ";
ins += " ext_max, spatial_data) VALUES (?,?,?,?,?,?,?,?,?,?)";
IBPP::Statement st = IBPP::StatementFactory(firebird_, transaction_, ins);
st->Prepare(ins);
int polyGeomId = -1;
for(unsigned int i=0; i<poly.size(); i++)
{
string obId = escapeSequence(poly.objectId());
TeBox b = poly.box();
saveLineInBlob(blob, poly[i]);
int geomId = getLastGeneratedAutoNumber(table);
poly[i].geomId(geomId);
if(i == 0)
{
polyGeomId = geomId;
}
st->Set(1,obId);
st->Set(2, (int)poly[i].size());
st->Set(3, (i != 0) ? 0 : (int)poly.size()-1);
st->Set(4, polyGeomId);
st->Set(5, b.lowerLeft().x());
st->Set(6, b.lowerLeft().y());
st->Set(7, b.upperRight().x());
st->Set(8, b.upperRight().y());
st->Set(9, MAX(b.width(), b.height()));
st->Set(10, blob);
st->Execute();
}
}
catch(IBPP::SQLException& e1)
{
errorMessage_ = e1.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e1)
{
errorMessage_ = e1.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebird::updatePolygon (const string& table, TePolygon &poly )
{
try
{
IBPP::Blob blob = IBPP::BlobFactory(firebird_, transaction_);
// insert data
std::string ins = "UPDATE " + table + " SET ";
ins += "object_id=?, num_coords=?, num_holes=?, ";
ins += " parent_id=?, lower_x=?, lower_y=?, upper_x=?, upper_y=?, ";
ins += " ext_max=?, spatial_data=? WHERE geom_id = " + Te2String(poly.geomId());
IBPP::Statement st = IBPP::StatementFactory(firebird_, transaction_, ins);
st->Prepare(ins);
for(unsigned int i=0; i<poly.size(); i++)
{
string obId = escapeSequence(poly.objectId());
TeBox b = poly.box();
saveLineInBlob(blob, poly[i]);
st->Set(1, obId);
st->Set(2, (int)poly[i].size());
st->Set(3, (i != 0) ? 0 : (int)poly.size()-1);
st->Set(4, poly[0].geomId());
st->Set(5, b.lowerLeft().x());
st->Set(6, b.lowerLeft().y());
st->Set(7, b.upperRight().x());
st->Set(8, b.upperRight().y());
st->Set(9, MAX(b.width(), b.height()));
st->Set(10, blob);
st->Execute();
}
}
catch(IBPP::SQLException& e1)
{
errorMessage_ = e1.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e1)
{
errorMessage_ = e1.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebirdPortal::fetchGeometry (TePolygon& poly)
{
int geomId = getInt("geom_id");
string oId = getData("object_id");
TeBox b(getDouble("lower_x"), getDouble("lower_y"), getDouble("upper_x"), getDouble("upper_x"));
TeLinearRing l;
loadFromBlob(result_, l);
l.geomId(geomId);
poly.geomId(geomId);
poly.objectId (oId);
poly.add (l);
int parentId = poly.geomId();
while (fetchRow())
{
if (getInt("parent_id") == parentId)
{
TeLinearRing hole;
loadFromBlob(result_, hole);
hole.geomId(getInt("geom_id"));
hole.objectId (getData("object_id"));
poly.add (hole);
}
else
return true;
}
return false;
}
bool
TeFirebirdPortal::fetchGeometry (TePolygon& poly, const unsigned int& initIndex)
{
TeLinearRing l;
loadFromBlob(result_, l);
poly.geomId(getInt(initIndex));
poly.objectId (getData(initIndex+1));
poly.add (l);
int parentId = poly.geomId();
while (fetchRow())
{
if (getInt(initIndex+4) == parentId)
{
l.clear();
loadFromBlob(result_, l);
l.geomId(getInt(initIndex));
l.objectId (getData(initIndex+1));
poly.add (l);
}
else
return true;
}
return false;
}
TeLinearRing
TeFirebirdPortal::getLinearRing (int &/*ni*/)
{
int index = atoi(getData("geom_id"));
string object_id = getData("object_id");
//int np = atoi (getData("num_coords"));
TeBox b (getDouble("lower_x"),getDouble("lower_y"),getDouble("upper_x"),getDouble("upper_y"));
TeLinearRing line;
loadFromBlob(result_, line);
line.objectId(object_id);
line.geomId (index);
line.setBox (b);
return line;
}
bool
TeFirebird::insertLine (const string& table, TeLine2D &l)
{
try
{
IBPP::Blob blob = IBPP::BlobFactory(firebird_, transaction_);
// insert data
std::string ins = "INSERT INTO " + table + " ( ";
ins += " object_id, num_coords, ";
ins += " lower_x, lower_y, upper_x, upper_y, ";
ins += " ext_max, spatial_data) VALUES (?,?,?,?,?,?,?,?)";
IBPP::Statement st = IBPP::StatementFactory(firebird_, transaction_, ins);
st->Prepare(ins);
std::string obId = escapeSequence(l.objectId());
TeBox b = l.box();
int index = getLastGeneratedAutoNumber(table);
TeLinearRing ring;
ring.copyElements(l);
saveLineInBlob(blob, ring);
st->Set(1, obId);
st->Set(2, (int)ring.size());
st->Set(3, b.lowerLeft().x());
st->Set(4, b.lowerLeft().y());
st->Set(5, b.upperRight().x());
st->Set(6, b.upperRight().y());
st->Set(7, MAX(b.width(), b.height()));
st->Set(8, blob);
st->Execute();
l.geomId(index);
}
catch(IBPP::SQLException& e1)
{
errorMessage_ = e1.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e1)
{
errorMessage_ = e1.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebird::updateLine (const string& table, TeLine2D &l)
{
try
{
IBPP::Blob blob = IBPP::BlobFactory(firebird_, transaction_);
// insert data
std::string ins = "UPDATE " + table + " SET (";
ins += "object_id=?, num_coords=?, ";
ins += "lower_x=?, lower_y=?, upper_x=?, upper_y=?, ";
ins += "ext_max=?, spatial_data=?) WHERE geom_id="+Te2String(l.geomId());
IBPP::Statement st = IBPP::StatementFactory(firebird_, transaction_, ins);
st->Prepare(ins);
std::string obId = escapeSequence(l.objectId());
TeBox b = l.box();
TeLinearRing ring = l;
saveLineInBlob(blob, ring);
st->Set(1, obId);
st->Set(2, (int)l.size());
st->Set(3, b.lowerLeft().x());
st->Set(4, b.lowerLeft().y());
st->Set(5, b.upperRight().x());
st->Set(6, b.upperRight().y());
st->Set(7, MAX(b.width(), b.height()));
st->Set(8, blob);
st->Execute();
}
catch(IBPP::SQLException& e1)
{
errorMessage_ = e1.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e1)
{
errorMessage_ = e1.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebirdPortal::fetchGeometry(TeLine2D& line)
{
int ni;
line = getLinearRing(ni);
return(fetchRow());
}
bool
TeFirebirdPortal::fetchGeometry(TeLine2D& line, const unsigned int& initIndex)
{
//int index = getInt(initIndex);
string object_id = getData (initIndex+1);
//int np = getInt(initIndex+2);
TeLinearRing l;
loadFromBlob(result_, l);
l.geomId(getInt(initIndex));
l.objectId(getData(initIndex+1));
line.copyElements(l);
return (fetchRow());
}
bool
TeFirebird::insertPoint(const string& table, TePoint &p)
{
string q = "INSERT INTO " + table + " VALUES(0,";
q += "'" + escapeSequence(p.objectId()) + "',";
q += Te2String(p.location().x_) + ",";
q += Te2String(p.location().y_) + ")";
int geomId = getLastGeneratedAutoNumber(table);
if (!execute(string(q)))
{
return false;
}
p.geomId(geomId);
return true;
}
bool
TeFirebirdPortal::fetchGeometry(TePoint& p)
{
TeCoord2D c(getDouble("x"), getDouble("y"));
p.geomId(getInt("geom_id"));
p.objectId(getData("object_id"));
p.add(c);
return (fetchRow());
}
bool
TeFirebirdPortal::fetchGeometry(TePoint& p, const unsigned int& initIndex)
{
TeCoord2D c(getDouble(initIndex+2), getDouble(initIndex+3));
p.geomId(getInt(initIndex));
p.objectId(getData(initIndex+1));
p.add(c);
return (fetchRow());
}
bool
TeFirebird::insertText(const string& table, TeText &t)
{
char q[256];
int geomId = getLastGeneratedAutoNumber(table);
sprintf (q,"INSERT INTO %s values(0,'%s',%.12f,%.12f,'%s',%.12f, %.12f, %.12f, %.12f)",
table.c_str(), escapeSequence(t.objectId()).c_str(),
t.location().x_, t.location().y_,
t.textValue().c_str(), t.angle(), t.height(),t.alignmentVert(),t.alignmentHoriz());
if (!execute(string(q)))
return false;
t.geomId(geomId);
return true;
}
bool
TeFirebird::insertArc(const string& table, TeArc &arc)
{
char q[256];
int geomId = getLastGeneratedAutoNumber(table);
sprintf (q,"INSERT INTO %s values(0,'%s',%d,%d)",
table.c_str(),escapeSequence(arc.objectId()).c_str(),arc.fromNode().geomId(),arc.toNode().geomId());
if (!this->execute(string(q)))
{
return false;
}
arc.geomId(geomId);
return true;
}
bool
TeFirebird::insertNode(const string& table, TeNode &node)
{
char q[256];
int geomId = getLastGeneratedAutoNumber(table);
sprintf (q,"INSERT INTO %s values(0,'%s',%.12f,%.12f)",table.c_str(),node.objectId().c_str(),node.location().x(),node.location().y());
if (!execute(string(q)))
{
return false;
}
node.geomId(geomId);
return true;
}
bool
TeFirebird::insertBlob (const string& tableName, const string& columnBlob , const string& whereClause, unsigned char* data, int size)
{
if (whereClause.empty())
return false;
TeDatabasePortal* portal = getPortal();
string q = "SELECT * FROM "+ tableName +" WHERE "+ whereClause;
if((!portal->query(q)) || (!portal->fetchRow()))
{
delete portal;
return false;
}
delete portal;
std::string sql = "UPDATE ";
sql += tableName;
sql += " SET ";
sql += columnBlob;
sql += " = ?";
sql += " WHERE ";
sql += whereClause;
try
{
bool started = true;
if(!transaction_->Started())
{
transaction_->Start();
started = false;
}
IBPP::Blob blob = IBPP::BlobFactory(firebird_, transaction_);
// insert data
IBPP::Statement st = IBPP::StatementFactory(firebird_, transaction_, sql);
convertChar2Blob((char*)data, size, blob);
blob->Close();
st->Prepare(sql);
st->Set(1, blob);
st->Execute();
(started) ? transaction_->CommitRetain() : transaction_->Commit();
}
catch(IBPP::SQLException& e1)
{
errorMessage_ = e1.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e1)
{
errorMessage_ = e1.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebird::insertRasterBlock(const string& table, const string& blockId, const TeCoord2D& ll, const TeCoord2D& ur,
unsigned char *buf,unsigned long size, int band, unsigned int res, unsigned int subband)
{
if (blockId.empty()) // no block identifier provided
{
errorMessage_ = "bloco sem identificador";
return false;
}
TeDatabasePortal* portal = getPortal();
bool update = false;
std::string sql = "SELECT block_id FROM " + table + " WHERE block_id='" + blockId + "'";
if(!portal->query(sql))
{
delete portal;
errorMessage_ = portal->errorMessage();
return false;
}
if(portal->fetchRow())
{
update = true;
}
delete portal;
try
{
IBPP::Statement st = IBPP::StatementFactory(firebird_, transaction_);
if(!update)
{
sql = "INSERT INTO " + table + " (lower_x, lower_y, upper_x, upper_y, band_id, resolution_factor, subband, block_size, spatial_data, block_id) ";
sql += " VALUES (?,?,?,?,?,?,?,?,?,?)";
}
else
{
sql = "UPDATE " + table + " SET lower_x=?, lower_y=?, upper_x=?, upper_y=?, band_id=?,";
sql += "resolution_factor=?, subband=?, block_size=?, spatial_data=? WHERE block_id=? ";
}
bool trStarted = true;
if(!transaction_->Started())
{
transaction_->Start();
trStarted = false;
}
IBPP::Blob blob = IBPP::BlobFactory(firebird_, transaction_);
convertChar2Blob(reinterpret_cast<char*>(buf), size, blob);
blob->Close();
st->Prepare(sql);
st->Set(1, ll.x());
st->Set(2, ll.y());
st->Set(3, ur.x());
st->Set(4, ur.y());
st->Set(5, band);
st->Set(6, (int)res);
st->Set(7, (int)subband);
st->Set(8, (int)size);
st->Set(9, blob);
st->Set(10, blockId);
st->Execute();
(trStarted)? transaction_->CommitRetain() : transaction_->Commit();
}
catch(IBPP::SQLException& e)
{
transaction_->Rollback();
errorMessage_ = e.ErrorMessage();
return false;
}
catch(IBPP::LogicException& e)
{
transaction_->Rollback();
errorMessage_ = e.ErrorMessage();
return false;
}
return true;
}
bool
TeFirebird::getAttributeList(const string& tableName,TeAttributeList& attList)
{
if(!TeDatabase::getAttributeList(tableName, attList))
{
return false;
}
std::string sql = "SELECT trim(ixs.RDB$FIELD_NAME) from rdb$RELATION_CONSTRAINTS con";
sql += " JOIN RDB$INDEX_SEGMENTS ixs On ixs.RDB$INDEX_NAME = con.RDB$INDEX_NAME";
sql += " WHERE upper(con.RDB$RELATION_NAME) = upper('" + tableName + "') and con.RDB$CONSTRAINT_TYPE = 'PRIMARY KEY'";
TeDatabasePortal* portal = getPortal();
if(!portal->query(sql))
{
delete portal;
return false;
}
while(portal->fetchRow())
{
std::string columnName = portal->getData(0);
for(unsigned int i = 0; i < attList.size(); ++i)
{
if(columnName == attList[i].rep_.name_)
{
attList[i].rep_.isPrimaryKey_ = true;
}
}
}
delete portal;
return true;
}
bool
TeFirebirdPortal::fetchGeometry(TeNode& n)
{
TeCoord2D c(getDouble("x"), getDouble("y"));
n.geomId(getInt("geom_id"));
n.objectId(getData("object_id"));
n.add(c);
return (fetchRow());
}
bool
TeFirebirdPortal::fetchGeometry(TeNode& n, const unsigned int& initIndex)
{
TeCoord2D c(getDouble(initIndex+2), getDouble(initIndex+3));
n.geomId( getInt(initIndex));
n.objectId(getData(initIndex+1));
n.add(c);
return (fetchRow());
}
bool
TeFirebird::insertCell(const string& table, TeCell &c)
{
TeBox b=c.box();
char q[256];
int geomId = getLastGeneratedAutoNumber(table);
sprintf (q,"INSERT INTO %s values(0,'%s',%.15f,%.15f,%.15f,%.15f,%d,%d)",
table.c_str(),c.objectId().c_str(),
b.lowerLeft().x(),b.lowerLeft().y(),b.upperRight().x(),b.upperRight().y(),
c.column(),c.line());
if (!execute (q))
{
return false;
}
c.geomId(geomId);
return true;
}
TeTime
TeFirebirdPortal::getDate (int i)
{
string s = getData(i);
TeTime t(s, TeSECOND, "YYYYsMMsDDsHHsmmsSS",".");
return t;
}
TeTime
TeFirebirdPortal::getDate (const string& s)
{
string sv = getData(s);
TeTime t(sv, TeSECOND, "YYYYsMMsDDsHHsmmsSS",".");
return t;
}
string
TeFirebirdPortal::getDateAsString(const string& s)
{
TeTime t = this->getDate(s);
if (t.isValid())
{
string tval = "\'"+t.getDateTime("YYYYsMMsDDsHHsmmsSS", ".")+"\'";
return tval;
}
else
return "";
}
string
TeFirebirdPortal::getDateAsString(int i)
{
TeTime t = this->getDate(i);
if (t.isValid())
{
string tval = "\'"+t.getDateTime("YYYYsMMsDDsHHsmmsSS", ".")+"\'";
return tval;
}
else
return "";
}
double
TeFirebirdPortal::getDouble (const string& s)
{
return atof(getData(s));
}
double
TeFirebirdPortal::getDouble (int i)
{
return atof(getData(i));
}
int
TeFirebirdPortal::getInt (const string& s)
{
return atoi(getData(s));
}
int
TeFirebirdPortal::getInt (int i)
{
return atoi(getData(i));
}
char*
TeFirebirdPortal::getData (int i)
{
double fValue;
int iValue;
IBPP::Date dValue;
IBPP::Time tValue;
IBPP::Timestamp tsValue;
IBPP::Blob bValue;
std::string sValue;
data_.clear();
try
{
i++;
int numcols = result_->Columns();
if((i>0) && (i <= numcols))
{
IBPP::SDT fbType = result_->ColumnType(i);
switch(fbType)
{
case IBPP::sdFloat :
case IBPP::sdDouble :
if(!result_->Get(i, fValue))
{
char result[100];
sprintf( result, "%f", fValue );
data_ = result;
}
break;
case IBPP::sdInteger :
case IBPP::sdLargeint :
case IBPP::sdSmallint :
if(!result_->Get(i, &iValue))
{
data_ = Te2String(iValue);
}
break;
case IBPP::sdString :
if(!result_->Get(i, sValue))
{
data_ = sValue;
}
break;
case IBPP::sdDate:
if(!result_->Get(i, dValue))
{
//data_ = Te2String(dValue.GetDate());
data_ = Te2String(dValue.Year()) + "." + Te2String(dValue.Month()) + "." + Te2String(dValue.Day());
}
break;
case IBPP::sdTime:
if(!result_->Get(i, tValue))
{
//data_ = Te2String(tValue.GetTime());
data_ = Te2String(tValue.Hours()) + ":" + Te2String(tValue.Minutes()) + ":" + Te2String(tValue.Seconds());
}
break;
case IBPP::sdTimestamp:
if(!result_->Get(i, tsValue))
{
//data_ = Te2String(tsValue.GetTime());
data_ = Te2String(tsValue.Year()) + "." + Te2String(tsValue.Month()) + "." + Te2String(tsValue.Day());
data_ += " " + Te2String(tsValue.Hours()) + ":" + Te2String(tsValue.Minutes()) + ":" + Te2String(tsValue.Seconds());
}
break;
case IBPP::sdBlob:
bValue = IBPP::BlobFactory(firebird_, transaction_);
if(!result_->Get(i, bValue))
{
bValue->Load(data_);
}
bValue->Close();
break;
default:
break;
}
}
}
catch(IBPP::LogicException& e)
{
errorMessage_ = std::string("Error on function getData():\n") + e.ErrorMessage();
return "-1";
}
return (char*) data_.c_str();
}
char*
TeFirebirdPortal::getData (const string& s)
{
std::string::size_type pos = s.find(".");
std::string data = (pos == std::string::npos) ? s : s.substr(pos+1);
int index = result_->ColumnNum(data);
return getData(index-1);
}
bool TeFirebirdPortal::getBlob(const int& column, unsigned char* &data, unsigned long& size)
{
try
{
IBPP::Blob blob = IBPP::BlobFactory(firebird_, transaction_);
// std::string blobS;
result_->Get(column, blob);
char* buffer;
int bufSize;
convertBlob2Char(blob, buffer, bufSize);
blob->Close();
if(data == NULL)
{
data = new unsigned char[bufSize];
}
size = bufSize;
memcpy(data, buffer, bufSize);
delete []buffer;
}
catch(IBPP::LogicException& e)
{
errorMessage_ = e.ErrorMessage();
return false;
}
catch(...)
{
}
return true;
}
bool
TeFirebirdPortal::getBlob (const string& s, unsigned char* &data, long& size)
{
std::string::size_type pos = s.find(".");
std::string fieldS = (pos == std::string::npos) ? s : s.substr(pos+1);
int field = result_->ColumnNum(fieldS);
unsigned long aux;
bool res = getBlob(field, data, aux);
if(res)
{
size = static_cast<unsigned long>(aux);
}
return res;
}
bool
TeFirebirdPortal::getBool (const string& s)
{
int val = getInt(s);
return val ? true : false;
}
bool
TeFirebirdPortal::getBool (int i)
{
int val = getInt(i);
return val ? true : false;
}
bool
TeFirebirdPortal::getRasterBlock(unsigned long& size, unsigned char* ptData)
{
int idx = getColumnIndex("spatial_data")+1;
return getBlob(idx, ptData, size);
}
bool
TeFirebird::inClauseValues(const string& query, const string& attribute, vector<string>& inClauseVector)
{
int i = 0, numRows = 0, count = 0, chunk = 200;
string id, inClause = "(", plic = "'";
TeDatabasePortal *pt = getPortal();
if(pt->query(query) == false)
{
delete pt;
return false;
}
while (numRows < pt->numRows())
{
if(count < chunk && pt->fetchRow())
{
id = pt->getData(attribute);
inClause = inClause + plic + id + "',";
++count;
++numRows;
}
else
{
inClause = inClause.substr(0, inClause.size()-1);
inClause += ")";
inClauseVector.push_back(inClause);
count = 0;
++i;
inClause = "(";
}
}
if (numRows == 0)
{
delete pt;
return true;
}
else
{
inClause = inClause.substr(0, inClause.size()-1);
inClause += ")";
inClauseVector.push_back(inClause);
}
delete pt;
return true;
}
string
TeFirebird::getSQLTime(const TeTime& time) const
{
string result = "'"+ time.getDateTime("YYYYsMMsDDsHHsmmsSS", ".", ":") +"'";
return result;
}
string
TeFirebird::getSQLTemporalWhere(int time1, int time2, TeChronon chr, TeTemporalRelation rel,
const string& initialTime, const string& finalTime)
{
//In Firebird the first day of the week is monday with index 0
if(chr==TeDAYOFWEEK)
{
time1 = time1-1;
if(time1<0)
time1=6;
time2 = time2-1;
if(time2<0)
time2=6;
}
return(TeDatabase::getSQLTemporalWhere(time1, time2, chr, rel, initialTime, finalTime));
}
string TeFirebird::concatValues(vector<string>& values, const string& unionString)
{
string concat = "CONCAT(";
for(unsigned int i = 0; i < values.size(); ++i)
{
if(i != 0)
{
concat += ", ";
if(!unionString.empty())
{
concat += "'";
concat += unionString;
concat += "'";
concat += ", ";
}
}
concat += values[i];
}
concat += ")";
return concat;
}
bool
TeFirebird::updateLayerBox(TeLayer* layer)
{
if (!layer)
return false;
TeBox box = layer->box();
string sql = "UPDATE te_layer SET lower_x = " + Te2String(box.x1());
sql += ", lower_y = " + Te2String(box.y1());
sql += ", upper_x = " + Te2String(box.x2());
sql += ", upper_y = " + Te2String(box.y2());
sql += " WHERE layer_id=" + Te2String(layer->id());
return this->execute(sql);
}
string TeFirebird::toUpper(const string& value)
{
string result = "upper(";
result += value;
result += ")";
return result;
}
| [
"[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec"
]
| [
[
[
1,
3597
]
]
]
|
35c3b74242ac3e9db5e74e313d111c9ce8b33111 | 3cad09dde08a7f9f4fe4acbcb2ffd4643a642957 | /opencv/win/tests/cxcore/src/asolvepoly.cpp | 7741c9d9c4cc1d09bfdd74895860706ee51a1918 | []
| no_license | gmarcotte/cos436-eye-tracker | 420ad9c37cf1819a238c0379662dee71f6fd9b0f | 05d0b010bae8dcf06add2ae93534851668d4eff4 | refs/heads/master | 2021-01-23T13:47:38.533817 | 2009-01-15T02:40:43 | 2009-01-15T02:40:43 | 32,219,880 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,926 | cpp | #include "_cxts.h"
#include "cxcore.h"
#include <algorithm>
#include <complex>
#include <vector>
#include <iostream>
typedef std::complex<double> complex_type;
struct pred_complex {
bool operator() (const complex_type& lhs, const complex_type& rhs) const {
return lhs.real() != rhs.real() ? lhs.real() < rhs.real() :
lhs.imag() < rhs.imag();
}
};
class CV_SolvePolyTest : public CvTest {
public:
CV_SolvePolyTest();
~CV_SolvePolyTest();
protected:
virtual void run( int start_from );
};
CV_SolvePolyTest::CV_SolvePolyTest()
: CvTest( "solve-poly", "cvSolvePoly" ) {
}
CV_SolvePolyTest::~CV_SolvePolyTest() {
}
void CV_SolvePolyTest::run( int start_from ) {
CvRNG rng = cvRNG();
int fig = 100;
double range = 50;
for (int idx = 0, max_idx = 1000, progress = 0;
idx < max_idx; ++idx) {
int n = cvRandInt(&rng) % 13 + 1;
std::vector<complex_type> r(n), ar(n), c(n + 1, 0);
std::vector<double> a(n + 1), u(n * 2);
int rr_odds = 3; // odds that we get a real root
for (int j = 0; j < n;) {
if (cvRandInt(&rng) % rr_odds == 0 || j == n - 1)
r[j++] = cvRandReal(&rng) * range;
else {
r[j] = complex_type(cvRandReal(&rng) * range,
cvRandReal(&rng) * range + 1);
r[j + 1] = std::conj(r[j]);
j += 2;
}
}
for (int j = 0, k = 1 << n, jj, kk; j < k; ++j) {
int p = 0;
complex_type v(1);
for (jj = 0, kk = 1; jj < n && !(j & kk);
++jj, ++p, kk <<= 1);
for (; jj < n; ++jj, kk <<= 1)
if (j & kk)
v *= -r[jj];
else
++p;
c[p] += v;
}
bool pass = false;
double div;
for (int maxiter = 10;
!pass && maxiter < 10000;
maxiter *= 2) {
for (int j = 0; j < n + 1; ++j)
a[j] = c[j].real();
CvMat amat, umat;
cvInitMatHeader(&amat, n + 1, 1, CV_64FC1, &a[0]);
cvInitMatHeader(&umat, n, 1, CV_64FC2, &u[0]);
cvSolvePoly(&amat, &umat, maxiter, fig);
for (int j = 0; j < n; ++j)
ar[j] = complex_type(u[j * 2], u[j * 2 + 1]);
sort(r.begin(), r.end(), pred_complex());
sort(ar.begin(), ar.end(), pred_complex());
div = 0;
double s = 0;
for (int j = 0; j < n; ++j) {
s += r[j].real() + fabs(r[j].imag());
div += pow(r[j].real() - ar[j].real(), 2) +
pow(r[j].imag() - ar[j].imag(), 2);
}
div /= s;
pass = div < 1e-2;
}
if (!pass) {
ts->set_failed_test_info(CvTS::FAIL_INVALID_OUTPUT);
std::cerr<<std::endl;
for (unsigned int j=0;j<r.size();++j)
std::cout << "r[" << j << "] = " << r[j] << std::endl;
std::cout << std::endl;
for (unsigned int j=0;j<ar.size();++j)
std::cout << "ar[" << j << "] = " << ar[j] << std::endl;
}
progress = update_progress(progress, idx-1, max_idx, 0);
}
}
CV_SolvePolyTest solve_poly_test;
| [
"garrett.marcotte@45935db4-cf16-11dd-8ca8-e3ff79f713b6"
]
| [
[
[
1,
118
]
]
]
|
cd4b14e821e3004e982a48b20f231392d26101a9 | 0fe672525051ffc86e93706c57103d180a95d736 | /RoboEnvCompiler/trunk/RoboEnvCompiler/tokensBox.h | 4d1207e52583603580c744c58b5cbb1096a879c9 | []
| no_license | Kristijan10048/roboenvcompiler | b168375c7700e1c3e3e6a264538b9328745db8be | 231e6287e2593bcaaead6d4faf3b526b9e866f94 | refs/heads/master | 2021-01-10T16:44:21.712143 | 2010-06-16T22:40:43 | 2010-06-16T22:40:43 | 44,439,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,818 | h | #pragma once
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
namespace RoboEnvCompiler {
/// <summary>
/// Summary for tokensBox
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
/// </summary>
public ref class tokensBox : public System::Windows::Forms::Form
{
public:
tokensBox(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~tokensBox()
{
if (components)
{
delete components;
}
}
protected:
private: System::Windows::Forms::Button^ button1;
private: System::Windows::Forms::GroupBox^ groupBox1;
public: System::Windows::Forms::RichTextBox^ richTextBox1;
private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel1;
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(tokensBox::typeid));
this->button1 = (gcnew System::Windows::Forms::Button());
this->groupBox1 = (gcnew System::Windows::Forms::GroupBox());
this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox());
this->tableLayoutPanel1 = (gcnew System::Windows::Forms::TableLayoutPanel());
this->groupBox1->SuspendLayout();
this->tableLayoutPanel1->SuspendLayout();
this->SuspendLayout();
//
// button1
//
this->button1->AutoSize = true;
this->button1->Location = System::Drawing::Point(397, 3);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(59, 23);
this->button1->TabIndex = 1;
this->button1->Text = L"OK";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &tokensBox::button1_Click);
//
// groupBox1
//
this->groupBox1->Anchor = static_cast<System::Windows::Forms::AnchorStyles>((((System::Windows::Forms::AnchorStyles::Top | System::Windows::Forms::AnchorStyles::Bottom)
| System::Windows::Forms::AnchorStyles::Left)
| System::Windows::Forms::AnchorStyles::Right));
this->groupBox1->Controls->Add(this->richTextBox1);
this->groupBox1->Location = System::Drawing::Point(12, 12);
this->groupBox1->Name = L"groupBox1";
this->groupBox1->Size = System::Drawing::Size(853, 528);
this->groupBox1->TabIndex = 2;
this->groupBox1->TabStop = false;
this->groupBox1->Enter += gcnew System::EventHandler(this, &tokensBox::groupBox1_Enter);
//
// richTextBox1
//
this->richTextBox1->Dock = System::Windows::Forms::DockStyle::Fill;
this->richTextBox1->Location = System::Drawing::Point(3, 16);
this->richTextBox1->Name = L"richTextBox1";
this->richTextBox1->Size = System::Drawing::Size(847, 509);
this->richTextBox1->TabIndex = 0;
this->richTextBox1->Text = L"";
//
// tableLayoutPanel1
//
this->tableLayoutPanel1->ColumnCount = 3;
this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
45)));
this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
7.525656F)));
this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent,
47.54846F)));
this->tableLayoutPanel1->Controls->Add(this->button1, 1, 0);
this->tableLayoutPanel1->Dock = System::Windows::Forms::DockStyle::Bottom;
this->tableLayoutPanel1->Location = System::Drawing::Point(0, 546);
this->tableLayoutPanel1->Name = L"tableLayoutPanel1";
this->tableLayoutPanel1->RowCount = 1;
this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 100)));
this->tableLayoutPanel1->Size = System::Drawing::Size(877, 31);
this->tableLayoutPanel1->TabIndex = 3;
//
// tokensBox
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(877, 577);
this->Controls->Add(this->tableLayoutPanel1);
this->Controls->Add(this->groupBox1);
this->Icon = (cli::safe_cast<System::Drawing::Icon^ >(resources->GetObject(L"$this.Icon")));
this->Name = L"tokensBox";
this->Text = L"Tokens";
this->groupBox1->ResumeLayout(false);
this->tableLayoutPanel1->ResumeLayout(false);
this->tableLayoutPanel1->PerformLayout();
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
this->Hide();
}
public: void setText(String ^txt)
{
this->richTextBox1->Text=txt;
}
private: System::Void groupBox1_Enter(System::Object^ sender, System::EventArgs^ e) {
}
};
}
| [
"kristijan.petkov@c259c68d-e23d-8608-8b20-da301517ae45"
]
| [
[
[
1,
152
]
]
]
|
52f7952494b57bd724d1406ccbdf95f2f96f3db1 | 27c6eed99799f8398fe4c30df2088f30ae317aff | /rtt-tool/qdoc3/pagegenerator.cpp | d35fceecd97ba044e31f0767339c2907193edcca | []
| no_license | lit-uriy/ysoft | ae67cd174861e610f7e1519236e94ffb4d350249 | 6c3f077ff00c8332b162b4e82229879475fc8f97 | refs/heads/master | 2021-01-10T08:16:45.115964 | 2009-07-16T00:27:01 | 2009-07-16T00:27:01 | 51,699,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,049 | cpp | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
/*
pagegenerator.cpp
*/
#include <qfile.h>
#include <qfileinfo.h>
#include "pagegenerator.h"
#include "tree.h"
QT_BEGIN_NAMESPACE
PageGenerator::PageGenerator()
{
}
PageGenerator::~PageGenerator()
{
while ( !outStreamStack.isEmpty() )
endSubPage();
}
void PageGenerator::generateTree( const Tree *tree, CodeMarker *marker )
{
generateInnerNode( tree->root(), marker );
}
QString PageGenerator::fileBase(const Node *node)
{
if (node->relates())
node = node->relates();
else if (!node->isInnerNode())
node = node->parent();
QString base = node->doc().baseName();
if (!base.isEmpty())
return base;
const Node *p = node;
forever {
base.prepend(p->name());
const Node *pp = p->parent();
if (!pp || pp->name().isEmpty() || pp->type() == Node::Fake)
break;
base.prepend(QLatin1Char('-'));
p = pp;
}
if (node->type() == Node::Fake) {
#ifdef QDOC2_COMPAT
if (base.endsWith(".html"))
base.truncate(base.length() - 5);
#endif
}
// the code below is effectively equivalent to:
// base.replace(QRegExp("[^A-Za-z0-9]+"), " ");
// base = base.trimmed();
// base.replace(" ", "-");
// base = base.toLower();
// as this function accounted for ~8% of total running time
// we optimize a bit...
QString res;
// +5 prevents realloc in fileName() below
res.reserve(base.size() + 5);
bool begun = false;
for (int i = 0; i != base.size(); ++i) {
QChar c = base.at(i);
uint u = c.unicode();
if (u >= 'A' && u <= 'Z')
u -= 'A' - 'a';
if ((u >= 'a' && u <= 'z') || (u >= '0' && u <= '9')) {
res += QLatin1Char(u);
begun = true;
} else if (begun) {
res += QLatin1Char('-');
begun = false;
}
}
while (res.endsWith(QLatin1Char('-')))
res.chop(1);
return res;
}
QString PageGenerator::fileName( const Node *node )
{
if (!node->url().isEmpty())
return node->url();
QString name = fileBase(node);
name += QLatin1Char('.');
name += fileExtension(node);
return name;
}
QString PageGenerator::outFileName()
{
return QFileInfo(static_cast<QFile *>(out().device())->fileName()).fileName();
}
void PageGenerator::beginSubPage( const Location& location,
const QString& fileName )
{
QFile *outFile = new QFile( outputDir() + "/" + fileName );
if ( !outFile->open(QFile::WriteOnly) )
location.fatal( tr("Cannot open output file '%1'")
.arg(outFile->fileName()) );
QTextStream *out = new QTextStream(outFile);
out->setCodec("ISO-8859-1");
outStreamStack.push(out);
}
void PageGenerator::endSubPage()
{
outStreamStack.top()->flush();
delete outStreamStack.top()->device();
delete outStreamStack.pop();
}
QTextStream &PageGenerator::out()
{
return *outStreamStack.top();
}
void PageGenerator::generateInnerNode( const InnerNode *node,
CodeMarker *marker )
{
if (!node->url().isNull())
return;
if (node->type() == Node::Fake) {
const FakeNode *fakeNode = static_cast<const FakeNode *>(node);
if (fakeNode->subType() == FakeNode::ExternalPage)
return;
}
if ( node->parent() != 0 ) {
beginSubPage( node->location(), fileName(node) );
if ( node->type() == Node::Namespace || node->type() == Node::Class) {
generateClassLikeNode(node, marker);
} else if ( node->type() == Node::Fake ) {
generateFakeNode(static_cast<const FakeNode *>(node), marker);
}
endSubPage();
}
NodeList::ConstIterator c = node->childNodes().begin();
while ( c != node->childNodes().end() ) {
if ((*c)->isInnerNode() && (*c)->access() != Node::Private)
generateInnerNode( (const InnerNode *) *c, marker );
++c;
}
}
QT_END_NAMESPACE
| [
"lit-uriy@d7ba3245-3e7b-42d0-9cd4-356c8b94b330"
]
| [
[
[
1,
198
]
]
]
|
a181f9be63678a19b4618124236f2116a1bdc394 | 655fe8fa2c95def8ab819d480d66dfb2c3d5f9b4 | /dicomlib/ClientConnection.cpp | 18d80aebf094e8d65b52a9a023e1fb4da79ea182 | []
| no_license | PatrickRABEL/dicomlib | 66a2608ca215930270adab5611830c2842c207f1 | c85cd617833f801959d61c268fd970ed0ff0ca46 | refs/heads/master | 2016-08-12T15:10:29.968444 | 2011-12-05T02:45:12 | 2011-12-05T02:45:12 | 55,343,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,357 | cpp | /************************************************************************
* DICOMLIB
* Copyright 2003 Sunnybrook and Women's College Health Science Center
* Implemented by Trevor Morgan ([email protected])
*
* See LICENSE.txt for copyright and licensing info.
*************************************************************************/
#include <iostream>
#include "socket/Socket.hpp"
#include "UIDs.hpp"
#include "ImplementationUID.hpp"
#include "ClientConnection.hpp"
#include "aarj.hpp"
#include "AssociationRejection.hpp"
#include "Cdimse.hpp"
using std::cout;using std::endl;
/*
As I understand it, the way UCDMC99 works is this:
The user specifies a list of AbstractSyntaxes.
The Library converts this into a list of proposed PresentationContexts,
each having only one Transfer Syntax, of type Implicit VR/Little Endian.
This list get's sent to the server....
I'm a bit confused why UCDMC99 has all this endian handling stuff
and then only accepts one Transfer Syntax. Why not support the rest?
*/
namespace dicom
{
using namespace primitive;
ClientConnection::ClientConnection(std::string Host, unsigned short Port,
std::string LocalAET,std::string RemoteAET,
//const std::vector<PresentationContext>& ProposedPresentationContexts)
const PresentationContexts& ProposedPresentationContexts)
//: ServiceBase(new Network::ClientSocket(Host,Port))
: socket_(new Network::ClientSocket(Host,Port))
{
AAssociateRQ& association_request=AAssociateRQ_;//BAD BAD BAD
association_request.CallingAppTitle_=LocalAET;
association_request.CalledAppTitle_=RemoteAET;
//If we get this far, we have a valid TCP/IP connection,
//so now negotiate the association...
/*
user must specify 1 or more PresentationContexts.
framework must give these temporary IDS, and feed them
onto request object.
We propose a set of PresentationContexts, the other end selects
which ones it likes and sends us back a list.
*/
association_request.ProposedPresentationContexts_=ProposedPresentationContexts;//expensive copy operation!
//last bit to do is:
UserInformation UserInfo;
MaximumSubLength MaxSubLength;
MaxSubLength.Set(16384); // we can do all DICOM can handle???
UserInfo.ImpClass_.UID_=ImplementationClassUID;
UserInfo.ImpVersion_.Name=ImplementationVersionName;
UserInfo.SetMax(MaxSubLength);
association_request.SetUserInformation ( UserInfo );
association_request.Write(*socket_);
//examine response from server.
BYTE ItemType;
(*socket_) >> ItemType;
switch(ItemType)
{
case 0x02:
{
AAssociateAC acknowledgement;
acknowledgement.ReadDynamic (*socket_);
if(!InterogateAAssociateAC(acknowledgement))
{
throw FailedAssociation();//need a more detailed error here.
}
return;//negotiation succesful!
}
case 0x03:
{
AAssociateRJ rejection;
rejection.ReadDynamic(*socket_);
throw AssociationRejection(rejection.Result_,rejection.Source_,rejection.Reason_);
}
default:
throw BadItemType(ItemType,0);
}
//once we've finished negotiating, ServiceBase::AcceptedPresentationContexts_ will
//have correct values.
}
/*
There are some problems with this, for example if
the client connection is getting destroyed as part of
a stack unwind caused by an exception thrown on a failed
link.
*/
ClientConnection::~ClientConnection()
{
//Try to negotiate a clean release with the server...
try
{
AReleaseRQ release_request;
release_request.Write(*socket_);
AReleaseRP response;
response.Read(*socket_);//should we do anything with this?
}
catch(std::exception& e)
{
cout << "Exception thrown in ClientConnection destructor:"<<e.what() << endl;
}
catch(...)//can't allow destructors to emit exceptions
{
cout << "Unknown exception throw in ClientConnection destructor." << endl;
throw;//should actually be a terminate(), I think.
}
//delete socket_;
}
bool IsBad(PresentationContextAccept& PCA)
{
return (PCA.Result_!=0);
}
/*!
copy all succesfully proposed PresentationContexts onto
AcceptedPresentationContexts_
*/
bool ClientConnection::InterogateAAssociateAC(AAssociateAC& acknowledgement)
{
//"Accepted" means feed back from remote server. Not necessary "result is 0" -Sam
AcceptedPresentationContexts_=acknowledgement.PresContextAccepts_;
//AcceptedPresentationContexts_.clear();
AcceptedPresentationContexts_ = acknowledgement.PresContextAccepts_;
int unaccepted = std::count_if(acknowledgement.PresContextAccepts_.begin(),acknowledgement.PresContextAccepts_.end(),IsBad);
return (AcceptedPresentationContexts_.size()>unaccepted);
}
/*
This implies we need to add similar functions for the other operatons, such as MOVE
*/
//caller has not right to define ts here. It is determined by AcceptedPresentationContexts -Sam
DataSet ClientConnection::Store(const DataSet& data/*,TS ts*/)
{
UID classUID(data(TAG_SOP_CLASS_UID).Get<UID>());
UID instUID(data(TAG_SOP_INST_UID).Get<UID>());
//Check the SOPClass in data and find the accepted transfer syntax
BYTE presid;
try
{
presid=GetPresentationContextID(classUID);
}
catch (dicom::exception& e)
{
cout << "In ClientConnection::Store: " << e.what();
}
SetCurrentPCID(presid);
//commented out because the ts is handled inside ServiceBase class. -Sam April 9, 2007
//UID tsuid;
//try
//{
// tsuid=GetTransferSyntaxUID(presid);
//}
//catch (std::runtime_error& r)
//{
// cout << "In ClientConnection::Store: " << r.what();
//}
/*
maybe the following could be pushed into CStoreSCU
-after all, how else would one ever use a CStoreSCU?
*/
UINT16 status;
DataSet response;
CStoreSCU storeSCU(*this,classUID);
storeSCU.writeRQ(instUID, data/*,TS(tsuid)*/);
storeSCU.readRSP(status,response);
return response;
}
DataSet ClientConnection::Move(const std::string& destination,const DataSet& query,QueryRetrieve::Root root)
{
UID classUID;
switch(root)
{
case QueryRetrieve::STUDY_ROOT:
classUID=STUDY_ROOT_QR_MOVE_SOP_CLASS;
break;
case QueryRetrieve::PATIENT_ROOT:
classUID=PATIENT_ROOT_QR_MOVE_SOP_CLASS;
break;
case QueryRetrieve::PATIENT_STUDY_ONLY:
classUID=PATIENT_STUDY_ONLY_QR_MOVE_SOP_CLASS;
break;
default:
throw dicom::exception("Unknown QR root specified.");
}
//build a C-MOVE identifier...
CMoveSCU moveSCU(*this,classUID);
moveSCU.writeRQ(destination,query);
UINT16 status;
DataSet response;
moveSCU.readRSP(status,response);
return response;
}
/*
This utility function waits until all responses have been
sent back, then returns them in a vector. If you want to
process each response as it comes in, you'll have to
implement your own function, which should be straightforward
if you borrow the code here.
*/
std::vector<DataSet> ClientConnection::Find(const DataSet& Query,QueryRetrieve::Root root)
{
UID classUID;
switch(root)
{
case QueryRetrieve::STUDY_ROOT:
classUID=STUDY_ROOT_QR_FIND_SOP_CLASS;
break;
case QueryRetrieve::PATIENT_ROOT:
classUID=PATIENT_ROOT_QR_FIND_SOP_CLASS;
break;
case QueryRetrieve::PATIENT_STUDY_ONLY:
classUID=PATIENT_STUDY_ONLY_QR_FIND_SOP_CLASS;
break;
case QueryRetrieve::MODALITY_WORKLIST:
classUID=MODALITY_WORKLIST_SOP_CLASS;
break;
case QueryRetrieve::GENERAL_PURPOSE_WORKLIST:
classUID=GENERAL_PURPOSE_WORKLIST_SOP_CLASS;
break;
default:
throw dicom::exception("Unknown QR root specified.");
}
//Check the SOPClass in data and find the accepted transfer syntax
BYTE presid;
try
{
presid=GetPresentationContextID(classUID);
}
catch (dicom::exception& e)
{
cout << "In ClientConnection::Store: " << e.what();
}
SetCurrentPCID(presid);
CFindSCU findSCU(*this,classUID);
findSCU.writeRQ(Query);
UINT16 status = Status::PENDING;
std::vector<DataSet> Responses;
while (status==Status::PENDING || status == Status::PENDING1)
{
DataSet response;
DataSet data;
findSCU.readRSP(status,response,data);
if(data.size())
Responses.push_back(data);
}
return Responses;
}
DataSet ClientConnection::Echo()
{
CEchoSCU echoSCU(*this);
echoSCU.writeRQ();
DataSet response;
UINT16 status;
echoSCU.readRSP(status,response);//should we do something with status?
return response;
}
/*
C-GET design.
C-GET is harder to implement, as we have to recieve the images on the
same connection as we make the request.
So the procedure has to be:
Write request.
Listen for and process returned datasets.
Read response.
It's actually even more complicated than this, because the server
might be sending back 'pending' responses.
Do we need any callback tricks for this?
*/
#if 0
DataSet ClientConnection::Get(const DataSet& query,QueryRetrieve::Root root)
{
UID classUID=STUDY_ROOT_QR_GET_SOP_CLASS;// or whatever.
//build a C-MOVE identifier...
CGetSCU getSCU(*this,classUID);
getSCU.writeRQ(query);
/*
Now at this point we need to start listening for C-STORE operations
on THIS connection! Can we just call HandleCStore, or something?
*/
Command::Code cmd;
UID classUID;
while(true)
{
DataSet command;
Read(command);
//now command may be a C-STORE-RQ, or
//it may be a response to the C-GET-RQ!
command(TAG_CMD_FIELD) >> cmd;
command(TAG_AFF_SOP_CLASS_UID) >> classUID;
if(/*it's a response*/)
{
if(/*it's pending*/)
;//fine, carry on
else if(/*it's completed*/
break;
else//something's wrong
throw;
}
else
{
C_STORE_RQ==cmd
//make sure it's a C-STORE
//if it is, handle it.
HandlerFunction handler=server_.GetHandler(classUID);
HandleCStore(handler,*this,command,classUID);
}
}
UINT16 status;
DataSet response;
get.readRSP(status,response);
return response;
}
#endif //0
};//namespace dicom
| [
"trevor@localhost"
]
| [
[
[
1,
383
]
]
]
|
07e018ee6b2b46dafc05eaa2b8a72e0b41169596 | 0033659a033b4afac9b93c0ac80b8918a5ff9779 | /game/client/hl2mp/c_hl2mp_player.h | 72c233a310db4f1f59a20fb41d1331edfa8657ee | []
| no_license | jonnyboy0719/situation-outbreak-two | d03151dc7a12a97094fffadacf4a8f7ee6ec7729 | 50037e27e738ff78115faea84e235f865c61a68f | refs/heads/master | 2021-01-10T09:59:39.214171 | 2011-01-11T01:15:33 | 2011-01-11T01:15:33 | 53,858,955 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,349 | h | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
#ifndef HL2MP_PLAYER_H
#define HL2MP_PLAYER_H
#pragma once
#include "hl2mp_playeranimstate.h"
#include "c_basehlplayer.h"
#include "baseparticleentity.h"
#include "hl2mp_player_shared.h"
#include "beamdraw.h"
#include "flashlighteffect.h"
//Tony; m_pFlashlightEffect is private, so just subclass. We may want to do some more stuff with it later anyway.
class CHL2MPFlashlightEffect : public CFlashlightEffect
{
public:
CHL2MPFlashlightEffect(int nIndex = 0) :
CFlashlightEffect( nIndex )
{
}
~CHL2MPFlashlightEffect() {};
virtual void UpdateLight(const Vector &vecPos, const Vector &vecDir, const Vector &vecRight, const Vector &vecUp, int nDistance);
};
//=============================================================================
// >> HL2MP_Player
//=============================================================================
class C_HL2MP_Player : public C_BaseHLPlayer
{
public:
DECLARE_CLASS( C_HL2MP_Player, C_BaseHLPlayer );
DECLARE_CLIENTCLASS();
DECLARE_PREDICTABLE();
DECLARE_INTERPOLATION();
C_HL2MP_Player();
~C_HL2MP_Player( void );
// Player avoidance
bool ShouldCollide( int collisionGroup, int contentsMask ) const;
void AvoidPlayers( CUserCmd *pCmd );
float m_fNextThinkPushAway;
virtual bool CreateMove( float flInputSampleTime, CUserCmd *pCmd );
void ClientThink( void );
static C_HL2MP_Player* GetLocalHL2MPPlayer();
virtual int DrawModel( int flags );
virtual void AddEntity( void );
Vector GetAttackSpread( CBaseCombatWeapon *pWeapon, CBaseEntity *pTarget = NULL );
// Should this object cast shadows?
virtual ShadowType_t ShadowCastType( void );
virtual C_BaseAnimating *BecomeRagdollOnClient();
virtual const QAngle& GetRenderAngles();
virtual bool ShouldDraw( void );
virtual void OnDataChanged( DataUpdateType_t type );
virtual float GetFOV( void );
virtual void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr );
virtual void ItemPreFrame( void );
virtual void ItemPostFrame( void );
virtual float GetMinFOV() const { return 5.0f; }
virtual Vector GetAutoaimVector( float flDelta );
virtual void NotifyShouldTransmit( ShouldTransmitState_t state );
virtual void CreateLightEffects( void ) {}
virtual bool ShouldReceiveProjectedTextures( int flags );
virtual void PostDataUpdate( DataUpdateType_t updateType );
virtual void PlayStepSound( Vector &vecOrigin, surfacedata_t *psurface, float fvol, bool force );
virtual void PreThink( void );
virtual void DoImpactEffect( trace_t &tr, int nDamageType );
IRagdoll* GetRepresentativeRagdoll() const;
virtual void CalcView( Vector &eyeOrigin, QAngle &eyeAngles, float &zNear, float &zFar, float &fov );
virtual const QAngle& EyeAngles( void );
bool CanSprint( void );
void StartSprinting( void );
void StopSprinting( void );
void HandleSpeedChanges( void );
void UpdateLookAt( void );
int GetIDTarget() const;
void UpdateIDTarget( void );
void PrecacheFootStepSounds( void );
const char *GetPlayerModelSoundPrefix( void );
HL2MPPlayerState State_Get() const;
// Walking
void StartWalking( void );
void StopWalking( void );
bool IsWalking( void ) { return m_fIsWalking; }
virtual void UpdateClientSideAnimation();
/////
// SO2 - James
// Add support for CS:S player animations
// Made virtual for access purposes
//void DoAnimationEvent( PlayerAnimEvent_t event, int nData = 0 );
virtual void DoAnimationEvent( PlayerAnimEvent_t event, int nData = 0 );
/////
virtual void CalculateIKLocks( float currentTime );
//Tony; when model is changed, need to init some stuff.
virtual CStudioHdr *OnNewModel( void );
void InitializePoseParams( void );
/////
// SO2 - James
// First-person ragdolls
// http://developer.valvesoftware.com/wiki/First_Person_Ragdolls
// Moved from private to protected for access
protected:
EHANDLE m_hRagdoll;
/////
private:
C_HL2MP_Player( const C_HL2MP_Player & );
CHL2MPPlayerAnimState *m_PlayerAnimState;
QAngle m_angEyeAngles;
CInterpolatedVar< QAngle > m_iv_angEyeAngles;
/////
// SO2 - James
// First-person ragdolls
// http://developer.valvesoftware.com/wiki/First_Person_Ragdolls
// Moved from private to protected for access
//EHANDLE m_hRagdoll;
/////
int m_headYawPoseParam;
int m_headPitchPoseParam;
float m_headYawMin;
float m_headYawMax;
float m_headPitchMin;
float m_headPitchMax;
bool m_isInit;
Vector m_vLookAtTarget;
float m_flLastBodyYaw;
float m_flCurrentHeadYaw;
float m_flCurrentHeadPitch;
int m_iIDEntIndex;
CountdownTimer m_blinkTimer;
bool m_bSpawnInterpCounter;
bool m_bSpawnInterpCounterCache;
int m_iPlayerSoundType;
virtual void UpdateFlashlight( void ); //Tony; override.
void ReleaseFlashlight( void );
Beam_t *m_pFlashlightBeam;
CHL2MPFlashlightEffect *m_pHL2MPFlashLightEffect;
CNetworkVar( HL2MPPlayerState, m_iPlayerState );
bool m_fIsWalking;
};
inline C_HL2MP_Player *ToHL2MPPlayer( CBaseEntity *pEntity )
{
if ( !pEntity || !pEntity->IsPlayer() )
return NULL;
return dynamic_cast<C_HL2MP_Player*>( pEntity );
}
class C_HL2MPRagdoll : public C_BaseAnimatingOverlay
{
public:
DECLARE_CLASS( C_HL2MPRagdoll, C_BaseAnimatingOverlay );
DECLARE_CLIENTCLASS();
C_HL2MPRagdoll();
~C_HL2MPRagdoll();
virtual void OnDataChanged( DataUpdateType_t type );
int GetPlayerEntIndex() const;
IRagdoll* GetIRagdoll() const;
void ImpactTrace( trace_t *pTrace, int iDamageType, char *pCustomImpactName );
void UpdateOnRemove( void );
virtual void SetupWeights( const matrix3x4_t *pBoneToWorld, int nFlexWeightCount, float *pFlexWeights, float *pFlexDelayedWeights );
private:
C_HL2MPRagdoll( const C_HL2MPRagdoll & ) {}
void Interp_Copy( C_BaseAnimatingOverlay *pDestinationEntity );
void CreateHL2MPRagdoll( void );
private:
EHANDLE m_hPlayer;
CNetworkVector( m_vecRagdollVelocity );
CNetworkVector( m_vecRagdollOrigin );
};
#endif //HL2MP_PLAYER_H
| [
"MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61"
]
| [
[
[
1,
233
]
]
]
|
70003f84057b7d3aeb054aa73bdec665e35159bd | 38664d844d9fad34e88160f6ebf86c043db9f1c5 | /branches/initialize/skin/Samples/Skinmagic Toolkit 2.4/MFC/About/AboutDlg.cpp | 0571e60ab9623b9bfde23de1e68df4d42d504d22 | []
| no_license | cnsuhao/jezzitest | 84074b938b3e06ae820842dac62dae116d5fdaba | 9b5f6cf40750511350e5456349ead8346cabb56e | refs/heads/master | 2021-05-28T23:08:59.663581 | 2010-11-25T13:44:57 | 2010-11-25T13:44:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | cpp | #include "stdafx.h"
#include "AboutDlg.h"
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
DDX_Control( pDX , IDC_HOMEPAGE , m_homepage );
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL CAboutDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
| [
"zhongzeng@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd"
]
| [
[
[
1,
31
]
]
]
|
1fb1fc4ade5267720416d20c2c29c7f5e6685e0c | de75637338706776f8770c9cd169761cec128579 | /VHFOS/Viet heroes - Fight or Surrender/StartMenu.h | a734931b636629b29479e051fb8e213553d3a5d3 | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive"
]
| permissive | huytd/fosengine | e018957abb7b2ea2c4908167ec83cb459c3de716 | 1cebb1bec49720a8e9ecae1c3d0c92e8d16c27c5 | refs/heads/master | 2021-01-18T23:47:32.402023 | 2008-07-12T07:20:10 | 2008-07-12T07:20:10 | 38,933,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,574 | h | #ifndef _START_MENU_H_
#define _START_MENU_H_
#include <SGF.h>
#include "GameLevel.h"
#include "GameLevel.h"
#include "Utility.h"
#include "CharSelectScreen.h"
#include "Utility.h"
//#include "CGUIIconSlot.h"
//#include "CGUIIcon.h"
//#include "CGUISlotWindow.h"
//#include "CGUIBringUpSlotWindowButton.h"
class StartMenu : public sgfLevel
{
public:
//CGUISlotWindow* window;
//CGUIIcon *icon;
//CGUIIcon *icon2;
//CGUIIcon *bigIcon;
//IGUIButton* button ;
//ITexture* slotTex;
//ITexture* iconTex ;
//ITexture* iconTex2;
//ITexture* bigIconTex;
//core::array<IGUIElement*> slotArray;
private:
sgfMethodDelegate<StartMenu,irr::SEvent::SGUIEvent> onGUI;
sgfEntityManager* emgr;
irr::gui::IGUIImage* bgimg;
public:
StartMenu()
{
onGUI.addRef();
onGUI.bind(this,&StartMenu::onGUIEvent);
}
void onGUIEvent(irr::SEvent::SGUIEvent& args)
{
if(args.EventType==irr::gui::EGET_BUTTON_CLICKED)
{
if(args.Caller->getID()==1)//start
{
emgr->loadLevel(new GameLevel("levels/start.irr"));
}
else if(args.Caller->getID()==2)
{
//Utility::drawImage(emgr, "textures/CharSel.jpg");
emgr->loadLevel(new GameLevel("levels/levelOne.irr"));
//emgr->loadLevel(new LoadingScreen());
}
else if(args.Caller->getID()==3)
{
emgr->getCore()->getGame()->quit();
}
}
}
void onEnter(sgfEntityManager* emgr)
{
this->emgr=emgr;
//! Loading unicode font
Utility::setFont(emgr,"font/myfont.xml");
//! Get Gui Environment Manager
irr::gui::IGUIEnvironment* env = emgr->getCore()->getGraphicDevice()->getGUIEnvironment();
//! Get mouse
irr::gui::ICursorControl* cursor = emgr->getCore()->getGraphicDevice()->getCursorControl();
//! Get screen size
irr::core::dimension2d<s32> screenSize = env->getVideoDriver()->getScreenSize();
//! Set button text color
Utility::setTxColor(emgr,irr::video::SColor(255,255,255,255),EGDC_BUTTON_TEXT);
//env->addImage(env->getVideoDriver()->getTexture("textures/startBG.jpg"),position2d<s32>(0,0),false,0,-1,0);
bgimg = env->addImage(irr::core::rect<irr::s32>(0,0,screenSize.Width, screenSize.Height),0,-1,0);
bgimg->setImage(env->getVideoDriver()->getTexture("textures/startBG.jpg"));
bgimg->setScaleImage(true);
//! Add menu button
env->addButton(irr::core::rect<irr::s32>((screenSize.Width-150),(screenSize.Height-60)/2,
(screenSize.Width),
(screenSize.Height+60)/2), 0, 1, L"Bắt đầu", L"Bắt đầu game");
env->addButton(irr::core::rect<irr::s32>((screenSize.Width-150),(screenSize.Height-60)/2+50,
(screenSize.Width),
(screenSize.Height+60)/2+50), 0, 2, L"Bắt đầu 2", L"Bắt đầu game");
env->addButton(irr::core::rect<irr::s32>((screenSize.Width-150),(screenSize.Height-60)/2+50+50,
(screenSize.Width),
(screenSize.Height+60)/2+50+50), 0, 3, L"Thoát", L"Thoát khỏi game");
//! Đặt con trỏ chuột đúng giữa nút bắt đầu.
cursor->setPosition(screenSize.Width/2,screenSize.Height/2);
//emgr->getCore()->getGraphicDevice()->getVideoDriver()
//emgr->getCore()->getGraphicDevice()->getGUIEnvironment()
////! create a slot window
//window = new CGUISlotWindow(emgr->getCore()->getGraphicDevice(),
// env->getRootGUIElement(),
// -1,
// rect<s32>(25, 25, 300, 200));
//
//////! create a button to show/hide the window
//button = window->createBringUpButton(rect<s32>(10,210,110,242));
//
////! load some very beautiful textures
//slotTex = env->getVideoDriver()->getTexture("hud\\slot.png");
//iconTex = env->getVideoDriver()->getTexture("hud\\icon.png");
//iconTex2 = env->getVideoDriver()->getTexture("hud\\icon2.png");
//bigIconTex = env->getVideoDriver()->getTexture("hud\\bigicon.png");
////! create an array of slots in the window
//slotArray = window->addSlotArray(core::rect<s32>(0,0,32,32), slotTex, env->getRootGUIElement(), -1,
//core::position2d<s32>(80,40),core::dimension2d<s32>(6,6),core::dimension2d<s32>(0,0));
////! create an icon
//icon = new CGUIIcon(env, env->getRootGUIElement(), -1, rect<s32>(0,0,32,32));
//icon->setImage(iconTex);
////! create another icon
//icon2 = new CGUIIcon(env, env->getRootGUIElement(), -1, rect<s32>(0,0,32,32));
//
//icon2->setImage(iconTex2);
////! create another icon
//bigIcon = new CGUIIcon(env, env->getRootGUIElement(), -1, rect<s32>(0,0,64,64));
//
//bigIcon->setImage(bigIconTex);
////! Setup icon
//icon->setMoveable(true);
//icon2->setMoveable(true);
//bigIcon->setMoveable(true);
///*icon->setCanBeOutsideSlot(true);
//icon2->setCanBeOutsideSlot(true);*/
////! let the icons know about the slots
//icon->setUsableSlotArray(&slotArray);
//icon2->setUsableSlotArray(&slotArray);
//bigIcon->setUsableSlotArray(&slotArray);
//! Add delegate
emgr->getCore()->getGUIEvent()->addDelegate(&onGUI);
}
void onExit(sgfEntityManager* emgr)
{
irr::gui::IGUIEnvironment* env=emgr->getCore()->getGraphicDevice()->getGUIEnvironment();
env->clear();
emgr->getCore()->getGUIEvent()->removeDelegate(&onGUI);
//! Destroy drag and drop gui object
//window->drop();
//icon->drop();
//button->drop();
//bigIcon->drop();
//icon2->drop();
}
};
#endif | [
"doqkhanh@52f955dd-904d-0410-b1ed-9fe3d3cbfe06"
]
| [
[
[
1,
183
]
]
]
|
084d3acce64852513d240ba9a1fd25ad309900a4 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/nebula2/src/kernel/ndirectory.cc | 415e99f38ef05179db81d0f837cce4e4c4a2421e | []
| no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,138 | cc | //------------------------------------------------------------------------------
// (C) 2002 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "kernel/ndirectory.h"
//------------------------------------------------------------------------------
/**
*/
nDirectory::nDirectory() :
#if __WIN32__
handle(0),
#endif
empty(true)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nDirectory::~nDirectory()
{
if (this->IsOpen())
{
n_printf("Warning: Directory destroyed before closing\n");
this->Close();
}
}
//------------------------------------------------------------------------------
/**
opens the specified directory
@param dirName the name of the directory to open
@return success
history:
- 30-Jan-2002 peter created
*/
bool
nDirectory::Open(const nString& dirName)
{
n_assert(!this->IsOpen());
n_assert(dirName.IsValid());
// mangle path name
this->path = nFileServer2::Instance()->ManglePath(dirName);
#ifdef __WIN32__
bool retval;
this->handle = NULL;
// testen, ob File existiert und ein Dir ist...
DWORD attr = GetFileAttributes(this->path.Get());
if ((attr != 0xffffffff) && (attr & FILE_ATTRIBUTE_DIRECTORY))
{
retval = true;
this->empty = !(this->SetToFirstEntry());
}
else
{
retval = false;
this->path.Clear();
}
return retval;
#else
// FIXME LINUX NOT IMPLEMENTED YET
return false;
#endif
}
//------------------------------------------------------------------------------
/**
closes the directory
history:
- 30-Jan-2002 peter created
*/
void
nDirectory::Close()
{
n_assert(this->IsOpen());
#ifdef __WIN32__
if (this->handle)
{
FindClose(this->handle);
this->handle = NULL;
}
#else
// FIXME: LINUX NOT IMPLEMENTED YET
#endif
this->path.Clear();
}
//------------------------------------------------------------------------------
/**
asks if directory is empty
@return true if empty
history:
- 30-Jan-2002 peter created
*/
bool
nDirectory::IsEmpty()
{
n_assert(this->IsOpen());
return this->empty;
}
//------------------------------------------------------------------------------
/**
sets search index to first entry in directory
@return success
history:
- 30-Jan-2002 peter created
*/
bool
nDirectory::SetToFirstEntry()
{
n_assert(this->IsOpen());
#ifdef __WIN32__
if (this->handle)
{
FindClose(this->handle);
}
nString tmpName = this->path;
tmpName.Append("\\*.*");
this->handle = FindFirstFile(tmpName.Get(), &(this->findData));
if (this->handle == INVALID_HANDLE_VALUE)
{
return false;
}
while ((strcmp(this->findData.cFileName, "..") ==0) || (strcmp(this->findData.cFileName, ".") == 0))
{
if (!FindNextFile(this->handle, &this->findData))
{
return false;
}
}
return true;
#else
// FIXME: LINUX NOT IMPLEMENTED YET
return false;
#endif
}
//------------------------------------------------------------------------------
/**
selects next directory entry
@return success
history:
- 30-Jan-2002 peter created
*/
bool
nDirectory::SetToNextEntry()
{
n_assert(this->IsOpen());
#ifdef __WIN32__
n_assert(this->handle);
n_assert(this->handle != INVALID_HANDLE_VALUE);
bool suc = (FindNextFile(this->handle, &(this->findData)) != 0);
return suc;
#else
// FIXME: LINUX NOT IMPLEMENTED YET
return false;
#endif
}
//------------------------------------------------------------------------------
/**
gets name of actual directory entry
@return the name
history:
- 30-Jan-2002 peter created
*/
nString
nDirectory::GetEntryName()
{
n_assert(this->IsOpen());
#ifdef __WIN32__
n_assert(this->handle);
n_assert(this->handle != INVALID_HANDLE_VALUE);
this->apath = this->path;
this->apath.Append("/");
this->apath.Append(this->findData.cFileName);
return this->apath;
#else
// FIXME: LINUX NOT IMPLEMENTED YET
return 0;
#endif
}
//------------------------------------------------------------------------------
/**
gets type of actual directory entry
@return FILE or DIRECTORY
history:
- 30-Jan-2002 peter created
*/
nDirectory::EntryType
nDirectory::GetEntryType()
{
n_assert(this->IsOpen());
#ifdef __WIN32__
n_assert(this->handle);
n_assert(this->handle != INVALID_HANDLE_VALUE);
if (this->findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
return DIRECTORY;
return FILE;
#else
// FIXME: LINUX NOT IMPLEMENTED YET
return INVALID;
#endif
}
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
]
| [
[
[
1,
238
]
]
]
|
4f6e769fa476aae04aad596fd88e100ca7306529 | 3dca0a6382ea348a8617be05e1bfa6f4ed70d77c | /src/PgeBaseInputListener.cpp | 224a5b97ff4c8c30897d3fc3e54510c669f1890f | []
| no_license | David-Haim-zz/pharaoh-game-engine | 9c766916559f9c74667e981b9b3f03b43920bc4e | b71db3fd99ebad0ab40a0888360d560748f63131 | refs/heads/master | 2021-05-29T15:17:23.043407 | 2011-01-23T17:53:39 | 2011-01-23T17:53:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | cpp |
/*! $Id$
* @file PgeBaseInputListener.h
* @author Chad M. Draper
* @date June 2, 2008
*
*/
#include "PgeBaseInputListener.h"
namespace PGE
{
//Destructor----------------------------------------------------------------
BaseInputListener::~BaseInputListener()
{
//dtor
}
} // namespace PGE
| [
"pharaohgameengine@555db735-7c4c-0410-acd0-0358cc0c1ac3"
]
| [
[
[
1,
19
]
]
]
|
94d763eba364a7bb6168b2e6d1b41986b3ac9b30 | 2d4221efb0beb3d28118d065261791d431f4518a | /OIDE源代码/OLIDE/Controls/scintilla/scintillawrappers/ScintillaDemo.cpp | ef8e638e979d800804f5a445f848e6a3b2118860 | []
| no_license | ophyos/olanguage | 3ea9304da44f54110297a5abe31b051a13330db3 | 38d89352e48c2e687fd9410ffc59636f2431f006 | refs/heads/master | 2021-01-10T05:54:10.604301 | 2010-03-23T11:38:51 | 2010-03-23T11:38:51 | 48,682,489 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,709 | cpp | #include "stdafx.h"
#include "ScintillaDemo.h"
#include "MainFrm.h"
#include "ChildFrm.h"
#include "ScintillaDemoDoc.h"
#include "ScintillaDemoView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
BEGIN_MESSAGE_MAP(CScintillaDemoApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()
CScintillaDemoApp::CScintillaDemoApp()
{
}
CScintillaDemoApp theApp;
BOOL CScintillaDemoApp::InitInstance()
{
//Load the scintilla dll
m_hSciDLL = LoadLibrary(_T("SciLexer.dll"));
if (m_hSciDLL == NULL)
{
AfxMessageBox(_T("Scintilla DLL is not installed, Please download the SciTE editor and copy the SciLexer.dll into this application's directory"));
return FALSE;
}
SetRegistryKey(_T("PJ Naughter"));
LoadStdProfileSettings(); // Load standard INI file options (including MRU)
//Register the application's document templates. Document templates
//serve as the connection between documents, frame windows and views.
CMultiDocTemplate* pDocTemplate = new CMultiDocTemplate(IDR_SCINTITYPE,
RUNTIME_CLASS(CScintillaDemoDoc),
RUNTIME_CLASS(CChildFrame), // custom MDI child frame
RUNTIME_CLASS(CScintillaDemoView));
AddDocTemplate(pDocTemplate);
//create main MDI Frame window
CMainFrame* pMainFrame = new CMainFrame;
if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
return FALSE;
m_pMainWnd = pMainFrame;
//Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
//Dispatch commands specified on the command line
if (!ProcessShellCommand(cmdInfo))
return FALSE;
//The main window has been initialized, so show and update it.
pMainFrame->ShowWindow(m_nCmdShow);
pMainFrame->UpdateWindow();
//Enable drag/drop open
m_pMainWnd->DragAcceptFiles();
return TRUE;
}
int CScintillaDemoApp::ExitInstance()
{
//Free up the Scintilla DLL
if (m_hSciDLL)
FreeLibrary(m_hSciDLL);
return CWinApp::ExitInstance();
}
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
//Let the base class do its thing
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
void CScintillaDemoApp::OnAppAbout()
{
CAboutDlg aboutDlg;
aboutDlg.DoModal();
}
| [
"[email protected]"
]
| [
[
[
1,
111
]
]
]
|
f0a1b2cdc5d0af5a3c70898e7f3f35f3f465ff7c | fe7a7f1385a7dd8104e6ccc105f9bb3141c63c68 | /map.cpp | 0107ca95a2922eda97054a1548a7b08c95c3778d | []
| no_license | divinity76/ancient-divinity-ots | d29efe620cea3fe8d61ffd66480cf20c8f77af13 | 0c7b5bfd5b9277c97d28de598f781dbb198f473d | refs/heads/master | 2020-05-16T21:01:29.130756 | 2010-10-11T22:58:07 | 2010-10-11T22:58:07 | 29,501,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,505 | cpp | //////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
//////////////////////////////////////////////////////////////////////
// the map of OpenTibia
//////////////////////////////////////////////////////////////////////
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//////////////////////////////////////////////////////////////////////
#include "otpch.h"
#include "definitions.h"
#include <string>
#include <sstream>
#include <map>
#include <algorithm>
#include <boost/config.hpp>
#include <boost/bind.hpp>
#include "iomap.h"
#include "iomapxml.h"
#include "iomapotbm.h"
#include "iomapserialize.h"
#include <stdio.h>
#include <iomanip>
#include "items.h"
#include "map.h"
#include "tile.h"
#include "combat.h"
#include "creature.h"
#include "player.h"
#include "configmanager.h"
extern ConfigManager g_config;
Map::Map()
{
mapWidth = 0;
mapHeight = 0;
}
Map::~Map()
{
//
}
bool Map::loadMap(const std::string& identifier, const std::string& type)
{
IOMap* loader;
if(type == "XML"){
loader = new IOMapXML();
}
else if(type == "OTBM"){
loader = new IOMapOTBM();
}
else{
std::cout << "FATAL: Could not determine the map format!" << std::endl;
std::cin.get();
return false;
}
std::cout << ":: Loading map from: " << identifier << " " << loader->getSourceDescription() << std::endl;
if(!loader->loadMap(this, identifier)){
std::cout << "FATAL: [OTBM loader] " << loader->getLastErrorString() << std::endl;
std::cin.get();
return false;
}
if(!loader->loadSpawns(this)){
std::cout << "WARNING: could not load spawn data." << std::endl;
}
if(!loader->loadHouses(this)){
std::cout << "WARNING: could not load house data." << std::endl;
}
delete loader;
IOMapSerialize* IOMapSerialize = IOMapSerialize::getInstance();
IOMapSerialize->loadHouseInfo(this);
IOMapSerialize->loadMap(this);
return true;
}
bool Map::saveMap()
{
IOMapSerialize* IOMapSerialize = IOMapSerialize::getInstance();
bool saved = false;
for(uint32_t tries = 0; tries < 3; tries++){
if(IOMapSerialize->saveMap(this)){
saved = true;
break;
}
}
if(!saved)
return false;
saved = false;
for(uint32_t tries = 0; tries < 3; tries++){
if(IOMapSerialize->saveHouseInfo(this)){
saved = true;
break;
}
}
return saved;
}
Tile* Map::getTile(uint16_t x, uint16_t y, uint8_t z)
{
if(z < MAP_MAX_LAYERS){
//QTreeLeafNode* leaf = getLeaf(x, y);
QTreeLeafNode* leaf = QTreeNode::getLeafStatic(&root, x, y);
if(leaf){
Floor* floor = leaf->getFloor(z);
if(floor){
return floor->tiles[x & FLOOR_MASK][y & FLOOR_MASK];
}
else{
return NULL;
}
}
else{
return NULL;
}
}
else{
return NULL;
}
}
Tile* Map::getTile(const Position& pos)
{
return getTile(pos.x, pos.y, pos.z);
}
void Map::setTile(uint16_t x, uint16_t y, uint8_t z, Tile* newtile)
{
if(z >= MAP_MAX_LAYERS) {
std::cout << "ERROR: Attempt to set tile on invalid Z coordinate " << int(z) << "!" << std::endl;
return;
}
QTreeLeafNode::newLeaf = false;
QTreeLeafNode* leaf = root.createLeaf(x, y, 15);
if(QTreeLeafNode::newLeaf){
//update north
QTreeLeafNode* northLeaf = root.getLeaf(x, y - FLOOR_SIZE);
if(northLeaf){
northLeaf->m_leafS = leaf;
}
//update west leaf
QTreeLeafNode* westLeaf = root.getLeaf(x - FLOOR_SIZE, y);
if(westLeaf){
westLeaf->m_leafE = leaf;
}
//update south
QTreeLeafNode* southLeaf = root.getLeaf(x, y + FLOOR_SIZE);
if(southLeaf){
leaf->m_leafS = southLeaf;
}
//update east
QTreeLeafNode* eastLeaf = root.getLeaf(x + FLOOR_SIZE, y);
if(eastLeaf){
leaf->m_leafE = eastLeaf;
}
}
Floor* floor = leaf->createFloor(z);
uint32_t offsetX = x & FLOOR_MASK;
uint32_t offsetY = y & FLOOR_MASK;
if(!floor->tiles[offsetX][offsetY]){
floor->tiles[offsetX][offsetY] = newtile;
newtile->qt_node = leaf;
}
else{
std::cout << "Error: Map::setTile() already exists." << std::endl;
}
if(newtile->hasFlag(TILESTATE_REFRESH)){
RefreshBlock_t rb;
rb.lastRefresh = OTSYS_TIME();
for(ItemVector::iterator it = newtile->downItems.begin(); it != newtile->downItems.end(); ++it){
rb.list.push_back((*it)->clone());
}
refreshTileMap[newtile] = rb;
}
}
bool Map::placeCreature(const Position& centerPos, Creature* creature, bool extendedPos /*=false*/, bool forceLogin /*=false*/)
{
Tile* tile = getTile(centerPos);
bool foundTile = false;
bool placeInPZ = false;
if(tile){
placeInPZ = tile->hasFlag(TILESTATE_PROTECTIONZONE);
ReturnValue ret = tile->__queryAdd(0, creature, 1, FLAG_IGNOREBLOCKITEM);
if(forceLogin || ret == RET_NOERROR || ret == RET_PLAYERISNOTINVITED){
foundTile = true;
}
}
typedef std::pair<int32_t, int32_t> relPair;
std::vector<relPair> relList;
// Extended pos is used when summoning.
// X is player, 1 is first choice, 2 is second choice
// --1--
// -222-
// 12X21
// -222-
// --1--
if(extendedPos) {
relList.push_back(relPair(0, -2));
relList.push_back(relPair(-2, 0));
relList.push_back(relPair(0, 2));
relList.push_back(relPair(2, 0));
std::random_shuffle(relList.begin(), relList.end());
}
relList.push_back(relPair(-1, -1));
relList.push_back(relPair(-1, 0));
relList.push_back(relPair(-1, 1));
relList.push_back(relPair(0, -1));
relList.push_back(relPair(0, 1));
relList.push_back(relPair(1, -1));
relList.push_back(relPair(1, 0));
relList.push_back(relPair(1, 1));
std::random_shuffle(relList.begin() + (extendedPos? 4 : 0), relList.end());
uint32_t radius = 1;
Position tryPos;
for(uint32_t n = 1; n <= radius && !foundTile; ++n){
for(std::vector<relPair>::iterator it = relList.begin(); it != relList.end() && !foundTile; ++it){
int32_t dx = it->first * n;
int32_t dy = it->second * n;
tryPos = centerPos;
tryPos.x = tryPos.x + dx;
tryPos.y = tryPos.y + dy;
tile = getTile(tryPos);
if(!tile || (placeInPZ && !tile->hasFlag(TILESTATE_PROTECTIONZONE)))
continue;
if(tile->__queryAdd(0, creature, 1, 0) == RET_NOERROR){
if(extendedPos) {
if(isSightClear(centerPos, tryPos, false)) {
foundTile = true;
break;
}
} else {
foundTile = true;
break;
}
}
}
}
if(foundTile){
int32_t index = 0;
Item* toItem = NULL;
uint32_t flags = 0;
Cylinder* toCylinder = tile->__queryDestination(index, creature, &toItem, flags);
toCylinder->__internalAddThing(creature);
Tile* toTile = toCylinder->getTile();
toTile->qt_node->addCreature(creature);
return true;
}
#ifdef __DEBUG__
std::cout << "Failed to place creature onto map!" << std::endl;
#endif
return false;
}
bool Map::removeCreature(Creature* creature)
{
Tile* tile = creature->getTile();
if(tile){
tile->qt_node->removeCreature(creature);
tile->__removeThing(creature, 0);
return true;
}
return false;
}
void Map::getSpectatorsInternal(SpectatorVec& list, const Position& centerPos, bool checkforduplicate,
int32_t minRangeX, int32_t maxRangeX,
int32_t minRangeY, int32_t maxRangeY,
int32_t minRangeZ, int32_t maxRangeZ)
{
int32_t minoffset = centerPos.z - maxRangeZ;
int32_t x1 = std::min((int32_t)0xFFFF, std::max((int32_t)0, (centerPos.x + minRangeX + minoffset )));
int32_t y1 = std::min((int32_t)0xFFFF, std::max((int32_t)0, (centerPos.y + minRangeY + minoffset )));
int32_t maxoffset = centerPos.z - minRangeZ;
int32_t x2 = std::min((int32_t)0xFFFF, std::max((int32_t)0, (centerPos.x + maxRangeX + maxoffset )));
int32_t y2 = std::min((int32_t)0xFFFF, std::max((int32_t)0, (centerPos.y + maxRangeY + maxoffset )));
int32_t startx1 = x1 - (x1 % FLOOR_SIZE);
int32_t starty1 = y1 - (y1 % FLOOR_SIZE);
int32_t endx2 = x2 - (x2 % FLOOR_SIZE);
int32_t endy2 = y2 - (y2 % FLOOR_SIZE);
QTreeLeafNode* startLeaf;
QTreeLeafNode* leafE;
QTreeLeafNode* leafS;
startLeaf = getLeaf(startx1, starty1);
leafS = startLeaf;
/*
SpectatorVec oldList;
for(int32_t ny = starty1; ny <= endy2; ny += FLOOR_SIZE){
leafE = leafS;
for(int32_t nx = startx1; nx <= endx2; nx += FLOOR_SIZE){
if(leafE){
Floor* floor;
int32_t offsetZ;
for(int32_t nz = minRangeZ; nz <= maxRangeZ; ++nz){
if((floor = leafE->getFloor(nz))){
//get current floor limits
offsetZ = centerPos.z - nz;
int32_t floorx1 = std::min((int32_t)0xFFFF, std::max((int32_t)0, (centerPos.x + minRangeX + offsetZ)));
int32_t floory1 = std::min((int32_t)0xFFFF, std::max((int32_t)0, (centerPos.y + minRangeY + offsetZ)));
int32_t floorx2 = std::min((int32_t)0xFFFF, std::max((int32_t)0, (centerPos.x + maxRangeX + offsetZ)));
int32_t floory2 = std::min((int32_t)0xFFFF, std::max((int32_t)0, (centerPos.y + maxRangeY + offsetZ)));
for(int ly = 0; ly < FLOOR_SIZE; ++ly){
for(int lx = 0; lx < FLOOR_SIZE; ++lx){
if((nx + lx >= floorx1 && nx + lx <= floorx2) && (ny + ly >= floory1 && ny + ly <= floory2)){
Tile* tile;
if((tile = floor->tiles[(nx + lx) & FLOOR_MASK][(ny + ly) & FLOOR_MASK])){
for(uint32_t i = 0; i < tile->creatures.size(); ++i){
Creature* creature = tile->creatures[i];
if(checkforduplicate) {
if(std::find(oldList.begin(), oldList.end(), creature) == oldList.end()){
oldList.push_back(creature);
}
} else {
oldList.push_back(creature);
}
}
}
}
}
}
}
}
leafE = leafE->stepEast();
}
else{
leafE = getLeaf(nx + FLOOR_SIZE, ny);
}
}
if(leafS){
leafS = leafS->stepSouth();
}
else{
leafS = getLeaf(startx1, ny + FLOOR_SIZE);
}
}
*/
for(int32_t ny = starty1; ny <= endy2; ny += FLOOR_SIZE){
leafE = leafS;
for(int32_t nx = startx1; nx <= endx2; nx += FLOOR_SIZE){
if(leafE){
CreatureVector& node_list = leafE->creature_list;
CreatureVector::const_iterator node_iter = node_list.begin();
CreatureVector::const_iterator node_end = node_list.end();
if(node_iter != node_end){
do{
Creature* creature = *node_iter;
const Position& cpos = creature->getPosition();
int32_t offsetZ = centerPos.z - cpos.z;
if(cpos.z < minRangeZ || cpos.z > maxRangeZ){
continue;
}
if(cpos.y < (centerPos.y + minRangeY + offsetZ) || cpos.y > (centerPos.y + maxRangeY + offsetZ)){
continue;
}
if(cpos.x < (centerPos.x + minRangeX + offsetZ) || cpos.x > (centerPos.x + maxRangeX + offsetZ) ){
continue;
}
if(checkforduplicate){
if(std::find(list.begin(), list.end(), creature) == list.end()){
list.push_back(creature);
}
}
else{
list.push_back(creature);
}
}while(++node_iter != node_end);
}
leafE = leafE->stepEast();
}
else{
leafE = getLeaf(nx + FLOOR_SIZE, ny);
}
}
if(leafS){
leafS = leafS->stepSouth();
}
else{
leafS = getLeaf(startx1, ny + FLOOR_SIZE);
}
}
/*
if(list.size() != oldList.size()){
std::cout << "missmatch size" << std::endl;
}
*/
}
void Map::getSpectators(SpectatorVec& list, const Position& centerPos,
bool checkforduplicate /*= false*/, bool multifloor /*= false*/,
int32_t minRangeX /*= 0*/, int32_t maxRangeX /*= 0*/,
int32_t minRangeY /*= 0*/, int32_t maxRangeY /*= 0*/)
{
bool foundCache = false;
bool cacheResult = false;
if(minRangeX == 0 && maxRangeX == 0 && minRangeY == 0 && maxRangeY == 0 && multifloor == true && checkforduplicate == false) {
SpectatorCache::iterator it = spectatorCache.find(centerPos);
if(it != spectatorCache.end()){
list = *it->second;
foundCache = true;
}
else{
cacheResult = true;
}
}
if(!foundCache){
minRangeX = (minRangeX == 0 ? -maxViewportX : -minRangeX);
maxRangeX = (maxRangeX == 0 ? maxViewportX : maxRangeX);
minRangeY = (minRangeY == 0 ? -maxViewportY : -minRangeY);
maxRangeY = (maxRangeY == 0 ? maxViewportY : maxRangeY);
int32_t minRangeZ;
int32_t maxRangeZ;
if(multifloor){
if(centerPos.z > 7){
//underground
//8->15
minRangeZ = std::max(centerPos.z - 2, 0);
maxRangeZ = std::min(centerPos.z + 2, MAP_MAX_LAYERS - 1);
}
//above ground
else if(centerPos.z == 6){
minRangeZ = 0;
maxRangeZ = 8;
}
else if(centerPos.z == 7){
minRangeZ = 0;
maxRangeZ = 9;
}
else{
minRangeZ = 0;
maxRangeZ = 7;
}
}
else{
minRangeZ = centerPos.z;
maxRangeZ = centerPos.z;
}
getSpectatorsInternal(list, centerPos, true,
minRangeX, maxRangeX,
minRangeY, maxRangeY,
minRangeZ, maxRangeZ);
if(cacheResult){
spectatorCache[centerPos].reset(new SpectatorVec(list));
}
}
}
const SpectatorVec& Map::getSpectators(const Position& centerPos)
{
SpectatorCache::iterator it = spectatorCache.find(centerPos);
if(it != spectatorCache.end()) {
return *it->second;
} else {
boost::shared_ptr<SpectatorVec> p(new SpectatorVec());
spectatorCache[centerPos] = p;
SpectatorVec& list = *p;
int32_t minRangeX = -maxViewportX;
int32_t maxRangeX = maxViewportX;
int32_t minRangeY = -maxViewportY;
int32_t maxRangeY = maxViewportY;
int32_t minRangeZ;
int32_t maxRangeZ;
if(centerPos.z > 7){
//underground
//8->15
minRangeZ = std::max(centerPos.z - 2, 0);
maxRangeZ = std::min(centerPos.z + 2, MAP_MAX_LAYERS - 1);
}
//above ground
else if(centerPos.z == 6){
minRangeZ = 0;
maxRangeZ = 8;
}
else if(centerPos.z == 7){
minRangeZ = 0;
maxRangeZ = 9;
}
else{
minRangeZ = 0;
maxRangeZ = 7;
}
getSpectatorsInternal(list, centerPos, false,
minRangeX, maxRangeX,
minRangeY, maxRangeY,
minRangeZ, maxRangeZ);
return list;
}
}
void Map::clearSpectatorCache()
{
spectatorCache.clear();
}
bool Map::canThrowObjectTo(const Position& fromPos, const Position& toPos, bool checkLineOfSight /*= true*/,
int32_t rangex /*= Map::maxClientViewportX*/, int32_t rangey /*= Map::maxClientViewportY*/)
{
//z checks
//underground 8->15
//ground level and above 7->0
if((fromPos.z >= 8 && toPos.z < 8) || (toPos.z >= 8 && fromPos.z < 8)){
return false;
}
if(fromPos.z - fromPos.z > 2){
return false;
}
int deltax, deltay, deltaz;
deltax = std::abs(fromPos.x - toPos.x);
deltay = std::abs(fromPos.y - toPos.y);
deltaz = std::abs(fromPos.z - toPos.z);
//distance checks
if(deltax - deltaz > rangex || deltay - deltaz > rangey){
return false;
}
if(!checkLineOfSight){
return true;
}
return isSightClear(fromPos, toPos, false);
}
bool Map::checkSightLine(const Position& fromPos, const Position& toPos) const
{
Position start = fromPos;
Position end = toPos;
int x, y, z;
int dx, dy, dz;
int sx, sy, sz;
int ey, ez;
dx = abs(start.x - end.x);
dy = abs(start.y - end.y);
dz = abs(start.z - end.z);
int max = dx, dir = 0;
if(dy > max){
max = dy;
dir = 1;
}
if(dz > max){
max = dz;
dir = 2;
}
switch(dir){
case 0:
//x -> x
//y -> y
//z -> z
break;
case 1:
//x -> y
//y -> x
//z -> z
std::swap(start.x, start.y);
std::swap(end.x, end.y);
std::swap(dx, dy);
break;
case 2:
//x -> z
//y -> y
//z -> x
std::swap(start.x, start.z);
std::swap(end.x, end.z);
std::swap(dx, dz);
break;
}
sx = ((start.x < end.x) ? 1 : -1);
sy = ((start.y < end.y) ? 1 : -1);
sz = ((start.z < end.z) ? 1 : -1);
ey = 0, ez = 0;
x = start.x;
y = start.y;
z = start.z;
int lastrx = x, lastry = y, lastrz = z;
for( ; x != end.x + sx; x += sx){
int rx, ry, rz;
switch(dir){
case 1:
rx = y; ry = x; rz = z;
break;
case 2:
rx = z; ry = y; rz = x;
break;
default: //0
rx = x; ry = y; rz = z;
break;
}
if(!(toPos.x == rx && toPos.y == ry && toPos.z == rz) &&
!(fromPos.x == rx && fromPos.y == ry && fromPos.z == rz)){
if(lastrz != rz){
if(const_cast<Map*>(this)->getTile(lastrx, lastry, std::min(lastrz, rz))){
return false;
}
}
lastrx = rx; lastry = ry; lastrz = rz;
const Tile* tile = const_cast<Map*>(this)->getTile(rx, ry, rz);
if(tile)
{
if(tile->hasProperty(BLOCKPROJECTILE))
{
return false;
}
}
}
ey += dy;
ez += dz;
if(2*ey >= dx){
y += sy;
ey -= dx;
}
if(2*ez >= dx){
z += sz;
ez -= dx;
}
}
return true;
}
bool Map::isSightClear(const Position& fromPos, const Position& toPos, bool floorCheck) const
{
if(floorCheck && fromPos.z != toPos.z){
return false;
}
// Cast two converging rays and see if either yields a result.
return
checkSightLine(fromPos, toPos) ||
checkSightLine(toPos, fromPos);
}
const Tile* Map::canWalkTo(const Creature* creature, const Position& pos)
{
switch(creature->getWalkCache(pos)){
case 0: return NULL;
case 1: return getTile(pos);
break;
}
//used for none-cached tiles
Tile* tile = getTile(pos);
if(creature->getTile() != tile){
if(!tile || tile->__queryAdd(0, creature, 1, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) != RET_NOERROR){
return NULL;
}
}
return tile;
}
bool Map::getPathTo(const Creature* creature, const Position& destPos,
std::list<Direction>& listDir, int32_t maxSearchDist /*= -1*/)
{
if(canWalkTo(creature, destPos) == NULL){
return false;
}
listDir.clear();
Position startPos = destPos;
Position endPos = creature->getPosition();
if(startPos.z != endPos.z){
return false;
}
AStarNodes nodes;
AStarNode* startNode = nodes.createOpenNode();
startNode->x = startPos.x;
startNode->y = startPos.y;
startNode->g = 0;
startNode->h = nodes.getEstimatedDistance(startPos.x, startPos.y, endPos.x, endPos.y);
startNode->f = startNode->g + startNode->h;
startNode->parent = NULL;
Position pos;
pos.z = startPos.z;
static int32_t neighbourOrderList[8][2] =
{
{-1, 0},
{0, 1},
{1, 0},
{0, -1},
//diagonal
{-1, -1},
{1, -1},
{1, 1},
{-1, 1},
};
const Tile* tile = NULL;
AStarNode* found = NULL;
while(maxSearchDist != -1 || nodes.countClosedNodes() < 100){
AStarNode* n = nodes.getBestNode();
if(!n){
listDir.clear();
return false; //no path found
}
if(n->x == endPos.x && n->y == endPos.y){
found = n;
break;
}
else{
for(int i = 0; i < 8; ++i){
pos.x = n->x + neighbourOrderList[i][0];
pos.y = n->y + neighbourOrderList[i][1];
bool outOfRange = false;
if(maxSearchDist != -1 && (std::abs(endPos.x - pos.x) > maxSearchDist ||
std::abs(endPos.y - pos.y) > maxSearchDist) ){
outOfRange = true;
}
if(!outOfRange && (tile = canWalkTo(creature, pos))){
//The cost (g) for this neighbour
int32_t cost = nodes.getMapWalkCost(creature, n, tile, pos);
int32_t extraCost = nodes.getTileWalkCost(creature, tile);
int32_t newg = n->g + cost + extraCost;
//Check if the node is already in the closed/open list
//If it exists and the nodes already on them has a lower cost (g) then we can ignore this neighbour node
AStarNode* neighbourNode = nodes.getNodeInList(pos.x, pos.y);
if(neighbourNode){
if(neighbourNode->g <= newg){
//The node on the closed/open list is cheaper than this one
continue;
}
nodes.openNode(neighbourNode);
}
else{
//Does not exist in the open/closed list, create a new node
neighbourNode = nodes.createOpenNode();
if(!neighbourNode){
//seems we ran out of nodes
listDir.clear();
return false;
}
}
//This node is the best node so far with this state
neighbourNode->x = pos.x;
neighbourNode->y = pos.y;
neighbourNode->parent = n;
neighbourNode->g = newg;
neighbourNode->h = nodes.getEstimatedDistance(neighbourNode->x, neighbourNode->y,
endPos.x, endPos.y);
neighbourNode->f = neighbourNode->g + neighbourNode->h;
}
}
nodes.closeNode(n);
}
}
int32_t prevx = endPos.x;
int32_t prevy = endPos.y;
int32_t dx, dy;
while(found){
pos.x = found->x;
pos.y = found->y;
found = found->parent;
dx = pos.x - prevx;
dy = pos.y - prevy;
prevx = pos.x;
prevy = pos.y;
if(dx == -1 && dy == -1){
listDir.push_back(NORTHWEST);
}
else if(dx == 1 && dy == -1){
listDir.push_back(NORTHEAST);
}
else if(dx == -1 && dy == 1){
listDir.push_back(SOUTHWEST);
}
else if(dx == 1 && dy == 1){
listDir.push_back(SOUTHEAST);
}
else if(dx == -1){
listDir.push_back(WEST);
}
else if(dx == 1){
listDir.push_back(EAST);
}
else if(dy == -1){
listDir.push_back(NORTH);
}
else if(dy == 1){
listDir.push_back(SOUTH);
}
}
return !listDir.empty();
}
bool Map::getPathMatching(const Creature* creature, std::list<Direction>& dirList,
const FrozenPathingConditionCall& pathCondition, const FindPathParams& fpp)
{
dirList.clear();
Position startPos = creature->getPosition();
Position endPos;
AStarNodes nodes;
AStarNode* startNode = nodes.createOpenNode();
startNode->x = startPos.x;
startNode->y = startPos.y;
startNode->f = 0;
startNode->parent = NULL;
Position pos;
pos.z = startPos.z;
int32_t bestMatch = 0;
static int32_t neighbourOrderList[8][2] = {
{-1, 0},
{0, 1},
{1, 0},
{0, -1},
//diagonal
{-1, -1},
{1, -1},
{1, 1},
{-1, 1},
};
const Tile* tile = NULL;
AStarNode* found = NULL;
while(fpp.maxSearchDist != -1 || nodes.countClosedNodes() < 100){
AStarNode* n = nodes.getBestNode();
if(!n){
if(found){
//not quite what we want, but we found something
break;
}
dirList.clear();
return false; //no path found
}
if(pathCondition(startPos, Position(n->x, n->y, startPos.z), fpp, bestMatch)){
found = n;
endPos = Position(n->x, n->y, startPos.z);
if(bestMatch == 0){
break;
}
}
int32_t dirCount = (fpp.allowDiagonal ? 8 : 4);
for(int32_t i = 0; i < dirCount; ++i){
pos.x = n->x + neighbourOrderList[i][0];
pos.y = n->y + neighbourOrderList[i][1];
bool inRange = true;
if(fpp.maxSearchDist != -1 && (std::abs(startPos.x - pos.x) > fpp.maxSearchDist ||
std::abs(startPos.y - pos.y) > fpp.maxSearchDist) ){
inRange = false;
}
if(fpp.keepDistance){
if(!pathCondition.isInRange(startPos, pos, fpp)){
inRange = false;
}
}
if(inRange && (tile = canWalkTo(creature, pos))){
//The cost (g) for this neighbour
int32_t cost = nodes.getMapWalkCost(creature, n, tile, pos);
int32_t extraCost = nodes.getTileWalkCost(creature, tile);
int32_t newf = n->f + cost + extraCost;
//Check if the node is already in the closed/open list
//If it exists and the nodes already on them has a lower cost (g) then we can ignore this neighbour node
AStarNode* neighbourNode = nodes.getNodeInList(pos.x, pos.y);
if(neighbourNode){
if(neighbourNode->f <= newf){
//The node on the closed/open list is cheaper than this one
continue;
}
nodes.openNode(neighbourNode);
}
else{
//Does not exist in the open/closed list, create a new node
neighbourNode = nodes.createOpenNode();
if(!neighbourNode){
if(found){
//not quite what we want, but we found something
break;
}
//seems we ran out of nodes
dirList.clear();
return false;
}
}
//This node is the best node so far with this state
neighbourNode->x = pos.x;
neighbourNode->y = pos.y;
neighbourNode->parent = n;
neighbourNode->f = newf;
}
}
nodes.closeNode(n);
}
int32_t prevx = endPos.x;
int32_t prevy = endPos.y;
int32_t dx, dy;
if(!found){
return false;
}
found = found->parent;
while(found){
pos.x = found->x;
pos.y = found->y;
dx = pos.x - prevx;
dy = pos.y - prevy;
prevx = pos.x;
prevy = pos.y;
if(dx == 1 && dy == 1){
dirList.push_front(NORTHWEST);
}
else if(dx == -1 && dy == 1){
dirList.push_front(NORTHEAST);
}
else if(dx == 1 && dy == -1){
dirList.push_front(SOUTHWEST);
}
else if(dx == -1 && dy == -1){
dirList.push_front(SOUTHEAST);
}
else if(dx == 1){
dirList.push_front(WEST);
}
else if(dx == -1){
dirList.push_front(EAST);
}
else if(dy == 1){
dirList.push_front(NORTH);
}
else if(dy == -1){
dirList.push_front(SOUTH);
}
found = found->parent;
}
return true;
}
//*********** AStarNodes *************
AStarNodes::AStarNodes()
{
curNode = 0;
openNodes.reset();
}
AStarNode* AStarNodes::createOpenNode()
{
if(curNode >= MAX_NODES){
return NULL;
}
uint32_t ret_node = curNode;
curNode++;
openNodes[ret_node] = 1;
return &nodes[ret_node];
}
AStarNode* AStarNodes::getBestNode()
{
if(curNode == 0)
return NULL;
int best_node_f = 100000;
uint32_t best_node = 0;
bool found = false;
for(uint32_t i = 0; i < curNode; i++){
if(nodes[i].f < best_node_f && openNodes[i] == 1){
found = true;
best_node_f = nodes[i].f;
best_node = i;
}
}
if(found){
return &nodes[best_node];
}
return NULL;
}
void AStarNodes::closeNode(AStarNode* node)
{
uint32_t pos = GET_NODE_INDEX(node);
if(pos >= MAX_NODES){
assert(pos >= MAX_NODES);
std::cout << "AStarNodes. trying to close node out of range" << std::endl;
return;
}
openNodes[pos] = 0;
}
void AStarNodes::openNode(AStarNode* node)
{
uint32_t pos = GET_NODE_INDEX(node);
if(pos >= MAX_NODES){
assert(pos >= MAX_NODES);
std::cout << "AStarNodes. trying to open node out of range" << std::endl;
return;
}
openNodes[pos] = 1;
}
uint32_t AStarNodes::countClosedNodes()
{
uint32_t counter = 0;
for(uint32_t i = 0; i < curNode; i++){
if(openNodes[i] == 0){
counter++;
}
}
return counter;
}
uint32_t AStarNodes::countOpenNodes()
{
uint32_t counter = 0;
for(uint32_t i = 0; i < curNode; i++){
if(openNodes[i] == 1){
counter++;
}
}
return counter;
}
bool AStarNodes::isInList(int32_t x, int32_t y)
{
for(uint32_t i = 0; i < curNode; i++){
if(nodes[i].x == x && nodes[i].y == y){
return true;
}
}
return false;
}
AStarNode* AStarNodes::getNodeInList(int32_t x, int32_t y)
{
for(uint32_t i = 0; i < curNode; i++){
if(nodes[i].x == x && nodes[i].y == y){
return &nodes[i];
}
}
return NULL;
}
int32_t AStarNodes::getMapWalkCost(const Creature* creature, AStarNode* node,
const Tile* neighbourTile, const Position& neighbourPos)
{
int cost = 0;
if(std::abs((int)node->x - neighbourPos.x) == std::abs((int)node->y - neighbourPos.y)){
//diagonal movement extra cost
cost = MAP_DIAGONALWALKCOST;
}
else{
cost = MAP_NORMALWALKCOST;
}
return cost;
}
int32_t AStarNodes::getTileWalkCost(const Creature* creature, const Tile* tile)
{
int cost = 0;
if(!tile->creatures.empty()){
//destroy creature cost
cost += MAP_NORMALWALKCOST * 3;
}
if(const MagicField* field = tile->getFieldItem()){
if(!creature->isImmune(field->getCombatType())){
cost += MAP_NORMALWALKCOST * 3;
}
}
return cost;
}
int AStarNodes::getEstimatedDistance(int32_t x, int32_t y, int32_t xGoal, int32_t yGoal)
{
int h_diagonal = std::min(std::abs(x - xGoal), std::abs(y - yGoal));
int h_straight = (std::abs(x - xGoal) + std::abs(y - yGoal));
return MAP_DIAGONALWALKCOST * h_diagonal + MAP_NORMALWALKCOST * (h_straight - 2 * h_diagonal);
//return (std::abs(x - xGoal) + std::abs(y - yGoal)) * MAP_NORMALWALKCOST;
}
//*********** Floor constructor **************
Floor::Floor()
{
for(unsigned int i = 0; i < FLOOR_SIZE; ++i){
for(unsigned int j = 0; j < FLOOR_SIZE; ++j){
tiles[i][j] = 0;
}
}
}
//**************** QTreeNode **********************
QTreeNode::QTreeNode()
{
m_isLeaf = false;
m_child[0] = NULL;
m_child[1] = NULL;
m_child[2] = NULL;
m_child[3] = NULL;
}
QTreeNode::~QTreeNode()
{
delete m_child[0];
delete m_child[1];
delete m_child[2];
delete m_child[3];
}
QTreeLeafNode* QTreeNode::getLeaf(uint32_t x, uint32_t y)
{
if(!isLeaf()){
uint32_t index = ((x & 0x8000) >> 15) | ((y & 0x8000) >> 14);
if(m_child[index]){
return m_child[index]->getLeaf(x*2, y*2);
}
else{
return NULL;
}
}
else{
return static_cast<QTreeLeafNode*>(this);
}
}
QTreeLeafNode* QTreeNode::getLeafStatic(QTreeNode* root, uint32_t x, uint32_t y)
{
QTreeNode* currentNode = root;
uint32_t currentX = x, currentY = y;
while(currentNode){
if(!currentNode->isLeaf()){
uint32_t index = ((currentX & 0x8000) >> 15) | ((currentY & 0x8000) >> 14);
if(currentNode->m_child[index]){
currentNode = currentNode->m_child[index];
currentX = currentX*2;
currentY = currentY*2;
}
else{
return NULL;
}
}
else{
return static_cast<QTreeLeafNode*>(currentNode);
}
}
return NULL;
}
QTreeLeafNode* QTreeNode::createLeaf(uint32_t x, uint32_t y, uint32_t level)
{
if(!isLeaf()){
uint32_t index = ((x & 0x8000) >> 15) | ((y & 0x8000) >> 14);
if(!m_child[index]){
if(level != FLOOR_BITS){
m_child[index] = new QTreeNode();
}
else{
m_child[index] = new QTreeLeafNode();
QTreeLeafNode::newLeaf = true;
}
}
return m_child[index]->createLeaf(x*2, y*2, level - 1);
}
else{
return static_cast<QTreeLeafNode*>(this);
}
}
//************ LeafNode ************************
bool QTreeLeafNode::newLeaf = false;
QTreeLeafNode::QTreeLeafNode()
{
for(unsigned int i = 0; i < MAP_MAX_LAYERS; ++i){
m_array[i] = NULL;
}
m_isLeaf = true;
m_leafS = NULL;
m_leafE = NULL;
}
QTreeLeafNode::~QTreeLeafNode()
{
for(unsigned int i = 0; i < MAP_MAX_LAYERS; ++i){
delete m_array[i];
}
}
Floor* QTreeLeafNode::createFloor(uint32_t z)
{
if(!m_array[z]){
m_array[z] = new Floor();
}
return m_array[z];
}
| [
"[email protected]@6be3b30e-f956-11de-ba51-6b4196a2b81e"
]
| [
[
[
1,
1333
]
]
]
|
1104e840f9f7106c0ea0efc60c6c9e8f99b4b38b | 920f766fe36acd51410160bb0332c83ed38da4c7 | /phase2/cue.cpp | f203c120e85650a582cdb091165659389f734585 | []
| no_license | shaikuf/hagiga-basnooker | 4b302f9c969e119204291655bedb419b89f2cd31 | 7eb329bcf000ee8b29f22410a9b3a14ab8963abd | refs/heads/master | 2016-09-06T00:58:14.129776 | 2010-06-07T14:12:38 | 2010-06-07T14:12:38 | 41,489,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,593 | cpp | #include <iostream>
#include <cv.h>
#include <highgui.h>
#include "cue.h"
#include "misc.h"
#include <vector>
#include "linear.h"
#include "windows.h"
using namespace std;
double line2theta(double cue_m, CvPoint cue_cm, CvPoint white_center) {
double theta;
if(isinf(cue_m)) { // perpendicular line
if(cue_cm.y < white_center.y)
theta = 3*PI/2;
else
theta = PI/2;
} else { // non-perpendicular line
theta = atan(cue_m);
if(cue_cm.x < white_center.x) {
if(cue_cm.y < white_center.y) {
// quarter 2
theta = 2*PI - theta;
} else {
// quarter 3
theta = 2*PI - theta;
}
} else {
if(cue_cm.y < white_center.y) {
// quarter 1
theta = PI - theta;
} else {
// quarter 4
theta = PI - theta;
}
}
}
// mod 2*PI;
theta = theta;
if(theta >= 2*PI)
theta -= 2*PI;
if(theta < 0)
theta += 2*PI;
return theta;
}
bool findCueWithAllMarkers(IplImage *src, CvPoint white_center, double *theta,
vector<CvPoint> *ball_centers, int ball_count) {
/* THESE FUNCTION IS NOT COMPLETE. IN THE END WE DECIDED TO GO ONLY WITH
WHITE BLOBS, AFTER SWITCHING TO TOTAL LEAST SQUARES REGRESSION MODEL,
USING THE GLOVE AND PLAYING WITH THE PARAMETERS */
// find the blobs
vector<CvPoint> whites = findBlobs(src, ball_centers, ball_count, true);
vector<CvPoint> blacks = findBlobs(src, ball_centers, ball_count, false);
// create grayscale image
IplImage* gray = createBlankCopy(src, 1);
cvCvtColor(src, gray, CV_BGR2GRAY);
paintHolesBlack(gray);
// paint the balls black so they wont be found
for(int i=0; i<ball_count; i++) {
for(unsigned int j=0; j<ball_centers[i].size(); j++) {
cvCircle(gray, ball_centers[i][j],
1, cvScalar(0), BALL_DIAMETER_FOR_CUE_FINDING);
}
}
// set ROI
CvRect roi = tableBordersBoundingRect(-10);
cvSetImageROI(gray, roi);
// =========================== DEBUG
IplImage* color = createBlankCopy(gray, 3);
cvCvtColor(gray, color, CV_GRAY2BGR);
for(unsigned i=0; i<whites.size(); i++) {
cvCircle(color, cvPoint((int)whites[i].x - roi.x,
(int)whites[i].y - roi.y), 1, cvScalar(255, 0, 0), 3);
}
for(unsigned i=0; i<blacks.size(); i++) {
cvCircle(color, cvPoint((int)blacks[i].x - roi.x,
(int)blacks[i].y - roi.y), 1, cvScalar(0, 0, 255), 3);
}
cvNamedWindow("cue");
cvShowImage("cue", color);
// =========================== DEBUG
//whites.insert(whites.begin(), white_center);
// for every two white points
vector<CvPoint>::iterator i, j, k;
for(i = whites.begin(); i != whites.end(); i++) {
vector<CvPoint> tmp;
tmp.push_back(white_center);
tmp.push_back(*i);
double m_a, m_b, m_coeff;
for(j = i+1; j != whites.end(); j++) {
// fit these two points and the white ball
tmp.push_back(*j);
linearRegression(tmp, &m_a, &m_b, &m_coeff);
if(m_coeff > CUE_MIN_COEFF) {
// this is actually a line
// check if there's a black close to it
for(k = blacks.begin(); k != blacks.end(); k++) {
}
}
tmp.pop_back();
}
}
cvReleaseImage(&gray);
cvReleaseImage(&color);
return false;
}
vector<CvPoint> findBlobs(IplImage *src, vector<CvPoint> *ball_centers,
int ball_count, bool white) {
// set relevant ROI
CvRect roi = tableBordersBoundingRect((white)?
CUE_BLOB_MAX_DIST_FROM_TABLE_WHITE:\
CUE_BLOB_MAX_DIST_FROM_TABLE_BLACK);
// create grayscale image
IplImage* gray = createBlankCopy(src, 1);
cvCvtColor(src, gray, CV_BGR2GRAY);
if(!white) // if looking for black -- inverse
cvAbsDiffS(gray, gray, cvScalar(255));
paintHolesBlack(gray);
// paint the balls black so they wont be found
for(int i=0; i<ball_count; i++) {
for(unsigned int j=0; j<ball_centers[i].size(); j++) {
cvCircle(gray, ball_centers[i][j],
1, cvScalar(0), BALL_DIAMETER_FOR_CUE_FINDING);
}
}
cvSetImageROI(gray, roi);
// threshold to leave only white markers
IplImage* thresh = createBlankCopy(gray);
cvThreshold(gray, thresh, CUE_THRESH_VAL, 255, CV_THRESH_BINARY);
// morphological operations:
IplImage *morph = cvCloneImage(thresh);
IplImage *morph_marked = 0;
// remove small objects
cvErode(morph, morph, 0, (white)?CUE_OPENING_VAL_WHITE:\
CUE_OPENING_VAL_BLACK);
cvDilate(morph, morph, 0, (white)?CUE_OPENING_VAL_WHITE:\
CUE_OPENING_VAL_BLACK);
// merge large objects
cvDilate(morph, morph, 0, (white)?CUE_CLOSING_VAL_WHITE:\
CUE_CLOSING_VAL_BLACK);
cvErode(morph, morph, 0, (white)?CUE_CLOSING_VAL_WHITE:\
CUE_CLOSING_VAL_BLACK);
// find the contours
IplImage* temp = cvCloneImage(morph);
CvMemStorage *mem_storage = cvCreateMemStorage(0);
CvSeq* contours = NULL;
// actually find the contours
CvContourScanner scanner = cvStartFindContours(temp, mem_storage, \
sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
// filter/approximate the blobs
CvSeq* c;
int numCont = 0;
while( (c = cvFindNextContour( scanner )) != NULL ) {
double len = cvContourPerimeter( c );
if( len > ((white)?CUE_BLOB_MAX_SIZE_WHITE:\
CUE_BLOB_MAX_SIZE_BLACK) ) { // get rid of big blobs
cvSubstituteContour( scanner, NULL );
} else { // polynomial approximation
CvSeq* c_new;
c_new = cvApproxPoly(c, sizeof(CvContour), mem_storage,
CV_POLY_APPROX_DP, 1, 0);
cvSubstituteContour( scanner, c_new );
numCont++;
}
}
contours = cvEndFindContours( &scanner );
// find the blob centers
int i;
vector<CvPoint> centers;
CvMoments moments;
double M00, M01, M10;
for(i=0, c=contours; c != NULL; c = c->h_next, i++) {
cvContourMoments(c, &moments);
M00 = cvGetSpatialMoment(&moments,0,0);
M10 = cvGetSpatialMoment(&moments,1,0);
M01 = cvGetSpatialMoment(&moments,0,1);
// put in the output array
centers.push_back(cvPoint((int)(M10/M00) + roi.x,
(int)(M01/M00) + roi.y));
}
// release stuff
cvReleaseMemStorage(&mem_storage);
cvReleaseImage(&gray);
cvReleaseImage(&thresh);
cvReleaseImage(&morph);
cvReleaseImage(&morph_marked);
cvReleaseImage(&temp);
return centers;
}
bool findCueWithWhiteMarkers(IplImage *src, CvPoint white_center, double *theta,
vector<CvPoint> *ball_centers, int balls_count) {
static bool once = true;
if(once && CUE_FIND_DEBUG) {
cvNamedWindow("gray");
cvNamedWindow("threshold");
cvNamedWindow("morphed");
cvNamedWindow("morphed-marked");
once = false;
}
CvRect roi = tableBordersBoundingRect(CUE_BLOB_MAX_DIST_FROM_TABLE_WHITE);
// create grayscale image
IplImage* gray = createBlankCopy(src, 1);
cvCvtColor(src, gray, CV_BGR2GRAY);
paintHolesBlack(gray);
// paint the balls black so they wont be found
for(int i=0; i<balls_count; i++) {
for(unsigned int j=0; j<ball_centers[i].size(); j++) {
cvCircle(gray, ball_centers[i][j],
1, cvScalar(0), BALL_DIAMETER_FOR_CUE_FINDING);
}
}
cvSetImageROI(gray, roi);
white_center.x -= roi.x;
white_center.y -= roi.y;
if(CUE_FIND_DEBUG) {
cvShowImage("gray", gray);
}
// threshold to leave only white markers
IplImage* thresh = createBlankCopy(gray);
cvThreshold(gray, thresh, CUE_THRESH_VAL, 255, CV_THRESH_BINARY);
if(CUE_FIND_DEBUG) {
cvShowImage("threshold", thresh);
}
// morphological operations:
IplImage *morph = cvCloneImage(thresh);
IplImage *morph_marked = 0;
// remove small objects
cvErode(morph, morph, 0, CUE_OPENING_VAL_WHITE);
cvDilate(morph, morph, 0, CUE_OPENING_VAL_WHITE);
// merge large objects
cvDilate(morph, morph, 0, CUE_CLOSING_VAL_WHITE);
cvErode(morph, morph, 0, CUE_CLOSING_VAL_WHITE);
if(CUE_FIND_DEBUG) {
cvShowImage("morphed", morph);
morph_marked = createBlankCopy(morph, 3);
cvSet(morph_marked, cvScalar(255, 255, 255), morph);
}
// find the contours
IplImage* temp = cvCloneImage(morph);
CvMemStorage *mem_storage = cvCreateMemStorage(0);
CvSeq* contours = NULL;
// actually find the contours
CvContourScanner scanner = cvStartFindContours(temp, mem_storage, \
sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
// filter/approximate the blobs
CvSeq* c;
int numCont = 0;
while( (c = cvFindNextContour( scanner )) != NULL ) {
double len = cvContourPerimeter( c );
if( len > CUE_BLOB_MAX_SIZE_WHITE ) { // get rid of big blobs
cvSubstituteContour( scanner, NULL );
} else { // polynomial approximation
CvSeq* c_new;
c_new = cvApproxPoly(c, sizeof(CvContour), mem_storage,
CV_POLY_APPROX_DP, 1, 0);
cvSubstituteContour( scanner, c_new );
numCont++;
}
}
contours = cvEndFindContours( &scanner );
// find the blob centers
int i;
vector<CvPoint2D32f> centers;
CvMoments moments;
double M00, M01, M10;
for(i=0, c=contours; c != NULL; c = c->h_next, i++) {
cvContourMoments(c, &moments);
M00 = cvGetSpatialMoment(&moments,0,0);
M10 = cvGetSpatialMoment(&moments,1,0);
M01 = cvGetSpatialMoment(&moments,0,1);
centers.push_back(cvPoint2D32f((M10/M00),(M01/M00)));
}
// lose the far points (from the white ball)
vector<CvPoint2D32f>::iterator itr;
for(itr = centers.begin(); itr != centers.end();) {
if(dist(white_center, cvPoint((int)itr->x, (int)itr->y)) > MAX_BLOB_DIST_FROM_WHITE) {
itr = centers.erase(itr);
} else {
itr++;
}
}
// mark them on the debug image
if(CUE_FIND_DEBUG) {
for(unsigned i=0; i<centers.size(); i++) {
cvCircle(morph_marked, cvPoint((int)centers[i].x,
(int)centers[i].y), 1, cvScalar(0, 255, 255), 3);
}
}
// find the points with best linear regression
double cue_n;
double cue_m;
CvPoint cue_cm;
vector<CvPoint> real_centers = findPointsOnLineWith(white_center, centers, CUE_MIN_COEFF,
&cue_m, &cue_n, &cue_cm);
// perhaps filter the line
bool found_cue = true;
if(cue_cm.x == -1) { // did we even find one?
found_cue = false;
} else { // check if the line is around the white ball
double d;
if((d = distFromLine(white_center.x, white_center.y, cue_n, cue_m)) >
CUE_MAX_DIST_FROM_WHITE) {
// ignore this cue
found_cue = false;
}
if(CUE_FIND_DEBUG) {
cout<<"dist from white: "<<d<<endl;
}
}
// paint debug image
if(CUE_FIND_DEBUG && cue_cm.x != -1) {
for(i=0; i < (int)real_centers.size(); i++) {
if(found_cue) {
cvCircle(src, cvPoint(real_centers[i].x+roi.x, real_centers[i].y+roi.y), 1,
cvScalar(255, 0, 0), 3);
cvCircle(morph_marked, cvPoint(real_centers[i].x, real_centers[i].y), 1,
cvScalar(255, 0, 0), 3);
} else {
cvCircle(src, cvPoint(real_centers[i].x+roi.x, real_centers[i].y+roi.y), 1,
cvScalar(0, 0, 255), 3);
cvCircle(morph_marked, cvPoint(real_centers[i].x, real_centers[i].y), 1,
cvScalar(0, 0, 255), 3);
}
}
}
// calculate the angle
if(found_cue) {
*theta = line2theta(cue_m, cue_cm, white_center);
}
if(CUE_FIND_DEBUG) {
if(cue_cm.x != -1) {
*theta = line2theta(cue_m, cue_cm, white_center);
int len = 350;
cvLine(morph_marked,
cvPoint((int)(cue_cm.x - len), (int)(cue_cm.y -len*cue_m)),
cvPoint((int)(cue_cm.x + len), (int)(cue_cm.y + len*cue_m)),
cvScalar(0, 255, 0));
cout<<"angle = "<<*theta * 180/PI<<endl;
}
cvShowImage("morphed-marked", morph_marked);
}
// release stuff
cvReleaseMemStorage(&mem_storage);
cvReleaseImage(&gray);
cvReleaseImage(&thresh);
cvReleaseImage(&morph);
cvReleaseImage(&morph_marked);
cvReleaseImage(&temp);
return found_cue;
}
double smoothTheta(double new_theta) {
static bool once;
// get the current time
FILETIME now;
GetSystemTimeAsFileTime(&now);
__int64 now_i = ((__int64)now.dwHighDateTime << 32) + now.dwLowDateTime;
// keep a vector of the thetas still in our time window
typedef pair<double, __int64> theta_time;
static vector<theta_time> last_samples;
// filter old thetas
vector<theta_time>::iterator itr = last_samples.begin();
while(last_samples.size() > 0) {
if(now_i - (__int64)(itr->second) > CUE_SMOOTH_WINDOWS) {
last_samples.erase(itr);
itr = last_samples.begin();
} else {
break;
}
}
// insert the new theta
last_samples.push_back(theta_time(new_theta, now_i));
// calculate the smoothed theta
double mean_theta = 0;
for(itr = last_samples.begin(); itr != last_samples.end(); itr++)
mean_theta += itr->first;
return mean_theta/last_samples.size();
}
| [
"c1ph3r.il@9f8e2b2e-e8c3-11de-b92f-5d3588262692"
]
| [
[
[
1,
466
]
]
]
|
141b85a496fff99627b641bb96b15cb96b672d90 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/multi_array/test/concept_checks.cpp | 48135f424faf2897c6c33a2f04d15255a97f0792 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,399 | cpp | // Copyright 2002 The Trustees of Indiana University.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Boost.MultiArray Library
// Authors: Ronald Garcia
// Jeremy Siek
// Andrew Lumsdaine
// See http://www.boost.org/libs/multi_array for documentation.
//
// concept_checks.cpp -
// make sure the types meet concept requirements
//
#include "boost/concept_check.hpp"
#include "boost/multi_array/concept_checks.hpp"
#include "boost/multi_array.hpp"
#include "boost/cstdlib.hpp"
#define BOOST_INCLUDE_MAIN
#include "boost/test/test_tools.hpp"
#include "boost/array.hpp"
int
test_main(int,char*[])
{
const int ndims=3;
typedef boost::multi_array<int,ndims> array;
typedef boost::multi_array_ref<int,ndims> array_ref;
typedef boost::const_multi_array_ref<int,ndims> const_array_ref;
typedef array::array_view<ndims>::type array_view;
typedef array::const_array_view<ndims>::type const_array_view;
typedef array::subarray<ndims>::type subarray;
typedef array::const_subarray<ndims>::type const_subarray;
boost::function_requires<
boost::detail::multi_array::ConstMultiArrayConcept<array,ndims> >();
boost::function_requires<
boost::detail::multi_array::ConstMultiArrayConcept<array_ref,ndims> >();
boost::function_requires<
boost::detail::multi_array::ConstMultiArrayConcept<const_array_ref,ndims> >();
boost::function_requires<
boost::detail::multi_array::ConstMultiArrayConcept<array_view,ndims> >();
boost::function_requires<
boost::detail::multi_array::ConstMultiArrayConcept<const_array_view,ndims> >();
boost::function_requires<
boost::detail::multi_array::ConstMultiArrayConcept<subarray,ndims> >();
boost::function_requires<
boost::detail::multi_array::ConstMultiArrayConcept<const_subarray,ndims> >();
boost::function_requires<
boost::detail::multi_array::MutableMultiArrayConcept<array,ndims> >();
boost::function_requires<
boost::detail::multi_array::MutableMultiArrayConcept<array_ref,ndims> >();
boost::function_requires<
boost::detail::multi_array::MutableMultiArrayConcept<array_view,ndims> >();
boost::function_requires<
boost::detail::multi_array::MutableMultiArrayConcept<subarray,ndims> >();
return 0;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
65
]
]
]
|
e10aa192271551c1a99cdc259206b4449ff54e7b | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/WorkLayer/ServerList.cpp | 94aa88730bed156b5c9d85e85073c4ad965bba7d | []
| no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 34,578 | cpp | //this file is part of eMule
//Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either
//version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include <io.h>
#include <share.h>
#include "emule.h"
#include "ServerList.h"
#include "SafeFile.h"
#include "Exceptions.h"
#include "OtherFunctions.h"
#include "IPFilter.h"
#include "LastCommonRouteFinder.h"
#include "Statistics.h"
#include "DownloadQueue.h"
#include "Preferences.h"
#include "Opcodes.h"
#include "Server.h"
#include "Sockets.h"
#include "Packets.h"
#include "emuledlg.h"
#include "HttpDownloadDlg.h"
#include "ServerWnd.h"
#include "Log.h"
#include ".\serverlist.h"
#include "GlobalVariable.h"
#include "UIMessage.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define SERVER_MET_FILENAME _T("server.met")
CServerList::CServerList()
{
servercount = 0;
version = 0;
serverpos = 0;
searchserverpos = 0;
statserverpos = 0;
delservercount = 0;
m_nLastSaved = ::GetTickCount();
}
CServerList::~CServerList()
{
SaveServermetToFile();
for (POSITION pos = list.GetHeadPosition(); pos != NULL; )
delete list.GetNext(pos);
}
//EastShare Start - added by AndCycle, IP to Country
void CServerList::ResetIP2Country(){
CServer *cur_server;
for(POSITION pos = list.GetHeadPosition(); pos != NULL; list.GetNext(pos)){
cur_server = list.GetAt(pos);
cur_server->ResetIP2Country();
}
}
//EastShare End - added by AndCycle, IP to Country
void CServerList::AutoUpdate()
{
if (thePrefs.addresses_list.IsEmpty()){
// Comment UI
//AfxMessageBox(GetResString(IDS_ERR_EMPTYADRESSESDAT), MB_ICONASTERISK);
return;
}
bool bDownloaded = false;
CString servermetdownload;
CString servermetbackup;
CString servermet;
CString strURLToDownload;
servermetdownload.Format(_T("%sserver_met.download"), thePrefs.GetMuleDirectory(EMULE_CONFIGDIR));
servermetbackup.Format(_T("%sserver_met.old"), thePrefs.GetMuleDirectory(EMULE_CONFIGDIR));
servermet.Format(_T("%s") SERVER_MET_FILENAME, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR));
(void)_tremove(servermetbackup);
(void)_tremove(servermetdownload);
(void)_trename(servermet, servermetbackup);
POSITION Pos = thePrefs.addresses_list.GetHeadPosition();
while (!bDownloaded && Pos != NULL)
{
// TODO: Comment UI, 移动到emuledlg中去做..
CHttpDownloadDlg dlgDownload;
dlgDownload.m_strTitle = GetResString(IDS_HTTP_CAPTION);
strURLToDownload = thePrefs.addresses_list.GetNext(Pos);
dlgDownload.m_sURLToDownload = strURLToDownload;
dlgDownload.m_sFileToDownloadInto = servermetdownload;
if (dlgDownload.DoModal() == IDOK)
bDownloaded = true;
else
LogError(LOG_STATUSBAR, GetResString(IDS_ERR_FAILEDDOWNLOADMET), strURLToDownload);
}
if (bDownloaded) {
(void)_trename(servermet, servermetdownload);
(void)_trename(servermetbackup, servermet);
}
else {
(void)_tremove(servermet);
(void)_trename(servermetbackup, servermet);
}
}
bool CServerList::Init()
{
// auto update the list by using an url
if (thePrefs.GetAutoUpdateServerList())
AutoUpdate();
// Load Metfile
CString strPath;
strPath.Format(_T("%s") SERVER_MET_FILENAME, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR));
bool bRes = AddServerMetToList(strPath, false);
if (thePrefs.GetAutoUpdateServerList())
{
strPath.Format(_T("%sserver_met.download"), thePrefs.GetMuleDirectory(EMULE_CONFIGDIR));
bool bRes2 = AddServerMetToList(strPath, true);
if (!bRes && bRes2)
bRes = true;
}
// insert static servers from textfile
strPath.Format(_T("%sstaticservers.dat"), thePrefs.GetMuleDirectory(EMULE_CONFIGDIR));
AddServersFromTextFile(strPath);
CGlobalVariable::serverlist->GiveServersForTraceRoute();
return bRes;
}
bool CServerList::AddServerMetToList(const CString& strFile, bool bMerge)
{
if (!bMerge)
{
// Comment UI
//theApp.emuledlg->serverwnd->serverlistctrl.DeleteAllItems();
RemoveAllServers();
}
CSafeBufferedFile servermet;
CFileException fexp;
if (!servermet.Open(strFile ,CFile::modeRead|CFile::osSequentialScan|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){
if (!bMerge){
// Comment UI
/*CString strError(GetResString(IDS_ERR_LOADSERVERMET));
TCHAR szError[MAX_CFEXP_ERRORMSG];
if (fexp.GetErrorMessage(szError,ARRSIZE(szError))){
strError += _T(" - ");
strError += szError;
}
LogError(LOG_STATUSBAR, _T("%s"), strError);*/
}
return false;
}
setvbuf(servermet.m_pStream, NULL, _IOFBF, 16384);
try{
version = servermet.ReadUInt8();
if (version != 0xE0 && version != MET_HEADER){
servermet.Close();
// Comment UI
//LogError(LOG_STATUSBAR,GetResString(IDS_ERR_BADSERVERMETVERSION), version);
return false;
}
// Comment UI
/*theApp.emuledlg->serverwnd->serverlistctrl.Hide();
theApp.emuledlg->serverwnd->serverlistctrl.SetRedraw(FALSE);*/
UINT fservercount = servermet.ReadUInt32();
ServerMet_Struct sbuffer;
UINT iAddCount = 0;
for (UINT j = 0; j < fservercount; j++)
{
// get server
servermet.Read(&sbuffer, sizeof(ServerMet_Struct));
CServer* newserver = new CServer(&sbuffer);
// add tags
for (UINT i = 0; i < sbuffer.tagcount; i++)
newserver->AddTagFromFile(&servermet);
if (bMerge) {
// If we are merging a (downloaded) server list into our list, ignore the priority of the
// server -- some server list providers are doing a poor job with this and offering lists
// with dead servers set to 'High'..
newserver->SetPreference(SRV_PR_NORMAL);
}
// set listname for server
if (newserver->GetListName().IsEmpty())
newserver->SetListName(newserver->GetAddress());
// Comment UI
if(! ::SendMessage(CGlobalVariable::m_hListenWnd, WM_SERVER_ADD_SVR, (WPARAM)newserver, 0x0101))
{
delete newserver;
}
else iAddCount++;
/*if (!theApp.emuledlg->serverwnd->serverlistctrl.AddServer(newserver, true))
{
CServer* update = CGlobalVariable::serverlist->GetServerByAddress(newserver->GetAddress(), newserver->GetPort());
if (update)
{
update->SetListName(newserver->GetListName());
update->SetDescription(newserver->GetDescription());
theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(update);
}
delete newserver;
}
else
iAddCount++;*/
}
// Comment UI
/*if (!bMerge)
AddLogLine(true,GetResString(IDS_SERVERSFOUND), fservercount);
else
AddLogLine(true,GetResString(IDS_SERVERSADDED), iAddCount, fservercount - iAddCount);*/
servermet.Close();
}
catch(CFileException* error){
if (error->m_cause == CFileException::endOfFile){
// Comment UI
//LogError(LOG_STATUSBAR, GetResString(IDS_ERR_BADSERVERLIST));
}
else{
TCHAR buffer[MAX_CFEXP_ERRORMSG];
error->GetErrorMessage(buffer, ARRSIZE(buffer));
// Comment UI
//LogError(LOG_STATUSBAR, GetResString(IDS_ERR_FILEERROR_SERVERMET),buffer);
}
error->Delete();
}
// Comment UI
/*theApp.emuledlg->serverwnd->serverlistctrl.SetRedraw(TRUE);
theApp.emuledlg->serverwnd->serverlistctrl.Visable();*/
return true;
}
bool CServerList::AddServer(const CServer* pServer)
{
if (!IsGoodServerIP(pServer)){ // check for 0-IP, localhost and optionally for LAN addresses
if (thePrefs.GetLogFilteredIPs())
AddDebugLogLine(false, _T("Filtered server \"%s\" (IP=%s) - Invalid IP or LAN address."), pServer->GetListName(), ipstr(pServer->GetIP()));
return false;
}
if (thePrefs.GetFilterServerByIP()){
// IP-Filter: We don't need to reject dynIP-servers here. After the DN was
// resolved, the IP will get filtered and the server will get removed. This applies
// for TCP-connections as well as for outgoing UDP-packets because for both protocols
// we resolve the DN and filter the received IP.
//if (pServer->HasDynIP())
// return false;
// Comment UI
/*if (CGlobalVariable::ipfilter->IsFiltered(pServer->GetIP())){
if (thePrefs.GetLogFilteredIPs())
AddDebugLogLine(false, _T("Filtered server \"%s\" (IP=%s) - IP filter (%s)"), pServer->GetListName(), ipstr(pServer->GetIP()), CGlobalVariable::ipfilter->GetLastHit());
return false;
}*/
}
CServer* pFoundServer = GetServerByAddress(pServer->GetAddress(), pServer->GetPort());
// Avoid duplicate (dynIP) servers: If the server which is to be added, is a dynIP-server
// but we don't know yet it's DN, we need to search for an already available server with
// that IP.
if (pFoundServer == NULL && pServer->GetIP() != 0)
pFoundServer = GetServerByIPTCP(pServer->GetIP(), pServer->GetPort());
if (pFoundServer){
pFoundServer->ResetFailedCount();
// Comment UI
//theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pFoundServer);
UINotify(WM_SERVER_REFRESH, 0, (LPARAM)pFoundServer, pFoundServer);
return false;
}
list.AddTail(const_cast<CServer*>(pServer));
return true;
}
bool CServerList::GiveServersForTraceRoute()
{
// Comment UI
return CGlobalVariable::lastCommonRouteFinder->AddHostsToCheck(list);
// return false;
}
void CServerList::ServerStats()
{
// Update the server list even if we are connected to Kademlia only. The idea is for both networks to keep
// each other up to date.. Kad network can get you back into the ED2K network.. And the ED2K network can get
// you back into the Kad network..
// Comment UI
if (CGlobalVariable::IsConnected() && CGlobalVariable::serverconnect->IsUDPSocketAvailable() && list.GetCount() > 0)
{
CServer* ping_server = GetNextStatServer();
if (!ping_server)
return;
uint32 tNow = (uint32)time(NULL);
const CServer* test = ping_server;
while (ping_server->GetLastPingedTime() != 0 && (tNow - ping_server->GetLastPingedTime()) < UDPSERVSTATREASKTIME)
{
ping_server = GetNextStatServer();
if (ping_server == test)
return;
}
// IP-filter: We do not need to IP-filter any servers here, even dynIP-servers are not
// needed to get filtered here. See also comments in 'CServerSocket::ConnectTo'.
if (ping_server->GetFailedCount() >= thePrefs.GetDeadServerRetries()) {
// Comment UI
//theApp.emuledlg->serverwnd->serverlistctrl.RemoveServer(ping_server);
return;
}
srand(tNow);
ping_server->SetRealLastPingedTime(tNow); // this is not used to calcualte the next ping, but only to ensure a minimum delay for premature pings
if (!ping_server->GetCryptPingReplyPending() && (tNow - ping_server->GetLastPingedTime()) >= UDPSERVSTATREASKTIME && CGlobalVariable::GetPublicIP() != 0 && thePrefs.IsServerCryptLayerUDPEnabled()){
// we try a obfsucation ping first and wait 20 seconds for an answer
// if it doesn'T get responsed, we don't count it as error but continue with a normal ping
ping_server->SetCryptPingReplyPending(true);
uint32 nPacketLen = 4 + (uint8)(rand() % 16); // max padding 16 bytes
BYTE* pRawPacket = new BYTE[nPacketLen];
uint32 dwChallenge = (rand() << 17) | (rand() << 2) | (rand() & 0x03);
if (dwChallenge == 0)
dwChallenge++;
PokeUInt32(pRawPacket, dwChallenge);
for (uint32 i = 4; i < nPacketLen; i++) // fillung up the remaining bytes with random data
pRawPacket[i] = (uint8)rand();
ping_server->SetChallenge(dwChallenge);
ping_server->SetLastPinged(GetTickCount());
ping_server->SetLastPingedTime((tNow - (uint32)UDPSERVSTATREASKTIME) + 20); // give it 20 seconds to respond
if (thePrefs.GetDebugServerUDPLevel() > 0)
Debug(_T(">>> Sending OP__GlobServStatReq (obfuscated) to server %s:%u\n"), ping_server->GetAddress(), ping_server->GetPort());
theStats.AddUpDataOverheadServer(nPacketLen);
CGlobalVariable::serverconnect->SendUDPPacket(NULL, ping_server, true, ping_server->GetPort() + 12, pRawPacket, nPacketLen);
}
else if (ping_server->GetCryptPingReplyPending() || CGlobalVariable::GetPublicIP() == 0 || !thePrefs.IsServerCryptLayerUDPEnabled()){
// our obfsucation ping request was not answered, so probably the server doesn'T supports obfuscation
// continue with a normal request
if (ping_server->GetCryptPingReplyPending() && thePrefs.IsServerCryptLayerUDPEnabled())
DEBUG_ONLY(DebugLog(_T("CryptPing failed for server %s"), ping_server->GetListName()));
else if (thePrefs.IsServerCryptLayerUDPEnabled())
DEBUG_ONLY(DebugLog(_T("CryptPing skipped because our public IP is unknown for server %s"), ping_server->GetListName()));
ping_server->SetCryptPingReplyPending(false);
Packet* packet = new Packet(OP_GLOBSERVSTATREQ, 4);
uint32 uChallenge = 0x55AA0000 + GetRandomUInt16();
ping_server->SetChallenge(uChallenge);
PokeUInt32(packet->pBuffer, uChallenge);
ping_server->SetLastPinged(GetTickCount());
ping_server->SetLastPingedTime(tNow - (rand() % HR2S(1)));
ping_server->AddFailedCount();
// Comment UI
//theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(ping_server);
UINotify(WM_SERVER_REFRESH, 0, (LPARAM)ping_server, ping_server);
if (thePrefs.GetDebugServerUDPLevel() > 0)
Debug(_T(">>> Sending OP__GlobServStatReq (not obfuscated) to server %s:%u\n"), ping_server->GetAddress(), ping_server->GetPort());
theStats.AddUpDataOverheadServer(packet->size);
CGlobalVariable::serverconnect->SendUDPPacket(packet, ping_server, true);
}
else
ASSERT( false );
}
}
bool CServerList::IsGoodServerIP(const CServer* pServer) const
{
if (pServer->HasDynIP())
return true;
return IsGoodIPPort(pServer->GetIP(), pServer->GetPort());
}
void CServerList::RemoveServer(const CServer* pServer)
{
for (POSITION pos = list.GetHeadPosition(); pos != NULL; )
{
POSITION pos2 = pos;
const CServer* test_server = list.GetNext(pos);
if (test_server == pServer){
if (CGlobalVariable::downloadqueue->cur_udpserver == pServer)
CGlobalVariable::downloadqueue->cur_udpserver = NULL;
list.RemoveAt(pos2);
delservercount++;
delete test_server;
return;
}
}
}
void CServerList::RemoveAllServers()
{
for (POSITION pos = list.GetHeadPosition(); pos != NULL; ){
delete list.GetNext(pos);
delservercount++;
}
list.RemoveAll();
}
void CServerList::GetStatus(uint32& total, uint32& failed,
uint32& user, uint32& file, uint32& lowiduser,
uint32& totaluser, uint32& totalfile,
float& occ) const
{
total = list.GetCount();
failed = 0;
user = 0;
file = 0;
totaluser = 0;
totalfile = 0;
occ = 0;
lowiduser = 0;
uint32 maxuserknownmax = 0;
uint32 totaluserknownmax = 0;
for (POSITION pos = list.GetHeadPosition(); pos != 0; ){
const CServer* curr = list.GetNext(pos);
if (curr->GetFailedCount()){
failed++;
}
else{
user += curr->GetUsers();
file += curr->GetFiles();
lowiduser += curr->GetLowIDUsers();
}
totaluser += curr->GetUsers();
totalfile += curr->GetFiles();
if (curr->GetMaxUsers()){
totaluserknownmax += curr->GetUsers(); // total users on servers with known maximum
maxuserknownmax += curr->GetMaxUsers();
}
}
if (maxuserknownmax > 0)
occ = (float)(totaluserknownmax * 100) / maxuserknownmax;
}
void CServerList::GetAvgFile(uint32& average) const
{
//Since there is no real way to know how many files are in the kad network,
//I figure to try to use the ED2K network stats to find how many files the
//average user shares..
uint32 totaluser = 0;
uint32 totalfile = 0;
for (POSITION pos = list.GetHeadPosition(); pos != 0; ){
const CServer* curr = list.GetNext(pos);
//If this server has reported Users/Files and doesn't limit it's files too much
//use this in the calculation..
if( curr->GetUsers() && curr->GetFiles() && curr->GetSoftFiles() > 1000 )
{
totaluser += curr->GetUsers();
totalfile += curr->GetFiles();
}
}
//If the user count is a little low, don't send back a average..
//I added 50 to the count as many servers do not allow a large amount of files to be shared..
//Therefore the extimate here will be lower then the actual.
//I would love to add a way for the client to send some statistics back so we could see the real
//values here..
if ( totaluser > 500000 )
average = (totalfile/totaluser)+50;
else
average = 0;
}
void CServerList::GetUserFileStatus(uint32& user, uint32& file) const
{
user = 0;
file = 0;
for (POSITION pos = list.GetHeadPosition(); pos != 0; ){
const CServer* curr = list.GetNext(pos);
if( !curr->GetFailedCount() ){
user += curr->GetUsers();
file += curr->GetFiles();
}
}
}
void CServerList::MoveServerDown(const CServer* pServer)
{
POSITION pos1, pos2;
int i = 0;
for (pos1 = list.GetHeadPosition(); (pos2 = pos1) != NULL; ) {
list.GetNext(pos1);
CServer* cur_server = list.GetAt(pos2);
if (cur_server == pServer) {
list.AddTail(cur_server);
list.RemoveAt(pos2);
return;
}
i++;
if (i == list.GetCount())
break;
}
}
void CServerList::Sort()
{
POSITION pos1, pos2;
int i = 0;
for (pos1 = list.GetHeadPosition(); (pos2 = pos1) != NULL; ) {
list.GetNext(pos1);
CServer* cur_server = list.GetAt(pos2);
if (cur_server->GetPreference() == SRV_PR_HIGH) {
list.AddHead(cur_server);
list.RemoveAt(pos2);
}
else if (cur_server->GetPreference() == SRV_PR_LOW) {
list.AddTail(cur_server);
list.RemoveAt(pos2);
}
i++;
if (i == list.GetCount())
break;
}
}
void CServerList::GetUserSortedServers()
{
// Comment UI
/*CServerListCtrl& serverListCtrl = theApp.emuledlg->serverwnd->serverlistctrl;
ASSERT( serverListCtrl.GetItemCount() == list.GetCount() );
list.RemoveAll();
int iServers = serverListCtrl.GetItemCount();
for (int i = 0; i < iServers; i++)
list.AddTail((CServer*)serverListCtrl.GetItemData(i));*/
}
#ifdef _DEBUG
void CServerList::Dump()
{
int i = 1;
POSITION pos = list.GetHeadPosition();
while (pos)
{
const CServer* pServer = list.GetNext(pos);
TRACE(_T("%3u: Pri=%s \"%s\"\n"), i, pServer->GetPreference() == SRV_PR_HIGH ? _T("Hi") : (pServer->GetPreference() == SRV_PR_LOW ? _T("Lo") : _T("No")), pServer->GetListName());
i++;
}
}
#endif
void CServerList::SetServerPosition(UINT newPosition)
{
if (newPosition < (UINT)list.GetCount())
serverpos = newPosition;
else
serverpos = 0;
}
CServer* CServerList::GetNextServer(bool bOnlyObfuscated)
{
if (serverpos >= (UINT)list.GetCount())
return NULL;
CServer* nextserver = NULL;
int i = 0;
while (!nextserver && i < list.GetCount()){
POSITION posIndex = list.FindIndex(serverpos);
if (posIndex == NULL) { // check if search position is still valid (could be corrupted by server delete operation)
posIndex = list.GetHeadPosition();
serverpos = 0;
}
serverpos++;
i++;
if (!bOnlyObfuscated || ((CServer*)list.GetAt(posIndex))->SupportsObfuscationTCP())
nextserver = list.GetAt(posIndex);
else if (serverpos >= (UINT)list.GetCount())
return NULL;
}
return nextserver;
}
CServer* CServerList::GetNextSearchServer()
{
CServer* nextserver = NULL;
int i = 0;
while (!nextserver && i < list.GetCount()){
POSITION posIndex = list.FindIndex(searchserverpos);
if (posIndex == NULL) { // check if search position is still valid (could be corrupted by server delete operation)
posIndex = list.GetHeadPosition();
searchserverpos = 0;
}
nextserver = list.GetAt(posIndex);
searchserverpos++;
i++;
if (searchserverpos == (UINT)list.GetCount())
searchserverpos = 0;
}
return nextserver;
}
CServer* CServerList::GetNextStatServer()
{
CServer* nextserver = NULL;
int i = 0;
while (!nextserver && i < list.GetCount()){
POSITION posIndex = list.FindIndex(statserverpos);
if (posIndex == NULL) { // check if search position is still valid (could be corrupted by server delete operation)
posIndex = list.GetHeadPosition();
statserverpos = 0;
}
nextserver = list.GetAt(posIndex);
statserverpos++;
i++;
if (statserverpos == (UINT)list.GetCount())
statserverpos = 0;
}
return nextserver;
}
CServer* CServerList::GetSuccServer(const CServer* lastserver) const
{
if (list.IsEmpty())
return NULL;
if (!lastserver)
return list.GetHead();
POSITION pos = list.Find(const_cast<CServer*>(lastserver));
if (!pos)
return list.GetHead();
list.GetNext(pos);
if (!pos)
return NULL;
return list.GetAt(pos);
}
CServer* CServerList::GetServerByAddress(LPCTSTR address, uint16 port) const
{
for (POSITION pos = list.GetHeadPosition();pos != 0;){
CServer* s = list.GetNext(pos);
if ((port == s->GetPort() || port == 0) && !_tcscmp(s->GetAddress(), address))
return s;
}
return NULL;
}
CServer* CServerList::GetServerByIP(uint32 nIP) const
{
for (POSITION pos = list.GetHeadPosition();pos != 0;){
CServer* s = list.GetNext(pos);
if (s->GetIP() == nIP)
return s;
}
return NULL;
}
CServer* CServerList::GetServerByIPTCP(uint32 nIP, uint16 nTCPPort) const
{
for (POSITION pos = list.GetHeadPosition();pos != 0;){
CServer* s = list.GetNext(pos);
if (s->GetIP() == nIP && s->GetPort() == nTCPPort)
return s;
}
return NULL;
}
CServer* CServerList::GetServerByIPUDP(uint32 nIP, uint16 nUDPPort, bool bObfuscationPorts) const
{
for (POSITION pos = list.GetHeadPosition();pos != 0;){
CServer* s = list.GetNext(pos);
if (s->GetIP() == nIP && (s->GetPort() == nUDPPort-4 ||
(bObfuscationPorts && (s->GetObfuscationPortUDP() == nUDPPort) || (s->GetPort() == nUDPPort - 12))))
return s;
}
return NULL;
}
bool CServerList::SaveServermetToFile()
{
if (thePrefs.GetLogFileSaving())
AddDebugLogLine(false, _T("Saving servers list file \"%s\""), SERVER_MET_FILENAME);
m_nLastSaved = ::GetTickCount();
CString newservermet(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR));
newservermet += SERVER_MET_FILENAME _T(".new");
CSafeBufferedFile servermet;
CFileException fexp;
if (!servermet.Open(newservermet, CFile::modeWrite|CFile::modeCreate|CFile::typeBinary|CFile::shareDenyWrite, &fexp)){
// Comment UI
/*CString strError(GetResString(IDS_ERR_SAVESERVERMET));
TCHAR szError[MAX_CFEXP_ERRORMSG];
if (fexp.GetErrorMessage(szError, ARRSIZE(szError))){
strError += _T(" - ");
strError += szError;
}
LogError(LOG_STATUSBAR, _T("%s"), strError);*/
return false;
}
setvbuf(servermet.m_pStream, NULL, _IOFBF, 16384);
try{
servermet.WriteUInt8(0xE0);
UINT fservercount = list.GetCount();
servermet.WriteUInt32(fservercount);
for (UINT j = 0; j < fservercount; j++)
{
const CServer* nextserver = GetServerAt(j);
// don't write potential out-dated IPs of dynIP-servers
servermet.WriteUInt32(nextserver->HasDynIP() ? 0 : nextserver->GetIP());
servermet.WriteUInt16(nextserver->GetPort());
UINT uTagCount = 0;
ULONG uTagCountFilePos = (ULONG)servermet.GetPosition();
servermet.WriteUInt32(uTagCount);
if (!nextserver->GetListName().IsEmpty()){
if (WriteOptED2KUTF8Tag(&servermet, nextserver->GetListName(), ST_SERVERNAME))
uTagCount++;
CTag servername(ST_SERVERNAME, nextserver->GetListName());
servername.WriteTagToFile(&servermet);
uTagCount++;
}
if (!nextserver->GetDynIP().IsEmpty()){
if (WriteOptED2KUTF8Tag(&servermet, nextserver->GetDynIP(), ST_DYNIP))
uTagCount++;
CTag serverdynip(ST_DYNIP, nextserver->GetDynIP());
serverdynip.WriteTagToFile(&servermet);
uTagCount++;
}
if (!nextserver->GetDescription().IsEmpty()){
if (WriteOptED2KUTF8Tag(&servermet, nextserver->GetDescription(), ST_DESCRIPTION))
uTagCount++;
CTag serverdesc(ST_DESCRIPTION, nextserver->GetDescription());
serverdesc.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetFailedCount()){
CTag serverfail(ST_FAIL, nextserver->GetFailedCount());
serverfail.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetPreference() != SRV_PR_NORMAL){
CTag serverpref(ST_PREFERENCE, nextserver->GetPreference());
serverpref.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetUsers()){
CTag serveruser("users", nextserver->GetUsers());
serveruser.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetFiles()){
CTag serverfiles("files", nextserver->GetFiles());
serverfiles.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetPing()){
CTag serverping(ST_PING, nextserver->GetPing());
serverping.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetLastPingedTime()){
CTag serverlastp(ST_LASTPING, nextserver->GetLastPingedTime());
serverlastp.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetMaxUsers()){
CTag servermaxusers(ST_MAXUSERS, nextserver->GetMaxUsers());
servermaxusers.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetSoftFiles()){
CTag softfiles(ST_SOFTFILES, nextserver->GetSoftFiles());
softfiles.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetHardFiles()){
CTag hardfiles(ST_HARDFILES, nextserver->GetHardFiles());
hardfiles.WriteTagToFile(&servermet);
uTagCount++;
}
if (!nextserver->GetVersion().IsEmpty()){
// as long as we don't receive an integer version tag from the local server (TCP) we store it as string
CTag version(ST_VERSION, nextserver->GetVersion());
version.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetUDPFlags()){
CTag tagUDPFlags(ST_UDPFLAGS, nextserver->GetUDPFlags());
tagUDPFlags.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetLowIDUsers()){
CTag tagLowIDUsers(ST_LOWIDUSERS, nextserver->GetLowIDUsers());
tagLowIDUsers.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetServerKeyUDP(true)){
CTag tagServerKeyUDP(ST_UDPKEY, nextserver->GetServerKeyUDP(true));
tagServerKeyUDP.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetServerKeyUDPIP()){
CTag tagServerKeyUDPIP(ST_UDPKEYIP, nextserver->GetServerKeyUDPIP());
tagServerKeyUDPIP.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetObfuscationPortTCP()){
CTag tagObfuscationPortTCP(ST_TCPPORTOBFUSCATION, nextserver->GetObfuscationPortTCP());
tagObfuscationPortTCP.WriteTagToFile(&servermet);
uTagCount++;
}
if (nextserver->GetObfuscationPortUDP()){
CTag tagObfuscationPortUDP(ST_UDPPORTOBFUSCATION, nextserver->GetObfuscationPortUDP());
tagObfuscationPortUDP.WriteTagToFile(&servermet);
uTagCount++;
}
servermet.Seek(uTagCountFilePos, CFile::begin);
servermet.WriteUInt32(uTagCount);
servermet.SeekToEnd();
}
// Comment UI
/*if (thePrefs.GetCommitFiles() >= 2 || (thePrefs.GetCommitFiles() >= 1 && !theApp.emuledlg->IsRunning())){
servermet.Flush(); // flush file stream buffers to disk buffers
if (_commit(_fileno(servermet.m_pStream)) != 0) // commit disk buffers to disk
AfxThrowFileException(CFileException::hardIO, GetLastError(), servermet.GetFileName());
}*/
servermet.Close();
CString curservermet(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR));
CString oldservermet(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR));
curservermet += SERVER_MET_FILENAME;
oldservermet += _T("server_met.old");
if (_taccess(oldservermet, 0) == 0)
CFile::Remove(oldservermet);
if (_taccess(curservermet, 0) == 0)
CFile::Rename(curservermet,oldservermet);
CFile::Rename(newservermet,curservermet);
}
catch(CFileException* error) {
// Comment UI
/*CString strError(GetResString(IDS_ERR_SAVESERVERMET2));
TCHAR szError[MAX_CFEXP_ERRORMSG];
if (error->GetErrorMessage(szError, ARRSIZE(szError))){
strError += _T(" - ");
strError += szError;
}
LogError(LOG_STATUSBAR, _T("%s"), strError);*/
error->Delete();
return false;
}
return true;
}
void CServerList::AddServersFromTextFile(const CString& strFilename)
{
CStdioFile f;
if (!f.Open(strFilename, CFile::modeRead | CFile::typeText | CFile::shareDenyWrite))
return;
CString strLine;
while (f.ReadString(strLine))
{
// format is host:port,priority,Name
if (strLine.GetLength() < 5)
continue;
if (strLine.GetAt(0) == _T('#') || strLine.GetAt(0) == _T('/'))
continue;
// fetch host
int pos = strLine.Find(_T(':'));
if (pos == -1){
pos = strLine.Find(_T(','));
if (pos == -1)
continue;
}
CString strHost = strLine.Left(pos);
strLine = strLine.Mid(pos+1);
// fetch port
pos = strLine.Find(_T(','));
if (pos == -1)
continue;
CString strPort = strLine.Left(pos);
strLine = strLine.Mid(pos+1);
// Barry - fetch priority
pos = strLine.Find(_T(','));
int priority = SRV_PR_HIGH;
if (pos == 1)
{
CString strPriority = strLine.Left(pos);
priority = _tstoi(strPriority);
if (priority < 0 || priority > 2)
priority = SRV_PR_HIGH;
strLine = strLine.Mid(pos+1);
}
// fetch name
CString strName = strLine;
strName.Remove(_T('\r'));
strName.Remove(_T('\n'));
// create server object and add it to the list
CServer* nsrv = new CServer((uint16)_tstoi(strPort), strHost);
nsrv->SetListName(strName);
nsrv->SetIsStaticMember(true);
nsrv->SetPreference(priority);
if(! ::SendMessage(CGlobalVariable::m_hListenWnd, WM_SERVER_ADD_SVR, (WPARAM)nsrv, 0x0101))
{
delete nsrv;
}
// Comment UI
/*if (!theApp.emuledlg->serverwnd->serverlistctrl.AddServer(nsrv, true))
{
delete nsrv;
CServer* srvexisting = GetServerByAddress(strHost, (uint16)_tstoi(strPort));
if (srvexisting) {
srvexisting->SetListName(strName);
srvexisting->SetIsStaticMember(true);
srvexisting->SetPreference(priority);
if (theApp.emuledlg->serverwnd)
theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(srvexisting);
}
}*/
}
f.Close();
}
bool CServerList::SaveStaticServers()
{
bool bResult = false;
FILE* fpStaticServers = _tfsopen(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("staticservers.dat"), _T("w"), _SH_DENYWR);
if (fpStaticServers == NULL) {
// Comment UI
//LogError(LOG_STATUSBAR, GetResString(IDS_ERROR_SSF));
return bResult;
}
bResult = true;
POSITION pos = list.GetHeadPosition();
while (pos)
{
const CServer* pServer = list.GetNext(pos);
if (pServer->IsStaticMember())
{
if (_ftprintf(fpStaticServers, _T("%s:%i,%i,%s\n"), pServer->GetAddress(), pServer->GetPort(), pServer->GetPreference(), pServer->GetListName()) == EOF) {
bResult = false;
break;
}
}
}
fclose(fpStaticServers);
return bResult;
}
void CServerList::Process()
{
if (::GetTickCount() - m_nLastSaved > MIN2MS(17))
SaveServermetToFile();
}
int CServerList::GetPositionOfServer(const CServer* pServer) const
{
int iPos = -1;
for (POSITION pos = list.GetHeadPosition(); pos != NULL; ){
iPos++;
if (pServer == list.GetNext(pos))
break;
}
return iPos;
}
void CServerList::RemoveDuplicatesByAddress(const CServer* pExceptThis)
{
POSITION pos = list.GetHeadPosition();
while (pos)
{
CServer* pServer = list.GetNext(pos);
if (pServer == pExceptThis)
continue;
if ( _tcsicmp(pServer->GetAddress(), pExceptThis->GetAddress()) == 0
&& pServer->GetPort() == pExceptThis->GetPort())
{
// Comment UI
//theApp.emuledlg->serverwnd->serverlistctrl.RemoveServer(pServer);
return;
}
}
}
void CServerList::RemoveDuplicatesByIP(const CServer* pExceptThis)
{
POSITION pos = list.GetHeadPosition();
while (pos)
{
CServer* pServer = list.GetNext(pos);
if (pServer == pExceptThis)
continue;
if (pServer->GetIP() == pExceptThis->GetIP() && pServer->GetPort() == pExceptThis->GetPort())
{
// Comment UI
//theApp.emuledlg->serverwnd->serverlistctrl.RemoveServer(pServer);
return;
}
}
}
void CServerList::CheckForExpiredUDPKeys() {
if (!thePrefs.IsServerCryptLayerUDPEnabled())
return;
// uint32 cKeysTotal = 0;
// uint32 cKeysExpired = 0;
// uint32 cPingDelayed = 0;
// Comment UI
/*const uint32 dwIP = CGlobalVariable::GetPublicIP();
const uint32 tNow = (uint32)time(NULL);
ASSERT( dwIP != 0 );
for (POSITION pos = list.GetHeadPosition();pos != 0;){
CServer* pServer = list.GetNext(pos);
if (pServer->SupportsObfuscationUDP() && pServer->GetServerKeyUDP(true) != 0 && pServer->GetServerKeyUDPIP() != dwIP){
cKeysTotal++;
cKeysExpired++;
if (tNow - pServer->GetRealLastPingedTime() < UDPSERVSTATMINREASKTIME){
cPingDelayed++;
// next ping: Now + (MinimumDelay - already elapsed time)
pServer->SetLastPingedTime((tNow - (uint32)UDPSERVSTATREASKTIME) + (UDPSERVSTATMINREASKTIME - (tNow - pServer->GetRealLastPingedTime())));
}
else
pServer->SetLastPingedTime(0);
}
else if (pServer->SupportsObfuscationUDP() && pServer->GetServerKeyUDP(false) != 0)
cKeysTotal++;
}
DebugLog(_T("Possible IP Change - Checking for expired Server UDP-Keys: %u UDP Keys total, %u UDP Keys expired, %u immediate UDP Pings forced, %u delayed UDP Pings forced"),
cKeysTotal, cKeysExpired, cKeysExpired - cPingDelayed, cPingDelayed); */
} | [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
]
| [
[
[
1,
1083
]
]
]
|
147cd0a48b938e44743c9c6d354273d728b8f94b | 3ec3b97044e4e6a87125470cfa7eef535f26e376 | /darkbits-secret_of_fantasy_2/src/SplashScreen2.cpp | 1e75d0b545324a4af91dfdffc44fa0eec7201e5f | []
| no_license | strategist922/TINS-Is-not-speedhack-2010 | 6d7a43ebb9ab3b24208b3a22cbcbb7452dae48af | 718b9d037606f0dbd9eb6c0b0e021eeb38c011f9 | refs/heads/master | 2021-01-18T14:14:38.724957 | 2010-10-17T14:04:40 | 2010-10-17T14:04:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,556 | cpp | #include "Precompiled.hpp"
#include "SplashScreen2.hpp"
#include "Music.hpp"
#include "Resource.hpp"
SplashScreen2::SplashScreen2()
: Screen(false),
myFrameCounter(0)
{
myDarkbitsLogo = Resource::getBitmap("data/images/darkbitslogo.bmp");
myDarkbitsLogoBlackAndWhite = Resource::getBitmap("data/images/darkbitslogo_black_and_white.bmp");
myDarkbitsLogoGlow = Resource::getBitmap("data/images/darkbitslogo_glow.bmp");
mySoftware2010 = Resource::getBitmap("data/images/software_2010.bmp");
myDarkbitsLogoBlink = Resource::getBitmap("data/images/darkbitslogo_blink.bmp");
}
void SplashScreen2::onLogic()
{
myFrameCounter++;
if (myFrameCounter < 50)
return;
if (myFrameCounter == 51)
{
Music::playSong("data/music/splash2.xm");
}
if (myFrameCounter == 650)
{
Music::stop();
}
if (myFrameCounter > 700)
{
exit();
return;
}
}
void SplashScreen2::onDraw(BITMAP* aBuffer)
{
int flashStart = 100;
int flashEnd = 120;
if (myFrameCounter < flashStart
|| myFrameCounter > 650)
{
clear_to_color(aBuffer, 0);
return;
}
if ((myFrameCounter < flashEnd && myFrameCounter % 5 < 2))
{
masked_blit(myDarkbitsLogoBlackAndWhite, aBuffer,
0,
0,
0,
0,
myDarkbitsLogo->w,
myDarkbitsLogo->h);
}
else if (myFrameCounter < flashEnd && myFrameCounter % 5 >= 2
|| myFrameCounter >= flashEnd)
{
if (myFrameCounter > 140 && myFrameCounter < 200)
{
static int x = 0;
masked_blit(myDarkbitsLogoGlow,
aBuffer,
0,
0,
(x * 6) - 120,
0,
myDarkbitsLogo->w,
myDarkbitsLogo->h);
x++;
}
else
{
clear_to_color(aBuffer, makecol(166, 166, 166));
}
masked_blit(myDarkbitsLogo,
aBuffer,
0,
0,
0,
0,
myDarkbitsLogo->w,
myDarkbitsLogo->h);
}
else
{
clear_to_color(aBuffer, 0);
}
if ((myFrameCounter > 290 && myFrameCounter < 330 && rand() % 3 == 0)
|| myFrameCounter >= 330)
masked_blit(mySoftware2010,
aBuffer,
0,
0,
320 / 2 - mySoftware2010->w / 2,
180,
mySoftware2010->w,
mySoftware2010->h);
if (myFrameCounter > 190 && myFrameCounter < 200)
masked_blit(myDarkbitsLogoBlink, aBuffer, 0, 0, 70, 67, myDarkbitsLogoBlink->w, myDarkbitsLogoBlink->h);
if (myFrameCounter > 210 && myFrameCounter < 220)
masked_blit(myDarkbitsLogoBlink, aBuffer, 0, 0, 263, 114, myDarkbitsLogoBlink->w, myDarkbitsLogoBlink->h);
} | [
"[email protected]"
]
| [
[
[
1,
112
]
]
]
|
543b6d64e7730861317c409b98405cb188161a6a | 3d7d8969d540b99a1e53e00c8690e32e4d155749 | /EngSrc/IEThreadEngine.cpp | e551917705badbdba2d4c1afdb75403eff03aa74 | []
| no_license | SymbianSource/oss.FCL.sf.incubator.photobrowser | 50c4ea7142102068f33fc62e36baab9d14f348f9 | 818b5857895d2153c4cdd653eb0e10ba6477316f | refs/heads/master | 2021-01-11T02:45:51.269916 | 2010-10-15T01:18:29 | 2010-10-15T01:18:29 | 70,931,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,875 | cpp | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors: Juha Kauppinen, Mika Hokkanen
*
* Description: Photo Browser
*
*/
// INCLUDES
#include <e32base.h>
#include <aknnotewrappers.h>
#include "IEThreadEngine.h"
#include "IEImageFinder.h"
#include "ImagicConsts.h"
// ----------------------------------------------------------------------------
// CFileFinderThread::CFileFinderThread(CSharedIntermediator* aSMediator)
//
// Constructor.
// ----------------------------------------------------------------------------
CFileFinderThread::CFileFinderThread(
CIEFileLoader* aFileLoader,
RArray<CImageData*>& aFileNameData,
RArray<CImageData*>& aFaceFileNameData,
RCriticalSection* aCritical,
TDesC& aFileName) :
iCreatedThreads(EFalse),
iFileLoader(aFileLoader),
iFileNameData(aFileNameData),
iFaceFileNameData(aFaceFileNameData),
iCritical(aCritical)
{
iFilename.Copy(aFileName);
}
// ----------------------------------------------------------------------------
// CFileFinderThread::~CFileFinderThread(void)
//
// Destructor.
// ----------------------------------------------------------------------------
CFileFinderThread::~CFileFinderThread(void)
{
DP0_IMAGIC(_L("CFileFinderThread::~CFileFinderThread++"));
if(iSMediator)
{
delete iSMediator;
iSMediator = NULL;
}
// Thread should be killed allready, if thread is already killed this does nothing
iThreadOne.Kill(KErrNone);
// Handles should be closed
iThreadOne.Close();
DP0_IMAGIC(_L("CFileFinderThread::~CFileFinderThread--"));
}
CFileFinderThread* CFileFinderThread::NewL(
CIEFileLoader* aFileLoader,
RArray<CImageData*>& aFileNameData,
RArray<CImageData*>& aFaceFileNameData,
RCriticalSection* aCritical,
TDesC& aFileName)
{
CFileFinderThread* self = CFileFinderThread::NewLC(
aFileLoader,
aFileNameData,
aFaceFileNameData,
aCritical,
aFileName);
CleanupStack::Pop(self);
return self;
}
CFileFinderThread* CFileFinderThread::NewLC(
CIEFileLoader* aFileLoader,
RArray<CImageData*>& aFileNameData,
RArray<CImageData*>& aFaceFileNameData,
RCriticalSection* aCritical,
TDesC& aFileName)
{
CFileFinderThread* self = new (ELeave) CFileFinderThread(
aFileLoader,
aFileNameData,
aFaceFileNameData,
aCritical,
aFileName);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
// Standard Symbian OS 2nd phase constructor
void CFileFinderThread::ConstructL()
{
DP0_IMAGIC(_L("CFileFinderThread::ConstructL ++ --"));
}
void CFileFinderThread::StartL()
{
DP0_IMAGIC(_L("CFileFinderThread::Start++"));
// Create threads only once
if ( iCreatedThreads == EFalse )
{
CreateThreadsL();
}
DP0_IMAGIC(_L("CFileFinderThread::Start--"));
}
void CFileFinderThread::Stop()
{
//TRequestStatus aStatus;
//iThreadOne.Logon(aStatus);
//iThreadOne.Suspend();
}
// ----------------------------------------------------------------------------
// CFileFinderThread::ExecuteThread(TAny *aPtr)
//
// Threadfunction of threadOne. Executed only by threadOne.
// ----------------------------------------------------------------------------
TInt CFileFinderThread::ExecuteThreadOne(TAny *aPtr)
{
DP0_IMAGIC(_L("CFileFinderThread::ExecuteThreadOne++"));
CMediator* aSMediator = static_cast<CMediator*>( aPtr );
//Create cleanupstack
CTrapCleanup* cleanupStack = CTrapCleanup::New();
//Test cleanup stack, additional cleanup stack must be prosessed under
//TRAP
//We can't use low level cleanup stack handling
TRAPD(error, CFileFinderThread::CreateFileFinderL(aSMediator));
delete cleanupStack;
DP0_IMAGIC(_L("CFileFinderThread::ExecuteThreadOne--"));
return 0;
}
// ----------------------------------------------------------------------------
// CFileFinderThread::CreateActiveScheduler(CSharedIntermediator* aSMediator)
//
// Create ActiveScheduler for thread1.
// ----------------------------------------------------------------------------
void CFileFinderThread::CreateFileFinderL(CMediator* aSMediator)
{
DP0_IMAGIC(_L("CFileFinderThread::CreateFileFinderL++"));
// create a new active scheduler
CActiveScheduler* activeScheduler = new (ELeave) CActiveScheduler;
CleanupStack::PushL(activeScheduler);
// use static function Install to install previously created scheduler
CActiveScheduler::Install(activeScheduler);
//Create and use iTNImageFinder to handle in backround AO iFileNameData array filling
CIEImageFinder* TNImageFinder = new (ELeave) CIEImageFinder(
aSMediator->iFileLoader,
*aSMediator->iFileNameData,
*aSMediator->iFaceFileNameData,
aSMediator->iCritical);
CleanupStack::PushL(TNImageFinder);
TNImageFinder->ConstructL();
TNImageFinder->StartFinderL(KFileString);
DP0_IMAGIC(_L("CFileFinderThread::CreateFileFinderL finder ended"));
aSMediator->iFileLoader->ImageFinderStopped();
aSMediator->iFileLoader->AllFilesAddedToFilenameArray();
// Start active scheduler
//CActiveScheduler::Start();
// Remove and delete scheduler and the rest.
CleanupStack::PopAndDestroy(2);
DP0_IMAGIC(_L("CFileFinderThread::CreateFileFinderL--"));
}
// ----------------------------------------------------------------------------
// CFileFinderThread::CreateThreadsL()
//
// Create thread1 and resume it. Activate thread1 listener.
// ----------------------------------------------------------------------------
void CFileFinderThread::CreateThreadsL()
{
DP0_IMAGIC(_L("CFileFinderThread::CreateThreadsL++"));
iSMediator = new (ELeave) CMediator();
iSMediator->iFileLoader = iFileLoader;
iSMediator->iFileNameData = &iFileNameData;
iSMediator->iFaceFileNameData = &iFaceFileNameData;
iSMediator->iCritical = iCritical;
iSMediator->iFileName = iFilename;
// Create thread which uses the same heap as main program.
iThreadOne.Create(_L("FileFinderThread"), ExecuteThreadOne, 12040, NULL, iSMediator);
//EPriorityNormal, EPriorityLess, EPriorityMuchLess
iThreadOne.SetPriority(EPriorityMuchLess);
iThreadOne.Resume();
iCreatedThreads = ETrue;
DP0_IMAGIC(_L("CFileFinderThread::CreateThreadsL--"));
}
| [
"none@none"
]
| [
[
[
1,
221
]
]
]
|
6679198e05ff392073c44def46f9081fa7a4a634 | 6188f1aaaf5508e046cde6da16b56feb3d5914bc | /CamFighter/Math/Cameras/FieldOfView.h | 76ee412855215c80923b342c6738b77e81782ef3 | []
| no_license | dogtwelve/fighter3d | 7bb099f0dc396e8224c573743ee28c54cdd3d5a2 | c073194989bc1589e4aa665714c5511f001e6400 | refs/heads/master | 2021-04-30T15:58:11.300681 | 2011-06-27T18:51:30 | 2011-06-27T18:51:30 | 33,675,635 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,587 | h | #ifndef __incl_Math_Cameras_FieldOfView_h
#define __incl_Math_Cameras_FieldOfView_h
#include "../xMath.h"
#include "../Figures/xBoxA.h"
#include "../Figures/xBoxO.h"
#include "../Figures/xSphere.h"
namespace Math { namespace Cameras {
class Camera;
struct FieldOfView
{
private:
Camera *camera;
public:
bool Empty;
enum eProjection {
PROJECT_UNDEFINED,
PROJECT_PERSPECTIVE,
PROJECT_ORTHOGONAL
} Projection;
union {
xFLOAT PerspAngle;
xFLOAT OrthoScale;
};
xFLOAT Aspect;
xFLOAT FrontClip;
xFLOAT BackClip;
xMatrix MX_Projection;
xLONG ViewportLeft;
xLONG ViewportTop;
xLONG ViewportWidth;
xLONG ViewportHeight;
xFLOAT ViewportLeftPercent;
xFLOAT ViewportTopPercent;
xFLOAT ViewportWidthPercent;
xFLOAT ViewportHeightPercent;
xPlane LeftPlane;
xPlane RightPlane;
xPlane TopPlane;
xPlane BottomPlane;
xPoint3 Corners3D[4];
xPlane Planes[5];
FieldOfView() : Empty(true) { Projection = PROJECT_UNDEFINED; Aspect = 1.333f; }
void InitCamera(Camera *camera) { this->camera = camera; }
void InitViewportPercent ( xFLOAT leftPcnt, xFLOAT topPcnt,
xFLOAT widthPcnt, xFLOAT heightPcnt,
xDWORD windowWidth, xDWORD windowHeight );
void ResizeViewport ( xDWORD windowWidth, xDWORD windowHeight );
void InitViewport ( xDWORD left, xDWORD top, xDWORD width, xDWORD height,
xDWORD windowWidth = 0, xDWORD windowHeight = 0 );
void InitPerspective( xFLOAT angle = 45.f, xFLOAT frontClip = 0.1f,
xFLOAT backClip = xFLOAT_HUGE_POSITIVE );
void InitOrthogonal ( xFLOAT frontClip = 0.1f, xFLOAT backClip = 1000.f );
void Update();
const xMatrix &MX_Projection_Get() const
{ return MX_Projection; }
const Camera *Camera_Get() const
{ return camera; }
bool ViewportContains(xLONG ScreenX, xLONG ScreenY)
{
return ScreenX >= ViewportLeft && ScreenY >= ViewportTop &&
ScreenX <= ViewportLeft + ViewportWidth &&
ScreenY <= ViewportTop + ViewportHeight;
}
xPoint3 Get3dPos(xLONG ScreenX, xLONG ScreenY, xPlane PN_plane);
xPoint3 Get3dPos(xLONG ScreenX, xLONG ScreenY, xPoint3 P_onPlane);
bool CheckSphere(const xPoint3 &P_center, xFLOAT S_radius) const;
bool CheckSphere(const Math::Figures::xSphere &sphere) const
{ return CheckSphere(sphere.P_center, sphere.S_radius); }
bool CheckBox(const xPoint3 P_corners[8]) const;
bool CheckBox(Math::Figures::xBoxA &box, const xMatrix &MX_LocaltoWorld) const
{
if (Empty || box.P_min == box.P_max) return true;
return CheckBox(box.fillCornersTransformed(MX_LocaltoWorld));
}
bool CheckBox(Math::Figures::xBoxO &box) const
{
if (Empty || box.S_top == 0.f) return true;
return CheckBox(box.P_corners);
}
bool CheckPoints(const xPoint4 *P_points, xWORD I_count) const;
bool CheckPoints(const xPoint3 *P_points, xWORD I_count) const;
};
} } // namespace Math::Cameras
#endif
| [
"dmaciej1@f75eed02-8a0f-11dd-b20b-83d96e936561",
"darekmac@f75eed02-8a0f-11dd-b20b-83d96e936561"
]
| [
[
[
1,
72
],
[
76,
81
],
[
83,
107
]
],
[
[
73,
75
],
[
82,
82
]
]
]
|
597c480a750aaca9c46c0893670ed5fb5ef872b7 | 8103a6a032f7b3ec42bbf7a4ad1423e220e769e0 | /Prominence/Window.h | c330d8a3e4a9ec6643040d19bf3a88066e6292fa | []
| no_license | wgoddard/2d-opengl-engine | 0400bb36c2852ce4f5619f8b5526ba612fda780c | 765b422277a309b3d4356df2e58ee8db30d91914 | refs/heads/master | 2016-08-08T14:28:07.909649 | 2010-06-17T19:13:12 | 2010-06-17T19:13:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 754 | h | #pragma once
#include "Export.h"
#include "Logger.h"
#include "SDL.h"
#include "SDL_opengl.h"
#include <string>
#include <iostream>
namespace Prominence {
class DECLSPEC Window
{
private:
std::string m_Title;
SDL_Surface * m_Screen;
Uint32 m_Width;
Uint32 m_Height;
Uint16 m_Bpp;
//bool m_Fullscreen;
Uint32 m_Flags;
Logger & m_Logger;
public:
Window(Logger & logger, Uint32 width, Uint32 height, Uint16 bpp, std::string name);
~Window(void);
int Start();
int ToggleFullscreen(void);
void SetTitle(std::string title) { m_Title = title; SDL_WM_SetCaption(m_Title.c_str(), m_Title.c_str()); }
int ResizeWindow(Uint32 width, Uint32 height, Uint16 bpp, bool fullscreen);
};
} //Exit Prominence namespace | [
"William@18b72257-4ce5-c346-ae33-905a28f88ba6"
]
| [
[
[
1,
34
]
]
]
|
dd0db63f6f2f095e53223c60a0ec96cfdefeee63 | 9df4b47eb2d37fd7f08b8e723e17f733fd21c92b | /plugintemplate/serverplugin/serverplugin_enginepython.cpp | a620f773e8a3e8eb8360a2fe2dfe99c7e152ad34 | []
| no_license | sn4k3/sourcesdk-plugintemplate | d5a806f8793ad328b21cf8e7af81903c98b07143 | d89166b79a92b710d275c817be2fb723f6be64b5 | refs/heads/master | 2020-04-09T07:11:55.754168 | 2011-01-23T22:58:09 | 2011-01-23T22:58:09 | 32,112,282 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,670 | cpp | //========= Copyright © 2010-2011, Tiago Conceição, All rights reserved. ============
// Plugin Template
//
// Please Read (LICENSE.txt) and (README.txt)
// Dont Forget Visit:
// (http://www.sourceplugins.com) -> VPS Plugins
// (http://www.sourcemm.net) (http://forums.alliedmods.net/forumdisplay.php?f=52) - MMS Plugins
//
//===================================================================================
//=================================================================================
// Includes
//=================================================================================
#define NO_INCLUDE_LIBRARIES
#include "includes/precommun.h"
#include "serverplugin/serverplugin_enginepython.h"
SERVERPLUGIN_ENGINEPYTHON_CLASS::SERVERPLUGIN_ENGINEPYTHON_CLASS(){}
SERVERPLUGIN_ENGINEPYTHON_CLASS::~SERVERPLUGIN_ENGINEPYTHON_CLASS(){}
bool isPythonEnabled = false;
#ifdef PYTHON
//=================================================================================
// Global variables
//=================================================================================
extern char szGameDir[MAX_STR_LEN];
PyMethodDef VAR_PYTHON_METHODS[PYTHON_METHOD_TABLE_SIZE]; // Holds all of our python methods.
//=================================================================================
// Initializes python for us
//=================================================================================
bool EnablePython()
{
#ifdef _WIN32
char szPythonDLL[MAX_STR_LEN];
char szMSVCRTDLL[MAX_STR_LEN];
// Path to python25.dll and msvcrt.dll
V_snprintf(szMSVCRTDLL, MAX_STR_LEN, "%s\\addons\\eventscripts\\_engines\\python\\Lib\\plat-win\\msvcr71.dll", szGameDir);
V_snprintf(szPythonDLL, MAX_STR_LEN, "%s\\addons\\eventscripts\\_engines\\python\\Lib\\plat-win\\python25.dll", szGameDir);
// Load both modules.
if(!LoadLibrary(szMSVCRTDLL) || !LoadLibrary(szPythonDLL))
{
Msg("[ERROR] Could not load one or more required dependencies to initialize python!\n");
return false;
}
#else
if( !dlopen("libpython2.5.so.1.0", RTLD_NOW | RTLD_GLOBAL ) )
{
Error("[ERROR] Unable to open libpython2.5.so.1.0!\n");
return false;
}
#endif
// Initialize python
Py_Initialize();
// Setup the module
Py_InitModule(PYTHON_MODULE_NAME, VAR_PYTHON_METHODS);
return true;
}
// Test
/*DECLARE_PYCMD(Msg, "Print text to console")
{
char *szText;
if( !PyArg_ParseTuple(args, "s", &szText) )
{
Msg("Could not parse function arguments.\n");
return Py_BuildValue("i", 0);
}
Msg(szText);
return Py_BuildValue("i", 1);
}*/
#endif | [
"[email protected]@2dd402b7-31f5-573d-f87e-a7bc63fa017b"
]
| [
[
[
1,
81
]
]
]
|
661db59a8a30a3a2202fa3d2a684bbccb96383fd | 85d9531c984cd9ffc0c9fe8058eb1210855a2d01 | /QxOrm/inl/QxDataMember/QxDataMemberX.inl | 43a95e93c74e299c118176820b38a481210ba5f0 | []
| no_license | padenot/PlanningMaker | ac6ece1f60345f857eaee359a11ee6230bf62226 | d8aaca0d8cdfb97266091a3ac78f104f8d13374b | refs/heads/master | 2020-06-04T12:23:15.762584 | 2011-02-23T21:36:57 | 2011-02-23T21:36:57 | 1,125,341 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,309 | inl | /****************************************************************************
**
** http://www.qxorm.com/
** http://sourceforge.net/projects/qxorm/
** Original file by Lionel Marty
**
** This file is part of the QxOrm library
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any
** damages arising from the use of this software.
**
** GNU Lesser General Public License Usage
** This file must be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file 'license.lgpl.txt' included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you have questions regarding the use of this file, please contact :
** [email protected]
**
****************************************************************************/
namespace qx {
template <class T>
template <typename V>
IxDataMember * QxDataMemberX<T>::add(V T::* pData, const QString & sKey, long lVersion, bool bSerialize, bool bDao)
{
if (exist_WithDaoStrategy(sKey)) { qAssert(false); return NULL; }
qAssert(lVersion <= getVersion());
IxDataMember * pNewDataMember = new QxDataMember<V, T>(pData, sKey, lVersion, bSerialize, bDao);
pNewDataMember->setSqlType(qx::trait::get_sql_type<V>::get());
pNewDataMember->setNameParent(getName());
pNewDataMember->setParent(this);
m_lstDataMember.insert(sKey, pNewDataMember);
return pNewDataMember;
}
template <class T>
template <typename V>
IxDataMember * QxDataMemberX<T>::add(V T::* pData, const QString & sKey, long lVersion, bool bSerialize)
{ return add(pData, sKey, lVersion, bSerialize, true); }
template <class T>
template <typename V>
IxDataMember * QxDataMemberX<T>::add(V T::* pData, const QString & sKey, long lVersion)
{ return add(pData, sKey, lVersion, true, true); }
template <class T>
template <typename V>
IxDataMember * QxDataMemberX<T>::add(V T::* pData, const QString & sKey)
{ return add(pData, sKey, 0, true, true); }
template <class T>
IxDataMember * QxDataMemberX<T>::id(typename QxDataMemberX<T>::type_primary_key T::* pDataMemberId, const QString & sKey)
{ return id(pDataMemberId, sKey, 0); }
template <class T>
IxDataMember * QxDataMemberX<T>::id(typename QxDataMemberX<T>::type_primary_key T::* pDataMemberId, const QString & sKey, long lVersion)
{
if (exist_WithDaoStrategy(sKey) || getId_WithDaoStrategy()) { qAssert(false); return getId_WithDaoStrategy(); }
qAssert(lVersion <= getVersion());
m_pDataMemberId = new QxDataMember<typename QxDataMemberX<T>::type_primary_key, T>(pDataMemberId, sKey);
m_pDataMemberId->setSqlType(qx::trait::get_sql_type<typename QxDataMemberX<T>::type_primary_key>::get());
m_pDataMemberId->setAutoIncrement(boost::is_integral<typename QxDataMemberX<T>::type_primary_key>::value);
m_pDataMemberId->setNameParent(getName());
m_pDataMemberId->setIsPrimaryKey(true);
m_pDataMemberId->setNotNull(true);
m_pDataMemberId->setVersion(lVersion);
m_pDataMemberId->setParent(this);
m_lstDataMember.insert(sKey, m_pDataMemberId);
return m_pDataMemberId;
}
template <class T>
template <typename V>
IxSqlRelation * QxDataMemberX<T>::relationOneToOne(V T::* pData, const QString & sKey)
{ return this->relationOneToOne(pData, sKey, 0); }
template <class T>
template <typename V>
IxSqlRelation * QxDataMemberX<T>::relationManyToOne(V T::* pData, const QString & sKey)
{ return this->relationManyToOne(pData, sKey, 0); }
template <class T>
template <typename V>
IxSqlRelation * QxDataMemberX<T>::relationOneToMany(V T::* pData, const QString & sKey, const QString & sForeignKey)
{ return this->relationOneToMany(pData, sKey, sForeignKey, 0); }
template <class T>
template <typename V>
IxSqlRelation * QxDataMemberX<T>::relationManyToMany(V T::* pData, const QString & sKey, const QString & sExtraTable, const QString & sForeignKeyOwner, const QString & sForeignKeyDataType)
{ return this->relationManyToMany(pData, sKey, sExtraTable, sForeignKeyOwner, sForeignKeyDataType, 0); }
template <class T>
template <typename V>
IxSqlRelation * QxDataMemberX<T>::relationOneToOne(V T::* pData, const QString & sKey, long lVersion)
{
if (exist_WithDaoStrategy(sKey)) { qAssert(false); return NULL; }
IxDataMember * pDataMember = this->add(pData, sKey, lVersion);
IxSqlRelation * pSqlRelation = new QxSqlRelation_OneToOne<V, T>(pDataMember);
pDataMember->setSqlRelation(pSqlRelation);
return pSqlRelation;
}
template <class T>
template <typename V>
IxSqlRelation * QxDataMemberX<T>::relationManyToOne(V T::* pData, const QString & sKey, long lVersion)
{
if (exist_WithDaoStrategy(sKey)) { qAssert(false); return NULL; }
IxDataMember * pDataMember = this->add(pData, sKey, lVersion);
IxSqlRelation * pSqlRelation = new QxSqlRelation_ManyToOne<V, T>(pDataMember);
pDataMember->setSqlRelation(pSqlRelation);
return pSqlRelation;
}
template <class T>
template <typename V>
IxSqlRelation * QxDataMemberX<T>::relationOneToMany(V T::* pData, const QString & sKey, const QString & sForeignKey, long lVersion)
{
if (exist_WithDaoStrategy(sKey)) { qAssert(false); return NULL; }
IxDataMember * pDataMember = this->add(pData, sKey, lVersion);
IxSqlRelation * pSqlRelation = new QxSqlRelation_OneToMany<V, T>(pDataMember, sForeignKey);
pDataMember->setSqlRelation(pSqlRelation);
return pSqlRelation;
}
template <class T>
template <typename V>
IxSqlRelation * QxDataMemberX<T>::relationManyToMany(V T::* pData, const QString & sKey, const QString & sExtraTable, const QString & sForeignKeyOwner, const QString & sForeignKeyDataType, long lVersion)
{
if (exist_WithDaoStrategy(sKey)) { qAssert(false); return NULL; }
IxDataMember * pDataMember = this->add(pData, sKey, lVersion);
IxSqlRelation * pSqlRelation = new QxSqlRelation_ManyToMany<V, T>(pDataMember, sExtraTable, sForeignKeyOwner, sForeignKeyDataType);
pDataMember->setSqlRelation(pSqlRelation);
return pSqlRelation;
}
template <class T>
template <class Archive>
inline void QxDataMemberX<T>::toArchive(const T * pOwner, Archive & ar, const unsigned int file_version) const
{
Q_UNUSED(file_version);
_foreach_if(IxDataMember * pDataMember, m_lstDataMember, (pDataMember->getSerialize()))
pDataMember->toArchive(pOwner, ar);
}
template <class T>
template <class Archive>
inline void QxDataMemberX<T>::fromArchive(T * pOwner, Archive & ar, const unsigned int file_version)
{
Q_UNUSED(file_version);
_foreach_if(IxDataMember * pDataMember, m_lstDataMember, (pDataMember->getSerialize() && (pDataMember->getVersion() <= static_cast<long>(file_version))))
pDataMember->fromArchive(pOwner, ar);
}
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
QxDataMemberX<qx::trait::no_base_class_defined>::QxDataMemberX() : IxDataMemberX(), QxSingleton< QxDataMemberX<qx::trait::no_base_class_defined> >("qx::QxDataMemberX_no_base_class_defined"), m_pDataMemberId(NULL) { ; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
QxDataMemberX<QObject>::QxDataMemberX() : IxDataMemberX(), QxSingleton< QxDataMemberX<QObject> >("qx::QxDataMemberX_QObject"), m_pDataMemberId(NULL) { ; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
long QxDataMemberX<qx::trait::no_base_class_defined>::count_WithDaoStrategy_Helper() const { return 0; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
bool QxDataMemberX<qx::trait::no_base_class_defined>::exist_WithDaoStrategy_Helper(const QString & sKey) const { Q_UNUSED(sKey); return false; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
IxDataMember * QxDataMemberX<qx::trait::no_base_class_defined>::get_WithDaoStrategy_Helper(long lIndex) const { Q_UNUSED(lIndex); return NULL; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
IxDataMember * QxDataMemberX<qx::trait::no_base_class_defined>::get_WithDaoStrategy_Helper(const QString & sKey) const { Q_UNUSED(sKey); return NULL; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
IxDataMember * QxDataMemberX<qx::trait::no_base_class_defined>::getId_WithDaoStrategy_Helper() const { return NULL; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
long QxDataMemberX<QObject>::count_WithDaoStrategy_Helper() const { return 0; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
bool QxDataMemberX<QObject>::exist_WithDaoStrategy_Helper(const QString & sKey) const { Q_UNUSED(sKey); return false; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
IxDataMember * QxDataMemberX<QObject>::get_WithDaoStrategy_Helper(long lIndex) const { Q_UNUSED(lIndex); return NULL; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
IxDataMember * QxDataMemberX<QObject>::get_WithDaoStrategy_Helper(const QString & sKey) const { Q_UNUSED(sKey); return NULL; }
template <> QX_GCC_WORKAROUND_TEMPLATE_SPEC_INLINE
IxDataMember * QxDataMemberX<QObject>::getId_WithDaoStrategy_Helper() const { return NULL; }
} // namespace qx
| [
"[email protected]"
]
| [
[
[
1,
204
]
]
]
|
0ba08dd329f7432421ca439a7cfc13faeff024d1 | be7df324d5509c7ebb368c884b53ea9445d32e4f | /GUI/Cardiac/arthurwidgets.cpp | 6a4e6bf5fff82b44741719622cf29b0401374e58 | []
| no_license | shadimsaleh/thesis.code | b75281001aa0358282e9cceefa0d5d0ecfffdef1 | 085931bee5b07eec9e276ed0041d494c4a86f6a5 | refs/heads/master | 2021-01-11T12:20:13.655912 | 2011-10-19T13:34:01 | 2011-10-19T13:34:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,776 | cpp | /****************************************************************************
**
** Copyright (C) 2005-2006 Trolltech ASA. All rights reserved.
**
** This file is part of the demonstration applications of the Qt Toolkit.
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file. Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://www.trolltech.com/products/qt/opensource.html
**
** If you are unsure which license is appropriate for your use, please
** review the following information:
** http://www.trolltech.com/products/qt/licensing.html or contact the
** sales department at [email protected].
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
#include "arthurwidgets.h"
#include <QPainter>
#include <QPainterPath>
#include <QPixmapCache>
#include <QtEvents>
#include <QTextDocument>
#include <QAbstractTextDocumentLayout>
#include <QFile>
#include <QTextBrowser>
#include <QBoxLayout>
extern QPixmap cached(const QString &img);
ArthurFrame::ArthurFrame(QWidget *parent)
: QWidget(parent), m_prefer_image(false)
{
m_document = 0;
m_show_doc = false;
m_tile = QPixmap(100, 100);
m_tile.fill(Qt::white);
QPainter pt(&m_tile);
QColor color(240, 240, 240);
pt.fillRect(0, 0, 50, 50, color);
pt.fillRect(50, 50, 50, 50, color);
pt.end();
// QPalette pal = palette();
// pal.setBrush(backgroundRole(), m_tile);
// setPalette(pal);
#ifdef Q_WS_X11
QPixmap xRenderPixmap(1, 1);
m_prefer_image = !xRenderPixmap.x11PictureHandle();
#endif
}
void ArthurFrame::paintEvent(QPaintEvent *e)
{
static QImage *static_image = 0;
QPainter painter;
if (preferImage()) {
if (!static_image) {
static_image = new QImage(size(), QImage::Format_RGB32);
} else if (static_image->size() != size()) {
delete static_image;
static_image = new QImage(size(), QImage::Format_RGB32);
}
painter.begin(static_image);
int o = 10;
QBrush bg = palette().brush(QPalette::Background);
painter.fillRect(0, 0, o, o, bg);
painter.fillRect(width() - o, 0, o, o, bg);
painter.fillRect(0, height() - o, o, o, bg);
painter.fillRect(width() - o, height() - o, o, o, bg);
} else {
painter.begin(this);
}
painter.setClipRect(e->rect());
painter.setRenderHint(QPainter::Antialiasing);
QPainterPath clipPath;
QRect r = rect();
double left = r.x() + 1;
double top = r.y() + 1;
double right = r.right();
double bottom = r.bottom();
double radius2 = 8 * 2;
clipPath.moveTo(right - radius2, top);
clipPath.arcTo(right - radius2, top, radius2, radius2, 90, -90);
clipPath.arcTo(right - radius2, bottom - radius2, radius2, radius2, 0, -90);
clipPath.arcTo(left, bottom - radius2, radius2, radius2, 270, -90);
clipPath.arcTo(left, top, radius2, radius2, 180, -90);
clipPath.closeSubpath();
painter.save();
painter.setClipPath(clipPath, Qt::IntersectClip);
painter.drawTiledPixmap(rect(), m_tile);
// client painting
paint(&painter);
painter.restore();
painter.save();
if (m_show_doc)
paintDescription(&painter);
painter.restore();
int level = 180;
painter.setPen(QPen(QColor(level, level, level), 2));
painter.setBrush(Qt::NoBrush);
painter.drawPath(clipPath);
if (preferImage()) {
painter.end();
painter.begin(this);
painter.drawImage(e->rect(), *static_image, e->rect());
}
}
void ArthurFrame::setDescriptionEnabled(bool enabled)
{
if (m_show_doc != enabled) {
m_show_doc = enabled;
emit descriptionEnabledChanged(m_show_doc);
update();
}
}
void ArthurFrame::loadDescription(const QString &fileName)
{
QFile textFile(fileName);
QString text;
if (!textFile.open(QFile::ReadOnly))
text = QString("Unable to load resource file: '%1'").arg(fileName);
else
text = textFile.readAll();
setDescription(text);
}
void ArthurFrame::setDescription(const QString &text)
{
m_document = new QTextDocument(this);
m_document->setHtml(text);
}
void ArthurFrame::paintDescription(QPainter *painter)
{
if (!m_document)
return;
int pageWidth = qMax(width() - 100, 100);
int pageHeight = qMax(height() - 100, 100);
if (pageWidth != m_document->pageSize().width()) {
m_document->setPageSize(QSize(pageWidth, pageHeight));
}
QRect textRect(width() / 2 - pageWidth / 2,
height() / 2 - pageHeight / 2,
pageWidth,
pageHeight);
int pad = 10;
QRect clearRect = textRect.adjusted(-pad, -pad, pad, pad);
painter->setPen(Qt::NoPen);
painter->setBrush(QColor(0, 0, 0, 63));
int shade = 10;
painter->drawRect(clearRect.x() + clearRect.width() + 1,
clearRect.y() + shade,
shade,
clearRect.height() + 1);
painter->drawRect(clearRect.x() + shade,
clearRect.y() + clearRect.height() + 1,
clearRect.width() - shade + 1,
shade);
painter->setRenderHint(QPainter::Antialiasing, false);
painter->setBrush(QColor(255, 255, 255, 220));
painter->setPen(Qt::black);
painter->drawRect(clearRect);
painter->setClipRegion(textRect, Qt::IntersectClip);
painter->translate(textRect.topLeft());
QAbstractTextDocumentLayout::PaintContext ctx;
QLinearGradient g(0, 0, 0, textRect.height());
g.setColorAt(0, Qt::black);
g.setColorAt(0.9, Qt::black);
g.setColorAt(1, Qt::transparent);
QPalette pal = palette();
pal.setBrush(QPalette::Text, g);
ctx.palette = pal;
ctx.clip = QRect(0, 0, textRect.width(), textRect.height());
m_document->documentLayout()->draw(painter, ctx);
}
void ArthurFrame::loadSourceFile(const QString &sourceFile)
{
m_sourceFileName = sourceFile;
}
void ArthurFrame::showSource()
{
// Check for existing source
if (qFindChild<QTextBrowser *>(this))
return;
QString contents;
if (m_sourceFileName.isEmpty()) {
contents = QString("No source for widget: '%1'").arg(objectName());
} else {
QFile f(m_sourceFileName);
if (!f.open(QFile::ReadOnly))
contents = QString("Could not open file: '%1'").arg(m_sourceFileName);
else
contents = f.readAll();
}
contents.replace('&', "&");
contents.replace('<', "<");
contents.replace('>', ">");
QStringList keywords;
keywords << "for " << "if " << "switch " << " int " << "#include " << "const"
<< "void " << "uint " << "case " << "double " << "#define " << "static"
<< "new" << "this";
foreach (QString keyword, keywords)
contents.replace(keyword, QLatin1String("<font color=olive>") + keyword + QLatin1String("</font>"));
contents.replace("(int ", "(<font color=olive><b>int </b></font>");
QStringList ppKeywords;
ppKeywords << "#ifdef" << "#ifndef" << "#if" << "#endif" << "#else";
foreach (QString keyword, ppKeywords)
contents.replace(keyword, QLatin1String("<font color=navy>") + keyword + QLatin1String("</font>"));
contents.replace(QRegExp("(\\d\\d?)"), QLatin1String("<font color=navy>\\1</font>"));
QRegExp commentRe("(//.+)\\n");
commentRe.setMinimal(true);
contents.replace(commentRe, QLatin1String("<font color=red>\\1</font>\n"));
QRegExp stringLiteralRe("(\".+\")");
stringLiteralRe.setMinimal(true);
contents.replace(stringLiteralRe, QLatin1String("<font color=green>\\1</font>"));
QString html = contents;
html.prepend("<html><pre>");
html.append("</pre></html>");
QTextBrowser *sourceViewer = new QTextBrowser(0);
sourceViewer->setWindowTitle("Source: " + m_sourceFileName.mid(5));
sourceViewer->setParent(this, Qt::Dialog);
sourceViewer->setAttribute(Qt::WA_DeleteOnClose);
sourceViewer->setHtml(html);
sourceViewer->resize(600, 600);
sourceViewer->show();
}
| [
"[email protected]"
]
| [
[
[
1,
276
]
]
]
|
82ccfc13bc4c6c92fdaff335355efd391863b3f7 | c70941413b8f7bf90173533115c148411c868bad | /core/src/vtxFileParsingJob.cpp | 619f057816efb54e2f02df01bd1fd1d828b58e19 | []
| no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,190 | cpp | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "vtxFileParsingJob.h"
#include "vtxFile.h"
#include "vtxFileManager.h"
#include "vtxFileStream.h"
#include "vtxThreadingDefines.h"
#include "vtxThreadingHeaders.h"
namespace vtx
{
//-----------------------------------------------------------------------
FileParsingJob::FileParsingJob(FileParser* parser, File* file)
: mParser(parser),
mFile(file)
{
}
//-----------------------------------------------------------------------
FileParsingJob::~FileParsingJob()
{
}
//-----------------------------------------------------------------------
void FileParsingJob::start()
{
VTX_LOG("FileParsingJob started (%s)...", mFile->getFilename().c_str());
FileManager* file_mgr = FileManager::getSingletonPtr();
const String& filename = mFile->getFilename();
FileStream* stream = file_mgr->getFileStream(filename);
if(!stream)
{
// no container found
VTX_WARN("Unable to find container to load file '%s'.", filename.c_str());
file_mgr->_failedParsing(mFile);
delete mParser;
return;
}
mParser->parse(stream, mFile);
if(mParser->errorsOccured())
{
String error = mParser->getError();
while(error.length())
{
VTX_WARN(error.c_str());
error = mParser->getError();
}
VTX_EXCEPT("An error occured while parsing the file \"%s\", see the log for details.", filename.c_str());
}
// TODO: implement FileStreamPtr, so we don't need to destroy instances by hand ?
stream->close();
delete stream;
// TODO: use factory ???
delete mParser;
file_mgr->_finishedParsing(mFile);
VTX_LOG("FileParsingJob finished (%s)...", mFile->getFilename().c_str());
}
//-----------------------------------------------------------------------
}
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
]
| [
[
[
1,
96
]
]
]
|
91766454f8f91f93c8a47ddcb8fc68f6c75dc45f | 74e7667ad65cbdaa869c6e384fdd8dc7e94aca34 | /MicroFrameworkPK_v4_1/BuildOutput/public/debug/Client/stubs/corlib_native_System_MulticastDelegate.cpp | f5e99c39018f878a5772c3479b8632f208292c44 | [
"BSD-3-Clause",
"OpenSSL",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
]
| permissive | gezidan/NETMF-LPC | 5093ab223eb9d7f42396344ea316cbe50a2f784b | db1880a03108db6c7f611e6de6dbc45ce9b9adce | refs/heads/master | 2021-01-18T10:59:42.467549 | 2011-06-28T08:11:24 | 2011-06-28T08:11:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 915 | cpp | //-----------------------------------------------------------------------------
//
// ** WARNING! **
// This file was generated automatically by a tool.
// Re-running the tool will overwrite this file.
// You should copy this file to a custom location
// before adding any customization in the copy to
// prevent loss of your changes when the tool is
// re-run.
//
//-----------------------------------------------------------------------------
#include "corlib_native.h"
#include "corlib_native_System_MulticastDelegate.h"
using namespace System;
INT8 MulticastDelegate::op_Equality( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, HRESULT &hr )
{
INT8 retVal = 0;
return retVal;
}
INT8 MulticastDelegate::op_Inequality( UNSUPPORTED_TYPE param0, UNSUPPORTED_TYPE param1, HRESULT &hr )
{
INT8 retVal = 0;
return retVal;
}
| [
"[email protected]"
]
| [
[
[
1,
30
]
]
]
|
78b00712460105ebda20932db78366fedaece2ef | 636990a23a0f702e3c82fa3fc422f7304b0d7b9e | /ocx/AnvizOcx/AnvizOcx/ProtocolTest/ComPort.cpp | 64443a1f3145e8a92f2243797e3243ba0b3c5acc | []
| no_license | ak869/armcontroller | 09599d2c145e6457aa8c55c8018514578d897de9 | da68e180cacce06479158e7b31374e7ec81c3ebf | refs/heads/master | 2021-01-13T01:17:25.501840 | 2009-02-09T18:03:20 | 2009-02-09T18:03:20 | 40,271,726 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,731 | cpp | // ComPort.cpp: implementation of the CComPort class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ComPort.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CComPort::CComPort()
{
m_hCom = INVALID_HANDLE_VALUE;
m_ErrCode = 0;
}
CComPort::~CComPort()
{
CloseCom();
}
BOOL CComPort::OpenPort(void)
{
return OpenCom(_T("COM1"));
}
VOID CComPort::ClosePort(void)
{
CloseCom();
}
BOOL CComPort::OpenCom(TCHAR * COMName)
{
DCB dcb;
HANDLE hCom;
BOOL fSuccess;
COMMTIMEOUTS CommTimeOuts;
hCom = ::CreateFile( COMName,
GENERIC_READ | GENERIC_WRITE,
0, // must be opened with exclusive-access
NULL, // no security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
0, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);
if (hCom == INVALID_HANDLE_VALUE)
{
// Handle the error.
// printf ("CreateFile failed with error %d.\n", GetLastError());
return FALSE;
}
// Build on the current configuration, and skip setting the size
// of the input and output buffers with SetupComm.
fSuccess = GetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
// printf ("GetCommState failed with error %d.\n", GetLastError());
CloseHandle(hCom);
return FALSE;
}
// Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit.
fSuccess = GetCommState(hCom, &dcb);
dcb.BaudRate = CBR_9600; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fInX = dcb.fOutX = 0 ;
dcb.fBinary = TRUE ;
fSuccess = SetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
// printf ("SetCommState failed with error %d.\n", GetLastError());
CloseHandle(hCom);
}
SetupComm( hCom, 4096, 4096 );
PurgeComm( hCom, PURGE_TXABORT | PURGE_RXABORT |
PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
CommTimeOuts.ReadIntervalTimeout = 10;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
CommTimeOuts.ReadTotalTimeoutConstant = 4000;
// CBR_9600 is approximately 1byte/ms. For our purposes, allow
// double the expected time per character for a fudge factor.
CommTimeOuts.WriteTotalTimeoutMultiplier = 1;
CommTimeOuts.WriteTotalTimeoutConstant = 0 ;
SetCommTimeouts( hCom, &CommTimeOuts ) ;
read_o.hEvent = CreateEvent(
NULL, // default security attributes
FALSE, // auto reset event
FALSE, // not signaled
NULL // no name
);
write_o.hEvent = CreateEvent(
NULL, // default security attributes
FALSE, // auto reset event
FALSE, // not signaled
NULL // no name
);
read_o.Internal = 0;
read_o.InternalHigh = 0;
read_o.Offset = 0;
read_o.OffsetHigh = 0;
write_o.Internal = 0;
write_o.InternalHigh = 0;
write_o.Offset = 0;
write_o.OffsetHigh = 0;
m_hCom = hCom;
return TRUE;
}
void CComPort::CloseCom()
{
if( m_hCom != INVALID_HANDLE_VALUE)
CloseHandle(m_hCom);
m_hCom = INVALID_HANDLE_VALUE;
}
BOOL CComPort::ReadData(BYTE *Buffer, DWORD *nSize)
{
DWORD dwLength,dwErrorFlags;
BOOL fReadStat;
COMSTAT ComStat;
dwLength = *nSize;
if( m_hCom == INVALID_HANDLE_VALUE ) return FALSE;
ClearCommError( m_hCom, &dwErrorFlags, &ComStat );
fReadStat = ReadFile(m_hCom, Buffer, dwLength, nSize, &read_o);
if( !fReadStat )
{
m_ErrCode = GetLastError();
ClearCommError( m_hCom, &dwErrorFlags, &ComStat );
}
return TRUE;
}
BOOL CComPort::WriteData(BYTE *Buffer, DWORD nSize)
{
DWORD dwLength;
BOOL fWriteStat;
dwLength = nSize;
if( m_hCom == INVALID_HANDLE_VALUE ) return FALSE;
fWriteStat = WriteFile(m_hCom, Buffer, dwLength, &nSize, &write_o);
if( !fWriteStat )
{
m_ErrCode = GetLastError();
}
return TRUE;
}
DWORD CComPort::GetErrCode()
{
return m_ErrCode;
}
void CComPort::ClearData(BYTE *Buffer, DWORD *nSize)
{
DWORD dwLength,dwErrorFlags;
BOOL fReadStat;
COMMTIMEOUTS CommTimeOuts;
COMSTAT ComStat;
if( m_hCom == INVALID_HANDLE_VALUE ) return;
ClearCommError( m_hCom, &dwErrorFlags, &ComStat );
GetCommTimeouts( m_hCom, &CommTimeOuts ) ;
CommTimeOuts.ReadTotalTimeoutConstant = 10;
SetCommTimeouts( m_hCom, &CommTimeOuts ) ;
dwLength = *nSize;
fReadStat = ReadFile(m_hCom, Buffer, dwLength, nSize, &read_o);
if( !fReadStat )
{
m_ErrCode = GetLastError();
ClearCommError( m_hCom, &dwErrorFlags, &ComStat );
}
CommTimeOuts.ReadTotalTimeoutConstant = 4000;
SetCommTimeouts( m_hCom, &CommTimeOuts ) ;
return;
}
VOID CComPort::SetTimeOut(DWORD RecvTimeOut)
{
COMMTIMEOUTS CommTimeOuts;
CommTimeOuts.ReadIntervalTimeout = 10;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
CommTimeOuts.ReadTotalTimeoutConstant = RecvTimeOut;
// CBR_9600 is approximately 1byte/ms. For our purposes, allow
// double the expected time per character for a fudge factor.
CommTimeOuts.WriteTotalTimeoutMultiplier = 1;
CommTimeOuts.WriteTotalTimeoutConstant = 0 ;
SetCommTimeouts( m_hCom, &CommTimeOuts ) ;
}
BOOL CComPort::OpenCom(TCHAR *port, LONG baudrate)
{
DCB dcb;
HANDLE hCom;
BOOL fSuccess;
COMMTIMEOUTS CommTimeOuts;
hCom = ::CreateFile( port,
GENERIC_READ | GENERIC_WRITE,
0, // must be opened with exclusive-access
NULL, // no security attributes
OPEN_EXISTING, // must use OPEN_EXISTING
0, // not overlapped I/O
NULL // hTemplate must be NULL for comm devices
);
if (hCom == INVALID_HANDLE_VALUE)
{
// Handle the error.
// printf ("CreateFile failed with error %d.\n", GetLastError());
return FALSE;
}
// Build on the current configuration, and skip setting the size
// of the input and output buffers with SetupComm.
fSuccess = GetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
// printf ("GetCommState failed with error %d.\n", GetLastError());
CloseHandle(hCom);
return FALSE;
}
// Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit.
fSuccess = GetCommState(hCom, &dcb);
dcb.BaudRate = baudrate; // set the baud rate
dcb.ByteSize = 8; // data size, xmit, and rcv
dcb.Parity = NOPARITY; // no parity bit
dcb.StopBits = ONESTOPBIT; // one stop bit
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fInX = dcb.fOutX = 0 ;
dcb.fBinary = TRUE ;
fSuccess = SetCommState(hCom, &dcb);
if (!fSuccess)
{
// Handle the error.
// printf ("SetCommState failed with error %d.\n", GetLastError());
CloseHandle(hCom);
}
SetupComm( hCom, 4096, 4096 );
PurgeComm( hCom, PURGE_TXABORT | PURGE_RXABORT |
PURGE_TXCLEAR | PURGE_RXCLEAR ) ;
CommTimeOuts.ReadIntervalTimeout = 10;
CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
CommTimeOuts.ReadTotalTimeoutConstant = 4000;
// CBR_9600 is approximately 1byte/ms. For our purposes, allow
// double the expected time per character for a fudge factor.
CommTimeOuts.WriteTotalTimeoutMultiplier = 1;
CommTimeOuts.WriteTotalTimeoutConstant = 0 ;
SetCommTimeouts( hCom, &CommTimeOuts ) ;
read_o.hEvent = CreateEvent(
NULL, // default security attributes
FALSE, // auto reset event
FALSE, // not signaled
NULL // no name
);
write_o.hEvent = CreateEvent(
NULL, // default security attributes
FALSE, // auto reset event
FALSE, // not signaled
NULL // no name
);
read_o.Internal = 0;
read_o.InternalHigh = 0;
read_o.Offset = 0;
read_o.OffsetHigh = 0;
write_o.Internal = 0;
write_o.InternalHigh = 0;
write_o.Offset = 0;
write_o.OffsetHigh = 0;
m_hCom = hCom;
return TRUE;
}
| [
"leon.b.dong@41cf9b94-d0c3-11dd-86c2-0f8696b7b6f9"
]
| [
[
[
1,
316
]
]
]
|
98c9cd5435dc90bcbdac47c51f867cd1eb48d117 | a9fedf8210ff0b776820766ce9757a67627c7b7b | /Graphing.cpp | 01f96eadaa43c2156295fae7bd96d54b28d52ad7 | []
| no_license | 4ydx/easygraph | 0cacd644cece912181f17f822ffe84d7a9aa5c2c | 133dc5340aac8a64b2acd0f9981c6ebd400e450a | refs/heads/master | 2016-09-09T20:07:53.666277 | 2008-09-04T23:23:07 | 2008-09-04T23:23:07 | 32,132,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,568 | cpp | /* Copyright Nathan Findley
* Using the GPLv3
*/
#include "Graphing.h"
#include "ShuntingYardAlgorithm.h"
#include "ReversePolishNotationCalculation.h"
#include <QGLWidget>
#include <QHeaderView>
#include <QMessageBox>
#include <iostream>
Graphing::Graphing() {
}
Graphing::~Graphing() {
}
void Graphing::initialize(QMainWindow &main) {
mainWindow.setupUi(&main);
mainWindow.constantsTableView->setModel(&model);
mainWindow.constantsTableView->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
QObject::connect(mainWindow.addConstantsModelPointPushButton, SIGNAL(clicked()), this, SLOT(AddConstantsModelPoint()));
QObject::connect(mainWindow.clearConstantsModelPushButton, SIGNAL(clicked()), this, SLOT(ClearConstantsModel()));
QObject::connect(mainWindow.evaluatePushButton, SIGNAL(clicked()), this, SLOT(EvaluateEquation()));
QObject::connect(mainWindow.useRangeCheckBox, SIGNAL(clicked(bool)), mainWindow.lowerDoubleSpinBox, SLOT(setEnabled(bool)));
QObject::connect(mainWindow.useRangeCheckBox, SIGNAL(clicked(bool)), mainWindow.higherDoubleSpinBox, SLOT(setEnabled(bool)));
QObject::connect(mainWindow.graphWidget, SIGNAL(gridMoved()), this, SLOT(ReevaluateEquation()));
main.show();
}
void Graphing::EvaluateEquation() {
ShuntingYardAlgorithm sya;
QString ErrorMessage = "";
QString equation = sya.FormatEquation(mainWindow.equationLineEdit->text(), ErrorMessage);
if(ErrorMessage != "") {
QMessageBox::critical(0,
"Invalid Equation",
ErrorMessage);
return;
}
if (sya.ValidateEquation(equation, this->model, mainWindow.independentVariableLineEdit->text(), ErrorMessage)) {
ConstantsModelPoint p;
p.VariableName = mainWindow.independentVariableLineEdit->text();
mainWindow.equationLabel->setText("Equation: " + equation);
equation = sya.GenerateReversePolishNotation(equation,
p,
model.getConstantValues());
mainWindow.textBrowser->setText(" ==> " + equation + "\n");
double low, high, step = 0.0;
if(mainWindow.useRangeCheckBox->isChecked()) {
low = mainWindow.lowerDoubleSpinBox->text().toDouble();
high = mainWindow.higherDoubleSpinBox->text().toDouble();
} else {
low = mainWindow.graphWidget->GetDomainMinimum();
high = mainWindow.graphWidget->GetDomainMaximum();
//Generate a tail on each end so that dragging still reveals a line
float width = high - low;
low = low < 0 ? low - width : - 1 * width;
high = high < 0 ? width : high + width;
}
step = (high - low) / 1000;
ReversePolishNotationCalculation rpn;
graphPoints.clear();
while(low < high)
{
p.Value = low;
double answer = rpn.Calculate(equation, p, model.getConstantValues());
mainWindow.textBrowser->append("X: " + QString::number(low) + " Y: " + QString::number(answer) + "\n");
Point graphPoint(D2);
graphPoint.X = low;
graphPoint.Y = answer;
graphPoints.append(graphPoint);
low += step;
}
//Now draw the points to the QGLWidget
mainWindow.graphWidget->drawGraph(graphPoints);
} else {
QMessageBox::critical(0,
"Invalid Equation",
ErrorMessage);
}
}
void Graphing::ReevaluateEquation() {
EvaluateEquation();
}
void Graphing::AddConstantsModelPoint() {
model.insertRow(model.rowCount(QModelIndex()));
}
void Graphing::ClearConstantsModel() {
model.removeRows(0, model.rowCount(), QModelIndex());
}
| [
"mojowings@c4cc5456-6250-0410-a01c-1b7e6a35f18a"
]
| [
[
[
1,
127
]
]
]
|
8a4b42078baf42fc0d662c014306fe8b9b6437a9 | 011359e589f99ae5fe8271962d447165e9ff7768 | /ps3/audit.cpp | 4f137c63c541ea05b9658fe3ede12d3d2a71b730 | []
| no_license | PS3emulators/fba-next-slim | 4c753375fd68863c53830bb367c61737393f9777 | d082dea48c378bddd5e2a686fe8c19beb06db8e1 | refs/heads/master | 2021-01-17T23:05:29.479865 | 2011-12-01T18:16:02 | 2011-12-01T18:16:02 | 2,899,840 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,804 | cpp | // Burner new audit module, added by regret
// NO_DUMP: CRC == 0
// BAD_DUMP: CRC != 0 && flag == BRF_NODUMP
/* changelog:
update 4: add disable crc check
update 3: add nodump and baddump check
update 2: add auditState interfaces
update 1: rewrite audit method (almost same as MAMEPlus GUI)
*/
#include "burner.h"
#include "seldef.h"
static char* auditState = NULL;
// variable definitions
struct RomInfo
{
string name;
unsigned int size;
unsigned int type;
unsigned int state;
};
struct GameInfo
{
string parent;
string board;
set<string> clones;
map<unsigned int /*crc*/, RomInfo> roms;
};
static map<string, GameInfo*> allGameMap;
static bool getinfo = false;
static ArcEntry* List = NULL;
static int listCount = 0;
// string function
static inline void lowerString(string& str)
{
char strs[MAX_PATH];
strcpy(strs, str.c_str());
int i = 0;
while (strs[i])
{
strs[i] = strlower(strs[i]);
i++;
}
str = strs;
}
static inline void freeArchiveList()
{
if (List)
{
for (int i = 0; i < listCount; i++)
{
free(List[i].szName);
List[i].szName = NULL;
}
free(List);
List = NULL;
}
listCount = 0;
}
static inline unsigned int getRomCount()
{
unsigned int count = 0;
for (count = 0; ; count++)
{
if (BurnDrvGetRomInfo(NULL, count))
break;
}
return count;
}
// find if gameinfo contain rom name
static inline RomInfo* getSetHasRom(GameInfo* info, string romname)
{
if (!info || romname == "")
return NULL;
lowerString(romname);
map<unsigned int, RomInfo>::iterator iter = info->roms.begin();
for (; iter != info->roms.end(); iter++)
{
if (iter->second.name == romname)
return &(iter->second);
}
return NULL;
}
static inline void deleteAllRomsetInfo()
{
map<string, GameInfo*>::iterator iter = allGameMap.begin();
for (; iter != allGameMap.end(); iter++)
{
if (iter->second)
delete iter->second;
}
allGameMap.clear();
getinfo = false;
}
static inline void clearAllRomsetState()
{
GameInfo* gameInfo = NULL;
RomInfo* romInfo = NULL;
map<string, GameInfo*>::iterator iter = allGameMap.begin();
for (; iter != allGameMap.end(); iter++)
{
gameInfo = iter->second;
if (!gameInfo)
continue;
map<unsigned int, RomInfo>::iterator it = gameInfo->roms.begin();
for (; it != gameInfo->roms.end(); it++)
{
romInfo = &it->second;
if (!romInfo)
continue;
if (it->first == 0)
romInfo->state = STAT_OK; // pass no_dump rom
else
romInfo->state = STAT_NOFIND;
}
}
}
static inline void getAllRomsetCloneInfo()
{
GameInfo* gameInfo = NULL;
GameInfo* parentInfo = NULL;
map<string, GameInfo*>::iterator it;
map<string, GameInfo*>::iterator iter = allGameMap.begin();
for (; iter != allGameMap.end(); iter++)
{
gameInfo = iter->second;
if (!gameInfo || (gameInfo->parent == "" && gameInfo->board == ""))
continue;
// add clone rom
if (gameInfo->parent != "")
{
it = allGameMap.find(gameInfo->parent);
if (it != allGameMap.end())
{
parentInfo = it->second;
if (parentInfo)
parentInfo->clones.insert(iter->first);
}
}
// add board rom
if (gameInfo->board != "")
{
it = allGameMap.find(gameInfo->board);
if (it != allGameMap.end())
{
parentInfo = it->second;
if (parentInfo)
parentInfo->clones.insert(iter->first);
}
}
}
}
// get all romsets info, only do once
int getAllRomsetInfo()
{
if (getinfo)
return 0;
char* sname = NULL;
BurnRomInfo ri;
unsigned int romCount = 0;
string name = "";
unsigned int tempBurnDrvSelect = nBurnDrvSelect;
// get all romset basic info
for (nBurnDrvSelect = 0; nBurnDrvSelect < nBurnDrvCount; nBurnDrvSelect++)
{
// get game info
GameInfo* gameInfo = new GameInfo;
gameInfo->parent = BurnDrvGetTextA(DRV_PARENT) ? BurnDrvGetTextA(DRV_PARENT) : "";
gameInfo->board = BurnDrvGetTextA(DRV_BOARDROM) ? BurnDrvGetTextA(DRV_BOARDROM) : "";
name = BurnDrvGetTextA(DRV_NAME);
// get rom info
romCount = getRomCount();
for (unsigned int i = 0; i < romCount; i++)
{
memset(&ri, 0, sizeof(ri));
BurnDrvGetRomInfo(&ri, i); // doesn't contain rom name
RomInfo romInfo;
BurnDrvGetRomName(&sname, i, 0); // get rom name
romInfo.name = sname;
romInfo.size = ri.nLen;
romInfo.type = ri.nType;
if (ri.nCrc == 0)
romInfo.state = STAT_OK; // pass no_dump rom
else
romInfo.state = STAT_NOFIND;
gameInfo->roms[ri.nCrc] = romInfo;
}
// add gameinfo to list
allGameMap[name] = gameInfo;
}
nBurnDrvSelect = tempBurnDrvSelect;
getAllRomsetCloneInfo();
getinfo = true;
return 0;
}
int setCloneRomInfo(GameInfo* info, ArcEntry& list)
{
if (!info)
return 1;
RomInfo* romInfo = NULL;
GameInfo* cloneInfo = NULL;
map<unsigned int, RomInfo>::iterator clone_iter;
set<string>::iterator it = info->clones.begin();
for (; it != info->clones.end(); it++)
{
cloneInfo = allGameMap[*it];
clone_iter = cloneInfo->roms.find(list.nCrc);
if (clone_iter != cloneInfo->roms.end())
{
romInfo = &clone_iter->second;
if (romInfo->size != list.nLen)
{
if (list.nLen < romInfo->size)
romInfo->state = STAT_SMALL;
else
romInfo->state = STAT_LARGE;
}
else
romInfo->state = STAT_OK;
}
else
{
// wrong CRC
if (nLoadMenuShowX & DISABLECRC)
{
RomInfo* rom = getSetHasRom(cloneInfo, list.szName);
if (rom)
rom->state = STAT_OK;
}
}
setCloneRomInfo(cloneInfo, list);
}
return 0;
}
extern void checkScanThread();
extern void romsSetProgress();
static int getArchiveInfo(const char* path, const char* name)
{
if (!name || !path)
return 1;
// omit extension
string _name = name;
lowerString(_name); // case-insensitive
size_t pos = _name.rfind(".");
_name = _name.substr(0, pos);
// set progress
// find name
map<string, GameInfo*>::iterator _it = allGameMap.find(_name);
if (_it == allGameMap.end())
return 1;
GameInfo* gameInfo = _it->second;
if (!gameInfo)
return 1;
static char fileName[MAX_PATH];
sprintf(fileName, "%s%s", path, name);
if (archiveOpenA(fileName))
return 1;
if (archiveGetList(&List, &listCount))
{
freeArchiveList();
return 1;
}
RomInfo* romInfo = NULL;
map<unsigned int, RomInfo>::iterator iter;
for (int i = 0; i < listCount; i++)
{
// check roms
iter = gameInfo->roms.find(List[i].nCrc);
if (iter != gameInfo->roms.end())
{
romInfo = &iter->second;
if (!romInfo)
continue;
if (romInfo->size != List[i].nLen)
{
if (List[i].nLen < romInfo->size)
romInfo->state = STAT_SMALL;
else
romInfo->state = STAT_LARGE;
}
else
romInfo->state = STAT_OK;
}
else
{
// wrong CRC
if (nLoadMenuShowX & DISABLECRC)
{
RomInfo* rom = getSetHasRom(gameInfo, List[i].szName);
if (rom)
rom->state = STAT_OK;
}
}
// check all clones
setCloneRomInfo(gameInfo, List[i]);
}
archiveClose();
freeArchiveList();
return 0;
}
// get archive info in all cofigured pathes
int getFileInfo(bool scanonly)
{
unsigned int count = 0;
return count;
}
void auditPrepare()
{
getAllRomsetInfo();
clearAllRomsetState();
freeArchiveList();
getFileInfo(false);
}
// audio all romsets
int auditRomset()
{
string name = BurnDrvGetTextA(DRV_NAME);
// get rom info
GameInfo* gameInfo = allGameMap[name];
if (!gameInfo)
return AUDIT_FAIL;
RomInfo* romInfo = NULL;
int ret = AUDIT_FULLPASS;
map<unsigned int, RomInfo>::iterator iter = gameInfo->roms.begin();
for (; iter != gameInfo->roms.end(); iter++)
{
romInfo = &iter->second;
if (!romInfo)
continue;
if (romInfo->state != STAT_OK && romInfo->type && iter->first)
{
if (iter->first == 0)
continue; // no_dump
if (!(romInfo->type & BRF_OPT))
return AUDIT_FAIL;
ret = AUDIT_PARTPASS;
}
}
return ret;
}
void auditCleanup()
{
deleteAllRomsetInfo();
}
// audit state
void initAuditState()
{
if (auditState)
return;
auditState = (char*)malloc(nBurnDrvCount);
resetAuditState();
}
void resetAuditState()
{
if (auditState)
memset(auditState, 0, nBurnDrvCount);
}
void freeAuditState()
{
free(auditState);
auditState = NULL;
}
char getAuditState(const unsigned int& id)
{
if (id < nBurnDrvCount)
return auditState[id];
return AUDIT_FAIL;
}
void setAuditState(const unsigned int& id, char val)
{
if (id >= nBurnDrvCount)
return;
auditState[id] = val;
}
| [
"[email protected]"
]
| [
[
[
1,
453
]
]
]
|
c4123a8f0bb22df9245b5c527ef8f0318e1e8863 | c497f6d85bdbcbb21e93ae701c5570f16370f0ae | /Sync/Lets_try_all_engine/CarrGen.cpp | 201c0f4bd8d792e240d0824f05f21cacf7aaf0f4 | []
| no_license | mfkiwl/gpsgyan_fork | 91b380cf3cfedb5d1aac569c6284bbf34c047573 | f7c850216c16b49e01a0653b70c1905b5b6c2587 | refs/heads/master | 2021-10-15T08:32:53.606124 | 2011-01-19T16:24:18 | 2011-01-19T16:24:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,427 | cpp |
/* * File name : CarrGen.cpp
* Hello My Name is Priyank
* Abstract : This file contains definitions of structures and Global classes
* Struchers used in the Gpsgyan project.
*
* Compiler : Visual C++ Version 9.0
*
* Compiler options : Default
*
* Pragmas : None used
*
* H/W Platform : IBM PC
*
* Portability : No Operating system call used.
* No machine specific instruction used.
* No compiler specific routines used.
* Hence Portable.
*
* Authors : Priyank Kumar
*
*
* Version history : Base version
* Priyank Kumar November 2009
*
* References : None
*
* Functions called : None
* Library Used : GPStk
* Copyright 2009, The University of Texas at Austin
*
*/
#include <stdio.h>
#include <iostream>
#include <string>
#include <list>
// gpstk
#include "StringUtils.hpp"
#include "GPSAlmanacStore.hpp"
#include "icd_200_constants.hpp"
#include "gps_constants.hpp"
#include "CarrGen.hpp"
#include "PreciseRange.hpp"
#include "GaussianDistribution.hpp"
//#include "Stats.hpp"
using namespace gpstk;
using namespace std;
/*----------------------------------------------------------------------------------------------
* Function : GetPassiveInput(<enginename>_passiveInput &ref)
* Abstract : This function takes the passive input structure to the engine
* which is normally done during initialization of engine. Input can
* be prepared in this function which as suitable to method of engine
* Formal
* Parameter(s) : reference to the passive input structure
* Return value : None
* System Call : None
* Functions called : None
* Reference : OOSDM core framework
* Specific library calls : None
* Member variables accessed: status flag of passive input
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::GetPassiveInput(carrGen_passiveInput &ref)
{
carrGen_probe.s_psvParam = false;
p_passiveData = ref;
carrGen_probe.s_psvParam = true;
}
/*----------------------------------------------------------------------------------------------
* Function : GetPassiveParam(<enginename>_passiveParam &ref)
* Abstract : This function takes the passive controls structure to the engine
* which is normally done during initialization of engine. dependent
* parameters can be created in this module.
*
* Formal
* Parameter(s) : reference to the passive parameter structure
* Return value : None
* System Call : None
* Functions called : None
* Reference : OOSDM core framework
* Specific library calls : None
* Member variables accessed: status flag of passive param
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::GetPassiveParam(carrGen_passiveParam &ref)
{
carrGen_probe.s_psvParam = false;
p_passiveControl = ref;
carrGen_probe.s_psvParam = true;
}
/*----------------------------------------------------------------------------------------------
* Function : GetActiveInput(<enginename>_activeInput &ref)
* Abstract : This function takes the active input structure to the engine
* which is normally done during run phase of engine. Input can
* be prepared in this function as per method of engine
* Formal
* Parameter(s) : reference to the passive input structure
* Return value : None
* System Call : None
* Functions called : None
* Reference : OOSDM core framework
* Specific library calls : None
* Member variables accessed: status flag of passive input
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::GetActiveInput(carrGen_activeInput &ref)
{
carrGen_probe.s_actInput = false;
p_activeData = ref;
carrGen_probe.s_actInput = true;
}
/*----------------------------------------------------------------------------------------------
* Function : GetActiveInput(<enginename>_activeInput &ref)
* Abstract : This function takes the active input structure to the engine
* which is normally done during run phase of engine. Input can
* be prepared in this function as per method of engine
* Formal
* Parameter(s) : reference to the passive input structure
* Return value : None
* System Call : None
* Functions called : None
* Reference : OOSDM core framework
* Specific library calls : None
* Member variables accessed: status flag of passive input
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::GetActiveParam(carrGen_activeParam &ref)
{
carrGen_probe.s_actParam = false;
p_activeControl = ref;
carrGen_probe.s_actParam = true;
}
/*----------------------------------------------------------------------------------------------
* Function : void SetInitialStateofEngine() throw(ExcCarrGen)
* Abstract : This perform the sets the initial input & Parameter fed to the
* Engine
* Formal
* Parameter(s) : None
* Exception(s) : ExcCarrGen
* Return value : None
* System Call : Exception handler
* Functions called : None
* Reference : None
* Specific library calls : None
* Member variables accessed: None
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::SetInitialStateofEngine()
{
carrGen_probe.s_engineControlPsv=false;
// This create a dictionary of all PRN CODE so that each time
// Code gen need not be calculated as soon as object is initialized
// this dictionary is created, Also this dictionary is
// available on PORT2 of this engine if incase its needed
GenerateBaseCarrier(baseCarrierI,baseCarrierQ);
carrGen_probe.s_engineControlPsv=true;
}
/*----------------------------------------------------------------------------------------------
* Function : void VerifyIpToEngine() throw(ExcCarrGen)
* Abstract : This perform the verification of the input & Parameter fed to the
* Engine
* Formal
* Parameter(s) : None
* Exception(s) : ExcCarrGen
* Return value : None
* System Call : Exception handler
* Functions called : None
* Reference : None
* Specific library calls : None
* Member variables accessed: None
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::SetActiveStateofEngine()
{ carrGen_probe.s_engineControlAct=false;
/*map<SatID, boost::circular_buffer<int>>::iterator it_sat;
it_sat=codeDictionary.find(p_activeData.satid);*/
currentSatCarrbufferI = baseCarrierI;
currentSatCarrbufferQ = baseCarrierQ;
carrGen_probe.s_engineControlAct=true;
carrGen_pData.lastCycle_I.clear();
carrGen_pData.lastCycle_Q.clear();
}
/*----------------------------------------------------------------------------------------------
* Function : void VerifyIpToEngine() throw(ExcCarrGen)
* Abstract : This perform the verification of the input & Parameter fed to the
* Engine
* Formal
* Parameter(s) : None
* Exception(s) : ExcCarrGen
* Return value : None
* System Call : Exception handler
* Functions called : None
* Reference : None
* Specific library calls : None
* Member variables accessed: None
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen:: EngineControl(Kind kind)
{
switch(kind)
{ case PASSIVE : // These parameters change only once during initialization or during Exception handling
//carrGen_probe = 0x0000;
GetPassiveInput(passiveData);
GetPassiveParam(passiveControl);
//Set the state depending on input, parameter and initial val
SetInitialStateofEngine();
break;
case ACTIVE :
// These parameters changes during the program execution where its taking input and param from some other
// Modules
//<modulename>_actInput : Defines active inputs to the module
GetActiveInput(activeData);
// Active Parameter : This is basicall user controlled param which user
// change in real time program execution
GetActiveParam(activeControl);
// Set the state and other param of the engine before calling the method of engine
SetActiveStateofEngine();
break;
default :
break;
}
// set debug level etc
}
/*----------------------------------------------------------------------------------------------
* Function : void VerifyIpToEngine() throw(ExcCarrGen)
* Abstract : This perform the verification of the input & Parameter fed to the
* Engine
* Formal
* Parameter(s) : None
* Exception(s) : ExcCarrGen
* Return value : None
* System Call : Exception handler
* Functions called : None
* Reference : None
* Specific library calls : None
* Member variables accessed: None
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::VerifyIpToEngine() throw(ExcCarrGen)
{
ExcCarrGen e("Verification" , 0 ,gpstk::Exception::recoverable);
e.setErrorId(1);
try
{
carrGen_probe.s_verEngine= false;
/* Verify the Input Elevation */
e.addText("Didn't get any Orbital data from the Yuma files. ");
e.addLocation(FILE_LOCATION);
error_number.push_back(2);
throw e;
carrGen_probe.s_verEngine= true;
}
catch(ExcCarrGen &e)
{
carrGen_probe.s_verEngine= false;
ExpHandler(e);
}
}
/*----------------------------------------------------------------------------------------------
* Function : void MethodOfEngine() throw(ExcCarrGen)
* Abstract : This perform the algorithm of engine under particular state decided
* by Engine controller based on active parameter and state
* Formal
* Parameter(s) : None
* Exception(s) : ExcCarrGen
* Return value : None
* System Call : Exception handler
* Functions called : None
* Reference : None
* Specific library calls : None
* Member variables accessed: None
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::MethodOfEngine()throw(ExcCarrGen)
{
// This updates the Rx IF frequency depending on the downconverter used
GenerateBeatFrequency();
GetGeneratedCarr(carrGen_pData,currentSatCarrbufferI,currentSatCarrbufferQ, p_activeData.initCoarsePhase, p_activeData.initCarrierFinePhase, rxIF);
carrGen_pData.rxIF = rxIF;
}
/*----------------------------------------------------------------------------------------------
* Function : void CarrGenCA_L1(int *ptr_to_code,int tap1,int tap2)
* Abstract : This function generate the GPS CA code for L1 GPS satellite
* given the satellite taps.
* Formal
* Parameter(s) : pointer to C/A code & tap values
* Return value : None
* System Call : None
* Functions called : None
* Reference : None
* Specific library calls : None
* Member variables accessed: None
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::ValidateOpOfEngine() throw(ExcCarrGen)
{
bool exceptionFlag;
ExcCarrGen e1("Validation" , 0 ,gpstk::Exception::recoverable);
e1.setErrorId(1);
carrGen_probe.s_valEngine= false;
exceptionFlag=ValidateOp(carrGen_pData ,e1);
try
{
if(exceptionFlag)
throw e1;
else
carrGen_probe.s_valEngine= true;
}
catch(ExcCarrGen &e1)
{
carrGen_probe.s_valEngine= false;
//CarrGen_ExpHandler(e);
}
}
/*----------------------------------------------------------------------------------------------
* Function : void CarrGenCA_L1(int *ptr_to_code,int tap1,int tap2)
* Abstract : This function generate the GPS CA code for L1 GPS satellite
* given the satellite taps.
* Formal
* Parameter(s) : pointer to C/A code & tap values
* Return value : None
* System Call : None
* Functions called : None
* Reference : None
* Specific library calls : None
* Member variables accessed: None
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::OutputData(std::ostream & s )
{
string el;
el = "";
using namespace StringUtils;
SatID temp_satid;
carrGen_Data = carrGen_pData;
s<<el;
}
void CarrGen::OutputData()
{
carrGen_Data = carrGen_pData;
}
void CarrGen::ExpHandler(ExcCarrGen &e)
{
unsigned long eid = error_number[1];
switch(eid)
{
case 1: e.terminate();
break;
case 0: cout<<"over";
break;
default: break;
}
}
/*----------------------------------------------------------------------------------------------
* Function : void dump(std::ostream& s)
* Abstract : This function generate the dump of the private variables and state
* of the Engines given the debug level
* given the satellite taps.
* Formal
* Parameter(s) : File name where dump of engine is stored
* Return value : None
* System Call : None
* Functions called : None
* Reference : None
* Specific library calls : None
* Member variables accessed: All Private Members; see the header files
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
bool CarrGen::ValidateOp(carrGen_opDataPort &outputPData ,ExcCarrGen &e)
{
string content;
content = "";
e.setErrorId(4);
using namespace StringUtils;
bool exceptionFlag = false;
content+=leftJustify("Satellite Number \t",10);
content+=leftJustify(asString(outputPData.prn.id), 6);
content += leftJustify("\n",3);
exceptionFlag = false;
content +=leftJustify("High General Relativity Value" ,40);
content += leftJustify("\n",3);
e.addText(content);
e.addLocation(FILE_LOCATION);
error_number.push_back(4);
return(exceptionFlag);
}
/*----------------------------------------------------------------------------------------------
* Function : void CodeGenCA_L1(int *ptr_to_code,int tap1,int tap2)
* Abstract : This function generate the GPS CA code for L1 GPS satellite
* given the satellite taps.
* Formal
* Parameter(s) : pointer to C/A code & tap values
* Return value : None
* System Call : None
* Functions called : None
* Reference : None
* Specific library calls : None
* Member variables accessed: None
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen::GenerateBaseCarrier(boost::circular_buffer<double>& carrArrayI,
boost::circular_buffer<double>& carrArrayQ)
{
carrArrayI.clear(); // Clear the buffer
carrArrayI.set_capacity(CARR_CYCLCE_RESOLUTION);
carrArrayQ.clear(); // Clear the buffer
carrArrayQ.set_capacity(CARR_CYCLCE_RESOLUTION);
int i;
double temp_cos,temp_sin;
for( i = M_ZERO ; i < CARR_CYCLCE_RESOLUTION ; i++)
{
//Forcing the value of sin (pi) and sin(0) to hard zero
if((i==CARR_CYCLCE_RESOLUTION/4)||(i==3*CARR_CYCLCE_RESOLUTION/4))
temp_cos= M_ZERO;
else
temp_cos = cos((M_TWO * gpstk::PI * i)/CARR_CYCLCE_RESOLUTION); // cos(2*pi*i
//Forcing the value of sin (pi) and sin(0) to hard zero
if((i==M_ZERO)||(i==CARR_CYCLCE_RESOLUTION/M_TWO))
temp_sin = M_ZERO;
else
temp_sin = sin((M_TWO * gpstk::PI * i)/CARR_CYCLCE_RESOLUTION);
carrArrayI.push_back(temp_cos);
carrArrayQ.push_back(temp_sin);
}
}
/*----------------------------------------------------------------------------------------------
* Function : void CarrGenCA_L1(int *ptr_to_code,int tap1,int tap2)
* Abstract : This function generate the GPS CA code for L1 GPS satellite
* given the satellite taps.
* Formal
* Parameter(s) : pointer to C/A code & tap values
* Return value : None
* System Call : None
* Functions called : None
* Reference : None
* Specific library calls : None
* Member variables accessed: None
* Assumptions : None
*
----------------------------------------------------------------------------------------------*/
void CarrGen:: GetGeneratedCarr(carrGen_opDataPort& generatedCarr,
boost::circular_buffer<double> & carrArrayI,
boost::circular_buffer<double> & carrArrayQ,
double& initCoarsePhase,
double& initCarrierFinePhase,
double& satCarrClk)
{
boost::circular_buffer<double> tempArray(carrArrayI);
double tempCarrCycles = satCarrClk;
double totalCompleteCycles = std::floor(tempCarrCycles);
double fractionalCycles = tempCarrCycles - totalCompleteCycles;
double totalPhaseInFracCycle = fractionalCycles * CARR_CYCLCE_RESOLUTION; // 1023 points make a cycle
double integerPhase = std::floor(totalPhaseInFracCycle);
double fracphase = totalPhaseInFracCycle - integerPhase;
/* Resolve for fractional slew*/
double carrierFinePhase = fracphase + initCarrierFinePhase;
if(carrierFinePhase >= M_ONE)
{
carrierFinePhase = carrierFinePhase - M_ONE;
integerPhase = integerPhase + M_ONE;
}
boost::circular_buffer<double>::iterator phaseIndex , phaseIndexLast,phaseIndexQ;
tempArray =carrArrayI;
phaseIndex = carrArrayI.begin() + int(initCoarsePhase);
phaseIndexQ =carrArrayQ.begin() + int(initCoarsePhase);
carrArrayI.rotate(phaseIndex); // Change the starting point of circularbuffer
carrArrayQ.rotate(phaseIndexQ); // Change the starting point of circularbuffer
//double tempfirst[CARR_CYCLCE_RESOLUTION];
int i;
for(phaseIndex = carrArrayI.begin(),i=0;phaseIndex !=carrArrayI.end();)
{
//phaseIndexLast = phaseIndex +Q_OFFSET;
generatedCarr.firstCycle_I[i] = *phaseIndex;
//tempfirst[i] = *phaseIndex;
phaseIndex++;
i++;
}
for(phaseIndexQ = carrArrayQ.begin(),i=0;phaseIndexQ !=carrArrayQ.end();)
{
generatedCarr.firstCycle_Q[i] = *(phaseIndexQ);
phaseIndexQ++;
i++;
}
double carrEndIndex = initCoarsePhase + integerPhase;
if(carrEndIndex >= CARR_CYCLCE_RESOLUTION)
{
carrEndIndex = carrEndIndex - CARR_CYCLCE_RESOLUTION;
totalCompleteCycles = totalCompleteCycles + M_ONE;
}
tempArray = carrArrayI;
phaseIndex = tempArray.begin();
phaseIndexLast = tempArray.begin()+ int(integerPhase);
//double tempLast[CARR_CYCLCE_RESOLUTION];
for(phaseIndex = tempArray.begin();phaseIndex !=phaseIndexLast;)
{
generatedCarr.lastCycle_I.push_back(*phaseIndex);
//generatedCarr.lastCycle_Q.push_back(*phaseIndex);
// tempLast[i]=*phaseIndex;
phaseIndex++;
}
tempArray = carrArrayQ;
phaseIndex = tempArray.begin();
phaseIndexLast = tempArray.begin()+ int(integerPhase);
for(phaseIndex = tempArray.begin();phaseIndex !=phaseIndexLast;)
{
generatedCarr.lastCycle_Q.push_back(*phaseIndex);
// tempLast[i]=*phaseIndex;
phaseIndex++;
}
generatedCarr.startIndex = initCoarsePhase;
generatedCarr.residueCoarsePhase = carrEndIndex;
generatedCarr.residueFinePhase = carrierFinePhase;
generatedCarr.totalCompleteCycles=totalCompleteCycles;
}
void CarrGen::GenerateBeatFrequency()
{
double rfTCXO = p_passiveControl.rxConstClk;
if( p_activeControl.useRxclkModel)
rfTCXO = p_activeData.rxClock;
double rxBeatFreq1 = p_passiveControl.IF1mult * rfTCXO;
double rxIF1 = p_activeData.satCarrClk - rxBeatFreq1;
double rxBeatFreq2 = p_passiveControl.IF2mult * rfTCXO;
rxIF = rxIF1 - rxBeatFreq2;
// this gives no of carrier cycles to be generated per code bit
}
| [
"priyankguddu@6c0848c6-feae-43ef-b685-015bb26c21a7"
]
| [
[
[
1,
671
]
]
]
|
d2e8e13f1362d7f52e8de28f314d5fe827350340 | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/coreplugin/iconnection.h | 557a8b5aa7e4d3dae905994dd6e265ab7e3cf975 | []
| no_license | caichunyang2007/my_OpenPilot_mods | 8e91f061dc209a38c9049bf6a1c80dfccb26cce4 | 0ca472f4da7da7d5f53aa688f632b1f5c6102671 | refs/heads/master | 2023-06-06T03:17:37.587838 | 2011-02-28T10:25:56 | 2011-02-28T10:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,492 | h | /**
******************************************************************************
*
* @file iconnection.h
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* Parts by Nokia Corporation ([email protected]) Copyright (C) 2009.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup CorePlugin Core Plugin
* @{
* @brief The Core GCS plugin
*****************************************************************************/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef ICONNECTION_H
#define ICONNECTION_H
#include <QObject>
#include <QtCore/QStringList>
#include <QtCore/QIODevice>
#include "core_global.h"
namespace Core {
/**
* An IConnection object define a "type of connection",
* for instance USB, Serial, Network, ...
*/
class CORE_EXPORT IConnection : public QObject
{
Q_OBJECT
public:
/**
* Return the list of devices found on the system
*/
virtual QStringList availableDevices() = 0;
/**
* Open a device, and return a QIODevice interface from it
* It should be a dynamically created object as it will be
* deleted by the connection manager.
*/
virtual QIODevice *openDevice(const QString &deviceName) = 0;
virtual void closeDevice(const QString &deviceName) {};
/**
* Connection type name "USB HID"
*/
virtual QString connectionName() = 0;
/**
* Short name to display in a combo box
*/
virtual QString shortName() {return connectionName();}
signals:
/**
* Available devices list has changed, signal it to connection manager (and whoever wants to know)
*/
void availableDevChanged(IConnection *);
};
} //namespace Core
#endif // ICONNECTION_H
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
]
| [
[
[
1,
82
]
]
]
|
22515fe40f78a8f8724d9de934c48c603da1d65b | 04fd8c592808305205a245682affda37d7ba5cc8 | /src/Phase.h | 0cd6b371b509e5741d61d51d1c628b700a9ab248 | []
| no_license | juananpe/xiq | b5042ac8fad741b5c9e1e796e13f562e665d8bff | 832c2ebae8f1fc39bff98ef4e03cd0c09a7ea89e | refs/heads/master | 2021-01-10T09:29:07.178741 | 2009-02-06T06:18:34 | 2009-02-06T06:18:34 | 48,246,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,040 | h | // (C) 2009 [email protected]
#ifndef PHASE_H_INCLUDED
#define PHASE_H_INCLUDED
struct Level;
/// the different phases of the game are represented as different types
namespace Phase
{
struct State
{
enum Type
{
None,
Boot,
Splash,
Attract,
TransitionToPlay,
Play,
PostPlay,
LevelTransition,
};
Type type;
};
/// common for all phases
struct Base : Object
{
/// optionally override to handle input during the phase
virtual bool InputEvent(SDL_Event const &) { return false; }
/// optionally override to enter this phaes, given last phase
virtual void Enter(Base * /*previous*/) { }
/// optionally override to leave this phaes, given next phase
virtual void Leave(Base * /*next*/) { Delete(); }
};
/// loading/boot phase
struct Boot : Base
{
void Prepare();
bool InputEvent(SDL_Event const &);
bool Update(GameTime);
void Draw(Matrix const &);
};
/// the attract phase runs the game in a demo loop
struct Attract : Base
{
void Prepare();
bool Update(GameTime);
void Draw(Matrix const &);
};
/// the main play phase
struct Play : Base
{
World *world;
int level;
Play();
~Play();
// overrides for Object
void Prepare();
void SetLevel(int level);
bool Update(GameTime);
void Draw(Matrix const &);
// overrides for Phase
bool InputEvent(SDL_Event const &);
void Leave(Base * /*next*/) { /* don't delete when leaving - GameOver phase will do that */ }
protected:
void PlayerDirects(Direction);
void PlayerUnDirects(Direction);
};
/// animation for moving from one level to another
struct Transition : Base
{
void Prepare();
bool Update(GameTime);
void Draw();
};
/// show the end score, high-scores and allow player to enter name
struct GameOver : Base
{
int score;
Base *prev;
void Prepare();
void Enter(Base *previous);
bool InputEvent(SDL_Event const &);
bool Update(GameTime);
void Draw(Matrix const &);
void Leave(Base *next);
};
}
#endif // PHASE_H_INCLUDED
//EOF
| [
"christian.schladetsch@d54a3f0e-f248-11dd-b556-9305e745af9e"
]
| [
[
[
1,
109
]
]
]
|
e4690153536be58b328d514867661eeb4cfe7945 | 718dc2ad71e8b39471b5bf0c6d60cbe5f5c183e1 | /soft micros/Codigo/codigo portable/Alarma/configuracionLazoAlarmas.cpp | c2d097797a711f842c4036d194a6b8da4605ab97 | []
| no_license | jonyMarino/microsdhacel | affb7a6b0ea1f4fd96d79a04d1a3ec3eaa917bca | 66d03c6a9d3a2d22b4d7104e2a38a2c9bb4061d3 | refs/heads/master | 2020-05-18T19:53:51.301695 | 2011-05-30T20:40:24 | 2011-05-30T20:40:24 | 34,532,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 452 | cpp | #include "configuracionLazoAlarmas.hpp"
ConfiguracionLazoAlarmas::ConfiguracionLazoAlarmas( LazoAlarmConf &_conf_, struct ManejadorMemoria & _manejadorMemoria):configuracion(_conf_),manejadorMemoria(_manejadorMemoria){}
TipoLazo ConfiguracionLazoAlarmas::getLazo(){
return configuracion.tipoLazo;
}
void ConfiguracionLazoAlarmas::setLazo(TipoLazo val){
manejadorMemoria.setWord((unsigned int * const)&configuracion.tipoLazo,val);
} | [
"nicopimen@9fc3b3b2-dce3-11dd-9b7c-b771bf68b549"
]
| [
[
[
1,
12
]
]
]
|
13b5e99277be32ac4870cbcab79ac5087aeb81d9 | 6baa03d2d25d4685cd94265bd0b5033ef185c2c9 | /TGL/src/interface/TGLinterfacePrint.cpp | 30c2ca0b12ee3d5cf70fa6b45995b3fc5033201b | []
| no_license | neiderm/transball | 6ac83b8dd230569d45a40f1bd0085bebdc4a5b94 | 458dd1a903ea4fad582fb494c6fd773e3ab8dfd2 | refs/heads/master | 2021-01-10T07:01:43.565438 | 2011-12-12T23:53:54 | 2011-12-12T23:53:54 | 55,928,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,359 | cpp | #ifdef KITSCHY_DEBUG_MEMORY
#include "debug_memorymanager.h"
#endif
#ifdef _WIN32
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
#include "string.h"
#include "gl.h"
#include "glu.h"
#include "SDL.h"
#include "SDL_mixer.h"
#include "SDL_ttf.h"
#include "SDL_rotozoom.h"
#include "List.h"
#include "Symbol.h"
#include "auxiliar.h"
#include "GLTile.h"
#include "keyboardstate.h"
#include "debug.h"
#include "TGLapp.h"
#include "TGLinterface.h"
#define TEXT_TILE_BUFFER_SIZE 100
class PrintBuffer {
public:
~PrintBuffer() {
delete []text;
delete tile;
} //
TTF_Font *font;
char *text;
GLTile *tile;
};
// This stores the last text messages we printed so that we are not generating new tiles all the time (and save CPU time):
List<PrintBuffer> text_tile_buffer;
void TGLinterface::clear_print_cache(void)
{
#ifdef __DEBUG_MESSAGES
output_debug_message("TGLinterface: Clearing print cache... showing textures used:\n");
{
PrintBuffer *pb;
text_tile_buffer.Rewind();
while(text_tile_buffer.Iterate(pb)) {
output_debug_message("%i -> '%s'\n",int(pb->tile->get_texture(0)),pb->text);
} // while
}
#endif
text_tile_buffer.Delete();
} /* TGLinterface::clear_print_cache */
GLTile *get_text_tile(char *text,TTF_Font *font)
{
PrintBuffer *pb;
text_tile_buffer.Rewind();
while(text_tile_buffer.Iterate(pb)) {
#ifdef __DEBUG_MESSAGES
if (pb->tile->get_texture(0)<0) {
output_debug_message("TGLinterface: Weird stuff just happened!\n");
} // if
#endif
if (pb->font==font && strcmp(pb->text,text)==0) {
// Move it the text to the top of the list to indicate that it has been used:
text_tile_buffer.DeleteElement(pb);
text_tile_buffer.Insert(pb);
#ifdef __DEBUG_MESSAGES
if (pb->tile->get_texture(0)<0) {
output_debug_message("TGLinterface: Weird stuff just happened (2)!\n");
} // if
#endif
return pb->tile;
} // if
} // if
//#ifdef __DEBUG_MESSAGES
// output_debug_message("New text message '%s', current number ot text tiles: %i\n",text,text_tile_buffer.Length());
//#endif
while(text_tile_buffer.Length()>=TEXT_TILE_BUFFER_SIZE) {
pb=text_tile_buffer.Extract();
delete pb;
} // while
{
GLTile *tile;
SDL_Surface *sfc;
SDL_Color c;
c.r=255;
c.g=255;
c.b=255;
sfc=TTF_RenderText_Blended(font,text,c);
tile=new GLTile(sfc);
tile->set_smooth();
pb=new PrintBuffer();
pb->font=font;
pb->text=new char[strlen(text)+1];
strcpy(pb->text,text);
pb->tile=tile;
text_tile_buffer.Insert(pb);
#ifdef __DEBUG_MESSAGES
if (pb->tile->get_texture(0)<0) {
output_debug_message("TGLinterface: Even weirdest stuff just happened!\n");
} // if
#endif
return tile;
}
} /* get_text_tile */
void TGLinterface::print_left(char *text,TTF_Font *font,float x,float y)
{
GLTile *tile;
tile=get_text_tile(text,font);
glNormal3f(0,0,1);
tile->set_hotspot(0,tile->get_dy());
tile->draw(x,y,0,0,1);
} /* TGLinterface::print_left */
void TGLinterface::print_center(char *text,TTF_Font *font,float x,float y)
{
GLTile *tile;
tile=get_text_tile(text,font);
glNormal3f(0,0,1);
tile->set_hotspot(tile->get_dx()/2,tile->get_dy());
tile->draw(x,y,0,0,1);
} /* TGLinterface::print_center */
void TGLinterface::print_left(char *text,TTF_Font *font,float x,float y,float r,float g,float b,float a)
{
GLTile *tile;
tile=get_text_tile(text,font);
glNormal3f(0,0,1);
tile->set_hotspot(0,tile->get_dy());
tile->draw(r,g,b,a,x,y,0,0,1);
} /* TGLinterface::print_left */
void TGLinterface::print_center(char *text,TTF_Font *font,float x,float y,float r,float g,float b,float a)
{
GLTile *tile;
tile=get_text_tile(text,font);
glNormal3f(0,0,1);
tile->set_hotspot(tile->get_dx()/2,tile->get_dy());
tile->draw(r,g,b,a,x,y,0,0,1);
} /* TGLinterface::print_center */
void TGLinterface::print_centered(char *text,TTF_Font *font,float x,float y,float r,float g,float b,float a,float angle,float scale)
{
GLTile *tile;
tile=get_text_tile(text,font);
glNormal3f(0,0,1);
tile->set_hotspot(tile->get_dx()/2,tile->get_dy()/2);
tile->draw(r,g,b,a,x,y,0,angle,scale);
} /* TGLinterface::print_center */
| [
"santi.ontanon@535450eb-5f2b-0410-a0e9-a13dc2d1f197"
]
| [
[
[
1,
190
]
]
]
|
73dfd39d6f02460f7234a51fa7f660daeeefc503 | 6c8c4728e608a4badd88de181910a294be56953a | /HttpUtilities/HttpTask.cpp | ae28ddfc82da5b9eabf6e1ce6a81fc8dde50a283 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,837 | cpp | // For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "HttpTask.h"
namespace HttpUtilities
{
HttpTask::HttpTask() :
Foundation::ThreadTask("HttpRequest"),
continuous_(false)
{
}
HttpTask::HttpTask(const std::string& task_description, bool continuous) :
Foundation::ThreadTask(task_description),
continuous_(continuous)
{
}
void HttpTask::SetContinuous(bool enable)
{
continuous_ = enable;
}
void HttpTask::Work()
{
while (ShouldRun())
{
WaitForRequests();
boost::shared_ptr<HttpTaskRequest> request = GetNextRequest<HttpTaskRequest>();
if (request)
{
HttpUtilities::HttpRequest http;
http.SetUrl(request->url_);
http.SetMethod(request->method_);
http.SetTimeout(request->timeout_);
if (request->data_.size())
{
http.SetRequestData(request->content_type_, request->data_);
}
http.Perform();
boost::shared_ptr<HttpTaskResult> result(new HttpTaskResult());
result->tag_ = request->tag_;
result->success_ = http.GetSuccess();
result->reason_ = http.GetReason();
result->data_ = http.GetResponseData();
if (continuous_)
QueueResult<HttpTaskResult>(result);
else
SetResult<HttpTaskResult>(result);
}
if (!continuous_)
break;
}
}
} | [
"cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
62
]
]
]
|
4472dbfd925fd8402bbde7eda66ef23ed2d31a20 | 22d9640edca14b31280fae414f188739a82733e4 | /Code/VTK/include/vtk-5.2/vtkDistributedStreamTracer.h | 172698ba14ac6df573701df4a9223babe22297c2 | []
| no_license | tack1/Casam | ad0a98febdb566c411adfe6983fcf63442b5eed5 | 3914de9d34c830d4a23a785768579bea80342f41 | refs/heads/master | 2020-04-06T03:45:40.734355 | 2009-06-10T14:54:07 | 2009-06-10T14:54:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,528 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkDistributedStreamTracer.h,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkDistributedStreamTracer - Distributed streamline generator
// .SECTION Description
// This filter integrates streamlines on a distributed dataset. It is
// essentially a serial algorithm: only one process is active at one
// time and it is not more efficient than a single process integration.
// It is useful when the data is too large to be on one process and
// has to be kept distributed.
// .SECTION See Also
// vtkStreamTracer vtkPStreamTracer
#ifndef __vtkDistributedStreamTracer_h
#define __vtkDistributedStreamTracer_h
#include "vtkPStreamTracer.h"
class VTK_PARALLEL_EXPORT vtkDistributedStreamTracer : public vtkPStreamTracer
{
public:
vtkTypeRevisionMacro(vtkDistributedStreamTracer,vtkPStreamTracer);
void PrintSelf(ostream& os, vtkIndent indent);
static vtkDistributedStreamTracer *New();
protected:
vtkDistributedStreamTracer();
~vtkDistributedStreamTracer();
void ForwardTask(double seed[3],
int direction,
int isNewSeed,
int lastid,
int lastCellId,
int currentLine,
double* firstNormal,
double propagation,
vtkIdType numSteps);
int ProcessTask(double seed[3],
int direction,
int isNewSeed,
int lastid,
int lastCellId,
int currentLine,
double* firstNormal,
double propagation,
vtkIdType numSteps);
int ProcessNextLine(int currentLine);
int ReceiveAndProcessTask();
virtual void ParallelIntegrate();
private:
vtkDistributedStreamTracer(const vtkDistributedStreamTracer&); // Not implemented.
void operator=(const vtkDistributedStreamTracer&); // Not implemented.
};
#endif
| [
"nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f"
]
| [
[
[
1,
74
]
]
]
|
2b4ec39d6fce7d97ac281ff6f596d434da5d00fc | 672d939ad74ccb32afe7ec11b6b99a89c64a6020 | /Misc/FTP-Union/FTPClientRelease/FTPClientDlg.h | d093d153237596df5acc83a0a4ff56aa7756bb13 | []
| no_license | cloudlander/legacy | a073013c69e399744de09d649aaac012e17da325 | 89acf51531165a29b35e36f360220eeca3b0c1f6 | refs/heads/master | 2022-04-22T14:55:37.354762 | 2009-04-11T13:51:56 | 2009-04-11T13:51:56 | 256,939,313 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,173 | h | // FTPClientDlg.h : header file
//
#if !defined(AFX_FTPCLIENTDLG_H__B02B8026_7EA2_492D_838B_66C3E9DFD6A8__INCLUDED_)
#define AFX_FTPCLIENTDLG_H__B02B8026_7EA2_492D_838B_66C3E9DFD6A8__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "FTPClient.h"
class CSystemTray;
/////////////////////////////////////////////////////////////////////////////
// CFTPClientDlg dialog
class CFTPClientDlg : public CDialog
{
// Construction
public:
CFTPClientDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CFTPClientDlg)
enum { IDD = IDD_FTPCLIENT_DIALOG };
CIPAddressCtrl m_IPFtp;
CIPAddressCtrl m_IPAuthSvr;
CString m_AuthPwd;
CString m_AuthUsr;
CString m_FtpPwd;
CString m_FtpUsr;
UINT m_Interval;
CString m_Path;
BOOL m_NeedLog;
BOOL m_NeedLoop;
BOOL m_NeedUser;
UINT m_Port;
//}}AFX_DATA
BOOL m_bFirstRun;
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CFTPClientDlg)
public:
virtual BOOL DestroyWindow();
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CFTPClientDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnSTRestore();
afx_msg void OnSTExit();
afx_msg void OnStart();
afx_msg void OnNeeduser();
afx_msg void OnNeedlog();
afx_msg void OnNeedloop();
afx_msg void OnBrowse();
afx_msg void OnAuthenticate();
//}}AFX_MSG(CFTPClientDlg)
DECLARE_MESSAGE_MAP()
CWinThread *th;
//// Internal support functions
void SetupTrayIcon();
void SetupTaskBarButton();
//// Internal data
bool bMinimized_;
CSystemTray* pTrayIcon_;
int nTrayNotificationMsg_;
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_FTPCLIENTDLG_H__B02B8026_7EA2_492D_838B_66C3E9DFD6A8__INCLUDED_)
| [
"xmzhang@5428276e-be0b-f542-9301-ee418ed919ad"
]
| [
[
[
1,
88
]
]
]
|
cd37f5fcc217f887b1438c116cb5e2af633498e7 | a04058c189ce651b85f363c51f6c718eeb254229 | /Src/Forms/ConnectionProgressForm.cpp | d559c6ed7dc31641edbe9f63d9365d46047235f5 | []
| no_license | kjk/moriarty-palm | 090f42f61497ecf9cc232491c7f5351412fba1f3 | a83570063700f26c3553d5f331968af7dd8ff869 | refs/heads/master | 2016-09-05T19:04:53.233536 | 2006-04-04T06:51:31 | 2006-04-04T06:51:31 | 18,799 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,608 | cpp | #include "ConnectionProgressForm.hpp"
#include "MoriartyPreferences.hpp"
#include "LookupManager.hpp"
#include "MoriartyApplication.hpp"
#include <SysUtils.hpp>
class MoriartyLookupProgressReporter: public LookupProgressReporter {
uint_t lastPercent_;
public:
MoriartyLookupProgressReporter():
lastPercent_(0) {}
void showProgress(const LookupProgressReportingSupport& support, Graphics& graphics, const ArsRectangle& bounds, bool clearBkg);
~MoriartyLookupProgressReporter();
};
void MoriartyLookupProgressReporter::showProgress(const LookupProgressReportingSupport& support, Graphics& graphics, const ArsRectangle& bounds, bool clearBkg)
{
if (clearBkg)
graphics.erase(bounds);
ArsRectangle rect(bounds);
rect.explode(2, 2, -4, -4);
Graphics::FontSetter setFont(graphics, Font());
const char_t* text=support.statusText;
uint_t length=tstrlen(text);
uint_t width=rect.width();
graphics.charsInWidth(text, length, width);
graphics.drawText(text, length, rect.topLeft);
uint_t percent=support.percentProgress();
if (support.percentProgressDisabled==percent)
percent=0;
lastPercent_=percent=std::max(percent, lastPercent_);
rect.y()+=(graphics.fontHeight()+2);
rect.height()=12;
PatternType oldPattern=WinGetPatternType();
WinSetPatternType(blackPattern);
RectangleType nativeRec=toNative(rect);
nativeRec.extent.x*=percent;
nativeRec.extent.x/=100;
WinPaintRectangle(&nativeRec, 0);
nativeRec.topLeft.x+=nativeRec.extent.x;
nativeRec.extent.x=rect.width()-nativeRec.extent.x;
WinSetPatternType(grayPattern);
WinPaintRectangle(&nativeRec, 0);
WinSetPatternType(oldPattern);
}
MoriartyLookupProgressReporter::~MoriartyLookupProgressReporter()
{}
void ConnectionProgressForm::attachControls()
{
MoriartyForm::attachControls();
cancelButton_.attach(cancelButton);
}
void ConnectionProgressForm::draw(UInt16 updateCode)
{
Graphics graphics(windowHandle());
MoriartyForm::draw(updateCode);
ArsRectangle rect;
bounds(rect);
rect.explode(2, 16, -4, -34);
if (lookupManager_->lookupInProgress())
{
WinDisplayToWindowPt(reinterpret_cast<Coord*>(&rect.topLeft.x), reinterpret_cast<Coord*>(&rect.topLeft.y));
lookupManager_->showProgress(graphics, rect);
}
}
void ConnectionProgressForm::resize(const ArsRectangle& screenBounds)
{
ArsRectangle bounds;
this->bounds(bounds);
bounds.x()=2;
bounds.y()=screenBounds.height()-62;
bounds.width()=screenBounds.width()-4;
bounds.height()=60;
setBounds(bounds);
cancelButton_.anchor(bounds, anchorLeftEdge, 44, anchorTopEdge, 15);
update();
}
bool ConnectionProgressForm::handleEvent(EventType& event)
{
bool handled=false;
switch (event.eType)
{
case ctlSelectEvent:
handleControlSelected(event);
handled=true;
break;
case LookupManager::lookupStartedEvent:
case LookupManager::lookupProgressEvent:
update();
handled=true;
break;
case LookupManager::lookupFinishedEvent:
handleLookupFinished(event);
handled=true;
break;
default:
handled=MoriartyForm::handleEvent(event);
}
return handled;
}
ConnectionProgressForm::ConnectionProgressForm(MoriartyApplication& app):
MoriartyForm(app, connectionProgressForm, true),
lookupManager_(app.lookupManager),
cancelButton_(*this)
{
assert(0!=lookupManager_);
lookupManager_->setProgressReporter(new MoriartyLookupProgressReporter());
}
ConnectionProgressForm::~ConnectionProgressForm()
{
lookupManager_->setProgressReporter(0);
}
void ConnectionProgressForm::handleControlSelected(const EventType& event)
{
assert(cancelButton==event.data.ctlSelect.controlID);
if (lookupManager_->lookupInProgress())
lookupManager_->abortConnections();
closePopup();
sendEvent(LookupManager::lookupFinishedEvent,LookupFinishedEventData(lookupResultConnectionCancelledByUser));
}
void ConnectionProgressForm::handleLookupFinished(const EventType& event)
{
const LookupFinishedEventData& data=reinterpret_cast<const LookupFinishedEventData&>(event.data);
closePopup();
sendEvent(LookupManager::lookupFinishedEvent, data);
}
| [
"andrzejc@a75a507b-23da-0310-9e0c-b29376b93a3c"
]
| [
[
[
1,
148
]
]
]
|
0eb4df73b15cbf3884812e282af91fcc3853e39c | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /wtl80/include/atlfind.h | 2de73facf38283a517f4595bfad381619c8ac550 | [
"MS-PL"
]
| permissive | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 28,262 | h | // Windows Template Library - WTL version 8.1
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This file is a part of the Windows Template Library.
// The use and distribution terms for this software are covered by the
// Microsoft Permissive License (Ms-PL) which can be found in the file
// Ms-PL.txt at the root of this distribution.
#ifndef __ATLFIND_H__
#define __ATLFIND_H__
#pragma once
#ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix)
#endif
#ifdef _WIN32_WCE
#error atlfind.h is not supported on Windows CE
#endif
#ifndef __ATLCTRLS_H__
#error atlfind.h requires atlctrls.h to be included first
#endif
#ifndef __ATLDLGS_H__
#error atlfind.h requires atldlgs.h to be included first
#endif
#if !((defined(__ATLMISC_H__) && defined(_WTL_USE_CSTRING)) || defined(__ATLSTR_H__))
#error atlfind.h requires CString (either from ATL's atlstr.h or WTL's atlmisc.h with _WTL_USE_CSTRING)
#endif
///////////////////////////////////////////////////////////////////////////////
// Classes in this file:
//
// CEditFindReplaceImplBase<T, TFindReplaceDialog>
// CEditFindReplaceImpl<T, TFindReplaceDialog>
// CRichEditFindReplaceImpl<T, TFindReplaceDialog>
namespace WTL
{
///////////////////////////////////////////////////////////////////////////////
// CEditFindReplaceImplBase - Base class for mixin classes that
// help implement Find/Replace for CEdit or CRichEditCtrl based window classes.
template <class T, class TFindReplaceDialog = CFindReplaceDialog>
class CEditFindReplaceImplBase
{
protected:
// Typedefs
typedef CEditFindReplaceImplBase<T, TFindReplaceDialog> thisClass;
// Data members
TFindReplaceDialog* m_pFindReplaceDialog;
_CSTRING_NS::CString m_sFindNext, m_sReplaceWith;
BOOL m_bFindOnly, m_bFirstSearch, m_bMatchCase, m_bWholeWord, m_bFindDown;
LONG m_nInitialSearchPos;
HCURSOR m_hOldCursor;
// Enumerations
enum TranslationTextItem
{
eText_OnReplaceAllMessage = 0,
eText_OnReplaceAllTitle = 1,
eText_OnTextNotFoundMessage = 2,
eText_OnTextNotFoundTitle = 3
};
public:
// Constructors
CEditFindReplaceImplBase() :
m_pFindReplaceDialog(NULL),
m_bFindOnly(TRUE),
m_bFirstSearch(TRUE),
m_bMatchCase(FALSE),
m_bWholeWord(FALSE),
m_bFindDown(TRUE),
m_nInitialSearchPos(0),
m_hOldCursor(NULL)
{
}
// Message Handlers
BEGIN_MSG_MAP(thisClass)
ALT_MSG_MAP(1)
MESSAGE_HANDLER(WM_DESTROY , OnDestroy )
MESSAGE_HANDLER(TFindReplaceDialog::GetFindReplaceMsg() , OnFindReplaceCmd )
COMMAND_ID_HANDLER(ID_EDIT_FIND , OnEditFind )
COMMAND_ID_HANDLER(ID_EDIT_REPEAT , OnEditRepeat )
COMMAND_ID_HANDLER(ID_EDIT_REPLACE , OnEditReplace )
END_MSG_MAP()
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
if (m_pFindReplaceDialog != NULL)
{
m_pFindReplaceDialog->SendMessage(WM_CLOSE);
ATLASSERT(m_pFindReplaceDialog == NULL);
}
bHandled = FALSE;
return 0;
}
LRESULT OnFindReplaceCmd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
{
T* pT = static_cast<T*>(this);
TFindReplaceDialog* pDialog = TFindReplaceDialog::GetNotifier(lParam);
if (pDialog == NULL)
{
ATLASSERT(FALSE);
::MessageBeep(MB_ICONERROR);
return 1;
}
ATLASSERT(pDialog == m_pFindReplaceDialog);
LPFINDREPLACE findReplace = (LPFINDREPLACE)lParam;
if ((m_pFindReplaceDialog != NULL) && (findReplace != NULL))
{
if (pDialog->FindNext())
{
pT->OnFindNext(pDialog->GetFindString(), pDialog->SearchDown(),
pDialog->MatchCase(), pDialog->MatchWholeWord());
}
else if (pDialog->ReplaceCurrent())
{
pT->OnReplaceSel(pDialog->GetFindString(),
pDialog->SearchDown(), pDialog->MatchCase(), pDialog->MatchWholeWord(),
pDialog->GetReplaceString());
}
else if (pDialog->ReplaceAll())
{
pT->OnReplaceAll(pDialog->GetFindString(), pDialog->GetReplaceString(),
pDialog->MatchCase(), pDialog->MatchWholeWord());
}
else if (pDialog->IsTerminating())
{
// Dialog is going away (but hasn't gone away yet)
// OnFinalMessage will "delete this"
pT->OnTerminatingFindReplaceDialog(m_pFindReplaceDialog);
m_pFindReplaceDialog = NULL;
}
}
return 0;
}
LRESULT OnEditFind(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
T* pT = static_cast<T*>(this);
pT->FindReplace(TRUE);
return 0;
}
LRESULT OnEditRepeat(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
T* pT = static_cast<T*>(this);
// If the user is holding down SHIFT when hitting F3, we'll
// search in reverse. Otherwise, we'll search forward.
// (be sure to have an accelerator mapped to ID_EDIT_REPEAT
// for both F3 and Shift+F3)
m_bFindDown = !((::GetKeyState(VK_SHIFT) & 0x8000) == 0x8000);
if (m_sFindNext.IsEmpty())
{
pT->FindReplace(TRUE);
}
else
{
if (!pT->FindTextSimple(m_sFindNext, m_bMatchCase, m_bWholeWord, m_bFindDown))
pT->TextNotFound(m_sFindNext);
}
return 0;
}
LRESULT OnEditReplace(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled)
{
T* pT = static_cast<T*>(this);
DWORD style = pT->GetStyle();
if ((style & ES_READONLY) != ES_READONLY)
{
pT->FindReplace(FALSE);
}
else
{
// Don't allow replace when the edit control is read only
bHandled = FALSE;
}
return 0;
}
// Operations (overrideable)
TFindReplaceDialog* CreateFindReplaceDialog(BOOL bFindOnly, // TRUE for Find, FALSE for FindReplace
LPCTSTR lpszFindWhat,
LPCTSTR lpszReplaceWith = NULL,
DWORD dwFlags = FR_DOWN,
HWND hWndParent = NULL)
{
// You can override all of this in a derived class
TFindReplaceDialog* findReplaceDialog = new TFindReplaceDialog();
if (findReplaceDialog == NULL)
{
::MessageBeep(MB_ICONHAND);
}
else
{
HWND hWndFindReplace = findReplaceDialog->Create(bFindOnly,
lpszFindWhat, lpszReplaceWith, dwFlags, hWndParent);
if (hWndFindReplace == NULL)
{
delete findReplaceDialog;
findReplaceDialog = NULL;
}
else
{
findReplaceDialog->SetActiveWindow();
findReplaceDialog->ShowWindow(SW_SHOW);
}
}
return findReplaceDialog;
}
void AdjustDialogPosition(HWND hWndDialog)
{
ATLASSERT((hWndDialog != NULL) && ::IsWindow(hWndDialog));
T* pT = static_cast<T*>(this);
LONG nStartChar = 0, nEndChar = 0;
// Send EM_GETSEL so we can use both Edit and RichEdit
// (CEdit::GetSel uses int&, and CRichEditCtrlT::GetSel uses LONG&)
::SendMessage(pT->m_hWnd, EM_GETSEL, (WPARAM)&nStartChar, (LPARAM)&nEndChar);
POINT point = pT->PosFromChar(nStartChar);
::ClientToScreen(pT->GetParent(), &point);
CRect rect;
::GetWindowRect(hWndDialog, &rect);
if (rect.PtInRect(point))
{
if (point.y > rect.Height())
{
rect.OffsetRect(0, point.y - rect.bottom - 20);
}
else
{
int nVertExt = GetSystemMetrics(SM_CYSCREEN);
if (point.y + rect.Height() < nVertExt)
rect.OffsetRect(0, 40 + point.y - rect.top);
}
::MoveWindow(hWndDialog, rect.left, rect.top, rect.Width(), rect.Height(), TRUE);
}
}
DWORD GetFindReplaceDialogFlags(void) const
{
DWORD dwFlags = 0;
if (m_bFindDown)
dwFlags |= FR_DOWN;
if (m_bMatchCase)
dwFlags |= FR_MATCHCASE;
if (m_bWholeWord)
dwFlags |= FR_WHOLEWORD;
return dwFlags;
}
void FindReplace(BOOL bFindOnly)
{
T* pT = static_cast<T*>(this);
m_bFirstSearch = TRUE;
if (m_pFindReplaceDialog != NULL)
{
if (m_bFindOnly == bFindOnly)
{
m_pFindReplaceDialog->SetActiveWindow();
m_pFindReplaceDialog->ShowWindow(SW_SHOW);
return;
}
else
{
m_pFindReplaceDialog->SendMessage(WM_CLOSE);
ATLASSERT(m_pFindReplaceDialog == NULL);
}
}
ATLASSERT(m_pFindReplaceDialog == NULL);
_CSTRING_NS::CString findNext;
pT->GetSelText(findNext);
// if selection is empty or spans multiple lines use old find text
if (findNext.IsEmpty() || (findNext.FindOneOf(_T("\n\r")) != -1))
findNext = m_sFindNext;
_CSTRING_NS::CString replaceWith = m_sReplaceWith;
DWORD dwFlags = pT->GetFindReplaceDialogFlags();
m_pFindReplaceDialog = pT->CreateFindReplaceDialog(bFindOnly,
findNext, replaceWith, dwFlags, pT->operator HWND());
ATLASSERT(m_pFindReplaceDialog != NULL);
if (m_pFindReplaceDialog != NULL)
m_bFindOnly = bFindOnly;
}
BOOL SameAsSelected(LPCTSTR lpszCompare, BOOL bMatchCase, BOOL /*bWholeWord*/)
{
T* pT = static_cast<T*>(this);
// check length first
size_t nLen = lstrlen(lpszCompare);
LONG nStartChar = 0, nEndChar = 0;
// Send EM_GETSEL so we can use both Edit and RichEdit
// (CEdit::GetSel uses int&, and CRichEditCtrlT::GetSel uses LONG&)
::SendMessage(pT->m_hWnd, EM_GETSEL, (WPARAM)&nStartChar, (LPARAM)&nEndChar);
if (nLen != (size_t)(nEndChar - nStartChar))
return FALSE;
// length is the same, check contents
_CSTRING_NS::CString selectedText;
pT->GetSelText(selectedText);
return (bMatchCase && selectedText.Compare(lpszCompare) == 0) ||
(!bMatchCase && selectedText.CompareNoCase(lpszCompare) == 0);
}
void TextNotFound(LPCTSTR lpszFind)
{
T* pT = static_cast<T*>(this);
m_bFirstSearch = TRUE;
pT->OnTextNotFound(lpszFind);
}
_CSTRING_NS::CString GetTranslationText(enum TranslationTextItem eItem) const
{
_CSTRING_NS::CString text;
switch (eItem)
{
case eText_OnReplaceAllMessage:
text = _T("Replaced %d occurances of \"%s\" with \"%s\"");
break;
case eText_OnReplaceAllTitle:
text = _T("Replace All");
break;
case eText_OnTextNotFoundMessage:
text = _T("Unable to find the text \"%s\"");
break;
case eText_OnTextNotFoundTitle:
text = _T("Text not found");
break;
}
return text;
}
// Overrideable Handlers
void OnFindNext(LPCTSTR lpszFind, BOOL bFindDown, BOOL bMatchCase, BOOL bWholeWord)
{
T* pT = static_cast<T*>(this);
m_sFindNext = lpszFind;
m_bMatchCase = bMatchCase;
m_bWholeWord = bWholeWord;
m_bFindDown = bFindDown;
if (!pT->FindTextSimple(m_sFindNext, m_bMatchCase, m_bWholeWord, m_bFindDown))
pT->TextNotFound(m_sFindNext);
else
pT->AdjustDialogPosition(m_pFindReplaceDialog->operator HWND());
}
void OnReplaceSel(LPCTSTR lpszFind, BOOL bFindDown, BOOL bMatchCase, BOOL bWholeWord, LPCTSTR lpszReplace)
{
T* pT = static_cast<T*>(this);
m_sFindNext = lpszFind;
m_sReplaceWith = lpszReplace;
m_bMatchCase = bMatchCase;
m_bWholeWord = bWholeWord;
m_bFindDown = bFindDown;
if (pT->SameAsSelected(m_sFindNext, m_bMatchCase, m_bWholeWord))
pT->ReplaceSel(m_sReplaceWith);
if (!pT->FindTextSimple(m_sFindNext, m_bMatchCase, m_bWholeWord, m_bFindDown))
pT->TextNotFound(m_sFindNext);
else
pT->AdjustDialogPosition(m_pFindReplaceDialog->operator HWND());
}
void OnReplaceAll(LPCTSTR lpszFind, LPCTSTR lpszReplace, BOOL bMatchCase, BOOL bWholeWord)
{
T* pT = static_cast<T*>(this);
m_sFindNext = lpszFind;
m_sReplaceWith = lpszReplace;
m_bMatchCase = bMatchCase;
m_bWholeWord = bWholeWord;
m_bFindDown = TRUE;
// no selection or different than what looking for
if (!pT->SameAsSelected(m_sFindNext, m_bMatchCase, m_bWholeWord))
{
if (!pT->FindTextSimple(m_sFindNext, m_bMatchCase, m_bWholeWord, m_bFindDown))
{
pT->TextNotFound(m_sFindNext);
return;
}
}
pT->OnReplaceAllCoreBegin();
int replaceCount=0;
do
{
++replaceCount;
pT->ReplaceSel(m_sReplaceWith);
} while (pT->FindTextSimple(m_sFindNext, m_bMatchCase, m_bWholeWord, m_bFindDown));
pT->OnReplaceAllCoreEnd(replaceCount);
}
void OnReplaceAllCoreBegin()
{
T* pT = static_cast<T*>(this);
m_hOldCursor = ::SetCursor(::LoadCursor(NULL, IDC_WAIT));
pT->HideSelection(TRUE, FALSE);
}
void OnReplaceAllCoreEnd(int replaceCount)
{
T* pT = static_cast<T*>(this);
pT->HideSelection(FALSE, FALSE);
::SetCursor(m_hOldCursor);
_CSTRING_NS::CString message = pT->GetTranslationText(eText_OnReplaceAllMessage);
if (message.GetLength() > 0)
{
_CSTRING_NS::CString formattedMessage;
formattedMessage.Format(message,
replaceCount, m_sFindNext, m_sReplaceWith);
if (m_pFindReplaceDialog != NULL)
{
m_pFindReplaceDialog->MessageBox(formattedMessage,
pT->GetTranslationText(eText_OnReplaceAllTitle),
MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
}
else
{
pT->MessageBox(formattedMessage,
pT->GetTranslationText(eText_OnReplaceAllTitle),
MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
}
}
}
void OnTextNotFound(LPCTSTR lpszFind)
{
T* pT = static_cast<T*>(this);
_CSTRING_NS::CString message = pT->GetTranslationText(eText_OnTextNotFoundMessage);
if (message.GetLength() > 0)
{
_CSTRING_NS::CString formattedMessage;
formattedMessage.Format(message, lpszFind);
if (m_pFindReplaceDialog != NULL)
{
m_pFindReplaceDialog->MessageBox(formattedMessage,
pT->GetTranslationText(eText_OnTextNotFoundTitle),
MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
}
else
{
pT->MessageBox(formattedMessage,
pT->GetTranslationText(eText_OnTextNotFoundTitle),
MB_OK | MB_ICONINFORMATION | MB_APPLMODAL);
}
}
else
{
::MessageBeep(MB_ICONHAND);
}
}
void OnTerminatingFindReplaceDialog(TFindReplaceDialog*& /*findReplaceDialog*/)
{
}
};
///////////////////////////////////////////////////////////////////////////////
// CEditFindReplaceImpl - Mixin class for implementing Find/Replace for CEdit
// based window classes.
// Chain to CEditFindReplaceImpl message map. Your class must also derive from CEdit.
// Example:
// class CMyEdit : public CWindowImpl<CMyEdit, CEdit>,
// public CEditFindReplaceImpl<CMyEdit>
// {
// public:
// BEGIN_MSG_MAP(CMyEdit)
// // your handlers...
// CHAIN_MSG_MAP_ALT(CEditFindReplaceImpl<CMyEdit>, 1)
// END_MSG_MAP()
// // other stuff...
// };
template <class T, class TFindReplaceDialog = CFindReplaceDialog>
class CEditFindReplaceImpl : public CEditFindReplaceImplBase<T, TFindReplaceDialog>
{
protected:
typedef CEditFindReplaceImpl<T, TFindReplaceDialog> thisClass;
typedef CEditFindReplaceImplBase<T, TFindReplaceDialog> baseClass;
// Data members
LPTSTR m_pShadowBuffer; // Special shadow buffer only used in some cases.
UINT m_nShadowSize;
int m_bShadowBufferNeeded; // TRUE, FALSE, < 0 => Need to check
public:
// Constructors
CEditFindReplaceImpl() :
m_pShadowBuffer(NULL),
m_nShadowSize(0),
m_bShadowBufferNeeded(-1)
{
}
virtual ~CEditFindReplaceImpl()
{
if (m_pShadowBuffer != NULL)
{
delete [] m_pShadowBuffer;
m_pShadowBuffer = NULL;
}
}
// Message Handlers
BEGIN_MSG_MAP(thisClass)
ALT_MSG_MAP(1)
CHAIN_MSG_MAP_ALT(baseClass, 1)
END_MSG_MAP()
// Operations
// Supported only for RichEdit, so this does nothing for Edit
void HideSelection(BOOL /*bHide*/ = TRUE, BOOL /*bChangeStyle*/ = FALSE)
{
}
// Operations (overrideable)
BOOL FindTextSimple(LPCTSTR lpszFind, BOOL bMatchCase, BOOL bWholeWord, BOOL bFindDown = TRUE)
{
T* pT = static_cast<T*>(this);
ATLASSERT(lpszFind != NULL);
ATLASSERT(*lpszFind != _T('\0'));
UINT nLen = pT->GetBufferLength();
int nStartChar = 0 , nEndChar = 0;
pT->GetSel(nStartChar, nEndChar);
UINT nStart = nStartChar;
int iDir = bFindDown ? +1 : -1;
// can't find a match before the first character
if (nStart == 0 && iDir < 0)
return FALSE;
LPCTSTR lpszText = pT->LockBuffer();
bool isDBCS = false;
#ifdef _MBCS
CPINFO info = { 0 };
::GetCPInfo(::GetOEMCP(), &info);
isDBCS = (info.MaxCharSize > 1);
#endif
if (iDir < 0)
{
// always go back one for search backwards
nStart -= int((lpszText + nStart) - ::CharPrev(lpszText, lpszText + nStart));
}
else if (nStartChar != nEndChar && pT->SameAsSelected(lpszFind, bMatchCase, bWholeWord))
{
// easy to go backward/forward with SBCS
#ifndef _UNICODE
if (::IsDBCSLeadByte(lpszText[nStart]))
nStart++;
#endif
nStart += iDir;
}
// handle search with nStart past end of buffer
UINT nLenFind = ::lstrlen(lpszFind);
if (nStart + nLenFind - 1 >= nLen)
{
if (iDir < 0 && nLen >= nLenFind)
{
if (isDBCS)
{
// walk back to previous character n times
nStart = nLen;
int n = nLenFind;
while (n--)
{
nStart -= int((lpszText + nStart) - ::CharPrev(lpszText, lpszText + nStart));
}
}
else
{
// single-byte character set is easy and fast
nStart = nLen - nLenFind;
}
ATLASSERT(nStart + nLenFind - 1 <= nLen);
}
else
{
pT->UnlockBuffer();
return FALSE;
}
}
// start the search at nStart
LPCTSTR lpsz = lpszText + nStart;
typedef int (WINAPI* CompareProc)(LPCTSTR str1, LPCTSTR str2);
CompareProc pfnCompare = bMatchCase ? lstrcmp : lstrcmpi;
if (isDBCS)
{
// double-byte string search
LPCTSTR lpszStop = NULL;
if (iDir > 0)
{
// start at current and find _first_ occurrance
lpszStop = lpszText + nLen - nLenFind + 1;
}
else
{
// start at top and find _last_ occurrance
lpszStop = lpsz;
lpsz = lpszText;
}
LPCTSTR lpszFound = NULL;
while (lpsz <= lpszStop)
{
#ifndef _UNICODE
if (!bMatchCase || (*lpsz == *lpszFind && (!::IsDBCSLeadByte(*lpsz) || lpsz[1] == lpszFind[1])))
#else
if (!bMatchCase || (*lpsz == *lpszFind && lpsz[1] == lpszFind[1]))
#endif
{
LPTSTR lpch = (LPTSTR)(lpsz + nLenFind);
TCHAR chSave = *lpch;
*lpch = _T('\0');
int nResult = (*pfnCompare)(lpsz, lpszFind);
*lpch = chSave;
if (nResult == 0)
{
lpszFound = lpsz;
if (iDir > 0)
break;
}
}
lpsz = ::CharNext(lpsz);
}
pT->UnlockBuffer();
if (lpszFound != NULL)
{
int n = (int)(lpszFound - lpszText);
pT->SetSel(n, n + nLenFind);
return TRUE;
}
}
else
{
// single-byte string search
UINT nCompare;
if (iDir < 0)
nCompare = (UINT)(lpsz - lpszText) + 1;
else
nCompare = nLen - (UINT)(lpsz - lpszText) - nLenFind + 1;
while (nCompare > 0)
{
ATLASSERT(lpsz >= lpszText);
ATLASSERT(lpsz + nLenFind - 1 <= lpszText + nLen - 1);
LPSTR lpch = (LPSTR)(lpsz + nLenFind);
char chSave = *lpch;
*lpch = '\0';
int nResult = (*pfnCompare)(lpsz, lpszFind);
*lpch = chSave;
if (nResult == 0)
{
pT->UnlockBuffer();
int n = (int)(lpsz - lpszText);
pT->SetSel(n, n + nLenFind);
return TRUE;
}
// restore character at end of search
*lpch = chSave;
// move on to next substring
nCompare--;
lpsz += iDir;
}
pT->UnlockBuffer();
}
return FALSE;
}
LPCTSTR LockBuffer() const
{
const T* pT = static_cast<const T*>(this);
ATLASSERT(pT->m_hWnd != NULL);
BOOL useShadowBuffer = pT->UseShadowBuffer();
if (useShadowBuffer)
{
if (m_pShadowBuffer == NULL || pT->GetModify())
{
ATLASSERT(m_pShadowBuffer != NULL || m_nShadowSize == 0);
UINT nSize = pT->GetWindowTextLength() + 1;
if (nSize > m_nShadowSize)
{
// need more room for shadow buffer
T* pThisNoConst = const_cast<T*>(pT);
delete[] m_pShadowBuffer;
pThisNoConst->m_pShadowBuffer = NULL;
pThisNoConst->m_nShadowSize = 0;
pThisNoConst->m_pShadowBuffer = new TCHAR[nSize];
pThisNoConst->m_nShadowSize = nSize;
}
// update the shadow buffer with GetWindowText
ATLASSERT(m_nShadowSize >= nSize);
ATLASSERT(m_pShadowBuffer != NULL);
pT->GetWindowText(m_pShadowBuffer, nSize);
}
return m_pShadowBuffer;
}
HLOCAL hLocal = pT->GetHandle();
ATLASSERT(hLocal != NULL);
LPCTSTR lpszText = (LPCTSTR)::LocalLock(hLocal);
ATLASSERT(lpszText != NULL);
return lpszText;
}
void UnlockBuffer() const
{
const T* pT = static_cast<const T*>(this);
ATLASSERT(pT->m_hWnd != NULL);
BOOL useShadowBuffer = pT->UseShadowBuffer();
if (!useShadowBuffer)
{
HLOCAL hLocal = pT->GetHandle();
ATLASSERT(hLocal != NULL);
::LocalUnlock(hLocal);
}
}
UINT GetBufferLength() const
{
const T* pT = static_cast<const T*>(this);
ATLASSERT(pT->m_hWnd != NULL);
UINT nLen = 0;
LPCTSTR lpszText = pT->LockBuffer();
if (lpszText != NULL)
nLen = ::lstrlen(lpszText);
pT->UnlockBuffer();
return nLen;
}
LONG EndOfLine(LPCTSTR lpszText, UINT nLen, UINT nIndex) const
{
LPCTSTR lpsz = lpszText + nIndex;
LPCTSTR lpszStop = lpszText + nLen;
while (lpsz < lpszStop && *lpsz != _T('\r'))
++lpsz;
return LONG(lpsz - lpszText);
}
LONG GetSelText(_CSTRING_NS::CString& strText) const
{
const T* pT = static_cast<const T*>(this);
int nStartChar = 0, nEndChar = 0;
pT->GetSel(nStartChar, nEndChar);
ATLASSERT((UINT)nEndChar <= pT->GetBufferLength());
LPCTSTR lpszText = pT->LockBuffer();
LONG nLen = pT->EndOfLine(lpszText, nEndChar, nStartChar) - nStartChar;
SecureHelper::memcpy_x(strText.GetBuffer(nLen), nLen * sizeof(TCHAR), lpszText + nStartChar, nLen * sizeof(TCHAR));
strText.ReleaseBuffer(nLen);
pT->UnlockBuffer();
return nLen;
}
BOOL UseShadowBuffer(void) const
{
const T* pT = static_cast<const T*>(this);
if (pT->m_bShadowBufferNeeded < 0)
{
T* pThisNoConst = const_cast<T*>(pT);
OSVERSIONINFO ovi = { 0 };
ovi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
::GetVersionEx(&ovi);
bool bWin9x = (ovi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS);
if (bWin9x)
{
// Windows 95, 98, ME
// Under Win9x, it is necessary to maintain a shadow buffer.
// It is only updated when the control contents have been changed.
pThisNoConst->m_bShadowBufferNeeded = TRUE;
}
else
{
// Windows NT, 2000, XP, etc.
pThisNoConst->m_bShadowBufferNeeded = FALSE;
#ifndef _UNICODE
// On Windows XP (or later), if common controls version 6 is in use
// (such as via theming), then EM_GETHANDLE will always return a UNICODE string.
// If theming is enabled and Common Controls version 6 is in use,
// you're really not suppose to superclass or subclass common controls
// with an ANSI windows procedure (so its best to only theme if you use UNICODE).
// Using a shadow buffer uses GetWindowText instead, so it solves
// this problem for us (although it makes it a little less efficient).
if ((ovi.dwMajorVersion == 5 && ovi.dwMinorVersion >= 1) || (ovi.dwMajorVersion > 5))
{
// We use DLLVERSIONINFO_private so we don't have to depend on shlwapi.h
typedef struct _DLLVERSIONINFO_private
{
DWORD cbSize;
DWORD dwMajorVersion;
DWORD dwMinorVersion;
DWORD dwBuildNumber;
DWORD dwPlatformID;
} DLLVERSIONINFO_private;
HMODULE hModule = ::LoadLibrary("comctl32.dll");
if (hModule != NULL)
{
typedef HRESULT (CALLBACK *LPFN_DllGetVersion)(DLLVERSIONINFO_private *);
LPFN_DllGetVersion fnDllGetVersion = (LPFN_DllGetVersion)::GetProcAddress(hModule, "DllGetVersion");
if (fnDllGetVersion != NULL)
{
DLLVERSIONINFO_private version = { 0 };
version.cbSize = sizeof(DLLVERSIONINFO_private);
if (SUCCEEDED(fnDllGetVersion(&version)))
{
if (version.dwMajorVersion >= 6)
{
pThisNoConst->m_bShadowBufferNeeded = TRUE;
ATLTRACE2(atlTraceUI, 0, _T("Warning: You have compiled for MBCS/ANSI but are using common controls version 6 or later (likely through a manifest file).\r\n"));
ATLTRACE2(atlTraceUI, 0, _T("If you use common controls version 6 or later, you should only do so for UNICODE builds.\r\n"));
}
}
}
::FreeLibrary(hModule);
hModule = NULL;
}
}
#endif // !_UNICODE
}
}
return (pT->m_bShadowBufferNeeded == TRUE);
}
};
///////////////////////////////////////////////////////////////////////////////
// CRichEditFindReplaceImpl - Mixin class for implementing Find/Replace for CRichEditCtrl
// based window classes.
// Chain to CRichEditFindReplaceImpl message map. Your class must also derive from CRichEditCtrl.
// Example:
// class CMyRichEdit : public CWindowImpl<CMyRichEdit, CRichEditCtrl>,
// public CRichEditFindReplaceImpl<CMyRichEdit>
// {
// public:
// BEGIN_MSG_MAP(CMyRichEdit)
// // your handlers...
// CHAIN_MSG_MAP_ALT(CRichEditFindReplaceImpl<CMyRichEdit>, 1)
// END_MSG_MAP()
// // other stuff...
// };
template <class T, class TFindReplaceDialog = CFindReplaceDialog>
class CRichEditFindReplaceImpl : public CEditFindReplaceImplBase<T, TFindReplaceDialog>
{
protected:
typedef CRichEditFindReplaceImpl<T, TFindReplaceDialog> thisClass;
typedef CEditFindReplaceImplBase<T, TFindReplaceDialog> baseClass;
public:
BEGIN_MSG_MAP(thisClass)
ALT_MSG_MAP(1)
CHAIN_MSG_MAP_ALT(baseClass, 1)
END_MSG_MAP()
// Operations (overrideable)
BOOL FindTextSimple(LPCTSTR lpszFind, BOOL bMatchCase, BOOL bWholeWord, BOOL bFindDown = TRUE)
{
T* pT = static_cast<T*>(this);
ATLASSERT(lpszFind != NULL);
FINDTEXTEX ft = { 0 };
pT->GetSel(ft.chrg);
if (m_bFirstSearch)
{
if (bFindDown)
m_nInitialSearchPos = ft.chrg.cpMin;
else
m_nInitialSearchPos = ft.chrg.cpMax;
m_bFirstSearch = FALSE;
}
#if (_RICHEDIT_VER >= 0x0200)
ft.lpstrText = (LPTSTR)lpszFind;
#else // !(_RICHEDIT_VER >= 0x0200)
USES_CONVERSION;
ft.lpstrText = T2A((LPTSTR)lpszFind);
#endif // !(_RICHEDIT_VER >= 0x0200)
if (ft.chrg.cpMin != ft.chrg.cpMax) // i.e. there is a selection
{
if (bFindDown)
{
ft.chrg.cpMin++;
}
else
{
// won't wraparound backwards
ft.chrg.cpMin = max(ft.chrg.cpMin, 0);
}
}
DWORD dwFlags = bMatchCase ? FR_MATCHCASE : 0;
dwFlags |= bWholeWord ? FR_WHOLEWORD : 0;
ft.chrg.cpMax = pT->GetTextLength() + m_nInitialSearchPos;
if (bFindDown)
{
if (m_nInitialSearchPos >= 0)
ft.chrg.cpMax = pT->GetTextLength();
dwFlags |= FR_DOWN;
ATLASSERT(ft.chrg.cpMax >= ft.chrg.cpMin);
}
else
{
if (m_nInitialSearchPos >= 0)
ft.chrg.cpMax = 0;
dwFlags &= ~FR_DOWN;
ATLASSERT(ft.chrg.cpMax <= ft.chrg.cpMin);
}
BOOL bRet = FALSE;
if (pT->FindAndSelect(dwFlags, ft) != -1)
{
bRet = TRUE; // we found the text
}
else if (m_nInitialSearchPos > 0)
{
// if the original starting point was not the beginning
// of the buffer and we haven't already been here
if (bFindDown)
{
ft.chrg.cpMin = 0;
ft.chrg.cpMax = m_nInitialSearchPos;
}
else
{
ft.chrg.cpMin = pT->GetTextLength();
ft.chrg.cpMax = m_nInitialSearchPos;
}
m_nInitialSearchPos = m_nInitialSearchPos - pT->GetTextLength();
bRet = (pT->FindAndSelect(dwFlags, ft) != -1) ? TRUE : FALSE;
}
return bRet;
}
long FindAndSelect(DWORD dwFlags, FINDTEXTEX& ft)
{
T* pT = static_cast<T*>(this);
LONG index = pT->FindText(dwFlags, ft);
if (index != -1) // i.e. we found something
pT->SetSel(ft.chrgText);
return index;
}
};
}; // namespace WTL
#endif // __ATLFIND_H__
| [
"[email protected]"
]
| [
[
[
1,
1033
]
]
]
|
838bebfc83fb72d6f5b613ce52a96d8f78303430 | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /RenamerDlg.cpp | 8432f457dbfad53e9a91614aa332d5ccf530d99c | []
| no_license | outcast1000/Jaangle | 062c7d8d06e058186cb65bdade68a2ad8d5e7e65 | 18feb537068f1f3be6ecaa8a4b663b917c429e3d | refs/heads/master | 2020-04-08T20:04:56.875651 | 2010-12-25T10:44:38 | 2010-12-25T10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,973 | cpp | // /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.com)
// *
// * This Program is free software; you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation; either version 2, or (at your option)
// * any later version.
// *
// * This Program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
#include "stdafx.h"
#include "TeenSpirit.h"
#include "RenamerDlg.h"
#include "PrgAPI.h"
#include "FileNameTagger.h"
#include "SQLManager.h"
#include "cStringUtils.h"
#define TIMER_UPDATE 100
// CRenamerDlg dialog
IMPLEMENT_DYNAMIC(CRenamerDlg, CDialog)
CRenamerDlg::CRenamerDlg(FullTrackRecordCollection& col, CWnd* pParent /*=NULL*/)
: CDialog(CRenamerDlg::IDD, pParent),
m_col(col),
m_bSomethingChanged(FALSE)
{
ASSERT(col.size() != 0);
}
CRenamerDlg::~CRenamerDlg()
{
}
void CRenamerDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_LST_TAGS, m_lstTags);
DDX_Control(pDX, IDC_CMB_CASING, m_cmbCasing);
DDX_Control(pDX, IDC_CMB_PATTERN, m_cmbPattern);
}
BEGIN_MESSAGE_MAP(CRenamerDlg, CDialog)
ON_BN_CLICKED(IDC_RENAME, &CRenamerDlg::OnBnClickedRename)
ON_BN_CLICKED(IDC_SKIP, &CRenamerDlg::OnBnClickedSkip)
ON_BN_CLICKED(IDC_ALL, &CRenamerDlg::OnBnClickedAll)
ON_BN_CLICKED(IDC_CANCEL, &CRenamerDlg::OnBnClickedCancel)
ON_CBN_EDITCHANGE(IDC_CMB_PATTERN, &CRenamerDlg::UpdatePreview)
ON_CBN_SELCHANGE(IDC_CMB_CASING, &CRenamerDlg::UpdatePreviewDelayed)
ON_CBN_SELCHANGE(IDC_CMB_PATTERN, &CRenamerDlg::UpdatePreviewDelayed)
ON_WM_TIMER()
END_MESSAGE_MAP()
// CRenamerDlg message handlers
void CRenamerDlg::OnBnClickedRename()
{
CString pat;
GetDlgItemText(IDC_CMB_PATTERN, pat);
if (pat.GetLength() == 0)
return;
if (m_col.size() > 0)
{
FullTrackRecordSP& rec = m_col[0];
if (RenameTrack(rec, pat))
OnBnClickedSkip();
else
PRGAPI()->MessageBox(m_hWnd, _T("Operation Failed"));
}
}
BOOL CRenamerDlg::RenameTrack(FullTrackRecordSP& rec, LPCTSTR pat)
{
TCHAR newPathName[MAX_PATH];
TCHAR artist[100];
TCHAR album[100];
TCHAR title[100];
_tcsncpy(artist, rec->artist.name.c_str(), 100);
artist[99] = 0;
_tcsncpy(album, rec->album.name.c_str(), 100);
album[99] = 0;
_tcsncpy(title, rec->track.name.c_str(), 100);
title[99] = 0;
INT curSel = m_cmbCasing.GetCurSel();
switch (curSel)
{
case 1:
_tcsproper(artist);
_tcsproper(album);
_tcsproper(title);
break;
case 2:
_tcsupr(artist);
_tcsupr(album);
_tcsupr(title);
break;
case 3:
_tcslwr(artist);
_tcslwr(album);
_tcslwr(title);
break;
}
FileNameTagger fnTagger;
if (fnTagger.CustomWrite(newPathName,
rec->track.location.c_str(),
pat,
artist,
album,
rec->track.trackNo,
title,
rec->track.year))
{
m_bSomethingChanged = TRUE;
rec->track.location = newPathName;
return PRGAPI()->GetSQLManager()->UpdateTrackRecord(rec->track);
}
return FALSE;
}
void CRenamerDlg::OnBnClickedSkip()
{
ASSERT(m_col.size() != 0);
m_col.erase(m_col.begin());
if (m_col.size() == 0)
OnOK();
else
PrepareNextTrack();
}
void CRenamerDlg::OnBnClickedAll()
{
CString pat;
GetDlgItemText(IDC_CMB_PATTERN, pat);
if (pat.GetLength() == 0)
return;
PrgAPI* pAPI = PRGAPI();
for (size_t i = 0; i < m_col.size(); i++)
{
FullTrackRecordSP& rec = m_col[i];
if (!RenameTrack(rec, pat))
{
TCHAR bf[1000];
_sntprintf(bf, 1000, _T("%s: %s: '%s'"),
pAPI->GetString(IDS_OPERATIONFAILED),
pAPI->GetString(IDS_RENAME),
rec->track.location.c_str());
pAPI->NotifyUser(bf, NULL, SEV_Warning);
}
}
OnOK();
}
void CRenamerDlg::OnBnClickedCancel()
{
OnCancel();
}
BOOL CRenamerDlg::OnInitDialog()
{
CDialog::OnInitDialog();
PrgAPI* pAPI = PRGAPI();
INT i = 0;
while (TRUE)//FileNameTagger::GetWritePredifinedFormat(i))
{
LPCTSTR curPat = FileNameTagger::GetWritePredifinedFormat(i);
if (curPat == NULL)
break;
i++;
m_cmbPattern.AddString(curPat);
}
m_header.SetIconHandle(pAPI->GetIcon(ICO_Main));
m_header.SetTitleText(pAPI->GetString(IDS_RENAMER));
m_header.SetTitleFont(pAPI->GetFont(FONT_DialogsBigBold));
m_header.SetDescFont(pAPI->GetFont(FONT_Dialogs));
m_header.SetIconSize(48, 48);
m_header.Init(this);
m_header.MoveCtrls(this);
m_cmbCasing.AddString(pAPI->GetString(IDS_AUTOMATIC));
m_cmbCasing.AddString(pAPI->GetString(IDS_PROPERCASE));
m_cmbCasing.AddString(pAPI->GetString(IDS_ALLCAPS));
m_cmbCasing.AddString(pAPI->GetString(IDS_NOCAPS));
m_cmbCasing.SetCurSel(0);
m_cmbPattern.SetCurSel(0);
m_lstTags.InsertColumn(0, _T(""), 0, 20);
m_lstTags.InsertColumn(1, _T(""), 0, 80);
m_lstTags.InsertColumn(2, _T(""), 0, 200);
PrepareNextTrack();
SetDlgItemText(IDC_ST_SYMBOLS, pAPI->GetString(IDS_SYMBOLS));
SetDlgItemText(IDC_ST_FILENAME, pAPI->GetString(IDS_FILE));
SetDlgItemText(IDC_ST_PATTERN, pAPI->GetString(IDS_PATTERN));
SetDlgItemText(IDC_ST_CASING, pAPI->GetString(IDS_CHANGECASE));
SetDlgItemText(IDC_ST_PREVIEW, pAPI->GetString(IDS_PREVIEW));
SetDlgItemText(IDC_RENAME, pAPI->GetString(IDS_RENAME));
SetDlgItemText(IDC_SKIP, pAPI->GetString(IDS_SKIP));
TCHAR bf[500];
_sntprintf(bf, 500, _T("%s (%s)"), pAPI->GetString(IDS_RENAME), pAPI->GetString(IDS_ALL));
SetDlgItemText(IDC_ALL, bf);
SetDlgItemText(IDC_CANCEL, pAPI->GetString(IDS_EXIT));
SetWindowText(pAPI->GetString(IDS_RENAMER));
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CRenamerDlg::InsertItem(INT rowID, LPCTSTR id, INT descID, LPCTSTR curVal)
{
INT item = m_lstTags.InsertItem(rowID, id);
INT ret = m_lstTags.SetItem(item, 1, LVIF_TEXT, PRGAPI()->GetString(descID), 0,0,0,0);
ret = m_lstTags.SetItem(item, 2, LVIF_TEXT, curVal, 0,0,0,0);
}
BOOL CRenamerDlg::PrepareNextTrack()
{
if (m_col.size() == 0)
return FALSE;
FullTrackRecordSP& rec = m_col[0];
SetDlgItemText(IDC_EDT_FILENAME, rec->track.location.c_str());
m_lstTags.DeleteAllItems();
TCHAR bf[300];
InsertItem(0, _T("$a"), IDS_ARTIST, rec->artist.name.c_str());
InsertItem(1, _T("$l"), IDS_ALBUM, rec->album.name.c_str());
_sntprintf(bf, 300, _T("%02d"), rec->track.trackNo);
InsertItem(2, _T("$n"), IDS_TRACKNO, bf);
InsertItem(3, _T("$t"), IDS_TITLE, rec->track.name.c_str());
_sntprintf(bf, 300, _T("%d"), rec->track.year);
InsertItem(4, _T("$y"), IDS_YEAR, bf);
UpdatePreview();
if (m_col.size() > 1)
_sntprintf(bf, 300, _T("%d %s"), m_col.size(), PRGAPI()->GetString(IDS_TRACKS));
else
bf[0] = 0;
SetDlgItemText(IDC_ST_TRACKS, bf);
GetDlgItem(IDC_SKIP)->EnableWindow(m_col.size() > 1);
GetDlgItem(IDC_ALL)->EnableWindow(m_col.size() > 1);
//if (m_col)
return TRUE;
}
void CRenamerDlg::UpdatePreviewDelayed()
{
SetTimer(TIMER_UPDATE, 50, NULL);
}
void CRenamerDlg::UpdatePreview()
{
TCHAR bf[MAX_PATH];
BOOL ret = GetNewFileName(bf, MAX_PATH);
if (ret)
SetDlgItemText(IDC_EDT_PREVIEW, ret ? bf : PRGAPI()->GetString(IDS_FAILURE));
GetDlgItem(IDC_RENAME)->EnableWindow(ret);
}
BOOL CRenamerDlg::GetNewFileName(LPTSTR bf, UINT bfLen)
{
if (m_col.size() == 0)
return FALSE;
FullTrackRecordSP& rec = m_col[0];
CString pat;
GetDlgItemText(IDC_CMB_PATTERN, pat);
TCHAR artist[100];
TCHAR album[100];
TCHAR title[100];
_tcsncpy(artist, rec->artist.name.c_str(), 100);
artist[99] = 0;
_tcsncpy(album, rec->album.name.c_str(), 100);
album[99] = 0;
_tcsncpy(title, rec->track.name.c_str(), 100);
title[99] = 0;
INT curSel = m_cmbCasing.GetCurSel();
switch (curSel)
{
case 1:
_tcsproper(artist);
_tcsproper(album);
_tcsproper(title);
break;
case 2:
_tcsupr(artist);
_tcsupr(album);
_tcsupr(title);
break;
case 3:
_tcslwr(artist);
_tcslwr(album);
_tcslwr(title);
break;
}
return FileNameTagger::TranslatePattern(bf, bfLen, pat,
artist,
album,
rec->track.trackNo,
title,
rec->track.year,
NULL
);
}
void CRenamerDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: Add your message handler code here and/or call default
if (nIDEvent == TIMER_UPDATE)
{
KillTimer(nIDEvent);
UpdatePreview();
}
CDialog::OnTimer(nIDEvent);
}
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
]
| [
[
[
1,
336
]
]
]
|
bf6632139684159cb9f5af07f205da3f7fe3469b | 12732dc8a5dd518f35c8af3f2a805806f5e91e28 | /trunk/LiteEditor/lexer_page.cpp | c8ba16aed2d80487a3a1a3d6b33a1d128b94847e | []
| no_license | BackupTheBerlios/codelite-svn | 5acd9ac51fdd0663742f69084fc91a213b24ae5c | c9efd7873960706a8ce23cde31a701520bad8861 | refs/heads/master | 2020-05-20T13:22:34.635394 | 2007-08-02T21:35:35 | 2007-08-02T21:35:35 | 40,669,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,555 | cpp | ///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version Feb 1 2007)
// http://www.wxformbuilder.org/
//
// PLEASE DO "NOT" EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif //__BORLANDC__
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif //WX_PRECOMP
#include "lexer_page.h"
#include "lexer_configuration.h"
#include "attribute_style.h"
#include <wx/font.h>
#include "editor_config.h"
///////////////////////////////////////////////////////////////////////////
BEGIN_EVENT_TABLE( LexerPage, wxPanel )
EVT_LISTBOX( wxID_ANY, LexerPage::OnItemSelected )
EVT_FONTPICKER_CHANGED(wxID_ANY, LexerPage::OnFontChanged)
EVT_COLOURPICKER_CHANGED(wxID_ANY, LexerPage::OnColourChanged)
END_EVENT_TABLE()
LexerPage::LexerPage( wxWindow* parent, LexerConfPtr lexer, int id, wxPoint pos, wxSize size, int style )
: wxPanel(parent, id, pos, size, style)
, m_lexer(lexer)
, m_selection(0)
{
wxBoxSizer* bSizer6;
bSizer6 = new wxBoxSizer( wxVERTICAL );
wxStaticBoxSizer* sbSizer5;
sbSizer5 = new wxStaticBoxSizer( new wxStaticBox( this, -1, wxT("Display Item:") ), wxHORIZONTAL );
m_properties = new wxListBox( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, NULL, 0 );
sbSizer5->Add( m_properties, 1, wxALL|wxEXPAND, 5 );
m_propertyList = m_lexer->GetProperties();
std::list<StyleProperty>::iterator it = m_propertyList.begin();
for(; it != m_propertyList.end(); it++){
m_properties->Append((*it).GetName());
}
m_properties->SetSelection(0);
wxBoxSizer* bSizer7;
bSizer7 = new wxBoxSizer( wxVERTICAL );
wxString initialColor = wxT("BLACK");
wxFont initialFont = wxNullFont;
if(m_propertyList.empty() == false){
StyleProperty p;
p = (*m_propertyList.begin());
initialColor = p.GetFgColour();
int size = p.GetFontSize();
wxString face = p.GetFaceName();
bool bold = p.IsBold();
initialFont = wxFont(size, wxFONTFAMILY_TELETYPE, wxNORMAL, bold ? wxBOLD : wxNORMAL, false, face);
}
m_fontPicker = new wxFontPickerCtrl(this, wxID_ANY, initialFont);
bSizer7->Add( m_fontPicker, 0, wxALL|wxEXPAND, 5 );
m_colourPicker = new wxColourPickerCtrl(this, wxID_ANY, wxColour(initialColor), wxDefaultPosition, wxDefaultSize, wxCLRP_SHOW_LABEL);
bSizer7->Add( m_colourPicker, 0, wxALL|wxEXPAND, 5 );
sbSizer5->Add( bSizer7, 1, wxEXPAND, 5 );
wxStaticBoxSizer *hs = new wxStaticBoxSizer(wxHORIZONTAL, this, wxT("File Types:"));
m_fileSpec = new wxTextCtrl(this, wxID_ANY, m_lexer->GetFileSpec());
hs->Add(m_fileSpec, 1, wxALL | wxEXPAND, 5);
bSizer6->Add( sbSizer5, 1, wxEXPAND, 5 );
bSizer6->Add( hs, 0, wxEXPAND, 5 );
this->SetSizer( bSizer6 );
this->Layout();
if(m_propertyList.empty()){
m_fontPicker->Enable(false);
m_colourPicker->Enable(false);
}
}
void LexerPage::OnItemSelected(wxCommandEvent & event)
{
// update colour picker & font pickers
wxString selectionString = event.GetString();
m_selection = event.GetSelection();
std::list<StyleProperty>::iterator iter = m_propertyList.begin();
for(; iter != m_propertyList.end(); iter++){
if(iter->GetName() == selectionString){
// update font & color
StyleProperty p = (*iter);
wxString colour = p.GetFgColour();
wxFont font = wxNullFont;
int size = p.GetFontSize();
wxString face = p.GetFaceName();
bool bold = p.IsBold();
font = wxFont(size, wxFONTFAMILY_TELETYPE, wxNORMAL, bold ? wxBOLD : wxNORMAL, false, face);
m_fontPicker->SetSelectedFont(font);
m_colourPicker->SetColour(colour);
}
}
}
void LexerPage::OnFontChanged(wxFontPickerEvent &event)
{
// update font
wxFont font = event.GetFont();
std::list<StyleProperty>::iterator iter = m_propertyList.begin();
for(int i=0; i<m_selection; i++)
iter++;
iter->SetBold(font.GetWeight() == wxFONTWEIGHT_BOLD);
iter->SetFaceName(font.GetFaceName());
iter->SetFontSize(font.GetPointSize());
}
void LexerPage::OnColourChanged(wxColourPickerEvent &event)
{
// update font
wxColour colour = event.GetColour();
std::list<StyleProperty>::iterator iter = m_propertyList.begin();
for(int i=0; i<m_selection; i++)
iter++;
iter->SetFgColour(colour.GetAsString(wxC2S_HTML_SYNTAX));
}
void LexerPage::SaveSettings()
{
m_lexer->SetProperties( m_propertyList );
m_lexer->SetFileSpec( m_fileSpec->GetValue() );
m_lexer->Save();
}
| [
"eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b"
]
| [
[
[
1,
147
]
]
]
|
5c5a169f4b1a0a19a57ed7dce4eba0f5880ea400 | 822ab63b75d4d4e2925f97b9360a1b718b5321bc | /WeatherEngine/WeatherbugInfo.cpp | 24df452358d813a4d866cd88ee12d5b9c97e7060 | []
| no_license | sriks/decii | 71e4becff5c30e77da8f87a56383e02d48b78b28 | 02c58fbaea69c2448249710d13f2e774762da2c3 | refs/heads/master | 2020-05-17T23:03:27.822905 | 2011-12-16T07:29:38 | 2011-12-16T07:29:38 | 32,251,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,171 | cpp | #include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QDebug>
#include <QNetworkRequest>
#include <QFile>
#include <QBuffer>
#include <QVariantMap>
#include "LocationSuggestions.h"
#include "WeatherbugInfo.h"
#include "NetworkEngine.h"
#include "XQueryEngine.h"
#include "Constants.h"
QString WeatherRequestAPI("http://api.wxbug.net/getLiveWeatherRSS.aspx?ACode=A5580663883&unittype=1&outputtype=1&");
QString USALocation("0");
QString NonUSALocation("1");
QString Zipcode("zipcode");
QString Citycode("citycode");
QString Citytype("citytype");
struct WeatherBugInfoPrivate {
NetworkEngine* net;
XQueryEngine* xquery;
SuggestionInfo* info;
WeatherBugInfoPrivate() {
net = new NetworkEngine;
xquery = new XQueryEngine;
info = NULL;
}
~WeatherBugInfoPrivate() {
net->deleteLater();
xquery->deleteLater();
}
};
WeatherBugInfo::WeatherBugInfo(QObject *parent) :
WeatherInfo(parent) {
d = new WeatherBugInfoPrivate;
connect(d->net,SIGNAL(dataAvailable(QByteArray)),this,SLOT(onDataAvailable(QByteArray)));
connect(d->net,SIGNAL(error(QNetworkReply::NetworkError,QString)),
this,SLOT(onNetworkError(QNetworkReply::NetworkError,QString)));
}
WeatherBugInfo::~WeatherBugInfo() {
delete d;
}
void WeatherBugInfo::update() {
if(!d->info)
return;
SuggestionInfo* si = qobject_cast<SuggestionInfo*>(d->info);
if(si) {
si->setParent(this);
QVariantMap extraInfo = si->info().toMap();
QString additionalParams;
if(USALocation == extraInfo.value(Citytype).toString())
additionalParams = Zipcode+"="+extraInfo.value(Zipcode).toString();
else
additionalParams = Citycode+"="+extraInfo.value(Citycode).toString();
QUrl url(WeatherRequestAPI+additionalParams);
qDebug()<<Q_FUNC_INFO<<url;
QNetworkRequest request(url);
d->net->get(request);
} else {
qWarning()<<Q_FUNC_INFO<<"invalid info";
}
}
void WeatherBugInfo::onDataAvailable(QByteArray data) {
QBuffer b(&data);
QFile f(":/resources/weatherbug/converttonormalizedxml.xq");
if(f.open(QIODevice::ReadOnly) && b.open(QIODevice::ReadOnly)) {
QString q = f.readAll();
QVariant result = d->xquery->executeQuery(q,&b);
if(result.isValid() && d->xquery->isSuccess()) {
handleNormalizedWeatherXml(result.toString());
// Some times WB sends invaid city names, hence using what user has selected.
setWeatherData(PROP_CITY,d->info->title());
setWeatherData(PROP_COUNTRY,d->info->subTitle());
setWeatherData(PROP_TEMPERATUREUNITS,"C"); // default is C
// convert percentage of moonphase to number.
int moonPhase = weatherData().value(PROP_MOONPHASE).toString().toInt();
if(moonPhase > 30) {
int moonPhaseNum = (moonPhase*30)/100;
setWeatherData(PROP_MOONPHASE,QVariant(QString().setNum(moonPhaseNum)));
}
qDebug()<<Q_FUNC_INFO<<weatherData();
emit updated(this);
} else {
emit error(QString("Unable to get weather data."));
}
}
f.close();
}
void WeatherBugInfo::onNetworkError(QNetworkReply::NetworkError errorType, QString errorString) {
Q_UNUSED(errorType)
Q_UNUSED(errorString);
emit error("Network conection error");
}
void WeatherBugInfo::setInfo(QObject* info) {
if(info) {
info->setParent(this);
d->info = qobject_cast<SuggestionInfo*>(info);
}
}
QObject * WeatherBugInfo::info() const {
return d->info;
}
// WeatherBugLocationSuggestions
QString KSuggFilterRegex("(\\b%1)\\w+\\b");
struct WeatherBugLocationSuggestionsPrivate {
QMap<QString,QObject*> names;
QStringList suggestions;
QString query;
XQueryEngine* xquery;
WeatherBugLocationSuggestionsPrivate() {
xquery = new XQueryEngine;
}
~WeatherBugLocationSuggestionsPrivate() {
xquery->deleteLater();
}
};
WeatherBugLocationSuggestions::WeatherBugLocationSuggestions(QObject *parent) {
d = new WeatherBugLocationSuggestionsPrivate;
QFile xqf(":/resources/weatherbug/locationnames/names.xq");
if(xqf.open(QIODevice::ReadOnly))
d->query = xqf.readAll();
xqf.close();
}
WeatherBugLocationSuggestions::~WeatherBugLocationSuggestions() {
delete d;
}
/*!
Handles input from user and returns location suggestions.
**/
void WeatherBugLocationSuggestions::handleInput(QString userTyping) {
QString key = userTyping.trimmed().toLower();
if(1 == key.size()) {
QString firstChar = key.at(0);
QFile data(":/resources/weatherbug/locationnames/"+firstChar+".txt");
if(data.open(QIODevice::ReadOnly)) {
clearSuggestions();
QStringList* sl = new QStringList(QString(data.readAll()).split("\n"));
QStringListIterator iter(*sl);
while(iter.hasNext()) {
QStringList info = iter.next().split("|");
if(info.size() != 6)
continue;
SuggestionInfo* sugginfo = new SuggestionInfo;
sugginfo->setParent(this);
sugginfo->_title = info.at(0);
sugginfo->_subTitle = info.at(1) + " " + info.at(2); // statename country name
sugginfo->_subTitle = sugginfo->_subTitle.trimmed();
QVariantMap extra;
extra.insert(Zipcode,info.at(3));
extra.insert(Citycode,info.at(4));
extra.insert(Citytype,info.at(5));
sugginfo->_info = QVariant(extra);
d->names.insert(sugginfo->_title+sugginfo->_subTitle,sugginfo);
}
delete sl;
}
data.close();
} else if(0 == key.size()) {
d->suggestions.clear();
}
QString regex = KSuggFilterRegex.arg(key);
d->suggestions = QStringList(d->names.keys()).filter(QRegExp(regex,Qt::CaseInsensitive));
emit countChanged();
}
int WeatherBugLocationSuggestions::count() const {
return d->suggestions.size();
}
QObject * WeatherBugLocationSuggestions::suggestionInfo(int index) {
if(index >=0 && index < d->suggestions.size())
return d->names.value(d->suggestions.at(index));
else {
qWarning()<<Q_FUNC_INFO<<"accessing invalid index "<<index<<" sugg count is:"<<count();
return NULL;
}
}
void WeatherBugLocationSuggestions::done() {
clearSuggestions();
}
void WeatherBugLocationSuggestions::clearSuggestions() {
if(!d->names.isEmpty()) {
QMapIterator<QString,QObject*> iter(d->names);
while(iter.hasNext()) {
QObject* sugg = iter.next().value();
if(sugg->parent() == this)
sugg->deleteLater();
}
d->names.clear();
}
}
// eof
| [
"[email protected]@016151e7-202e-141d-2e90-f2560e693586"
]
| [
[
[
1,
213
]
]
]
|
a7cf9a219b8159bdea54f862f231407e6f7e237c | cfcd2a448c91b249ea61d0d0d747129900e9e97f | /thirdparty/OpenCOLLADA/COLLADAFramework/src/COLLADAFWConstants.cpp | de23ee1ba6cc90a8a3610382cee0b09361fbd62f | []
| no_license | fire-archive/OgreCollada | b1686b1b84b512ffee65baddb290503fb1ebac9c | 49114208f176eb695b525dca4f79fc0cfd40e9de | refs/heads/master | 2020-04-10T10:04:15.187350 | 2009-05-31T15:33:15 | 2009-05-31T15:33:15 | 268,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,766 | cpp | /*
Copyright (c) 2008 NetAllied Systems GmbH
This file is part of COLLADAFramework.
Licensed under the MIT Open Source License,
for details please see LICENSE file or the website
http://www.opensource.org/licenses/mit-license.php
*/
#include "COLLADAFWStableHeaders.h"
#include "COLLADAFWConstants.h"
namespace COLLADAFW
{
const String Constants::EMPTY_STRING = "";
const String Constants::ERR_UNKNOWN_INPUT = "UNKNOWN INPUT ERROR";
const String Constants::SEMANTIC_BINORMAL = "BINORMAL";
const String Constants::SEMANTIC_COLOR = "COLOR";
const String Constants::SEMANTIC_CONTINUITY = "CONTINUITY";
const String Constants::SEMANTIC_IMAGE = "IMAGE";
const String Constants::SEMANTIC_INPUT = "INPUT";
const String Constants::SEMANTIC_IN_TANGENT = "IN_TANGENT";
const String Constants::SEMANTIC_INTERPOLATION = "INTERPOLATION";
const String Constants::SEMANTIC_INV_BIND_MATRIX = "INV_BIND_MATRIX";
const String Constants::SEMANTIC_JOINT = "JOINT";
const String Constants::SEMANTIC_LINEAR_STEPS = "LINEAR_STEPS";
const String Constants::SEMANTIC_MORPH_TARGET = "MORPH_TARGET";
const String Constants::SEMANTIC_MORPH_WEIGHT = "MORPH_WEIGHT";
const String Constants::SEMANTIC_NORMAL = "NORMAL";
const String Constants::SEMANTIC_OUTPUT = "OUTPUT";
const String Constants::SEMANTIC_OUT_TANGENT = "OUT_TANGENT";
const String Constants::SEMANTIC_POSITION = "POSITION";
const String Constants::SEMANTIC_TANGENT = "TANGENT";
const String Constants::SEMANTIC_TEXBINORMAL = "TEXBINORMAL";
const String Constants::SEMANTIC_TEXCOORD = "TEXCOORD";
const String Constants::SEMANTIC_TEXTANGENT = "TEXTANGENT";
const String Constants::SEMANTIC_UV = "UV";
const String Constants::SEMANTIC_VERTEX = "VERTEX";
const String Constants::SEMANTIC_WEIGHT = "WEIGHT";
const String Constants::VALUE_TYPE_BOOL = "bool";
const String Constants::VALUE_TYPE_BOOL2 = "bool2";
const String Constants::VALUE_TYPE_BOOL3 = "bool3";
const String Constants::VALUE_TYPE_BOOL4 = "bool4";
const String Constants::VALUE_TYPE_INT = "int";
const String Constants::VALUE_TYPE_INT2 = "int2";
const String Constants::VALUE_TYPE_INT3 = "int3";
const String Constants::VALUE_TYPE_INT4 = "int4";
const String Constants::VALUE_TYPE_FLOAT = "float";
const String Constants::VALUE_TYPE_FLOAT2 = "float2";
const String Constants::VALUE_TYPE_FLOAT3 = "float3";
const String Constants::VALUE_TYPE_FLOAT4 = "float4";
const String Constants::VALUE_TYPE_FLOAT2x2 = "float2x2";
const String Constants::VALUE_TYPE_FLOAT3x3 = "float3x3";
const String Constants::VALUE_TYPE_FLOAT4x4 = "float4x4";
const String Constants::VALUE_TYPE_STRING = "string";
const String Constants::VALUE_TYPE_SURFACE = "surface";
const String Constants::VALUE_TYPE_SAMPLER_1D = "sampler1D";
const String Constants::VALUE_TYPE_SAMPLER_2D = "sampler2D";
const String Constants::VALUE_TYPE_SAMPLER_3D = "sampler3D";
const String Constants::VALUE_TYPE_SAMPLER_CUBE = "samplerCUBE";
const String Constants::VALUE_TYPE_SAMPLER_RECT = "samplerRECT";
const String Constants::VALUE_TYPE_SAMPLER_DEPTH = "samplerDEPTH";
const String Constants::VALUE_TYPE_SAMPLER_STATE = "sampler_state";
const String Constants::VALUE_TYPE_NAME = "name";
const String Constants::VALUE_TYPE_IDREF = "IDREF";
const String Constants::FX_FUNCTION_NEVER = "NEVER";
const String Constants::FX_FUNCTION_LESS = "LESS";
const String Constants::FX_FUNCTION_EQUAL = "EQUAL";
const String Constants::FX_FUNCTION_LEQUAL = "LEQUAL";
const String Constants::FX_FUNCTION_GREATER = "GREATER";
const String Constants::FX_FUNCTION_NEQUAL = "NOTEQUAL";
const String Constants::FX_FUNCTION_GEQUAL = "GEQUAL";
const String Constants::FX_FUNCTION_ALWAYS = "ALWAYS";
const String Constants::FX_ANNOTATION_RESOURCE_NAME = "ResourceName";
const String Constants::FX_ANNOTATION_RESOURCE_TYPE = "ResourceType";
const String Constants::FX_SHADER_STAGE_VERTEX = "VERTEX";
const String Constants::FX_SHADER_STAGE_VERTEXPROGRAM = "VERTEXPROGRAM";
const String Constants::FX_SHADER_STAGE_FRAGMENT = "FRAGMENT";
const String Constants::FX_SHADER_STAGE_FRAGMENTPROGRAM = "FRAGMENTPROGRAM";
const String Constants::FX_STATE_ALPHA_FUNC = "alpha_func";
const String Constants::FX_STATE_BLEND_FUNC = "blend_func";
const String Constants::FX_STATE_BLEND_FUNC_SEPARATE = "blend_func_separate";
const String Constants::FX_STATE_BLEND_EQUATION = "blend_equation";
const String Constants::FX_STATE_BLEND_EQUATION_SEPARATE = "blend_equation_separate";
const String Constants::FX_STATE_COLOR_MATERIAL = "color_material";
const String Constants::FX_STATE_CULL_FACE = "cull_face";
const String Constants::FX_STATE_DEPTH_FUNC = "depth_func";
const String Constants::FX_STATE_FOG_MODE = "fog_mode";
const String Constants::FX_STATE_FOG_COORD_SRC = "fog_coord_src";
const String Constants::FX_STATE_FRONT_FACE = "front_face";
const String Constants::FX_STATE_LIGHT_MODEL_COLOR_CONTROL = "light_model_color_control";
const String Constants::FX_STATE_LOGIC_OP = "logic_op";
const String Constants::FX_STATE_POLYGON_MODE = "polygon_mode";
const String Constants::FX_STATE_SHADE_MODEL = "shade_model";
const String Constants::FX_STATE_STENCIL_FUNC = "stencil_func";
const String Constants::FX_STATE_STENCIL_OP = "stencil_op";
const String Constants::FX_STATE_STENCIL_FUNC_SEPARATE = "stencil_func_separate";
const String Constants::FX_STATE_STENCIL_OP_SEPARATE = "stencil_op_separate";
const String Constants::FX_STATE_STENCIL_MASK_SEPARATE = "stencil_mask_separate";
const String Constants::FX_STATE_LIGHT_ENABLE = "light_enable";
const String Constants::FX_STATE_LIGHT_AMBIENT = "light_ambient";
const String Constants::FX_STATE_LIGHT_DIFFUSE = "light_diffuse";
const String Constants::FX_STATE_LIGHT_SPECULAR = "light_specular";
const String Constants::FX_STATE_LIGHT_POSITION = "light_position";
const String Constants::FX_STATE_LIGHT_CONSTANT_ATTENUATION = "light_constant_attenuation";
const String Constants::FX_STATE_LIGHT_LINEAR_ATTENUATION = "light_linear_attenuation";
const String Constants::FX_STATE_LIGHT_QUADRATIC_ATTENUATION = "light_quadratic_attenuation";
const String Constants::FX_STATE_LIGHT_SPOT_CUTOFF = "light_spot_cutoff";
const String Constants::FX_STATE_LIGHT_SPOT_DIRECTION = "light_spot_direction";
const String Constants::FX_STATE_LIGHT_SPOT_EXPONENT = "light_spot_exponent";
const String Constants::FX_STATE_TEXTURE1D = "texture1D";
const String Constants::FX_STATE_TEXTURE2D = "texture2D";
const String Constants::FX_STATE_TEXTURE3D = "texture3D";
const String Constants::FX_STATE_TEXTURECUBE = "textureCUBE";
const String Constants::FX_STATE_TEXTURERECT = "textureRECT";
const String Constants::FX_STATE_TEXTUREDEPTH = "textureDEPTH";
const String Constants::FX_STATE_TEXTURE1D_ENABLE = "texture1D_enable";
const String Constants::FX_STATE_TEXTURE2D_ENABLE = "texture2D_enable";
const String Constants::FX_STATE_TEXTURE3D_ENABLE = "texture3D_enable";
const String Constants::FX_STATE_TEXTURECUBE_ENABLE = "textureCUBE_enable";
const String Constants::FX_STATE_TEXTURERECT_ENABLE = "textureRECT_enable";
const String Constants::FX_STATE_TEXTUREDEPTH_ENABLE = "textureDEPTH_enable";
const String Constants::FX_STATE_TEXTURE_ENV_COLOR = "texture_env_color";
const String Constants::FX_STATE_TEXTURE_ENV_MODE = "texture_env_mode";
const String Constants::FX_STATE_CLIP_PLANE = "clip_plane";
const String Constants::FX_STATE_CLIP_PLANE_ENABLE = "clip_plane_enable";
const String Constants::FX_STATE_BLEND_COLOR = "blend_color";
const String Constants::FX_STATE_CLEAR_COLOR = "clear_color";
const String Constants::FX_STATE_CLEAR_STENCIL = "clear_stencil";
const String Constants::FX_STATE_CLEAR_DEPTH = "clear_depth";
const String Constants::FX_STATE_COLOR_MASK = "color_mask";
const String Constants::FX_STATE_DEPTH_BOUNDS = "depth_bounds";
const String Constants::FX_STATE_DEPTH_MASK = "depth_mask";
const String Constants::FX_STATE_DEPTH_RANGE = "depth_range";
const String Constants::FX_STATE_FOG_DENSITY = "fog_density";
const String Constants::FX_STATE_FOG_START = "fog_start";
const String Constants::FX_STATE_FOG_END = "fog_end";
const String Constants::FX_STATE_FOG_COLOR = "fog_color";
const String Constants::FX_STATE_LIGHT_MODEL_AMBIENT = "light_model_ambient";
const String Constants::FX_STATE_LIGHTING_ENABLE = "lighting_enable";
const String Constants::FX_STATE_LINE_STIPPLE = "line_stipple";
const String Constants::FX_STATE_LINE_STIPPLE_ENABLE = "line_stipple_enable";
const String Constants::FX_STATE_LINE_WIDTH = "line_width";
const String Constants::FX_STATE_MATERIAL_AMBIENT = "material_ambient";
const String Constants::FX_STATE_MATERIAL_DIFFUSE = "material_diffuse";
const String Constants::FX_STATE_MATERIAL_EMISSION = "material_emission";
const String Constants::FX_STATE_MATERIAL_SHININESS = "material_shininess";
const String Constants::FX_STATE_MATERIAL_SPECULAR = "material_specular";
const String Constants::FX_STATE_MODEL_VIEW_MATRIX = "model_view_matrix";
const String Constants::FX_STATE_POINT_DISTANCE_ATTENUATION = "point_distance_attenuation";
const String Constants::FX_STATE_POINT_FADE_THRESHOLD_SIZE = "point_fade_threshold_size";
const String Constants::FX_STATE_POINT_SIZE = "point_size";
const String Constants::FX_STATE_POINT_SIZE_MIN = "point_size_min";
const String Constants::FX_STATE_POINT_SIZE_MAX = "point_size_max";
const String Constants::FX_STATE_POLYGON_OFFSET = "polygon_offset";
const String Constants::FX_STATE_PROJECTION_MATRIX = "projection_matrix";
const String Constants::FX_STATE_SCISSOR = "scissor";
const String Constants::FX_STATE_STENCIL_MASK = "stencil_mask";
const String Constants::FX_STATE_ALPHA_TEST_ENABLE = "alpha_test_enable";
const String Constants::FX_STATE_AUTO_NORMAL_ENABLE = "auto_normal_enable";
const String Constants::FX_STATE_BLEND_ENABLE = "blend_enable";
const String Constants::FX_STATE_COLOR_LOGIC_OP_ENABLE = "color_logic_op_enable";
const String Constants::FX_STATE_COLOR_MATERIAL_ENABLE = "color_material_enable";
const String Constants::FX_STATE_CULL_FACE_ENABLE = "cull_face_enable";
const String Constants::FX_STATE_DEPTH_BOUNDS_ENABLE = "depth_bounds_enable";
const String Constants::FX_STATE_DEPTH_CLAMP_ENABLE = "depth_clamp_enable";
const String Constants::FX_STATE_DEPTH_TEST_ENABLE = "depth_test_enable";
const String Constants::FX_STATE_DITHER_ENABLE = "dither_enable";
const String Constants::FX_STATE_FOG_ENABLE = "fog_enable";
const String Constants::FX_STATE_LIGHT_MODEL_LOCAL_VIEWER_ENABLE = "light_model_local_viewer_enable";
const String Constants::FX_STATE_LIGHT_MODEL_TWO_SIDE_ENABLE = "light_model_two_side_enable";
const String Constants::FX_STATE_LINE_SMOOTH_ENABLE = "line_smooth_enable";
const String Constants::FX_STATE_LOGIC_OP_ENABLE = "logic_op_enable";
const String Constants::FX_STATE_MULTISAMPLE_ENABLE = "multisample_enable";
const String Constants::FX_STATE_NORMALIZE_ENABLE = "normalize_enable";
const String Constants::FX_STATE_POINT_SMOOTH_ENABLE = "point_smooth_enable";
const String Constants::FX_STATE_POLYGON_OFFSET_FILL_ENABLE = "polygon_offset_fill_enable";
const String Constants::FX_STATE_POLYGON_OFFSET_LINE_ENABLE = "polygon_offset_line_enable";
const String Constants::FX_STATE_POLYGON_OFFSET_POINT_ENABLE = "polygon_offset_point_enable";
const String Constants::FX_STATE_POLYGON_SMOOTH_ENABLE = "polygon_smooth_enable";
const String Constants::FX_STATE_POLYGON_STIPPLE_ENABLE = "polygon_stipple_enable";
const String Constants::FX_STATE_RESCALE_NORMAL_ENABLE = "rescale_normal_enable";
const String Constants::FX_STATE_SAMPLE_ALPHA_TO_COVERAGE_ENABLE = "sample_alpha_to_coverage_enable";
const String Constants::FX_STATE_SAMPLE_ALPHA_TO_ONE_ENABLE = "sample_alpha_to_one_enable";
const String Constants::FX_STATE_SAMPLE_COVERAGE_ENABLE = "sample_coverage_enable";
const String Constants::FX_STATE_SCISSOR_TEST_ENABLE = "scissor_test_enable";
const String Constants::FX_STATE_STENCIL_TEST_ENABLE = "stencil_test_enable";
} // namespace COLLADAFW
| [
"[email protected]"
]
| [
[
[
1,
197
]
]
]
|
d3a8294206df80fdfc3dfe7c72ba3c526d8d4a3e | 5eb582292aeef7c56b13bc05accf71592d15931f | /include/raknet/NetworkIDGenerator.h | 37091d9e28c7f9a444cf32a1c84f66d591acf873 | []
| no_license | goebish/WiiBlob | 9316a56f2a60a506ecbd856ab7c521f906b961a1 | bef78fc2fdbe2d52749ed3bc965632dd699c2fea | refs/heads/master | 2020-05-26T12:19:40.164479 | 2010-09-05T18:09:07 | 2010-09-05T18:09:07 | 188,229,195 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,682 | h | /* -*- mode: c++; c-file-style: raknet; tab-always-indent: nil; -*- */
/**
* @file
* @brief Creates unique network IDs. Must be derived from to implement integration into network system.
* NetworkObject is an add-on system that uses RakNet and interfaces with another add-on system: DistributedNetworkObject
* NetworkIDGenerator is a core system in RakNet and does not interface with any external systems
*
* This file is part of RakNet Copyright 2003 Rakkarsoft LLC and Kevin Jenkins.
*
* Usage of Raknet is subject to the appropriate licence agreement.
* "Shareware" Licensees with Rakkarsoft LLC are subject to the
* shareware license found at
* http://www.rakkarsoft.com/shareWareLicense.html which you agreed to
* upon purchase of a "Shareware license" "Commercial" Licensees with
* Rakkarsoft LLC are subject to the commercial license found at
* http://www.rakkarsoft.com/sourceCodeLicense.html which you agreed
* to upon purchase of a "Commercial license"
* Custom license users are subject to the terms therein.
* All other users are
* subject to the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* Refer to the appropriate license agreement for distribution,
* modification, and warranty rights.
*/
#if !defined(__NETWORK_ID_GENERATOR)
#define __NETWORK_ID_GENERATOR
#include "BinarySearchTree.h"
#include "NetworkTypes.h"
class NetworkIDGenerator;
/**
* @brief Define a node of an Object Tree.
* Used internally to contain objects in the tree. Ignore this
*/
struct ObjectIDNode
{
/**
* id
*/
ObjectID objectID;
/**
* a pointer to the object associated to id
*/
NetworkIDGenerator *object;
/**
* Default Constructor
*/
ObjectIDNode();
/**
* Create a node based on the objectID and a pointer to the NetworkIDGenerator
* @param ObjectID id of the node
* @param Object the network object
*/
ObjectIDNode( ObjectID _objectID, NetworkIDGenerator *_object );
/**
* Test if two nodes are equals
* @param left a node
* @param right a node
* @return true if the nodes are the same
*/
friend int operator==( const ObjectIDNode& left, const ObjectIDNode& right );
/**
* Test if one node is greater than the other
* @param left a node
* @param right a node
* @return True if @em left is greater than @em right
*/
friend int operator > ( const ObjectIDNode& left, const ObjectIDNode& right );
/**
* Test if one node is lesser than the other
* @param left a node
* @param right a node
* @return True if @em left is lesser than @em right
*/
friend int operator < ( const ObjectIDNode& left, const ObjectIDNode& right );
};
/**
* A NetworkIDGenerator is used to identify uniquely an object on the
* network You can easly create object with network unique id by
* subclassing this class.
*/
class NetworkIDGenerator
{
public:
/**
* Default Constructor
*/
NetworkIDGenerator();
/**
* Default Destructor
*/
virtual ~NetworkIDGenerator();
/**
* Get the id of the object
* @return the id of the current object
*/
virtual ObjectID GetNetworkID( void );
/**
* Associate an id to an object
* @param id the new id of the network object.
* @note Only the server code should
* call this.
*
*/
virtual void SetNetworkID( ObjectID id );
/**
* If you want this to be a member object of another class
* Then call SetParent. It will return the parent rather than itself.
* Useful if you can't derive, such as with multiple inheritance
*
*/
virtual void SetParent( void *_parent );
/**
* Return what was passed to SetParent
*
*/
virtual void* GetParent( void ) const;
/**
* Store all object in an AVL Tree using id as key
*/
static BasicDataStructures::AVLBalancedBinarySearchTree<ObjectIDNode> IDTree;
/**
* These function is only meant to be used when saving games as you
* should save the HIGHEST value staticItemID has achieved upon save
* and reload it upon load. Save AFTER you've created all the items
* derived from this class you are going to create.
* @return the HIGHEST Object Id currently used
*/
static ObjectID GetStaticNetworkID( void );
/**
* These function is only meant to be used when loading games. Load
* BEFORE you create any new objects that are not SetIDed based on
* the save data.
* @param i the highest number of NetworkIDGenerator reached.
*/
static void SetStaticNetworkID( ObjectID i );
/**
* OVERLOAD or REWRITE these to reflect the status of the server and client in your own game - or even peers if you transfer who assigns new IDs
IsObjectIDAuthority should return true if this is a system that either is or will create IDs to other systems
IsObjectIDAuthorityActive should return true if this is a system will create IDs to other systems and is currently doing so
IsObjectIDRecipient should return true if this is a system that either is or will accept IDs from other systems
IsObjectIDRecipientActive should return true if this is a system that is currently accepting IDs from other systems
*/
virtual bool IsObjectIDAuthority(void) const=0; // Usually means is this a server?
virtual bool IsObjectIDAuthorityActive(void) const=0; // Usually means is this a server and that the server is running?
virtual bool IsObjectIDRecipient(void) const=0; // Usually means is this a client?
virtual bool IsObjectIDRecipientActive(void) const=0; // Usually means is this a client and that client is connected?
// Return true if you require that SetParent is called before this object is used. You should do this if you want this to be
// a member object of another class rather than derive from this class.
virtual bool RequiresSetParent(void) const;
protected:
/**
* The network ID of this object
*/
ObjectID objectID;
/**
* Store whether or not its a server assigned ID
*/
bool serverAssignedID;
void *parent;
void GenerateID(void);
bool callGenerationCode; // This is crap but is necessary because virtual functions don't work in the constructor
private:
/**
* Number of network object.
*/
static ObjectID staticItemID;
};
/**
* Retrieve a NetworkIDGenerator from its ID
* @param x the object id
* @return a pointer to a NetworkIDGenerator or 0 if there is no corresponding Id.
*/
void* GET_OBJECT_FROM_ID( ObjectID x );
#endif // !defined(AFX_NetworkIDGenerator_H__29266376_3F9E_42CD_B208_B58957E1935B__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
189
]
]
]
|
20aa966a9e5560bef94c66f5aff21b9700f37b5b | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Common/Base/Reflection/hkClassEnum.inl | 178d8d001fc0f322302b9e5654d9f580e8d9b009 | []
| no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,842 | inl | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
inline hkClassEnum::hkClassEnum( const char* name, const hkClassEnum::Item* items, int numItems )
: m_name(name),
m_items(items),
m_numItems(numItems),
m_attributes(HK_NULL),
m_flags(0)
{
}
inline const char* hkClassEnum::getName() const
{
return m_name;
}
inline int hkClassEnum::getNumItems() const
{
return m_numItems;
}
inline const hkClassEnum::Item& hkClassEnum::getItem(int i) const
{
HK_ASSERT(0x75c7fff1, i >= 0 && i < m_numItems );
return m_items[i];
}
inline const hkClassEnum::Flags& hkClassEnum::getFlags() const
{
return m_flags;
}
inline hkClassEnum::Flags& hkClassEnum::getFlags()
{
return m_flags;
}
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
57
]
]
]
|
d033ded0f714f0d8ce6d767bdbd10ba5ebdde909 | 05f4bd87bd001ab38701ff8a71d91b198ef1cb72 | /TPTaller/TP3/src/Tag.h | f9e3142f3bba1be3edd49e4ae7403fc70ee5d167 | []
| no_license | oscarcp777/tpfontela | ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12 | 2489442b81dab052cf87b6dedd33cbb51c2a0a04 | refs/heads/master | 2016-09-01T18:40:21.893393 | 2011-12-03T04:26:33 | 2011-12-03T04:26:33 | 35,110,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | h | #ifndef __TAG_H___
#define __TAG_H___
#include <iostream>
#include <iostream.h>
#include <string>
#include <list>
using namespace std;
class Tag{
private:
std::string nombreTag;
std::list<std::string> listaAtributos;
public:
Tag(std::string nombreTag);
~Tag();
void Tag::addAtributo(std::string atributo);
int Tag::chequearAtributo(std::string nombreAtributo);
std::string Tag::getNombreTag();
};
#endif
| [
"rdubini@a1477896-89e5-11dd-84d8-5ff37064ad4b"
]
| [
[
[
1,
32
]
]
]
|
c259e0338d49ad5a2b4ed6f10a4980e902e0c704 | 989aa92c9dab9a90373c8f28aa996c7714a758eb | /HydraIRC/Prefs_MiscPage.cpp | 72746003afa8cf9cc06dc0324c8f793d7c6b1bd1 | []
| no_license | john-peterson/hydrairc | 5139ce002e2537d4bd8fbdcebfec6853168f23bc | f04b7f4abf0de0d2536aef93bd32bea5c4764445 | refs/heads/master | 2021-01-16T20:14:03.793977 | 2010-04-03T02:10:39 | 2010-04-03T02:10:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,563 | cpp | /*
HydraIRC
Copyright (C) 2002-2006 Dominic Clifton aka Hydra
HydraIRC limited-use source license
1) You can:
1.1) Use the source to create improvements and bug-fixes to send to the
author to be incorporated in the main program.
1.2) Use it for review/educational purposes.
2) You can NOT:
2.1) Use the source to create derivative works. (That is, you can't release
your own version of HydraIRC with your changes in it)
2.2) Compile your own version and sell it.
2.3) Distribute unmodified, modified source or compiled versions of HydraIRC
without first obtaining permission from the author. (I want one place
for people to come to get HydraIRC from)
2.4) Use any of the code or other part of HydraIRC in anything other than
HydraIRC.
3) All code submitted to the project:
3.1) Must not be covered by any license that conflicts with this license
(e.g. GPL code)
3.2) Will become the property of the author.
*/
// Prefs_IdentitiesPage.h : interface of the CMiscPage class
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "HydraIRC.h"
#define PII_BOOL 1
#define PII_INTEGER 2
#define PII_STRING 3
#define PII_PATH 4
#define PII_FONT 5
#define PII_COLOR 6
void CMiscPage::OnPageDisplay( void )
{
HPROPERTY hItem;
m_PropertyList.AddItem( PropCreateCategory("Strings") );
for (int i = 0; i < PREF_STRING_MAX; i++)
{
hItem = m_PropertyList.AddItem( PropCreateSimple(PREF_STRING_NAME(i) , g_pNewPrefs->m_StringPrefs[i] ));
if (hItem)
m_PropertyList.SetItemData(hItem, MAKELPARAM(i,PII_STRING) );
}
m_PropertyList.AddItem( PropCreateCategory("Paths") );
for (int i = 0; i < PREF_PATH_MAX; i++)
{
hItem = m_PropertyList.AddItem( PropCreateFileName(PREF_PATH_NAME(i) , g_pNewPrefs->m_PathPrefs[i] ));
if (hItem)
m_PropertyList.SetItemData(hItem, MAKELPARAM(i,PII_PATH) );
}
m_PropertyList.AddItem( PropCreateCategory("Numbers") );
for (int i = 0; i < PREF_INT_MAX; i++)
{
hItem = m_PropertyList.AddItem( PropCreateSimple(PREF_INT_NAME(i) , (LONG)g_pNewPrefs->m_IntPrefs[i] ));
if (hItem)
m_PropertyList.SetItemData(hItem, MAKELPARAM(i,PII_INTEGER) );
}
m_PropertyList.AddItem( PropCreateCategory("Booleans") );
for (int i = 0; i < PREF_BOOL_MAX; i++)
{
hItem = m_PropertyList.AddItem( PropCreateSimple(PREF_BOOL_NAME(i) , g_pNewPrefs->m_BoolPrefs[i] ? (bool)true : (bool)false )); // note the case of "bool"
if (hItem)
m_PropertyList.SetItemData(hItem, MAKELPARAM(i,PII_BOOL) );
}
m_PropertyList.AddItem( PropCreateCategory("Fonts") );
for (int i = 0; i < PREF_FONT_MAX; i++)
{
char *FontInfo = HydraIRC_BuildString(128,"%s,%d,%s%s%s",
g_pNewPrefs->m_FontPrefs[i].m_Name,
g_pNewPrefs->m_FontPrefs[i].m_Size,
g_pNewPrefs->m_FontPrefs[i].m_Flags == FIF_NONE ? "N" :
(g_pNewPrefs->m_FontPrefs[i].m_Flags & FIF_BOLD ? "B" : ""),
g_pNewPrefs->m_FontPrefs[i].m_Flags & FIF_ITALIC ? "I" : "",
g_pNewPrefs->m_FontPrefs[i].m_Flags & FIF_UNDERLINE ? "U" : "");
if (FontInfo)
{
hItem = m_PropertyList.AddItem( PropCreateSimple(PREF_FONT_NAME(i), FontInfo ));
if (hItem)
m_PropertyList.SetItemData(hItem, MAKELPARAM(i,PII_FONT) );
free(FontInfo);
}
}
m_PropertyList.AddItem( PropCreateCategory("Colors") );
for (int i = 0; i < PREF_COLOR_MAX; i++)
{
char *ColorInfo;
if (g_pNewPrefs->m_ColorPrefs[i] != -1)
ColorInfo = HydraIRC_BuildString(8,"#%06x",RGBVALTOCOLORREF(g_pNewPrefs->m_ColorPrefs[i]));
else
ColorInfo = strdup("System");
if (ColorInfo)
{
hItem = m_PropertyList.AddItem( PropCreateSimple(PREF_COLOR_NAME(i) , ColorInfo ));
if (hItem)
m_PropertyList.SetItemData(hItem, MAKELPARAM(i,PII_COLOR) );
free(ColorInfo);
}
}
this->UpdateWindow();
}
void CMiscPage::OnPageDone( void )
{
m_PropertyList.ResetContent();
}
BOOL CMiscPage::OnPageValidate( void )
{
BOOL OK = TRUE;
for (int i = 0; i < PREF_STRING_MAX; i++)
{
HPROPERTY hFind = m_PropertyList.FindProperty(PREF_STRING_NAME(i));
if (hFind)
{
CComVariant value;
BOOL Result = m_PropertyList.GetItemValue(hFind,&value);
LPARAM lParam = m_PropertyList.GetItemData(hFind);
if (HIWORD(lParam) == PII_STRING)
{
int ItemIndex = LOWORD(lParam);
if (g_pNewPrefs->m_StringPrefs[ItemIndex]) free(g_pNewPrefs->m_StringPrefs[ItemIndex]);
g_pNewPrefs->m_StringPrefs[ItemIndex] = strdup(CW2A(value.bstrVal));
}
else OK = FALSE;
}
else OK = FALSE;
}
for (int i = 0; i < PREF_PATH_MAX; i++)
{
HPROPERTY hFind = m_PropertyList.FindProperty(PREF_PATH_NAME(i));
if (hFind)
{
CComVariant value;
BOOL Result = m_PropertyList.GetItemValue(hFind,&value);
LPARAM lParam = m_PropertyList.GetItemData(hFind);
if (HIWORD(lParam) == PII_PATH)
{
int ItemIndex = LOWORD(lParam);
if (g_pNewPrefs->m_PathPrefs[ItemIndex]) free(g_pNewPrefs->m_PathPrefs[ItemIndex]);
g_pNewPrefs->m_PathPrefs[ItemIndex] = strdup(CW2A(value.bstrVal));
strippathseparator(g_pNewPrefs->m_PathPrefs[ItemIndex]);
}
else OK = FALSE;
}
else OK = FALSE;
}
for (int i = 0; i < PREF_INT_MAX; i++)
{
HPROPERTY hFind = m_PropertyList.FindProperty(PREF_INT_NAME(i));
if (hFind)
{
CComVariant value;
BOOL Result = m_PropertyList.GetItemValue(hFind,&value);
LPARAM lParam = m_PropertyList.GetItemData(hFind);
if (HIWORD(lParam) == PII_INTEGER)
{
int ItemIndex = LOWORD(lParam);
g_pNewPrefs->m_IntPrefs[ItemIndex] = value.intVal;
}
else OK = FALSE;
}
else OK = FALSE;
}
for (int i = 0; i < PREF_BOOL_MAX; i++)
{
HPROPERTY hFind = m_PropertyList.FindProperty(PREF_BOOL_NAME(i));
if (hFind)
{
CComVariant value;
BOOL Result = m_PropertyList.GetItemValue(hFind,&value);
LPARAM lParam = m_PropertyList.GetItemData(hFind);
if (HIWORD(lParam) == PII_BOOL)
{
int ItemIndex = LOWORD(lParam);
g_pNewPrefs->m_BoolPrefs[ItemIndex] = value.boolVal;
}
else OK = FALSE;
}
else OK = FALSE;
}
for (int i = 0; i < PREF_FONT_MAX; i++)
{
HPROPERTY hFind = m_PropertyList.FindProperty(PREF_FONT_NAME(i));
if (hFind)
{
CComVariant value;
BOOL Result = m_PropertyList.GetItemValue(hFind,&value);
LPARAM lParam = m_PropertyList.GetItemData(hFind);
if (HIWORD(lParam) == PII_FONT)
{
int ItemIndex = LOWORD(lParam);
g_pNewPrefs->UpdateFontPrefItem(&g_pNewPrefs->m_FontPrefs[ItemIndex],CW2A(value.bstrVal));
}
else OK = FALSE;
}
else OK = FALSE;
}
for (int i = 0; i < PREF_COLOR_MAX; i++)
{
HPROPERTY hFind = m_PropertyList.FindProperty(PREF_COLOR_NAME(i));
if (hFind)
{
CComVariant value;
BOOL Result = m_PropertyList.GetItemValue(hFind,&value);
LPARAM lParam = m_PropertyList.GetItemData(hFind);
if (HIWORD(lParam) == PII_COLOR)
{
int ItemIndex = LOWORD(lParam);
if (stricmp(CW2A(value.bstrVal),"System") == 0)
g_pNewPrefs->m_ColorPrefs[ItemIndex] = -1;
else
{
g_pNewPrefs->SetIntPref((int&)g_pNewPrefs->m_ColorPrefs[ItemIndex],CW2A(value.bstrVal));
g_pNewPrefs->m_ColorPrefs[ItemIndex] = RGBVALTOCOLORREF(g_pNewPrefs->m_ColorPrefs[ItemIndex]);
}
}
else OK = FALSE;
}
else OK = FALSE;
}
return OK;
}
LRESULT CMiscPage::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// the real init is done when the page is OnPageDisplay'd, as other preference items might
// make a difference to the data
DlgResize_Init(false,true,0);
m_PropertyList.SubclassWindow(GetDlgItem(IDC_MISC_PROPERTYLIST));
m_PropertyList.SetExtendedListStyle(PLS_EX_CATEGORIZED);
return 0;
}
LRESULT CMiscPage::OnPinBrowse(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/)
{
LPNMPROPERTYITEM nmp = (LPNMPROPERTYITEM)pnmh;
USES_CONVERSION;
/*
CComVariant value;
BOOL Result = m_PropertyList.GetItemValue(nmp->prop,&value);
CFileDialog *pFileDialog = new CFileDialog(FALSE,NULL,CW2A(value.bstrVal));
int result = pFileDialog->DoModal();
if (result > 0)
{
CComVariant v(pFileDialog->m_szFileName);
m_PropertyList.SetItemValue(nmp->prop, &v);
}
delete pFileDialog;
*/
CComVariant value;
BOOL Result = m_PropertyList.GetItemValue(nmp->prop,&value);
LPARAM lParam = m_PropertyList.GetItemData(nmp->prop);
if (HIWORD(lParam) != PII_PATH)
return 0;
int ItemIndex = LOWORD(lParam);
CFolderDialog *pFolderDialog = new CFolderDialog();
// TODO: annoyingly, this has no effect
//strcpy(pFolderDialog->m_szFolderPath,CW2A(value.bstrVal));
strcpy(pFolderDialog->m_szFolderDisplayName,CW2A(value.bstrVal));
int result = pFolderDialog->DoModal();
if (result > 0)
{
CComVariant v(pFolderDialog->m_szFolderPath);
m_PropertyList.SetItemValue(nmp->prop, &v);
}
delete pFolderDialog;
return 0;
}
| [
"hydra@b2473a34-e2c4-0310-847b-bd686bddb4b0"
]
| [
[
[
1,
302
]
]
]
|
9527d0bcd4a8a53a935cce3face0cf2712535f91 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aosdesigner/core/resources/ResourcePtr.hpp | f60229902f7d4bb4930a6ed67d91030f6035ceea | []
| no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 250 | hpp | #ifndef HGUARD_AOSD_CORE_RESOURCEPTR_H__
#define HGUARD_AOSD_CORE_RESOURCEPTR_H__
#pragma once
#include <memory>
namespace aosd
{
namespace core
{
class Resource;
typedef std::shared_ptr< Resource > ResourcePtr;
}
}
#endif
| [
"klaim@localhost"
]
| [
[
[
1,
19
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.