blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 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
sequencelengths 1
16
| author_lines
sequencelengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
43a02dff46c8720cdb354b256fc660b00151c312 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Application/SysCAD/PrjDCmp.cpp | 949ca5737af935a6e0e8cb44f2ed3e37ed91d400 | [] | no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,513 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#include "syscad.h"
#include "resource.h"
#include "PrjDCmp.h"
#include "tagdb.h"
#include "dlgbusy.h"
#include "dbhelper.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//------------------------------------------------------------------------
// CPrjDataCompare dialog
CPrjDataCompare::CPrjDataCompare(CWnd* pParent /*=NULL*/)
: CDialog(CPrjDataCompare::IDD, pParent)
{
//{{AFX_DATA_INIT(CPrjDataCompare)
m_Prj1 = _T("");
m_Prj2 = _T("");
m_Tolerance = 0.1;
m_Report1 = _T("");
m_FirstInClass = TRUE;
m_MissingTags = TRUE;
m_MissingValues = TRUE;
m_ValuesDifferent = FALSE;
//}}AFX_DATA_INIT
m_Prj1 = ScdPFUser.RdStr("ProjectCompare", "Project1", StartupDirectory());
m_Prj2 = ScdPFUser.RdStr("ProjectCompare", "Project2", StartupDirectory());
m_Tolerance=ScdPFUser.RdDouble("ProjectCompare", "Tolerance", m_Tolerance);
Strng S=TemporaryFiles();
S+="PrjDiffs.csv";
m_Report1=ScdPFUser.RdStr("ProjectCompare", "ReportFile", S());
m_FirstInClass=ScdPFUser.RdInt("ProjectCompare", "FirstInClass", m_FirstInClass);
m_MissingTags=ScdPFUser.RdInt("ProjectCompare", "MissingTags", m_MissingTags);
m_MissingValues=ScdPFUser.RdInt("ProjectCompare", "MissingValues", m_MissingValues);
m_ValuesDifferent=ScdPFUser.RdInt("ProjectCompare", "ValuesDifferent", m_ValuesDifferent);
hRpt=NULL;
}
//------------------------------------------------------------------------
void CPrjDataCompare::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CPrjDataCompare)
DDX_Text(pDX, IDC_PRJ1, m_Prj1);
DDX_Text(pDX, IDC_PRJ2, m_Prj2);
DDX_Text(pDX, IDC_TOLERANCE, m_Tolerance);
DDX_Text(pDX, IDC_REPORT1, m_Report1);
DDX_Check(pDX, IDC_FIRSTINCLASS, m_FirstInClass);
DDX_Check(pDX, IDC_MISSINGTAGS, m_MissingTags);
DDX_Check(pDX, IDC_MISSINGVALUES, m_MissingValues);
DDX_Check(pDX, IDC_VALUESDIFF, m_ValuesDifferent);
//}}AFX_DATA_MAP
}
//------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(CPrjDataCompare, CDialog)
//{{AFX_MSG_MAP(CPrjDataCompare)
ON_BN_CLICKED(ID_BROWSE1, OnBrowse1)
ON_BN_CLICKED(ID_BROWSE2, OnBrowse2)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
//------------------------------------------------------------------------
void CPrjDataCompare::OnOK()
{
CDialog::OnOK();
ScdPFUser.WrStr("ProjectCompare", "Project1", m_Prj1);
ScdPFUser.WrStr("ProjectCompare", "Project2", m_Prj2);
ScdPFUser.WrDouble("ProjectCompare", "Tolerance", m_Tolerance);
ScdPFUser.WrStr("ProjectCompare", "ReportFile", m_Report1);
ScdPFUser.WrInt("ProjectCompare", "FirstInClass", m_FirstInClass);
ScdPFUser.WrInt("ProjectCompare", "MissingTags", m_MissingTags);
ScdPFUser.WrInt("ProjectCompare", "MissingValues", m_MissingValues);
ScdPFUser.WrInt("ProjectCompare", "ValuesDifferent", m_ValuesDifferent);
}
//------------------------------------------------------------------------
void CPrjDataCompare::DoBrowse(CString & Prj)
{
Strng X;
X.Set("(*.MDB)|*.MDB|SysCAD Databases (*.MDB)|*.MDB||");
Strng Init;
Init.FnDrivePath((char*)(LPCTSTR)Prj);
CSCDFileDialog Dlg(true, "*.MDB", "", OFN_HIDEREADONLY | OFN_SHAREAWARE, X());
Dlg.m_ofn.lpstrInitialDir = Init();
Dlg.m_ofn.lpstrTitle = "Browse";
if (Dlg.DoModal()==IDOK)
{
Prj=Dlg.GetPathName();
}
}
//------------------------------------------------------------------------
void CPrjDataCompare::OnBrowse1()
{
DoBrowse(m_Prj1);
UpdateData(FALSE);
}
//------------------------------------------------------------------------
void CPrjDataCompare::OnBrowse2()
{
DoBrowse(m_Prj2);
UpdateData(FALSE);
}
//------------------------------------------------------------------------
flag CPrjDataCompare::DoCompare()
{
CDlgBusy::Open("", true);
CWaitCursor Wait;
CTagDBase TagDB[2];
int db, db1, DBFmt[2];
Strng Prj[2];
Prj[0].FnDrivePath((char*)(LPCTSTR)m_Prj1);
Prj[1].FnDrivePath((char*)(LPCTSTR)m_Prj2);
ClsTagMap.InitHashTable(FindNextPrimeNumber(4096));
NdMaps[0].InitHashTable(FindNextPrimeNumber(4096));
NdMaps[1].InitHashTable(FindNextPrimeNumber(4096));
CDlgBusy::SetLine(1, "Open : %s", Prj[0]());
DBFmt[0]=TagDB[0].Open(DBConnect_Find, DBO_ForRead, Prj[0](), NULL, NULL);
if (DBFmt[0]==0)
{
LogError("Compare Project", LF_Exclamation, "Cannot Open Database %s", (LPCTSTR)m_Prj1);
goto Close0;
}
CDlgBusy::SetLine(2, "Open : %s", Prj[1]());
DBFmt[1]=TagDB[1].Open(DBConnect_Find, DBO_ForRead, Prj[1](), NULL, NULL);
if (DBFmt[1]==0)
{
LogError("Compare Project", LF_Exclamation, "Cannot Open Database %s", (LPCTSTR)m_Prj2);
goto Close1;
}
hRpt=fopen((LPCTSTR)m_Report1, "wt");
if (hRpt==NULL)
{
LogError("Compare Project", LF_Exclamation, "Cannot Open Report %s", (LPCTSTR)m_Report1);
goto Close2;
}
else
{
fprintf(hRpt, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n", "Tag", "ClassTag", "Cnvs", "Value1", "Value2", "Difference");
fprintf(hRpt, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n", "$PrjName", "", "", (LPCTSTR)m_Prj1, (LPCTSTR)m_Prj2, "");
}
CDlgBusy::SetLine(1, "Comparing : %s", Prj[0]());
CDlgBusy::SetLine(2, "to : %s", Prj[1]());
//
LogNote("Compare Project", 0, "Project 1: %s", (LPCTSTR)m_Prj1);
LogNote("Compare Project", 0, "Project 2: %s", (LPCTSTR)m_Prj2);
LogNote("Compare Project", 0, "Report : %s", (LPCTSTR)m_Report1);
TagDB[0].FindRevisionNo(DBRev_MostRecent);
TagDB[1].FindRevisionNo(DBRev_MostRecent);
dbgpln("================================ Compare Data Start");
if (1)
{
//CXMsgLst XM;
CXM_ObjectData OD1(0);
CXM_ObjectData OD2(0);
CStopWatch Elapsed;//, LOSW, TLOSW;
flag AllLoaded=true;
flag Cancelled=false;
int n=0;
Elapsed.Start();
for (db=0; db<2; db++)
{
OD1.List.Clear();
//OD1.SetSize();
n=0;
TagDB[db].StartLoadSequence("Node");
while (!Cancelled && TagDB[db].LoadObject(&OD1, true)>=0)
{
//LOSW.Stop();
n++;
if ((n%Min(n,10))==0)
CDlgBusy::SetLine(3, "Identifying Unit :%i/%i", db+1 ,n);
Cancelled=CDlgBusy::IsCancelled();
//nObjs++;
//LOSW.Start();
Strng Tag;
CPkDataItem * pItem=OD1.FirstItem();
if (pItem->Type()==tt_Object)
{
CRootObj RObj;
RObj.Tag=pItem->TagStr();
RObj.Class=pItem->Class();
Nds[db].AddTail(RObj);
CRootObj* pRObj=&Nds[db].GetTail();
NdMaps[db].SetAt(pRObj->Tag(), pRObj);
}
else
LogError("Compare Project", LF_Exclamation, "Unknown Object Type");
//dbgpln("%*s %5i: %s", db*20,"", n, Tag());
}
CDlgBusy::SetLine(3, "%d) Identifying Unit : %i/%i", db+1, n);
}
// Check for existance
for (db=0; db<2; db++)
{
CDlgBusy::SetLine(3, "Check for existance : %i", db+1);
OD2.List.Clear();
//OD2.SetSize();
db1=(db+1)%2;
POSITION Pos=Nds[db].GetHeadPosition();
while (Pos)
{
CRootObj & S1=Nds[db].GetNext(Pos);
CRootObj *pS2;
if (!NdMaps[db1].Lookup(S1.Tag(), pS2) && m_MissingTags)
{
fprintf(hRpt, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n", S1.Tag(), S1.Class(),"", db==0 ? S1.Tag() : "", db==1 ? S1.Tag() : "", db==0 ? "Tag Missing from 2":"Tag Missing from 1");
}
}
}
if (m_MissingValues || m_ValuesDifferent)
if (1)
{
LogError("Compare Project", LF_Exclamation, "Object to object comparison not implemented!");
}
else
{
// Compare Data
OD2.List.Clear();
//OD2.SetSize();
db=0;
db1=1;
n=0;
POSITION Pos=Nds[db].GetHeadPosition();
while (Pos)
{
n++;
if ((n%Min(n,10))==0)
CDlgBusy::SetLine(3, "Comparing Unit :%i", n);
CRootObj & S1=Nds[db].GetNext(Pos);
CRootObj *pS2;
if (NdMaps[db1].Lookup(S1.Tag(), pS2))
{
int ret0=TagDB[0].LoadObject(S1.Tag(), &OD1);
int ret1=TagDB[1].LoadObject(S1.Tag(), &OD2);
if (ret0)
LogError("Compare Project", LF_Exclamation, "Object %s not loaded from Project1", S1.Tag());
else if (ret1)
LogError("Compare Project", LF_Exclamation, "Object %s not loaded form Project2", S1.Tag());
else
{
CompareObjects(&OD1, &OD2);
}
}
}
}
/*
//TLOSW.Start();
//LOSW.Start();
OD1.List.Clear();
OD1.SetSize();
TagDB1.StartLoadSequence("Node");
while (!Cancelled && TagDB1.LoadObject(&OD1, false)>=0)
{
//LOSW.Stop();
n++;
if ((n%Min(n,10))==0)
CDlgBusy::SetLine(3, "Comparing Unit :%i" ,n);
Cancelled=CDlgBusy::IsCancelled();
nObjs++;
//LOSW.Start();
}
//TLOSW.Stop();
//LOSW.Stop();
CDlgBusy::SetLine(3,"Comparing Unit :%i",n);
*/
Elapsed.ReStart();
/*
if (AllLoaded)
{
n=0;
//TLOSW.ReStart();
//LOSW.ReStart();
OD1.List.Clear();
OD1.SetSize();
TagDB1.StartLoadSequence("Conn");
while (!Cancelled && TagDB1.LoadObject(&OD1, false)>=0)
{
//LOSW.Stop();
n++;
if ((n%Min(n,10))==0)
CDlgBusy::SetLine(3,"Comparing Connection :%i",n);
Cancelled=CDlgBusy::IsCancelled();
//LOSW.Start();
}
//TLOSW.Stop();
//LOSW.Stop();
CDlgBusy::SetLine(3, "Comparing Connection :%i", n);
Elapsed.ReStart();
}
*/
//if (AllLoaded)
// {
// TagDB1.StartLoadSequence("Node");
// for (OInx=0; !Cancelled && OInx<Objs_Reg.GetSize(); OInx++)
// {
// CExecObj *r=Objs_Reg[OInx];
// if (LoadIt[OInx])//r->EO_BeginLoad(FCB))
// {
// n=0;
// TLOSW.ReStart();
//// TLOSW.Stop();
// LOSW.ReStart();
// OD1.List.Clear();
// OD1.SetSize();
// while (!Cancelled && TagDB1.LoadObject(&OD1, false)>=0)
// {
// LOSW.Stop();
// XM.Clear();
// if (XM.PackMsg(OD1))
// {
// n++;
// if ((n%Min(n,10))==0)
// CDlgBusy::SetLine(3, "Loading Object :%i of %i", n, nObjs);
// Cancelled=CDlgBusy::IsCancelled();
// #if dbgExecutive
// if (dbgDBMsgs())
// XM.dbgDump((flag)dbgFullDBMsgs(), r->sName(), "Load");
// #endif
// TLOSW.Start();
// r->EO_LoadDefinedData(FCB, XM);
// TLOSW.Stop();
// #if dbgStats
// if ((n%10)==0)
// dbgpln("Load TmElapsed %i, %10.5f/Obj", n, Elapsed.Secs()/Max(1,n));
// #endif
// }
// LOSW.Start();
// }
// TLOSW.Stop();
// LOSW.Stop();
// //TLOSW.Stop();
// CDlgBusy::SetLine(3, "Loading Object :%i of %i", n, nObjs);
//
// dbgpln("EO_LoadDB %-15s Load %8.3g = %8.5g/Obj [LO:%8.3f][TLO:%8.3f]",r->sName(), Elapsed.Secs(), Elapsed.Secs()/Max(1,n), LOSW.Secs(), TLOSW.Secs());
// }
// }
// }
}
goto CloseRpt;
CloseRpt:
fclose(hRpt);
Close2:
TagDB[1].Close();
Close1:
TagDB[0].Close();
Close0:
CDlgBusy::Close();
return true;
}
//------------------------------------------------------------------------
static flag ExpandObject(CXM_ObjectData *pObjData, CObjTagList& List, CObjTagMap & Map)
{
int dodbg=1;
CXM_ObjectData &OD=*pObjData;
Strng TagStack[30];
Strng ClsStack[30];
int iTag=-1;
Map.InitHashTable(FindNextPrimeNumber(256));
CPkDataIter Iter;
for (CPkDataItem* pPItem=OD.FirstItem(Iter); pPItem; pPItem=OD.List.NextItem(Iter))
{
CObjTag Tag, *pTag;
Tag.Str=pPItem->SymOrTag();
if (!IsLayout(pPItem->Type()) && Tag.Str.Length()>0)
{
if (IsStructStart(pPItem->Type()))
{
iTag++;
if (iTag>0)
{
TagStack[iTag]=TagStack[iTag-1];
TagStack[iTag]+=".";
}
TagStack[iTag]+=Tag.Str();
if (pPItem->Class() && _stricmp(pPItem->Class(), "*")!=0)
ClsStack[iTag]=pPItem->Class();
else
{
ClsStack[iTag]=ClsStack[iTag-1];
ClsStack[iTag]+=".";
ClsStack[iTag]+=Tag.Str();
}
if (dodbg)
dbgpln(" %-8.8s: %s",tt_TypeString(pPItem->Type()), ">>", TagStack[iTag]());
}
else if (IsStructEnd(pPItem->Type()))
{
if (dodbg)
dbgpln(" %-8.8s: %s",tt_TypeString(pPItem->Type()), "<<", TagStack[iTag]());
iTag--;
}
else
{
Tag.Str=TagStack[iTag];
Tag.Str+=".";
Tag.Str+=pPItem->SymOrTag();
Tag.pPItem=pPItem;
Tag.ClsTag=ClsStack[iTag];
Tag.ClsTag+=".";
Tag.ClsTag+=pPItem->SymOrTag();
List.AddTail(Tag);
pTag=&List.GetTail();
Map.SetAt(pTag->Str(), pTag);
if (dodbg)
dbgpln(" %-8.8s: %s = %s",tt_TypeString(pTag->Item().Type()), pTag->Str(), pTag->Item().Value()->String());
}
}
else
{
if (dodbg)
dbgpln(" %-8.8s: %s %s", tt_TypeString(pPItem->Type()), pPItem->SymOrTag(), "-------------- SKIP");
}
}
return true;
}
//------------------------------------------------------------------------
static int GetType(char * pStr)
{
int Typ=tt_Strng;
while (*pStr==' ') pStr++;
if (*pStr=='+' || *pStr=='-' || isdigit(*pStr))
{
Typ=tt_Long;
pStr++;
while (isdigit(*pStr))
pStr++;
if (*pStr=='.')
{
Typ=tt_Double;
pStr++;
while (isdigit(*pStr))
pStr++;
if (*pStr=='E' || *pStr=='e')
{
pStr++;
if (*pStr=='+' || *pStr=='-')
pStr++;
while (isdigit(*pStr))
pStr++;
}
}
while (*pStr && *pStr==' ')
pStr++;
if (*pStr && *pStr!=' ')
Typ=tt_Strng;
}
else
Typ=tt_Strng;
return Typ;
}
//------------------------------------------------------------------------
flag CPrjDataCompare::DoMessage(char * ClsTag0)
{
Strng *pClsTag;
if (!m_FirstInClass || !ClsTagMap.Lookup(ClsTag0, pClsTag))
{
if (m_FirstInClass)
{
Strng ClsTag(ClsTag0);
ClsTagLst.AddTail(ClsTag);
pClsTag=&ClsTagLst.GetTail();
ClsTagMap.SetAt(pClsTag->Str(), pClsTag);
}
return true;
}
return false;
}
//------------------------------------------------------------------------
flag CPrjDataCompare::CompareObject(CObjTagList& List0, CObjTagMap & Map0,
CObjTagList& List1, CObjTagMap & Map1,
FILE* hRpt, double Tol)
{
Strng sVal0, sVal1;
long lVal0, lVal1;
double dVal0, dVal1;
flag OK=true;
CObjTagListIter Lst0(List0);
for (CObjTag * pObj0=Lst0.First(); (pObj0); pObj0=Lst0.Next())
{
CObjTag * pObj1;
char * ClsTag0 =pObj0->ClsTag();
if (Map1.Lookup(pObj0->Str(), pObj1))
{
if (m_ValuesDifferent)
{
pObj0->Found=true;
pObj1->Found=true;
PkDataUnion * pVal0=pObj0->Item().Value();
PkDataUnion * pVal1=pObj1->Item().Value();
//char * Class1 =pObj1->Class();
char * Cnv0 =pObj0->Item().CnvFam();
char * Cnv1 =pObj1->Item().CnvFam();
int Typ0=pVal0->Type();
int Typ1=pVal1->Type();
char * pStr0=pVal0->String();
char * pStr1=pVal1->String();
if (Typ0==tt_Generic)
Typ0=GetType(pStr0);
if (Typ1==tt_Generic)
Typ1=GetType(pStr1);
flag Done=false;
if (Typ0!=Typ1)
{
if (IsNumData(Typ0) && IsNumData(Typ1))
{
Typ0=tt_Double;
Typ1=tt_Double;
}
else if ((IsNumData(Typ0) && _stricmp(pStr1, "*")==0) ||
(IsNumData(Typ1) && _stricmp(pStr0, "*")==0))
{
if (DoMessage(ClsTag0))
fprintf(hRpt, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%i\"\n", pObj0->Str(), ClsTag0, "", pStr0, pStr1, "Disabled");
Done=true;
}
}
if (Typ0==Typ1 && !Done)
{
if (IsIntData(Typ0))
{
lVal0=atol(pStr0);
lVal1=atol(pStr1);
if (lVal0!=lVal1 && DoMessage(ClsTag0))
fprintf(hRpt, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%i\"\n", pObj0->Str(), ClsTag0, "", pStr0, pStr1, lVal1-lVal0);
}
else if (IsFloatData(Typ0))
{
dVal0=atof(pStr0);
dVal1=atof(pStr1);
if (!ConvergedVV(dVal0, dVal1, 1.0e-12, Tol) && DoMessage(ClsTag0))
fprintf(hRpt, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%g\"\n", pObj0->Str(), ClsTag0, "", pStr0, pStr1, dVal1-dVal0);
}
else //if (IsFloatData(Typ0))
{
if (_stricmp(pStr0, pStr1)!=0 && DoMessage(ClsTag0))
fprintf(hRpt, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n", pObj0->Str(), ClsTag0, "", pStr0, pStr1, "");
}
}
else
{
if (DoMessage(ClsTag0))
fprintf(hRpt, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n", pObj0->Str(), ClsTag0, "", pStr0, pStr1, "Types Different");
}
}
}
else if (m_MissingValues)
{
if (DoMessage(ClsTag0))
fprintf(hRpt, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n", pObj0->Str(), ClsTag0, "", pObj0->Item().Value()->String(), "", "Missing from 2");
}
}
if (m_MissingValues)
{
CObjTagListIter Lst1(List1);
for (CObjTag * pObj1=Lst1.First(); (pObj1); pObj1=Lst1.Next())
{
char * ClsTag1 =pObj1->ClsTag();
if (!pObj1->Found)
{
if (DoMessage(ClsTag1))
fprintf(hRpt, "\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"\n", pObj1->Str(), ClsTag1, "", "", pObj1->Item().Value()->String(), "Missing from 1");
}
}
}
return OK;
}
//------------------------------------------------------------------------
flag CPrjDataCompare::CompareObjects(CXM_ObjectData *pObjData0, CXM_ObjectData *pObjData1)
{
CObjTagMap Map0, Map1;
CObjTagList Lst0, Lst1;
ExpandObject(pObjData0, Lst0, Map0);
ExpandObject(pObjData1, Lst1, Map1);
return CompareObject(Lst0, Map0, Lst1, Map1, hRpt, m_Tolerance);
}
//------------------------------------------------------------------------
| [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
428
],
[
430,
569
],
[
572,
590
],
[
592,
595
],
[
597,
642
]
],
[
[
429,
429
],
[
570,
571
],
[
596,
596
]
],
[
[
591,
591
]
]
] |
65f5e4bc47878ac87c3169135bedc6954027e3a1 | ab4b2c5f98973babd82d47a4cf52f9701d85ea66 | /src/analyzer/aql-driver.h | e66255439409a42a28bcf88b1d961d990e60bf56 | [] | no_license | rodrigomicrosiga/AQL | 033c1f1bd0d77275cd4561279c272c8b234becbe | cbc5a24828af779c46fb1ece740769a1d5fce338 | refs/heads/master | 2021-01-16T21:24:55.871464 | 2011-10-24T23:34:03 | 2011-10-24T23:34:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | h | #ifndef AQL_DRIVER_H
#define AQL_DRIVER_H
#include <string>
#include <sstream>
#include "aql-parser.tab.hh"
#define YY_DECL \
AQL::aql_parser::token_type \
yylex( AQL::aql_parser::semantic_type* yylval, \
AQL::aql_parser::location_type* yylloc, \
AQL::aql_driver& driver)
YY_DECL;
namespace AQL {
class aql_driver {
private:
std::string* currentFileName;
unsigned int currentLine;
unsigned int currentColumn;
public:
aql_driver();
virtual ~aql_driver();
//AQL::AqlQueriesManager* qManager;
int result;
void scan_begin();
void scan_end();
bool trace_scanning;
bool trace_parsing;
int parse(const std::string& f);
std::string file;
void error(const AQL::location& l, const std::string& m);
void error(const std::string& m);
void setCurrentLocation(const AQL::location& l);
std::string * getLocationString(void) const;*/
inline std::ostream
};
} //namespace AQL
#endif | [
"[email protected]"
] | [
[
[
1,
51
]
]
] |
060902226d1ffc06b5b36daf987c89e5cb447e7a | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Networking/SecureSockets/SecEngine.cpp | fdc061b26f8cf26e9153c7f8c7c656f8393b7aa0 | [] | no_license | huellif/symbian-example | 72097c9aec6d45d555a79a30d576dddc04a65a16 | 56f6c5e67a3d37961408fc51188d46d49bddcfdc | refs/heads/master | 2016-09-06T12:49:32.021854 | 2010-10-14T06:31:20 | 2010-10-14T06:31:20 | 38,062,421 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,222 | cpp | //
// SecEngine.cpp
//
// Copyright (c) 2001 Symbian Ltd. All rights reserved.
#include "SecEngine.h"
// Send buffer size
const TInt KSendBufferSize = 256;
// Receive buffer size
const TInt KReceiveBufferSize = 256;
// HTTP messages
_LIT8(KSimpleGet, "GET ");
_LIT8(KNewLine, "\n");
// Progress messages
_LIT(KConnnectedMessage, "\nConnecting to %S:%d%S\n");
_LIT(KSecureConnnectingMessage, "\nMaking secure connection");
_LIT(KGettingPageMessage, "\nRequesting web page");
_LIT(KReceivingMessage,"\nReceiving server response");
_LIT(KCipherSuiteInUseMessage,"\nCipher suite in use: %S");
_LIT(KProtocolMessage, "\nProtocol used in connection: %S");
_LIT(KReceivedMessage,"\nReceived server response");
_LIT(KCompleteMessage,"\nTransaction complete: bytes recieved %d");
_LIT(KFileErrorMessage,"\nError in writing data to file");
_LIT(KCancelledMessage,"\nConnection closed");
// State reporting messages
_LIT( KStateErrESocketConnected, "\nError in state ESocketConnected: %d\n" );
_LIT( KStateErrESettingCiphers, "\nError in state ESettingCiphers: %d\n" );
_LIT( KStateErrSecureConnected, "\nError in state ESecureConnected: %d\n" );
_LIT( KStateErrGetRequestSent, "\nError in state EGetRequestSent: %d\n" );
_LIT( KStateErrEDataReceived, "\nError in state EDataReceived: %d\n" );
// Panic code
_LIT( KSecEnginePanic, "SEC-ENGINE");
//
// CSecEngine
//
CSecEngine* CSecEngine::NewL()
{
CSecEngine* self = new(ELeave) CSecEngine;
CleanupStack::PushL( self );
self->ConstructL();
CleanupStack::Pop();
return self;
}
// Constructor should also call the parent constructor to set the priority
// of the active object.
CSecEngine::CSecEngine()
: CActive(0), iSndBuffer(0,0), iRcvBuffer(0,0)
{
}
CSecEngine::~CSecEngine()
{
// Cancel any outstanding request- this cleans up
// resources created during a connection
//Cancel();
ConnectionClosed();
// Clean up engine's permanent resources
delete (void*)iSndBuffer.Ptr();
delete (void*)iRcvBuffer.Ptr();
iTimer.Close();
iSocketServ.Close();
}
void CSecEngine::ConstructL()
{
iSndBuffer.Set((TUint8*)User::AllocL(KSendBufferSize),0,KSendBufferSize);
iRcvBuffer.Set((TUint8*)User::AllocL(KReceiveBufferSize),0,KReceiveBufferSize);
// Connect the socket server
User::LeaveIfError( iSocketServ.Connect());
// Create a local timer
User::LeaveIfError( iTimer.CreateLocal());
// Set initial state
iRunState = ESocketConnected;
iInUse = EFalse;
CActiveScheduler::Add( this );
}
void CSecEngine::ConnectL(const TConnectSettings& aConnectSettings)
{
iConnectSettings = &aConnectSettings;
// Set initial values for flags & buffers
iSuccess = ETrue;
iInUse = ETrue;
iRunState = ESocketConnected;
iSndBuffer.SetLength( 0 );
iRcvBuffer.SetLength( 0 );
iTotalBytesRead = 0;
// Interpret server address
if (iInetAddr.Input(iConnectSettings->iAddress) != KErrNone)
// Success if already in dotted-decimal format
{
// Connect to a host resolver (for DNS resolution) - happens sychronously
User::LeaveIfError( iHostResolver.Open( iSocketServ, KAfInet, KProtocolInetTcp ));
// Try to resolve symbolic name
TNameEntry nameEntry;
User::LeaveIfError (iHostResolver.GetByName( iConnectSettings->iAddress, nameEntry ));
TSockAddr sockAddr = nameEntry().iAddr;
iInetAddr = iInetAddr.Cast( sockAddr );
iHostResolver.Close();
}
// Store other connection parameters
iInetAddr.SetPort( iConnectSettings->iPortNum );
// Open a TCP socket
User::LeaveIfError( iSocket.Open( iSocketServ, KAfInet, KSockStream, KProtocolInetTcp ) );
// Connect to the server, asynchronously
iSocket.Connect( iInetAddr, iStatus );
SetActive();
// Print status
iConsole->Printf(KConnnectedMessage,
&iConnectSettings->iAddress,
iConnectSettings->iPortNum,
&iConnectSettings->iPage );
}
void CSecEngine::SetConsole( CConsoleBase& aConsole )
{
iConsole = &aConsole;
}
void CSecEngine::SetOutputFile( RFile& aOutputFile )
{
iOutputFile = &aOutputFile;
}
TBool CSecEngine::InUse()
{
return iInUse;
}
void CSecEngine::RunL()
{
switch ( iRunState )
{
case ESocketConnected:
MakeSecureConnectionL();
break;
case ESecureConnected:
MakePageRequestL();
break;
case EGetRequestSent:
GetServerResponseL();
break;
case EDataReceived:
ReadServerResponseL();
break;
case EConnectionClosed:
ConnectionClosed();
break;
default:
break;
} // end switch
}
TInt CSecEngine::RunError( TInt aError )
{
// Panic prevents looping
__ASSERT_ALWAYS(iRunState != EConnectionClosed,
User::Panic(KSecEnginePanic,0));
// do a switch on the state to get the right err message
switch (iRunState)
{
case ESocketConnected:
iConsole->Printf(KStateErrESocketConnected, aError );
break;
case ESettingCiphers:
iConsole->Printf(KStateErrESettingCiphers, aError );
break;
case ESecureConnected:
iConsole->Printf(KStateErrSecureConnected, aError);
break;
case EGetRequestSent:
iConsole->Printf(KStateErrGetRequestSent, aError);
break;
case EDataReceived:
iConsole->Printf(KStateErrEDataReceived, aError);
break;
default:
break;
}
iRunState = EConnectionClosed;
iSuccess = EFalse;
iTimer.After( iStatus, 1000000 );
SetActive();
return KErrNone;
}
void CSecEngine::DoCancel()
{
iConsole->Printf(KCancelledMessage);
ConnectionClosed();
}
void CSecEngine::MakeSecureConnectionL()
{
User::LeaveIfError(iStatus.Int()); // errors caught by RunError()
// Construct the TLS socket, to use the TLS1.0 protocol.
// Specifying SSL3.0 would also use the same implementation
iConsole->Printf(KSecureConnnectingMessage);
_LIT(KTLS1,"TLS1.0");
iTlsSocket = CSecureSocket::NewL( iSocket, KTLS1 );
// Set any options before the handshake starts
// Clears any previous options
iTlsSocket->FlushSessionCache();
/* Note: You could here set the available ciphers with code such as the following:
TBuf8<2> buf;
buf.SetLength(2);
buf[0]=0; buf[1]=10;
iTlsSocket->SetAvailableCipherSuites( buf ); */
// start the handshake
iTlsSocket->StartClientHandshake( iStatus );
iRunState = ESecureConnected;
SetActive();
}
void CSecEngine::MakePageRequestL()
{
// The secure connection has now been made.
// Send a get request for the page.
User::LeaveIfError(iStatus.Int());
iConsole->Printf(KGettingPageMessage);
// Create a GET request
iSndBuffer+=KSimpleGet;
iSndBuffer+=iConnectSettings->iPage;
iSndBuffer+=KNewLine;
// Send the request
iRunState = EGetRequestSent;
iTlsSocket->Send( iSndBuffer, iStatus, iBytesSent );
SetActive();
}
void CSecEngine::GetServerResponseL()
{
// The get request has been sent, can now try and receive the data
User::LeaveIfError(iStatus.Int());
iConsole->Printf(KReceivingMessage);
// Print the cipher suite that has been negotiated.
TBuf8<2> buf;
User::LeaveIfError(iTlsSocket->CurrentCipherSuite( buf ));
PrintCipherNameL(buf);
// Print the protocol version string
TBuf<32> protocol;
User::LeaveIfError(iTlsSocket->Protocol( protocol ));
iConsole->Printf(KProtocolMessage, &protocol );
// Print info about the server's certificate
const CX509Certificate *servCert = iTlsSocket->ServerCert();
if ( servCert ) PrintCertInfo( *servCert );
// Read asynchonously-returns when buffer full
iRunState = EDataReceived;
iTlsSocket->Recv( iRcvBuffer, iStatus );
SetActive();
}
void CSecEngine::ReadServerResponseL()
{
// Any error other than KErrEof means the test is a failure
if (iStatus!=KErrEof) User::LeaveIfError(iStatus.Int());
iConsole->Printf(KReceivedMessage);
// Put the received data in the output file & reset the receive buffer
iTotalBytesRead += iRcvBuffer.Length();
TInt ret = iOutputFile->Write(iRcvBuffer);
if (ret != KErrNone) iConsole->Printf(KFileErrorMessage);
// Case 1: error is KErrEof (message complete) or no data received, so stop
if ( ( iStatus==KErrEof ) || ( iRcvBuffer.Length() == 0 ) )
{
iConsole->Printf(KCompleteMessage, iTotalBytesRead);
// Close the socket neatly
iRunState = EConnectionClosed;
iTimer.After( iStatus, 1000000 );
SetActive();
return;
}
// Case 2: there's more data to get from the server
iRcvBuffer.SetLength( 0 );
iRunState = EDataReceived;
iTlsSocket->Recv( iRcvBuffer, iStatus );
SetActive();
}
void CSecEngine::ConnectionClosed()
{
if (!iInUse) return;
// Clean up
iHostResolver.Close();
iSocket.CancelAll();
iTlsSocket->CancelAll();
iTlsSocket->Close();
delete iTlsSocket;
iTlsSocket =0;
iSocket.Close();
// Close the output file
iOutputFile->Close();
// Wait here for an unload of the ssl.dll to make sure that a session is not
// reconnected next time.
User::After( 1000000 );
iInUse = EFalse;
}
void CSecEngine::PrintCipherNameL(const TDes8& aBuf)
{
TLex8 lex(aBuf);
TUint cipherCode=aBuf[1];
if ((cipherCode<1) || (cipherCode > 0x1B))
User::Leave(KErrArgument);
const TText* KCipherNameArray[0x1B] =
{
_S("TLS_RSA_WITH_NULL_MD5"),
_S("TLS_RSA_WITH_NULL_SHA"),
_S("TLS_RSA_EXPORT_WITH_RC4_40_MD5"),
_S("TLS_RSA_WITH_RC4_128_MD5"),
_S("TLS_RSA_WITH_RC4_128_SHA"),
_S("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5"),
_S("TLS_RSA_WITH_IDEA_CBC_SHA"),
_S("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA"),
_S("TLS_RSA_WITH_DES_CBC_SHA"),
_S("TLS_RSA_WITH_3DES_EDE_CBC_SHA"),
_S("TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"),
_S("TLS_DH_DSS_WITH_DES_CBC_SHA"),
_S("TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA"),
_S("TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"),
_S("TLS_DH_RSA_WITH_DES_CBC_SHA"),
_S("TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA"),
_S("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"),
_S("TLS_DHE_DSS_WITH_DES_CBC_SHA"),
_S("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"),
_S("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"),
_S("TLS_DHE_RSA_WITH_DES_CBC_SHA"),
_S("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"),
_S("TLS_DH_anon_EXPORT_WITH_RC4_40_MD5"),
_S("TLS_DH_anon_WITH_RC4_128_MD5"),
_S("TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA"),
_S("TLS_DH_anon_WITH_DES_CBC_SHA"),
_S("TLS_DH_anon_WITH_3DES_EDE_CBC_SHA")
};
TPtrC name(KCipherNameArray[cipherCode-1]);
iConsole->Printf(KCipherSuiteInUseMessage, &name );
}
void CSecEngine::PrintCertInfo(const CX509Certificate& aSource)
{
_LIT(KCertInfoMessage1, "\nCertificate received: \n\tIssuer %S \n\tSubject %S");
_LIT(KCertInfoMessage2, "\n\tValid from %S to %S");
_LIT(KDateString,"%F%/0%M%/1%Y%/2%D%/3");
TRAP_IGNORE(
// Print issuer and subject
HBufC* issuer = aSource.IssuerL();
HBufC* subject = aSource.SubjectL();
iConsole->Printf(KCertInfoMessage1, issuer, subject);
delete issuer;
delete subject;
// Print validity period
TBuf<20> startTime;
TBuf<20> finishTime;
aSource.ValidityPeriod().Start().FormatL(startTime,KDateString);
aSource.ValidityPeriod().Finish().FormatL(finishTime,KDateString);
iConsole->Printf(KCertInfoMessage2, &startTime, &finishTime);
);
}
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
] | [
[
[
1,
399
]
]
] |
e8f4c162d8ae97e37f02f6406af6a57c875d2474 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian/CSImageConverterCache.cpp | 73c870258344e1b8052caa46ef5b91ac5597b0ed | [
"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 | 5,348 | 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 "CSImageConverterCache.h"
CCSImageConverterCache* CCSImageConverterCache::NewLC(MCSImageConverterCacheObserver& aRequester,
const TDesC& aImageExt)
{
CCSImageConverterCache* self = new (ELeave) CCSImageConverterCache(aRequester, aImageExt);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
CCSImageConverterCache* CCSImageConverterCache::NewL(MCSImageConverterCacheObserver& aRequester,
const TDesC& aImageExt)
{
CCSImageConverterCache* self = CCSImageConverterCache::NewLC(aRequester, aImageExt);
CleanupStack::Pop(self);
return self;
}
CCSImageConverterCache::~CCSImageConverterCache()
{
for (cacheMapIt_t it = iCacheMap.begin(); it != iCacheMap.end(); ++it) {
delete it->first;
delete it->second;
}
iFs.Close();
}
void CCSImageConverterCache::ConvertImage(const TDesC& aFilename, TSize aSize)
{
CWsScreenDevice* screenDevice = CCoeEnv::Static()->ScreenDevice();
iBitmapConverter->ConvertFileL(aFilename,
aSize,
screenDevice->DisplayMode());
}
void CCSImageConverterCache::ImageConversionDone(TInt aResult)
{
if (aResult != KErrNone) {
// Something wrong, delete from imageVec and ignore this image
iNameVec.pop_back();
}
CEikImage* image = new (ELeave) CEikImage();
image->SetBitmap(iBitmapConverter->GetImage());
image->SetMask(iBitmapConverter->GetMask());
TParse parser;
parser.Set(iNameVec.back(), NULL, NULL);
HBufC* name = parser.Name().AllocL();
iCacheMap.insert(std::make_pair(name, image));
iNameVec.pop_back();
if (iNameVec.size() > 0) {
ConvertImage(iNameVec.back(), iSize);
} else {
iRequester.ImagesConverted();
}
}
void CCSImageConverterCache::ConstructL()
{
iFs.Connect();
iBitmapConverter = CBitmapConverter::NewL(this, iFs);
}
CCSImageConverterCache::CCSImageConverterCache(MCSImageConverterCacheObserver& aRequester,
const TDesC& aImageExt) :
iRequester(aRequester),
iImageExt(aImageExt)
{ }
void CCSImageConverterCache::LocateAndConvertImages(const TDesC& aPath, TSize aSize)
{
iSize = aSize;
CDir* dirList;
iFs.GetDir(aPath, KEntryAttNormal, ESortByName, dirList);
class TParse parser;
if (dirList->Count() <= TInt(iCacheMap.size())) {
// We can assume that we have converted and cached all existing
// images. By doing this we skip the text compare below.
iRequester.ImagesConverted();
return;
}
for (TInt i = 0; i < dirList->Count(); ++i) {
parser.Set(dirList->operator[](i).iName, &aPath, NULL);
if (parser.Ext().CompareF(iImageExt) == 0) {
// Found a file with the correct extension
HBufC* tmpName = dirList->operator[](i).iName.AllocLC();
if (iCacheMap.find(tmpName) == iCacheMap.end()) {
iNameVec.push_back(parser.FullName());
}
CleanupStack::PopAndDestroy(tmpName);
}
}
delete dirList;
if (iNameVec.size() > 0) {
ConvertImage(iNameVec.back(), iSize);
} else {
iRequester.ImagesConverted();
}
}
const cacheMap_t CCSImageConverterCache::GetImageCache() const
{
return iCacheMap;
}
cacheMap_t::const_iterator CCSImageConverterCache::FindImagePair(HBufC* aFilename) const
{
return iCacheMap.find(aFilename);
}
CEikImage* CCSImageConverterCache::FindImage(HBufC* aFilename)
{
cacheMap_t::iterator it = iCacheMap.find(aFilename);
if (it == iCacheMap.end()) {
return NULL;
}
return it->second;
}
| [
"[email protected]"
] | [
[
[
1,
132
]
]
] |
c03c1911afc20653ea7e59e707ba495cc3d2fd06 | 3472e587cd1dff88c7a75ae2d5e1b1a353962d78 | /XMonitor/debug/moc_thread.cpp | ee9e104cd96e040c014eab51d1c7bce88b23b3ec | [] | no_license | yewberry/yewtic | 9624d05d65e71c78ddfb7bd586845e107b9a1126 | 2468669485b9f049d7498470c33a096e6accc540 | refs/heads/master | 2021-01-01T05:40:57.757112 | 2011-09-14T12:32:15 | 2011-09-14T12:32:15 | 32,363,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,069 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'thread.h'
**
** Created: Mon Feb 28 06:57:16 2011
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/thread.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'thread.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_Thread[] = {
// content:
5, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_Thread[] = {
"Thread\0"
};
const QMetaObject Thread::staticMetaObject = {
{ &QThread::staticMetaObject, qt_meta_stringdata_Thread,
qt_meta_data_Thread, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &Thread::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *Thread::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *Thread::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_Thread))
return static_cast<void*>(const_cast< Thread*>(this));
return QThread::qt_metacast(_clname);
}
int Thread::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QThread::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86"
] | [
[
[
1,
69
]
]
] |
117aca18ec228db48042fb837cef5b0a1d0fae11 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/src/signals/nsignal.cc | f4ce39fa898485392639c9df2d0011fc459a67de | [] | 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 | 2,598 | cc | //------------------------------------------------------------------------------
// nsignal.cc
// (c) 2004 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "precompiled/pchnkernel.h"
#include "kernel/ntypes.h"
#include "signals/nsignal.h"
#include "signals/nsignalemitter.h"
#include "signals/nsignalbindingset.h"
#include "signals/nsignalbinding.h"
//------------------------------------------------------------------------------
// internal variable used as temporal buffer
char _nSignalPrototypeBuffer[N_MAXPATH];
//------------------------------------------------------------------------------
bool
nSignal::Dispatch(void * emitter, nCmd * cmd)
{
// get binding list for emitter for this signal
nSignalBindingSet * bs = this->GetBindingSet(
reinterpret_cast<nObject *> (emitter),
this->GetId()
);
// if binding set exists then call every binding in the list
if (bs)
{
nSignalBinding * binding = bs->GetHead();
while (binding)
{
if (binding->IsValid())
{
binding->Invoke(cmd);
binding = binding->GetSucc();
}
else
{
nSignalBinding * tmp = binding->GetSucc();
n_delete(binding);
binding = tmp;
}
}
}
return true;
}
//------------------------------------------------------------------------------
/**
*/
bool
nSignal::Dispatch(nSignalEmitter * emitter, va_list args)
{
/*
XXX: The dispatch could be implemented same way as Dispatch(emitter, nCmd)
but calling Invoke(va_list args).
The most optimum could be to know if the binding is done with scripting or
native code, in order to call the proper member function with nCmd or args
depending on the case.
*/
// get new command and forward to Dispatch
nCmd * cmd = this->NewCmd();
cmd->CopyInArgsFrom(args);
this->Dispatch(static_cast<nObject *> (emitter), cmd);
this->RelCmd(cmd);
return true;
}
//------------------------------------------------------------------------------
/**
*/
nSignalBindingSet *
nSignal::GetBindingSet(nSignalEmitter * emitter, nFourCC signalId) const
{
return emitter->FindSignalBindingSet(signalId);
}
//------------------------------------------------------------------------------
// EOF
//------------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
84
]
]
] |
89a3b916f580d44e3fd347a20f54441329ab99be | 0d8034b26c80aad5d762ecac95beb180c74e16e9 | /Billiard/Billiard/optitrack.h | 83625ece3edef80576827665f6fff7379069ed04 | [] | no_license | zinking/3ddesktopgame | c61a20f3812418f032dbf94b5479f3c9306f2f8d | 867abd5189b028732e222326e83eed313d7caf83 | refs/heads/master | 2021-03-12T23:30:28.875389 | 2009-09-16T10:22:28 | 2009-09-16T10:22:28 | 32,133,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150,104 | h |
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 6.00.0366 */
/* Compiler settings for optitrack.idl:
Oicf, W1, Zp8, env=Win32 (32b run)
protocol : dce , ms_ext, c_ext, robust
error checks: allocation ref bounds_check enum stub_data , no_format_optimization
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
//@@MIDL_FILE_HEADING( )
#pragma warning( disable: 4049 ) /* more than 64k source lines */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif // __RPCNDR_H_VERSION__
#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif /*COM_NO_WINDOWS_H*/
#ifndef __optitrack_h__
#define __optitrack_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifndef __INPCameraCollection_FWD_DEFINED__
#define __INPCameraCollection_FWD_DEFINED__
typedef interface INPCameraCollection INPCameraCollection;
#endif /* __INPCameraCollection_FWD_DEFINED__ */
#ifndef __INPCamera_FWD_DEFINED__
#define __INPCamera_FWD_DEFINED__
typedef interface INPCamera INPCamera;
#endif /* __INPCamera_FWD_DEFINED__ */
#ifndef __INPCameraFrame_FWD_DEFINED__
#define __INPCameraFrame_FWD_DEFINED__
typedef interface INPCameraFrame INPCameraFrame;
#endif /* __INPCameraFrame_FWD_DEFINED__ */
#ifndef __INPObject_FWD_DEFINED__
#define __INPObject_FWD_DEFINED__
typedef interface INPObject INPObject;
#endif /* __INPObject_FWD_DEFINED__ */
#ifndef __INPSmoothing_FWD_DEFINED__
#define __INPSmoothing_FWD_DEFINED__
typedef interface INPSmoothing INPSmoothing;
#endif /* __INPSmoothing_FWD_DEFINED__ */
#ifndef __INPVector_FWD_DEFINED__
#define __INPVector_FWD_DEFINED__
typedef interface INPVector INPVector;
#endif /* __INPVector_FWD_DEFINED__ */
#ifndef __INPPoint_FWD_DEFINED__
#define __INPPoint_FWD_DEFINED__
typedef interface INPPoint INPPoint;
#endif /* __INPPoint_FWD_DEFINED__ */
#ifndef __INPVector2_FWD_DEFINED__
#define __INPVector2_FWD_DEFINED__
typedef interface INPVector2 INPVector2;
#endif /* __INPVector2_FWD_DEFINED__ */
#ifndef __INPVector3_FWD_DEFINED__
#define __INPVector3_FWD_DEFINED__
typedef interface INPVector3 INPVector3;
#endif /* __INPVector3_FWD_DEFINED__ */
#ifndef __INPAvi_FWD_DEFINED__
#define __INPAvi_FWD_DEFINED__
typedef interface INPAvi INPAvi;
#endif /* __INPAvi_FWD_DEFINED__ */
#ifndef ___INPCameraCollectionEvents_FWD_DEFINED__
#define ___INPCameraCollectionEvents_FWD_DEFINED__
typedef interface _INPCameraCollectionEvents _INPCameraCollectionEvents;
#endif /* ___INPCameraCollectionEvents_FWD_DEFINED__ */
#ifndef ___INPCameraEvents_FWD_DEFINED__
#define ___INPCameraEvents_FWD_DEFINED__
typedef interface _INPCameraEvents _INPCameraEvents;
#endif /* ___INPCameraEvents_FWD_DEFINED__ */
#ifndef __NPCameraCollection_FWD_DEFINED__
#define __NPCameraCollection_FWD_DEFINED__
#ifdef __cplusplus
typedef class NPCameraCollection NPCameraCollection;
#else
typedef struct NPCameraCollection NPCameraCollection;
#endif /* __cplusplus */
#endif /* __NPCameraCollection_FWD_DEFINED__ */
#ifndef __NPCamera_FWD_DEFINED__
#define __NPCamera_FWD_DEFINED__
#ifdef __cplusplus
typedef class NPCamera NPCamera;
#else
typedef struct NPCamera NPCamera;
#endif /* __cplusplus */
#endif /* __NPCamera_FWD_DEFINED__ */
#ifndef __NPCameraFrame_FWD_DEFINED__
#define __NPCameraFrame_FWD_DEFINED__
#ifdef __cplusplus
typedef class NPCameraFrame NPCameraFrame;
#else
typedef struct NPCameraFrame NPCameraFrame;
#endif /* __cplusplus */
#endif /* __NPCameraFrame_FWD_DEFINED__ */
#ifndef __NPObject_FWD_DEFINED__
#define __NPObject_FWD_DEFINED__
#ifdef __cplusplus
typedef class NPObject NPObject;
#else
typedef struct NPObject NPObject;
#endif /* __cplusplus */
#endif /* __NPObject_FWD_DEFINED__ */
#ifndef __NPSmoothing_FWD_DEFINED__
#define __NPSmoothing_FWD_DEFINED__
#ifdef __cplusplus
typedef class NPSmoothing NPSmoothing;
#else
typedef struct NPSmoothing NPSmoothing;
#endif /* __cplusplus */
#endif /* __NPSmoothing_FWD_DEFINED__ */
#ifndef __NPVector_FWD_DEFINED__
#define __NPVector_FWD_DEFINED__
#ifdef __cplusplus
typedef class NPVector NPVector;
#else
typedef struct NPVector NPVector;
#endif /* __cplusplus */
#endif /* __NPVector_FWD_DEFINED__ */
#ifndef __NPPoint_FWD_DEFINED__
#define __NPPoint_FWD_DEFINED__
#ifdef __cplusplus
typedef class NPPoint NPPoint;
#else
typedef struct NPPoint NPPoint;
#endif /* __cplusplus */
#endif /* __NPPoint_FWD_DEFINED__ */
#ifndef __NPAvi_FWD_DEFINED__
#define __NPAvi_FWD_DEFINED__
#ifdef __cplusplus
typedef class NPAvi NPAvi;
#else
typedef struct NPAvi NPAvi;
#endif /* __cplusplus */
#endif /* __NPAvi_FWD_DEFINED__ */
/* header files for imported files */
#include "oaidl.h"
#include "ocidl.h"
#ifdef __cplusplus
extern "C"{
#endif
void * __RPC_USER MIDL_user_allocate(size_t);
void __RPC_USER MIDL_user_free( void * );
/* interface __MIDL_itf_optitrack_0000 */
/* [local] */
#define B2VB(b) ((VARIANT_BOOL)(b ? VARIANT_TRUE : VARIANT_FALSE))
#define VB2B(b) ((BOOL) b == VARIANT_TRUE ? TRUE : FALSE)
#define NP_THRESHOLD_MIN 1
#define NP_THRESHOLD_MAX 253
#define NP_DRAW_SCALE_MIN 0.1
#define NP_DRAW_SCALE_MAX 15.0
#define NP_SMOOTHING_MIN 10
#define NP_SMOOTHING_MAX 120
#define NP_E_DEVICE_NOT_SUPPORTED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA000)
#define NP_E_DEVICE_DISCONNECTED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA001)
#define NP_E_NEVER MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA002)
#define NP_E_WAIT MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA003)
#define NP_E_NOT_STARTED MAKE_HRESULT(SEVERITY_ERROR, FACILITY_ITF, 0xA004)
typedef /* [public] */
enum __MIDL___MIDL_itf_optitrack_0000_0001
{ NP_OPTION_STATUS_GREEN_ON_TRACKING = 0,
NP_OPTION_TRACKED_OBJECT_COLOR = NP_OPTION_STATUS_GREEN_ON_TRACKING + 1,
NP_OPTION_UNTRACKED_OBJECTS_COLOR = NP_OPTION_TRACKED_OBJECT_COLOR + 1,
NP_OPTION_OBJECT_COLOR_OPTION = NP_OPTION_UNTRACKED_OBJECTS_COLOR + 1,
NP_OPTION_DRAW_SCALE = NP_OPTION_OBJECT_COLOR_OPTION + 1,
NP_OPTION_THRESHOLD = NP_OPTION_DRAW_SCALE + 1,
NP_OPTION_OBJECT_MASS_WEIGHT = NP_OPTION_THRESHOLD + 1,
NP_OPTION_OBJECT_RATIO_WEIGHT = NP_OPTION_OBJECT_MASS_WEIGHT + 1,
NP_OPTION_PROXIMITY_WEIGHT = NP_OPTION_OBJECT_RATIO_WEIGHT + 1,
NP_OPTION_STATIC_COUNT_WEIGHT = NP_OPTION_PROXIMITY_WEIGHT + 1,
NP_OPTION_SCREEN_CENTER_WEIGHT = NP_OPTION_STATIC_COUNT_WEIGHT + 1,
NP_OPTION_LAST_OBJECT_TRACKED_WEIGHT = NP_OPTION_SCREEN_CENTER_WEIGHT + 1,
NP_OPTION_OBJECT_MASS_MIN = NP_OPTION_LAST_OBJECT_TRACKED_WEIGHT + 1,
NP_OPTION_OBJECT_MASS_MAX = NP_OPTION_OBJECT_MASS_MIN + 1,
NP_OPTION_OBJECT_MASS_IDEAL = NP_OPTION_OBJECT_MASS_MAX + 1,
NP_OPTION_OBJECT_MASS_OUT_OF_RANGE = NP_OPTION_OBJECT_MASS_IDEAL + 1,
NP_OPTION_OBJECT_RATIO_MIN = NP_OPTION_OBJECT_MASS_OUT_OF_RANGE + 1,
NP_OPTION_OBJECT_RATIO_MAX = NP_OPTION_OBJECT_RATIO_MIN + 1,
NP_OPTION_OBJECT_RATIO_IDEAL = NP_OPTION_OBJECT_RATIO_MAX + 1,
NP_OPTION_OBJECT_RATIO_OUT_OF_RANGE = NP_OPTION_OBJECT_RATIO_IDEAL + 1,
NP_OPTION_PROXIMITY_MIN = NP_OPTION_OBJECT_RATIO_OUT_OF_RANGE + 1,
NP_OPTION_PROXIMITY_MAX = NP_OPTION_PROXIMITY_MIN + 1,
NP_OPTION_PROXIMITY_IDEAL = NP_OPTION_PROXIMITY_MAX + 1,
NP_OPTION_PROXIMITY_OUT_OF_RANGE = NP_OPTION_PROXIMITY_IDEAL + 1,
NP_OPTION_STATIC_COUNT_MIN = NP_OPTION_PROXIMITY_OUT_OF_RANGE + 1,
NP_OPTION_STATIC_COUNT_MAX = NP_OPTION_STATIC_COUNT_MIN + 1,
NP_OPTION_STATIC_COUNT_IDEAL = NP_OPTION_STATIC_COUNT_MAX + 1,
NP_OPTION_STATIC_COUNT_OUT_OF_RANGE = NP_OPTION_STATIC_COUNT_IDEAL + 1,
NP_OPTION_SCREEN_CENTER_MIN = NP_OPTION_STATIC_COUNT_OUT_OF_RANGE + 1,
NP_OPTION_SCREEN_CENTER_MAX = NP_OPTION_SCREEN_CENTER_MIN + 1,
NP_OPTION_SCREEN_CENTER_IDEAL = NP_OPTION_SCREEN_CENTER_MAX + 1,
NP_OPTION_SCREEN_CENTER_OUT_OF_RANGE = NP_OPTION_SCREEN_CENTER_IDEAL + 1,
NP_OPTION_LAST_OBJECT_MIN = NP_OPTION_SCREEN_CENTER_OUT_OF_RANGE + 1,
NP_OPTION_LAST_OBJECT_MAX = NP_OPTION_LAST_OBJECT_MIN + 1,
NP_OPTION_LAST_OBJECT_IDEAL = NP_OPTION_LAST_OBJECT_MAX + 1,
NP_OPTION_LAST_OBJECT_OUT_OF_RANGE = NP_OPTION_LAST_OBJECT_IDEAL + 1,
NP_OPTION_STATUS_LED_ON_START = NP_OPTION_LAST_OBJECT_OUT_OF_RANGE + 1,
NP_OPTION_ILLUMINATION_LEDS_ON_START = NP_OPTION_STATUS_LED_ON_START + 1,
NP_OPTION_CAMERA_ROTATION = NP_OPTION_ILLUMINATION_LEDS_ON_START + 1,
NP_OPTION_MIRROR_X = NP_OPTION_CAMERA_ROTATION + 1,
NP_OPTION_MIRROR_Y = NP_OPTION_MIRROR_X + 1,
NP_OPTION_SEND_EMPTY_FRAMES = NP_OPTION_MIRROR_Y + 1,
NP_OPTION_CAMERA_ID = NP_OPTION_SEND_EMPTY_FRAMES + 1,
NP_OPTION_CAMERA_ID_DEFAULT = NP_OPTION_CAMERA_ID + 1,
NP_OPTION_FRAME_RATE = NP_OPTION_CAMERA_ID_DEFAULT + 1,
NP_OPTION_FRAME_RATE_DEFAULT = NP_OPTION_FRAME_RATE + 1,
NP_OPTION_EXPOSURE = NP_OPTION_FRAME_RATE_DEFAULT + 1,
NP_OPTION_EXPOSURE_DEFAULT = NP_OPTION_EXPOSURE + 1,
NP_OPTION_VIDEO_TYPE = NP_OPTION_EXPOSURE_DEFAULT + 1,
NP_OPTION_VIDEO_TYPE_DEFAULT = NP_OPTION_VIDEO_TYPE + 1,
NP_OPTION_INTENSITY = NP_OPTION_VIDEO_TYPE_DEFAULT + 1,
NP_OPTION_INTENSITY_DEFAULT = NP_OPTION_INTENSITY + 1,
NP_OPTION_FRAME_DECIMATION = NP_OPTION_INTENSITY_DEFAULT + 1,
NP_OPTION_FRAME_DECIMATION_DEFAULT = NP_OPTION_FRAME_DECIMATION + 1,
NP_OPTION_MINIMUM_SEGMENT_LENGTH = NP_OPTION_FRAME_DECIMATION_DEFAULT + 1,
NP_OPTION_MINIMUM_SEGMENT_LENGTH_DEFAULT = NP_OPTION_MINIMUM_SEGMENT_LENGTH + 1,
NP_OPTION_MAXIMUM_SEGMENT_LENGTH = NP_OPTION_MINIMUM_SEGMENT_LENGTH_DEFAULT + 1,
NP_OPTION_MAXIMUM_SEGMENT_LENGTH_DEFAULT = NP_OPTION_MAXIMUM_SEGMENT_LENGTH + 1,
NP_OPTION_WINDOW_EXTENTS_X = NP_OPTION_MAXIMUM_SEGMENT_LENGTH_DEFAULT + 1,
NP_OPTION_WINDOW_EXTENTS_X_DEFAULT = NP_OPTION_WINDOW_EXTENTS_X + 1,
NP_OPTION_WINDOW_EXTENTS_X_END = NP_OPTION_WINDOW_EXTENTS_X_DEFAULT + 1,
NP_OPTION_WINDOW_EXTENTS_X_END_DEFAULT = NP_OPTION_WINDOW_EXTENTS_X_END + 1,
NP_OPTION_WINDOW_EXTENTS_Y = NP_OPTION_WINDOW_EXTENTS_X_END_DEFAULT + 1,
NP_OPTION_WINDOW_EXTENTS_Y_DEFAULT = NP_OPTION_WINDOW_EXTENTS_Y + 1,
NP_OPTION_WINDOW_EXTENTS_Y_END = NP_OPTION_WINDOW_EXTENTS_Y_DEFAULT + 1,
NP_OPTION_WINDOW_EXTENTS_Y_END_DEFAULT = NP_OPTION_WINDOW_EXTENTS_Y_END + 1,
NP_OPTION_RESET_FRAME_COUNT = NP_OPTION_WINDOW_EXTENTS_Y_END_DEFAULT + 1,
NP_OPTION_USER_HWND = NP_OPTION_RESET_FRAME_COUNT + 1,
NP_OPTION_MULTICAM = NP_OPTION_USER_HWND + 1,
NP_OPTION_MULTICAM_MASTER = NP_OPTION_MULTICAM + 1,
NP_OPTION_MULTICAM_GROUP_NOTIFY = NP_OPTION_MULTICAM_MASTER + 1,
NP_OPTION_NUMERIC_DISPLAY_ON = NP_OPTION_MULTICAM_GROUP_NOTIFY + 1,
NP_OPTION_NUMERIC_DISPLAY_OFF = NP_OPTION_NUMERIC_DISPLAY_ON + 1,
NP_OPTION_SEND_FRAME_MASK = NP_OPTION_NUMERIC_DISPLAY_OFF + 1,
NP_OPTION_TEXT_OVERLAY_OPTION = NP_OPTION_SEND_FRAME_MASK + 1,
NP_OPTION_USER_DEF1 = NP_OPTION_TEXT_OVERLAY_OPTION + 1,
NP_OPTION_SCORING_ENABLED = NP_OPTION_USER_DEF1 + 1,
NP_OPTION_GRAYSCALE_DECIMATION = NP_OPTION_SCORING_ENABLED + 1,
NP_OPTION_OBJECT_CAP = NP_OPTION_GRAYSCALE_DECIMATION + 1,
NP_OPTION_HARDWARE_REVISION = NP_OPTION_OBJECT_CAP + 1,
NP_OPTION_SENSORCLOCK_FORCEENABLE = NP_OPTION_HARDWARE_REVISION + 1,
NP_OPTION_SHUTTER_DELAY = NP_OPTION_SENSORCLOCK_FORCEENABLE + 1,
NP_OPTION_SYNC_MODE = NP_OPTION_SHUTTER_DELAY + 1,
NP_OPTION_TRIGGER_SNAPSHOT = NP_OPTION_SYNC_MODE + 1,
NP_OPTION_RESET_SNAPTSHOT_ID = NP_OPTION_TRIGGER_SNAPSHOT + 1
} NP_OPTION;
typedef /* [public] */
enum __MIDL___MIDL_itf_optitrack_0000_0002
{ NP_SYNC_NORMAL = 0,
NP_SYNC_FORCE_SLAVE = 0x1,
NP_SYNC_SNAPSHOT_PSEUDO_MASTER = 0x2,
NP_SYNC_FORCE_SLAVE_LAST = 0x3
} NP_SYNC_MODE_LIST;
typedef /* [public] */
enum __MIDL___MIDL_itf_optitrack_0000_0003
{ NP_FRAME_SENDEMPTY = 0x1,
NP_FRAME_SENDINVALID = 0x2,
NP_FRAME_GRAYSCALEOBJECTS = 0x4,
NP_FRAME_GRAYSCALEPRECISION = 0x8
} NP_FRAME_SEND_MASK;
typedef /* [public] */
enum __MIDL___MIDL_itf_optitrack_0000_0004
{ NP_HW_MODEL_OLDTRACKIR = 0x100800a8,
NP_HW_MODEL_SMARTNAV = NP_HW_MODEL_OLDTRACKIR + 1,
NP_HW_MODEL_TRACKIR = NP_HW_MODEL_SMARTNAV + 1,
NP_HW_MODEL_OPTITRACK = NP_HW_MODEL_TRACKIR + 1,
NP_HW_MODEL_UNKNOWN = NP_HW_MODEL_OPTITRACK + 1
} NP_HW_MODEL;
typedef /* [public] */
enum __MIDL___MIDL_itf_optitrack_0000_0005
{ NP_HW_REVISION_OLDTRACKIR_LEGACY = 0x200800b8,
NP_HW_REVISION_OLDTRACKIR_BASIC = NP_HW_REVISION_OLDTRACKIR_LEGACY + 1,
NP_HW_REVISION_OLDTRACKIR_EG = NP_HW_REVISION_OLDTRACKIR_BASIC + 1,
NP_HW_REVISION_OLDTRACKIR_AT = NP_HW_REVISION_OLDTRACKIR_EG + 1,
NP_HW_REVISION_OLDTRACKIR_GX = NP_HW_REVISION_OLDTRACKIR_AT + 1,
NP_HW_REVISION_OLDTRACKIR_MAC = NP_HW_REVISION_OLDTRACKIR_GX + 1,
NP_HW_REVISION_SMARTNAV_BASIC = NP_HW_REVISION_OLDTRACKIR_MAC + 1,
NP_HW_REVISION_SMARTNAV_EG = NP_HW_REVISION_SMARTNAV_BASIC + 1,
NP_HW_REVISION_SMARTNAV_AT = NP_HW_REVISION_SMARTNAV_EG + 1,
NP_HW_REVISION_SMARTNAV_MAC_BASIC = NP_HW_REVISION_SMARTNAV_AT + 1,
NP_HW_REVISION_SMARTNAV_MAC_AT = NP_HW_REVISION_SMARTNAV_MAC_BASIC + 1,
NP_HW_REVISION_TRACKIR_BASIC = NP_HW_REVISION_SMARTNAV_MAC_AT + 1,
NP_HW_REVISION_TRACKIR_PRO = NP_HW_REVISION_TRACKIR_BASIC + 1,
NP_HW_REVISION_OPTITRACK_BASIC = NP_HW_REVISION_TRACKIR_PRO + 1,
NP_HW_REVISION_OPTITRACK_FLEX = NP_HW_REVISION_OPTITRACK_BASIC + 1,
NP_HW_REVISION_OPTITRACK_SLIM = NP_HW_REVISION_OPTITRACK_FLEX + 1,
NP_HW_REVISION_UNKNOWN = NP_HW_REVISION_OPTITRACK_SLIM + 1
} NP_HW_REVISION;
typedef /* [public] */
enum __MIDL___MIDL_itf_optitrack_0000_0006
{ NP_OBJECT_COLOR_OPTION_ALL_SAME = 0,
NP_OBJECT_COLOR_OPTION_TRACKED_ONLY = NP_OBJECT_COLOR_OPTION_ALL_SAME + 1,
NP_OBJECT_COLOR_OPTION_SHADE_BY_RANK = NP_OBJECT_COLOR_OPTION_TRACKED_ONLY + 1,
NP_OBJECT_COLOR_OPTION_VECTOR = NP_OBJECT_COLOR_OPTION_SHADE_BY_RANK + 1,
NP_OBJECT_COLOR_OPTION_VECTOR_SHADE_BY_RANK = NP_OBJECT_COLOR_OPTION_VECTOR + 1
} NP_OBJECT_COLOR_OPTION;
typedef /* [public] */
enum __MIDL___MIDL_itf_optitrack_0000_0007
{ NP_TEXT_OVERLAY_HEADER = 0x1,
NP_TEXT_OVERLAY_OBJECT = 0x2,
NP_TEXT_OVERLAY_OBJECT_HIGHLIGHT = 0x4,
NP_TEXT_OVERLAY_PRECISION_GRAYSCALE = 0x8
} NP_TEXT_OVERLAY_OPTION;
typedef /* [public] */
enum __MIDL___MIDL_itf_optitrack_0000_0008
{ NP_SWITCH_STATE_BOTH_DOWN = 0,
NP_SWITCH_STATE_ONE_DOWN = 0x4,
NP_SWITCH_STATE_TWO_DOWN = 0x8,
NP_SWITCH_STATE_BOTH_UP = 0xc
} NP_SWITCH_STATE;
typedef /* [public] */
enum __MIDL___MIDL_itf_optitrack_0000_0009
{ NP_LED_ONE = 0,
NP_LED_TWO = NP_LED_ONE + 1,
NP_LED_THREE = NP_LED_TWO + 1,
NP_LED_FOUR = NP_LED_THREE + 1
} NP_LED;
typedef /* [public] */
enum __MIDL___MIDL_itf_optitrack_0000_0010
{ NP_CAMERA_ROTATION_0 = 0,
NP_CAMERA_ROTATION_90 = NP_CAMERA_ROTATION_0 + 1,
NP_CAMERA_ROTATION_180 = NP_CAMERA_ROTATION_90 + 1,
NP_CAMERA_ROTATION_270 = NP_CAMERA_ROTATION_180 + 1
} NP_CAMERA_ROTATION;
extern RPC_IF_HANDLE __MIDL_itf_optitrack_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_optitrack_0000_v0_0_s_ifspec;
#ifndef __INPCameraCollection_INTERFACE_DEFINED__
#define __INPCameraCollection_INTERFACE_DEFINED__
/* interface INPCameraCollection */
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_INPCameraCollection;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("28E501BB-FDD9-46CF-A112-741587110F0E")
INPCameraCollection : public IDispatch
{
public:
virtual /* [restricted][helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum(
/* [retval][out] */ LPUNKNOWN *ppunk) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Count(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Item(
/* [in] */ LONG a_vlIndex,
/* [retval][out] */ INPCamera **ppCamera) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Enum( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Synchronize( void) = 0;
};
#else /* C style interface */
typedef struct INPCameraCollectionVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
INPCameraCollection * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
INPCameraCollection * This);
ULONG ( STDMETHODCALLTYPE *Release )(
INPCameraCollection * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
INPCameraCollection * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
INPCameraCollection * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
INPCameraCollection * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
INPCameraCollection * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [restricted][helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )(
INPCameraCollection * This,
/* [retval][out] */ LPUNKNOWN *ppunk);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )(
INPCameraCollection * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Item )(
INPCameraCollection * This,
/* [in] */ LONG a_vlIndex,
/* [retval][out] */ INPCamera **ppCamera);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Enum )(
INPCameraCollection * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Synchronize )(
INPCameraCollection * This);
END_INTERFACE
} INPCameraCollectionVtbl;
interface INPCameraCollection
{
CONST_VTBL struct INPCameraCollectionVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define INPCameraCollection_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define INPCameraCollection_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define INPCameraCollection_Release(This) \
(This)->lpVtbl -> Release(This)
#define INPCameraCollection_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define INPCameraCollection_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define INPCameraCollection_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define INPCameraCollection_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define INPCameraCollection_get__NewEnum(This,ppunk) \
(This)->lpVtbl -> get__NewEnum(This,ppunk)
#define INPCameraCollection_get_Count(This,pVal) \
(This)->lpVtbl -> get_Count(This,pVal)
#define INPCameraCollection_Item(This,a_vlIndex,ppCamera) \
(This)->lpVtbl -> Item(This,a_vlIndex,ppCamera)
#define INPCameraCollection_Enum(This) \
(This)->lpVtbl -> Enum(This)
#define INPCameraCollection_Synchronize(This) \
(This)->lpVtbl -> Synchronize(This)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [restricted][helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraCollection_get__NewEnum_Proxy(
INPCameraCollection * This,
/* [retval][out] */ LPUNKNOWN *ppunk);
void __RPC_STUB INPCameraCollection_get__NewEnum_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraCollection_get_Count_Proxy(
INPCameraCollection * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCameraCollection_get_Count_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCameraCollection_Item_Proxy(
INPCameraCollection * This,
/* [in] */ LONG a_vlIndex,
/* [retval][out] */ INPCamera **ppCamera);
void __RPC_STUB INPCameraCollection_Item_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCameraCollection_Enum_Proxy(
INPCameraCollection * This);
void __RPC_STUB INPCameraCollection_Enum_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCameraCollection_Synchronize_Proxy(
INPCameraCollection * This);
void __RPC_STUB INPCameraCollection_Synchronize_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __INPCameraCollection_INTERFACE_DEFINED__ */
#ifndef __INPCamera_INTERFACE_DEFINED__
#define __INPCamera_INTERFACE_DEFINED__
/* interface INPCamera */
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_INPCamera;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("ADE1E272-C86A-460D-B7B9-3051F310E4D0")
INPCamera : public IDispatch
{
public:
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_SerialNumber(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Model(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Revision(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Width(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Height(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_FrameRate(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_BlockingMaskWidth(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_BlockingMaskHeight(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Start( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Stop( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Open( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Close( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetLED(
/* [in] */ LONG lLED,
/* [in] */ VARIANT_BOOL fOn) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFrame(
/* [in] */ LONG lTimeout,
/* [retval][out] */ INPCameraFrame **ppFrame) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE DrawFrame(
/* [in] */ INPCameraFrame *pFrame,
/* [in] */ LONG hwnd) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ResetTrackedObject( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetOption(
/* [in] */ LONG lOption,
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetOption(
/* [in] */ LONG lOption,
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFrameById(
/* [in] */ LONG Id,
/* [retval][out] */ INPCameraFrame **ppFrame) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetFrameImage(
/* [in] */ INPCameraFrame *pFrame,
/* [in] */ INT PixelWidth,
/* [in] */ INT PixelHeight,
/* [in] */ INT ByteSpan,
/* [in] */ INT BitsPerPixel,
/* [in] */ BYTE *Buffer) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetVideo(
/* [in] */ VARIANT_BOOL fOn) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE ClearBlockingMask( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE EnableBlockingMask( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE DisableBlockingMask( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE AddBlockingRectangle(
/* [in] */ LONG X1,
/* [in] */ LONG Y1,
/* [in] */ LONG X2,
/* [in] */ LONG Y2) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE RemoveBlockingRectangle(
/* [in] */ LONG X1,
/* [in] */ LONG Y1,
/* [in] */ LONG X2,
/* [in] */ LONG Y2) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetBlockingMask(
/* [in] */ BYTE *Buffer,
/* [in] */ LONG BufferSize) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE SetBlockingMask(
/* [in] */ BYTE *Buffer,
/* [in] */ LONG BufferSize) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE UpdateBlockingMask( void) = 0;
};
#else /* C style interface */
typedef struct INPCameraVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
INPCamera * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
INPCamera * This);
ULONG ( STDMETHODCALLTYPE *Release )(
INPCamera * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
INPCamera * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
INPCamera * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
INPCamera * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
INPCamera * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SerialNumber )(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Model )(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Revision )(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Width )(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Height )(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_FrameRate )(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockingMaskWidth )(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_BlockingMaskHeight )(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Start )(
INPCamera * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Stop )(
INPCamera * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Open )(
INPCamera * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Close )(
INPCamera * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetLED )(
INPCamera * This,
/* [in] */ LONG lLED,
/* [in] */ VARIANT_BOOL fOn);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetFrame )(
INPCamera * This,
/* [in] */ LONG lTimeout,
/* [retval][out] */ INPCameraFrame **ppFrame);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *DrawFrame )(
INPCamera * This,
/* [in] */ INPCameraFrame *pFrame,
/* [in] */ LONG hwnd);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *ResetTrackedObject )(
INPCamera * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetOption )(
INPCamera * This,
/* [in] */ LONG lOption,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetOption )(
INPCamera * This,
/* [in] */ LONG lOption,
/* [in] */ VARIANT Val);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetFrameById )(
INPCamera * This,
/* [in] */ LONG Id,
/* [retval][out] */ INPCameraFrame **ppFrame);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetFrameImage )(
INPCamera * This,
/* [in] */ INPCameraFrame *pFrame,
/* [in] */ INT PixelWidth,
/* [in] */ INT PixelHeight,
/* [in] */ INT ByteSpan,
/* [in] */ INT BitsPerPixel,
/* [in] */ BYTE *Buffer);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetVideo )(
INPCamera * This,
/* [in] */ VARIANT_BOOL fOn);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *ClearBlockingMask )(
INPCamera * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *EnableBlockingMask )(
INPCamera * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *DisableBlockingMask )(
INPCamera * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *AddBlockingRectangle )(
INPCamera * This,
/* [in] */ LONG X1,
/* [in] */ LONG Y1,
/* [in] */ LONG X2,
/* [in] */ LONG Y2);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *RemoveBlockingRectangle )(
INPCamera * This,
/* [in] */ LONG X1,
/* [in] */ LONG Y1,
/* [in] */ LONG X2,
/* [in] */ LONG Y2);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetBlockingMask )(
INPCamera * This,
/* [in] */ BYTE *Buffer,
/* [in] */ LONG BufferSize);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *SetBlockingMask )(
INPCamera * This,
/* [in] */ BYTE *Buffer,
/* [in] */ LONG BufferSize);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *UpdateBlockingMask )(
INPCamera * This);
END_INTERFACE
} INPCameraVtbl;
interface INPCamera
{
CONST_VTBL struct INPCameraVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define INPCamera_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define INPCamera_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define INPCamera_Release(This) \
(This)->lpVtbl -> Release(This)
#define INPCamera_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define INPCamera_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define INPCamera_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define INPCamera_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define INPCamera_get_SerialNumber(This,pVal) \
(This)->lpVtbl -> get_SerialNumber(This,pVal)
#define INPCamera_get_Model(This,pVal) \
(This)->lpVtbl -> get_Model(This,pVal)
#define INPCamera_get_Revision(This,pVal) \
(This)->lpVtbl -> get_Revision(This,pVal)
#define INPCamera_get_Width(This,pVal) \
(This)->lpVtbl -> get_Width(This,pVal)
#define INPCamera_get_Height(This,pVal) \
(This)->lpVtbl -> get_Height(This,pVal)
#define INPCamera_get_FrameRate(This,pVal) \
(This)->lpVtbl -> get_FrameRate(This,pVal)
#define INPCamera_get_BlockingMaskWidth(This,pVal) \
(This)->lpVtbl -> get_BlockingMaskWidth(This,pVal)
#define INPCamera_get_BlockingMaskHeight(This,pVal) \
(This)->lpVtbl -> get_BlockingMaskHeight(This,pVal)
#define INPCamera_Start(This) \
(This)->lpVtbl -> Start(This)
#define INPCamera_Stop(This) \
(This)->lpVtbl -> Stop(This)
#define INPCamera_Open(This) \
(This)->lpVtbl -> Open(This)
#define INPCamera_Close(This) \
(This)->lpVtbl -> Close(This)
#define INPCamera_SetLED(This,lLED,fOn) \
(This)->lpVtbl -> SetLED(This,lLED,fOn)
#define INPCamera_GetFrame(This,lTimeout,ppFrame) \
(This)->lpVtbl -> GetFrame(This,lTimeout,ppFrame)
#define INPCamera_DrawFrame(This,pFrame,hwnd) \
(This)->lpVtbl -> DrawFrame(This,pFrame,hwnd)
#define INPCamera_ResetTrackedObject(This) \
(This)->lpVtbl -> ResetTrackedObject(This)
#define INPCamera_GetOption(This,lOption,pVal) \
(This)->lpVtbl -> GetOption(This,lOption,pVal)
#define INPCamera_SetOption(This,lOption,Val) \
(This)->lpVtbl -> SetOption(This,lOption,Val)
#define INPCamera_GetFrameById(This,Id,ppFrame) \
(This)->lpVtbl -> GetFrameById(This,Id,ppFrame)
#define INPCamera_GetFrameImage(This,pFrame,PixelWidth,PixelHeight,ByteSpan,BitsPerPixel,Buffer) \
(This)->lpVtbl -> GetFrameImage(This,pFrame,PixelWidth,PixelHeight,ByteSpan,BitsPerPixel,Buffer)
#define INPCamera_SetVideo(This,fOn) \
(This)->lpVtbl -> SetVideo(This,fOn)
#define INPCamera_ClearBlockingMask(This) \
(This)->lpVtbl -> ClearBlockingMask(This)
#define INPCamera_EnableBlockingMask(This) \
(This)->lpVtbl -> EnableBlockingMask(This)
#define INPCamera_DisableBlockingMask(This) \
(This)->lpVtbl -> DisableBlockingMask(This)
#define INPCamera_AddBlockingRectangle(This,X1,Y1,X2,Y2) \
(This)->lpVtbl -> AddBlockingRectangle(This,X1,Y1,X2,Y2)
#define INPCamera_RemoveBlockingRectangle(This,X1,Y1,X2,Y2) \
(This)->lpVtbl -> RemoveBlockingRectangle(This,X1,Y1,X2,Y2)
#define INPCamera_GetBlockingMask(This,Buffer,BufferSize) \
(This)->lpVtbl -> GetBlockingMask(This,Buffer,BufferSize)
#define INPCamera_SetBlockingMask(This,Buffer,BufferSize) \
(This)->lpVtbl -> SetBlockingMask(This,Buffer,BufferSize)
#define INPCamera_UpdateBlockingMask(This) \
(This)->lpVtbl -> UpdateBlockingMask(This)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCamera_get_SerialNumber_Proxy(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCamera_get_SerialNumber_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCamera_get_Model_Proxy(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCamera_get_Model_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCamera_get_Revision_Proxy(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCamera_get_Revision_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCamera_get_Width_Proxy(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCamera_get_Width_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCamera_get_Height_Proxy(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCamera_get_Height_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCamera_get_FrameRate_Proxy(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCamera_get_FrameRate_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCamera_get_BlockingMaskWidth_Proxy(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCamera_get_BlockingMaskWidth_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCamera_get_BlockingMaskHeight_Proxy(
INPCamera * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCamera_get_BlockingMaskHeight_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_Start_Proxy(
INPCamera * This);
void __RPC_STUB INPCamera_Start_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_Stop_Proxy(
INPCamera * This);
void __RPC_STUB INPCamera_Stop_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_Open_Proxy(
INPCamera * This);
void __RPC_STUB INPCamera_Open_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_Close_Proxy(
INPCamera * This);
void __RPC_STUB INPCamera_Close_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_SetLED_Proxy(
INPCamera * This,
/* [in] */ LONG lLED,
/* [in] */ VARIANT_BOOL fOn);
void __RPC_STUB INPCamera_SetLED_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_GetFrame_Proxy(
INPCamera * This,
/* [in] */ LONG lTimeout,
/* [retval][out] */ INPCameraFrame **ppFrame);
void __RPC_STUB INPCamera_GetFrame_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_DrawFrame_Proxy(
INPCamera * This,
/* [in] */ INPCameraFrame *pFrame,
/* [in] */ LONG hwnd);
void __RPC_STUB INPCamera_DrawFrame_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_ResetTrackedObject_Proxy(
INPCamera * This);
void __RPC_STUB INPCamera_ResetTrackedObject_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_GetOption_Proxy(
INPCamera * This,
/* [in] */ LONG lOption,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPCamera_GetOption_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_SetOption_Proxy(
INPCamera * This,
/* [in] */ LONG lOption,
/* [in] */ VARIANT Val);
void __RPC_STUB INPCamera_SetOption_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_GetFrameById_Proxy(
INPCamera * This,
/* [in] */ LONG Id,
/* [retval][out] */ INPCameraFrame **ppFrame);
void __RPC_STUB INPCamera_GetFrameById_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_GetFrameImage_Proxy(
INPCamera * This,
/* [in] */ INPCameraFrame *pFrame,
/* [in] */ INT PixelWidth,
/* [in] */ INT PixelHeight,
/* [in] */ INT ByteSpan,
/* [in] */ INT BitsPerPixel,
/* [in] */ BYTE *Buffer);
void __RPC_STUB INPCamera_GetFrameImage_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_SetVideo_Proxy(
INPCamera * This,
/* [in] */ VARIANT_BOOL fOn);
void __RPC_STUB INPCamera_SetVideo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_ClearBlockingMask_Proxy(
INPCamera * This);
void __RPC_STUB INPCamera_ClearBlockingMask_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_EnableBlockingMask_Proxy(
INPCamera * This);
void __RPC_STUB INPCamera_EnableBlockingMask_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_DisableBlockingMask_Proxy(
INPCamera * This);
void __RPC_STUB INPCamera_DisableBlockingMask_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_AddBlockingRectangle_Proxy(
INPCamera * This,
/* [in] */ LONG X1,
/* [in] */ LONG Y1,
/* [in] */ LONG X2,
/* [in] */ LONG Y2);
void __RPC_STUB INPCamera_AddBlockingRectangle_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_RemoveBlockingRectangle_Proxy(
INPCamera * This,
/* [in] */ LONG X1,
/* [in] */ LONG Y1,
/* [in] */ LONG X2,
/* [in] */ LONG Y2);
void __RPC_STUB INPCamera_RemoveBlockingRectangle_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_GetBlockingMask_Proxy(
INPCamera * This,
/* [in] */ BYTE *Buffer,
/* [in] */ LONG BufferSize);
void __RPC_STUB INPCamera_GetBlockingMask_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_SetBlockingMask_Proxy(
INPCamera * This,
/* [in] */ BYTE *Buffer,
/* [in] */ LONG BufferSize);
void __RPC_STUB INPCamera_SetBlockingMask_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCamera_UpdateBlockingMask_Proxy(
INPCamera * This);
void __RPC_STUB INPCamera_UpdateBlockingMask_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __INPCamera_INTERFACE_DEFINED__ */
#ifndef __INPCameraFrame_INTERFACE_DEFINED__
#define __INPCameraFrame_INTERFACE_DEFINED__
/* interface INPCameraFrame */
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_INPCameraFrame;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("73CF9A64-837A-4F05-9BF6-8A253CE16E46")
INPCameraFrame : public IDispatch
{
public:
virtual /* [restricted][helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get__NewEnum(
/* [retval][out] */ LPUNKNOWN *ppunk) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Count(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Item(
/* [in] */ LONG a_vlIndex,
/* [retval][out] */ INPObject **ppObject) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Id(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_SwitchState(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_IsEmpty(
/* [retval][out] */ VARIANT_BOOL *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_IsCorrupt(
/* [retval][out] */ VARIANT_BOOL *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_IsGreyscale(
/* [retval][out] */ VARIANT_BOOL *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_TimeStamp(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_TimeStampFrequency(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetObjectData(
/* [in] */ BYTE *Buffer,
/* [in] */ INT BufferSize,
/* [retval][out] */ LONG *pObjectCount) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Free( void) = 0;
};
#else /* C style interface */
typedef struct INPCameraFrameVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
INPCameraFrame * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
INPCameraFrame * This);
ULONG ( STDMETHODCALLTYPE *Release )(
INPCameraFrame * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
INPCameraFrame * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
INPCameraFrame * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
INPCameraFrame * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
INPCameraFrame * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [restricted][helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get__NewEnum )(
INPCameraFrame * This,
/* [retval][out] */ LPUNKNOWN *ppunk);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Count )(
INPCameraFrame * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Item )(
INPCameraFrame * This,
/* [in] */ LONG a_vlIndex,
/* [retval][out] */ INPObject **ppObject);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Id )(
INPCameraFrame * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_SwitchState )(
INPCameraFrame * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsEmpty )(
INPCameraFrame * This,
/* [retval][out] */ VARIANT_BOOL *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsCorrupt )(
INPCameraFrame * This,
/* [retval][out] */ VARIANT_BOOL *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_IsGreyscale )(
INPCameraFrame * This,
/* [retval][out] */ VARIANT_BOOL *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TimeStamp )(
INPCameraFrame * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_TimeStampFrequency )(
INPCameraFrame * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetObjectData )(
INPCameraFrame * This,
/* [in] */ BYTE *Buffer,
/* [in] */ INT BufferSize,
/* [retval][out] */ LONG *pObjectCount);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Free )(
INPCameraFrame * This);
END_INTERFACE
} INPCameraFrameVtbl;
interface INPCameraFrame
{
CONST_VTBL struct INPCameraFrameVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define INPCameraFrame_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define INPCameraFrame_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define INPCameraFrame_Release(This) \
(This)->lpVtbl -> Release(This)
#define INPCameraFrame_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define INPCameraFrame_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define INPCameraFrame_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define INPCameraFrame_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define INPCameraFrame_get__NewEnum(This,ppunk) \
(This)->lpVtbl -> get__NewEnum(This,ppunk)
#define INPCameraFrame_get_Count(This,pVal) \
(This)->lpVtbl -> get_Count(This,pVal)
#define INPCameraFrame_Item(This,a_vlIndex,ppObject) \
(This)->lpVtbl -> Item(This,a_vlIndex,ppObject)
#define INPCameraFrame_get_Id(This,pVal) \
(This)->lpVtbl -> get_Id(This,pVal)
#define INPCameraFrame_get_SwitchState(This,pVal) \
(This)->lpVtbl -> get_SwitchState(This,pVal)
#define INPCameraFrame_get_IsEmpty(This,pVal) \
(This)->lpVtbl -> get_IsEmpty(This,pVal)
#define INPCameraFrame_get_IsCorrupt(This,pVal) \
(This)->lpVtbl -> get_IsCorrupt(This,pVal)
#define INPCameraFrame_get_IsGreyscale(This,pVal) \
(This)->lpVtbl -> get_IsGreyscale(This,pVal)
#define INPCameraFrame_get_TimeStamp(This,pVal) \
(This)->lpVtbl -> get_TimeStamp(This,pVal)
#define INPCameraFrame_get_TimeStampFrequency(This,pVal) \
(This)->lpVtbl -> get_TimeStampFrequency(This,pVal)
#define INPCameraFrame_GetObjectData(This,Buffer,BufferSize,pObjectCount) \
(This)->lpVtbl -> GetObjectData(This,Buffer,BufferSize,pObjectCount)
#define INPCameraFrame_Free(This) \
(This)->lpVtbl -> Free(This)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [restricted][helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_get__NewEnum_Proxy(
INPCameraFrame * This,
/* [retval][out] */ LPUNKNOWN *ppunk);
void __RPC_STUB INPCameraFrame_get__NewEnum_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_get_Count_Proxy(
INPCameraFrame * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCameraFrame_get_Count_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_Item_Proxy(
INPCameraFrame * This,
/* [in] */ LONG a_vlIndex,
/* [retval][out] */ INPObject **ppObject);
void __RPC_STUB INPCameraFrame_Item_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_get_Id_Proxy(
INPCameraFrame * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCameraFrame_get_Id_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_get_SwitchState_Proxy(
INPCameraFrame * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPCameraFrame_get_SwitchState_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_get_IsEmpty_Proxy(
INPCameraFrame * This,
/* [retval][out] */ VARIANT_BOOL *pVal);
void __RPC_STUB INPCameraFrame_get_IsEmpty_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_get_IsCorrupt_Proxy(
INPCameraFrame * This,
/* [retval][out] */ VARIANT_BOOL *pVal);
void __RPC_STUB INPCameraFrame_get_IsCorrupt_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_get_IsGreyscale_Proxy(
INPCameraFrame * This,
/* [retval][out] */ VARIANT_BOOL *pVal);
void __RPC_STUB INPCameraFrame_get_IsGreyscale_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_get_TimeStamp_Proxy(
INPCameraFrame * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPCameraFrame_get_TimeStamp_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_get_TimeStampFrequency_Proxy(
INPCameraFrame * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPCameraFrame_get_TimeStampFrequency_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_GetObjectData_Proxy(
INPCameraFrame * This,
/* [in] */ BYTE *Buffer,
/* [in] */ INT BufferSize,
/* [retval][out] */ LONG *pObjectCount);
void __RPC_STUB INPCameraFrame_GetObjectData_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPCameraFrame_Free_Proxy(
INPCameraFrame * This);
void __RPC_STUB INPCameraFrame_Free_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __INPCameraFrame_INTERFACE_DEFINED__ */
#ifndef __INPObject_INTERFACE_DEFINED__
#define __INPObject_INTERFACE_DEFINED__
/* interface INPObject */
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_INPObject;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("6E439CE4-AB0D-44B8-BF1E-644C5CC489DC")
INPObject : public IDispatch
{
public:
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Area(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_X(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Y(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Score(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Rank(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Width(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Height(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Transform(
/* [in] */ INPCamera *pCamera) = 0;
};
#else /* C style interface */
typedef struct INPObjectVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
INPObject * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
INPObject * This);
ULONG ( STDMETHODCALLTYPE *Release )(
INPObject * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
INPObject * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
INPObject * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
INPObject * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
INPObject * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Area )(
INPObject * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_X )(
INPObject * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Y )(
INPObject * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Score )(
INPObject * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Rank )(
INPObject * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Width )(
INPObject * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Height )(
INPObject * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Transform )(
INPObject * This,
/* [in] */ INPCamera *pCamera);
END_INTERFACE
} INPObjectVtbl;
interface INPObject
{
CONST_VTBL struct INPObjectVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define INPObject_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define INPObject_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define INPObject_Release(This) \
(This)->lpVtbl -> Release(This)
#define INPObject_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define INPObject_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define INPObject_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define INPObject_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define INPObject_get_Area(This,pVal) \
(This)->lpVtbl -> get_Area(This,pVal)
#define INPObject_get_X(This,pVal) \
(This)->lpVtbl -> get_X(This,pVal)
#define INPObject_get_Y(This,pVal) \
(This)->lpVtbl -> get_Y(This,pVal)
#define INPObject_get_Score(This,pVal) \
(This)->lpVtbl -> get_Score(This,pVal)
#define INPObject_get_Rank(This,pVal) \
(This)->lpVtbl -> get_Rank(This,pVal)
#define INPObject_get_Width(This,pVal) \
(This)->lpVtbl -> get_Width(This,pVal)
#define INPObject_get_Height(This,pVal) \
(This)->lpVtbl -> get_Height(This,pVal)
#define INPObject_Transform(This,pCamera) \
(This)->lpVtbl -> Transform(This,pCamera)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPObject_get_Area_Proxy(
INPObject * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPObject_get_Area_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPObject_get_X_Proxy(
INPObject * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPObject_get_X_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPObject_get_Y_Proxy(
INPObject * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPObject_get_Y_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPObject_get_Score_Proxy(
INPObject * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPObject_get_Score_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPObject_get_Rank_Proxy(
INPObject * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPObject_get_Rank_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPObject_get_Width_Proxy(
INPObject * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPObject_get_Width_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPObject_get_Height_Proxy(
INPObject * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPObject_get_Height_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPObject_Transform_Proxy(
INPObject * This,
/* [in] */ INPCamera *pCamera);
void __RPC_STUB INPObject_Transform_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __INPObject_INTERFACE_DEFINED__ */
#ifndef __INPSmoothing_INTERFACE_DEFINED__
#define __INPSmoothing_INTERFACE_DEFINED__
/* interface INPSmoothing */
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_INPSmoothing;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("0EDD3505-855C-4D91-A9C1-DCBEC1B816FA")
INPSmoothing : public IDispatch
{
public:
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Amount(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_Amount(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_X(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Y(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Update(
/* [in] */ VARIANT ValX,
VARIANT ValY) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Reset( void) = 0;
};
#else /* C style interface */
typedef struct INPSmoothingVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
INPSmoothing * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
INPSmoothing * This);
ULONG ( STDMETHODCALLTYPE *Release )(
INPSmoothing * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
INPSmoothing * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
INPSmoothing * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
INPSmoothing * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
INPSmoothing * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Amount )(
INPSmoothing * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_Amount )(
INPSmoothing * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_X )(
INPSmoothing * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Y )(
INPSmoothing * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Update )(
INPSmoothing * This,
/* [in] */ VARIANT ValX,
VARIANT ValY);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Reset )(
INPSmoothing * This);
END_INTERFACE
} INPSmoothingVtbl;
interface INPSmoothing
{
CONST_VTBL struct INPSmoothingVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define INPSmoothing_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define INPSmoothing_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define INPSmoothing_Release(This) \
(This)->lpVtbl -> Release(This)
#define INPSmoothing_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define INPSmoothing_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define INPSmoothing_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define INPSmoothing_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define INPSmoothing_get_Amount(This,pVal) \
(This)->lpVtbl -> get_Amount(This,pVal)
#define INPSmoothing_put_Amount(This,Val) \
(This)->lpVtbl -> put_Amount(This,Val)
#define INPSmoothing_get_X(This,pVal) \
(This)->lpVtbl -> get_X(This,pVal)
#define INPSmoothing_get_Y(This,pVal) \
(This)->lpVtbl -> get_Y(This,pVal)
#define INPSmoothing_Update(This,ValX,ValY) \
(This)->lpVtbl -> Update(This,ValX,ValY)
#define INPSmoothing_Reset(This) \
(This)->lpVtbl -> Reset(This)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPSmoothing_get_Amount_Proxy(
INPSmoothing * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPSmoothing_get_Amount_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPSmoothing_put_Amount_Proxy(
INPSmoothing * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPSmoothing_put_Amount_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPSmoothing_get_X_Proxy(
INPSmoothing * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPSmoothing_get_X_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPSmoothing_get_Y_Proxy(
INPSmoothing * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPSmoothing_get_Y_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPSmoothing_Update_Proxy(
INPSmoothing * This,
/* [in] */ VARIANT ValX,
VARIANT ValY);
void __RPC_STUB INPSmoothing_Update_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPSmoothing_Reset_Proxy(
INPSmoothing * This);
void __RPC_STUB INPSmoothing_Reset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __INPSmoothing_INTERFACE_DEFINED__ */
#ifndef __INPVector_INTERFACE_DEFINED__
#define __INPVector_INTERFACE_DEFINED__
/* interface INPVector */
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_INPVector;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("9124C9A8-9296-4E89-973D-4F3C502E36CA")
INPVector : public IDispatch
{
public:
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Yaw(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Pitch(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Roll(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_X(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Y(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Z(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Update(
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Reset( void) = 0;
};
#else /* C style interface */
typedef struct INPVectorVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
INPVector * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
INPVector * This);
ULONG ( STDMETHODCALLTYPE *Release )(
INPVector * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
INPVector * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
INPVector * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
INPVector * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
INPVector * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Yaw )(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Pitch )(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Roll )(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_X )(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Y )(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Z )(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Update )(
INPVector * This,
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Reset )(
INPVector * This);
END_INTERFACE
} INPVectorVtbl;
interface INPVector
{
CONST_VTBL struct INPVectorVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define INPVector_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define INPVector_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define INPVector_Release(This) \
(This)->lpVtbl -> Release(This)
#define INPVector_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define INPVector_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define INPVector_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define INPVector_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define INPVector_get_Yaw(This,pVal) \
(This)->lpVtbl -> get_Yaw(This,pVal)
#define INPVector_get_Pitch(This,pVal) \
(This)->lpVtbl -> get_Pitch(This,pVal)
#define INPVector_get_Roll(This,pVal) \
(This)->lpVtbl -> get_Roll(This,pVal)
#define INPVector_get_X(This,pVal) \
(This)->lpVtbl -> get_X(This,pVal)
#define INPVector_get_Y(This,pVal) \
(This)->lpVtbl -> get_Y(This,pVal)
#define INPVector_get_Z(This,pVal) \
(This)->lpVtbl -> get_Z(This,pVal)
#define INPVector_Update(This,pCamera,pFrame) \
(This)->lpVtbl -> Update(This,pCamera,pFrame)
#define INPVector_Reset(This) \
(This)->lpVtbl -> Reset(This)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector_get_Yaw_Proxy(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector_get_Yaw_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector_get_Pitch_Proxy(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector_get_Pitch_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector_get_Roll_Proxy(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector_get_Roll_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector_get_X_Proxy(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector_get_X_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector_get_Y_Proxy(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector_get_Y_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector_get_Z_Proxy(
INPVector * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector_get_Z_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPVector_Update_Proxy(
INPVector * This,
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame);
void __RPC_STUB INPVector_Update_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPVector_Reset_Proxy(
INPVector * This);
void __RPC_STUB INPVector_Reset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __INPVector_INTERFACE_DEFINED__ */
#ifndef __INPPoint_INTERFACE_DEFINED__
#define __INPPoint_INTERFACE_DEFINED__
/* interface INPPoint */
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_INPPoint;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("9124C9F0-9296-4E89-973D-4F3C502E36CA")
INPPoint : public IDispatch
{
public:
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_X(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Y(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Z(
/* [retval][out] */ VARIANT *pVal) = 0;
};
#else /* C style interface */
typedef struct INPPointVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
INPPoint * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
INPPoint * This);
ULONG ( STDMETHODCALLTYPE *Release )(
INPPoint * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
INPPoint * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
INPPoint * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
INPPoint * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
INPPoint * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_X )(
INPPoint * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Y )(
INPPoint * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Z )(
INPPoint * This,
/* [retval][out] */ VARIANT *pVal);
END_INTERFACE
} INPPointVtbl;
interface INPPoint
{
CONST_VTBL struct INPPointVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define INPPoint_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define INPPoint_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define INPPoint_Release(This) \
(This)->lpVtbl -> Release(This)
#define INPPoint_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define INPPoint_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define INPPoint_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define INPPoint_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define INPPoint_get_X(This,pVal) \
(This)->lpVtbl -> get_X(This,pVal)
#define INPPoint_get_Y(This,pVal) \
(This)->lpVtbl -> get_Y(This,pVal)
#define INPPoint_get_Z(This,pVal) \
(This)->lpVtbl -> get_Z(This,pVal)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPPoint_get_X_Proxy(
INPPoint * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPPoint_get_X_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPPoint_get_Y_Proxy(
INPPoint * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPPoint_get_Y_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPPoint_get_Z_Proxy(
INPPoint * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPPoint_get_Z_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __INPPoint_INTERFACE_DEFINED__ */
#ifndef __INPVector2_INTERFACE_DEFINED__
#define __INPVector2_INTERFACE_DEFINED__
/* interface INPVector2 */
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_INPVector2;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("9124C9A9-9296-4E89-973D-4F3C502E36CA")
INPVector2 : public IDispatch
{
public:
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Yaw(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Pitch(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Roll(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_X(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Y(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Z(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_dist01(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_dist01(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_dist02(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_dist02(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_dist12(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_dist12(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_distol(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_distol(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Tracking(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Update(
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Reset( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetPoint(
/* [in] */ int nPoint,
/* [retval][out] */ INPPoint **ppPoint) = 0;
};
#else /* C style interface */
typedef struct INPVector2Vtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
INPVector2 * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
INPVector2 * This);
ULONG ( STDMETHODCALLTYPE *Release )(
INPVector2 * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
INPVector2 * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
INPVector2 * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
INPVector2 * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
INPVector2 * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Yaw )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Pitch )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Roll )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_X )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Y )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Z )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_dist01 )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_dist01 )(
INPVector2 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_dist02 )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_dist02 )(
INPVector2 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_dist12 )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_dist12 )(
INPVector2 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_distol )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_distol )(
INPVector2 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Tracking )(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Update )(
INPVector2 * This,
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Reset )(
INPVector2 * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetPoint )(
INPVector2 * This,
/* [in] */ int nPoint,
/* [retval][out] */ INPPoint **ppPoint);
END_INTERFACE
} INPVector2Vtbl;
interface INPVector2
{
CONST_VTBL struct INPVector2Vtbl *lpVtbl;
};
#ifdef COBJMACROS
#define INPVector2_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define INPVector2_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define INPVector2_Release(This) \
(This)->lpVtbl -> Release(This)
#define INPVector2_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define INPVector2_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define INPVector2_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define INPVector2_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define INPVector2_get_Yaw(This,pVal) \
(This)->lpVtbl -> get_Yaw(This,pVal)
#define INPVector2_get_Pitch(This,pVal) \
(This)->lpVtbl -> get_Pitch(This,pVal)
#define INPVector2_get_Roll(This,pVal) \
(This)->lpVtbl -> get_Roll(This,pVal)
#define INPVector2_get_X(This,pVal) \
(This)->lpVtbl -> get_X(This,pVal)
#define INPVector2_get_Y(This,pVal) \
(This)->lpVtbl -> get_Y(This,pVal)
#define INPVector2_get_Z(This,pVal) \
(This)->lpVtbl -> get_Z(This,pVal)
#define INPVector2_get_dist01(This,pVal) \
(This)->lpVtbl -> get_dist01(This,pVal)
#define INPVector2_put_dist01(This,Val) \
(This)->lpVtbl -> put_dist01(This,Val)
#define INPVector2_get_dist02(This,pVal) \
(This)->lpVtbl -> get_dist02(This,pVal)
#define INPVector2_put_dist02(This,Val) \
(This)->lpVtbl -> put_dist02(This,Val)
#define INPVector2_get_dist12(This,pVal) \
(This)->lpVtbl -> get_dist12(This,pVal)
#define INPVector2_put_dist12(This,Val) \
(This)->lpVtbl -> put_dist12(This,Val)
#define INPVector2_get_distol(This,pVal) \
(This)->lpVtbl -> get_distol(This,pVal)
#define INPVector2_put_distol(This,Val) \
(This)->lpVtbl -> put_distol(This,Val)
#define INPVector2_get_Tracking(This,pVal) \
(This)->lpVtbl -> get_Tracking(This,pVal)
#define INPVector2_Update(This,pCamera,pFrame) \
(This)->lpVtbl -> Update(This,pCamera,pFrame)
#define INPVector2_Reset(This) \
(This)->lpVtbl -> Reset(This)
#define INPVector2_GetPoint(This,nPoint,ppPoint) \
(This)->lpVtbl -> GetPoint(This,nPoint,ppPoint)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_Yaw_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_Yaw_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_Pitch_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_Pitch_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_Roll_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_Roll_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_X_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_X_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_Y_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_Y_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_Z_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_Z_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_dist01_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_dist01_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector2_put_dist01_Proxy(
INPVector2 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector2_put_dist01_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_dist02_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_dist02_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector2_put_dist02_Proxy(
INPVector2 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector2_put_dist02_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_dist12_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_dist12_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector2_put_dist12_Proxy(
INPVector2 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector2_put_dist12_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_distol_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_distol_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector2_put_distol_Proxy(
INPVector2 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector2_put_distol_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector2_get_Tracking_Proxy(
INPVector2 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector2_get_Tracking_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPVector2_Update_Proxy(
INPVector2 * This,
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame);
void __RPC_STUB INPVector2_Update_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPVector2_Reset_Proxy(
INPVector2 * This);
void __RPC_STUB INPVector2_Reset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPVector2_GetPoint_Proxy(
INPVector2 * This,
/* [in] */ int nPoint,
/* [retval][out] */ INPPoint **ppPoint);
void __RPC_STUB INPVector2_GetPoint_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __INPVector2_INTERFACE_DEFINED__ */
#ifndef __INPVector3_INTERFACE_DEFINED__
#define __INPVector3_INTERFACE_DEFINED__
/* interface INPVector3 */
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_INPVector3;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("9124C9AA-9296-4E89-973D-4F3C502E36CA")
INPVector3 : public IDispatch
{
public:
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Yaw(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Pitch(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Roll(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_X(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Y(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Z(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_dist01(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_dist01(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_dist02(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_dist02(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_dist12(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_dist12(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_distol(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_distol(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_Tracking(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_imagerPixelWidth(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_imagerPixelWidth(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_imagerPixelHeight(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_imagerPixelHeight(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_imagerMMWidth(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_imagerMMWidth(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_imagerMMHeight(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_imagerMMHeight(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_imagerMMFocalLength(
/* [retval][out] */ VARIANT *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_imagerMMFocalLength(
/* [in] */ VARIANT Val) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Update(
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Reset( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE GetPoint(
/* [in] */ int nPoint,
/* [retval][out] */ INPPoint **ppPoint) = 0;
};
#else /* C style interface */
typedef struct INPVector3Vtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
INPVector3 * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
INPVector3 * This);
ULONG ( STDMETHODCALLTYPE *Release )(
INPVector3 * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
INPVector3 * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
INPVector3 * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
INPVector3 * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
INPVector3 * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Yaw )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Pitch )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Roll )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_X )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Y )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Z )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_dist01 )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_dist01 )(
INPVector3 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_dist02 )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_dist02 )(
INPVector3 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_dist12 )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_dist12 )(
INPVector3 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_distol )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_distol )(
INPVector3 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Tracking )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_imagerPixelWidth )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_imagerPixelWidth )(
INPVector3 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_imagerPixelHeight )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_imagerPixelHeight )(
INPVector3 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_imagerMMWidth )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_imagerMMWidth )(
INPVector3 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_imagerMMHeight )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_imagerMMHeight )(
INPVector3 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_imagerMMFocalLength )(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_imagerMMFocalLength )(
INPVector3 * This,
/* [in] */ VARIANT Val);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Update )(
INPVector3 * This,
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Reset )(
INPVector3 * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *GetPoint )(
INPVector3 * This,
/* [in] */ int nPoint,
/* [retval][out] */ INPPoint **ppPoint);
END_INTERFACE
} INPVector3Vtbl;
interface INPVector3
{
CONST_VTBL struct INPVector3Vtbl *lpVtbl;
};
#ifdef COBJMACROS
#define INPVector3_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define INPVector3_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define INPVector3_Release(This) \
(This)->lpVtbl -> Release(This)
#define INPVector3_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define INPVector3_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define INPVector3_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define INPVector3_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define INPVector3_get_Yaw(This,pVal) \
(This)->lpVtbl -> get_Yaw(This,pVal)
#define INPVector3_get_Pitch(This,pVal) \
(This)->lpVtbl -> get_Pitch(This,pVal)
#define INPVector3_get_Roll(This,pVal) \
(This)->lpVtbl -> get_Roll(This,pVal)
#define INPVector3_get_X(This,pVal) \
(This)->lpVtbl -> get_X(This,pVal)
#define INPVector3_get_Y(This,pVal) \
(This)->lpVtbl -> get_Y(This,pVal)
#define INPVector3_get_Z(This,pVal) \
(This)->lpVtbl -> get_Z(This,pVal)
#define INPVector3_get_dist01(This,pVal) \
(This)->lpVtbl -> get_dist01(This,pVal)
#define INPVector3_put_dist01(This,Val) \
(This)->lpVtbl -> put_dist01(This,Val)
#define INPVector3_get_dist02(This,pVal) \
(This)->lpVtbl -> get_dist02(This,pVal)
#define INPVector3_put_dist02(This,Val) \
(This)->lpVtbl -> put_dist02(This,Val)
#define INPVector3_get_dist12(This,pVal) \
(This)->lpVtbl -> get_dist12(This,pVal)
#define INPVector3_put_dist12(This,Val) \
(This)->lpVtbl -> put_dist12(This,Val)
#define INPVector3_get_distol(This,pVal) \
(This)->lpVtbl -> get_distol(This,pVal)
#define INPVector3_put_distol(This,Val) \
(This)->lpVtbl -> put_distol(This,Val)
#define INPVector3_get_Tracking(This,pVal) \
(This)->lpVtbl -> get_Tracking(This,pVal)
#define INPVector3_get_imagerPixelWidth(This,pVal) \
(This)->lpVtbl -> get_imagerPixelWidth(This,pVal)
#define INPVector3_put_imagerPixelWidth(This,Val) \
(This)->lpVtbl -> put_imagerPixelWidth(This,Val)
#define INPVector3_get_imagerPixelHeight(This,pVal) \
(This)->lpVtbl -> get_imagerPixelHeight(This,pVal)
#define INPVector3_put_imagerPixelHeight(This,Val) \
(This)->lpVtbl -> put_imagerPixelHeight(This,Val)
#define INPVector3_get_imagerMMWidth(This,pVal) \
(This)->lpVtbl -> get_imagerMMWidth(This,pVal)
#define INPVector3_put_imagerMMWidth(This,Val) \
(This)->lpVtbl -> put_imagerMMWidth(This,Val)
#define INPVector3_get_imagerMMHeight(This,pVal) \
(This)->lpVtbl -> get_imagerMMHeight(This,pVal)
#define INPVector3_put_imagerMMHeight(This,Val) \
(This)->lpVtbl -> put_imagerMMHeight(This,Val)
#define INPVector3_get_imagerMMFocalLength(This,pVal) \
(This)->lpVtbl -> get_imagerMMFocalLength(This,pVal)
#define INPVector3_put_imagerMMFocalLength(This,Val) \
(This)->lpVtbl -> put_imagerMMFocalLength(This,Val)
#define INPVector3_Update(This,pCamera,pFrame) \
(This)->lpVtbl -> Update(This,pCamera,pFrame)
#define INPVector3_Reset(This) \
(This)->lpVtbl -> Reset(This)
#define INPVector3_GetPoint(This,nPoint,ppPoint) \
(This)->lpVtbl -> GetPoint(This,nPoint,ppPoint)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_Yaw_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_Yaw_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_Pitch_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_Pitch_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_Roll_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_Roll_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_X_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_X_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_Y_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_Y_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_Z_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_Z_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_dist01_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_dist01_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector3_put_dist01_Proxy(
INPVector3 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector3_put_dist01_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_dist02_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_dist02_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector3_put_dist02_Proxy(
INPVector3 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector3_put_dist02_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_dist12_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_dist12_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector3_put_dist12_Proxy(
INPVector3 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector3_put_dist12_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_distol_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_distol_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector3_put_distol_Proxy(
INPVector3 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector3_put_distol_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_Tracking_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_Tracking_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_imagerPixelWidth_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_imagerPixelWidth_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector3_put_imagerPixelWidth_Proxy(
INPVector3 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector3_put_imagerPixelWidth_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_imagerPixelHeight_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_imagerPixelHeight_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector3_put_imagerPixelHeight_Proxy(
INPVector3 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector3_put_imagerPixelHeight_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_imagerMMWidth_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_imagerMMWidth_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector3_put_imagerMMWidth_Proxy(
INPVector3 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector3_put_imagerMMWidth_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_imagerMMHeight_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_imagerMMHeight_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector3_put_imagerMMHeight_Proxy(
INPVector3 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector3_put_imagerMMHeight_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPVector3_get_imagerMMFocalLength_Proxy(
INPVector3 * This,
/* [retval][out] */ VARIANT *pVal);
void __RPC_STUB INPVector3_get_imagerMMFocalLength_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPVector3_put_imagerMMFocalLength_Proxy(
INPVector3 * This,
/* [in] */ VARIANT Val);
void __RPC_STUB INPVector3_put_imagerMMFocalLength_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPVector3_Update_Proxy(
INPVector3 * This,
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame);
void __RPC_STUB INPVector3_Update_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPVector3_Reset_Proxy(
INPVector3 * This);
void __RPC_STUB INPVector3_Reset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPVector3_GetPoint_Proxy(
INPVector3 * This,
/* [in] */ int nPoint,
/* [retval][out] */ INPPoint **ppPoint);
void __RPC_STUB INPVector3_GetPoint_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __INPVector3_INTERFACE_DEFINED__ */
#ifndef __INPAvi_INTERFACE_DEFINED__
#define __INPAvi_INTERFACE_DEFINED__
/* interface INPAvi */
/* [unique][helpstring][dual][uuid][object] */
EXTERN_C const IID IID_INPAvi;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("9124CA00-9296-4E89-973D-4F3C502E36CA")
INPAvi : public IDispatch
{
public:
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_FileName(
/* [retval][out] */ BSTR *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_FileName(
/* [in] */ BSTR Val) = 0;
virtual /* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE get_FrameRate(
/* [retval][out] */ LONG *pVal) = 0;
virtual /* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE put_FrameRate(
/* [in] */ LONG Val) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Start( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE Stop( void) = 0;
virtual /* [helpstring][id] */ HRESULT STDMETHODCALLTYPE AddFrame(
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame) = 0;
};
#else /* C style interface */
typedef struct INPAviVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
INPAvi * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
INPAvi * This);
ULONG ( STDMETHODCALLTYPE *Release )(
INPAvi * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
INPAvi * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
INPAvi * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
INPAvi * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
INPAvi * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_FileName )(
INPAvi * This,
/* [retval][out] */ BSTR *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_FileName )(
INPAvi * This,
/* [in] */ BSTR Val);
/* [helpstring][id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_FrameRate )(
INPAvi * This,
/* [retval][out] */ LONG *pVal);
/* [helpstring][id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_FrameRate )(
INPAvi * This,
/* [in] */ LONG Val);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Start )(
INPAvi * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *Stop )(
INPAvi * This);
/* [helpstring][id] */ HRESULT ( STDMETHODCALLTYPE *AddFrame )(
INPAvi * This,
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame);
END_INTERFACE
} INPAviVtbl;
interface INPAvi
{
CONST_VTBL struct INPAviVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define INPAvi_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define INPAvi_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define INPAvi_Release(This) \
(This)->lpVtbl -> Release(This)
#define INPAvi_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define INPAvi_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define INPAvi_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define INPAvi_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#define INPAvi_get_FileName(This,pVal) \
(This)->lpVtbl -> get_FileName(This,pVal)
#define INPAvi_put_FileName(This,Val) \
(This)->lpVtbl -> put_FileName(This,Val)
#define INPAvi_get_FrameRate(This,pVal) \
(This)->lpVtbl -> get_FrameRate(This,pVal)
#define INPAvi_put_FrameRate(This,Val) \
(This)->lpVtbl -> put_FrameRate(This,Val)
#define INPAvi_Start(This) \
(This)->lpVtbl -> Start(This)
#define INPAvi_Stop(This) \
(This)->lpVtbl -> Stop(This)
#define INPAvi_AddFrame(This,pCamera,pFrame) \
(This)->lpVtbl -> AddFrame(This,pCamera,pFrame)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPAvi_get_FileName_Proxy(
INPAvi * This,
/* [retval][out] */ BSTR *pVal);
void __RPC_STUB INPAvi_get_FileName_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPAvi_put_FileName_Proxy(
INPAvi * This,
/* [in] */ BSTR Val);
void __RPC_STUB INPAvi_put_FileName_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propget] */ HRESULT STDMETHODCALLTYPE INPAvi_get_FrameRate_Proxy(
INPAvi * This,
/* [retval][out] */ LONG *pVal);
void __RPC_STUB INPAvi_get_FrameRate_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id][propput] */ HRESULT STDMETHODCALLTYPE INPAvi_put_FrameRate_Proxy(
INPAvi * This,
/* [in] */ LONG Val);
void __RPC_STUB INPAvi_put_FrameRate_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPAvi_Start_Proxy(
INPAvi * This);
void __RPC_STUB INPAvi_Start_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPAvi_Stop_Proxy(
INPAvi * This);
void __RPC_STUB INPAvi_Stop_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [helpstring][id] */ HRESULT STDMETHODCALLTYPE INPAvi_AddFrame_Proxy(
INPAvi * This,
/* [in] */ INPCamera *pCamera,
/* [in] */ INPCameraFrame *pFrame);
void __RPC_STUB INPAvi_AddFrame_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __INPAvi_INTERFACE_DEFINED__ */
#ifndef __OptiTrack_LIBRARY_DEFINED__
#define __OptiTrack_LIBRARY_DEFINED__
/* library OptiTrack */
/* [helpstring][version][uuid] */
EXTERN_C const IID LIBID_OptiTrack;
#ifndef ___INPCameraCollectionEvents_DISPINTERFACE_DEFINED__
#define ___INPCameraCollectionEvents_DISPINTERFACE_DEFINED__
/* dispinterface _INPCameraCollectionEvents */
/* [helpstring][uuid] */
EXTERN_C const IID DIID__INPCameraCollectionEvents;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("076F9DDA-1422-4B4D-926A-961DF5725B5A")
_INPCameraCollectionEvents : public IDispatch
{
};
#else /* C style interface */
typedef struct _INPCameraCollectionEventsVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
_INPCameraCollectionEvents * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
_INPCameraCollectionEvents * This);
ULONG ( STDMETHODCALLTYPE *Release )(
_INPCameraCollectionEvents * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
_INPCameraCollectionEvents * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
_INPCameraCollectionEvents * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
_INPCameraCollectionEvents * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
_INPCameraCollectionEvents * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
END_INTERFACE
} _INPCameraCollectionEventsVtbl;
interface _INPCameraCollectionEvents
{
CONST_VTBL struct _INPCameraCollectionEventsVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define _INPCameraCollectionEvents_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define _INPCameraCollectionEvents_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define _INPCameraCollectionEvents_Release(This) \
(This)->lpVtbl -> Release(This)
#define _INPCameraCollectionEvents_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define _INPCameraCollectionEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define _INPCameraCollectionEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define _INPCameraCollectionEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* ___INPCameraCollectionEvents_DISPINTERFACE_DEFINED__ */
#ifndef ___INPCameraEvents_DISPINTERFACE_DEFINED__
#define ___INPCameraEvents_DISPINTERFACE_DEFINED__
/* dispinterface _INPCameraEvents */
/* [helpstring][uuid] */
EXTERN_C const IID DIID__INPCameraEvents;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("A50B57C5-7472-4F16-BC14-2345B8D24BFD")
_INPCameraEvents : public IDispatch
{
};
#else /* C style interface */
typedef struct _INPCameraEventsVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
_INPCameraEvents * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
_INPCameraEvents * This);
ULONG ( STDMETHODCALLTYPE *Release )(
_INPCameraEvents * This);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
_INPCameraEvents * This,
/* [out] */ UINT *pctinfo);
HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
_INPCameraEvents * This,
/* [in] */ UINT iTInfo,
/* [in] */ LCID lcid,
/* [out] */ ITypeInfo **ppTInfo);
HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
_INPCameraEvents * This,
/* [in] */ REFIID riid,
/* [size_is][in] */ LPOLESTR *rgszNames,
/* [in] */ UINT cNames,
/* [in] */ LCID lcid,
/* [size_is][out] */ DISPID *rgDispId);
/* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
_INPCameraEvents * This,
/* [in] */ DISPID dispIdMember,
/* [in] */ REFIID riid,
/* [in] */ LCID lcid,
/* [in] */ WORD wFlags,
/* [out][in] */ DISPPARAMS *pDispParams,
/* [out] */ VARIANT *pVarResult,
/* [out] */ EXCEPINFO *pExcepInfo,
/* [out] */ UINT *puArgErr);
END_INTERFACE
} _INPCameraEventsVtbl;
interface _INPCameraEvents
{
CONST_VTBL struct _INPCameraEventsVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define _INPCameraEvents_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define _INPCameraEvents_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define _INPCameraEvents_Release(This) \
(This)->lpVtbl -> Release(This)
#define _INPCameraEvents_GetTypeInfoCount(This,pctinfo) \
(This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)
#define _INPCameraEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \
(This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)
#define _INPCameraEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \
(This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)
#define _INPCameraEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \
(This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* ___INPCameraEvents_DISPINTERFACE_DEFINED__ */
EXTERN_C const CLSID CLSID_NPCameraCollection;
#ifdef __cplusplus
class DECLSPEC_UUID("1CA83C6F-70A6-40EB-836F-D9EEC0BD168F")
NPCameraCollection;
#endif
EXTERN_C const CLSID CLSID_NPCamera;
#ifdef __cplusplus
class DECLSPEC_UUID("77686C4C-8402-42CE-ADF2-913B53E0A25B")
NPCamera;
#endif
EXTERN_C const CLSID CLSID_NPCameraFrame;
#ifdef __cplusplus
class DECLSPEC_UUID("4656500B-863B-48F6-8725-AB029769EA89")
NPCameraFrame;
#endif
EXTERN_C const CLSID CLSID_NPObject;
#ifdef __cplusplus
class DECLSPEC_UUID("B696B174-5B53-4DDD-B78B-CA75C072C85A")
NPObject;
#endif
EXTERN_C const CLSID CLSID_NPSmoothing;
#ifdef __cplusplus
class DECLSPEC_UUID("B4CA710D-9B17-42C3-846B-FC16876B6D5E")
NPSmoothing;
#endif
EXTERN_C const CLSID CLSID_NPVector;
#ifdef __cplusplus
class DECLSPEC_UUID("FE7D5FB0-0560-49ED-BF49-CE9996C62A6B")
NPVector;
#endif
EXTERN_C const CLSID CLSID_NPPoint;
#ifdef __cplusplus
class DECLSPEC_UUID("FE7D5FB2-0560-49ED-BF49-CE9996C62A6B")
NPPoint;
#endif
EXTERN_C const CLSID CLSID_NPAvi;
#ifdef __cplusplus
class DECLSPEC_UUID("FE7D5FB3-0560-49ED-BF49-CE9996C62A6B")
NPAvi;
#endif
#endif /* __OptiTrack_LIBRARY_DEFINED__ */
/* Additional Prototypes for ALL interfaces */
unsigned long __RPC_USER BSTR_UserSize( unsigned long *, unsigned long , BSTR * );
unsigned char * __RPC_USER BSTR_UserMarshal( unsigned long *, unsigned char *, BSTR * );
unsigned char * __RPC_USER BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * );
void __RPC_USER BSTR_UserFree( unsigned long *, BSTR * );
unsigned long __RPC_USER VARIANT_UserSize( unsigned long *, unsigned long , VARIANT * );
unsigned char * __RPC_USER VARIANT_UserMarshal( unsigned long *, unsigned char *, VARIANT * );
unsigned char * __RPC_USER VARIANT_UserUnmarshal(unsigned long *, unsigned char *, VARIANT * );
void __RPC_USER VARIANT_UserFree( unsigned long *, VARIANT * );
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
| [
"LeoYang01@a4a63562-5fa1-11de-92c7-cf56be1892c0"
] | [
[
[
1,
4596
]
]
] |
0b47e02b0e1034e5dc6aac0b0a15b05714a17381 | 17083b919f058848c3eb038eae37effd1a5b0759 | /SimpleGL/sgl/Math/Base.hpp | c9fef720d753cbb266fba32ff74978ed182b4dcb | [] | 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 | 1,096 | hpp | #ifndef SIMPLE_GL_MATH_BASE_HPP
#define SIMPLE_GL_MATH_BASE_HPP
#include "../Utility/Aligned.h"
#include "FPT.hpp"
#ifdef SIMPLE_GL_USE_SSE
# ifdef _MSC_VER
# include <mmintrin.h>
# else // __GNUC__
# include <xmmintrin.h>
# ifdef SIMPLE_GL_USE_SSE4
# include <smmintrin.h>
# elif defined(SIMPLE_GL_USE_SSE3)
# include <pmmintrin.h>
# else // SIMPLE_GL_USE_SSE2
# include <emmintrin.h>
# endif // SIMPLE_GL_USE_SSE4
# endif // __GNUC__
#endif // SIMPLE_GL_USE_SSE
SGL_BEGIN_MATH_NAMESPACE
template<typename ValueType,
int n,
int m>
class MatrixBase
{
public:
typedef ValueType value_type;
static const int num_elements = n * m;
static const int num_rows = n;
static const int num_columns = m;
protected:
/** Don't delete using MatrixBase. */
inline ~MatrixBase() {}
};
// Create useless 1x1 matrices
template<typename T>
class MatrixBase<T, 1, 1> {};
SGL_END_MATH_NAMESPACE
#endif // SIMPLE_GL_MATH_BASE_HPP
| [
"devnull@localhost"
] | [
[
[
1,
47
]
]
] |
1e292df023e2a51700305953eb2aa2c867901680 | d411188fd286604be7670b61a3c4c373345f1013 | /zomgame/ZGame/inventory.cpp | d283ce858950c00a404a19916460e9205560a25d | [] | no_license | kjchiu/zomgame | 5af3e45caea6128e6ac41a7e3774584e0ca7a10f | 1f62e569da4c01ecab21a709a4a3f335dff18f74 | refs/heads/master | 2021-01-13T13:16:58.843499 | 2008-09-13T05:11:16 | 2008-09-13T05:11:16 | 1,560,000 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,223 | cpp | #include "inventory.h"
Inventory::Inventory(){
totalWeight = 0;
totalBulk = 0;
items = vector<Item*>();
}
bool Inventory::addItem(Item* item){
//check to see if possible first
items.push_back(item);
totalWeight += item->getWeight();
totalBulk += item->getBulk();
return true;
}
Item* Inventory::getItemAt(int index){
if (index < items.size() && index >= 0)
return items.at(index);
else
return NULL;
}
vector<Item*> Inventory::getItems(){
return items;
}
int Inventory::getSize(){
return items.size();
}
int Inventory::getTotalBulk(){
return totalBulk;
}
int Inventory::getTotalWeight(){
return totalWeight;
}
bool Inventory::removeItem(Item* item){
for (unsigned int i=0; i<items.size(); i++){
if (items.at(i)->getID() == item->getID()){
if (i==items.size()-1){
items.pop_back();
} else {
items.erase(items.begin()+i, items.begin()+i+1);
}
}
}
return true;
}
bool Inventory::removeItemAt(int index){
if (index < items.size() && index >= 0){
if (index==items.size()-1){
items.pop_back();
} else {
items.erase(items.begin()+index, items.begin()+index+1);
}
return true;
}
return false;
} | [
"nicholasbale@9b66597e-bb4a-0410-bce4-15c857dd0990",
"krypes@9b66597e-bb4a-0410-bce4-15c857dd0990"
] | [
[
[
1,
18
],
[
23,
64
]
],
[
[
19,
22
]
]
] |
9b5172841c0fe4197dbe09f06f6b127eebfdc87c | 8ab2c6ddf732e1858c7ee2c07220b7ab91ec1d13 | /Guolice/include/Geometry.h | f8bbbfc6e854113d32e952bfdb8ac33bc83ead17 | [] | no_license | manouti/c-shell | 6f26df0ac59b179abd6e8151d18b7aa8847b676d | 642d547cb27cc92b0852f5e04d00957e626fca46 | refs/heads/master | 2021-01-01T15:36:44.217896 | 2011-01-29T22:30:47 | 2011-01-29T22:30:47 | 34,175,220 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 929 | h | /**\file Geometry.h
* \brief Holds any static fields and methods used in Segment.h or Line.h
* This file was written to study the case where a triangle contains ather shapes
*/
#ifndef GEOMETRY
#define GEOMETRY
/**
* \class Geometry
* \brief Holds any static fields and methods used in Segment.h or Line.h
*
*/
class Geometry
{
public:
/**
* Tolerance of the calculations. Anything smaller is considered zero.
*/
static const double TOLERANCE = 1e-9;
/**
* Checks whether a real value is close to zero.
* @param x
* @return <code>true</code> if <code>x</code> is close to zero
*/
static bool isZero(double x)
{
return fabs(x) < TOLERANCE;
}
/**
* Checks whether two double values are equal.
* @param x
* @return <code>true</code> if <code>x</code> they are equal
*/
static bool areEqual(double a, double b)
{
return isZero(a - b);
}
};
#endif //GEOMETRY
| [
"[email protected]@d2ccdeb4-faeb-767e-6b92-2c8aa4952157"
] | [
[
[
1,
42
]
]
] |
1745f6fafc4e13c69f680808bc08bfc20b1e4548 | b822313f0e48cf146b4ebc6e4548b9ad9da9a78e | /KylinSdk/Engine/Source/uiCursorEx.cpp | e69e23573952345cee4ee0bcdbc8968d9a57031f | [] | no_license | dzw/kylin001v | 5cca7318301931bbb9ede9a06a24a6adfe5a8d48 | 6cec2ed2e44cea42957301ec5013d264be03ea3e | refs/heads/master | 2021-01-10T12:27:26.074650 | 2011-05-30T07:11:36 | 2011-05-30T07:11:36 | 46,501,473 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,545 | cpp | #include "engpch.h"
#include "uiCursorEx.h"
#include <MyGUI.h>
#include "rogreRoot.h"
#include "InputManager.h"
Kylin::CursorEx::CursorEx()
: GuiBase(CLASS_TO(CursorEx))
, m_eType(CT_NORMAL)
{
}
KBOOL Kylin::CursorEx::Initialize()
{
//MyGUI::PointerManager::getInstance().load("Pointers.xml");
SetPointer(CT_NORMAL);
MyGUI::IntSize size = MyGUI::Gui::getInstance().getViewSize();
Kylin::OgreRoot::GetSingletonPtr()->GetInputManager()->SetMousePosition(size.width / 2, size.height / 2);
return true;
}
KVOID Kylin::CursorEx::SetVisible(KBOOL bShow)
{
GuiBase::SetVisible(bShow);
MyGUI::PointerManager& refPointer = MyGUI::PointerManager::getInstance();
if ( bShow )
{
if (!refPointer.isVisible())
refPointer.setVisible(bShow);
}
else
{
if (refPointer.isVisible())
refPointer.setVisible(bShow);
}
}
KVOID Kylin::CursorEx::SetPointer( CursorType eType )
{
MyGUI::PointerManager& refPointer = MyGUI::PointerManager::getInstance();
switch (eType)
{
case CT_NORMAL:
MyGUI::PointerManager::getInstance().setPointer("ptr_Normal");
break;
case CT_ATTACK:
MyGUI::PointerManager::getInstance().setPointer("ptr_Attack");
break;
case CT_PICKUP:
MyGUI::PointerManager::getInstance().setPointer("ptr_Pickup");
break;
case CT_UNREACHABLE:
break;
}
MyGUI::PointerManager::getInstance().setVisible(true);
m_eType = eType;
}
Kylin::CursorEx::CursorType Kylin::CursorEx::GetPointerType()
{
return m_eType;
} | [
"[email protected]",
"apayaccount@5fe9e158-c84b-58b7-3744-914c3a81fc4f"
] | [
[
[
1,
4
],
[
7,
7
],
[
17,
18
],
[
27,
48
],
[
51,
53
],
[
56,
58
],
[
61,
71
],
[
75,
76
]
],
[
[
5,
6
],
[
8,
16
],
[
19,
26
],
[
49,
50
],
[
54,
55
],
[
59,
60
],
[
72,
74
],
[
77,
80
]
]
] |
388768dd602e644fad9103f5a30b583f503f9579 | df4928511778393732aa2f1560f204826f05fe10 | /textdialog.cpp | f07a4ddc75af2f3b0910ed701ee6184dd3eb2515 | [] | no_license | ViktorNordgren/sword-of-kings | ad88769671eb5a1134e3909bd25310d429fede81 | 4d16f69dca6f0d1f82aac393fa79d96632903f49 | refs/heads/master | 2018-01-08T10:26:29.012309 | 2007-11-29T06:57:45 | 2007-11-29T06:57:45 | 49,721,358 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,112 | cpp | /*
* TextDialog.cpp
*/
#include "textdialog.h"
/*
* TextDialog
*/
TextDialog::TextDialog()
{
}
TextDialog::~TextDialog()
{
}
TextDialog::TextDialog(string speech)
{
userString = speech;
vector<string> words;
Parser::tokenize(speech, words);
string currDialog = "";
//loop through and put into seperate dialogs.
for(int word = 0; word < words.size(); word++)
{
if( currDialog.length() + words[word].length() + 1 > (LINE_LENGTH - 2) * NUM_LINES )
{
dialogs.push_back(currDialog);
currDialog = "";
}
currDialog.append(" ");
currDialog.append(words[word]);
}
dialogs.push_back(currDialog);
iterator = 0;
}
void TextDialog::resetIterator()
{
iterator = 0;
}
bool TextDialog::moreDialogs()
{
return iterator < dialogs.size();
}
string TextDialog::getNextDialog()
{
return dialogs[iterator++];
}
string TextDialog::getAction()
{
return action;
}
void TextDialog::setAction(string a)
{
action = a;
}
| [
"[email protected]",
"mhousser@5b9ac4b1-7c3f-0410-9070-89a53124ee38"
] | [
[
[
1,
57
]
],
[
[
58,
67
]
]
] |
980b40278a86bf865e503f2b5a064cfe0ea78c9e | 944e19e1a68ac1d4c5f6e7ccde1061a43e791887 | /OBBDetection/OBBDetection/DrawableTex2D.cpp | 8f568fd5633a9a3b931b72937426c5a000bb4ace | [] | no_license | Fredrib/obbdetection | 0a797ecac2c24be1a75ddd67fd928e35ddc586f5 | 41e065c379ddfb7ec0ca4ec0616be5204736b984 | refs/heads/master | 2020-04-22T14:03:17.358440 | 2011-01-17T15:24:09 | 2011-01-17T15:24:09 | 41,830,450 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,670 | cpp | //=============================================================================
// DrawableTex2D.cpp by Frank Luna (C) 2005 All Rights Reserved.
//=============================================================================
#include "main.h"
DrawableTex2D::DrawableTex2D(UINT width, UINT height, UINT mipLevels,
D3DFORMAT texFormat, bool useDepthBuffer,
D3DFORMAT depthFormat, D3DVIEWPORT9& viewport, bool autoGenMips)
: mTex(0), mRTS(0), mTopSurf(0), mWidth(width), mHeight(height),
mMipLevels(mipLevels), mTexFormat(texFormat), mUseDepthBuffer(useDepthBuffer),
mDepthFormat(depthFormat), mViewPort(viewport), mAutoGenMips(autoGenMips)
{
}
DrawableTex2D::~DrawableTex2D()
{
onLostDevice();
}
IDirect3DTexture9* DrawableTex2D::d3dTex()
{
return mTex;
}
void DrawableTex2D::onLostDevice()
{
ReleaseCOM(mTex);
ReleaseCOM(mRTS);
ReleaseCOM(mTopSurf);
}
void DrawableTex2D::onResetDevice()
{
UINT usage = D3DUSAGE_RENDERTARGET;
if(mAutoGenMips)
usage |= D3DUSAGE_AUTOGENMIPMAP;
HR(D3DXCreateTexture(g_app->m_pD3DDev, mWidth, mHeight, mMipLevels, usage, mTexFormat, D3DPOOL_DEFAULT, &mTex),
L"DrawableTex2D::onResetDevice: D3DXCreateTexture failed: ");
HR(D3DXCreateRenderToSurface(g_app->m_pD3DDev, mWidth, mHeight, mTexFormat, mUseDepthBuffer, mDepthFormat, &mRTS),
L"DrawableTex2D::onResetDevice: D3DXCreateRenderToSurface failed: ");
HR(mTex->GetSurfaceLevel(0, &mTopSurf),L"DrawableTex2D::onResetDevice: GetSurfaceLevel failed: ");
}
void DrawableTex2D::beginScene()
{
mRTS->BeginScene(mTopSurf, &mViewPort);
}
void DrawableTex2D::endScene()
{
mRTS->EndScene(D3DX_FILTER_NONE);
} | [
"jonathantompson@5e2a6976-228a-6e25-3d16-ad1625af6446"
] | [
[
[
1,
54
]
]
] |
cc57142ca8b00422b7f4154b3f38d5a63357e0d4 | 3b0bcc3e6cba0109463101aea0b1a3406fc45429 | /Debugger/source/MethodInformation.h | d741bda411fb93ed63f80bd286c4657aa691a756 | [
"MIT"
] | permissive | lsalamon/slimgen | 85a5dad4995b590152f761b18eebc174f9baebbc | a4c959438a9d6dfc487fc34856e2b69a146c1e61 | refs/heads/master | 2021-01-10T08:17:50.381747 | 2010-11-07T04:29:26 | 2010-11-07T04:29:26 | 54,969,433 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,371 | h | /*
* Copyright (c) 2007-2010 SlimGen Group
*
* 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.
*/
#pragma once
namespace SlimGen
{
struct MethodInformation
{
std::wstring Assembly;
std::wstring Method;
std::vector<std::vector<char>> CompiledData;
bool Replaced;
MethodInformation() : Replaced(false)
{
}
};
} | [
"Mike.Popoloski@dc685512-7b07-11de-a624-ab7c8f4ec817",
"ryoohki@dc685512-7b07-11de-a624-ab7c8f4ec817"
] | [
[
[
1,
25
],
[
27,
32
],
[
34,
37
]
],
[
[
26,
26
],
[
33,
33
]
]
] |
ae07a15cf0a59b54f68ee9fdbbf07afe259010fe | 44d499cacf286b033ce08eeceec1002e5ce782c9 | /hardware/at91/cortex-m3/rtc.cpp | 7d94fc17ddef0d8c40a08f0208676eae40687f52 | [] | no_license | thumbos/tmos | ef134ecc57b44e029ded14f957d7a23c982a4fae | 756c2bc513288bfe1be96331a9e388ed0d744c83 | refs/heads/master | 2021-03-12T22:56:14.235818 | 2010-12-04T16:25:26 | 2010-12-04T16:25:26 | 1,137,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,944 | cpp | /* ----------------------------------------------------------------------------
* ATMEL Microcontroller Software Support
* ----------------------------------------------------------------------------
* Copyright (c) 2009, Atmel Corporation
*
* 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 disclaimer below.
*
* Atmel's name may not be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* DISCLAIMER: THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
* ----------------------------------------------------------------------------
*/
/**************************************************************************//**
* @ingroup HW_SAM3S_RTC
* @file
* @brief Implementation of Real Time Clock (RTC) controller.
*
*/
/*----------------------------------------------------------------------------
* Headers
*----------------------------------------------------------------------------*/
//#include "chip.h"
//#include <stdint.h>
//#include <assert.h>
#include <tmos.h>
#include "platform_cpp.h"
/*----------------------------------------------------------------------------
* Exported functions
*----------------------------------------------------------------------------*/
/**
* \brief Sets the RTC in either 12 or 24 hour mode.
*
* @param pRtc
* \param dwMode Hour mode.
*/
extern void RTC_SetHourMode( Rtc* pRtc, uint32_t dwMode )
{
ASSERT((dwMode & 0xFFFFFFFE) == 0);
pRtc->RTC_MR = dwMode ;
}
/**
* \brief Gets the RTC mode.
*
* \return Hour mode.
*/
extern uint32_t RTC_GetHourMode( Rtc* pRtc )
{
uint32_t dwMode ;
TRACE_DEBUG( "RTC_SetHourMode()\n\r" ) ;
dwMode = pRtc->RTC_MR;
dwMode &= 0xFFFFFFFE;
return dwMode ;
}
/**
* \brief Enables the selected interrupt sources of the RTC.
*
* @param pRtc
* \param dwSources Interrupt sources to enable.
*/
extern void RTC_EnableIt( Rtc* pRtc, uint32_t dwSources )
{
ASSERT((dwSources & (uint32_t)(~0x1F)) == 0);
TRACE_DEBUG( "RTC_EnableIt()\n\r" ) ;
pRtc->RTC_IER = dwSources ;
}
/**
* \brief Disables the selected interrupt sources of the RTC.
*
* @param pRtc
* \param dwSources Interrupt sources to disable.
*/
extern void RTC_DisableIt( Rtc* pRtc, uint32_t dwSources )
{
ASSERT((dwSources & (uint32_t)(~0x1F)) == 0);
TRACE_DEBUG( "RTC_DisableIt()\n\r" ) ;
pRtc->RTC_IDR = dwSources ;
}
/**
* \brief Sets the current time in the RTC.
*
* \note In successive update operations, the user must wait at least one second
* after resetting the UPDTIM/UPDCAL bit in the RTC_CR before setting these
* bits again. Please look at the RTC section of the datasheet for detail.
*
* @param pRtc
* \param ucHour Current hour in 12 or 24 hour mode.
* \param ucMinute Current minute.
* \param ucSecond Current second.
*
* \return 0 sucess, 1 fail to set
*/
extern int RTC_SetTime( Rtc* pRtc, uint8_t ucHour, uint8_t ucMinute, uint8_t ucSecond )
{
uint32_t dwTime=0 ;
uint8_t ucHour_bcd ;
uint8_t ucMin_bcd ;
uint8_t ucSec_bcd ;
TRACE_DEBUG( "RTC_SetTime(%02d:%02d:%02d)\n\r", ucHour, ucMinute, ucSecond ) ;
/* if 12-hour mode, set AMPM bit */
if ( (pRtc->RTC_MR & RTC_MR_HRMOD) == RTC_MR_HRMOD )
{
if ( ucHour > 12 )
{
ucHour -= 12 ;
dwTime |= RTC_TIMR_AMPM ;
}
}
ucHour_bcd = (ucHour%10) | ((ucHour/10)<<4) ;
ucMin_bcd = (ucMinute%10) | ((ucMinute/10)<<4) ;
ucSec_bcd = (ucSecond%10) | ((ucSecond/10)<<4) ;
/* value overflow */
if ( (ucHour_bcd & (uint8_t)(~RTC_HOUR_BIT_LEN_MASK)) |
(ucMin_bcd & (uint8_t)(~RTC_MIN_BIT_LEN_MASK)) |
(ucSec_bcd & (uint8_t)(~RTC_SEC_BIT_LEN_MASK)))
{
return 1 ;
}
dwTime = ucSec_bcd | (ucMin_bcd << 8) | (ucHour_bcd<<16) ;
pRtc->RTC_CR |= RTC_CR_UPDTIM ;
while ((pRtc->RTC_SR & RTC_SR_ACKUPD) != RTC_SR_ACKUPD) ;
pRtc->RTC_SCCR = RTC_SCCR_ACKCLR ;
pRtc->RTC_TIMR = dwTime ;
pRtc->RTC_CR &= (uint32_t)(~RTC_CR_UPDTIM) ;
pRtc->RTC_SCCR |= RTC_SCCR_SECCLR ;
return (int)(pRtc->RTC_VER & RTC_VER_NVTIM) ;
}
/**
* \brief Retrieves the current time as stored in the RTC in several variables.
*
* @param pRtc
* \param pucHour If not null, current hour is stored in this variable.
* \param pucMinute If not null, current minute is stored in this variable.
* \param pucSecond If not null, current second is stored in this variable.
*/
extern void RTC_GetTime( Rtc* pRtc, uint8_t *pucHour, uint8_t *pucMinute, uint8_t *pucSecond )
{
uint32_t dwTime ;
TRACE_DEBUG( "RTC_GetTime()\n\r" ) ;
/* Get current RTC time */
dwTime = pRtc->RTC_TIMR ;
while ( dwTime != pRtc->RTC_TIMR )
{
dwTime = pRtc->RTC_TIMR ;
}
/* Hour */
if ( pucHour )
{
*pucHour = ((dwTime & 0x00300000) >> 20) * 10
+ ((dwTime & 0x000F0000) >> 16);
if ( (dwTime & RTC_TIMR_AMPM) == RTC_TIMR_AMPM )
{
*pucHour += 12 ;
}
}
/* Minute */
if ( pucMinute )
{
*pucMinute = ((dwTime & 0x00007000) >> 12) * 10
+ ((dwTime & 0x00000F00) >> 8);
}
/* Second */
if ( pucSecond )
{
*pucSecond = ((dwTime & 0x00000070) >> 4) * 10
+ (dwTime & 0x0000000F);
}
}
/**
* \brief Sets a time alarm on the RTC.
* The match is performed only on the provided variables;
* Setting all pointers to 0 disables the time alarm.
*
* \note In AM/PM mode, the hour value must have bit #7 set for PM, cleared for
* AM (as expected in the time registers).
*
* @param pRtc
* \param pucHour If not null, the time alarm will hour-match this value.
* \param pucMinute If not null, the time alarm will minute-match this value.
* \param pucSecond If not null, the time alarm will second-match this value.
*
* \return 0 success, 1 fail to set
*/
extern int RTC_SetTimeAlarm( Rtc* pRtc, uint8_t *pucHour, uint8_t *pucMinute, uint8_t *pucSecond )
{
uint32_t dwAlarm=0 ;
TRACE_DEBUG( "RTC_SetTimeAlarm()\n\r" ) ;
/* Hour */
if ( pucHour )
{
dwAlarm |= RTC_TIMALR_HOUREN | ((*pucHour / 10) << 20) | ((*pucHour % 10) << 16);
}
/* Minute */
if ( pucMinute )
{
dwAlarm |= RTC_TIMALR_MINEN | ((*pucMinute / 10) << 12) | ((*pucMinute % 10) << 8);
}
/* Second */
if ( pucSecond )
{
dwAlarm |= RTC_TIMALR_SECEN | ((*pucSecond / 10) << 4) | (*pucSecond % 10);
}
pRtc->RTC_TIMALR = dwAlarm ;
return (int)(pRtc->RTC_VER & RTC_VER_NVTIMALR) ;
}
/**
* \brief Retrieves the current year, month and day from the RTC.
* Month, day and week values are numbered starting at 1.
*
* @param pRtc
* \param pwYear Current year (optional).
* \param pucMonth Current month (optional).
* \param pucDay Current day (optional).
* \param pucWeek Current day in current week (optional).
*/
extern void RTC_GetDate( Rtc* pRtc, uint16_t *pwYear, uint8_t *pucMonth, uint8_t *pucDay, uint8_t *pucWeek )
{
uint32_t dwDate ;
/* Get current date (multiple reads are necessary to insure a stable value) */
do
{
dwDate = pRtc->RTC_CALR ;
}
while ( dwDate != pRtc->RTC_CALR ) ;
/* Retrieve year */
if ( pwYear )
{
*pwYear = (((dwDate >> 4) & 0x7) * 1000)
+ ((dwDate & 0xF) * 100)
+ (((dwDate >> 12) & 0xF) * 10)
+ ((dwDate >> 8) & 0xF);
}
/* Retrieve month */
if ( pucMonth )
{
*pucMonth = (((dwDate >> 20) & 1) * 10) + ((dwDate >> 16) & 0xF);
}
/* Retrieve day */
if ( pucDay )
{
*pucDay = (((dwDate >> 28) & 0x3) * 10) + ((dwDate >> 24) & 0xF);
}
/* Retrieve week */
if ( pucWeek )
{
*pucWeek = ((dwDate >> 21) & 0x7);
}
}
/**
* \brief Sets the current year, month and day in the RTC.
* Month, day and week values must be numbered starting from 1.
*
* \note In successive update operations, the user must wait at least one second
* after resetting the UPDTIM/UPDCAL bit in the RTC_CR before setting these
* bits again. Please look at the RTC section of the datasheet for detail.
*
* @param pRtc
* \param wYear Current year.
* \param ucMonth Current month.
* \param ucDay Current day.
* \param ucWeek Day number in current week.
*
* \return 0 success, 1 fail to set
*/
extern int RTC_SetDate( Rtc* pRtc, uint16_t wYear, uint8_t ucMonth, uint8_t ucDay, uint8_t ucWeek )
{
uint32_t wDate ;
uint8_t ucCent_bcd ;
uint8_t ucYear_bcd ;
uint8_t ucMonth_bcd ;
uint8_t ucDay_bcd ;
uint8_t ucWeek_bcd ;
ucCent_bcd = ((wYear/100)%10) | ((wYear/1000)<<4);
ucYear_bcd = (wYear%10) | (((wYear/10)%10)<<4);
ucMonth_bcd = ((ucMonth%10) | (ucMonth/10)<<4);
ucDay_bcd = ((ucDay%10) | (ucDay/10)<<4);
ucWeek_bcd = ((ucWeek%10) | (ucWeek/10)<<4);
/* value over flow */
if ( (ucCent_bcd & (uint8_t)(~RTC_CENT_BIT_LEN_MASK)) |
(ucYear_bcd & (uint8_t)(~RTC_YEAR_BIT_LEN_MASK)) |
(ucMonth_bcd & (uint8_t)(~RTC_MONTH_BIT_LEN_MASK)) |
(ucWeek_bcd & (uint8_t)(~RTC_WEEK_BIT_LEN_MASK)) |
(ucDay_bcd & (uint8_t)(~RTC_DATE_BIT_LEN_MASK))
)
{
return 1 ;
}
/* Convert values to date register value */
wDate = ucCent_bcd |
(ucYear_bcd << 8) |
(ucMonth_bcd << 16) |
(ucWeek_bcd << 21) |
(ucDay_bcd << 24);
/* Update calendar register */
pRtc->RTC_CR |= RTC_CR_UPDCAL ;
while ((pRtc->RTC_SR & RTC_SR_ACKUPD) != RTC_SR_ACKUPD) ;
pRtc->RTC_SCCR = RTC_SCCR_ACKCLR;
pRtc->RTC_CALR = wDate ;
pRtc->RTC_CR &= (uint32_t)(~RTC_CR_UPDCAL) ;
pRtc->RTC_SCCR |= RTC_SCCR_SECCLR; /* clear SECENV in SCCR */
return (int)(pRtc->RTC_VER & RTC_VER_NVCAL) ;
}
/**
* \brief Sets a date alarm in the RTC.
* The alarm will match only the provided values;
* Passing a null-pointer disables the corresponding field match.
*
* @param pRtc
* \param pucMonth If not null, the RTC alarm will month-match this value.
* \param pucDay If not null, the RTC alarm will day-match this value.
*
* \return 0 success, 1 fail to set
*/
extern int RTC_SetDateAlarm( Rtc* pRtc, uint8_t *pucMonth, uint8_t *pucDay )
{
uint32_t dwAlarm ;
dwAlarm = ((pucMonth) || (pucDay)) ? (0) : (0x01010000);
TRACE_DEBUG( "RTC_SetDateAlarm()\n\r" ) ;
/* Compute alarm field value */
if ( pucMonth )
{
dwAlarm |= RTC_CALALR_MTHEN | ((*pucMonth / 10) << 20) | ((*pucMonth % 10) << 16);
}
if ( pucDay )
{
dwAlarm |= RTC_CALALR_DATEEN | ((*pucDay / 10) << 28) | ((*pucDay % 10) << 24);
}
/* Set alarm */
pRtc->RTC_CALALR = dwAlarm ;
return (int)(pRtc->RTC_VER & RTC_VER_NVCALALR) ;
}
/**
* \brief Clear flag bits of status clear command register in the RTC.
*
* @param pRtc
* \param dwMask Bits mask of cleared events
*/
extern void RTC_ClearSCCR( Rtc* pRtc, uint32_t dwMask )
{
/* Clear all flag bits in status clear command register */
dwMask &= RTC_SCCR_ACKCLR | RTC_SCCR_ALRCLR | RTC_SCCR_SECCLR | RTC_SCCR_TIMCLR | RTC_SCCR_CALCLR ;
pRtc->RTC_SCCR = dwMask ;
}
/**
* \brief Get flag bits of status register in the RTC.
*
* @param pRtc
* \param dwMask Bits mask of Status Register
*
* \return Status register & mask
*/
extern uint32_t RTC_GetSR( Rtc* pRtc, uint32_t dwMask )
{
uint32_t dwEvent ;
dwEvent = pRtc->RTC_SR ;
return (dwEvent & dwMask) ;
}
| [
"[email protected]"
] | [
[
[
1,
437
]
]
] |
c4039ef2fe4255d1a5d7c8975c3d374a103ffdfb | d115cf7a1b374d857f6b094d4b4ccd8e9b1ac189 | /tags/pyplusplus_dev_1.0.0/unittests/data/member_variables_protected_to_be_exported.hpp | 0e0b4e81a330841f44bf76c984f5ee9da75e11a2 | [
"BSL-1.0"
] | permissive | gatoatigrado/pyplusplusclone | 30af9065fb6ac3dcce527c79ed5151aade6a742f | a64dc9aeeb718b2f30bd6a5ff8dcd8bfb1cd2ede | refs/heads/master | 2016-09-05T23:32:08.595261 | 2010-05-16T10:53:45 | 2010-05-16T10:53:45 | 700,369 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,703 | hpp | // Copyright 2004-2008 Roman Yakovenko.
// Distributed under 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)
#ifndef __member_variables_protected_to_be_exported_hpp__
#define __member_variables_protected_to_be_exported_hpp__
#include <memory>
#include <string>
#include <iostream>
namespace member_variables{
struct point{
enum color{ red, green, blue };
point()
: prefered_color( blue )
, x( -1 )
, y( 2 )
{++instance_count;}
point( const point& other )
: prefered_color( other.prefered_color )
, x( other.x )
, y( other.y )
{}
~point()
{ --instance_count; }
protected:
int x;
int y;
const color prefered_color;
static int instance_count;
static const color default_color;
};
struct bit_fields_t{
friend unsigned int get_a(const bit_fields_t& inst);
friend void set_a( bit_fields_t& inst, unsigned int new_value );
friend unsigned int get_b(const bit_fields_t& inst);
bit_fields_t()
: b(28){}
protected:
unsigned int a : 1;
unsigned int : 0;
const unsigned int b : 11;
};
unsigned int get_a(const bit_fields_t& inst);
void set_a( bit_fields_t& inst, unsigned int new_value );
unsigned int get_b(const bit_fields_t& inst);
struct array_t{
array_t(){
for( int i = 0; i < 10; ++i ){
ivars[i] = -i;
}
}
struct variable_t{
variable_t() : value(-9){}
int value;
};
int get_ivars_item( int index ){
return ivars[index];
}
protected:
const variable_t vars[3];
int ivars[10];
int ivars2[10];
};
namespace pointers{
struct tree_node_t;
struct data_t{
friend struct tree_node_t;
friend std::auto_ptr<tree_node_t> create_tree();
data_t() : value( 201 ) {}
protected:
int value;
static char* reserved;
};
struct tree_node_t{
protected:
data_t *data;
tree_node_t *left;
tree_node_t *right;
const tree_node_t *parent;
public:
tree_node_t(const tree_node_t* parent=0)
: data(0)
, left( 0 )
, right( 0 )
, parent( parent )
{}
~tree_node_t(){
std::cout << "\n~tree_node_t";
}
friend std::auto_ptr<tree_node_t> create_tree();
};
std::auto_ptr<tree_node_t> create_tree();
}
namespace reference{
enum EFruit{ apple, orange };
struct fundamental_t{
fundamental_t( EFruit& fruit, const int& i )
: m_fruit( fruit ), m_i( i )
{}
protected:
EFruit& m_fruit;
const int& m_i;
};
struct A{};
struct B {
B( A& a_ ): a( a_ ){}
protected:
A& a;
};
struct C {
C( A& a_ ): a( a_ ){}
protected:
const A& a;
};
}
namespace statics{
struct mem_var_str_t{
protected:
static std::string class_name;
public:
std::string identity(std::string x){ return x; }
};
}
namespace bugs{
struct allocator_ {
void * (*alloc) (unsigned);
void (*dispose) (void *p);
};
typedef struct allocator_ *allocator_t;
struct faulty {
protected:
allocator_t allocator;
};
}
namespace ctypes{
struct image_t{
image_t(){
data = new int[5];
for(int i=0; i<5; i++){
data[i] = i;
}
}
int* data;
static int* none_image;
};
class Andy{
protected:
Andy() : userData(NULL) {}
virtual ~Andy() {}
public:
void * userData;
};
}
}
#endif//__member_variables_protected_to_be_exported_hpp__
| [
"roman_yakovenko@dc5859f9-2512-0410-ae5c-dd123cda1f76"
] | [
[
[
1,
197
]
]
] |
8478896195c89781a61b83e269cfd4c283a68b92 | 901512f73a7ffc83849c787ab44376520a713ac1 | /narb-sw/rce/rce_clicmd.hh | c02d3e03b96c45ef4ea03f00debf9b712e4582e5 | [
"BSD-3-Clause"
] | permissive | penguin2005/NARB | 3e33316d3f378c2f9f1a660c917bdd42cac88d34 | a2fd5e01904581f91f4558f0f41ad52bbcd1ce82 | refs/heads/master | 2020-06-23T02:19:24.434895 | 2010-02-04T22:07:55 | 2010-02-04T22:07:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,247 | hh | /*
* Copyright (c) 2007
* DRAGON Project.
* University of Southern California/Information Sciences Institute.
* All rights reserved.
*
* Created by Xi Yang 2004-2007
*
* 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. Neither the name of the project 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 PROJECT 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 PROJECT 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 __RCE_CLICMD_H__
#define __RCE_CLICMD_H__
#include "rce_types.hh"
#include "event.hh"
#include "rce_cli.hh"
#include "rce_log.hh"
#include <ctype.h>
using namespace std;
#include <string>
#include <vector>
#define CMD_BUF_SIZE 512
class CLINode;
class CLICommand: public Event
{
protected:
string cmd;
vector<string> cmdv; //vector of comands
vector<string> helpv; //vector of help strings
vector<string> argv; //vector of arguments
CLINode* cli_node; //the CLI node this command is assocaited to
public:
CLICommand(char* cmd_cstr, char* help_cstr)
{
cmd = cmd_cstr;
int ret = cmdstr_to_vector(cmd_cstr, cmdv); assert (ret == 0);
ret = helpstr_to_vector(help_cstr, helpv); assert (ret == 0);
}
CLICommand(string& cmd_str, string& help_str)
{
cmd = cmd_str;
char * cmd_cstr = (char*)cmd_str.c_str();
char * help_cstr = (char*)help_str.c_str();
int ret = cmdstr_to_vector(cmd_cstr, cmdv); assert (ret == 0);
ret = helpstr_to_vector(help_cstr, helpv); assert (ret == 0);
}
CLINode * Node();
void SetNode (CLINode * node);
virtual void Run() {}
//func to take a vector of arguments and do self schedule
void Execute(vector<string>& args)
{
argv.clear();
for (int i = 0; i < args.size(); i++)
{
argv.push_back(args[i]);
}
//Do NOT SetAutoDelete for static commands.
//SetAutoDelete only for dynamically created commands.
eventMaster.Schedule(this);
}
//execute using existing args
void Execute(void)
{
//Do NOT SetAutoDelete for static commands.
//SetAutoDelete only for dynamically created commands.
eventMaster.Schedule(this);
}
//func to take a vector of arguments and do self schedule
void ExecuteNow(vector<string>& args)
{
argv.clear();
for (int i = 0; i < args.size(); i++)
{
argv.push_back(args[i]);
}
this->Run();
}
vector<string>& CmdVector() {return cmdv;}
vector<string>& HelpVector() {return helpv;}
vector<string>& ArgVector() {return argv;}
void MakeAlias (char* cs, char* cs_h) { cmdstr_to_vector(cs, cmdv); helpstr_to_vector(cs_h, helpv); }
void MakeAlias (string& s, string& s_h) { MakeAlias((char*)s.c_str(), (char*)s_h.c_str()); }
//cmdv ==> a catenated string (separated by spaces)
string CmdsToStr(int n = 0)
{
if ((cmdv.size() == 0))
return NULL;
if (n == 0)
n = cmdv.size();
string str(cmdv[0]);
for (int i = 1; i < cmdv.size() && i < n; i++)
{
str += ' ';
str += cmdv[i];
}
return str;
}
//vectors of cmdv + argv ==> a catenated string (separated by spaces)
string CmdsArgsToStr(int n = 0)
{
assert((cmdv.size() == argv.size()) || (cmdv.size() == 1 && argv.size() == 0));
assert (n <=argv.size());
if (n ==0)
n = cmdv.size();
string str(cmdv[0]);
str += ' ';
str += argv[0];
for (int i = 1; i < n; i++)
{
str += ' ';
str += cmdv[i];
str += ' ';
str += argv[i];
}
return str;
}
static int cmdstr_to_vector(char* s, vector<string> &v);
static int helpstr_to_vector(char* s, vector<string> &v);
};
#define COMMAND(class_name, cmd_cstr, help_cstr) \
class class_name: public CLICommand \
{ \
public:\
class_name(char* c_cstr, char* h_cstr):CLICommand (c_cstr, h_cstr) { }\
virtual void Run();\
};\
class_name class_name##_instance(cmd_cstr, help_cstr);\
inline void class_name::Run()
#define COMMAND_CLASS(class_name, cmd_cstr, help_cstr) \
class class_name: public CLICommand \
{ \
public:\
class_name(char* c_cstr, char* h_cstr):CLICommand (c_cstr, h_cstr) { }\
virtual void Run();\
};\
inline void class_name::Run()
#define COMMAND_DECLARE(class_name) extern class class_name class_name##_instance; \
static CLICommand* class_name##_pointer = (CLICommand*)&class_name##_instance
#endif
| [
"isiehpn@aacf9c1e-ac80-435b-8e83-6affbfa3956d"
] | [
[
[
1,
184
]
]
] |
cd524e4674c5a6c3c56f0068573199527ea93233 | 971b000b9e6c4bf91d28f3723923a678520f5bcf | /apng_label/src/InternalFrameStructure.cpp | fb0ecfb277630ed01e13638faed53245b53be8cb | [] | no_license | google-code-export/fop-miniscribus | 14ce53d21893ce1821386a94d42485ee0465121f | 966a9ca7097268c18e690aa0ea4b24b308475af9 | refs/heads/master | 2020-12-24T17:08:51.551987 | 2011-09-02T07:55:05 | 2011-09-02T07:55:05 | 32,133,292 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,295 | cpp | #include "InternalFrameStructure.h"
void fatalError(char* str)
{
fprintf(stderr, "Fatal Error: %s\n", str);
exit(1);
}
FrameWrite::FrameWrite( QMap<int,VIFrame> li , const QString File_APNG_Format )
: file(File_APNG_Format),opening(true),MainFrameCache(false)
{
FILE* newImage;
bool globalsSet = false;
png_structp png_ptr_read;
png_infop info_ptr_read;
png_structp png_ptr_write;
png_infop info_ptr_write;
png_bytep* row_pointers;
png_uint_32 bytesPerRow;
int framenr = -1;
if (li.size() > 0) {
newImage = fopen(QFile::encodeName(file), "wb");
writeSetup(&newImage, &png_ptr_write, &info_ptr_write);
if(setjmp(png_ptr_write->jmpbuf))
fatalError("something didn't work while writing");
QMapIterator<int,VIFrame> i(li);
while (i.hasNext()) {
i.next();
framenr++;
APNGwrittelStream myqtchunk(this);
VIFrame record = i.value();
QImage imageios = record.exportpic();
imageios.save(myqtchunk.device(),"PNG",1); // writes image into ba in PNG format
myqtchunk.start(); /* block to begin pointer */
qDebug() << "### writing frame from " << framenr << " from " << li.size();
qDebug() << "### rect " << record.maxframe;
qDebug() << "### rect " << imageios.width() << "x" << imageios.height();
PrepareStruct( &png_ptr_read, &info_ptr_read);
png_set_read_fn(png_ptr_read,&myqtchunk,EncoderReaderCallback);
if(setjmp(png_ptr_read->jmpbuf))
fatalError("something didn't work while reading");
png_read_info(png_ptr_read, info_ptr_read);
const uint height = imageios.height();
png_bytep *row_pointers = new png_bytep[height];
for (uint i = 0; i < height; ++i) {
row_pointers[i] = (png_bytep)imageios.scanLine(i);
}
if(!globalsSet)
{
qDebug() << "### first frame header ";
writeSetup2(png_ptr_write, info_ptr_write, png_ptr_read, info_ptr_read);
png_set_acTL(png_ptr_write, info_ptr_write, li.size(), 0);
png_write_info(png_ptr_write, info_ptr_write);
globalsSet = true;
}
png_read_image(png_ptr_read,row_pointers);
/* all other frame ..... */
png_write_frame_head(png_ptr_write, info_ptr_write, row_pointers,
imageios.width(), /* width */
imageios.height(), /* height */
0, /* x offset */
0, /* y offset */
record.play, 1000, /* delay numerator and denominator */
PNG_DISPOSE_OP_NONE, /* dispose */
0 /* blend */
);
png_write_image(png_ptr_write, row_pointers);
png_write_frame_tail(png_ptr_write, info_ptr_write);
png_destroy_read_struct(&png_ptr_read, &info_ptr_read, NULL);
myqtchunk.~APNGwrittelStream();
}
png_write_end(png_ptr_write, NULL);
png_destroy_write_struct(&png_ptr_write, &info_ptr_write);
fclose(newImage);
printf("all done\n");
}
}
void PrepareStruct( png_structp* png_ptr_read, png_infop* info_ptr_read)
{
*png_ptr_read = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(*png_ptr_read == NULL)
fatalError("unable to create read struct");
*info_ptr_read = png_create_info_struct(*png_ptr_read);
if(*info_ptr_read == NULL)
fatalError("unable to create info struct");
//////////png_init_io(*png_ptr_read, *image);
//////////png_set_sig_bytes(*png_ptr_read, 8);
}
void writeSetup(FILE** image, png_structp* png_ptr_write, png_infop* info_ptr_write)
{
if(image == NULL)
fatalError("couldn't open original png");
*png_ptr_write = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if(*png_ptr_write == NULL)
fatalError("unable to create write struct");
*info_ptr_write = png_create_info_struct(*png_ptr_write);
if(*info_ptr_write == NULL)
fatalError("unable to create write struct");
png_init_io(*png_ptr_write, *image);
}
void writeSetup2(png_structp png_ptr_write, png_infop info_ptr_write,
png_structp png_ptr_read, png_infop info_ptr_read)
{
/* IHDR */
png_uint_32 width;
png_uint_32 height;
int bit_depth;
int colour_type;
int interlace_method;
int compression_method;
int filter_method;
/* PLTE */
png_colorp palette = NULL;
int palette_size = 0;
/* gAMA */
double gamma;
/* tRNS */
png_bytep trans;
int num_trans;
png_color_16p trans_values;
/* bKGD */
png_color_16p background;
png_get_IHDR(png_ptr_read, info_ptr_read, &width, &height,
&bit_depth, &colour_type, &interlace_method,
&compression_method, &filter_method);
png_set_IHDR(png_ptr_write, info_ptr_write, width, height,
bit_depth, colour_type, interlace_method,
compression_method, filter_method);
if(png_get_valid(png_ptr_read, info_ptr_read, PNG_INFO_PLTE))
{
png_get_PLTE(png_ptr_read, info_ptr_read, &palette, &palette_size);
png_set_PLTE(png_ptr_write, info_ptr_write, palette, palette_size);
}
if(png_get_valid(png_ptr_read, info_ptr_read, PNG_INFO_gAMA))
{
png_get_gAMA(png_ptr_read, info_ptr_read, &gamma);
png_set_gAMA(png_ptr_write, info_ptr_write, gamma);
}
if(png_get_valid(png_ptr_read, info_ptr_read, PNG_INFO_tRNS))
{
png_get_tRNS(png_ptr_read, info_ptr_read, &trans, &num_trans, &trans_values);
png_set_tRNS(png_ptr_write, info_ptr_write, trans, num_trans, trans_values);
}
if(png_get_valid(png_ptr_read, info_ptr_read, PNG_INFO_bKGD))
{
png_get_bKGD(png_ptr_read, info_ptr_read, &background);
png_set_bKGD(png_ptr_write, info_ptr_write, background);
}
}
FrameWrite::~FrameWrite()
{
}
/* definition from one qt frame to play */
VIFrame::VIFrame()
{
play = 1000;
dimg = QByteArray("error");
mode = 5;
pos = 0;
bg = QColor(Qt::transparent);
point = QPoint(0,0); /* QPoint point */
}
VIFrame& VIFrame::operator=( const VIFrame& d )
{
dimg = d.dimg;
play = d.play;
mode = d.mode;
pos = d.pos;
point = d.point;
maxframe = d.maxframe;
bg = d.bg;
option = d.option;
zliblevel = d.zliblevel;
option = d.option;
colortype = d.colortype;
return *this;
}
/*
VIFrame VIFrame::operator=( const VIFrame d )
{
dimg = d.dimg;
play = d.play;
mode = d.mode;
pos = d.pos;
point = d.point;
maxframe = d.maxframe;
bg = d.bg;
option = d.option;
zliblevel = d.zliblevel;
option = d.option;
colortype = d.colortype;
return *this;
}
*/
/*
QRect maxframe;
QByteArray dimg;
uint play;
quint32 mode;
int pos;
QColor bg;
QStringList option;
QPoint point;
int zliblevel;
int colortype;
*/
QPixmap VIFrame::erno_pix()
{
maxframe = QRect(0,0,250,250);
QPixmap pError = QPixmap(maxframe.width(),maxframe.height());
pError.fill( Qt::red );
QPainter pter( &pError );
pter.setFont( QFont( "Helvetica", 8 ) );
pter.setBrush( Qt::green );
pter.drawText( 20, 12 , "Sorry is not APNG image!" );
return pError;
}
QPixmap VIFrame::pix()
{
if (dimg.size() < 1 || dimg == QByteArray("error")) {
return erno_pix();
}
QPixmap resultimage;
QByteArray daunq = qUncompress( dimg );
resultimage.loadFromData( daunq );
if (resultimage.isNull()) {
return erno_pix();
}
return resultimage;
}
QPixmap VIFrame::videopix()
{
QPixmap base = pix();
///////qDebug() << "### option ->" << option;
//////// qDebug() << "### play ->" << play;
////////qDebug() << "### rect ->" << maxframe;
///////////qDebug() << "### rect pi ->" << base.width()<< "," << base.width();
QPixmap Pvidi = QPixmap(maxframe.width(),maxframe.height());
Pvidi.fill(bg);
QPainter p( &Pvidi );
p.drawPixmap(point,base);
return Pvidi;
}
QImage VIFrame::theardpix()
{
QImage base;
QByteArray daunq = qUncompress( dimg );
base.loadFromData( daunq );
QRectF target(point.x(),point.y(),base.width(),base.height());
QImage Pvidi(maxframe.width(),maxframe.height(),QImage::Format_ARGB32);
QPainter p( &Pvidi );
p.setBrush(bg);
p.drawRect(maxframe);
p.drawImage(target,base);
return Pvidi.convertToFormat(QImage::Format_ARGB32,Qt::ColorOnly);
}
QImage VIFrame::exportpic()
{
QImage alla = videopix().toImage();
return alla.convertToFormat(QImage::Format_ARGB32,Qt::ColorOnly);
}
QByteArray VIFrame::stream()
{
return qUncompress( dimg );
}
QImage VIFrame::ipix()
{
if (dimg.size() < 1) {
return erno_pix().toImage();
}
QImage resultimage;
QByteArray daunq = qUncompress( dimg );
resultimage.loadFromData( daunq );
if (resultimage.isNull()) {
return erno_pix().toImage();
}
return resultimage;
}
void VIFrame::set_pics( QImage barcode )
{
if (barcode.isNull()) {
return;
}
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
barcode.save(&buffer,"PNG");
dimg = qCompress(bytes,9);
}
void VIFrame::set_pics( const QByteArray bytes )
{
dimg = qCompress(bytes,9);
}
void VIFrame::set_pics( const QPixmap * barcode )
{
if (barcode->isNull()) {
return;
}
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
barcode->save(&buffer,"PNG");
dimg = qCompress(bytes,9);
}
void VIFrame::set_pics( QPixmap barcode )
{
if (barcode.isNull()) {
return;
}
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
barcode.save(&buffer,"PNG");
dimg = qCompress(bytes,9);
}
| [
"ppkciz@9af58faf-7e3e-0410-b956-55d145112073"
] | [
[
[
1,
400
]
]
] |
029f6346a7cbaa59699e898cb1bcc986f7269480 | f1e7413e6a7fead7481c2ba5a188df04ee298adf | /XFS SPI/Template/ServiceBasic.cpp | 37479bf2619438cd838a02a2ded8fff1c0ae90bf | [] | no_license | lifugang/freexfs | 6b04de19d8ac01a3e5cde4ac4fd592da9275f23d | 8ecfe872f076ecef175410cbea6769407a2f78e5 | refs/heads/master | 2021-12-06T05:15:31.544997 | 2010-01-07T03:52:09 | 2010-01-07T03:52:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,907 | cpp | // ServiceBasic.cpp: implementation of the CServiceBasic class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "$$root$$.h"
#include "WorkThread.h"
#include "ServiceBasic.h"
#include "Xfsconf.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
extern CWorkThread *g_pDefaultThread;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CServiceBasic::CServiceBasic()
{
m_strAppID = "";
m_dwTimeOut = 0;
m_dwTraceLevel = 0;
m_pServiceThread = 0;
m_hWND = 0;
m_dwSrvcVersionsRequired = 0;
m_lpSrvcVersion = 0; // no delete
m_lpSPIVersion = 0; // no delete
m_lpRequestID = 0;
m_bAutoDeleteRequestID = FALSE;
m_hService = 0;
m_strLogicalName = "";
m_hResult = 0;
m_dwCommand = 0;
m_lpCmdData = 0;
m_dwCategory = 0;
m_lpQueryDetails = 0;
m_lppResult = 0;
m_hWndReg = 0;
m_dwEventClass = 0;
m_hLib= 0;
}
CServiceBasic::~CServiceBasic()
{
}
BOOL CServiceBasic::LoadSPI(CString strPath)
{
return TRUE;
}
CString CServiceBasic::FindSPIPath(CString strLogicalService)
{
DWORD dwResult = 0;
HKEY hKeyLogicalService;
HRESULT hr = WFMCreateKey(WFS_CFG_USER_DEFAULT_XFS_ROOT,
"LOGICAL_SERVICES", //lpszSubKey,
&hKeyLogicalService,&dwResult); //phkResult, lpdwDisposition )
if(hr != WFS_SUCCESS) return "";
HKEY hKeyTarget;
hr = WFMCreateKey(hKeyLogicalService,
strLogicalService.GetBuffer(0), //lpszSubKey,
&hKeyTarget,&dwResult); //phkResult, lpdwDisposition )
if(hr != WFS_SUCCESS) return "";
if(dwResult == WFS_CFG_CREATED_NEW_KEY)
{
WFMDeleteKey(hKeyLogicalService,strLogicalService.GetBuffer(0));
return "";
}
char buf[2048];
DWORD len = 2048;
hr = WFMQueryValue (hKeyTarget,"provider",buf, &len);
if(hr != WFS_SUCCESS) return "";
buf[len] = 0;
CString strProvider = buf;
HKEY hKeyServiceProviders;
hr = WFMCreateKey(WFS_CFG_MACHINE_XFS_ROOT,
"SERVICE_PROVIDERS", //lpszSubKey,
&hKeyServiceProviders,&dwResult);
if(hr != WFS_SUCCESS) return "";
HKEY hKeyTarget1;
hr = WFMCreateKey(hKeyServiceProviders,
strProvider.GetBuffer(0), //lpszSubKey,
&hKeyTarget1,&dwResult);
if(hr != WFS_SUCCESS) return "";
if(dwResult == WFS_CFG_CREATED_NEW_KEY)
{
WFMDeleteKey (hKeyServiceProviders,strProvider.GetBuffer(0));
return "";
}
len = 2048;
hr = WFMQueryValue (hKeyTarget1,"dllname",buf, &len);
if(hr != WFS_SUCCESS) return "";
buf[len] = 0;
CString strOut = buf;
return strOut;
}
CWorkThread * CServiceBasic::GetThread()
{
return g_pDefaultThread;
}
void CServiceBasic::Destroy()
{
if(m_bAutoDeleteRequestID && m_lpRequestID) delete m_lpRequestID;
delete this;
}
| [
"proj.ni@469b34be-d976-11de-8d17-8328ca00869f"
] | [
[
[
1,
129
]
]
] |
634f94b6e8c33ba6953f8c42b801c16ce166099f | da48afcbd478f79d70767170da625b5f206baf9a | /tbmessage/src/tbmessage.cpp | fc36f843b0b28b19d9a1157908008d61bf864420 | [] | no_license | haokeyy/fahister | 5ba50a99420dbaba2ad4e5ab5ee3ab0756563d04 | c71dc56a30b862cc4199126d78f928fce11b12e5 | refs/heads/master | 2021-01-10T19:09:22.227340 | 2010-05-06T13:17:35 | 2010-05-06T13:17:35 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,939 | cpp |
// tbmessage.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "tbmessage.h"
#include "MainDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CtbmsgApp
BEGIN_MESSAGE_MAP(CtbmsgApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CtbmsgApp 构造
CtbmsgApp::CtbmsgApp()
{
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CtbmsgApp 对象
CtbmsgApp theApp;
// CtbmsgApp 初始化
BOOL CtbmsgApp::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
CoInitialize( NULL );
//CtbmsgDlg dlg;
CMainDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 在此放置处理何时用
// “确定”来关闭对话框的代码
}
else if (nResponse == IDCANCEL)
{
// TODO: 在此放置处理何时用
// “取消”来关闭对话框的代码
}
CoUninitialize();
// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
// 而不是启动应用程序的消息泵。
return FALSE;
}
| [
"[email protected]@d41c10be-1f87-11de-a78b-a7aca27b2395"
] | [
[
[
1,
82
]
]
] |
ff42f98bcbb7e8ae372eb56fececf7c832a5cecc | 0046bde1a59a57381e8fbfc14747824c08fa5e81 | /animation_main.cpp | 9bdf76a3c814c433a80f7d80c4c2cf8f384fc224 | [] | no_license | m3ngu/graphics | dc66ad574855f6a6ee5cacaef8a42c3cddce5092 | 15918bd60585deb8a615b089b41d2199a12e9401 | refs/heads/master | 2020-05-18T16:08:45.287103 | 2008-11-10T04:52:54 | 2008-11-10T04:52:54 | 32,230,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,194 | cpp | #include <stdio.h>
#if defined(__APPLE__)
#include <GLUT/glut.h>
#else
#include <gl/glut.h>
#endif
#include "main.h"
#include "Transform.h"
#include "tga.h"
int amount;
vec3 eye;
vec3 up;
vec3 lookAt;
bool updateLight0, updateLight1;
int w, h;
unsigned int nindices;
unsigned int *indices;
float xMax, yMax, zMax;
/*For animation of the ants*/
GLdouble antLoc = 0.0;
GLint animate = 0;
GLfloat ant_x_pos = 0.0;
GLfloat ant_y_pos = 20.0;
GLfloat ant_z_pos = 0.0;
int ant_counter = 1;
int ant_flag = 0;
int pause_flag = 0;
const GLfloat PI = 3.1415926f;
const GLfloat RAD_TO_DEG = 180.0 / PI;
const GLfloat TWO_PI = 2.0 * PI;
/******************************/
/*For animation of grass*/
float grassAngle = 0.0;
int grass_flag = 0;
int grass_counter = 1;
/************************/
GLuint TexID1,
TexID2,
TexIDSquirrel,
TexIDShroom,
TexIDWood,
TexIDCatFur; // Handles to our textures
objects objCat,
objSquirrel,
objShroom,
objFlwr1,
objFlwr2,
objButt,
objPebble,
objAnt,
objBench; //Stores all the data for the loaded object
float center[3] = { 2.0, 2.0, 0.3};
/*Random points
**for pebbles**
***************/
float pebbleArray[100][3];
float pebbleScaleArray[100][3];
/*Random points
*for grass blade
***************/
float grassArray[150][3];
/******
*Nurbs*
******/
GLfloat ctlpoints[4][4][3];
GLUnurbsObj *theNurb;
GLuint treeStump; //The tree stump
GLuint pebble; //The pebble
/********
* Main *
********/
int main(int argc, char* argv[]) {
// Load GLUT
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutCreateWindow("HW3: Helper Scene");
// Initialize
init();
// Register functions
glutDisplayFunc(display);
glutSpecialFunc(specialKey);
glutKeyboardFunc(keyboard);
glutReshapeFunc(reshape);
glutReshapeWindow(600, 400);
// Print instructions to console
printHelp();
// Start main loop
glutMainLoop();
return 0;
}
void grassBlade(float x, float y, float height, float anglex, float anglez)
{
float ow = 0.25f;
float od = 0.10f;
float oh = height;
vec3* v1 = new vec3(0.0f, 0.0f, oh );
vec3* v2 = new vec3(-ow , -od , 0.0f);
vec3* v3 = new vec3( ow , -od , 0.0f);
vec3* v4 = new vec3( ow , -od , 0.0f);
vec3* v5 = new vec3( ow , od , 0.0f);
vec3* v6 = new vec3( ow , od , 0.0f);
vec3* v7 = new vec3(-ow , od , 0.0f);
vec3* v8 = new vec3(-ow , od , 0.0f);
vec3* v9 = new vec3(-ow , -od , 0.0f);
vec3 n1; cross(n1, *v2 - *v1, *v3 - *v1); n1.normalize();
vec3 n2; cross(n2, *v4 - *v1, *v5 - *v1); n2.normalize();
vec3 n3; cross(n3, *v6 - *v1, *v7 - *v1); n3.normalize();
vec3 n4; cross(n4, *v8 - *v1, *v9 - *v1); n4.normalize();
glPushMatrix();
glTranslatef(x, y, 0.0f);
glRotatef(anglez, 0.0f, 0.0f, 1.0f);
glRotatef(anglex, 1.0f, 0.0f, 0.0f);
//glEnable(GL_COLOR_MATERIAL);
//float kd[3] = {0.140397f, 0.283725f, 0.0654061f};
//float kd[3] = {0.430477f, 0.464616f, 0.209123f};
float kd[3] = {0.0f, 0.75f, 0.0f};
float ks[3] = {0.25f,0.25f,0.25f};
glMaterialfv(GL_FRONT, GL_DIFFUSE, kd);
glMaterialfv(GL_FRONT, GL_AMBIENT, kd);
glMaterialfv(GL_FRONT, GL_SPECULAR, ks);
glMaterialf(GL_FRONT, GL_SHININESS, 120.0f); // / 1000.0f * 128.0f
glBegin(GL_TRIANGLES); // Start Drawing The Pyramid
glColor3f(0.0f,1.0f,0.0f); // Green
glNormal3f( n1.x, n1.y, n1.z);
glVertex3f( v1->x, v1->y, v1->z); // Top Of Triangle (Front)
glVertex3f( v2->x, v2->y, v2->z); // Left Of Triangle (Front)
glVertex3f( v3->x, v3->y, v3->z); // Right Of Triangle (Front)
glNormal3f( n2.x, n2.y, n2.z);
glVertex3f( v1->x, v1->y, v1->z); // Top Of Triangle (Right)
glVertex3f( v4->x, v4->y, v4->z); // Left Of Triangle (Right)
glVertex3f( v5->x, v5->y, v5->z); // Right Of Triangle (Right)
glNormal3f( n3.x, n3.y, n3.z);
glVertex3f( v1->x, v1->y, v1->z); // Top Of Triangle (Back)
glVertex3f( v6->x, v6->y, v6->z); // Left Of Triangle (Back)
glVertex3f( v7->x, v7->y, v7->z); // Right Of Triangle (Back)
glNormal3f( n4.x, n4.y, n4.z);
glVertex3f( v1->x, v1->y, v1->z); // Top Of Triangle (Left)
glVertex3f( v8->x, v8->y, v8->z); // Left Of Triangle (Left)
glVertex3f( v9->x, v9->y, v9->z); // Right Of Triangle (Left)
glEnd();
//glDisable(GL_COLOR_MATERIAL);
glPopMatrix();
}
/************************
*Random Object Generator*
*************************/
void randomPoints(float randArray[][3], int xStart, int xEnd, int yStart, int yEnd, int zStart, int zEnd,
int numberOfPoints, bool symm)
{
for(int i = 0; i < numberOfPoints; i++)
{
float xrandom = 0.0, yrandom = 0.0, zrandom = 0.0;
int xLimit = 0, yLimit = 0, zLimit = 0;
if(xStart > xEnd)
xLimit = xStart - xEnd;
else
xLimit = xEnd - xStart;
if(yStart > yEnd)
yLimit = yStart - yEnd;
else
yLimit = yEnd - yStart;
if(zStart > zEnd)
zLimit = zStart - zEnd;
else
zLimit = zEnd - zStart;
if(symm == true)
{
if(xLimit != 0)
xrandom = xStart + float(rand()%xLimit)+((float)rand()/10000);
if(yLimit != 0)
yrandom = yStart + float(rand()%yLimit)+((float)rand()/10000);
if(zLimit != 0)
zrandom = zStart + float(rand()%zLimit)+((float)rand()/10000);
if(rand()%3 == 0)
xrandom = -xrandom;
if(rand()%3 == 0)
yrandom = -yrandom;
if(rand()%3 == 0)
zrandom = -zrandom;
}
else
{
if(xLimit != 0)
xrandom = xStart + float(rand()%xLimit);
if(yLimit != 0)
yrandom = yStart + float(rand()%yLimit);
if(zLimit != 0)
zrandom = zStart + float(rand()%zLimit);
}
randArray[i][0] = xrandom;
randArray[i][1] = yrandom;
randArray[i][2] = zrandom;
}
}
/******
*Nurbs*
*******/
/*Initialize*/
void init_surface(void)
{
int u, v;
for (u = 0; u < 4; u++)
{
for (v = 0; v < 4; v++)
{
ctlpoints[u][v][0] = u;
ctlpoints[u][v][1] = (u + v);
if (u == 1 && v == 2)
{
ctlpoints[u][v][2] = 4.5;
ctlpoints[u][v][2] = 5;
}
}
}
}
/*Display Nurbs*/
void drawNurbs(GLUnurbsObj *theNurbObj, GLfloat knots[], GLuint texture, GLfloat ctlpoints[][4][3])
{
gluBeginSurface(theNurbObj);
gluNurbsSurface(theNurbObj, 8, knots,
8, knots,
4 * 3,
3,
&ctlpoints[0][0][0],
4, 4, GL_MAP2_TEXTURE_COORD_2);
gluNurbsSurface(theNurbObj, 8, knots,
8, knots,
4 * 3,
3,
&ctlpoints[0][0][0],
4, 4, GL_MAP2_NORMAL);
if(texture > 0) {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
}
gluNurbsSurface(theNurbObj,
8, knots,
8, knots,
4 * 3,
3,
&ctlpoints[0][0][0],
4, 4,
GL_MAP2_VERTEX_3);
gluEndSurface(theNurbObj);
if(texture > 0)
glDisable(GL_TEXTURE_2D);
}
/********
* Init *
********/
void init() {
eye = vec3(0, -10 , 5 );
//eye = vec3(0, 20 , 80 );
lookAt = vec3(0, 0 , 5 );
up = vec3(0, 0 , 1 );
amount = 5;
xMax = 200.0f;
yMax = 200.0f;
zMax = 100.0f;
// Load the textures
TexID1 = LoadTexture("Textures/Soil2.tga");
TexID2 = LoadTexture("Textures/sky.tga");
TexIDShroom = LoadTexture("Textures/shroomTex13.tga");
TexIDSquirrel = LoadTexture("Textures/Squirrel_diffuse.tga");
TexIDWood = LoadTexture("Textures/wood256.tga");
TexIDCatFur = LoadTexture("Textures/cat_fur.tga");
/*LoadObject("Objects/cat.obj" , objCat , center , 0.1 );
LoadObject("Objects/shroom.obj" , objShroom , center , 0.2 );
LoadObject("Objects/squirrel.obj" , objSquirrel , center , 1 );
LoadObject("Objects/toonflower1.obj" , objFlwr1 , center , 0.1 );
LoadObject("Objects/toonflower4.obj" , objFlwr2 , center , 0.1 );
LoadObject("Objects/BUTT_M_file.obj" , objButt , center , 0.75 );
LoadObject("Objects/GardenSeat1.obj" , objBench , center , 0.03 );*/
//LoadObject("Objects/pebble1.obj" ,objPebble, center , 0.2);
//LoadObject("Objects/Ant.obj" ,objAnt, center , 0.2);
/*Making the wooden tree stump - hand drawn*/
GLUquadricObj * cyl;
cyl = gluNewQuadric() ;
treeStump = glGenLists(1);
glNewList(treeStump, GL_COMPILE);
gluQuadricTexture(cyl, GL_TRUE);
gluDisk(cyl,0,2,100,5);
glTranslatef(0.0,0.0,-3.0);
gluCylinder(cyl, 2, 2, 3, 100, 5);
gluDisk(cyl,0,2,100,5);
//glutSolidSphere(0.191, polySubdivisions, polySubdivisions);
glEndList();
/*Make pebbles*/
GLUquadricObj *sphere = gluNewQuadric();
pebble = glGenLists(2);
glNewList(pebble, GL_COMPILE);
gluSphere(sphere,0.5,15,15);
glEndList();
/*Initialize random pebble position*/
//randomPoints(pebbleArray,100,50,0,100,true);
randomPoints(pebbleArray,0,100,0,50,0,0,100,true);
/*Initialize random grass position*/
randomPoints(grassArray,5,50,10,50,0,0,150,true);
/*Make ant*/
glutWireSphere(2,15,15);
/*Nurb curves*/
init_surface();
theNurb = gluNewNurbsRenderer();
gluNurbsProperty(theNurb, GLU_SAMPLING_TOLERANCE, 25.0);
gluNurbsProperty(theNurb, GLU_DISPLAY_MODE, GLU_FILL);
glEnable(GL_DEPTH_TEST);
glEnableClientState(GL_VERTEX_ARRAY);
glEnable(GL_TEXTURE_2D);
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
}
//printf("ant_counter is %d",ant_counter);
void animation(void)
{
/*antLoc = antLoc + 0.005 ;
if (antLoc > 0.5)
antLoc = -0.5 ;*/
//printf("grass angle is %f\n",grassAngle);
if(grassAngle > 25.0)
{
grass_flag = 1;
}
if(grass_flag == 1)
{
grassAngle -= 0.2;
if(grassAngle <= 0)
grass_flag = 2;
}
else if(grass_flag == 2)
{
/*grassAngle -= 0.2;
if(grassAngle < -25.0)
grass_flag = 0;*/
if(grass_counter%50 == 0)
grass_flag = 0;
else
grass_counter++;
}
else
{
grass_counter = 1;
grassAngle += 0.2f;
}
/*Ant Animation*/
if(ant_counter%50 == 0)
{
antLoc += 0.005*8;
pause_flag = 1;
}
//printf("the antLoc is %f and the if stmt is %f\n",antLoc,0.005*4);
if((antLoc >= 0.005*10 && antLoc <= 0.005*12) || (antLoc >= 0.005*70 && antLoc <= 0.005*72)
|| (antLoc >= 0.005*300 && antLoc <= 0.005*302))
{
ant_counter++;
ant_flag = 1;
}
if(pause_flag == 1)
{
antLoc -= 0.005*8;
pause_flag = 0;
ant_counter = 1;
ant_flag = 0;
}
if(ant_flag == 0)
{
ant_x_pos = 20.0 * sin(antLoc);
ant_y_pos = 20.0 * cos(antLoc);
antLoc += 0.005f;
if (antLoc > TWO_PI)
antLoc -= TWO_PI;
}
glutPostRedisplay() ;
}
/***********
* Display *
***********/
void display() {
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt( eye.x, eye.y , eye.z,
lookAt.x, lookAt.y , lookAt.z,
up.x, up.y , up.z);
/*************\
| Horizon/Sky |
\*************/
skybox(xMax, yMax, zMax);
/*
// Squirrel
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, objSquirrel.vertexdata);
glDrawElements( GL_TRIANGLES, objSquirrel.nindices, GL_UNSIGNED_INT, objSquirrel.indices );
glDisableClientState(GL_VERTEX_ARRAY);
*/
///*************\
//| Shrooms |
//\*************/
//float shroom_center[3] = {-5.0, 0.0, 4.0};
//glPushMatrix();
// glTranslated( shroom_center[0], shroom_center[1], shroom_center[2]);
// glRotated(90.0, 1.0, 0.0, 0.0);
// //Initialize and bind texture
// drawObject(objShroom, TexIDShroom, 1);
//glPopMatrix();
//glPushMatrix();
// glTranslated( shroom_center[0]+7, shroom_center[1]+7, shroom_center[2]);
// glRotated(90.0, 0.0, 0.0, 1.0);
// glRotated(90.0, 1.0, 0.0, 0.0);
// //Initialize and bind texture
// drawObject(objShroom, TexIDShroom, 1);
//glPopMatrix();
//glPushMatrix();
// glTranslated( shroom_center[0]-15, shroom_center[1]+12, shroom_center[2]);
// glRotated(180.0, 0.0, 0.0, 1.0);
// glRotated(90.0, 1.0, 0.0, 0.0);
// //Initialize and bind texture
// drawObject(objShroom, TexIDShroom, 1);
//glPopMatrix();
///*************\
//| Flowers |
//\*************/
//glPushMatrix();
// glTranslated(20,5,10);
// glRotated(90.0, 1.0, 0.0, 0.0);
// //Initialize and bind texture
// glColor3d(0.0, 0.25, 0.0);
// drawObject(objFlwr1, 0, 0);
//glPopMatrix();
//glPushMatrix();
// glTranslated(20,20,10);
// glRotated(90.0, 1.0, 0.0, 0.0);
// //Initialize and bind texture
// drawObject(objFlwr2, 0, 0);
//glPopMatrix();
///*************\
//| Butt |
//\*************/
//glPushMatrix();
// glTranslated(2,-2 ,12);
// glRotated(75.0, 1.0, 0.0, 0.0);
// glRotated(-135.0, 0.0, 0.0, 1.0);
// //Initialize and bind texture
// glColor3d(1.0, 1.0, 0.0);
// drawObject(objButt, 0, 0);
//glPopMatrix();
///*************\
//| Bench |
//\*************/
//glPushMatrix();
// glTranslated(-40 , 40 , 20);
// glRotated(45.0, 0.0, 0.0, 1.0);
// //Initialize and bind texture
// drawObject(objBench, TexIDWood, 1);
//glPopMatrix();
///**************\
//| Tree Stump |
//\**************/
//glPushMatrix();
// glTranslated(50 , 50 , 20);
// glScaled(8, 8, 8);
// glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
// glBindTexture(GL_TEXTURE_2D, TexIDWood);
// glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
// glCallList(treeStump);
// glDisable(GL_TEXTURE_2D);
//glPopMatrix();
///**************\
//| Cat |
//\**************/
//glPushMatrix();
// glTranslated(50 , 50 , 35);
// glRotated(90.0, 0.0, 0.0, 1.0);
// //glScaled(20, 20, 20);
// //Initialize and bind texture
// drawObject(objCat, TexIDCatFur, 1);
//glPopMatrix();
/***************
*Ants Animation*
***************/
glPushMatrix();
glColor3f(1.0,1.0,1.0);
//glTranslatef(antLoc, 0.0, 0.0) ;
glTranslatef(ant_x_pos, ant_y_pos, ant_z_pos);
glRotatef(RAD_TO_DEG * antLoc, 0.0, 0.0, -1.0);
glRotatef(270.0, 0.0, 0.0, 1.0);
//glScaled(20, 20, 20);
//Initialize and bind texture
drawObject(objAnt, 0,0 );
glPopMatrix();
/*Scatter the pebbles all over*/
for(int i=0; i < 100; i++)
{
glPushMatrix();
glColor3f(0.0f, 0.0f, 0.0f);
if(i%5 == 0)
glScalef(8,4,4);
else if(i%4 == 0)
glScalef(4,4,4);
else if(i%3 == 0)
glScalef(6,4,3);
else if(i%2 == 0)
glScalef(2,4,2);
glTranslatef(pebbleArray[i][0],pebbleArray[i][1],0);
glCallList(pebble);
//drawObject(objPebble, 0, 0);
glPopMatrix();
glFlush();
}
/*************\
| Grass |
\*************/
//glPushMatrix();
//glRotatef(grassAngle,0,1,0);
//grassBlade(0.0f, 0.0f, 10.0f, 0.0f, 0.0f);
//glPopMatrix();
//glPushMatrix();
//glTranslatef(1.0,1.0,0.0);
//glRotatef(grassAngle,0,1,0);
//glTranslatef(-1.0,-1.0,0.0);
//grassBlade(1.0f, 1.0f, 12.0f, 10.0f, 0.0f);
//glPopMatrix();
//
//glPushMatrix();
//glTranslatef(-1.0f, 2.0f,0.0);
//glRotatef(grassAngle,0,1,0);
//glTranslatef(1.0f, -2.0f,0.0);
//grassBlade(-1.0f, 2.0f, 8.0f, 10.0f, 10.0f);
//glPopMatrix();
int grass_choice = 0;
for(int grass_count = 0; grass_count < 150; grass_count++)
{
glPushMatrix();
glTranslatef(grassArray[grass_count][0], grassArray[grass_count][1],0.0);
glRotatef(grassAngle,0,1,0);
glTranslatef(-grassArray[grass_count][0], -grassArray[grass_count][1],0.0);
//grassBlade(-1.5f, 0.25f, 15.0f, 30.0f, 70.0f);
if(grass_choice == 4)
grass_choice = 0;
printf("the grass_choice is %d\n",grass_choice);
printf("the grass_count is %d\n",grass_count);
if(grass_choice == 0)
grassBlade(grassArray[grass_count][0], grassArray[grass_count][1], 8.0f, 10.0f, 10.0f);
else if(grass_choice == 1)
grassBlade(grassArray[grass_count][0], grassArray[grass_count][1], 15.0f, 30.0f, 70.0f);
else if(grass_choice == 2)
grassBlade(grassArray[grass_count][0], grassArray[grass_count][1], 12.0f, 10.0f, 0.0f);
else if(grass_choice == 3)
grassBlade(grassArray[grass_count][0], grassArray[grass_count][1], 10.0f, 0.0f, 0.0f);
grass_choice++;
glPopMatrix();
}
//glPopMatrix();
/******************
*Hills using Nurbs*
******************
GLfloat knots[8] = {0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0};
glPushMatrix();
glColor3f(0.2f, 0.1f, 0.0f);
glTranslatef(4.5,-4.0,2.0);
glRotatef(105.0, 0.0,0.0,1.);
glScalef (3, 3, 4);
drawNurbs(theNurb,knots,-1,ctlpoints);
glPopMatrix();
*/
glutSwapBuffers();
glFlush();
}
/**********
* Skybox *
**********/
void skybox(float width, float depth, float height) {
float bottom = 0.0f;
// Store the current matrix
glPushMatrix();
glTranslatef( eye.x, eye.y, bottom);
//glPushAttrib(GL_ENABLE_BIT);
//glDisable(GL_DEPTH_TEST);
//glDisable(GL_LIGHTING);
//glDisable(GL_BLEND);
// Ground
//glBindTexture(GL_TEXTURE_2D, TexID1);
//glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glColor3f(0.2f, 0.1f, 0.0f);
glBegin( GL_QUADS );
//glTexCoord2d( 0.0, 0.0);
glVertex3d(-width,-depth, bottom);
//glTexCoord2d( 10.0, 0.0);
glVertex3d( width,-depth, bottom);
//glTexCoord2d( 10.0, 5.0);
glVertex3d( width, depth, bottom);
//glTexCoord2d( 0.0, 5.0);
glVertex3d(-width, depth, bottom);
glEnd();
glFlush();
glEnable(GL_TEXTURE_2D);
// Sky - front
glBindTexture(GL_TEXTURE_2D, TexID2);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBegin( GL_QUADS );
glTexCoord2d(0.0,0.0); glVertex3d(-width, depth, bottom);
glTexCoord2d(1.0,0.0); glVertex3d(-width, depth, height + eye.z);
glTexCoord2d(1.0,1.0); glVertex3d( width, depth, height + eye.z);
glTexCoord2d(0.0,1.0); glVertex3d( width, depth, bottom);
glEnd();
// Sky - left
glBindTexture(GL_TEXTURE_2D, TexID2);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBegin( GL_QUADS );
glTexCoord2d(0.0,0.0); glVertex3d(-width, depth, bottom);
glTexCoord2d(1.0,0.0); glVertex3d(-width, depth, height + eye.z);
glTexCoord2d(1.0,1.0); glVertex3d(-width, -depth, height + eye.z);
glTexCoord2d(0.0,1.0); glVertex3d(-width, -depth, bottom);
glEnd();
// Sky - right
glBindTexture(GL_TEXTURE_2D, TexID2);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBegin( GL_QUADS );
glTexCoord2d(0.0,0.0); glVertex3d( width, depth, bottom);
glTexCoord2d(1.0,0.0); glVertex3d( width, depth, height + eye.z);
glTexCoord2d(1.0,1.0); glVertex3d( width, -depth, height + eye.z);
glTexCoord2d(0.0,1.0); glVertex3d( width, -depth, bottom);
glEnd();
// Sky - back
glBindTexture(GL_TEXTURE_2D, TexID2);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBegin( GL_QUADS );
glTexCoord2d(0.0,0.0); glVertex3d(-width, -depth, bottom);
glTexCoord2d(1.0,0.0); glVertex3d(-width, -depth, height + eye.z);
glTexCoord2d(1.0,1.0); glVertex3d( width, -depth, height + eye.z);
glTexCoord2d(0.0,1.0); glVertex3d( width, -depth, bottom);
glEnd();
// Sky - top
glBindTexture(GL_TEXTURE_2D, TexID2);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glBegin( GL_QUADS );
glTexCoord2d( 0.0, 0.0); glVertex3d(-width,-depth, height + eye.z);
glTexCoord2d( 1.0, 0.0); glVertex3d( width,-depth, height + eye.z);
glTexCoord2d( 1.0, 1.0); glVertex3d( width, depth, height + eye.z);
glTexCoord2d( 0.0, 1.0); glVertex3d(-width, depth, height + eye.z);
glEnd();
// Restore enable bits and matrix
//glPopAttrib();
glDisable(GL_TEXTURE_2D);
glPopMatrix();
}
/***************
* LoadTexture *
***************/
GLuint LoadTexture(char *TexName) {
TGAImg Img; // Image loader
GLuint Texture;
// Load our Texture
if(Img.Load(TexName)!=IMG_OK)
return -1;
glGenTextures(1,&Texture); // Allocate space for texture
glBindTexture(GL_TEXTURE_2D,Texture); // Set our Tex handle as current
// Create the texture
if(Img.GetBPP()==24)
glTexImage2D(GL_TEXTURE_2D,0,3,Img.GetWidth(),Img.GetHeight(),0,
GL_RGB,GL_UNSIGNED_BYTE,Img.GetImg());
else if(Img.GetBPP()==32)
glTexImage2D(GL_TEXTURE_2D,0,4,Img.GetWidth(),Img.GetHeight(),0,
GL_RGBA,GL_UNSIGNED_BYTE,Img.GetImg());
else
return -1;
// Build Mipmaps (builds different versions of the picture for distances - looks better)
//gluBuild2DMipmaps(GL_TEXTURE_2D, 3, Img.GetWidth(), Img.GetHeight(), GL_RGB, GL_UNSIGNED_BYTE, Img.GetImg());
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
//glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR_MIPMAP_LINEAR);
// Specify filtering and edge actions
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT); //GL_CLAMP
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
return Texture;
}
/**************
* DrawObject *
**************/
void drawObject(objects obj, GLuint TexID, int texture) {
//Initialize and bind texture
if(texture > 0) {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, TexID);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
//Get the texture on the object
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer( 2, GL_FLOAT, 0, obj.texcoords );
}
//Get the vertex pointer enabled
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, obj.vertexdata);
glDrawElements( GL_TRIANGLES, obj.nindices, GL_UNSIGNED_INT, obj.indices );
//Disable the vertex, texture array and texture
glDisableClientState(GL_VERTEX_ARRAY);
if(texture > 0) {
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
}
}
/***********
* Reshape *
***********/
void reshape(int width, int height){
w = width;
h = height;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(90.0f, w/(float)h, 1.0f, 600.0f);
glViewport(0, 0, w, h);
}
/*************
* PrintHelp *
*************/
void printHelp() {
printf("press '+' or '-' to change the amount of rotation that\noccurs with each arrow press.\n");
}
/************
* Keyboard *
************/
void keyboard(unsigned char key, int x, int y) {
switch(key) {
case '+':
amount++;
printf("amount set to %d\n", amount);
break;
case '-':
amount--;
printf("amount set to %d\n", amount);
break;
case 'w':
Transform::forward(static_cast<float>(amount), eye, lookAt, xMax, yMax, zMax);
break;
case 's':
Transform::forward(static_cast<float>(-amount), eye, lookAt, xMax, yMax, zMax);
break;
case 'a':
Transform::sideways(static_cast<float>(-amount), eye, lookAt, up, xMax, yMax);
break;
case 'd':
Transform::sideways(static_cast<float>(amount), eye, lookAt, up, xMax, yMax);
break;
case 'c':
Transform::straighten( eye, lookAt, up);
break;
case 'm':
Transform::toggleMapView( eye, lookAt, up);
break;
case 'p':
animate = !animate ;
if (animate)
glutIdleFunc(animation) ;
else
glutIdleFunc(NULL) ;
break ;
}
glutPostRedisplay();
}
/**************
* SpecialKey *
**************/
void specialKey(int key, int x, int y) {
switch(key) {
case GLUT_KEY_LEFT: //left
Transform::left(static_cast<float>(amount), eye, lookAt, up);
break;
case GLUT_KEY_UP: //up
Transform::up(static_cast<float>(amount), eye, lookAt, up);
break;
case GLUT_KEY_RIGHT: //right
Transform::left(static_cast<float>(-amount), eye, lookAt, up);
break;
case GLUT_KEY_DOWN: //down
Transform::up(static_cast<float>(-amount), eye, lookAt, up);
break;
}
up.normalize();
glutPostRedisplay();
}
| [
"Swati.Kumar.A@670f90bc-9716-11dd-a8fd-1f832368400c"
] | [
[
[
1,
926
]
]
] |
a3bcf2571324d30b0a241be9e757bf876c8166e6 | b308f1edaab2be56eb66b7c03b0bf4673621b62f | /Code/Game/GameDll/ItemParams.cpp | 4f37dc6543c64309660ec1423a567e1daf5f4e67 | [] | no_license | blockspacer/project-o | 14e95aa2692930ee90d098980a7595759a8a1f74 | 403ec13c10757d7d948eafe9d0a95a7f59285e90 | refs/heads/master | 2021-05-31T16:46:36.814786 | 2011-09-16T14:34:07 | 2011-09-16T14:34:07 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 22,782 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2004.
-------------------------------------------------------------------------
$Id$
$DateTime$
-------------------------------------------------------------------------
History:
- 30:8:2005 12:33 : Created by Márcio Martins
*************************************************************************/
#include "StdAfx.h"
#include "Item.h"
#include "ItemSharedParams.h"
#include "ItemParamReader.h"
#include "Game.h"
#include <ISound.h>
//------------------------------------------------------------------------
bool CItem::ReadItemParams(const IItemParamsNode *root)
{
if (!root)
{
GameWarning("Warning: ItemParams for item <%s> NULL", GetEntity()->GetName());
return false;
}
const IItemParamsNode *params = root->GetChild("params");
const IItemParamsNode *geometry = root->GetChild("geometry");
const IItemParamsNode *actions = root->GetChild("actions");
const IItemParamsNode *layers = root->GetChild("layers");
const IItemParamsNode *accessories = root->GetChild("accessories");
const IItemParamsNode *damagelevels = root->GetChild("damagelevels");
const IItemParamsNode *accessoryAmmo = root->GetChild("accessoryAmmo");
if (params) ReadParams(params);
if (actions) ReadActions(actions);
if (geometry) ReadGeometry(geometry);
if (layers) ReadLayers(layers);
if (accessories) ReadAccessories(accessories);
if (damagelevels) ReadDamageLevels(damagelevels);
if (accessoryAmmo) ReadAccessoryAmmo(accessoryAmmo);
m_sharedparams->SetValid(true);
return true;
}
#define ReadValue(hold, param) reader.Read(#param, hold.param)
#define ReadValueEx(hold, name, param) reader.Read(#name, hold.param)
//------------------------------------------------------------------------
bool CItem::ReadParams(const IItemParamsNode *params)
{
if(!m_sharedparams->Valid())
{
CItemParamReader reader(params);
ReadValue(m_sharedparams->params, selectable);
ReadValue(m_sharedparams->params, droppable);
ReadValue(m_sharedparams->params, pickable);
ReadValue(m_sharedparams->params, mountable);
ReadValue(m_sharedparams->params, usable);
ReadValue(m_sharedparams->params, giveable);
ReadValue(m_sharedparams->params, unique);
ReadValue(m_sharedparams->params, arms);
ReadValue(m_sharedparams->params, drawNearestFP);
ReadValue(m_sharedparams->params, two_hand);
ReadValue(m_sharedparams->params, mass);
ReadValue(m_sharedparams->params, fly_timer);
ReadValue(m_sharedparams->params, drop_impulse);
ReadValue(m_sharedparams->params, drop_impulse_pos);
ReadValue(m_sharedparams->params, drop_angles);
ReadValue(m_sharedparams->params, pose);
ReadValue(m_sharedparams->params, select_override);
ReadValueEx(m_sharedparams->params, attachment_right, attachment[eIH_Right]);
ReadValueEx(m_sharedparams->params, attachment_left, attachment[eIH_Left]);
ReadValue(m_sharedparams->params, dual_wield_suffix);
ReadValue(m_sharedparams->params, prone_not_usable);
ReadValue(m_sharedparams->params, raiseable);
ReadValue(m_sharedparams->params, raise_distance);
ReadValue(m_sharedparams->params, update_hud);
ReadValue(m_sharedparams->params, auto_droppable);
ReadValue(m_sharedparams->params, has_first_select);
ReadValue(m_sharedparams->params, attach_to_back);
ReadValue(m_sharedparams->params, scopeAttachment);
ReadValue(m_sharedparams->params, attachment_gives_ammo);
ReadValue(m_sharedparams->params, display_name);
ReadValueEx(m_sharedparams->params, bone_attachment_01, bone_attachment_01);
ReadValueEx(m_sharedparams->params, bone_attachment_02, bone_attachment_02);
}
const IItemParamsNode *dw = params->GetChild("dualWield");
if (dw)
{
int n = dw->GetChildCount();
for (int i=0; i<n; i++)
{
const IItemParamsNode *item = dw->GetChild(i);
if (!stricmp(dw->GetChildName(i), "item") && !m_sharedparams->Valid())
{
const char *name = item->GetAttribute("value");
if (name && name[0])
m_sharedparams->dualWieldSupport.insert(TDualWieldSupportMap::value_type(name, true));
}
else if (!stricmp(dw->GetChildName(i), "suffix"))
{
const char *suffix = item->GetAttribute("value");
if (suffix)
m_sharedparams->params.dual_wield_suffix = suffix;
}
else if (!stricmp(dw->GetChildName(i), "pose"))
{
const char *pose = item->GetAttribute("value");
if (pose)
m_sharedparams->params.dual_wield_pose = pose;
}
}
}
const IItemParamsNode *mp = params->GetChild("mount");
if (mp)
{
CItemParamReader reader(mp);
ReadValue(m_mountparams, pivot);
ReadValue(m_mountparams, eye_distance);
ReadValue(m_mountparams, eye_height);
ReadValue(m_mountparams, body_distance);
//kirill - those are per-entity properties now, set from script
// ReadValue(m_mountparams, min_pitch);
// ReadValue(m_mountparams, max_pitch);
// ReadValue(m_mountparams, yaw_range);
ReadValue(m_mountparams, left_hand_helper);
ReadValue(m_mountparams, right_hand_helper);
}
return true;
}
#undef ReadValue
//------------------------------------------------------------------------
bool CItem::ReadGeometry(const IItemParamsNode *geometry)
{
FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);
if (!m_sharedparams->Valid())
{
// read teh helpers
m_sharedparams->helpers.resize(0);
const IItemParamsNode *attachments = geometry->GetChild("boneattachments");
if (attachments)
{
int n = attachments->GetChildCount();
SAttachmentHelper helper;
for (int i=0; i<n; i++)
{
const IItemParamsNode *attachment = attachments->GetChild(i);
const char *slot = attachment->GetAttribute("target");
const char *name = attachment->GetAttribute("name");
const char *bone = attachment->GetAttribute("bone");
int islot = TargetToSlot(slot);
if (islot == eIGS_Last)
{
GameWarning("Invalid attachment helper target for item '%s'! Skipping...", GetEntity()->GetName());
continue;
}
if (!name || !bone)
{
GameWarning("Invalid attachment helper specification for item '%s'! Skipping...", GetEntity()->GetName());
continue;
}
helper.name = name;
helper.bone = bone;
helper.slot = islot;
m_sharedparams->helpers.push_back(helper);
}
}
}
bool result = true;
int n = geometry->GetChildCount();
for (int i=0; i<n; i++)
{
const IItemParamsNode *child = geometry->GetChild(i);
int islot=TargetToSlot(geometry->GetChildName(i));
if (islot!=eIGS_Last)
{
result = result && SetGeometryFromParams(islot, child);
if (result)
PlayAction(m_idleAnimation[islot], 0, true, (eIPAF_Default|eIPAF_NoBlend)&~eIPAF_Owner);
}
}
ForceSkinning(true);
return result;
}
//------------------------------------------------------------------------
bool CItem::ReadActions(const IItemParamsNode *actions)
{
if (!m_sharedparams->Valid())
{
m_sharedparams->actions.clear();
int n = actions->GetChildCount();
for (int i=0; i<n; i++)
{
const IItemParamsNode *actionparams = actions->GetChild(i);
if (actionparams)
{
SAction action;
if (ReadAction(actionparams, &action))
{
const char *name = actionparams->GetAttribute("name");
m_sharedparams->actions.insert(TActionMap::value_type(name, action));
}
}
}
}
return true;
}
//------------------------------------------------------------------------
bool CItem::ReadAction(const IItemParamsNode *actionparams, SAction *pAction)
{
const char *actionName = actionparams->GetAttribute("name");
if (!actionName)
{
GameWarning("Missing action name for item '%s'! Skipping...", GetEntity()->GetName());
return false;
}
int children=0;
actionparams->GetAttribute("children", children);
pAction->children=children!=0;
int n = actionparams->GetChildCount();
for (int i=0; i<n; i++)
{
const IItemParamsNode *child = actionparams->GetChild(i);
const char *childName = actionparams->GetChildName(i);
if (!stricmp(childName, "sound"))
{
const char *name = child->GetAttribute("name");
if (!name)
{
GameWarning("Missing name of sound for action '%s' in item '%s'! Skipping...", actionName, GetEntity()->GetName());
return false;
}
const char *slot = child->GetAttribute("target");
int islot = TargetToSlot(slot);
if ((islot != eIGS_FirstPerson) && (islot != eIGS_ThirdPerson))
{
GameWarning("Invalid sound target '%s' for action '%s' in item '%s'! Skipping...", slot, actionName, GetEntity()->GetName());
return false;
}
if (!pAction->sound[islot].name.empty())
{
GameWarning("Sound target '%s' for action '%s' in item '%s' already specified! Skipping...", slot, actionName, GetEntity()->GetName());
return false;
}
float radius = 1.0f; child->GetAttribute("radius", radius);
float sphere = 0.0f; child->GetAttribute("sphere", sphere);
int isstatic = 0; child->GetAttribute("static", isstatic);
int issynched =0; child->GetAttribute("synched", issynched);
pAction->sound[islot].name = name;
pAction->sound[islot].airadius = radius;
pAction->sound[islot].sphere = sphere;
pAction->sound[islot].isstatic = isstatic!=0;
pAction->sound[islot].issynched = issynched!=0;
}
else if (!stricmp(childName, "animation"))
{
const char *name = child->GetAttribute("name");
if (!name)
{
GameWarning("Missing name of animation for action '%s' in item '%s'! Skipping...", actionName, GetEntity()->GetName());
return false;
}
const char *slot = child->GetAttribute("target");
int islot = TargetToSlot(slot);
if (islot == eIGS_Last)
{
GameWarning("Invalid animation target '%s' for action '%s' in item '%s'! Skipping...", slot, actionName, GetEntity()->GetName());
return false;
}
float speed = 1.0f; child->GetAttribute("speed", speed);
float blend = 0.125f; child->GetAttribute("blendTime", blend);
SAnimation animation;
const char *camera_helper = child->GetAttribute("camera_helper");
if (camera_helper && camera_helper[0])
{
int pos=1; child->GetAttribute("camera_position", pos);
int rot=1; child->GetAttribute("camera_rotation", rot);
int follow=0; child->GetAttribute("camera_follow", follow);
int reorient=0; child->GetAttribute("camera_reorient", reorient);
animation.camera_helper = camera_helper;
animation.camera_pos=pos!=0;
animation.camera_rot=rot!=0;
animation.camera_follow=follow!=0;
animation.camera_reorient=reorient!=0;
}
animation.name = name;
animation.speed = speed;
animation.blend = blend;
pAction->animation[islot].push_back(animation);
}
else if (!stricmp(childName, "effect"))
{
const char *name = child->GetAttribute("name");
if (!name)
{
GameWarning("Missing name of effect for action '%s' in item '%s'! Skipping...", actionName, GetEntity()->GetName());
return false;
}
const char *slot = child->GetAttribute("target");
int islot = TargetToSlot(slot);
if ((islot != eIGS_FirstPerson) && (islot != eIGS_ThirdPerson))
{
GameWarning("Invalid effect target '%s' for action '%s' in item '%s'! Skipping...", slot, actionName, GetEntity()->GetName());
return false;
}
if (!pAction->effect[islot].name.empty())
{
GameWarning("Effect target '%s' for action '%s' in item '%s' already specified! Skipping...", slot, actionName, GetEntity()->GetName());
return false;
}
pAction->effect[islot].name = name;
const char *helper = child->GetAttribute("helper");
if (helper && helper[0])
pAction->effect[islot].helper = helper;
}
else
{
GameWarning("Unknown param '%s' for action '%s' in item '%s'! Skipping...", childName, actionName, GetEntity()->GetName());
return false;
}
}
return true;
}
//------------------------------------------------------------------------
bool CItem::ReadDamageLevels(const IItemParamsNode *damagelevels)
{
m_damageLevels.resize(0);
int n = damagelevels->GetChildCount();
for (int i=0; i<n; i++)
{
const IItemParamsNode *levelparams = damagelevels->GetChild(i);
if (levelparams)
{
SDamageLevel level;
levelparams->GetAttribute("min_health", level.min_health);
levelparams->GetAttribute("max_health", level.max_health);
levelparams->GetAttribute("scale", level.scale);
const char *helper=levelparams->GetAttribute("helper");
const char *effect=levelparams->GetAttribute("effect");
if (effect)
level.effect=effect;
if (helper)
level.helper=helper;
m_damageLevels.push_back(level);
}
}
return true;
}
//------------------------------------------------------------------------
bool CItem::ReadLayers(const IItemParamsNode *layers)
{
if (!m_sharedparams->Valid())
{
m_sharedparams->layers.clear();
int n = layers->GetChildCount();
for (int i=0; i<n; i++)
{
const IItemParamsNode *layer = layers->GetChild(i);
if (layer)
{
SLayer lyr;
if (ReadLayer(layer, &lyr))
{
const char *name = layer->GetAttribute("name");
m_sharedparams->layers.insert(TLayerMap::value_type(name, lyr));
}
}
}
}
return true;
}
//------------------------------------------------------------------------
bool CItem::ReadLayer(const IItemParamsNode *layer, SLayer *pLayer)
{
const char *layerName = layer->GetAttribute("name");
if (!layerName)
{
GameWarning("Missing layer name for item '%s'! Skipping...", GetEntity()->GetName());
return false;
}
pLayer->isstatic=false;
int isstatic;
if (layer->GetAttribute("static", isstatic))
pLayer->isstatic = isstatic!=0;
int n = layer->GetChildCount();
for (int i=0; i<n; i++)
{
const IItemParamsNode *child = layer->GetChild(i);
if (!stricmp(layer->GetChildName(i), "animation"))
{
const char *name = child->GetAttribute("name");
if (!name)
{
GameWarning("Missing name of animation for layer '%s' in item '%s'! Skipping...", layerName, GetEntity()->GetName());
return false;
}
const char *slot = child->GetAttribute("target");
int islot = TargetToSlot(slot);
if (islot == eIGS_Last)
{
GameWarning("Invalid animation target '%s' of for layer '%s' in item '%s'! Skipping...", slot, layerName, GetEntity()->GetName());
return false;
}
pLayer->name[islot] = name;
pLayer->id[islot] = 0; child->GetAttribute("layerId", pLayer->id[islot]);
}
else if (!stricmp(layer->GetChildName(i), "bones"))
{
int nb = child->GetChildCount();
for (int b=0; b<nb; b++)
{
const IItemParamsNode *bone = child->GetChild(b);
if (!stricmp(child->GetChildName(b), "bone"))
{
const char *name = bone->GetAttribute("name");
if (!name)
{
GameWarning("Missing name of bone for layer '%s' in item '%s'! Skipping...", layerName, GetEntity()->GetName());
return false;
}
pLayer->bones.push_back(name);
}
}
}
else
{
GameWarning("Unknown param '%s' for layer '%s' in item '%s'! Skipping...", layer->GetChildName(i), layerName, GetEntity()->GetName());
return false;
}
}
return true;
}
//------------------------------------------------------------------------
bool CItem::ReadAccessories(const IItemParamsNode *accessories)
{
if (!m_sharedparams->Valid())
m_sharedparams->accessoryparams.clear();
m_initialSetup.clear();
int n = accessories->GetChildCount();
for (int i=0; i<n; i++)
{
const IItemParamsNode *child = accessories->GetChild(i);
if (!stricmp(accessories->GetChildName(i), "accessory") && !m_sharedparams->Valid())
{
SAccessoryParams params;
if (!ReadAccessoryParams(child, ¶ms))
continue;
const char *name = child->GetAttribute("name");
m_sharedparams->accessoryparams.insert(TAccessoryParamsMap::value_type(name, params));
}
else if (!stricmp(accessories->GetChildName(i), "initialsetup"))
{
const char *setupName = child->GetAttribute("name");
if (!setupName || !setupName[0])
setupName = "default";
m_initialSetup[setupName].resize(0);
int na = child->GetChildCount();
for (int k=0; k<na; k++)
{
const IItemParamsNode *accessory = child->GetChild(k);
if (!stricmp(child->GetChildName(k), "accessory"))
{
const char *name = accessory->GetAttribute("name");
if (!name || !name[0])
{
GameWarning("Missing accessory name for initial setup in item '%s'! Skipping...", GetEntity()->GetName());
continue;
}
m_initialSetup[setupName].push_back(name);
}
else
{
GameWarning("Unknown param '%s' in initial setup for item '%s'! Skipping...", child->GetChildName(k), GetEntity()->GetName());
continue;
}
}
}
}
return true;
}
//------------------------------------------------------------------------
bool CItem::ReadAccessoryParams(const IItemParamsNode *accessory, SAccessoryParams *params)
{
const char *name = accessory->GetAttribute("name");
if (!name || !name[0])
{
GameWarning("Missing accessory name for item '%s'! Skipping...", GetEntity()->GetName());
return false;
}
const IItemParamsNode *attach = accessory->GetChild("attach");
const IItemParamsNode *detach = accessory->GetChild("detach");
if (!attach || !detach)
{
GameWarning("Missing attach/detach details for accessory '%s' in item '%s'! Skipping...", name, GetEntity()->GetName());
return false;
}
params->attach_action = attach->GetAttribute("action");
params->attach_helper = attach->GetAttribute("helper");
params->attach_layer = attach->GetAttribute("layer");
params->detach_action = detach->GetAttribute("action");
string firemodes = accessory->GetAttribute("firemodes");
int curPos = 0;
string curToken, nextToken;
nextToken = firemodes.Tokenize(",", curPos);
while (!nextToken.empty())
{
curToken = nextToken;
curToken.Trim();
#ifdef ITEM_USE_SHAREDSTRING
params->firemodes.push_back(curToken.c_str());
#else
params->firemodes.push_back(curToken);
#endif
nextToken = firemodes.Tokenize(",", curPos);
}
params->switchToFireMode = accessory->GetAttribute("switchToFireMode");
params->zoommode = accessory->GetAttribute("zoommode");
int exclusive = 0;
accessory->GetAttribute("exclusive", exclusive);
params->exclusive = exclusive!=0;
int client_only=1;
accessory->GetAttribute("client_only", client_only);
params->client_only= client_only!=0;
params->params = accessory->GetChild("params");
return true;
}
//-----------------------------------------------------------------------
bool CItem::ReadAccessoryAmmo(const IItemParamsNode *ammos)
{
m_bonusAccessoryAmmo.clear();
if (!ammos)
return false;
for (int i=0; i<ammos->GetChildCount(); i++)
{
const IItemParamsNode *ammo = ammos->GetChild(i);
if (!strcmpi(ammo->GetName(), "ammo"))
{
int amount=0;
const char* name = ammo->GetAttribute("name");
IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(name);
assert(pClass);
ammo->GetAttribute("amount", amount);
if (amount)
m_bonusAccessoryAmmo[pClass]=amount;
}
}
return true;
}
//------------------------------------------------------------------------
bool CItem::SetGeometryFromParams(int slot, const IItemParamsNode *geometry)
{
FUNCTION_PROFILER(GetISystem(), PROFILE_GAME);
const char *name = geometry->GetAttribute("name");
if (!name || !name[0])
{
GameWarning("Missing geometry name for loading item '%s'!", GetEntity()->GetName());
return false;
}
Vec3 position(0,0,0); geometry->GetAttribute("position", position);
Ang3 angles(0,0,0); geometry->GetAttribute("angles", angles);
float scale=1.0f; geometry->GetAttribute("scale", scale);
if (slot == eIGS_FirstPerson)
{
const char *hand = geometry->GetAttribute("hand");
int idx = 0;
if (hand && hand[0])
{
if (!stricmp(hand, "right"))
idx = 1;
else if (!stricmp(hand, "left"))
idx = 2;
else
{
GameWarning("Invalid hand '%s' loading item '%s'!", hand, GetEntity()->GetName());
return false;
}
}
m_fpgeometry[idx].name=name;
m_fpgeometry[idx].position=position;
m_fpgeometry[idx].angles=DEG2RAD(angles);
m_fpgeometry[idx].scale=scale;
// marcio: first person geometry will be loaded upon selecting the weapon in first person
//if (((idx<2) && (m_stats.hand == eIH_Right)) || ((idx==2) && (m_stats.hand == eIH_Left)))
// SetGeometry(slot, name, position, DEG2RAD(angles), scale, false);
}
else
SetGeometry(slot, name, position, DEG2RAD(angles), scale, false);
return true;
}
//------------------------------------------------------------------------
int CItem::TargetToSlot(const char *slot)
{
int islot = eIGS_Last;
if (slot)
{
if (!stricmp(slot, "firstperson"))
islot = eIGS_FirstPerson;
else if (!stricmp(slot, "thirdperson"))
islot = eIGS_ThirdPerson;
else if (!stricmp(slot, "arms"))
islot = eIGS_Arms;
else if (!stricmp(slot, "aux0"))
islot = eIGS_Aux0;
else if (!stricmp(slot, "owner"))
islot = eIGS_Owner;
else if (!stricmp(slot, "ownerloop"))
islot = eIGS_OwnerLooped;
else if (!stricmp(slot, "offhand"))
islot = eIGS_OffHand;
else if (!stricmp(slot, "destroyed"))
islot = eIGS_Destroyed;
else if (!stricmp(slot, "thirdpersonAux"))
islot = eIGS_ThirdPersonAux;
else if (!stricmp(slot, "aux1"))
islot = eIGS_Aux1;
}
return islot;
}
//------------------------------------------------------------------------
void CItem::ReadProperties(IScriptTable *pProperties)
{
if (pProperties)
{
GetEntityProperty("HitPoints", m_properties.hitpoints);
GetEntityProperty("bPickable", m_properties.pickable);
GetEntityProperty("bMounted", m_properties.mounted);
GetEntityProperty("bPhysics", m_properties.physics);
GetEntityProperty("bUsable", m_properties.usable);
GetEntityProperty("bAutoPickup", m_properties.autopickup);
GetEntityProperty("Respawn", "bRespawn", m_respawnprops.respawn);
GetEntityProperty("Respawn", "nTimer", m_respawnprops.timer);
GetEntityProperty("Respawn", "bUnique", m_respawnprops.unique);
}
}
| [
"[email protected]"
] | [
[
[
1,
728
]
]
] |
fceeb725e024f7af64fe36021f90ebd97d44c95a | b73f27ba54ad98fa4314a79f2afbaee638cf13f0 | /libproject/ScreenRecord/stdafx.cpp | fa470019a81385ef89cb58b0e40d760bc6c1b4fe | [] | no_license | weimingtom/httpcontentparser | 4d5ed678f2b38812e05328b01bc6b0c161690991 | 54554f163b16a7c56e8350a148b1bd29461300a0 | refs/heads/master | 2021-01-09T21:58:30.326476 | 2009-09-23T08:05:31 | 2009-09-23T08:05:31 | 48,733,304 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 271 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// ScreenRecord.pch 将成为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
//引用任何所需的附加头文件,而不是在此文件中引用
| [
"[email protected]"
] | [
[
[
1,
8
]
]
] |
56e01d14999cc87cf4273d9f68f5656e495ef68a | 78fb44a7f01825c19d61e9eaaa3e558ce80dcdf5 | /guceCORE/include/guceCORE_CVideoOptions.h | 712f8784b1133a6a8f955f6b049c4d4f6764f3c2 | [] | no_license | LiberatorUSA/GUCE | a2d193e78d91657ccc4eab50fab06de31bc38021 | a4d6aa5421f8799cedc7c9f7dc496df4327ac37f | refs/heads/master | 2021-01-02T08:14:08.541536 | 2011-09-08T03:00:46 | 2011-09-08T03:00:46 | 41,840,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,679 | h | /*
* guceCORE: GUCE module providing tie-in functionality between systems
* Copyright (C) 2002 - 2008. Dinand Vanvelzen
*
* 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.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef GUCE_CORE_CVIDEOOPTIONS_H
#define GUCE_CORE_CVIDEOOPTIONS_H
/*-------------------------------------------------------------------------//
// //
// INCLUDES //
// //
//-------------------------------------------------------------------------*/
#include <vector>
#ifndef GUCE_CORE_MACROS_H
#include "guceCORE_macros.h" /* guceCORE build config and macros */
#define GUCE_CORE_MACROS_H
#endif /* GUCE_CORE_MACROS_H ? */
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GUCE {
namespace CORE {
/*-------------------------------------------------------------------------//
// //
// CLASSES //
// //
//-------------------------------------------------------------------------*/
class CVideoSettings;
/*-------------------------------------------------------------------------*/
class GUCE_CORE_EXPORT_CPP CVideoOptions
{
public:
struct SDisplayMode
{
UInt32 widthInPixels;
UInt32 heightInPixels;
UInt32 depthInBits;
UInt32 frequency;
};
typedef struct SDisplayMode TDisplayMode;
typedef std::vector< TDisplayMode > TDisplayModeVector;
CVideoOptions( void );
CVideoOptions( const CVideoOptions& src );
virtual ~CVideoOptions();
CVideoOptions& operator=( const CVideoOptions& src );
bool AreSettingsPossible( const CVideoSettings& settings ) const;
const TDisplayModeVector& GetDisplayModes( void ) const;
void GetDisplayModesForResolution( const UInt32 widthInPixels ,
const UInt32 heightInPixels ,
TDisplayModeVector& modes ) const;
void Clear( void );
static bool RetrieveOptionsFromOS( CVideoOptions& options );
private:
TDisplayModeVector m_displayModes;
};
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
}; /* namespace CORE */
}; /* namespace GUCE */
/*-------------------------------------------------------------------------*/
#endif /* GUCE_CORE_CVIDEOOPTIONS_H ? */
/*-------------------------------------------------------------------------//
// //
// Info & Changes //
// //
//-------------------------------------------------------------------------//
- 02-04-2005 :
- Initial version of this file.
-----------------------------------------------------------------------------*/
| [
"[email protected]"
] | [
[
[
1,
116
]
]
] |
20f93e6d0346105249cc62f6ab1fb85fece4e6d4 | de37068405e7fa8f7a4e43bfe8af9b23787f6926 | /AccessObj.cpp | c20b4f4b51b8eb4b159d00c4394bd6aeb3e3c667 | [] | no_license | ssserenity/zbuffer-cpu | faf052c30ba77f88fc3140c478b59cb4e6bb24d8 | e014c783a25bbd0ff19c7bfc6846d6997bee227e | refs/heads/master | 2021-01-21T18:50:59.847444 | 2011-11-24T16:16:51 | 2011-11-24T16:16:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,125 | cpp | #include <cstdio>
#include <cstdlib>
#include <string>
#include <cmath>
#include <cassert>
#include <list>
#include <vector>
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
using namespace std;
#ifndef SAFE_DELETE
#define SAFE_DELETE(p) if(p) { delete (p); (p)=0; }
#endif
#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) if(p) { delete[] (p); (p)=0; }
#endif
//////////////////////////////////////////////////////////////////////
#include "AccessObj.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CAccessObj::CAccessObj()
{
m_pModel = NULL;
}
CAccessObj::~CAccessObj()
{
Destory();
}
//////////////////////////////////////////////////////////////////////
// Equal: compares two vectors and returns true if they are
// equal (within a certain threshold) or false if not. An epsilon
// that works fairly well is 0.000001.
//
// u - array of 3 GLfloats (float u[3])
// v - array of 3 GLfloats (float v[3])
//////////////////////////////////////////////////////////////////////
bool CAccessObj::Equal(CPoint3D * u, CPoint3D * v, float epsilon)
{
if (objAbs(u->x - v->x) < epsilon &&
objAbs(u->y - v->y) < epsilon &&
objAbs(u->z - v->z) < epsilon)
{
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////
// FindGroup: Find a group in the model
//////////////////////////////////////////////////////////////////////
COBJgroup * CAccessObj::FindGroup(char* name)
{
COBJgroup * group;
assert(m_pModel);
group = m_pModel->pGroups;
while(group)
{
if (!strcmp(name, group->name))
break;
group = group->next;
}
return group;
}
//////////////////////////////////////////////////////////////////////
// AddGroup: Add a group to the model
//////////////////////////////////////////////////////////////////////
COBJgroup * CAccessObj::AddGroup(char* name)
{
COBJgroup* group;
group = FindGroup(name);
if (!group)
{
group = new COBJgroup;
sprintf_s(group->name, 256, "%s", name);
group->nTriangles = 0;
group->pTriangles = NULL;
group->next = m_pModel->pGroups;
m_pModel->pGroups = group;
m_pModel->nGroups++;
}
return group;
}
//////////////////////////////////////////////////////////////////////
// DirName: return the directory given a path
//
// path - filesystem path
//
// NOTE: the return value should be free'd.
//////////////////////////////////////////////////////////////////////
char * CAccessObj::DirName(char* path)
{
static char dir[256];
char *s;
sprintf_s(dir,256, "%s", path);
s = strrchr(dir, '\\');
if (s) s[1] = '\0';
else dir[0] = '\0';
return dir;
}
//////////////////////////////////////////////////////////////////////
// FirstPass: first pass at a Wavefront OBJ file that gets all the
// statistics of the model (such as #vertices, #normals, etc)
//
// model - properly initialized COBJmodel structure
// file - (fopen'd) file descriptor
//////////////////////////////////////////////////////////////////////
bool CAccessObj::FirstPass(FILE* file)
{
unsigned int nVertices; /* number of vertices in m_pModel */
unsigned int nNormals; /* number of normals in m_pModel */
unsigned int nTexCoords; /* number of texcoords in m_pModel */
unsigned int nTriangles; /* number of triangles in m_pModel */
COBJgroup* group; /* current group */
unsigned v, n, t;
char buf[129];
/* make a default group */
group = AddGroup("default");
nVertices = nNormals = nTexCoords = nTriangles = 0;
while(fscanf(file, "%128s", buf, 129) != EOF)
{
switch(buf[0])
{
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'v': /* v, vn, vt */
switch(buf[1])
{
case '\0': /* vertex */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
nVertices++;
break;
case 'n': /* normal */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
nNormals++;
break;
case 't': /* texcoord */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
nTexCoords++;
break;
default:
printf("FirstPass(): Unknown token \"%s\".\n", buf);
exit(1);
break;
}
break;
case 'u':
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'g': /* group */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
buf[strlen(buf)-1] = '\0'; /* nuke '\n' */
group = AddGroup(buf);
break;
case 'f': /* face */
v = n = t = 0;
fscanf(file, "%128s", buf, 129);
/* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
if (strstr(buf, "//"))
{
/* v//n */
sscanf(buf, "%d//%d", &v, &n);
fscanf(file, "%d//%d", &v, &n);
fscanf(file, "%d//%d", &v, &n);
nTriangles++;
group->nTriangles++;
while(fscanf(file, "%d//%d", &v, &n) > 0)
{
nTriangles++;
group->nTriangles++;
}
}
else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3)
{
/* v/t/n */
fscanf(file, "%d/%d/%d", &v, &t, &n);
fscanf(file, "%d/%d/%d", &v, &t, &n);
nTriangles++;
group->nTriangles++;
while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0)
{
nTriangles++;
group->nTriangles++;
}
}
else if (sscanf(buf, "%d/%d", &v, &t) == 2)
{
/* v/t */
fscanf(file, "%d/%d", &v, &t);
fscanf(file, "%d/%d", &v, &t);
nTriangles++;
group->nTriangles++;
while(fscanf(file, "%d/%d", &v, &t) > 0)
{
nTriangles++;
group->nTriangles++;
}
}
else
{
/* v */
fscanf(file, "%d", &v);
fscanf(file, "%d", &v);
nTriangles++;
group->nTriangles++;
while(fscanf(file, "%d", &v) > 0)
{
nTriangles++;
group->nTriangles++;
}
}
break;
default:
/* eat up rest of line */
if (isalpha(buf[0]))
{
fgets(buf, sizeof(buf), file);
}
else
return false;
break;
}
}
/* set the stats in the m_pModel structure */
m_pModel->nVertices = nVertices;
m_pModel->nNormals = nNormals;
m_pModel->nTriangles = nTriangles;
/* allocate memory for the triangles in each group */
group = m_pModel->pGroups;
while(group)
{
if (group->nTriangles > 0)
group->pTriangles = new unsigned int [group->nTriangles];
group->nTriangles = 0;
group = group->next;
}
return true;
}
//////////////////////////////////////////////////////////////////////
// SecondPass: second pass at a Wavefront OBJ file that gets all
// the data.
//
// model - properly initialized COBJmodel structure
// file - (fopen'd) file descriptor
//////////////////////////////////////////////////////////////////////
void CAccessObj::SecondPass(FILE* file)
{
unsigned int nVertices; /* number of vertices in m_pModel */
unsigned int nNormals; /* number of normals in m_pModel */
unsigned int nTriangles; /* number of triangles in m_pModel */
CPoint3D * vertices; /* array of vertices */
CPoint3D * normals; /* array of normals */
COBJgroup * group; /* current group pointer */
unsigned int v, n, t;
char buf[128];
/* set the pointer shortcuts */
vertices = m_pModel->vpVertices;
normals = m_pModel->vpNormals;
group = m_pModel->pGroups;
/* on the second pass through the file, read all the data into the
allocated arrays */
nVertices = nNormals = 1;
nTriangles = 0;
int nNormalAdd = 0;
int nNormalCount = 0;
while(fscanf(file, "%s", buf) != EOF)
{
switch(buf[0])
{
case '#': /* comment */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
case 'v': /* v, vn, vt */
switch(buf[1])
{
case '\0': /* vertex */
fscanf(file, "%f %f %f",
&vertices[nVertices].x,
&vertices[nVertices].y,
&vertices[nVertices].z);
nVertices++;
break;
case 'n': /* normal */
fscanf(file, "%f %f %f",
&normals[nNormals].x,
&normals[nNormals].y,
&normals[nNormals].z);
nNormals++;
nNormalCount ++;
break;
}
break;
case 'g': /* group */
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
buf[strlen(buf)-1] = '\0'; /* nuke '\n' */
group = FindGroup(buf);
nNormalAdd += nNormalCount;
nNormalCount = 0;
break;
case 'f': /* face */
v = n = t = 0;
fscanf(file, "%s", buf);
/* can be one of %d, %d//%d, %d/%d, %d/%d/%d %d//%d */
if (strstr(buf, "//"))
{
/* v//n */
sscanf(buf, "%d//%d", &v, &n);
Tri(nTriangles).vindices[0] = v;
Tri(nTriangles).nindices[0] = n;// + nNormalAdd;
fscanf(file, "%d//%d", &v, &n);
Tri(nTriangles).vindices[1] = v;
Tri(nTriangles).nindices[1] = n;// + nNormalAdd;
fscanf(file, "%d//%d", &v, &n);
Tri(nTriangles).vindices[2] = v;
Tri(nTriangles).nindices[2] = n;// + nNormalAdd;
group->pTriangles[group->nTriangles++] = nTriangles;
nTriangles++;
while(fscanf(file, "%d//%d", &v, &n) > 0)
{
Tri(nTriangles).vindices[0] = Tri(nTriangles-1).vindices[0];
Tri(nTriangles).nindices[0] = Tri(nTriangles-1).nindices[0];
Tri(nTriangles).vindices[1] = Tri(nTriangles-1).vindices[2];
Tri(nTriangles).nindices[1] = Tri(nTriangles-1).nindices[2];
Tri(nTriangles).vindices[2] = v;
Tri(nTriangles).nindices[2] = n;// + nNormalAdd;
group->pTriangles[group->nTriangles++] = nTriangles;
nTriangles++;
}
}
else if (sscanf(buf, "%d/%d/%d", &v, &t, &n) == 3)
{
/* v/t/n */
Tri(nTriangles).vindices[0] = v;
Tri(nTriangles).nindices[0] = n;// + nNormalAdd;
fscanf(file, "%d/%d/%d", &v, &t, &n);
Tri(nTriangles).vindices[1] = v;
Tri(nTriangles).nindices[1] = n;// + nNormalAdd;
fscanf(file, "%d/%d/%d", &v, &t, &n);
Tri(nTriangles).vindices[2] = v;
Tri(nTriangles).nindices[2] = n;// + nNormalAdd;
group->pTriangles[group->nTriangles++] = nTriangles;
nTriangles++;
while(fscanf(file, "%d/%d/%d", &v, &t, &n) > 0)
{
Tri(nTriangles).vindices[0] = Tri(nTriangles-1).vindices[0];
Tri(nTriangles).nindices[0] = Tri(nTriangles-1).nindices[0];
Tri(nTriangles).vindices[1] = Tri(nTriangles-1).vindices[2];
Tri(nTriangles).nindices[1] = Tri(nTriangles-1).nindices[2];
Tri(nTriangles).vindices[2] = v;
Tri(nTriangles).nindices[2] = n;// + nNormalAdd;
group->pTriangles[group->nTriangles++] = nTriangles;
nTriangles++;
}
}
else if (sscanf(buf, "%d/%d", &v, &t) == 2)
{
/* v/t */
Tri(nTriangles).vindices[0] = v;
fscanf(file, "%d/%d", &v, &t);
Tri(nTriangles).vindices[1] = v;
fscanf(file, "%d/%d", &v, &t);
Tri(nTriangles).vindices[2] = v;
group->pTriangles[group->nTriangles++] = nTriangles;
nTriangles++;
while(fscanf(file, "%d/%d", &v, &t) > 0)
{
Tri(nTriangles).vindices[0] = Tri(nTriangles-1).vindices[0];
Tri(nTriangles).vindices[1] = Tri(nTriangles-1).vindices[2];
Tri(nTriangles).vindices[2] = v;
group->pTriangles[group->nTriangles++] = nTriangles;
nTriangles++;
}
}
else
{
/* v */
sscanf(buf, "%d", &v);
Tri(nTriangles).vindices[0] = v;
fscanf(file, "%d", &v);
Tri(nTriangles).vindices[1] = v;
fscanf(file, "%d", &v);
Tri(nTriangles).vindices[2] = v;
group->pTriangles[group->nTriangles++] = nTriangles;
nTriangles++;
while(fscanf(file, "%d", &v) > 0)
{
Tri(nTriangles).vindices[0] = Tri(nTriangles-1).vindices[0];
Tri(nTriangles).vindices[1] = Tri(nTriangles-1).vindices[2];
Tri(nTriangles).vindices[2] = v;
group->pTriangles[group->nTriangles++] = nTriangles;
nTriangles++;
}
}
break;
default:
/* eat up rest of line */
fgets(buf, sizeof(buf), file);
break;
}
}
}
//////////////////////////////////////////////////////////////////////
// Dimensions: Calculates the dimensions (width, height, depth) of
// a model.
//
// model - initialized COBJmodel structure
// dimensions - array of 3 GLfloats (float dimensions[3])
//////////////////////////////////////////////////////////////////////
void CAccessObj::Dimensions(float* dimensions)
{
unsigned int i;
CPoint3D vMax, vMin;
assert(m_pModel);
assert(m_pModel->vpVertices);
assert(dimensions);
/* get the max/mins */
vMax = vMin = m_pModel->vpVertices[0];
for (i = 1; i <= m_pModel->nVertices; i++)
{
if (vMax.x < m_pModel->vpVertices[i].x)
vMax.x = m_pModel->vpVertices[i].x;
if (vMin.x > m_pModel->vpVertices[i].x)
vMin.x = m_pModel->vpVertices[i].x;
if (vMax.y < m_pModel->vpVertices[i].y)
vMax.y = m_pModel->vpVertices[i].y;
if (vMin.y > m_pModel->vpVertices[i].y)
vMin.y = m_pModel->vpVertices[i].y;
if (vMax.z < m_pModel->vpVertices[i].z)
vMax.z = m_pModel->vpVertices[i].z;
if (vMin.z > m_pModel->vpVertices[i].z)
vMin.z = m_pModel->vpVertices[i].z;
}
/* calculate m_pModel width, height, and depth */
dimensions[0] = vMax.x-vMin.x;
dimensions[1] = vMax.y-vMin.y;
dimensions[2] = vMax.z-vMin.z;
}
//////////////////////////////////////////////////////////////////////
// Scale: Scales a model by a given amount.
//
// model - properly initialized COBJmodel structure
// scale - scalefactor (0.5 = half as large, 2.0 = twice as large)
//////////////////////////////////////////////////////////////////////
void CAccessObj::Scale(float scale)
{
unsigned int i;
for (i = 1; i <= m_pModel->nVertices; i++)
m_pModel->vpVertices[i] = m_pModel->vpVertices[i] * scale;
}
//////////////////////////////////////////////////////////////////////
// ReverseWinding: Reverse the polygon winding for all polygons in
// this model. Default winding is counter-clockwise. Also changes
// the direction of the normals.
//
// model - properly initialized COBJmodel structure
//////////////////////////////////////////////////////////////////////
void CAccessObj::ReverseWinding()
{
unsigned int i, swap;
assert(m_pModel);
for (i = 0; i < m_pModel->nTriangles; i++)
{
swap = Tri(i).vindices[0];
Tri(i).vindices[0] = Tri(i).vindices[2];
Tri(i).vindices[2] = swap;
if (m_pModel->nNormals)
{
swap = Tri(i).nindices[0];
Tri(i).nindices[0] = Tri(i).nindices[2];
Tri(i).nindices[2] = swap;
}
}
/* reverse facet normals */
for (i = 1; i <= m_pModel->nFacetnorms; i++)
m_pModel->vpFacetNorms[i] = m_pModel->vpFacetNorms[i]*(-1);
/* reverse vertex normals */
for (i = 1; i <= m_pModel->nNormals; i++)
m_pModel->vpNormals[i] = m_pModel->vpNormals[i]*(-1);
}
//////////////////////////////////////////////////////////////////////
// FacetNormals: Generates facet normals for a model (by taking the
// cross product of the two vectors derived from the sides of each
// triangle). Assumes a counter-clockwise winding.
//
// model - initialized COBJmodel structure
//////////////////////////////////////////////////////////////////////
void CAccessObj::FacetNormals()
{
unsigned int i;
CPoint3D u, v;
assert(m_pModel);
assert(m_pModel->vpVertices);
/* clobber any old facetnormals */
SAFE_DELETE_ARRAY(m_pModel->vpFacetNorms);
/* allocate memory for the new facet normals */
m_pModel->nFacetnorms = m_pModel->nTriangles;
m_pModel->vpFacetNorms = new CPoint3D [m_pModel->nFacetnorms + 1];
for (i = 0; i < m_pModel->nTriangles; i++)
{
m_pModel->pTriangles[i].findex = i+1;
u = m_pModel->vpVertices[Tri(i).vindices[1]] - m_pModel->vpVertices[Tri(i).vindices[0]];
v = m_pModel->vpVertices[Tri(i).vindices[2]] - m_pModel->vpVertices[Tri(i).vindices[0]];
m_pModel->vpFacetNorms[i+1] = u * v;
m_pModel->vpFacetNorms[i+1].unify();
}
}
//////////////////////////////////////////////////////////////////////
// VertexNormals: Generates smooth vertex normals for a model.
// First builds a list of all the triangles each vertex is in. Then
// loops through each vertex in the the list averaging all the facet
// normals of the triangles each vertex is in. Finally, sets the
// normal index in the triangle for the vertex to the generated smooth
// normal. If the dot product of a facet normal and the facet normal
// associated with the first triangle in the list of triangles the
// current vertex is in is greater than the cosine of the angle
// parameter to the function, that facet normal is not added into the
// average normal calculation and the corresponding vertex is given
// the facet normal. This tends to preserve hard edges. The angle to
// use depends on the model, but 90 degrees is usually a good start.
//
// model - initialized COBJmodel structure
// angle - maximum angle (in degrees) to smooth across
//////////////////////////////////////////////////////////////////////
void CAccessObj::VertexNormals(float angle)
{
OBJnode* node;
typedef list<OBJnode*> NodeList;
typedef NodeList::iterator NodeListItor;
typedef vector<NodeList> ListArray;
typedef ListArray::iterator ListArrItor;
ListArray members;
CPoint3D * normals;
unsigned int nNormals;
CPoint3D t_vAverage;
float dot, cos_angle;
unsigned int i;
assert(m_pModel);
assert(m_pModel->vpFacetNorms);
/* calculate the cosine of the angle (in degrees) */
cos_angle = (float)cos(angle * 3.14159265 / 180.0);
/* nuke any previous normals */
SAFE_DELETE_ARRAY(m_pModel->vpNormals);
/* allocate space for new normals */
m_pModel->nNormals = m_pModel->nTriangles * 3; /* 3 normals per triangle */
m_pModel->vpNormals = new CPoint3D [m_pModel->nNormals+1];
/* allocate a structure that will hold a linked list of triangle
indices for each vertex */
members.resize(m_pModel->nVertices + 1);
/* for every triangle, create a node for each vertex in it */
for (i = 0; i < m_pModel->nTriangles; i++)
{
node = new OBJnode;
node->triIdx = i;
node->index = 0;
members[Tri(i).vindices[0]].push_back(node);
node = new OBJnode;
node->triIdx = i;
node->index = 1;
members[Tri(i).vindices[1]].push_back(node);
node = new OBJnode;
node->triIdx = i;
node->index = 2;
members[Tri(i).vindices[2]].push_back(node);
}
/* calculate the average normal for each vertex */
nNormals = 1;
for (i = 1; i <= m_pModel->nVertices; i++)
{
if (members[i].empty())
{
continue;
#ifdef _DEBUG
//fprintf(stderr, "VertexNormals(): vertex w/o a triangle\n");
#endif // _DEBUG
}
// calculate an average normal for this vertex by averaging the
// facet normal of every triangle this vertex is in
NodeListItor itl = members[i].begin();
NodeListItor itl_end = members[i].end();
for (; itl!=itl_end; ++itl)
{
/* only average if the dot product of the angle between the two
facet normals is greater than the cosine of the threshold
angle -- or, said another way, the angle between the two
facet normals is less than (or equal to) the threshold angle */
node = *itl;
t_vAverage = CPoint3D(0, 0, 0);
NodeListItor itl_t = members[i].begin();
for (; itl_t!=itl_end; ++itl_t)
{
OBJnode* node_t = *itl_t;
dot = m_pModel->vpFacetNorms[Tri(node->triIdx).findex] &
m_pModel->vpFacetNorms[Tri(node_t->triIdx).findex];
if (dot > cos_angle)
{
t_vAverage += m_pModel->vpFacetNorms[Tri(node_t->triIdx).findex];
/* we averaged at least one normal! */
}
}
/* normalize the averaged normal */
t_vAverage.unify();
/* add the normal to the vertex normals list */
m_pModel->vpNormals[nNormals] = t_vAverage;
Tri(node->triIdx).nindices[node->index] = nNormals;
++nNormals;
}
}
/* free the member information */
ListArrItor ita = members.begin();
ListArrItor ita_end = members.end();
for (; ita!=ita_end; ++ita)
{
NodeListItor itl = ita->begin();
NodeListItor itl_end = ita->end();
for (; itl!=itl_end; ++itl)
{
SAFE_DELETE(*itl);
}
}
}
//////////////////////////////////////////////////////////////////////
// objDelete: Deletes a COBJmodel structure.
//
// model - initialized COBJmodel structure
//////////////////////////////////////////////////////////////////////
void CAccessObj::Destory()
{
delete m_pModel;
m_pModel = NULL;
}
//////////////////////////////////////////////////////////////////////
// objReadOBJ: Reads a model description from a Wavefront .OBJ file.
// Returns a pointer to the created object which should be free'd with
// objDelete().
//
// filename - name of the file containing the Wavefront .OBJ format data.
//////////////////////////////////////////////////////////////////////
bool CAccessObj::LoadOBJ(const char* filename)
{
FILE* file;
// open the file
file = fopen(filename, "r");
if (!file)
{
fprintf(stderr, "objReadOBJ() failed: can't open data file \"%s\".\n",
filename);
exit(1);
}
// save old model for invalid obj file
COBJmodel *pOldModel = m_pModel;
// allocate a new model
m_pModel = new COBJmodel;
sprintf(m_pModel->pathname, "%s", filename);
m_pModel->nVertices = 0;
m_pModel->vpVertices = NULL;
m_pModel->nNormals = 0;
m_pModel->vpNormals = NULL;
m_pModel->nFacetnorms = 0;
m_pModel->vpFacetNorms = NULL;
m_pModel->nTriangles = 0;
m_pModel->pTriangles = NULL;
m_pModel->nGroups = 0;
m_pModel->pGroups = NULL;
m_pModel->position = CPoint3D (0, 0, 0);
// make a first pass through the file to get a count of the number
// of vertices, normals, texcoords & triangles
if (FirstPass(file))
{
SAFE_DELETE(pOldModel);
/* allocate memory */
m_pModel->vpVertices = new CPoint3D [m_pModel->nVertices + 1];
m_pModel->pTriangles = new COBJtriangle [m_pModel->nTriangles];
if (m_pModel->nNormals)
{
m_pModel->vpNormals = new CPoint3D [m_pModel->nNormals + 1];
}
/* rewind to beginning of file and read in the data this pass */
rewind(file);
SecondPass(file);
// Calc bounding box
CalcBoundingBox();
}
else
{
// restore old model
if (m_pModel != NULL) Destory();
m_pModel = pOldModel;
}
/* close the file */
fclose(file);
return (pOldModel==NULL);
}
void CAccessObj::Boundingbox(CPoint3D &vMax, CPoint3D &vMin)
{
vMax = m_vMax;
vMin = m_vMin;
}
void CAccessObj::CalcBoundingBox()
{
unsigned int i;
m_vMax = m_vMin = m_pModel->vpVertices[1];
for (i = 1; i <= m_pModel->nVertices; i++)
{
if (m_vMax.x < m_pModel->vpVertices[i].x)
m_vMax.x = m_pModel->vpVertices[i].x;
if (m_vMin.x > m_pModel->vpVertices[i].x)
m_vMin.x = m_pModel->vpVertices[i].x;
if (m_vMax.y < m_pModel->vpVertices[i].y)
m_vMax.y = m_pModel->vpVertices[i].y;
if (m_vMin.y > m_pModel->vpVertices[i].y)
m_vMin.y = m_pModel->vpVertices[i].y;
if (m_vMax.z < m_pModel->vpVertices[i].z)
m_vMax.z = m_pModel->vpVertices[i].z;
if (m_vMin.z > m_pModel->vpVertices[i].z)
m_vMin.z = m_pModel->vpVertices[i].z;
}
CPoint3D vCent = (m_vMax + m_vMin)*0.5f;
for (i = 1; i <= m_pModel->nVertices; i++)
m_pModel->vpVertices[i] = m_pModel->vpVertices[i] - vCent;
m_vMax = m_vMax - vCent;
m_vMin = m_vMin -vCent;
}
//////////////////////////////////////////////////////////////////////////
// Unified the model to center
//////////////////////////////////////////////////////////////////////////
void CAccessObj::UnifiedModel()
{
if (m_pModel==NULL) return;
CPoint3D vDiameter = m_vMax - m_vMin;
float radius = vDiameter.length() * 0.4f / 1.414f;
Scale(1.0f/radius);
CalcBoundingBox();
if (m_pModel->nNormals==0)
{
FacetNormals();
VertexNormals(90.f);
}
} | [
"[email protected]"
] | [
[
[
1,
838
]
]
] |
2c55442b985ab6712441d884dd80bf545b1be9d2 | 6c8c4728e608a4badd88de181910a294be56953a | /OgreRenderingModule/EC_OgreLight.h | 85d3c0a2e8341a1df2db82fd8698c961f5bbb549 | [
"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 | 3,294 | h | // For conditions of distribution and use, see copyright notice in license.txt
#ifndef incl_OgreRenderer_EC_OgreLight_h
#define incl_OgreRenderer_EC_OgreLight_h
#include "ComponentInterface.h"
#include "OgreModuleApi.h"
#include "Color.h"
#include "Vector3D.h"
#include "Declare_EC.h"
namespace Ogre
{
class Light;
}
namespace OgreRenderer
{
class Renderer;
class EC_OgrePlaceable;
typedef boost::shared_ptr<Renderer> RendererPtr;
typedef boost::weak_ptr<Renderer> RendererWeakPtr;
//! Ogre light component
/*! A light can optionally be attached to a placeable (ie. a scene node) but it can also exist without one.
\ingroup OgreRenderingModuleClient
*/
class OGRE_MODULE_API EC_OgreLight : public Foundation::ComponentInterface
{
Q_OBJECT
DECLARE_EC(EC_OgreLight);
public:
//! light type enumeration
enum Type
{
LT_Point,
LT_Spot,
LT_Directional
};
//! Destructor.
virtual ~EC_OgreLight();
//! gets placeable component
Foundation::ComponentPtr GetPlaceable() const { return placeable_; }
//! sets placeable component
/*! set a null placeable (or do not set a placeable) to have a detached light
\param placeable placeable component
*/
void SetPlaceable(Foundation::ComponentPtr placeable);
//! sets type of light
/*! \param type light type - point, directional or spot
*/
void SetType(Type type);
//! sets diffuse color of light
/*! \param color diffuse color value
*/
void SetColor(const Color& color);
//! sets light attenuation parameters
/*! \param range maximum range of light
\param constant constant attenuation
\param linear linear attenuation
\param quad quadratic attenuation
*/
void SetAttenuation(float range, float constant, float linear, float quad);
//! sets light direction
/*! does not affect point lights
\param direction light direction
*/
void SetDirection(const Vector3df& direction);
//! Whether the light casts shadows or not.
//! @param enabled Whether the light casts shadows or not.
void SetCastShadows(const bool &enabled);
//! @return Ogre light pointer
Ogre::Light* GetLight() const { return light_; }
private:
//! constructor
/*! \param module renderer module
*/
EC_OgreLight(Foundation::ModuleInterface* module);
//! attaches light to placeable
void AttachLight();
//! detaches light from placeable
void DetachLight();
//! placeable component, optional
Foundation::ComponentPtr placeable_;
//! renderer
RendererWeakPtr renderer_;
//! Ogre light
Ogre::Light* light_;
//! light attached to placeable -flag
bool attached_;
};
}
#endif
| [
"cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jjj@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jaakkoallander@5b2332b8-efa3-11de-8684-7d64432d61a3"
] | [
[
[
1,
6
],
[
11,
28
],
[
30,
42
],
[
44,
77
],
[
82,
82
],
[
84,
111
]
],
[
[
7,
7
],
[
29,
29
]
],
[
[
8,
10
]
],
[
[
43,
43
],
[
78,
81
],
[
83,
83
],
[
112,
112
]
]
] |
215142f127b289903c3482f3bfb2eb8cb54e4cde | 118ded1d2bad8ae3b5fa5b6abaf4d45b54ece2fa | /src/Library/Rtcm31/RawRtcm3.h | dda17895d16c82297038c55457781aa9e3799bf9 | [] | no_license | gpoleszuk/kinematic | ab064f6dffeea91f7dd91ebc6eac5c30e3d6ee16 | b5c95c43771f74b17152498b602295ee21c60037 | refs/heads/master | 2021-01-10T10:52:24.487730 | 2011-01-15T17:29:25 | 2011-01-15T17:29:25 | 55,036,059 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,563 | h | #ifndef RAWRTCM_INCLUDED
#define RAWRTCM_INCLUDED
// Part of Kinematic, a utility for GPS positioning
//
// Copyright (C) 2006 John Morris www.precision-gps.org
//
// 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, version 2.
//
// 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 "CommRtcm3.h"
#include "RawReceiver.h"
class RawRtcm3: public RawReceiver
{
protected:
CommRtcm3 In;
// To keep track of slips and overflows between epochs
int32 PhaseAdjust[MaxSats];
int32 OldPhase[MaxSats];
// Guess we are using current time until we get ephemeris
bool GuessTime;
public:
RawRtcm3(Stream& in);
virtual bool NextEpoch();
virtual ~RawRtcm3(void);
private:
bool ProcessStationRef(Block& b);
bool ProcessAntennaRef(Block& b);
bool ProcessObservations(Block& b);
bool ProcessEphemeris(Block& b);
double PreviousPhaseRange[MaxSats];
int PreviousLockTime[MaxSats];
};
#endif // RAWRTCM_INCLUDED
| [
"[email protected]"
] | [
[
[
1,
53
]
]
] |
ec7a4eba48920eec184361d39647f3801894807a | fa7611075650f4b4d4066c3b0ca3ded5847c7ae2 | /solitairecore/main.h | f5a9a73b1493d5749094d239f08d8bbb10313df3 | [] | no_license | EdwinTauro/solitaire | b9207d4d4cfc79a68cfbd8790ddb61231c6015e0 | 93826a3cd6e431d18814d4180af71944b3cbdc6e | refs/heads/master | 2016-09-05T22:59:52.806347 | 2011-11-20T23:30:48 | 2011-11-20T23:30:48 | 2,686,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 771 | h | #include <windows.h>
#include <iostream>
#include "logger.h"
#include "solitairegameengine.h"
#include "boardstate.h"
#define EXPORT __declspec (dllexport)
EXPORT int Square( int X);
EXPORT int Cube( int X);
EXPORT BoardState NewGame();
EXPORT bool IsValidMove(int fromPosition, int toPosition);
/*
#ifndef __MAIN_H__
#define __MAIN_H__
#include <windows.h>
*/
/* To use this exported function of dll, include this header
* in your project.
*/
/*
#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport)
#else
#define DLL_EXPORT __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C"
{
#endif
void DLL_EXPORT SomeFunction(const LPCSTR sometext);
#ifdef __cplusplus
}
#endif
#endif // __MAIN_H__
*/
| [
"[email protected]"
] | [
[
[
1,
45
]
]
] |
ab00691a092fefc26c8c2b37c040552e4900cf18 | aefc3d630a28e054a438d13ab16d32f2d39ccb1e | /HDCEx.h | b6240be368db1b3d64b2a5d1aafe45e4b22d0c50 | [] | no_license | imcooder/publicwince | e64305d86496b550116c312d2e9a67e7fb33c6f8 | 58a337768161e1a10664b4d5edc2aadfb2ab1328 | refs/heads/master | 2021-05-28T10:40:35.786601 | 2010-06-27T06:25:09 | 2010-06-27T06:25:09 | 32,301,144 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,902 | h | /********************************************************************
Copyright (c) 2002-2003 汉王科技有限公司. 版权所有.
文件名称: XDC.h
文件内容:
版本历史: 1.0
作者: xuejuntao [email protected] 2008/08/19
*********************************************************************/
#ifndef HWX_HDCEX_H
#define HWX_HDCEX_H
class CXUE_BitmapLock
{
public:
CXUE_BitmapLock(HDC, HBITMAP hBitmap);
virtual ~CXUE_BitmapLock();
void SetBitmap(HBITMAP);
protected:
HDC m_hDC;
HGDIOBJ m_hOldBitmap;
};
class CXUE_FontLock
{
public:
CXUE_FontLock(HDC, HFONT = NULL);
CXUE_FontLock(HDC, HFONT, COLORREF clrTextColor);
CXUE_FontLock(HDC, const LOGFONT*);
virtual ~CXUE_FontLock();
void SetColor(COLORREF clrTextColor);
void SetFontHeight(LONG);
void SetFontFaceName(LPCTSTR);
LONG GetFontHeight();
protected:
void ReplaceCurrentFont(const LOGFONT*);
protected:
HDC m_hDC;
HFONT m_hFont;
HFONT m_hFontOld;
COLORREF m_crOldTextColor;
};
class CXUE_PenLock
{
public:
CXUE_PenLock(HDC, HPEN);
CXUE_PenLock(HDC hDC, INT fnPenStyle, INT nWidth, COLORREF crColor);
virtual ~CXUE_PenLock();
void SetPenColor(COLORREF crColor);
void SetPenStyle(INT);
void SetPenWidth(INT);
protected:
void ReplaceCurrentPen(const LOGPEN*);
protected:
HDC m_hDC;
HPEN m_hPen;
HPEN m_hOldPen;
};
class CXUE_SolidBrushLock
{
public:
CXUE_SolidBrushLock(HDC hDC, HBRUSH);
CXUE_SolidBrushLock(HDC hDC, COLORREF crColor);
virtual ~CXUE_SolidBrushLock();
void SetBrushColor(COLORREF crColor);
protected:
void ReplaceCurrentBrush(COLORREF);
protected:
HDC m_hDC;
HBRUSH m_hBrush;
HBRUSH m_hOldBrush;
};
class CXUE_StockObjectLock
{
public:
CXUE_StockObjectLock(HDC hDC, int);
virtual ~CXUE_StockObjectLock();
protected:
HDC m_hDC;
HGDIOBJ m_hGdiObj;
HGDIOBJ m_hOldGdiObj;
};
class CXUE_BkModeLock
{
public:
CXUE_BkModeLock(HDC hDC, int);
virtual ~CXUE_BkModeLock();
void SetBkMode(int);
protected:
HDC m_hDC;
LONG m_nBkModeOld;
};
class CXUE_SafeCompatibleBitmap
{
public:
CXUE_SafeCompatibleBitmap(HDC, INT, INT);
virtual ~CXUE_SafeCompatibleBitmap();
HBITMAP GetSafeHBitmap();
protected:
protected:
HBITMAP m_hBitmap;
HDC m_hDC;
};
class CXUE_SafeCompatibleDC
{
public:
CXUE_SafeCompatibleDC(HDC, HBITMAP hBitmap = NULL);
CXUE_SafeCompatibleDC(HDC, LPCTSTR);
CXUE_SafeCompatibleDC(HDC, HINSTANCE, LONG);
virtual ~CXUE_SafeCompatibleDC();
HDC GetSafeHdc();
LONG GetHeight();
LONG GetWidth();
protected:
void Construct(HDC, HBITMAP);
void Destruct();
protected:
HBITMAP m_hBitmap;
HBITMAP m_hOldBitmap;
HDC m_hMemDC;
BITMAP m_Bitmap;
};
class CXUE_SafeMemDC
{
public:
CXUE_SafeMemDC(HDC hDestDC, const LPRECT prcPaint = NULL);
virtual ~CXUE_SafeMemDC();
HDC GetSafeHdc();
BOOL Clear(COLORREF);
BOOL SwapDC();
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
void DrawDragRect(const LPRECT lpRect, SIZE size, const LPRECT lpRectLast, SIZE sizeLast, HBRUSH pBrush, HBRUSH pBrushLast);
void FillSolidRect(LPCRECT lpRect, COLORREF clr);
void FillSolidRect(int x, int y, int cx, int cy, COLORREF clr);
void Draw3dRect(LPCRECT lpRect,COLORREF clrTopLeft, COLORREF clrBottomRight);
void Draw3dRect(int x, int y, int cx, int cy, COLORREF clrTopLeft, COLORREF clrBottomRight);
//////////////////////////////////////////////////////////////////////////
HBRUSH GetHalftoneBrush();
protected:
void Construct(HDC hDestDC, const LPRECT);
protected:
HDC m_hDC;
HDC m_hDestDC;
HBITMAP m_hBitmap;
RECT m_rtPaint;
HGDIOBJ m_hOldBitmap;
};
class CXUE_SafePaintDC
{
public:
CXUE_SafePaintDC(HWND hWnd);
virtual ~CXUE_SafePaintDC();
HDC GetSafeHdc();
protected:
HWND m_hWnd;
PAINTSTRUCT m_ps;
HDC m_hDC;
};
class CXUE_SafeClientDC
{
public:
CXUE_SafeClientDC(HWND hWnd);
virtual ~CXUE_SafeClientDC();
HDC GetSafeHdc();
protected:
HWND m_hWnd;
HDC m_hDC;
};
class CXUE_SafeWindowDC
{
public:
CXUE_SafeWindowDC(HWND hWnd);
virtual ~CXUE_SafeWindowDC();
HDC GetSafeHdc();
protected:
HWND m_hWnd;
HDC m_hDC;
};
class CXUE_SetViewportOrgExLock
{
public:
CXUE_SetViewportOrgExLock(HDC, POINT);
virtual ~CXUE_SetViewportOrgExLock();
void SetViewportOrgEx(POINT);
protected:
HDC m_hDC;
POINT m_PointOld;
};
class CXUE_StretchBltModeLock
{
public:
CXUE_StretchBltModeLock(HDC, INT);
virtual ~CXUE_StretchBltModeLock();
void SetStretchBltMode(INT);
protected:
HDC m_hDC;
INT m_nStretchModeOld;
};
#endif //HWX_HDCEX_H | [
"[email protected]@a9ac5a9c-960a-11de-b8e1-0bcae535652c"
] | [
[
[
1,
210
]
]
] |
8ca2bdf564e9c94787ea3ebbbdd80da32dafb834 | 3c2dc480d637cc856a1be74be1bbc197a0b24bd2 | /s34Rect.cpp | 8187a36f9fdef1a21c430dc9805dc1b00ea4a337 | [] | no_license | cjus/s34mme | d49ff5ede63fbae83fa0694eeea66b0024a4b72b | 77d372c9f55d2053c11e41bdfd9d2f074329e451 | refs/heads/master | 2020-04-14T19:30:39.690545 | 2010-09-05T18:23:37 | 2010-09-05T18:23:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,332 | cpp | // Rect.cpp: implementation of the CS34Rect class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "s34Rect.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CS34Rect::CS34Rect(CS34Rect &rect)
{
left = rect.left;
top = rect.top;
right = rect.right;
bottom = rect.bottom;
}
BOOL CS34Rect::IntersectRect(CS34Rect &r1, CS34Rect &r2)
{
if (r1.left > r2.right)
{
SetRectEmpty();
return FALSE;
}
if (r1.right < r2.left)
{
SetRectEmpty();
return FALSE;
}
if (r1.top > r2.bottom)
{
SetRectEmpty();
return FALSE;
}
if (r1.bottom < r2.top)
{
SetRectEmpty();
return FALSE;
}
CS34Rect tmpRect = r1;
if (r2.top > r1.top)
tmpRect.top = r2.top;
if (r2.left > r1.left)
tmpRect.left = r2.left;
if (r2.right < r1.right)
tmpRect.right = r2.right;
if (r2.bottom < r1.bottom)
tmpRect.bottom = r2.bottom;
left = tmpRect.left;
top = tmpRect.top;
right = tmpRect.right;
bottom = tmpRect.bottom;
return TRUE;
}
void CS34Rect::OffsetRect(CS34Point &pt)
{
left += pt.x;
top += pt.y;
right += pt.x;
bottom += pt.y;
}
void CS34Rect::OffsetRect(int x, int y)
{
left += x; right += x; top += y; bottom += y;
}
void CS34Rect::InflateRect(CS34Point &pt)
{
left += pt.x; top += pt.y; right += pt.x; bottom += pt.y;
}
void CS34Rect::InflateRect(int x, int y)
{
left += x; right += x; top += y; bottom += y;
}
void CS34Rect::InflateRect(CS34Size size)
{
left += size.cx;
right += size.cx;
top += size.cy;
bottom += size.cy;
}
BOOL CS34Rect::IsPointInRect(CS34Point &pt)
{
if (pt.x < left)
return FALSE;
if (pt.x > right)
return FALSE;
if (pt.y < top)
return FALSE;
if (pt.y > bottom)
return FALSE;
return TRUE;
}
BOOL CS34Rect::IsPointInRect(int x, int y)
{
if (x < left)
return FALSE;
if (x > right)
return FALSE;
if (y < top)
return FALSE;
if (y > bottom)
return FALSE;
return TRUE;
}
void CS34Rect::UnionRect(CS34Rect &rect)
{
left = (left < rect.left) ? left : rect.left;
top = (top < rect.top) ? top : rect.top;
right = (right > rect.right) ? right : rect.right;
bottom = (bottom > rect.bottom) ? bottom : rect.bottom;
}
void CS34Rect::UnionRect(CS34Rect &rect1, CS34Rect &rect2)
{
left = (rect1.left < rect2.left) ? rect1.left : rect2.left;
top = (rect1.top < rect2.top) ? rect1.top : rect2.top;
right = (rect1.right > rect2.right) ? rect1.right : rect2.right;
bottom = (rect1.bottom > rect2.bottom) ? rect1.bottom : rect2.bottom;
}
void CS34Rect::operator=(const CS34Rect& srCS34Rect)
{
left = srCS34Rect.left;
top = srCS34Rect.top;
right = srCS34Rect.right;
bottom = srCS34Rect.bottom;
}
int CS34Rect::operator ==(const CS34Rect& srCS34Rect) const
{
return (left == srCS34Rect.left && top == srCS34Rect.top &&
right == srCS34Rect.right && bottom == srCS34Rect.bottom);
}
BOOL CS34Rect::EqualRect(const CS34Rect& srCS34Rect) const
{
if (left == srCS34Rect.left && top == srCS34Rect.top &&
right == srCS34Rect.right && bottom == srCS34Rect.bottom)
return TRUE;
else
return FALSE;
}
| [
"[email protected]"
] | [
[
[
1,
160
]
]
] |
7837d10fa00581c9dc7758c061d68ea2fdf6535b | 905a210043c8a48d128822ddb6ab141a0d583d27 | /viewer/mainwindow.cpp | c9f434fec9e94290e89e87423f489527dee71e1a | [] | no_license | mweiguo/sgt | 50036153c81f35356e2bfbba7019a8307556abe4 | 7770cdc030f5e69fef0b2150b92b87b7c8b56ba5 | refs/heads/master | 2020-04-01T16:32:21.566890 | 2011-10-31T04:35:02 | 2011-10-31T04:35:02 | 1,139,668 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,087 | cpp | #include <QtGui>
#include <QActionGroup>
#include <QList>
#include "mainwindow.h"
#include "sgr_render2d.h"
#include "layermanagerwidget.h"
#include "tools.h"
#include <exception>
#include <iostream>
#include <list>
using namespace std;
MainWindow::MainWindow()
{
doc = new Document;
context = new ViewerContext;
context->doc = doc;
context->mainwindow = this;
QGLFormat fmt;
fmt.setDepth ( true );
fmt.setDoubleBuffer ( true );
fmt.setRgba ( true );
shareWidget = new QGLWidget ( fmt );
// displayer
mainviewtools = new Tools ( context, 0 );
ToolsEntry entry[] = {
{Tools::NONE_TOOL, new NoneTool(mainviewtools)},
{Tools::ZOOM_TOOL, new ZoomTool(mainviewtools)},
{Tools::HAND_TOOL, new HandTool(mainviewtools)},
{0, 0}
};
mainviewtools->setTools ( entry );
GLMainView* mainview = new GLMainView(context, mainviewtools, &(doc->sceneid), fmt, 0, shareWidget );
displayer = new GLScrollWidget ( context, mainview );
mainviewtools->parent = displayer;
// birdview
birdview = new GLBirdView (context, 0, &(doc->sceneid), fmt, 0, shareWidget );
connect ( displayer,
SIGNAL(transformChanged(float,float,float,float)),
this,
SLOT(onMainViewTransformChanged(float,float,float,float)) );
setCentralWidget(displayer);
createActions();
createMenus();
createToolBars();
createStatusBar();
createDockWindows();
setWindowTitle(tr("Dock Widgets"));
setUnifiedTitleAndToolBarOnMac(true);
setMouseTracking ( false );
r2d_init ();
}
MainWindow::~MainWindow()
{
delete context;
delete doc;
delete mainviewtools;
delete shareWidget;
}
void MainWindow::init ()
{
doc->init ( displayer->widget, shareWidget );
}
void MainWindow::open()
{
try
{
QString fileName = QFileDialog::getOpenFileName(this, tr("Choose a file name"), ".", tr("SLC (*.slc *.slc)"));
if (fileName.isEmpty())
return;
cout << "file name = " << fileName.toStdString() << endl;
open ( fileName.toStdString().c_str() );
}
catch ( exception& ex )
{
cout << ex.what() << endl;
}
}
void MainWindow::open ( const char* filename )
{
doc->openScene ( displayer->widget, filename );
layerManagerWidget->loadFromScene ( doc->sceneid );
displayer->homeposition();
birdview->homeposition();
}
void MainWindow::about()
{
QMessageBox::about(this, tr("About Dock Widgets"),
tr("The <b>Dock Widgets</b> example demonstrates how to "
"use Qt's dock widgets. You can enter your own text, "
"click a customer to add a customer name and "
"address, and click standard paragraphs to add them."));
}
void MainWindow::actionEvent( QAction* action )
{
try
{
if ( action == winzoomAct )
displayer->widget->tools->selectTool ( Tools::ZOOM_TOOL );
else if ( action == handAct )
displayer->widget->tools->selectTool ( Tools::HAND_TOOL );
}
catch ( exception& ex )
{
cerr << ex.what() << endl;
}
}
//================================================================================
void MainWindow::onMainViewTransformChanged(float x1, float y1, float x2, float y2 )
{
try
{
// cout << "-----------------MainWindow::onMainViewTransformChanged" << endl;
if ( doc->birdviewmiscid != -1 )
{
if ( birdview->rectid == -1 )
{
int sid = doc->birdviewmiscid;
r2d_to_element ( sid, R2D_ROOT );
r2d_to_element ( sid, R2D_FIRST_CHILD ); // layer
r2d_to_element ( sid, R2D_FIRST_CHILD ); // lod
r2d_to_element ( sid, R2D_FIRST_CHILD ); // lodpage
birdview->rectid = r2d_to_element ( sid, R2D_FIRST_CHILD ); // rect
}
float pnts[] = {x1, y1, 2.1, x2, y2, 2.1 };
r2d_rect_points ( doc->birdviewmiscid, birdview->rectid, pnts );
// cout << "r2d_rect_points (" << doc->birdviewmiscid << ", " << birdview->rectid << ", " << x1 << ", " << y1 << ", " <<
// 50 << ", " << x2 << ", " << y2 << ", " << 50 << " )" << endl;
birdview->update();
}
}
catch ( exception& ex )
{
cerr << ex.what() << endl;
}
}
//================================================================================
void MainWindow::createActions()
{
openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
openAct->setShortcuts(QKeySequence::Open);
openAct->setStatusTip(tr("Open a New Scene"));
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
quitAct = new QAction(tr("&Quit"), this);
QList<QKeySequence> lst;
lst.push_back ( QKeySequence::Quit );
lst.push_back ( QKeySequence( Qt::Key_Escape ) );
quitAct->setShortcuts( lst );
quitAct->setStatusTip(tr("Quit the application"));
connect(quitAct, SIGNAL(triggered()), this, SLOT(close()));
aboutAct = new QAction(tr("&About"), this);
aboutAct->setStatusTip(tr("Show the application's About box"));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
aboutQtAct = new QAction(tr("About &Qt"), this);
aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
lst.clear();
lst.push_back ( QKeySequence::ZoomIn );
lst.push_back ( QKeySequence (Qt::CTRL + Qt::Key_PageUp) );
zoominAct = new QAction(QIcon(":/images/zoomin.png"), tr("&ZoomIn..."), this);
zoominAct->setAutoRepeat ( true );
zoominAct->setShortcuts( lst );
zoominAct->setStatusTip(tr("Zoom In Scene"));
connect(zoominAct, SIGNAL(triggered()), displayer, SLOT(zoomin()));
lst.clear();
lst.push_back ( QKeySequence::ZoomOut );
lst.push_back ( QKeySequence (Qt::CTRL + Qt::Key_PageDown) );
zoomoutAct = new QAction(QIcon(":/images/zoomout.png"), tr("&ZoomOut..."), this);
zoomoutAct->setAutoRepeat ( true );
zoomoutAct->setShortcuts( lst );
zoomoutAct->setStatusTip(tr("Zoom Out Scene"));
connect(zoomoutAct, SIGNAL(triggered()), displayer, SLOT(zoomout()));
winzoomAct = new QAction(QIcon(":/images/windowzoom.png"), tr("&Window Zoom..."), this);
winzoomAct->setStatusTip(tr("window Zoom tool"));
winzoomAct->setCheckable ( true );
handAct = new QAction(QIcon(":/images/hand.png"), tr("&HandMove..."), this);
handAct->setShortcut( QKeySequence( Qt::CTRL + Qt::Key_P ) );
handAct->setStatusTip(tr("use a hand tool to move the canvas"));
handAct->setCheckable ( true );
navigroup = new QActionGroup( this );
navigroup->setExclusive ( true );
navigroup->addAction ( winzoomAct );
navigroup->addAction ( handAct );
connect(navigroup, SIGNAL(triggered(QAction*)), this, SLOT(actionEvent(QAction*)));
leftAct = new QAction(tr("Left Translate "), this);
leftAct->setShortcut( QKeySequence( Qt::Key_Left ) );
leftAct->setStatusTip(tr("move objects left"));
connect(leftAct, SIGNAL(triggered()), displayer, SLOT(lefttranslate()));
rightAct = new QAction(tr("Right Translate"), this);
rightAct->setShortcut( QKeySequence( Qt::Key_Right ) );
rightAct->setStatusTip(tr("move objects right"));
connect(rightAct, SIGNAL(triggered()), displayer, SLOT(righttranslate()));
upAct = new QAction(tr("&Up Translate"), this);
upAct->setShortcut( QKeySequence( Qt::Key_Up ) );
upAct->setStatusTip(tr("move objects up"));
connect(upAct, SIGNAL(triggered()), displayer, SLOT(uptranslate()));
downAct = new QAction(tr("&Down Translate"), this);
downAct->setShortcut( QKeySequence( Qt::Key_Down ) );
downAct->setStatusTip(tr("move objects down"));
connect(downAct, SIGNAL(triggered()), displayer, SLOT(downtranslate()));
fullextentAct = new QAction(QIcon(":/images/home_32.png"), tr("&view whole scene ..."), this);
fullextentAct->setShortcut( QKeySequence( Qt::CTRL + Qt::Key_H ) );
fullextentAct->setStatusTip(tr("to home position"));
connect(fullextentAct, SIGNAL(triggered()), displayer, SLOT(homeposition()));
}
void MainWindow::createMenus()
{
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAct);
fileMenu->addSeparator();
fileMenu->addAction(quitAct);
viewMenu = menuBar()->addMenu(tr("&View"));
viewMenu->addAction(zoominAct);
viewMenu->addAction(zoomoutAct);
viewMenu->addActions( navigroup->actions());
// viewMenu->addAction(winzoomAct);
// viewMenu->addAction(handAct);
viewMenu->addAction(leftAct);
viewMenu->addAction(rightAct);
viewMenu->addAction(upAct);
viewMenu->addAction(downAct);
viewMenu->addAction(fullextentAct);
menuBar()->addSeparator();
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(aboutAct);
helpMenu->addAction(aboutQtAct);
}
void MainWindow::createToolBars()
{
fileToolBar = addToolBar(tr("File"));
fileToolBar->addAction(openAct);
navToolBar = addToolBar(tr("Navigation"));
navToolBar->addAction(fullextentAct);
navToolBar->addActions( navigroup->actions());
// navToolBar->addAction(handAct);
// navToolBar->addAction(winzoomAct);
navToolBar->addAction(zoominAct);
navToolBar->addAction(zoomoutAct);
}
void MainWindow::createStatusBar()
{
statusBar()->showMessage(tr("Ready"));
}
void MainWindow::createDockWindows()
{
QDockWidget *dock = new QDockWidget(tr("Layers"), this);
list<QGLWidget*> lst;
lst.push_back ( displayer->widget );
lst.push_back ( birdview );
layerManagerWidget = new LayerManagerWidget(lst, dock);
dock->setWidget(layerManagerWidget);
addDockWidget(Qt::RightDockWidgetArea, dock);
dock = new QDockWidget(tr("birdview"), this);
dock->setMinimumSize ( 230, 200 );
dock->setMaximumSize ( 230, 200 );
dock->setWidget(birdview);
addDockWidget(Qt::RightDockWidgetArea, dock);
}
| [
"[email protected]"
] | [
[
[
1,
301
]
]
] |
c2a6278628ee33da98154b464815013a0e1f809a | 7faf74792eca2bc712b4dcec6afb9945ad726019 | /Record/WriteSoundFile.cpp | 714a296cabb465daf184ea1e5a733a70f695bd7f | [] | no_license | axfree/iRecord | 0994e79a247a67cf0021d950a3923404ecc39b15 | 403104d5fedf9c8f1309f8fa9a06a7c4dcf15f2d | refs/heads/master | 2021-01-22T23:26:15.020374 | 2011-03-15T23:36:33 | 2011-03-15T23:36:33 | 1,485,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,087 | cpp | // WriteSoundFile.cpp : implementation file
//
#include "stdafx.h"
#include <mmsystem.h>
#include "record.h"
#include "WriteSoundFile.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CWriteSoundFile
IMPLEMENT_DYNCREATE(CWriteSoundFile, CWinThread)
CWriteSoundFile::CWriteSoundFile()
{
}
CWriteSoundFile::~CWriteSoundFile()
{
}
BOOL CWriteSoundFile::InitInstance()
{
// TODO: perform and per-thread initialization here
return TRUE;
}
int CWriteSoundFile::ExitInstance()
{
// TODO: perform any per-thread cleanup here
return CWinThread::ExitInstance();
}
BEGIN_MESSAGE_MAP(CWriteSoundFile, CWinThread)
//{{AFX_MSG_MAP(CWriteSoundFile)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
ON_THREAD_MESSAGE(WM_WRITESOUNDFILE_FILENAME, CreateWaveFile)
ON_THREAD_MESSAGE(WM_WRITESOUNDFILE_WRITEBLOCK, WriteToSoundFile)
ON_THREAD_MESSAGE(WM_WRITESOUNDFILE_CLOSEFILE, CloseSoundFile)
ON_THREAD_MESSAGE(WM_WRITESOUNDFILE_ENDTHREAD, OnEndThread)
END_MESSAGE_MAP()
void CWriteSoundFile::CreateWaveFile(WPARAM wParam, LPARAM lParam)
{
PWRITESOUNDFILE pWriteSoundFile = (PWRITESOUNDFILE) lParam;
int cbWaveFormatEx = sizeof(WAVEFORMATEX) + pWriteSoundFile->waveFormatEx.cbSize;
m_hFile = ::mmioOpen(pWriteSoundFile->lpszFileName,NULL, MMIO_CREATE|MMIO_WRITE|MMIO_EXCLUSIVE | MMIO_ALLOCBUF);
if (!m_hFile)
return;
ZeroMemory(&m_MMCKInfoParent, sizeof(MMCKINFO));
m_MMCKInfoParent.fccType = mmioFOURCC('W','A','V','E');
MMRESULT err = ::mmioCreateChunk( m_hFile,&m_MMCKInfoParent,
MMIO_CREATERIFF);
ZeroMemory(&m_MMCKInfoChild, sizeof(MMCKINFO));
m_MMCKInfoChild.ckid = mmioFOURCC('f','m','t',' ');
m_MMCKInfoChild.cksize = cbWaveFormatEx;
err = ::mmioCreateChunk(m_hFile, &m_MMCKInfoChild, 0);
err = ::mmioWrite(m_hFile, (char*)&pWriteSoundFile->waveFormatEx, cbWaveFormatEx);
err = ::mmioAscend(m_hFile, &m_MMCKInfoChild, 0);
m_MMCKInfoChild.ckid = mmioFOURCC('d', 'a', 't', 'a');
err = ::mmioCreateChunk(m_hFile, &m_MMCKInfoChild, 0);
}
void CWriteSoundFile::WriteToSoundFile(WPARAM wParam, LPARAM lParam)
{
LPWAVEHDR lpHdr = (LPWAVEHDR) lParam;
int cbLength = lpHdr->dwBufferLength;
if (lpHdr)
{
char *soundbuffer = (char*) lpHdr->lpData;
if (m_hFile && soundbuffer)
::mmioWrite(m_hFile, soundbuffer, cbLength);
if (soundbuffer)
delete (BYTE*) soundbuffer;
if (lpHdr)
delete lpHdr;
}
}
void CWriteSoundFile::CloseSoundFile(WPARAM wParam, LPARAM lParam)
{
if (m_hFile)
{
::mmioAscend(m_hFile, &m_MMCKInfoChild, 0);
::mmioAscend(m_hFile, &m_MMCKInfoParent, 0);
::mmioClose(m_hFile, 0);
m_hFile = NULL;
}
}
void CWriteSoundFile::OnEndThread(WPARAM wParam, LPARAM lParam)
{
CloseSoundFile(0,0);
::PostQuitMessage(0);
}
/////////////////////////////////////////////////////////////////////////////
// CWriteSoundFile message handlers
| [
"axfree.live.com"
] | [
[
[
1,
111
]
]
] |
40a52c8b3a157a9f17997bfce729f7765a6f3f1a | 21fe9ddd8ba3a3798246be0f01a56a10e07acb2e | /v8/src/parser.cc | 29b62a3918e4397d33dd0bc10caa60047f2ea0a6 | [
"bzip2-1.0.6",
"BSD-3-Clause"
] | permissive | yong/xruby2 | 5e2ed23574b8f9f790b7df2ab347acca4f651373 | ecc8fa062c30cb54ef41d2ccdbe46c6d5ffaa844 | refs/heads/master | 2021-01-20T11:26:04.196967 | 2011-12-02T17:40:48 | 2011-12-02T17:40:48 | 2,893,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 197,291 | cc | // Copyright 2011 the V8 project authors. 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 Google Inc. 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.
#include "v8.h"
#include "api.h"
#include "ast.h"
#include "bootstrapper.h"
#include "char-predicates-inl.h"
#include "codegen.h"
#include "compiler.h"
#include "func-name-inferrer.h"
#include "messages.h"
#include "parser.h"
#include "platform.h"
#include "preparser.h"
#include "runtime.h"
#include "scanner-character-streams.h"
#include "scopeinfo.h"
#include "string-stream.h"
namespace v8 {
namespace internal {
// PositionStack is used for on-stack allocation of token positions for
// new expressions. Please look at ParseNewExpression.
class PositionStack {
public:
explicit PositionStack(bool* ok) : top_(NULL), ok_(ok) {}
~PositionStack() { ASSERT(!*ok_ || is_empty()); }
class Element {
public:
Element(PositionStack* stack, int value) {
previous_ = stack->top();
value_ = value;
stack->set_top(this);
}
private:
Element* previous() { return previous_; }
int value() { return value_; }
friend class PositionStack;
Element* previous_;
int value_;
};
bool is_empty() { return top_ == NULL; }
int pop() {
ASSERT(!is_empty());
int result = top_->value();
top_ = top_->previous();
return result;
}
private:
Element* top() { return top_; }
void set_top(Element* value) { top_ = value; }
Element* top_;
bool* ok_;
};
RegExpBuilder::RegExpBuilder()
: zone_(Isolate::Current()->zone()),
pending_empty_(false),
characters_(NULL),
terms_(),
alternatives_()
#ifdef DEBUG
, last_added_(ADD_NONE)
#endif
{}
void RegExpBuilder::FlushCharacters() {
pending_empty_ = false;
if (characters_ != NULL) {
RegExpTree* atom = new(zone()) RegExpAtom(characters_->ToConstVector());
characters_ = NULL;
text_.Add(atom);
LAST(ADD_ATOM);
}
}
void RegExpBuilder::FlushText() {
FlushCharacters();
int num_text = text_.length();
if (num_text == 0) {
return;
} else if (num_text == 1) {
terms_.Add(text_.last());
} else {
RegExpText* text = new(zone()) RegExpText();
for (int i = 0; i < num_text; i++)
text_.Get(i)->AppendToText(text);
terms_.Add(text);
}
text_.Clear();
}
void RegExpBuilder::AddCharacter(uc16 c) {
pending_empty_ = false;
if (characters_ == NULL) {
characters_ = new(zone()) ZoneList<uc16>(4);
}
characters_->Add(c);
LAST(ADD_CHAR);
}
void RegExpBuilder::AddEmpty() {
pending_empty_ = true;
}
void RegExpBuilder::AddAtom(RegExpTree* term) {
if (term->IsEmpty()) {
AddEmpty();
return;
}
if (term->IsTextElement()) {
FlushCharacters();
text_.Add(term);
} else {
FlushText();
terms_.Add(term);
}
LAST(ADD_ATOM);
}
void RegExpBuilder::AddAssertion(RegExpTree* assert) {
FlushText();
terms_.Add(assert);
LAST(ADD_ASSERT);
}
void RegExpBuilder::NewAlternative() {
FlushTerms();
}
void RegExpBuilder::FlushTerms() {
FlushText();
int num_terms = terms_.length();
RegExpTree* alternative;
if (num_terms == 0) {
alternative = RegExpEmpty::GetInstance();
} else if (num_terms == 1) {
alternative = terms_.last();
} else {
alternative = new(zone()) RegExpAlternative(terms_.GetList());
}
alternatives_.Add(alternative);
terms_.Clear();
LAST(ADD_NONE);
}
RegExpTree* RegExpBuilder::ToRegExp() {
FlushTerms();
int num_alternatives = alternatives_.length();
if (num_alternatives == 0) {
return RegExpEmpty::GetInstance();
}
if (num_alternatives == 1) {
return alternatives_.last();
}
return new(zone()) RegExpDisjunction(alternatives_.GetList());
}
void RegExpBuilder::AddQuantifierToAtom(int min,
int max,
RegExpQuantifier::Type type) {
if (pending_empty_) {
pending_empty_ = false;
return;
}
RegExpTree* atom;
if (characters_ != NULL) {
ASSERT(last_added_ == ADD_CHAR);
// Last atom was character.
Vector<const uc16> char_vector = characters_->ToConstVector();
int num_chars = char_vector.length();
if (num_chars > 1) {
Vector<const uc16> prefix = char_vector.SubVector(0, num_chars - 1);
text_.Add(new(zone()) RegExpAtom(prefix));
char_vector = char_vector.SubVector(num_chars - 1, num_chars);
}
characters_ = NULL;
atom = new(zone()) RegExpAtom(char_vector);
FlushText();
} else if (text_.length() > 0) {
ASSERT(last_added_ == ADD_ATOM);
atom = text_.RemoveLast();
FlushText();
} else if (terms_.length() > 0) {
ASSERT(last_added_ == ADD_ATOM);
atom = terms_.RemoveLast();
if (atom->max_match() == 0) {
// Guaranteed to only match an empty string.
LAST(ADD_TERM);
if (min == 0) {
return;
}
terms_.Add(atom);
return;
}
} else {
// Only call immediately after adding an atom or character!
UNREACHABLE();
return;
}
terms_.Add(new(zone()) RegExpQuantifier(min, max, type, atom));
LAST(ADD_TERM);
}
Handle<String> Parser::LookupSymbol(int symbol_id) {
// Length of symbol cache is the number of identified symbols.
// If we are larger than that, or negative, it's not a cached symbol.
// This might also happen if there is no preparser symbol data, even
// if there is some preparser data.
if (static_cast<unsigned>(symbol_id)
>= static_cast<unsigned>(symbol_cache_.length())) {
if (scanner().is_literal_ascii()) {
return isolate()->factory()->LookupAsciiSymbol(
scanner().literal_ascii_string());
} else {
return isolate()->factory()->LookupTwoByteSymbol(
scanner().literal_uc16_string());
}
}
return LookupCachedSymbol(symbol_id);
}
Handle<String> Parser::LookupCachedSymbol(int symbol_id) {
// Make sure the cache is large enough to hold the symbol identifier.
if (symbol_cache_.length() <= symbol_id) {
// Increase length to index + 1.
symbol_cache_.AddBlock(Handle<String>::null(),
symbol_id + 1 - symbol_cache_.length());
}
Handle<String> result = symbol_cache_.at(symbol_id);
if (result.is_null()) {
if (scanner().is_literal_ascii()) {
result = isolate()->factory()->LookupAsciiSymbol(
scanner().literal_ascii_string());
} else {
result = isolate()->factory()->LookupTwoByteSymbol(
scanner().literal_uc16_string());
}
symbol_cache_.at(symbol_id) = result;
return result;
}
isolate()->counters()->total_preparse_symbols_skipped()->Increment();
return result;
}
FunctionEntry ScriptDataImpl::GetFunctionEntry(int start) {
// The current pre-data entry must be a FunctionEntry with the given
// start position.
if ((function_index_ + FunctionEntry::kSize <= store_.length())
&& (static_cast<int>(store_[function_index_]) == start)) {
int index = function_index_;
function_index_ += FunctionEntry::kSize;
return FunctionEntry(store_.SubVector(index,
index + FunctionEntry::kSize));
}
return FunctionEntry();
}
int ScriptDataImpl::GetSymbolIdentifier() {
return ReadNumber(&symbol_data_);
}
bool ScriptDataImpl::SanityCheck() {
// Check that the header data is valid and doesn't specify
// point to positions outside the store.
if (store_.length() < PreparseDataConstants::kHeaderSize) return false;
if (magic() != PreparseDataConstants::kMagicNumber) return false;
if (version() != PreparseDataConstants::kCurrentVersion) return false;
if (has_error()) {
// Extra sane sanity check for error message encoding.
if (store_.length() <= PreparseDataConstants::kHeaderSize
+ PreparseDataConstants::kMessageTextPos) {
return false;
}
if (Read(PreparseDataConstants::kMessageStartPos) >
Read(PreparseDataConstants::kMessageEndPos)) {
return false;
}
unsigned arg_count = Read(PreparseDataConstants::kMessageArgCountPos);
int pos = PreparseDataConstants::kMessageTextPos;
for (unsigned int i = 0; i <= arg_count; i++) {
if (store_.length() <= PreparseDataConstants::kHeaderSize + pos) {
return false;
}
int length = static_cast<int>(Read(pos));
if (length < 0) return false;
pos += 1 + length;
}
if (store_.length() < PreparseDataConstants::kHeaderSize + pos) {
return false;
}
return true;
}
// Check that the space allocated for function entries is sane.
int functions_size =
static_cast<int>(store_[PreparseDataConstants::kFunctionsSizeOffset]);
if (functions_size < 0) return false;
if (functions_size % FunctionEntry::kSize != 0) return false;
// Check that the count of symbols is non-negative.
int symbol_count =
static_cast<int>(store_[PreparseDataConstants::kSymbolCountOffset]);
if (symbol_count < 0) return false;
// Check that the total size has room for header and function entries.
int minimum_size =
PreparseDataConstants::kHeaderSize + functions_size;
if (store_.length() < minimum_size) return false;
return true;
}
const char* ScriptDataImpl::ReadString(unsigned* start, int* chars) {
int length = start[0];
char* result = NewArray<char>(length + 1);
for (int i = 0; i < length; i++) {
result[i] = start[i + 1];
}
result[length] = '\0';
if (chars != NULL) *chars = length;
return result;
}
Scanner::Location ScriptDataImpl::MessageLocation() {
int beg_pos = Read(PreparseDataConstants::kMessageStartPos);
int end_pos = Read(PreparseDataConstants::kMessageEndPos);
return Scanner::Location(beg_pos, end_pos);
}
const char* ScriptDataImpl::BuildMessage() {
unsigned* start = ReadAddress(PreparseDataConstants::kMessageTextPos);
return ReadString(start, NULL);
}
Vector<const char*> ScriptDataImpl::BuildArgs() {
int arg_count = Read(PreparseDataConstants::kMessageArgCountPos);
const char** array = NewArray<const char*>(arg_count);
// Position after text found by skipping past length field and
// length field content words.
int pos = PreparseDataConstants::kMessageTextPos + 1
+ Read(PreparseDataConstants::kMessageTextPos);
for (int i = 0; i < arg_count; i++) {
int count = 0;
array[i] = ReadString(ReadAddress(pos), &count);
pos += count + 1;
}
return Vector<const char*>(array, arg_count);
}
unsigned ScriptDataImpl::Read(int position) {
return store_[PreparseDataConstants::kHeaderSize + position];
}
unsigned* ScriptDataImpl::ReadAddress(int position) {
return &store_[PreparseDataConstants::kHeaderSize + position];
}
Scope* Parser::NewScope(Scope* parent, ScopeType type) {
Scope* result = new(zone()) Scope(parent, type);
result->Initialize();
return result;
}
// ----------------------------------------------------------------------------
// Target is a support class to facilitate manipulation of the
// Parser's target_stack_ (the stack of potential 'break' and
// 'continue' statement targets). Upon construction, a new target is
// added; it is removed upon destruction.
class Target BASE_EMBEDDED {
public:
Target(Target** variable, AstNode* node)
: variable_(variable), node_(node), previous_(*variable) {
*variable = this;
}
~Target() {
*variable_ = previous_;
}
Target* previous() { return previous_; }
AstNode* node() { return node_; }
private:
Target** variable_;
AstNode* node_;
Target* previous_;
};
class TargetScope BASE_EMBEDDED {
public:
explicit TargetScope(Target** variable)
: variable_(variable), previous_(*variable) {
*variable = NULL;
}
~TargetScope() {
*variable_ = previous_;
}
private:
Target** variable_;
Target* previous_;
};
// ----------------------------------------------------------------------------
// FunctionState and BlockState together implement the parser's scope stack.
// The parser's current scope is in top_scope_. The BlockState and
// FunctionState constructors push on the scope stack and the destructors
// pop. They are also used to hold the parser's per-function and per-block
// state.
class Parser::BlockState BASE_EMBEDDED {
public:
BlockState(Parser* parser, Scope* scope)
: parser_(parser),
outer_scope_(parser->top_scope_) {
parser->top_scope_ = scope;
}
~BlockState() { parser_->top_scope_ = outer_scope_; }
private:
Parser* parser_;
Scope* outer_scope_;
};
class Parser::FunctionState BASE_EMBEDDED {
public:
FunctionState(Parser* parser, Scope* scope, Isolate* isolate);
~FunctionState();
int NextMaterializedLiteralIndex() {
return next_materialized_literal_index_++;
}
int materialized_literal_count() {
return next_materialized_literal_index_ - JSFunction::kLiteralsPrefixSize;
}
int NextHandlerIndex() { return next_handler_index_++; }
int handler_count() { return next_handler_index_; }
void SetThisPropertyAssignmentInfo(
bool only_simple_this_property_assignments,
Handle<FixedArray> this_property_assignments) {
only_simple_this_property_assignments_ =
only_simple_this_property_assignments;
this_property_assignments_ = this_property_assignments;
}
bool only_simple_this_property_assignments() {
return only_simple_this_property_assignments_;
}
Handle<FixedArray> this_property_assignments() {
return this_property_assignments_;
}
void AddProperty() { expected_property_count_++; }
int expected_property_count() { return expected_property_count_; }
private:
// Used to assign an index to each literal that needs materialization in
// the function. Includes regexp literals, and boilerplate for object and
// array literals.
int next_materialized_literal_index_;
// Used to assign a per-function index to try and catch handlers.
int next_handler_index_;
// Properties count estimation.
int expected_property_count_;
// Keeps track of assignments to properties of this. Used for
// optimizing constructors.
bool only_simple_this_property_assignments_;
Handle<FixedArray> this_property_assignments_;
Parser* parser_;
FunctionState* outer_function_state_;
Scope* outer_scope_;
unsigned saved_ast_node_id_;
};
Parser::FunctionState::FunctionState(Parser* parser,
Scope* scope,
Isolate* isolate)
: next_materialized_literal_index_(JSFunction::kLiteralsPrefixSize),
next_handler_index_(0),
expected_property_count_(0),
only_simple_this_property_assignments_(false),
this_property_assignments_(isolate->factory()->empty_fixed_array()),
parser_(parser),
outer_function_state_(parser->current_function_state_),
outer_scope_(parser->top_scope_),
saved_ast_node_id_(isolate->ast_node_id()) {
parser->top_scope_ = scope;
parser->current_function_state_ = this;
isolate->set_ast_node_id(AstNode::kDeclarationsId + 1);
}
Parser::FunctionState::~FunctionState() {
parser_->top_scope_ = outer_scope_;
parser_->current_function_state_ = outer_function_state_;
parser_->isolate()->set_ast_node_id(saved_ast_node_id_);
}
// ----------------------------------------------------------------------------
// The CHECK_OK macro is a convenient macro to enforce error
// handling for functions that may fail (by returning !*ok).
//
// CAUTION: This macro appends extra statements after a call,
// thus it must never be used where only a single statement
// is correct (e.g. an if statement branch w/o braces)!
#define CHECK_OK ok); \
if (!*ok) return NULL; \
((void)0
#define DUMMY ) // to make indentation work
#undef DUMMY
#define CHECK_FAILED /**/); \
if (failed_) return NULL; \
((void)0
#define DUMMY ) // to make indentation work
#undef DUMMY
// ----------------------------------------------------------------------------
// Implementation of Parser
Parser::Parser(Handle<Script> script,
int parser_flags,
v8::Extension* extension,
ScriptDataImpl* pre_data)
: isolate_(script->GetIsolate()),
symbol_cache_(pre_data ? pre_data->symbol_count() : 0),
script_(script),
scanner_(isolate_->unicode_cache()),
reusable_preparser_(NULL),
top_scope_(NULL),
current_function_state_(NULL),
target_stack_(NULL),
extension_(extension),
pre_data_(pre_data),
fni_(NULL),
allow_natives_syntax_((parser_flags & kAllowNativesSyntax) != 0),
allow_lazy_((parser_flags & kAllowLazy) != 0),
stack_overflow_(false),
parenthesized_function_(false) {
AstNode::ResetIds();
if ((parser_flags & kLanguageModeMask) == EXTENDED_MODE) {
scanner().SetHarmonyScoping(true);
}
}
FunctionLiteral* Parser::ParseProgram(CompilationInfo* info) {
ZoneScope zone_scope(isolate(), DONT_DELETE_ON_EXIT);
HistogramTimerScope timer(isolate()->counters()->parse());
Handle<String> source(String::cast(script_->source()));
isolate()->counters()->total_parse_size()->Increment(source->length());
fni_ = new(zone()) FuncNameInferrer(isolate());
// Initialize parser state.
source->TryFlatten();
if (source->IsExternalTwoByteString()) {
// Notice that the stream is destroyed at the end of the branch block.
// The last line of the blocks can't be moved outside, even though they're
// identical calls.
ExternalTwoByteStringUC16CharacterStream stream(
Handle<ExternalTwoByteString>::cast(source), 0, source->length());
scanner_.Initialize(&stream);
return DoParseProgram(info, source, &zone_scope);
} else {
GenericStringUC16CharacterStream stream(source, 0, source->length());
scanner_.Initialize(&stream);
return DoParseProgram(info, source, &zone_scope);
}
}
FunctionLiteral* Parser::DoParseProgram(CompilationInfo* info,
Handle<String> source,
ZoneScope* zone_scope) {
ASSERT(top_scope_ == NULL);
ASSERT(target_stack_ == NULL);
if (pre_data_ != NULL) pre_data_->Initialize();
// Compute the parsing mode.
mode_ = (FLAG_lazy && allow_lazy_) ? PARSE_LAZILY : PARSE_EAGERLY;
if (allow_natives_syntax_ || extension_ != NULL) mode_ = PARSE_EAGERLY;
Handle<String> no_name = isolate()->factory()->empty_symbol();
FunctionLiteral* result = NULL;
{ Scope* scope = NewScope(top_scope_, GLOBAL_SCOPE);
info->SetGlobalScope(scope);
if (!info->is_global()) {
scope = Scope::DeserializeScopeChain(*info->calling_context(), scope);
scope = NewScope(scope, EVAL_SCOPE);
}
scope->set_start_position(0);
scope->set_end_position(source->length());
FunctionState function_state(this, scope, isolate());
top_scope_->SetLanguageMode(info->language_mode());
ZoneList<Statement*>* body = new(zone()) ZoneList<Statement*>(16);
bool ok = true;
int beg_loc = scanner().location().beg_pos;
ParseSourceElements(body, Token::EOS, &ok);
if (ok && !top_scope_->is_classic_mode()) {
CheckOctalLiteral(beg_loc, scanner().location().end_pos, &ok);
}
if (ok && is_extended_mode()) {
CheckConflictingVarDeclarations(scope, &ok);
}
if (ok) {
result = new(zone()) FunctionLiteral(
isolate(),
no_name,
top_scope_,
body,
function_state.materialized_literal_count(),
function_state.expected_property_count(),
function_state.handler_count(),
function_state.only_simple_this_property_assignments(),
function_state.this_property_assignments(),
0,
FunctionLiteral::ANONYMOUS_EXPRESSION,
false); // Does not have duplicate parameters.
} else if (stack_overflow_) {
isolate()->StackOverflow();
}
}
// Make sure the target stack is empty.
ASSERT(target_stack_ == NULL);
// If there was a syntax error we have to get rid of the AST
// and it is not safe to do so before the scope has been deleted.
if (result == NULL) zone_scope->DeleteOnExit();
return result;
}
FunctionLiteral* Parser::ParseLazy(CompilationInfo* info) {
ZoneScope zone_scope(isolate(), DONT_DELETE_ON_EXIT);
HistogramTimerScope timer(isolate()->counters()->parse_lazy());
Handle<String> source(String::cast(script_->source()));
isolate()->counters()->total_parse_size()->Increment(source->length());
Handle<SharedFunctionInfo> shared_info = info->shared_info();
// Initialize parser state.
source->TryFlatten();
if (source->IsExternalTwoByteString()) {
ExternalTwoByteStringUC16CharacterStream stream(
Handle<ExternalTwoByteString>::cast(source),
shared_info->start_position(),
shared_info->end_position());
FunctionLiteral* result = ParseLazy(info, &stream, &zone_scope);
return result;
} else {
GenericStringUC16CharacterStream stream(source,
shared_info->start_position(),
shared_info->end_position());
FunctionLiteral* result = ParseLazy(info, &stream, &zone_scope);
return result;
}
}
FunctionLiteral* Parser::ParseLazy(CompilationInfo* info,
UC16CharacterStream* source,
ZoneScope* zone_scope) {
Handle<SharedFunctionInfo> shared_info = info->shared_info();
scanner_.Initialize(source);
ASSERT(top_scope_ == NULL);
ASSERT(target_stack_ == NULL);
Handle<String> name(String::cast(shared_info->name()));
fni_ = new(zone()) FuncNameInferrer(isolate());
fni_->PushEnclosingName(name);
mode_ = PARSE_EAGERLY;
// Place holder for the result.
FunctionLiteral* result = NULL;
{
// Parse the function literal.
Scope* scope = NewScope(top_scope_, GLOBAL_SCOPE);
info->SetGlobalScope(scope);
if (!info->closure().is_null()) {
scope = Scope::DeserializeScopeChain(info->closure()->context(), scope);
}
FunctionState function_state(this, scope, isolate());
ASSERT(scope->language_mode() != STRICT_MODE || !info->is_classic_mode());
ASSERT(scope->language_mode() != EXTENDED_MODE ||
info->is_extended_mode());
ASSERT(info->language_mode() == shared_info->language_mode());
scope->SetLanguageMode(shared_info->language_mode());
FunctionLiteral::Type type = shared_info->is_expression()
? (shared_info->is_anonymous()
? FunctionLiteral::ANONYMOUS_EXPRESSION
: FunctionLiteral::NAMED_EXPRESSION)
: FunctionLiteral::DECLARATION;
bool ok = true;
result = ParseFunctionLiteral(name,
false, // Strict mode name already checked.
RelocInfo::kNoPosition,
type,
&ok);
// Make sure the results agree.
ASSERT(ok == (result != NULL));
}
// Make sure the target stack is empty.
ASSERT(target_stack_ == NULL);
// If there was a stack overflow we have to get rid of AST and it is
// not safe to do before scope has been deleted.
if (result == NULL) {
zone_scope->DeleteOnExit();
if (stack_overflow_) isolate()->StackOverflow();
} else {
Handle<String> inferred_name(shared_info->inferred_name());
result->set_inferred_name(inferred_name);
}
return result;
}
Handle<String> Parser::GetSymbol(bool* ok) {
int symbol_id = -1;
if (pre_data() != NULL) {
symbol_id = pre_data()->GetSymbolIdentifier();
}
return LookupSymbol(symbol_id);
}
void Parser::ReportMessage(const char* type, Vector<const char*> args) {
Scanner::Location source_location = scanner().location();
ReportMessageAt(source_location, type, args);
}
void Parser::ReportMessageAt(Scanner::Location source_location,
const char* type,
Vector<const char*> args) {
MessageLocation location(script_,
source_location.beg_pos,
source_location.end_pos);
Factory* factory = isolate()->factory();
Handle<FixedArray> elements = factory->NewFixedArray(args.length());
for (int i = 0; i < args.length(); i++) {
Handle<String> arg_string = factory->NewStringFromUtf8(CStrVector(args[i]));
elements->set(i, *arg_string);
}
Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
Handle<Object> result = factory->NewSyntaxError(type, array);
isolate()->Throw(*result, &location);
}
void Parser::ReportMessageAt(Scanner::Location source_location,
const char* type,
Vector<Handle<String> > args) {
MessageLocation location(script_,
source_location.beg_pos,
source_location.end_pos);
Factory* factory = isolate()->factory();
Handle<FixedArray> elements = factory->NewFixedArray(args.length());
for (int i = 0; i < args.length(); i++) {
elements->set(i, *args[i]);
}
Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
Handle<Object> result = factory->NewSyntaxError(type, array);
isolate()->Throw(*result, &location);
}
// Base class containing common code for the different finder classes used by
// the parser.
class ParserFinder {
protected:
ParserFinder() {}
static Assignment* AsAssignment(Statement* stat) {
if (stat == NULL) return NULL;
ExpressionStatement* exp_stat = stat->AsExpressionStatement();
if (exp_stat == NULL) return NULL;
return exp_stat->expression()->AsAssignment();
}
};
// An InitializationBlockFinder finds and marks sequences of statements of the
// form expr.a = ...; expr.b = ...; etc.
class InitializationBlockFinder : public ParserFinder {
public:
// We find and mark the initialization blocks in top level
// non-looping code only. This is because the optimization prevents
// reuse of the map transitions, so it should be used only for code
// that will only be run once.
InitializationBlockFinder(Scope* top_scope, Target* target)
: enabled_(top_scope->DeclarationScope()->is_global_scope() &&
!IsLoopTarget(target)),
first_in_block_(NULL),
last_in_block_(NULL),
block_size_(0) {}
~InitializationBlockFinder() {
if (!enabled_) return;
if (InBlock()) EndBlock();
}
void Update(Statement* stat) {
if (!enabled_) return;
Assignment* assignment = AsAssignment(stat);
if (InBlock()) {
if (BlockContinues(assignment)) {
UpdateBlock(assignment);
} else {
EndBlock();
}
}
if (!InBlock() && (assignment != NULL) &&
(assignment->op() == Token::ASSIGN)) {
StartBlock(assignment);
}
}
private:
// The minimum number of contiguous assignment that will
// be treated as an initialization block. Benchmarks show that
// the overhead exceeds the savings below this limit.
static const int kMinInitializationBlock = 3;
static bool IsLoopTarget(Target* target) {
while (target != NULL) {
if (target->node()->AsIterationStatement() != NULL) return true;
target = target->previous();
}
return false;
}
// Returns true if the expressions appear to denote the same object.
// In the context of initialization blocks, we only consider expressions
// of the form 'expr.x' or expr["x"].
static bool SameObject(Expression* e1, Expression* e2) {
VariableProxy* v1 = e1->AsVariableProxy();
VariableProxy* v2 = e2->AsVariableProxy();
if (v1 != NULL && v2 != NULL) {
return v1->name()->Equals(*v2->name());
}
Property* p1 = e1->AsProperty();
Property* p2 = e2->AsProperty();
if ((p1 == NULL) || (p2 == NULL)) return false;
Literal* key1 = p1->key()->AsLiteral();
Literal* key2 = p2->key()->AsLiteral();
if ((key1 == NULL) || (key2 == NULL)) return false;
if (!key1->handle()->IsString() || !key2->handle()->IsString()) {
return false;
}
String* name1 = String::cast(*key1->handle());
String* name2 = String::cast(*key2->handle());
if (!name1->Equals(name2)) return false;
return SameObject(p1->obj(), p2->obj());
}
// Returns true if the expressions appear to denote different properties
// of the same object.
static bool PropertyOfSameObject(Expression* e1, Expression* e2) {
Property* p1 = e1->AsProperty();
Property* p2 = e2->AsProperty();
if ((p1 == NULL) || (p2 == NULL)) return false;
return SameObject(p1->obj(), p2->obj());
}
bool BlockContinues(Assignment* assignment) {
if ((assignment == NULL) || (first_in_block_ == NULL)) return false;
if (assignment->op() != Token::ASSIGN) return false;
return PropertyOfSameObject(first_in_block_->target(),
assignment->target());
}
void StartBlock(Assignment* assignment) {
first_in_block_ = assignment;
last_in_block_ = assignment;
block_size_ = 1;
}
void UpdateBlock(Assignment* assignment) {
last_in_block_ = assignment;
++block_size_;
}
void EndBlock() {
if (block_size_ >= kMinInitializationBlock) {
first_in_block_->mark_block_start();
last_in_block_->mark_block_end();
}
last_in_block_ = first_in_block_ = NULL;
block_size_ = 0;
}
bool InBlock() { return first_in_block_ != NULL; }
const bool enabled_;
Assignment* first_in_block_;
Assignment* last_in_block_;
int block_size_;
DISALLOW_COPY_AND_ASSIGN(InitializationBlockFinder);
};
// A ThisNamedPropertyAssignmentFinder finds and marks statements of the form
// this.x = ...;, where x is a named property. It also determines whether a
// function contains only assignments of this type.
class ThisNamedPropertyAssignmentFinder : public ParserFinder {
public:
explicit ThisNamedPropertyAssignmentFinder(Isolate* isolate)
: isolate_(isolate),
only_simple_this_property_assignments_(true),
names_(0),
assigned_arguments_(0),
assigned_constants_(0) {
}
void Update(Scope* scope, Statement* stat) {
// Bail out if function already has property assignment that are
// not simple this property assignments.
if (!only_simple_this_property_assignments_) {
return;
}
// Check whether this statement is of the form this.x = ...;
Assignment* assignment = AsAssignment(stat);
if (IsThisPropertyAssignment(assignment)) {
HandleThisPropertyAssignment(scope, assignment);
} else {
only_simple_this_property_assignments_ = false;
}
}
// Returns whether only statements of the form this.x = y; where y is either a
// constant or a function argument was encountered.
bool only_simple_this_property_assignments() {
return only_simple_this_property_assignments_;
}
// Returns a fixed array containing three elements for each assignment of the
// form this.x = y;
Handle<FixedArray> GetThisPropertyAssignments() {
if (names_.is_empty()) {
return isolate_->factory()->empty_fixed_array();
}
ASSERT_EQ(names_.length(), assigned_arguments_.length());
ASSERT_EQ(names_.length(), assigned_constants_.length());
Handle<FixedArray> assignments =
isolate_->factory()->NewFixedArray(names_.length() * 3);
for (int i = 0; i < names_.length(); ++i) {
assignments->set(i * 3, *names_[i]);
assignments->set(i * 3 + 1, Smi::FromInt(assigned_arguments_[i]));
assignments->set(i * 3 + 2, *assigned_constants_[i]);
}
return assignments;
}
private:
bool IsThisPropertyAssignment(Assignment* assignment) {
if (assignment != NULL) {
Property* property = assignment->target()->AsProperty();
return assignment->op() == Token::ASSIGN
&& property != NULL
&& property->obj()->AsVariableProxy() != NULL
&& property->obj()->AsVariableProxy()->is_this();
}
return false;
}
void HandleThisPropertyAssignment(Scope* scope, Assignment* assignment) {
// Check that the property assigned to is a named property, which is not
// __proto__.
Property* property = assignment->target()->AsProperty();
ASSERT(property != NULL);
Literal* literal = property->key()->AsLiteral();
uint32_t dummy;
if (literal != NULL &&
literal->handle()->IsString() &&
!String::cast(*(literal->handle()))->Equals(
isolate_->heap()->Proto_symbol()) &&
!String::cast(*(literal->handle()))->AsArrayIndex(&dummy)) {
Handle<String> key = Handle<String>::cast(literal->handle());
// Check whether the value assigned is either a constant or matches the
// name of one of the arguments to the function.
if (assignment->value()->AsLiteral() != NULL) {
// Constant assigned.
Literal* literal = assignment->value()->AsLiteral();
AssignmentFromConstant(key, literal->handle());
return;
} else if (assignment->value()->AsVariableProxy() != NULL) {
// Variable assigned.
Handle<String> name =
assignment->value()->AsVariableProxy()->name();
// Check whether the variable assigned matches an argument name.
for (int i = 0; i < scope->num_parameters(); i++) {
if (*scope->parameter(i)->name() == *name) {
// Assigned from function argument.
AssignmentFromParameter(key, i);
return;
}
}
}
}
// It is not a simple "this.x = value;" assignment with a constant
// or parameter value.
AssignmentFromSomethingElse();
}
// We will potentially reorder the property assignments, so they must be
// simple enough that the ordering does not matter.
void AssignmentFromParameter(Handle<String> name, int index) {
EnsureInitialized();
for (int i = 0; i < names_.length(); ++i) {
if (name->Equals(*names_[i])) {
assigned_arguments_[i] = index;
assigned_constants_[i] = isolate_->factory()->undefined_value();
return;
}
}
names_.Add(name);
assigned_arguments_.Add(index);
assigned_constants_.Add(isolate_->factory()->undefined_value());
}
void AssignmentFromConstant(Handle<String> name, Handle<Object> value) {
EnsureInitialized();
for (int i = 0; i < names_.length(); ++i) {
if (name->Equals(*names_[i])) {
assigned_arguments_[i] = -1;
assigned_constants_[i] = value;
return;
}
}
names_.Add(name);
assigned_arguments_.Add(-1);
assigned_constants_.Add(value);
}
void AssignmentFromSomethingElse() {
// The this assignment is not a simple one.
only_simple_this_property_assignments_ = false;
}
void EnsureInitialized() {
if (names_.capacity() == 0) {
ASSERT(assigned_arguments_.capacity() == 0);
ASSERT(assigned_constants_.capacity() == 0);
names_.Initialize(4);
assigned_arguments_.Initialize(4);
assigned_constants_.Initialize(4);
}
}
Isolate* isolate_;
bool only_simple_this_property_assignments_;
ZoneStringList names_;
ZoneList<int> assigned_arguments_;
ZoneObjectList assigned_constants_;
};
Statement* Parser::ParseSourceElement(ZoneStringList* labels,
bool* ok) {
// (Ecma 262 5th Edition, clause 14):
// SourceElement:
// Statement
// FunctionDeclaration
//
// In harmony mode we allow additionally the following productions
// SourceElement:
// LetDeclaration
// ConstDeclaration
if (peek() == Token::FUNCTION) {
return ParseFunctionDeclaration(ok);
} else if (peek() == Token::LET || peek() == Token::CONST) {
return ParseVariableStatement(kSourceElement, ok);
}
return ParseStatement(labels, ok);
}
void* Parser::ParseSourceElements(ZoneList<Statement*>* processor,
int end_token,
bool* ok) {
// SourceElements ::
// (SourceElement)* <end_token>
// Allocate a target stack to use for this set of source
// elements. This way, all scripts and functions get their own
// target stack thus avoiding illegal breaks and continues across
// functions.
TargetScope scope(&this->target_stack_);
ASSERT(processor != NULL);
InitializationBlockFinder block_finder(top_scope_, target_stack_);
ThisNamedPropertyAssignmentFinder this_property_assignment_finder(isolate());
bool directive_prologue = true; // Parsing directive prologue.
while (peek() != end_token) {
if (directive_prologue && peek() != Token::STRING) {
directive_prologue = false;
}
Scanner::Location token_loc = scanner().peek_location();
Statement* stat = ParseSourceElement(NULL, CHECK_OK);
if (stat == NULL || stat->IsEmpty()) {
directive_prologue = false; // End of directive prologue.
continue;
}
if (directive_prologue) {
// A shot at a directive.
ExpressionStatement *e_stat;
Literal *literal;
// Still processing directive prologue?
if ((e_stat = stat->AsExpressionStatement()) != NULL &&
(literal = e_stat->expression()->AsLiteral()) != NULL &&
literal->handle()->IsString()) {
Handle<String> directive = Handle<String>::cast(literal->handle());
// Check "use strict" directive (ES5 14.1).
if (top_scope_->is_classic_mode() &&
directive->Equals(isolate()->heap()->use_strict()) &&
token_loc.end_pos - token_loc.beg_pos ==
isolate()->heap()->use_strict()->length() + 2) {
// TODO(ES6): Fix entering extended mode, once it is specified.
top_scope_->SetLanguageMode(FLAG_harmony_scoping
? EXTENDED_MODE : STRICT_MODE);
// "use strict" is the only directive for now.
directive_prologue = false;
}
} else {
// End of the directive prologue.
directive_prologue = false;
}
}
block_finder.Update(stat);
// Find and mark all assignments to named properties in this (this.x =)
if (top_scope_->is_function_scope()) {
this_property_assignment_finder.Update(top_scope_, stat);
}
processor->Add(stat);
}
// Propagate the collected information on this property assignments.
if (top_scope_->is_function_scope()) {
bool only_simple_this_property_assignments =
this_property_assignment_finder.only_simple_this_property_assignments()
&& top_scope_->declarations()->length() == 0;
if (only_simple_this_property_assignments) {
current_function_state_->SetThisPropertyAssignmentInfo(
only_simple_this_property_assignments,
this_property_assignment_finder.GetThisPropertyAssignments());
}
}
return 0;
}
Statement* Parser::ParseStatement(ZoneStringList* labels, bool* ok) {
// Statement ::
// Block
// VariableStatement
// EmptyStatement
// ExpressionStatement
// IfStatement
// IterationStatement
// ContinueStatement
// BreakStatement
// ReturnStatement
// WithStatement
// LabelledStatement
// SwitchStatement
// ThrowStatement
// TryStatement
// DebuggerStatement
// Note: Since labels can only be used by 'break' and 'continue'
// statements, which themselves are only valid within blocks,
// iterations or 'switch' statements (i.e., BreakableStatements),
// labels can be simply ignored in all other cases; except for
// trivial labeled break statements 'label: break label' which is
// parsed into an empty statement.
// Keep the source position of the statement
int statement_pos = scanner().peek_location().beg_pos;
Statement* stmt = NULL;
switch (peek()) {
case Token::LBRACE:
return ParseBlock(labels, ok);
case Token::CONST: // fall through
case Token::LET:
case Token::VAR:
stmt = ParseVariableStatement(kStatement, ok);
break;
case Token::SEMICOLON:
Next();
return EmptyStatement();
case Token::IF:
stmt = ParseIfStatement(labels, ok);
break;
case Token::DO:
stmt = ParseDoWhileStatement(labels, ok);
break;
case Token::WHILE:
stmt = ParseWhileStatement(labels, ok);
break;
case Token::FOR:
stmt = ParseForStatement(labels, ok);
break;
case Token::CONTINUE:
stmt = ParseContinueStatement(ok);
break;
case Token::BREAK:
stmt = ParseBreakStatement(labels, ok);
break;
case Token::RETURN:
stmt = ParseReturnStatement(ok);
break;
case Token::WITH:
stmt = ParseWithStatement(labels, ok);
break;
case Token::SWITCH:
stmt = ParseSwitchStatement(labels, ok);
break;
case Token::THROW:
stmt = ParseThrowStatement(ok);
break;
case Token::TRY: {
// NOTE: It is somewhat complicated to have labels on
// try-statements. When breaking out of a try-finally statement,
// one must take great care not to treat it as a
// fall-through. It is much easier just to wrap the entire
// try-statement in a statement block and put the labels there
Block* result = new(zone()) Block(isolate(), labels, 1, false);
Target target(&this->target_stack_, result);
TryStatement* statement = ParseTryStatement(CHECK_OK);
if (statement) {
statement->set_statement_pos(statement_pos);
}
if (result) result->AddStatement(statement);
return result;
}
case Token::FUNCTION: {
// FunctionDeclaration is only allowed in the context of SourceElements
// (Ecma 262 5th Edition, clause 14):
// SourceElement:
// Statement
// FunctionDeclaration
// Common language extension is to allow function declaration in place
// of any statement. This language extension is disabled in strict mode.
if (!top_scope_->is_classic_mode()) {
ReportMessageAt(scanner().peek_location(), "strict_function",
Vector<const char*>::empty());
*ok = false;
return NULL;
}
return ParseFunctionDeclaration(ok);
}
case Token::DEBUGGER:
stmt = ParseDebuggerStatement(ok);
break;
default:
stmt = ParseExpressionOrLabelledStatement(labels, ok);
}
// Store the source position of the statement
if (stmt != NULL) stmt->set_statement_pos(statement_pos);
return stmt;
}
VariableProxy* Parser::Declare(Handle<String> name,
VariableMode mode,
FunctionLiteral* fun,
bool resolve,
bool* ok) {
Variable* var = NULL;
// If we are inside a function, a declaration of a var/const variable is a
// truly local variable, and the scope of the variable is always the function
// scope.
// Let/const variables in harmony mode are always added to the immediately
// enclosing scope.
Scope* declaration_scope = (mode == LET || mode == CONST_HARMONY)
? top_scope_ : top_scope_->DeclarationScope();
InitializationFlag init_flag = (fun != NULL || mode == VAR)
? kCreatedInitialized : kNeedsInitialization;
// If a function scope exists, then we can statically declare this
// variable and also set its mode. In any case, a Declaration node
// will be added to the scope so that the declaration can be added
// to the corresponding activation frame at runtime if necessary.
// For instance declarations inside an eval scope need to be added
// to the calling function context.
// Similarly, strict mode eval scope does not leak variable declarations to
// the caller's scope so we declare all locals, too.
// Also for block scoped let/const bindings the variable can be
// statically declared.
if (declaration_scope->is_function_scope() ||
declaration_scope->is_strict_or_extended_eval_scope() ||
declaration_scope->is_block_scope()) {
// Declare the variable in the function scope.
var = declaration_scope->LocalLookup(name);
if (var == NULL) {
// Declare the name.
var = declaration_scope->DeclareLocal(name, mode, init_flag);
} else {
// The name was declared in this scope before; check for conflicting
// re-declarations. We have a conflict if either of the declarations is
// not a var. There is similar code in runtime.cc in the Declare
// functions. The function CheckNonConflictingScope checks for conflicting
// var and let bindings from different scopes whereas this is a check for
// conflicting declarations within the same scope. This check also covers
//
// function () { let x; { var x; } }
//
// because the var declaration is hoisted to the function scope where 'x'
// is already bound.
if ((mode != VAR) || (var->mode() != VAR)) {
// We only have vars, consts and lets in declarations.
ASSERT(var->mode() == VAR ||
var->mode() == CONST ||
var->mode() == CONST_HARMONY ||
var->mode() == LET);
if (is_extended_mode()) {
// In harmony mode we treat re-declarations as early errors. See
// ES5 16 for a definition of early errors.
SmartArrayPointer<char> c_string = name->ToCString(DISALLOW_NULLS);
const char* elms[2] = { "Variable", *c_string };
Vector<const char*> args(elms, 2);
ReportMessage("redeclaration", args);
*ok = false;
return NULL;
}
const char* type = (var->mode() == VAR)
? "var" : var->is_const_mode() ? "const" : "let";
Handle<String> type_string =
isolate()->factory()->NewStringFromUtf8(CStrVector(type), TENURED);
Expression* expression =
NewThrowTypeError(isolate()->factory()->redeclaration_symbol(),
type_string, name);
declaration_scope->SetIllegalRedeclaration(expression);
}
}
}
// We add a declaration node for every declaration. The compiler
// will only generate code if necessary. In particular, declarations
// for inner local variables that do not represent functions won't
// result in any generated code.
//
// Note that we always add an unresolved proxy even if it's not
// used, simply because we don't know in this method (w/o extra
// parameters) if the proxy is needed or not. The proxy will be
// bound during variable resolution time unless it was pre-bound
// below.
//
// WARNING: This will lead to multiple declaration nodes for the
// same variable if it is declared several times. This is not a
// semantic issue as long as we keep the source order, but it may be
// a performance issue since it may lead to repeated
// Runtime::DeclareContextSlot() calls.
VariableProxy* proxy = declaration_scope->NewUnresolved(
name, scanner().location().beg_pos);
declaration_scope->AddDeclaration(
new(zone()) Declaration(proxy, mode, fun, top_scope_));
if ((mode == CONST || mode == CONST_HARMONY) &&
declaration_scope->is_global_scope()) {
// For global const variables we bind the proxy to a variable.
ASSERT(resolve); // should be set by all callers
Variable::Kind kind = Variable::NORMAL;
var = new(zone()) Variable(declaration_scope,
name,
mode,
true,
kind,
kNeedsInitialization);
} else if (declaration_scope->is_eval_scope() &&
declaration_scope->is_classic_mode()) {
// For variable declarations in a non-strict eval scope the proxy is bound
// to a lookup variable to force a dynamic declaration using the
// DeclareContextSlot runtime function.
Variable::Kind kind = Variable::NORMAL;
var = new(zone()) Variable(declaration_scope,
name,
mode,
true,
kind,
init_flag);
var->AllocateTo(Variable::LOOKUP, -1);
resolve = true;
}
// If requested and we have a local variable, bind the proxy to the variable
// at parse-time. This is used for functions (and consts) declared inside
// statements: the corresponding function (or const) variable must be in the
// function scope and not a statement-local scope, e.g. as provided with a
// 'with' statement:
//
// with (obj) {
// function f() {}
// }
//
// which is translated into:
//
// with (obj) {
// // in this case this is not: 'var f; f = function () {};'
// var f = function () {};
// }
//
// Note that if 'f' is accessed from inside the 'with' statement, it
// will be allocated in the context (because we must be able to look
// it up dynamically) but it will also be accessed statically, i.e.,
// with a context slot index and a context chain length for this
// initialization code. Thus, inside the 'with' statement, we need
// both access to the static and the dynamic context chain; the
// runtime needs to provide both.
if (resolve && var != NULL) proxy->BindTo(var);
return proxy;
}
// Language extension which is only enabled for source files loaded
// through the API's extension mechanism. A native function
// declaration is resolved by looking up the function through a
// callback provided by the extension.
Statement* Parser::ParseNativeDeclaration(bool* ok) {
Expect(Token::FUNCTION, CHECK_OK);
Handle<String> name = ParseIdentifier(CHECK_OK);
Expect(Token::LPAREN, CHECK_OK);
bool done = (peek() == Token::RPAREN);
while (!done) {
ParseIdentifier(CHECK_OK);
done = (peek() == Token::RPAREN);
if (!done) {
Expect(Token::COMMA, CHECK_OK);
}
}
Expect(Token::RPAREN, CHECK_OK);
Expect(Token::SEMICOLON, CHECK_OK);
// Make sure that the function containing the native declaration
// isn't lazily compiled. The extension structures are only
// accessible while parsing the first time not when reparsing
// because of lazy compilation.
top_scope_->DeclarationScope()->ForceEagerCompilation();
// Compute the function template for the native function.
v8::Handle<v8::FunctionTemplate> fun_template =
extension_->GetNativeFunction(v8::Utils::ToLocal(name));
ASSERT(!fun_template.IsEmpty());
// Instantiate the function and create a shared function info from it.
Handle<JSFunction> fun = Utils::OpenHandle(*fun_template->GetFunction());
const int literals = fun->NumberOfLiterals();
Handle<Code> code = Handle<Code>(fun->shared()->code());
Handle<Code> construct_stub = Handle<Code>(fun->shared()->construct_stub());
Handle<SharedFunctionInfo> shared =
isolate()->factory()->NewSharedFunctionInfo(name, literals, code,
Handle<ScopeInfo>(fun->shared()->scope_info()));
shared->set_construct_stub(*construct_stub);
// Copy the function data to the shared function info.
shared->set_function_data(fun->shared()->function_data());
int parameters = fun->shared()->formal_parameter_count();
shared->set_formal_parameter_count(parameters);
// TODO(1240846): It's weird that native function declarations are
// introduced dynamically when we meet their declarations, whereas
// other functions are setup when entering the surrounding scope.
SharedFunctionInfoLiteral* lit =
new(zone()) SharedFunctionInfoLiteral(isolate(), shared);
VariableProxy* var = Declare(name, VAR, NULL, true, CHECK_OK);
return new(zone()) ExpressionStatement(new(zone()) Assignment(
isolate(), Token::INIT_VAR, var, lit, RelocInfo::kNoPosition));
}
Statement* Parser::ParseFunctionDeclaration(bool* ok) {
// FunctionDeclaration ::
// 'function' Identifier '(' FormalParameterListopt ')' '{' FunctionBody '}'
Expect(Token::FUNCTION, CHECK_OK);
int function_token_position = scanner().location().beg_pos;
bool is_strict_reserved = false;
Handle<String> name = ParseIdentifierOrStrictReservedWord(
&is_strict_reserved, CHECK_OK);
FunctionLiteral* fun = ParseFunctionLiteral(name,
is_strict_reserved,
function_token_position,
FunctionLiteral::DECLARATION,
CHECK_OK);
// Even if we're not at the top-level of the global or a function
// scope, we treat is as such and introduce the function with it's
// initial value upon entering the corresponding scope.
VariableMode mode = is_extended_mode() ? LET : VAR;
Declare(name, mode, fun, true, CHECK_OK);
return EmptyStatement();
}
Block* Parser::ParseBlock(ZoneStringList* labels, bool* ok) {
if (top_scope_->is_extended_mode()) return ParseScopedBlock(labels, ok);
// Block ::
// '{' Statement* '}'
// Note that a Block does not introduce a new execution scope!
// (ECMA-262, 3rd, 12.2)
//
// Construct block expecting 16 statements.
Block* result = new(zone()) Block(isolate(), labels, 16, false);
Target target(&this->target_stack_, result);
Expect(Token::LBRACE, CHECK_OK);
InitializationBlockFinder block_finder(top_scope_, target_stack_);
while (peek() != Token::RBRACE) {
Statement* stat = ParseStatement(NULL, CHECK_OK);
if (stat && !stat->IsEmpty()) {
result->AddStatement(stat);
block_finder.Update(stat);
}
}
Expect(Token::RBRACE, CHECK_OK);
return result;
}
Block* Parser::ParseScopedBlock(ZoneStringList* labels, bool* ok) {
// The harmony mode uses source elements instead of statements.
//
// Block ::
// '{' SourceElement* '}'
// Construct block expecting 16 statements.
Block* body = new(zone()) Block(isolate(), labels, 16, false);
Scope* block_scope = NewScope(top_scope_, BLOCK_SCOPE);
// Parse the statements and collect escaping labels.
Expect(Token::LBRACE, CHECK_OK);
block_scope->set_start_position(scanner().location().beg_pos);
{ BlockState block_state(this, block_scope);
TargetCollector collector;
Target target(&this->target_stack_, &collector);
Target target_body(&this->target_stack_, body);
InitializationBlockFinder block_finder(top_scope_, target_stack_);
while (peek() != Token::RBRACE) {
Statement* stat = ParseSourceElement(NULL, CHECK_OK);
if (stat && !stat->IsEmpty()) {
body->AddStatement(stat);
block_finder.Update(stat);
}
}
}
Expect(Token::RBRACE, CHECK_OK);
block_scope->set_end_position(scanner().location().end_pos);
block_scope = block_scope->FinalizeBlockScope();
body->set_block_scope(block_scope);
return body;
}
Block* Parser::ParseVariableStatement(VariableDeclarationContext var_context,
bool* ok) {
// VariableStatement ::
// VariableDeclarations ';'
Handle<String> ignore;
Block* result = ParseVariableDeclarations(var_context,
NULL,
&ignore,
CHECK_OK);
ExpectSemicolon(CHECK_OK);
return result;
}
bool Parser::IsEvalOrArguments(Handle<String> string) {
return string.is_identical_to(isolate()->factory()->eval_symbol()) ||
string.is_identical_to(isolate()->factory()->arguments_symbol());
}
// If the variable declaration declares exactly one non-const
// variable, then *var is set to that variable. In all other cases,
// *var is untouched; in particular, it is the caller's responsibility
// to initialize it properly. This mechanism is used for the parsing
// of 'for-in' loops.
Block* Parser::ParseVariableDeclarations(
VariableDeclarationContext var_context,
VariableDeclarationProperties* decl_props,
Handle<String>* out,
bool* ok) {
// VariableDeclarations ::
// ('var' | 'const' | 'let') (Identifier ('=' AssignmentExpression)?)+[',']
//
// The ES6 Draft Rev3 specifies the following grammar for const declarations
//
// ConstDeclaration ::
// const ConstBinding (',' ConstBinding)* ';'
// ConstBinding ::
// Identifier '=' AssignmentExpression
//
// TODO(ES6):
// ConstBinding ::
// BindingPattern '=' AssignmentExpression
VariableMode mode = VAR;
// True if the binding needs initialization. 'let' and 'const' declared
// bindings are created uninitialized by their declaration nodes and
// need initialization. 'var' declared bindings are always initialized
// immediately by their declaration nodes.
bool needs_init = false;
bool is_const = false;
Token::Value init_op = Token::INIT_VAR;
if (peek() == Token::VAR) {
Consume(Token::VAR);
} else if (peek() == Token::CONST) {
// TODO(ES6): The ES6 Draft Rev4 section 12.2.2 reads:
//
// ConstDeclaration : const ConstBinding (',' ConstBinding)* ';'
//
// * It is a Syntax Error if the code that matches this production is not
// contained in extended code.
//
// However disallowing const in classic mode will break compatibility with
// existing pages. Therefore we keep allowing const with the old
// non-harmony semantics in classic mode.
Consume(Token::CONST);
switch (top_scope_->language_mode()) {
case CLASSIC_MODE:
mode = CONST;
init_op = Token::INIT_CONST;
break;
case STRICT_MODE:
ReportMessage("strict_const", Vector<const char*>::empty());
*ok = false;
return NULL;
case EXTENDED_MODE:
if (var_context != kSourceElement &&
var_context != kForStatement) {
// In extended mode 'const' declarations are only allowed in source
// element positions.
ReportMessage("unprotected_const", Vector<const char*>::empty());
*ok = false;
return NULL;
}
mode = CONST_HARMONY;
init_op = Token::INIT_CONST_HARMONY;
}
is_const = true;
needs_init = true;
} else if (peek() == Token::LET) {
// ES6 Draft Rev4 section 12.2.1:
//
// LetDeclaration : let LetBindingList ;
//
// * It is a Syntax Error if the code that matches this production is not
// contained in extended code.
if (!is_extended_mode()) {
ReportMessage("illegal_let", Vector<const char*>::empty());
*ok = false;
return NULL;
}
Consume(Token::LET);
if (var_context != kSourceElement &&
var_context != kForStatement) {
// Let declarations are only allowed in source element positions.
ASSERT(var_context == kStatement);
ReportMessage("unprotected_let", Vector<const char*>::empty());
*ok = false;
return NULL;
}
mode = LET;
needs_init = true;
init_op = Token::INIT_LET;
} else {
UNREACHABLE(); // by current callers
}
Scope* declaration_scope = (mode == LET || mode == CONST_HARMONY)
? top_scope_ : top_scope_->DeclarationScope();
// The scope of a var/const declared variable anywhere inside a function
// is the entire function (ECMA-262, 3rd, 10.1.3, and 12.2). Thus we can
// transform a source-level var/const declaration into a (Function)
// Scope declaration, and rewrite the source-level initialization into an
// assignment statement. We use a block to collect multiple assignments.
//
// We mark the block as initializer block because we don't want the
// rewriter to add a '.result' assignment to such a block (to get compliant
// behavior for code such as print(eval('var x = 7')), and for cosmetic
// reasons when pretty-printing. Also, unless an assignment (initialization)
// is inside an initializer block, it is ignored.
//
// Create new block with one expected declaration.
Block* block = new(zone()) Block(isolate(), NULL, 1, true);
int nvars = 0; // the number of variables declared
Handle<String> name;
do {
if (fni_ != NULL) fni_->Enter();
// Parse variable name.
if (nvars > 0) Consume(Token::COMMA);
name = ParseIdentifier(CHECK_OK);
if (fni_ != NULL) fni_->PushVariableName(name);
// Strict mode variables may not be named eval or arguments
if (!declaration_scope->is_classic_mode() && IsEvalOrArguments(name)) {
ReportMessage("strict_var_name", Vector<const char*>::empty());
*ok = false;
return NULL;
}
// Declare variable.
// Note that we *always* must treat the initial value via a separate init
// assignment for variables and constants because the value must be assigned
// when the variable is encountered in the source. But the variable/constant
// is declared (and set to 'undefined') upon entering the function within
// which the variable or constant is declared. Only function variables have
// an initial value in the declaration (because they are initialized upon
// entering the function).
//
// If we have a const declaration, in an inner scope, the proxy is always
// bound to the declared variable (independent of possibly surrounding with
// statements).
// For let/const declarations in harmony mode, we can also immediately
// pre-resolve the proxy because it resides in the same scope as the
// declaration.
VariableProxy* proxy = Declare(name, mode, NULL, mode != VAR, CHECK_OK);
nvars++;
if (declaration_scope->num_var_or_const() > kMaxNumFunctionLocals) {
ReportMessageAt(scanner().location(), "too_many_variables",
Vector<const char*>::empty());
*ok = false;
return NULL;
}
// Parse initialization expression if present and/or needed. A
// declaration of the form:
//
// var v = x;
//
// is syntactic sugar for:
//
// var v; v = x;
//
// In particular, we need to re-lookup 'v' (in top_scope_, not
// declaration_scope) as it may be a different 'v' than the 'v' in the
// declaration (e.g., if we are inside a 'with' statement or 'catch'
// block).
//
// However, note that const declarations are different! A const
// declaration of the form:
//
// const c = x;
//
// is *not* syntactic sugar for:
//
// const c; c = x;
//
// The "variable" c initialized to x is the same as the declared
// one - there is no re-lookup (see the last parameter of the
// Declare() call above).
Scope* initialization_scope = is_const ? declaration_scope : top_scope_;
Expression* value = NULL;
int position = -1;
// Harmony consts have non-optional initializers.
if (peek() == Token::ASSIGN || mode == CONST_HARMONY) {
Expect(Token::ASSIGN, CHECK_OK);
position = scanner().location().beg_pos;
value = ParseAssignmentExpression(var_context != kForStatement, CHECK_OK);
// Don't infer if it is "a = function(){...}();"-like expression.
if (fni_ != NULL &&
value->AsCall() == NULL &&
value->AsCallNew() == NULL) {
fni_->Infer();
} else {
fni_->RemoveLastFunction();
}
if (decl_props != NULL) *decl_props = kHasInitializers;
}
// Record the end position of the initializer.
if (proxy->var() != NULL) {
proxy->var()->set_initializer_position(scanner().location().end_pos);
}
// Make sure that 'const x' and 'let x' initialize 'x' to undefined.
if (value == NULL && needs_init) {
value = GetLiteralUndefined();
}
// Global variable declarations must be compiled in a specific
// way. When the script containing the global variable declaration
// is entered, the global variable must be declared, so that if it
// doesn't exist (not even in a prototype of the global object) it
// gets created with an initial undefined value. This is handled
// by the declarations part of the function representing the
// top-level global code; see Runtime::DeclareGlobalVariable. If
// it already exists (in the object or in a prototype), it is
// *not* touched until the variable declaration statement is
// executed.
//
// Executing the variable declaration statement will always
// guarantee to give the global object a "local" variable; a
// variable defined in the global object and not in any
// prototype. This way, global variable declarations can shadow
// properties in the prototype chain, but only after the variable
// declaration statement has been executed. This is important in
// browsers where the global object (window) has lots of
// properties defined in prototype objects.
if (initialization_scope->is_global_scope()) {
// Compute the arguments for the runtime call.
ZoneList<Expression*>* arguments = new(zone()) ZoneList<Expression*>(3);
// We have at least 1 parameter.
arguments->Add(NewLiteral(name));
CallRuntime* initialize;
if (is_const) {
arguments->Add(value);
value = NULL; // zap the value to avoid the unnecessary assignment
// Construct the call to Runtime_InitializeConstGlobal
// and add it to the initialization statement block.
// Note that the function does different things depending on
// the number of arguments (1 or 2).
initialize =
new(zone()) CallRuntime(
isolate(),
isolate()->factory()->InitializeConstGlobal_symbol(),
Runtime::FunctionForId(Runtime::kInitializeConstGlobal),
arguments);
} else {
// Add strict mode.
// We may want to pass singleton to avoid Literal allocations.
LanguageMode language_mode = initialization_scope->language_mode();
arguments->Add(NewNumberLiteral(language_mode));
// Be careful not to assign a value to the global variable if
// we're in a with. The initialization value should not
// necessarily be stored in the global object in that case,
// which is why we need to generate a separate assignment node.
if (value != NULL && !inside_with()) {
arguments->Add(value);
value = NULL; // zap the value to avoid the unnecessary assignment
}
// Construct the call to Runtime_InitializeVarGlobal
// and add it to the initialization statement block.
// Note that the function does different things depending on
// the number of arguments (2 or 3).
initialize =
new(zone()) CallRuntime(
isolate(),
isolate()->factory()->InitializeVarGlobal_symbol(),
Runtime::FunctionForId(Runtime::kInitializeVarGlobal),
arguments);
}
block->AddStatement(new(zone()) ExpressionStatement(initialize));
} else if (needs_init) {
// Constant initializations always assign to the declared constant which
// is always at the function scope level. This is only relevant for
// dynamically looked-up variables and constants (the start context for
// constant lookups is always the function context, while it is the top
// context for var declared variables). Sigh...
// For 'let' and 'const' declared variables in harmony mode the
// initialization also always assigns to the declared variable.
ASSERT(proxy != NULL);
ASSERT(proxy->var() != NULL);
ASSERT(value != NULL);
Assignment* assignment =
new(zone()) Assignment(isolate(), init_op, proxy, value, position);
block->AddStatement(new(zone()) ExpressionStatement(assignment));
value = NULL;
}
// Add an assignment node to the initialization statement block if we still
// have a pending initialization value.
if (value != NULL) {
ASSERT(mode == VAR);
// 'var' initializations are simply assignments (with all the consequences
// if they are inside a 'with' statement - they may change a 'with' object
// property).
VariableProxy* proxy = initialization_scope->NewUnresolved(name);
Assignment* assignment =
new(zone()) Assignment(isolate(), init_op, proxy, value, position);
block->AddStatement(new(zone()) ExpressionStatement(assignment));
}
if (fni_ != NULL) fni_->Leave();
} while (peek() == Token::COMMA);
// If there was a single non-const declaration, return it in the output
// parameter for possible use by for/in.
if (nvars == 1 && !is_const) {
*out = name;
}
return block;
}
static bool ContainsLabel(ZoneStringList* labels, Handle<String> label) {
ASSERT(!label.is_null());
if (labels != NULL)
for (int i = labels->length(); i-- > 0; )
if (labels->at(i).is_identical_to(label))
return true;
return false;
}
Statement* Parser::ParseExpressionOrLabelledStatement(ZoneStringList* labels,
bool* ok) {
// ExpressionStatement | LabelledStatement ::
// Expression ';'
// Identifier ':' Statement
bool starts_with_idenfifier = peek_any_identifier();
Expression* expr = ParseExpression(true, CHECK_OK);
if (peek() == Token::COLON && starts_with_idenfifier && expr != NULL &&
expr->AsVariableProxy() != NULL &&
!expr->AsVariableProxy()->is_this()) {
// Expression is a single identifier, and not, e.g., a parenthesized
// identifier.
VariableProxy* var = expr->AsVariableProxy();
Handle<String> label = var->name();
// TODO(1240780): We don't check for redeclaration of labels
// during preparsing since keeping track of the set of active
// labels requires nontrivial changes to the way scopes are
// structured. However, these are probably changes we want to
// make later anyway so we should go back and fix this then.
if (ContainsLabel(labels, label) || TargetStackContainsLabel(label)) {
SmartArrayPointer<char> c_string = label->ToCString(DISALLOW_NULLS);
const char* elms[2] = { "Label", *c_string };
Vector<const char*> args(elms, 2);
ReportMessage("redeclaration", args);
*ok = false;
return NULL;
}
if (labels == NULL) labels = new(zone()) ZoneStringList(4);
labels->Add(label);
// Remove the "ghost" variable that turned out to be a label
// from the top scope. This way, we don't try to resolve it
// during the scope processing.
top_scope_->RemoveUnresolved(var);
Expect(Token::COLON, CHECK_OK);
return ParseStatement(labels, ok);
}
// If we have an extension, we allow a native function declaration.
// A native function declaration starts with "native function" with
// no line-terminator between the two words.
if (extension_ != NULL &&
peek() == Token::FUNCTION &&
!scanner().HasAnyLineTerminatorBeforeNext() &&
expr != NULL &&
expr->AsVariableProxy() != NULL &&
expr->AsVariableProxy()->name()->Equals(
isolate()->heap()->native_symbol()) &&
!scanner().literal_contains_escapes()) {
return ParseNativeDeclaration(ok);
}
// Parsed expression statement.
ExpectSemicolon(CHECK_OK);
return new(zone()) ExpressionStatement(expr);
}
IfStatement* Parser::ParseIfStatement(ZoneStringList* labels, bool* ok) {
// IfStatement ::
// 'if' '(' Expression ')' Statement ('else' Statement)?
Expect(Token::IF, CHECK_OK);
Expect(Token::LPAREN, CHECK_OK);
Expression* condition = ParseExpression(true, CHECK_OK);
Expect(Token::RPAREN, CHECK_OK);
Statement* then_statement = ParseStatement(labels, CHECK_OK);
Statement* else_statement = NULL;
if (peek() == Token::ELSE) {
Next();
else_statement = ParseStatement(labels, CHECK_OK);
} else {
else_statement = EmptyStatement();
}
return new(zone()) IfStatement(
isolate(), condition, then_statement, else_statement);
}
Statement* Parser::ParseContinueStatement(bool* ok) {
// ContinueStatement ::
// 'continue' Identifier? ';'
Expect(Token::CONTINUE, CHECK_OK);
Handle<String> label = Handle<String>::null();
Token::Value tok = peek();
if (!scanner().HasAnyLineTerminatorBeforeNext() &&
tok != Token::SEMICOLON && tok != Token::RBRACE && tok != Token::EOS) {
label = ParseIdentifier(CHECK_OK);
}
IterationStatement* target = NULL;
target = LookupContinueTarget(label, CHECK_OK);
if (target == NULL) {
// Illegal continue statement.
const char* message = "illegal_continue";
Vector<Handle<String> > args;
if (!label.is_null()) {
message = "unknown_label";
args = Vector<Handle<String> >(&label, 1);
}
ReportMessageAt(scanner().location(), message, args);
*ok = false;
return NULL;
}
ExpectSemicolon(CHECK_OK);
return new(zone()) ContinueStatement(target);
}
Statement* Parser::ParseBreakStatement(ZoneStringList* labels, bool* ok) {
// BreakStatement ::
// 'break' Identifier? ';'
Expect(Token::BREAK, CHECK_OK);
Handle<String> label;
Token::Value tok = peek();
if (!scanner().HasAnyLineTerminatorBeforeNext() &&
tok != Token::SEMICOLON && tok != Token::RBRACE && tok != Token::EOS) {
label = ParseIdentifier(CHECK_OK);
}
// Parse labeled break statements that target themselves into
// empty statements, e.g. 'l1: l2: l3: break l2;'
if (!label.is_null() && ContainsLabel(labels, label)) {
return EmptyStatement();
}
BreakableStatement* target = NULL;
target = LookupBreakTarget(label, CHECK_OK);
if (target == NULL) {
// Illegal break statement.
const char* message = "illegal_break";
Vector<Handle<String> > args;
if (!label.is_null()) {
message = "unknown_label";
args = Vector<Handle<String> >(&label, 1);
}
ReportMessageAt(scanner().location(), message, args);
*ok = false;
return NULL;
}
ExpectSemicolon(CHECK_OK);
return new(zone()) BreakStatement(target);
}
Statement* Parser::ParseReturnStatement(bool* ok) {
// ReturnStatement ::
// 'return' Expression? ';'
// Consume the return token. It is necessary to do the before
// reporting any errors on it, because of the way errors are
// reported (underlining).
Expect(Token::RETURN, CHECK_OK);
// An ECMAScript program is considered syntactically incorrect if it
// contains a return statement that is not within the body of a
// function. See ECMA-262, section 12.9, page 67.
//
// To be consistent with KJS we report the syntax error at runtime.
Scope* declaration_scope = top_scope_->DeclarationScope();
if (declaration_scope->is_global_scope() ||
declaration_scope->is_eval_scope()) {
Handle<String> type = isolate()->factory()->illegal_return_symbol();
Expression* throw_error = NewThrowSyntaxError(type, Handle<Object>::null());
return new(zone()) ExpressionStatement(throw_error);
}
Token::Value tok = peek();
if (scanner().HasAnyLineTerminatorBeforeNext() ||
tok == Token::SEMICOLON ||
tok == Token::RBRACE ||
tok == Token::EOS) {
ExpectSemicolon(CHECK_OK);
return new(zone()) ReturnStatement(GetLiteralUndefined());
}
Expression* expr = ParseExpression(true, CHECK_OK);
ExpectSemicolon(CHECK_OK);
return new(zone()) ReturnStatement(expr);
}
Statement* Parser::ParseWithStatement(ZoneStringList* labels, bool* ok) {
// WithStatement ::
// 'with' '(' Expression ')' Statement
Expect(Token::WITH, CHECK_OK);
if (!top_scope_->is_classic_mode()) {
ReportMessage("strict_mode_with", Vector<const char*>::empty());
*ok = false;
return NULL;
}
Expect(Token::LPAREN, CHECK_OK);
Expression* expr = ParseExpression(true, CHECK_OK);
Expect(Token::RPAREN, CHECK_OK);
top_scope_->DeclarationScope()->RecordWithStatement();
Scope* with_scope = NewScope(top_scope_, WITH_SCOPE);
Statement* stmt;
{ BlockState block_state(this, with_scope);
with_scope->set_start_position(scanner().peek_location().beg_pos);
stmt = ParseStatement(labels, CHECK_OK);
with_scope->set_end_position(scanner().location().end_pos);
}
return new(zone()) WithStatement(expr, stmt);
}
CaseClause* Parser::ParseCaseClause(bool* default_seen_ptr, bool* ok) {
// CaseClause ::
// 'case' Expression ':' Statement*
// 'default' ':' Statement*
Expression* label = NULL; // NULL expression indicates default case
if (peek() == Token::CASE) {
Expect(Token::CASE, CHECK_OK);
label = ParseExpression(true, CHECK_OK);
} else {
Expect(Token::DEFAULT, CHECK_OK);
if (*default_seen_ptr) {
ReportMessage("multiple_defaults_in_switch",
Vector<const char*>::empty());
*ok = false;
return NULL;
}
*default_seen_ptr = true;
}
Expect(Token::COLON, CHECK_OK);
int pos = scanner().location().beg_pos;
ZoneList<Statement*>* statements = new(zone()) ZoneList<Statement*>(5);
while (peek() != Token::CASE &&
peek() != Token::DEFAULT &&
peek() != Token::RBRACE) {
Statement* stat = ParseStatement(NULL, CHECK_OK);
statements->Add(stat);
}
return new(zone()) CaseClause(isolate(), label, statements, pos);
}
SwitchStatement* Parser::ParseSwitchStatement(ZoneStringList* labels,
bool* ok) {
// SwitchStatement ::
// 'switch' '(' Expression ')' '{' CaseClause* '}'
SwitchStatement* statement = new(zone()) SwitchStatement(isolate(), labels);
Target target(&this->target_stack_, statement);
Expect(Token::SWITCH, CHECK_OK);
Expect(Token::LPAREN, CHECK_OK);
Expression* tag = ParseExpression(true, CHECK_OK);
Expect(Token::RPAREN, CHECK_OK);
bool default_seen = false;
ZoneList<CaseClause*>* cases = new(zone()) ZoneList<CaseClause*>(4);
Expect(Token::LBRACE, CHECK_OK);
while (peek() != Token::RBRACE) {
CaseClause* clause = ParseCaseClause(&default_seen, CHECK_OK);
cases->Add(clause);
}
Expect(Token::RBRACE, CHECK_OK);
if (statement) statement->Initialize(tag, cases);
return statement;
}
Statement* Parser::ParseThrowStatement(bool* ok) {
// ThrowStatement ::
// 'throw' Expression ';'
Expect(Token::THROW, CHECK_OK);
int pos = scanner().location().beg_pos;
if (scanner().HasAnyLineTerminatorBeforeNext()) {
ReportMessage("newline_after_throw", Vector<const char*>::empty());
*ok = false;
return NULL;
}
Expression* exception = ParseExpression(true, CHECK_OK);
ExpectSemicolon(CHECK_OK);
return new(zone()) ExpressionStatement(
new(zone()) Throw(isolate(), exception, pos));
}
TryStatement* Parser::ParseTryStatement(bool* ok) {
// TryStatement ::
// 'try' Block Catch
// 'try' Block Finally
// 'try' Block Catch Finally
//
// Catch ::
// 'catch' '(' Identifier ')' Block
//
// Finally ::
// 'finally' Block
Expect(Token::TRY, CHECK_OK);
TargetCollector try_collector;
Block* try_block;
{ Target target(&this->target_stack_, &try_collector);
try_block = ParseBlock(NULL, CHECK_OK);
}
Token::Value tok = peek();
if (tok != Token::CATCH && tok != Token::FINALLY) {
ReportMessage("no_catch_or_finally", Vector<const char*>::empty());
*ok = false;
return NULL;
}
// If we can break out from the catch block and there is a finally block,
// then we will need to collect escaping targets from the catch
// block. Since we don't know yet if there will be a finally block, we
// always collect the targets.
TargetCollector catch_collector;
Scope* catch_scope = NULL;
Variable* catch_variable = NULL;
Block* catch_block = NULL;
Handle<String> name;
if (tok == Token::CATCH) {
Consume(Token::CATCH);
Expect(Token::LPAREN, CHECK_OK);
catch_scope = NewScope(top_scope_, CATCH_SCOPE);
catch_scope->set_start_position(scanner().location().beg_pos);
name = ParseIdentifier(CHECK_OK);
if (!top_scope_->is_classic_mode() && IsEvalOrArguments(name)) {
ReportMessage("strict_catch_variable", Vector<const char*>::empty());
*ok = false;
return NULL;
}
Expect(Token::RPAREN, CHECK_OK);
if (peek() == Token::LBRACE) {
Target target(&this->target_stack_, &catch_collector);
VariableMode mode = is_extended_mode() ? LET : VAR;
catch_variable =
catch_scope->DeclareLocal(name, mode, kCreatedInitialized);
BlockState block_state(this, catch_scope);
catch_block = ParseBlock(NULL, CHECK_OK);
} else {
Expect(Token::LBRACE, CHECK_OK);
}
catch_scope->set_end_position(scanner().location().end_pos);
tok = peek();
}
Block* finally_block = NULL;
if (tok == Token::FINALLY || catch_block == NULL) {
Consume(Token::FINALLY);
finally_block = ParseBlock(NULL, CHECK_OK);
}
// Simplify the AST nodes by converting:
// 'try B0 catch B1 finally B2'
// to:
// 'try { try B0 catch B1 } finally B2'
if (catch_block != NULL && finally_block != NULL) {
// If we have both, create an inner try/catch.
ASSERT(catch_scope != NULL && catch_variable != NULL);
int index = current_function_state_->NextHandlerIndex();
TryCatchStatement* statement = new(zone()) TryCatchStatement(index,
try_block,
catch_scope,
catch_variable,
catch_block);
statement->set_escaping_targets(try_collector.targets());
try_block = new(zone()) Block(isolate(), NULL, 1, false);
try_block->AddStatement(statement);
catch_block = NULL; // Clear to indicate it's been handled.
}
TryStatement* result = NULL;
if (catch_block != NULL) {
ASSERT(finally_block == NULL);
ASSERT(catch_scope != NULL && catch_variable != NULL);
int index = current_function_state_->NextHandlerIndex();
result = new(zone()) TryCatchStatement(index,
try_block,
catch_scope,
catch_variable,
catch_block);
} else {
ASSERT(finally_block != NULL);
int index = current_function_state_->NextHandlerIndex();
result = new(zone()) TryFinallyStatement(index,
try_block,
finally_block);
// Combine the jump targets of the try block and the possible catch block.
try_collector.targets()->AddAll(*catch_collector.targets());
}
result->set_escaping_targets(try_collector.targets());
return result;
}
DoWhileStatement* Parser::ParseDoWhileStatement(ZoneStringList* labels,
bool* ok) {
// DoStatement ::
// 'do' Statement 'while' '(' Expression ')' ';'
DoWhileStatement* loop = new(zone()) DoWhileStatement(isolate(), labels);
Target target(&this->target_stack_, loop);
Expect(Token::DO, CHECK_OK);
Statement* body = ParseStatement(NULL, CHECK_OK);
Expect(Token::WHILE, CHECK_OK);
Expect(Token::LPAREN, CHECK_OK);
if (loop != NULL) {
int position = scanner().location().beg_pos;
loop->set_condition_position(position);
}
Expression* cond = ParseExpression(true, CHECK_OK);
Expect(Token::RPAREN, CHECK_OK);
// Allow do-statements to be terminated with and without
// semi-colons. This allows code such as 'do;while(0)return' to
// parse, which would not be the case if we had used the
// ExpectSemicolon() functionality here.
if (peek() == Token::SEMICOLON) Consume(Token::SEMICOLON);
if (loop != NULL) loop->Initialize(cond, body);
return loop;
}
WhileStatement* Parser::ParseWhileStatement(ZoneStringList* labels, bool* ok) {
// WhileStatement ::
// 'while' '(' Expression ')' Statement
WhileStatement* loop = new(zone()) WhileStatement(isolate(), labels);
Target target(&this->target_stack_, loop);
Expect(Token::WHILE, CHECK_OK);
Expect(Token::LPAREN, CHECK_OK);
Expression* cond = ParseExpression(true, CHECK_OK);
Expect(Token::RPAREN, CHECK_OK);
Statement* body = ParseStatement(NULL, CHECK_OK);
if (loop != NULL) loop->Initialize(cond, body);
return loop;
}
Statement* Parser::ParseForStatement(ZoneStringList* labels, bool* ok) {
// ForStatement ::
// 'for' '(' Expression? ';' Expression? ';' Expression? ')' Statement
Statement* init = NULL;
// Create an in-between scope for let-bound iteration variables.
Scope* saved_scope = top_scope_;
Scope* for_scope = NewScope(top_scope_, BLOCK_SCOPE);
top_scope_ = for_scope;
Expect(Token::FOR, CHECK_OK);
Expect(Token::LPAREN, CHECK_OK);
for_scope->set_start_position(scanner().location().beg_pos);
if (peek() != Token::SEMICOLON) {
if (peek() == Token::VAR || peek() == Token::CONST) {
Handle<String> name;
Block* variable_statement =
ParseVariableDeclarations(kForStatement, NULL, &name, CHECK_OK);
if (peek() == Token::IN && !name.is_null()) {
VariableProxy* each = top_scope_->NewUnresolved(name);
ForInStatement* loop = new(zone()) ForInStatement(isolate(), labels);
Target target(&this->target_stack_, loop);
Expect(Token::IN, CHECK_OK);
Expression* enumerable = ParseExpression(true, CHECK_OK);
Expect(Token::RPAREN, CHECK_OK);
Statement* body = ParseStatement(NULL, CHECK_OK);
loop->Initialize(each, enumerable, body);
Block* result = new(zone()) Block(isolate(), NULL, 2, false);
result->AddStatement(variable_statement);
result->AddStatement(loop);
top_scope_ = saved_scope;
for_scope->set_end_position(scanner().location().end_pos);
for_scope = for_scope->FinalizeBlockScope();
ASSERT(for_scope == NULL);
// Parsed for-in loop w/ variable/const declaration.
return result;
} else {
init = variable_statement;
}
} else if (peek() == Token::LET) {
Handle<String> name;
VariableDeclarationProperties decl_props = kHasNoInitializers;
Block* variable_statement =
ParseVariableDeclarations(kForStatement,
&decl_props,
&name,
CHECK_OK);
bool accept_IN = !name.is_null() && decl_props != kHasInitializers;
if (peek() == Token::IN && accept_IN) {
// Rewrite a for-in statement of the form
//
// for (let x in e) b
//
// into
//
// <let x' be a temporary variable>
// for (x' in e) {
// let x;
// x = x';
// b;
// }
// TODO(keuchel): Move the temporary variable to the block scope, after
// implementing stack allocated block scoped variables.
Variable* temp = top_scope_->DeclarationScope()->NewTemporary(name);
VariableProxy* temp_proxy = new(zone()) VariableProxy(isolate(), temp);
VariableProxy* each = top_scope_->NewUnresolved(name);
ForInStatement* loop = new(zone()) ForInStatement(isolate(), labels);
Target target(&this->target_stack_, loop);
Expect(Token::IN, CHECK_OK);
Expression* enumerable = ParseExpression(true, CHECK_OK);
Expect(Token::RPAREN, CHECK_OK);
Statement* body = ParseStatement(NULL, CHECK_OK);
Block* body_block = new(zone()) Block(isolate(), NULL, 3, false);
Assignment* assignment = new(zone()) Assignment(isolate(),
Token::ASSIGN,
each,
temp_proxy,
RelocInfo::kNoPosition);
Statement* assignment_statement =
new(zone()) ExpressionStatement(assignment);
body_block->AddStatement(variable_statement);
body_block->AddStatement(assignment_statement);
body_block->AddStatement(body);
loop->Initialize(temp_proxy, enumerable, body_block);
top_scope_ = saved_scope;
for_scope->set_end_position(scanner().location().end_pos);
for_scope = for_scope->FinalizeBlockScope();
body_block->set_block_scope(for_scope);
// Parsed for-in loop w/ let declaration.
return loop;
} else {
init = variable_statement;
}
} else {
Expression* expression = ParseExpression(false, CHECK_OK);
if (peek() == Token::IN) {
// Signal a reference error if the expression is an invalid
// left-hand side expression. We could report this as a syntax
// error here but for compatibility with JSC we choose to report
// the error at runtime.
if (expression == NULL || !expression->IsValidLeftHandSide()) {
Handle<String> type =
isolate()->factory()->invalid_lhs_in_for_in_symbol();
expression = NewThrowReferenceError(type);
}
ForInStatement* loop = new(zone()) ForInStatement(isolate(), labels);
Target target(&this->target_stack_, loop);
Expect(Token::IN, CHECK_OK);
Expression* enumerable = ParseExpression(true, CHECK_OK);
Expect(Token::RPAREN, CHECK_OK);
Statement* body = ParseStatement(NULL, CHECK_OK);
if (loop) loop->Initialize(expression, enumerable, body);
top_scope_ = saved_scope;
for_scope->set_end_position(scanner().location().end_pos);
for_scope = for_scope->FinalizeBlockScope();
ASSERT(for_scope == NULL);
// Parsed for-in loop.
return loop;
} else {
init = new(zone()) ExpressionStatement(expression);
}
}
}
// Standard 'for' loop
ForStatement* loop = new(zone()) ForStatement(isolate(), labels);
Target target(&this->target_stack_, loop);
// Parsed initializer at this point.
Expect(Token::SEMICOLON, CHECK_OK);
Expression* cond = NULL;
if (peek() != Token::SEMICOLON) {
cond = ParseExpression(true, CHECK_OK);
}
Expect(Token::SEMICOLON, CHECK_OK);
Statement* next = NULL;
if (peek() != Token::RPAREN) {
Expression* exp = ParseExpression(true, CHECK_OK);
next = new(zone()) ExpressionStatement(exp);
}
Expect(Token::RPAREN, CHECK_OK);
Statement* body = ParseStatement(NULL, CHECK_OK);
top_scope_ = saved_scope;
for_scope->set_end_position(scanner().location().end_pos);
for_scope = for_scope->FinalizeBlockScope();
if (for_scope != NULL) {
// Rewrite a for statement of the form
//
// for (let x = i; c; n) b
//
// into
//
// {
// let x = i;
// for (; c; n) b
// }
ASSERT(init != NULL);
Block* result = new(zone()) Block(isolate(), NULL, 2, false);
result->AddStatement(init);
result->AddStatement(loop);
result->set_block_scope(for_scope);
if (loop) loop->Initialize(NULL, cond, next, body);
return result;
} else {
if (loop) loop->Initialize(init, cond, next, body);
return loop;
}
}
// Precedence = 1
Expression* Parser::ParseExpression(bool accept_IN, bool* ok) {
// Expression ::
// AssignmentExpression
// Expression ',' AssignmentExpression
Expression* result = ParseAssignmentExpression(accept_IN, CHECK_OK);
while (peek() == Token::COMMA) {
Expect(Token::COMMA, CHECK_OK);
int position = scanner().location().beg_pos;
Expression* right = ParseAssignmentExpression(accept_IN, CHECK_OK);
result = new(zone()) BinaryOperation(
isolate(), Token::COMMA, result, right, position);
}
return result;
}
// Precedence = 2
Expression* Parser::ParseAssignmentExpression(bool accept_IN, bool* ok) {
// AssignmentExpression ::
// ConditionalExpression
// LeftHandSideExpression AssignmentOperator AssignmentExpression
if (fni_ != NULL) fni_->Enter();
Expression* expression = ParseConditionalExpression(accept_IN, CHECK_OK);
if (!Token::IsAssignmentOp(peek())) {
if (fni_ != NULL) fni_->Leave();
// Parsed conditional expression only (no assignment).
return expression;
}
// Signal a reference error if the expression is an invalid left-hand
// side expression. We could report this as a syntax error here but
// for compatibility with JSC we choose to report the error at
// runtime.
if (expression == NULL || !expression->IsValidLeftHandSide()) {
Handle<String> type =
isolate()->factory()->invalid_lhs_in_assignment_symbol();
expression = NewThrowReferenceError(type);
}
if (!top_scope_->is_classic_mode()) {
// Assignment to eval or arguments is disallowed in strict mode.
CheckStrictModeLValue(expression, "strict_lhs_assignment", CHECK_OK);
}
Token::Value op = Next(); // Get assignment operator.
int pos = scanner().location().beg_pos;
Expression* right = ParseAssignmentExpression(accept_IN, CHECK_OK);
// TODO(1231235): We try to estimate the set of properties set by
// constructors. We define a new property whenever there is an
// assignment to a property of 'this'. We should probably only add
// properties if we haven't seen them before. Otherwise we'll
// probably overestimate the number of properties.
Property* property = expression ? expression->AsProperty() : NULL;
if (op == Token::ASSIGN &&
property != NULL &&
property->obj()->AsVariableProxy() != NULL &&
property->obj()->AsVariableProxy()->is_this()) {
current_function_state_->AddProperty();
}
// If we assign a function literal to a property we pretenure the
// literal so it can be added as a constant function property.
if (property != NULL && right->AsFunctionLiteral() != NULL) {
right->AsFunctionLiteral()->set_pretenure();
}
if (fni_ != NULL) {
// Check if the right hand side is a call to avoid inferring a
// name if we're dealing with "a = function(){...}();"-like
// expression.
if ((op == Token::INIT_VAR
|| op == Token::INIT_CONST
|| op == Token::ASSIGN)
&& (right->AsCall() == NULL && right->AsCallNew() == NULL)) {
fni_->Infer();
} else {
fni_->RemoveLastFunction();
}
fni_->Leave();
}
return new(zone()) Assignment(isolate(), op, expression, right, pos);
}
// Precedence = 3
Expression* Parser::ParseConditionalExpression(bool accept_IN, bool* ok) {
// ConditionalExpression ::
// LogicalOrExpression
// LogicalOrExpression '?' AssignmentExpression ':' AssignmentExpression
// We start using the binary expression parser for prec >= 4 only!
Expression* expression = ParseBinaryExpression(4, accept_IN, CHECK_OK);
if (peek() != Token::CONDITIONAL) return expression;
Consume(Token::CONDITIONAL);
// In parsing the first assignment expression in conditional
// expressions we always accept the 'in' keyword; see ECMA-262,
// section 11.12, page 58.
int left_position = scanner().peek_location().beg_pos;
Expression* left = ParseAssignmentExpression(true, CHECK_OK);
Expect(Token::COLON, CHECK_OK);
int right_position = scanner().peek_location().beg_pos;
Expression* right = ParseAssignmentExpression(accept_IN, CHECK_OK);
return new(zone()) Conditional(
isolate(), expression, left, right, left_position, right_position);
}
static int Precedence(Token::Value tok, bool accept_IN) {
if (tok == Token::IN && !accept_IN)
return 0; // 0 precedence will terminate binary expression parsing
return Token::Precedence(tok);
}
// Precedence >= 4
Expression* Parser::ParseBinaryExpression(int prec, bool accept_IN, bool* ok) {
ASSERT(prec >= 4);
Expression* x = ParseUnaryExpression(CHECK_OK);
for (int prec1 = Precedence(peek(), accept_IN); prec1 >= prec; prec1--) {
// prec1 >= 4
while (Precedence(peek(), accept_IN) == prec1) {
Token::Value op = Next();
int position = scanner().location().beg_pos;
Expression* y = ParseBinaryExpression(prec1 + 1, accept_IN, CHECK_OK);
// Compute some expressions involving only number literals.
if (x && x->AsLiteral() && x->AsLiteral()->handle()->IsNumber() &&
y && y->AsLiteral() && y->AsLiteral()->handle()->IsNumber()) {
double x_val = x->AsLiteral()->handle()->Number();
double y_val = y->AsLiteral()->handle()->Number();
switch (op) {
case Token::ADD:
x = NewNumberLiteral(x_val + y_val);
continue;
case Token::SUB:
x = NewNumberLiteral(x_val - y_val);
continue;
case Token::MUL:
x = NewNumberLiteral(x_val * y_val);
continue;
case Token::DIV:
x = NewNumberLiteral(x_val / y_val);
continue;
case Token::BIT_OR:
x = NewNumberLiteral(DoubleToInt32(x_val) | DoubleToInt32(y_val));
continue;
case Token::BIT_AND:
x = NewNumberLiteral(DoubleToInt32(x_val) & DoubleToInt32(y_val));
continue;
case Token::BIT_XOR:
x = NewNumberLiteral(DoubleToInt32(x_val) ^ DoubleToInt32(y_val));
continue;
case Token::SHL: {
int value = DoubleToInt32(x_val) << (DoubleToInt32(y_val) & 0x1f);
x = NewNumberLiteral(value);
continue;
}
case Token::SHR: {
uint32_t shift = DoubleToInt32(y_val) & 0x1f;
uint32_t value = DoubleToUint32(x_val) >> shift;
x = NewNumberLiteral(value);
continue;
}
case Token::SAR: {
uint32_t shift = DoubleToInt32(y_val) & 0x1f;
int value = ArithmeticShiftRight(DoubleToInt32(x_val), shift);
x = NewNumberLiteral(value);
continue;
}
default:
break;
}
}
// For now we distinguish between comparisons and other binary
// operations. (We could combine the two and get rid of this
// code and AST node eventually.)
if (Token::IsCompareOp(op)) {
// We have a comparison.
Token::Value cmp = op;
switch (op) {
case Token::NE: cmp = Token::EQ; break;
case Token::NE_STRICT: cmp = Token::EQ_STRICT; break;
default: break;
}
x = new(zone()) CompareOperation(isolate(), cmp, x, y, position);
if (cmp != op) {
// The comparison was negated - add a NOT.
x = new(zone()) UnaryOperation(isolate(), Token::NOT, x, position);
}
} else {
// We have a "normal" binary operation.
x = new(zone()) BinaryOperation(isolate(), op, x, y, position);
}
}
}
return x;
}
Expression* Parser::ParseUnaryExpression(bool* ok) {
// UnaryExpression ::
// PostfixExpression
// 'delete' UnaryExpression
// 'void' UnaryExpression
// 'typeof' UnaryExpression
// '++' UnaryExpression
// '--' UnaryExpression
// '+' UnaryExpression
// '-' UnaryExpression
// '~' UnaryExpression
// '!' UnaryExpression
Token::Value op = peek();
if (Token::IsUnaryOp(op)) {
op = Next();
int position = scanner().location().beg_pos;
Expression* expression = ParseUnaryExpression(CHECK_OK);
if (expression != NULL && (expression->AsLiteral() != NULL)) {
Handle<Object> literal = expression->AsLiteral()->handle();
if (op == Token::NOT) {
// Convert the literal to a boolean condition and negate it.
bool condition = literal->ToBoolean()->IsTrue();
Handle<Object> result(isolate()->heap()->ToBoolean(!condition));
return NewLiteral(result);
} else if (literal->IsNumber()) {
// Compute some expressions involving only number literals.
double value = literal->Number();
switch (op) {
case Token::ADD:
return expression;
case Token::SUB:
return NewNumberLiteral(-value);
case Token::BIT_NOT:
return NewNumberLiteral(~DoubleToInt32(value));
default:
break;
}
}
}
// "delete identifier" is a syntax error in strict mode.
if (op == Token::DELETE && !top_scope_->is_classic_mode()) {
VariableProxy* operand = expression->AsVariableProxy();
if (operand != NULL && !operand->is_this()) {
ReportMessage("strict_delete", Vector<const char*>::empty());
*ok = false;
return NULL;
}
}
return new(zone()) UnaryOperation(isolate(), op, expression, position);
} else if (Token::IsCountOp(op)) {
op = Next();
Expression* expression = ParseUnaryExpression(CHECK_OK);
// Signal a reference error if the expression is an invalid
// left-hand side expression. We could report this as a syntax
// error here but for compatibility with JSC we choose to report the
// error at runtime.
if (expression == NULL || !expression->IsValidLeftHandSide()) {
Handle<String> type =
isolate()->factory()->invalid_lhs_in_prefix_op_symbol();
expression = NewThrowReferenceError(type);
}
if (!top_scope_->is_classic_mode()) {
// Prefix expression operand in strict mode may not be eval or arguments.
CheckStrictModeLValue(expression, "strict_lhs_prefix", CHECK_OK);
}
int position = scanner().location().beg_pos;
return new(zone()) CountOperation(isolate(),
op,
true /* prefix */,
expression,
position);
} else {
return ParsePostfixExpression(ok);
}
}
Expression* Parser::ParsePostfixExpression(bool* ok) {
// PostfixExpression ::
// LeftHandSideExpression ('++' | '--')?
Expression* expression = ParseLeftHandSideExpression(CHECK_OK);
if (!scanner().HasAnyLineTerminatorBeforeNext() &&
Token::IsCountOp(peek())) {
// Signal a reference error if the expression is an invalid
// left-hand side expression. We could report this as a syntax
// error here but for compatibility with JSC we choose to report the
// error at runtime.
if (expression == NULL || !expression->IsValidLeftHandSide()) {
Handle<String> type =
isolate()->factory()->invalid_lhs_in_postfix_op_symbol();
expression = NewThrowReferenceError(type);
}
if (!top_scope_->is_classic_mode()) {
// Postfix expression operand in strict mode may not be eval or arguments.
CheckStrictModeLValue(expression, "strict_lhs_prefix", CHECK_OK);
}
Token::Value next = Next();
int position = scanner().location().beg_pos;
expression =
new(zone()) CountOperation(isolate(),
next,
false /* postfix */,
expression,
position);
}
return expression;
}
Expression* Parser::ParseLeftHandSideExpression(bool* ok) {
// LeftHandSideExpression ::
// (NewExpression | MemberExpression) ...
Expression* result;
if (peek() == Token::NEW) {
result = ParseNewExpression(CHECK_OK);
} else {
result = ParseMemberExpression(CHECK_OK);
}
while (true) {
switch (peek()) {
case Token::LBRACK: {
Consume(Token::LBRACK);
int pos = scanner().location().beg_pos;
Expression* index = ParseExpression(true, CHECK_OK);
result = new(zone()) Property(isolate(), result, index, pos);
Expect(Token::RBRACK, CHECK_OK);
break;
}
case Token::LPAREN: {
int pos = scanner().location().beg_pos;
ZoneList<Expression*>* args = ParseArguments(CHECK_OK);
// Keep track of eval() calls since they disable all local variable
// optimizations.
// The calls that need special treatment are the
// direct eval calls. These calls are all of the form eval(...), with
// no explicit receiver.
// These calls are marked as potentially direct eval calls. Whether
// they are actually direct calls to eval is determined at run time.
VariableProxy* callee = result->AsVariableProxy();
if (callee != NULL &&
callee->IsVariable(isolate()->factory()->eval_symbol())) {
top_scope_->DeclarationScope()->RecordEvalCall();
}
result = NewCall(result, args, pos);
break;
}
case Token::PERIOD: {
Consume(Token::PERIOD);
int pos = scanner().location().beg_pos;
Handle<String> name = ParseIdentifierName(CHECK_OK);
result = new(zone()) Property(isolate(),
result,
NewLiteral(name),
pos);
if (fni_ != NULL) fni_->PushLiteralName(name);
break;
}
default:
return result;
}
}
}
Expression* Parser::ParseNewPrefix(PositionStack* stack, bool* ok) {
// NewExpression ::
// ('new')+ MemberExpression
// The grammar for new expressions is pretty warped. The keyword
// 'new' can either be a part of the new expression (where it isn't
// followed by an argument list) or a part of the member expression,
// where it must be followed by an argument list. To accommodate
// this, we parse the 'new' keywords greedily and keep track of how
// many we have parsed. This information is then passed on to the
// member expression parser, which is only allowed to match argument
// lists as long as it has 'new' prefixes left
Expect(Token::NEW, CHECK_OK);
PositionStack::Element pos(stack, scanner().location().beg_pos);
Expression* result;
if (peek() == Token::NEW) {
result = ParseNewPrefix(stack, CHECK_OK);
} else {
result = ParseMemberWithNewPrefixesExpression(stack, CHECK_OK);
}
if (!stack->is_empty()) {
int last = stack->pop();
result = new(zone()) CallNew(isolate(),
result,
new(zone()) ZoneList<Expression*>(0),
last);
}
return result;
}
Expression* Parser::ParseNewExpression(bool* ok) {
PositionStack stack(ok);
return ParseNewPrefix(&stack, ok);
}
Expression* Parser::ParseMemberExpression(bool* ok) {
return ParseMemberWithNewPrefixesExpression(NULL, ok);
}
Expression* Parser::ParseMemberWithNewPrefixesExpression(PositionStack* stack,
bool* ok) {
// MemberExpression ::
// (PrimaryExpression | FunctionLiteral)
// ('[' Expression ']' | '.' Identifier | Arguments)*
// Parse the initial primary or function expression.
Expression* result = NULL;
if (peek() == Token::FUNCTION) {
Expect(Token::FUNCTION, CHECK_OK);
int function_token_position = scanner().location().beg_pos;
Handle<String> name;
bool is_strict_reserved_name = false;
if (peek_any_identifier()) {
name = ParseIdentifierOrStrictReservedWord(&is_strict_reserved_name,
CHECK_OK);
}
FunctionLiteral::Type type = name.is_null()
? FunctionLiteral::ANONYMOUS_EXPRESSION
: FunctionLiteral::NAMED_EXPRESSION;
result = ParseFunctionLiteral(name,
is_strict_reserved_name,
function_token_position,
type,
CHECK_OK);
} else {
result = ParsePrimaryExpression(CHECK_OK);
}
while (true) {
switch (peek()) {
case Token::LBRACK: {
Consume(Token::LBRACK);
int pos = scanner().location().beg_pos;
Expression* index = ParseExpression(true, CHECK_OK);
result = new(zone()) Property(isolate(), result, index, pos);
if (fni_ != NULL) {
if (index->IsPropertyName()) {
fni_->PushLiteralName(index->AsLiteral()->AsPropertyName());
} else {
fni_->PushLiteralName(
isolate()->factory()->anonymous_function_symbol());
}
}
Expect(Token::RBRACK, CHECK_OK);
break;
}
case Token::PERIOD: {
Consume(Token::PERIOD);
int pos = scanner().location().beg_pos;
Handle<String> name = ParseIdentifierName(CHECK_OK);
result = new(zone()) Property(isolate(),
result,
NewLiteral(name),
pos);
if (fni_ != NULL) fni_->PushLiteralName(name);
break;
}
case Token::LPAREN: {
if ((stack == NULL) || stack->is_empty()) return result;
// Consume one of the new prefixes (already parsed).
ZoneList<Expression*>* args = ParseArguments(CHECK_OK);
int last = stack->pop();
result = new(zone()) CallNew(isolate(), result, args, last);
break;
}
default:
return result;
}
}
}
DebuggerStatement* Parser::ParseDebuggerStatement(bool* ok) {
// In ECMA-262 'debugger' is defined as a reserved keyword. In some browser
// contexts this is used as a statement which invokes the debugger as i a
// break point is present.
// DebuggerStatement ::
// 'debugger' ';'
Expect(Token::DEBUGGER, CHECK_OK);
ExpectSemicolon(CHECK_OK);
return new(zone()) DebuggerStatement();
}
void Parser::ReportUnexpectedToken(Token::Value token) {
// We don't report stack overflows here, to avoid increasing the
// stack depth even further. Instead we report it after parsing is
// over, in ParseProgram/ParseJson.
if (token == Token::ILLEGAL && stack_overflow_) return;
// Four of the tokens are treated specially
switch (token) {
case Token::EOS:
return ReportMessage("unexpected_eos", Vector<const char*>::empty());
case Token::NUMBER:
return ReportMessage("unexpected_token_number",
Vector<const char*>::empty());
case Token::STRING:
return ReportMessage("unexpected_token_string",
Vector<const char*>::empty());
case Token::IDENTIFIER:
return ReportMessage("unexpected_token_identifier",
Vector<const char*>::empty());
case Token::FUTURE_RESERVED_WORD:
return ReportMessage("unexpected_reserved",
Vector<const char*>::empty());
case Token::FUTURE_STRICT_RESERVED_WORD:
return ReportMessage(top_scope_->is_classic_mode() ?
"unexpected_token_identifier" :
"unexpected_strict_reserved",
Vector<const char*>::empty());
default:
const char* name = Token::String(token);
ASSERT(name != NULL);
ReportMessage("unexpected_token", Vector<const char*>(&name, 1));
}
}
void Parser::ReportInvalidPreparseData(Handle<String> name, bool* ok) {
SmartArrayPointer<char> name_string = name->ToCString(DISALLOW_NULLS);
const char* element[1] = { *name_string };
ReportMessage("invalid_preparser_data",
Vector<const char*>(element, 1));
*ok = false;
}
Expression* Parser::ParsePrimaryExpression(bool* ok) {
// PrimaryExpression ::
// 'this'
// 'null'
// 'true'
// 'false'
// Identifier
// Number
// String
// ArrayLiteral
// ObjectLiteral
// RegExpLiteral
// '(' Expression ')'
Expression* result = NULL;
switch (peek()) {
case Token::THIS: {
Consume(Token::THIS);
result = new(zone()) VariableProxy(isolate(), top_scope_->receiver());
break;
}
case Token::NULL_LITERAL:
Consume(Token::NULL_LITERAL);
result = new(zone()) Literal(
isolate(), isolate()->factory()->null_value());
break;
case Token::TRUE_LITERAL:
Consume(Token::TRUE_LITERAL);
result = new(zone()) Literal(
isolate(), isolate()->factory()->true_value());
break;
case Token::FALSE_LITERAL:
Consume(Token::FALSE_LITERAL);
result = new(zone()) Literal(
isolate(), isolate()->factory()->false_value());
break;
case Token::IDENTIFIER:
case Token::FUTURE_STRICT_RESERVED_WORD: {
Handle<String> name = ParseIdentifier(CHECK_OK);
if (fni_ != NULL) fni_->PushVariableName(name);
result = top_scope_->NewUnresolved(name, scanner().location().beg_pos);
break;
}
case Token::NUMBER: {
Consume(Token::NUMBER);
ASSERT(scanner().is_literal_ascii());
double value = StringToDouble(isolate()->unicode_cache(),
scanner().literal_ascii_string(),
ALLOW_HEX | ALLOW_OCTALS);
result = NewNumberLiteral(value);
break;
}
case Token::STRING: {
Consume(Token::STRING);
Handle<String> symbol = GetSymbol(CHECK_OK);
result = NewLiteral(symbol);
if (fni_ != NULL) fni_->PushLiteralName(symbol);
break;
}
case Token::ASSIGN_DIV:
result = ParseRegExpLiteral(true, CHECK_OK);
break;
case Token::DIV:
result = ParseRegExpLiteral(false, CHECK_OK);
break;
case Token::LBRACK:
result = ParseArrayLiteral(CHECK_OK);
break;
case Token::LBRACE:
result = ParseObjectLiteral(CHECK_OK);
break;
case Token::LPAREN:
Consume(Token::LPAREN);
// Heuristically try to detect immediately called functions before
// seeing the call parentheses.
parenthesized_function_ = (peek() == Token::FUNCTION);
result = ParseExpression(true, CHECK_OK);
Expect(Token::RPAREN, CHECK_OK);
break;
case Token::MOD:
if (allow_natives_syntax_ || extension_ != NULL) {
result = ParseV8Intrinsic(CHECK_OK);
break;
}
// If we're not allowing special syntax we fall-through to the
// default case.
default: {
Token::Value tok = Next();
ReportUnexpectedToken(tok);
*ok = false;
return NULL;
}
}
return result;
}
void Parser::BuildArrayLiteralBoilerplateLiterals(ZoneList<Expression*>* values,
Handle<FixedArray> literals,
bool* is_simple,
int* depth) {
// Fill in the literals.
// Accumulate output values in local variables.
bool is_simple_acc = true;
int depth_acc = 1;
for (int i = 0; i < values->length(); i++) {
MaterializedLiteral* m_literal = values->at(i)->AsMaterializedLiteral();
if (m_literal != NULL && m_literal->depth() >= depth_acc) {
depth_acc = m_literal->depth() + 1;
}
Handle<Object> boilerplate_value = GetBoilerplateValue(values->at(i));
if (boilerplate_value->IsUndefined()) {
literals->set_the_hole(i);
is_simple_acc = false;
} else {
literals->set(i, *boilerplate_value);
}
}
*is_simple = is_simple_acc;
*depth = depth_acc;
}
Expression* Parser::ParseArrayLiteral(bool* ok) {
// ArrayLiteral ::
// '[' Expression? (',' Expression?)* ']'
ZoneList<Expression*>* values = new(zone()) ZoneList<Expression*>(4);
Expect(Token::LBRACK, CHECK_OK);
while (peek() != Token::RBRACK) {
Expression* elem;
if (peek() == Token::COMMA) {
elem = GetLiteralTheHole();
} else {
elem = ParseAssignmentExpression(true, CHECK_OK);
}
values->Add(elem);
if (peek() != Token::RBRACK) {
Expect(Token::COMMA, CHECK_OK);
}
}
Expect(Token::RBRACK, CHECK_OK);
// Update the scope information before the pre-parsing bailout.
int literal_index = current_function_state_->NextMaterializedLiteralIndex();
// Allocate a fixed array to hold all the object literals.
Handle<FixedArray> object_literals =
isolate()->factory()->NewFixedArray(values->length(), TENURED);
Handle<FixedDoubleArray> double_literals;
ElementsKind elements_kind = FAST_SMI_ONLY_ELEMENTS;
// Fill in the literals.
bool is_simple = true;
int depth = 1;
for (int i = 0, n = values->length(); i < n; i++) {
MaterializedLiteral* m_literal = values->at(i)->AsMaterializedLiteral();
if (m_literal != NULL && m_literal->depth() + 1 > depth) {
depth = m_literal->depth() + 1;
}
Handle<Object> boilerplate_value = GetBoilerplateValue(values->at(i));
if (boilerplate_value->IsUndefined()) {
object_literals->set_the_hole(i);
if (elements_kind == FAST_DOUBLE_ELEMENTS) {
double_literals->set_the_hole(i);
}
is_simple = false;
} else {
// Examine each literal element, and adjust the ElementsKind if the
// literal element is not of a type that can be stored in the current
// ElementsKind. Start with FAST_SMI_ONLY_ELEMENTS, and transition to
// FAST_DOUBLE_ELEMENTS and FAST_ELEMENTS as necessary. Always remember
// the tagged value, no matter what the ElementsKind is in case we
// ultimately end up in FAST_ELEMENTS.
object_literals->set(i, *boilerplate_value);
if (elements_kind == FAST_SMI_ONLY_ELEMENTS) {
// Smi only elements. Notice if a transition to FAST_DOUBLE_ELEMENTS or
// FAST_ELEMENTS is required.
if (!boilerplate_value->IsSmi()) {
if (boilerplate_value->IsNumber() && FLAG_smi_only_arrays) {
// Allocate a double array on the FAST_DOUBLE_ELEMENTS transition to
// avoid over-allocating in TENURED space.
double_literals = isolate()->factory()->NewFixedDoubleArray(
values->length(), TENURED);
// Copy the contents of the FAST_SMI_ONLY_ELEMENT array to the
// FAST_DOUBLE_ELEMENTS array so that they are in sync.
for (int j = 0; j < i; ++j) {
Object* smi_value = object_literals->get(j);
if (smi_value->IsTheHole()) {
double_literals->set_the_hole(j);
} else {
double_literals->set(j, Smi::cast(smi_value)->value());
}
}
double_literals->set(i, boilerplate_value->Number());
elements_kind = FAST_DOUBLE_ELEMENTS;
} else {
elements_kind = FAST_ELEMENTS;
}
}
} else if (elements_kind == FAST_DOUBLE_ELEMENTS) {
// Continue to store double values in to FAST_DOUBLE_ELEMENTS arrays
// until the first value is seen that can't be stored as a double.
if (boilerplate_value->IsNumber()) {
double_literals->set(i, boilerplate_value->Number());
} else {
elements_kind = FAST_ELEMENTS;
}
}
}
}
// Simple and shallow arrays can be lazily copied, we transform the
// elements array to a copy-on-write array.
if (is_simple && depth == 1 && values->length() > 0 &&
elements_kind != FAST_DOUBLE_ELEMENTS) {
object_literals->set_map(isolate()->heap()->fixed_cow_array_map());
}
Handle<FixedArrayBase> element_values = elements_kind == FAST_DOUBLE_ELEMENTS
? Handle<FixedArrayBase>(double_literals)
: Handle<FixedArrayBase>(object_literals);
// Remember both the literal's constant values as well as the ElementsKind
// in a 2-element FixedArray.
Handle<FixedArray> literals =
isolate()->factory()->NewFixedArray(2, TENURED);
literals->set(0, Smi::FromInt(elements_kind));
literals->set(1, *element_values);
return new(zone()) ArrayLiteral(
isolate(), literals, values, literal_index, is_simple, depth);
}
bool Parser::IsBoilerplateProperty(ObjectLiteral::Property* property) {
return property != NULL &&
property->kind() != ObjectLiteral::Property::PROTOTYPE;
}
bool CompileTimeValue::IsCompileTimeValue(Expression* expression) {
if (expression->AsLiteral() != NULL) return true;
MaterializedLiteral* lit = expression->AsMaterializedLiteral();
return lit != NULL && lit->is_simple();
}
bool CompileTimeValue::ArrayLiteralElementNeedsInitialization(
Expression* value) {
// If value is a literal the property value is already set in the
// boilerplate object.
if (value->AsLiteral() != NULL) return false;
// If value is a materialized literal the property value is already set
// in the boilerplate object if it is simple.
if (CompileTimeValue::IsCompileTimeValue(value)) return false;
return true;
}
Handle<FixedArray> CompileTimeValue::GetValue(Expression* expression) {
ASSERT(IsCompileTimeValue(expression));
Handle<FixedArray> result = FACTORY->NewFixedArray(2, TENURED);
ObjectLiteral* object_literal = expression->AsObjectLiteral();
if (object_literal != NULL) {
ASSERT(object_literal->is_simple());
if (object_literal->fast_elements()) {
result->set(kTypeSlot, Smi::FromInt(OBJECT_LITERAL_FAST_ELEMENTS));
} else {
result->set(kTypeSlot, Smi::FromInt(OBJECT_LITERAL_SLOW_ELEMENTS));
}
result->set(kElementsSlot, *object_literal->constant_properties());
} else {
ArrayLiteral* array_literal = expression->AsArrayLiteral();
ASSERT(array_literal != NULL && array_literal->is_simple());
result->set(kTypeSlot, Smi::FromInt(ARRAY_LITERAL));
result->set(kElementsSlot, *array_literal->constant_elements());
}
return result;
}
CompileTimeValue::Type CompileTimeValue::GetType(Handle<FixedArray> value) {
Smi* type_value = Smi::cast(value->get(kTypeSlot));
return static_cast<Type>(type_value->value());
}
Handle<FixedArray> CompileTimeValue::GetElements(Handle<FixedArray> value) {
return Handle<FixedArray>(FixedArray::cast(value->get(kElementsSlot)));
}
Handle<Object> Parser::GetBoilerplateValue(Expression* expression) {
if (expression->AsLiteral() != NULL) {
return expression->AsLiteral()->handle();
}
if (CompileTimeValue::IsCompileTimeValue(expression)) {
return CompileTimeValue::GetValue(expression);
}
return isolate()->factory()->undefined_value();
}
// Defined in ast.cc
bool IsEqualString(void* first, void* second);
bool IsEqualNumber(void* first, void* second);
// Validation per 11.1.5 Object Initialiser
class ObjectLiteralPropertyChecker {
public:
ObjectLiteralPropertyChecker(Parser* parser, LanguageMode language_mode) :
props(&IsEqualString),
elems(&IsEqualNumber),
parser_(parser),
language_mode_(language_mode) {
}
void CheckProperty(
ObjectLiteral::Property* property,
Scanner::Location loc,
bool* ok);
private:
enum PropertyKind {
kGetAccessor = 0x01,
kSetAccessor = 0x02,
kAccessor = kGetAccessor | kSetAccessor,
kData = 0x04
};
static intptr_t GetPropertyKind(ObjectLiteral::Property* property) {
switch (property->kind()) {
case ObjectLiteral::Property::GETTER:
return kGetAccessor;
case ObjectLiteral::Property::SETTER:
return kSetAccessor;
default:
return kData;
}
}
HashMap props;
HashMap elems;
Parser* parser_;
LanguageMode language_mode_;
};
void ObjectLiteralPropertyChecker::CheckProperty(
ObjectLiteral::Property* property,
Scanner::Location loc,
bool* ok) {
ASSERT(property != NULL);
Literal *lit = property->key();
Handle<Object> handle = lit->handle();
uint32_t hash;
HashMap* map;
void* key;
if (handle->IsSymbol()) {
Handle<String> name(String::cast(*handle));
if (name->AsArrayIndex(&hash)) {
Handle<Object> key_handle = FACTORY->NewNumberFromUint(hash);
key = key_handle.location();
map = &elems;
} else {
key = handle.location();
hash = name->Hash();
map = &props;
}
} else if (handle->ToArrayIndex(&hash)) {
key = handle.location();
map = &elems;
} else {
ASSERT(handle->IsNumber());
double num = handle->Number();
char arr[100];
Vector<char> buffer(arr, ARRAY_SIZE(arr));
const char* str = DoubleToCString(num, buffer);
Handle<String> name = FACTORY->NewStringFromAscii(CStrVector(str));
key = name.location();
hash = name->Hash();
map = &props;
}
// Lookup property previously defined, if any.
HashMap::Entry* entry = map->Lookup(key, hash, true);
intptr_t prev = reinterpret_cast<intptr_t> (entry->value);
intptr_t curr = GetPropertyKind(property);
// Duplicate data properties are illegal in strict or extended mode.
if (language_mode_ != CLASSIC_MODE && (curr & prev & kData) != 0) {
parser_->ReportMessageAt(loc, "strict_duplicate_property",
Vector<const char*>::empty());
*ok = false;
return;
}
// Data property conflicting with an accessor.
if (((curr & kData) && (prev & kAccessor)) ||
((prev & kData) && (curr & kAccessor))) {
parser_->ReportMessageAt(loc, "accessor_data_property",
Vector<const char*>::empty());
*ok = false;
return;
}
// Two accessors of the same type conflicting
if ((curr & prev & kAccessor) != 0) {
parser_->ReportMessageAt(loc, "accessor_get_set",
Vector<const char*>::empty());
*ok = false;
return;
}
// Update map
entry->value = reinterpret_cast<void*> (prev | curr);
*ok = true;
}
void Parser::BuildObjectLiteralConstantProperties(
ZoneList<ObjectLiteral::Property*>* properties,
Handle<FixedArray> constant_properties,
bool* is_simple,
bool* fast_elements,
int* depth) {
int position = 0;
// Accumulate the value in local variables and store it at the end.
bool is_simple_acc = true;
int depth_acc = 1;
uint32_t max_element_index = 0;
uint32_t elements = 0;
for (int i = 0; i < properties->length(); i++) {
ObjectLiteral::Property* property = properties->at(i);
if (!IsBoilerplateProperty(property)) {
is_simple_acc = false;
continue;
}
MaterializedLiteral* m_literal = property->value()->AsMaterializedLiteral();
if (m_literal != NULL && m_literal->depth() >= depth_acc) {
depth_acc = m_literal->depth() + 1;
}
// Add CONSTANT and COMPUTED properties to boilerplate. Use undefined
// value for COMPUTED properties, the real value is filled in at
// runtime. The enumeration order is maintained.
Handle<Object> key = property->key()->handle();
Handle<Object> value = GetBoilerplateValue(property->value());
is_simple_acc = is_simple_acc && !value->IsUndefined();
// Keep track of the number of elements in the object literal and
// the largest element index. If the largest element index is
// much larger than the number of elements, creating an object
// literal with fast elements will be a waste of space.
uint32_t element_index = 0;
if (key->IsString()
&& Handle<String>::cast(key)->AsArrayIndex(&element_index)
&& element_index > max_element_index) {
max_element_index = element_index;
elements++;
} else if (key->IsSmi()) {
int key_value = Smi::cast(*key)->value();
if (key_value > 0
&& static_cast<uint32_t>(key_value) > max_element_index) {
max_element_index = key_value;
}
elements++;
}
// Add name, value pair to the fixed array.
constant_properties->set(position++, *key);
constant_properties->set(position++, *value);
}
*fast_elements =
(max_element_index <= 32) || ((2 * elements) >= max_element_index);
*is_simple = is_simple_acc;
*depth = depth_acc;
}
ObjectLiteral::Property* Parser::ParseObjectLiteralGetSet(bool is_getter,
bool* ok) {
// Special handling of getter and setter syntax:
// { ... , get foo() { ... }, ... , set foo(v) { ... v ... } , ... }
// We have already read the "get" or "set" keyword.
Token::Value next = Next();
bool is_keyword = Token::IsKeyword(next);
if (next == Token::IDENTIFIER || next == Token::NUMBER ||
next == Token::FUTURE_RESERVED_WORD ||
next == Token::FUTURE_STRICT_RESERVED_WORD ||
next == Token::STRING || is_keyword) {
Handle<String> name;
if (is_keyword) {
name = isolate_->factory()->LookupAsciiSymbol(Token::String(next));
} else {
name = GetSymbol(CHECK_OK);
}
FunctionLiteral* value =
ParseFunctionLiteral(name,
false, // reserved words are allowed here
RelocInfo::kNoPosition,
FunctionLiteral::ANONYMOUS_EXPRESSION,
CHECK_OK);
// Allow any number of parameters for compatiabilty with JSC.
// Specification only allows zero parameters for get and one for set.
ObjectLiteral::Property* property =
new(zone()) ObjectLiteral::Property(is_getter, value);
return property;
} else {
ReportUnexpectedToken(next);
*ok = false;
return NULL;
}
}
Expression* Parser::ParseObjectLiteral(bool* ok) {
// ObjectLiteral ::
// '{' (
// ((IdentifierName | String | Number) ':' AssignmentExpression)
// | (('get' | 'set') (IdentifierName | String | Number) FunctionLiteral)
// )*[','] '}'
ZoneList<ObjectLiteral::Property*>* properties =
new(zone()) ZoneList<ObjectLiteral::Property*>(4);
int number_of_boilerplate_properties = 0;
bool has_function = false;
ObjectLiteralPropertyChecker checker(this, top_scope_->language_mode());
Expect(Token::LBRACE, CHECK_OK);
while (peek() != Token::RBRACE) {
if (fni_ != NULL) fni_->Enter();
Literal* key = NULL;
Token::Value next = peek();
// Location of the property name token
Scanner::Location loc = scanner().peek_location();
switch (next) {
case Token::FUTURE_RESERVED_WORD:
case Token::FUTURE_STRICT_RESERVED_WORD:
case Token::IDENTIFIER: {
bool is_getter = false;
bool is_setter = false;
Handle<String> id =
ParseIdentifierNameOrGetOrSet(&is_getter, &is_setter, CHECK_OK);
if (fni_ != NULL) fni_->PushLiteralName(id);
if ((is_getter || is_setter) && peek() != Token::COLON) {
// Update loc to point to the identifier
loc = scanner().peek_location();
ObjectLiteral::Property* property =
ParseObjectLiteralGetSet(is_getter, CHECK_OK);
if (IsBoilerplateProperty(property)) {
number_of_boilerplate_properties++;
}
// Validate the property.
checker.CheckProperty(property, loc, CHECK_OK);
properties->Add(property);
if (peek() != Token::RBRACE) Expect(Token::COMMA, CHECK_OK);
if (fni_ != NULL) {
fni_->Infer();
fni_->Leave();
}
continue; // restart the while
}
// Failed to parse as get/set property, so it's just a property
// called "get" or "set".
key = NewLiteral(id);
break;
}
case Token::STRING: {
Consume(Token::STRING);
Handle<String> string = GetSymbol(CHECK_OK);
if (fni_ != NULL) fni_->PushLiteralName(string);
uint32_t index;
if (!string.is_null() && string->AsArrayIndex(&index)) {
key = NewNumberLiteral(index);
break;
}
key = NewLiteral(string);
break;
}
case Token::NUMBER: {
Consume(Token::NUMBER);
ASSERT(scanner().is_literal_ascii());
double value = StringToDouble(isolate()->unicode_cache(),
scanner().literal_ascii_string(),
ALLOW_HEX | ALLOW_OCTALS);
key = NewNumberLiteral(value);
break;
}
default:
if (Token::IsKeyword(next)) {
Consume(next);
Handle<String> string = GetSymbol(CHECK_OK);
key = NewLiteral(string);
} else {
// Unexpected token.
Token::Value next = Next();
ReportUnexpectedToken(next);
*ok = false;
return NULL;
}
}
Expect(Token::COLON, CHECK_OK);
Expression* value = ParseAssignmentExpression(true, CHECK_OK);
ObjectLiteral::Property* property =
new(zone()) ObjectLiteral::Property(key, value);
// Mark top-level object literals that contain function literals and
// pretenure the literal so it can be added as a constant function
// property.
if (top_scope_->DeclarationScope()->is_global_scope() &&
value->AsFunctionLiteral() != NULL) {
has_function = true;
value->AsFunctionLiteral()->set_pretenure();
}
// Count CONSTANT or COMPUTED properties to maintain the enumeration order.
if (IsBoilerplateProperty(property)) number_of_boilerplate_properties++;
// Validate the property
checker.CheckProperty(property, loc, CHECK_OK);
properties->Add(property);
// TODO(1240767): Consider allowing trailing comma.
if (peek() != Token::RBRACE) Expect(Token::COMMA, CHECK_OK);
if (fni_ != NULL) {
fni_->Infer();
fni_->Leave();
}
}
Expect(Token::RBRACE, CHECK_OK);
// Computation of literal_index must happen before pre parse bailout.
int literal_index = current_function_state_->NextMaterializedLiteralIndex();
Handle<FixedArray> constant_properties = isolate()->factory()->NewFixedArray(
number_of_boilerplate_properties * 2, TENURED);
bool is_simple = true;
bool fast_elements = true;
int depth = 1;
BuildObjectLiteralConstantProperties(properties,
constant_properties,
&is_simple,
&fast_elements,
&depth);
return new(zone()) ObjectLiteral(isolate(),
constant_properties,
properties,
literal_index,
is_simple,
fast_elements,
depth,
has_function);
}
Expression* Parser::ParseRegExpLiteral(bool seen_equal, bool* ok) {
if (!scanner().ScanRegExpPattern(seen_equal)) {
Next();
ReportMessage("unterminated_regexp", Vector<const char*>::empty());
*ok = false;
return NULL;
}
int literal_index = current_function_state_->NextMaterializedLiteralIndex();
Handle<String> js_pattern = NextLiteralString(TENURED);
scanner().ScanRegExpFlags();
Handle<String> js_flags = NextLiteralString(TENURED);
Next();
return new(zone()) RegExpLiteral(
isolate(), js_pattern, js_flags, literal_index);
}
ZoneList<Expression*>* Parser::ParseArguments(bool* ok) {
// Arguments ::
// '(' (AssignmentExpression)*[','] ')'
ZoneList<Expression*>* result = new(zone()) ZoneList<Expression*>(4);
Expect(Token::LPAREN, CHECK_OK);
bool done = (peek() == Token::RPAREN);
while (!done) {
Expression* argument = ParseAssignmentExpression(true, CHECK_OK);
result->Add(argument);
if (result->length() > kMaxNumFunctionParameters) {
ReportMessageAt(scanner().location(), "too_many_arguments",
Vector<const char*>::empty());
*ok = false;
return NULL;
}
done = (peek() == Token::RPAREN);
if (!done) Expect(Token::COMMA, CHECK_OK);
}
Expect(Token::RPAREN, CHECK_OK);
return result;
}
class SingletonLogger : public ParserRecorder {
public:
SingletonLogger() : has_error_(false), start_(-1), end_(-1) { }
~SingletonLogger() { }
void Reset() { has_error_ = false; }
virtual void LogFunction(int start,
int end,
int literals,
int properties,
LanguageMode mode) {
ASSERT(!has_error_);
start_ = start;
end_ = end;
literals_ = literals;
properties_ = properties;
mode_ = mode;
};
// Logs a symbol creation of a literal or identifier.
virtual void LogAsciiSymbol(int start, Vector<const char> literal) { }
virtual void LogUC16Symbol(int start, Vector<const uc16> literal) { }
// Logs an error message and marks the log as containing an error.
// Further logging will be ignored, and ExtractData will return a vector
// representing the error only.
virtual void LogMessage(int start,
int end,
const char* message,
const char* argument_opt) {
has_error_ = true;
start_ = start;
end_ = end;
message_ = message;
argument_opt_ = argument_opt;
}
virtual int function_position() { return 0; }
virtual int symbol_position() { return 0; }
virtual int symbol_ids() { return -1; }
virtual Vector<unsigned> ExtractData() {
UNREACHABLE();
return Vector<unsigned>();
}
virtual void PauseRecording() { }
virtual void ResumeRecording() { }
bool has_error() { return has_error_; }
int start() { return start_; }
int end() { return end_; }
int literals() {
ASSERT(!has_error_);
return literals_;
}
int properties() {
ASSERT(!has_error_);
return properties_;
}
LanguageMode language_mode() {
ASSERT(!has_error_);
return mode_;
}
const char* message() {
ASSERT(has_error_);
return message_;
}
const char* argument_opt() {
ASSERT(has_error_);
return argument_opt_;
}
private:
bool has_error_;
int start_;
int end_;
// For function entries.
int literals_;
int properties_;
LanguageMode mode_;
// For error messages.
const char* message_;
const char* argument_opt_;
};
FunctionLiteral* Parser::ParseFunctionLiteral(Handle<String> function_name,
bool name_is_strict_reserved,
int function_token_position,
FunctionLiteral::Type type,
bool* ok) {
// Function ::
// '(' FormalParameterList? ')' '{' FunctionBody '}'
// Anonymous functions were passed either the empty symbol or a null
// handle as the function name. Remember if we were passed a non-empty
// handle to decide whether to invoke function name inference.
bool should_infer_name = function_name.is_null();
// We want a non-null handle as the function name.
if (should_infer_name) {
function_name = isolate()->factory()->empty_symbol();
}
int num_parameters = 0;
// Function declarations are function scoped in normal mode, so they are
// hoisted. In harmony block scoping mode they are block scoped, so they
// are not hoisted.
Scope* scope = (type == FunctionLiteral::DECLARATION && !is_extended_mode())
? NewScope(top_scope_->DeclarationScope(), FUNCTION_SCOPE)
: NewScope(top_scope_, FUNCTION_SCOPE);
ZoneList<Statement*>* body = NULL;
int materialized_literal_count = -1;
int expected_property_count = -1;
int handler_count = 0;
bool only_simple_this_property_assignments;
Handle<FixedArray> this_property_assignments;
bool has_duplicate_parameters = false;
// Parse function body.
{ FunctionState function_state(this, scope, isolate());
top_scope_->SetScopeName(function_name);
// FormalParameterList ::
// '(' (Identifier)*[','] ')'
Expect(Token::LPAREN, CHECK_OK);
scope->set_start_position(scanner().location().beg_pos);
Scanner::Location name_loc = Scanner::Location::invalid();
Scanner::Location dupe_loc = Scanner::Location::invalid();
Scanner::Location reserved_loc = Scanner::Location::invalid();
bool done = (peek() == Token::RPAREN);
while (!done) {
bool is_strict_reserved = false;
Handle<String> param_name =
ParseIdentifierOrStrictReservedWord(&is_strict_reserved,
CHECK_OK);
// Store locations for possible future error reports.
if (!name_loc.IsValid() && IsEvalOrArguments(param_name)) {
name_loc = scanner().location();
}
if (!dupe_loc.IsValid() && top_scope_->IsDeclared(param_name)) {
has_duplicate_parameters = true;
dupe_loc = scanner().location();
}
if (!reserved_loc.IsValid() && is_strict_reserved) {
reserved_loc = scanner().location();
}
top_scope_->DeclareParameter(param_name, is_extended_mode() ? LET : VAR);
num_parameters++;
if (num_parameters > kMaxNumFunctionParameters) {
ReportMessageAt(scanner().location(), "too_many_parameters",
Vector<const char*>::empty());
*ok = false;
return NULL;
}
done = (peek() == Token::RPAREN);
if (!done) Expect(Token::COMMA, CHECK_OK);
}
Expect(Token::RPAREN, CHECK_OK);
Expect(Token::LBRACE, CHECK_OK);
// If we have a named function expression, we add a local variable
// declaration to the body of the function with the name of the
// function and let it refer to the function itself (closure).
// NOTE: We create a proxy and resolve it here so that in the
// future we can change the AST to only refer to VariableProxies
// instead of Variables and Proxis as is the case now.
Variable* fvar = NULL;
Token::Value fvar_init_op = Token::INIT_CONST;
if (type == FunctionLiteral::NAMED_EXPRESSION) {
VariableMode fvar_mode;
if (is_extended_mode()) {
fvar_mode = CONST_HARMONY;
fvar_init_op = Token::INIT_CONST_HARMONY;
} else {
fvar_mode = CONST;
}
fvar = top_scope_->DeclareFunctionVar(function_name, fvar_mode);
}
// Determine whether the function will be lazily compiled.
// The heuristics are:
// - It must not have been prohibited by the caller to Parse (some callers
// need a full AST).
// - The outer scope must be trivial (only global variables in scope).
// - The function mustn't be a function expression with an open parenthesis
// before; we consider that a hint that the function will be called
// immediately, and it would be a waste of time to make it lazily
// compiled.
// These are all things we can know at this point, without looking at the
// function itself.
bool is_lazily_compiled = (mode() == PARSE_LAZILY &&
top_scope_->outer_scope()->is_global_scope() &&
top_scope_->HasTrivialOuterContext() &&
!parenthesized_function_);
parenthesized_function_ = false; // The bit was set for this function only.
if (is_lazily_compiled) {
int function_block_pos = scanner().location().beg_pos;
FunctionEntry entry;
if (pre_data_ != NULL) {
// If we have pre_data_, we use it to skip parsing the function body.
// the preparser data contains the information we need to construct the
// lazy function.
entry = pre_data()->GetFunctionEntry(function_block_pos);
if (entry.is_valid()) {
if (entry.end_pos() <= function_block_pos) {
// End position greater than end of stream is safe, and hard
// to check.
ReportInvalidPreparseData(function_name, CHECK_OK);
}
scanner().SeekForward(entry.end_pos() - 1);
scope->set_end_position(entry.end_pos());
Expect(Token::RBRACE, CHECK_OK);
isolate()->counters()->total_preparse_skipped()->Increment(
scope->end_position() - function_block_pos);
materialized_literal_count = entry.literal_count();
expected_property_count = entry.property_count();
top_scope_->SetLanguageMode(entry.language_mode());
only_simple_this_property_assignments = false;
this_property_assignments = isolate()->factory()->empty_fixed_array();
} else {
is_lazily_compiled = false;
}
} else {
// With no preparser data, we partially parse the function, without
// building an AST. This gathers the data needed to build a lazy
// function.
SingletonLogger logger;
preparser::PreParser::PreParseResult result =
LazyParseFunctionLiteral(&logger);
if (result == preparser::PreParser::kPreParseStackOverflow) {
// Propagate stack overflow.
stack_overflow_ = true;
*ok = false;
return NULL;
}
if (logger.has_error()) {
const char* arg = logger.argument_opt();
Vector<const char*> args;
if (arg != NULL) {
args = Vector<const char*>(&arg, 1);
}
ReportMessageAt(Scanner::Location(logger.start(), logger.end()),
logger.message(), args);
*ok = false;
return NULL;
}
scope->set_end_position(logger.end());
Expect(Token::RBRACE, CHECK_OK);
isolate()->counters()->total_preparse_skipped()->Increment(
scope->end_position() - function_block_pos);
materialized_literal_count = logger.literals();
expected_property_count = logger.properties();
top_scope_->SetLanguageMode(logger.language_mode());
only_simple_this_property_assignments = false;
this_property_assignments = isolate()->factory()->empty_fixed_array();
}
}
if (!is_lazily_compiled) {
body = new(zone()) ZoneList<Statement*>(8);
if (fvar != NULL) {
VariableProxy* fproxy = top_scope_->NewUnresolved(function_name);
fproxy->BindTo(fvar);
body->Add(new(zone()) ExpressionStatement(
new(zone()) Assignment(isolate(),
fvar_init_op,
fproxy,
new(zone()) ThisFunction(isolate()),
RelocInfo::kNoPosition)));
}
ParseSourceElements(body, Token::RBRACE, CHECK_OK);
materialized_literal_count = function_state.materialized_literal_count();
expected_property_count = function_state.expected_property_count();
handler_count = function_state.handler_count();
only_simple_this_property_assignments =
function_state.only_simple_this_property_assignments();
this_property_assignments = function_state.this_property_assignments();
Expect(Token::RBRACE, CHECK_OK);
scope->set_end_position(scanner().location().end_pos);
}
// Validate strict mode.
if (!top_scope_->is_classic_mode()) {
if (IsEvalOrArguments(function_name)) {
int start_pos = scope->start_position();
int position = function_token_position != RelocInfo::kNoPosition
? function_token_position
: (start_pos > 0 ? start_pos - 1 : start_pos);
Scanner::Location location = Scanner::Location(position, start_pos);
ReportMessageAt(location,
"strict_function_name", Vector<const char*>::empty());
*ok = false;
return NULL;
}
if (name_loc.IsValid()) {
ReportMessageAt(name_loc, "strict_param_name",
Vector<const char*>::empty());
*ok = false;
return NULL;
}
if (dupe_loc.IsValid()) {
ReportMessageAt(dupe_loc, "strict_param_dupe",
Vector<const char*>::empty());
*ok = false;
return NULL;
}
if (name_is_strict_reserved) {
int start_pos = scope->start_position();
int position = function_token_position != RelocInfo::kNoPosition
? function_token_position
: (start_pos > 0 ? start_pos - 1 : start_pos);
Scanner::Location location = Scanner::Location(position, start_pos);
ReportMessageAt(location, "strict_reserved_word",
Vector<const char*>::empty());
*ok = false;
return NULL;
}
if (reserved_loc.IsValid()) {
ReportMessageAt(reserved_loc, "strict_reserved_word",
Vector<const char*>::empty());
*ok = false;
return NULL;
}
CheckOctalLiteral(scope->start_position(),
scope->end_position(),
CHECK_OK);
}
}
if (is_extended_mode()) {
CheckConflictingVarDeclarations(scope, CHECK_OK);
}
FunctionLiteral* function_literal =
new(zone()) FunctionLiteral(isolate(),
function_name,
scope,
body,
materialized_literal_count,
expected_property_count,
handler_count,
only_simple_this_property_assignments,
this_property_assignments,
num_parameters,
type,
has_duplicate_parameters);
function_literal->set_function_token_position(function_token_position);
if (fni_ != NULL && should_infer_name) fni_->AddFunction(function_literal);
return function_literal;
}
preparser::PreParser::PreParseResult Parser::LazyParseFunctionLiteral(
SingletonLogger* logger) {
HistogramTimerScope preparse_scope(isolate()->counters()->pre_parse());
ASSERT_EQ(Token::LBRACE, scanner().current_token());
if (reusable_preparser_ == NULL) {
intptr_t stack_limit = isolate()->stack_guard()->real_climit();
bool do_allow_lazy = true;
reusable_preparser_ = new preparser::PreParser(&scanner_,
NULL,
stack_limit,
do_allow_lazy,
allow_natives_syntax_);
}
preparser::PreParser::PreParseResult result =
reusable_preparser_->PreParseLazyFunction(top_scope_->language_mode(),
logger);
return result;
}
Expression* Parser::ParseV8Intrinsic(bool* ok) {
// CallRuntime ::
// '%' Identifier Arguments
Expect(Token::MOD, CHECK_OK);
Handle<String> name = ParseIdentifier(CHECK_OK);
ZoneList<Expression*>* args = ParseArguments(CHECK_OK);
if (extension_ != NULL) {
// The extension structures are only accessible while parsing the
// very first time not when reparsing because of lazy compilation.
top_scope_->DeclarationScope()->ForceEagerCompilation();
}
const Runtime::Function* function = Runtime::FunctionForSymbol(name);
// Check for built-in IS_VAR macro.
if (function != NULL &&
function->intrinsic_type == Runtime::RUNTIME &&
function->function_id == Runtime::kIS_VAR) {
// %IS_VAR(x) evaluates to x if x is a variable,
// leads to a parse error otherwise. Could be implemented as an
// inline function %_IS_VAR(x) to eliminate this special case.
if (args->length() == 1 && args->at(0)->AsVariableProxy() != NULL) {
return args->at(0);
} else {
ReportMessage("unable_to_parse", Vector<const char*>::empty());
*ok = false;
return NULL;
}
}
// Check that the expected number of arguments are being passed.
if (function != NULL &&
function->nargs != -1 &&
function->nargs != args->length()) {
ReportMessage("illegal_access", Vector<const char*>::empty());
*ok = false;
return NULL;
}
// We have a valid intrinsics call or a call to a builtin.
return new(zone()) CallRuntime(isolate(), name, function, args);
}
bool Parser::peek_any_identifier() {
Token::Value next = peek();
return next == Token::IDENTIFIER ||
next == Token::FUTURE_RESERVED_WORD ||
next == Token::FUTURE_STRICT_RESERVED_WORD;
}
void Parser::Consume(Token::Value token) {
Token::Value next = Next();
USE(next);
USE(token);
ASSERT(next == token);
}
void Parser::Expect(Token::Value token, bool* ok) {
Token::Value next = Next();
if (next == token) return;
ReportUnexpectedToken(next);
*ok = false;
}
bool Parser::Check(Token::Value token) {
Token::Value next = peek();
if (next == token) {
Consume(next);
return true;
}
return false;
}
void Parser::ExpectSemicolon(bool* ok) {
// Check for automatic semicolon insertion according to
// the rules given in ECMA-262, section 7.9, page 21.
Token::Value tok = peek();
if (tok == Token::SEMICOLON) {
Next();
return;
}
if (scanner().HasAnyLineTerminatorBeforeNext() ||
tok == Token::RBRACE ||
tok == Token::EOS) {
return;
}
Expect(Token::SEMICOLON, ok);
}
Literal* Parser::GetLiteralUndefined() {
return NewLiteral(isolate()->factory()->undefined_value());
}
Literal* Parser::GetLiteralTheHole() {
return NewLiteral(isolate()->factory()->the_hole_value());
}
Literal* Parser::GetLiteralNumber(double value) {
return NewNumberLiteral(value);
}
// Parses an identifier that is valid for the current scope, in particular it
// fails on strict mode future reserved keywords in a strict scope.
Handle<String> Parser::ParseIdentifier(bool* ok) {
if (!top_scope_->is_classic_mode()) {
Expect(Token::IDENTIFIER, ok);
} else if (!Check(Token::IDENTIFIER)) {
Expect(Token::FUTURE_STRICT_RESERVED_WORD, ok);
}
if (!*ok) return Handle<String>();
return GetSymbol(ok);
}
// Parses and identifier or a strict mode future reserved word, and indicate
// whether it is strict mode future reserved.
Handle<String> Parser::ParseIdentifierOrStrictReservedWord(
bool* is_strict_reserved, bool* ok) {
*is_strict_reserved = false;
if (!Check(Token::IDENTIFIER)) {
Expect(Token::FUTURE_STRICT_RESERVED_WORD, ok);
*is_strict_reserved = true;
}
if (!*ok) return Handle<String>();
return GetSymbol(ok);
}
Handle<String> Parser::ParseIdentifierName(bool* ok) {
Token::Value next = Next();
if (next != Token::IDENTIFIER &&
next != Token::FUTURE_RESERVED_WORD &&
next != Token::FUTURE_STRICT_RESERVED_WORD &&
!Token::IsKeyword(next)) {
ReportUnexpectedToken(next);
*ok = false;
return Handle<String>();
}
return GetSymbol(ok);
}
// Checks LHS expression for assignment and prefix/postfix increment/decrement
// in strict mode.
void Parser::CheckStrictModeLValue(Expression* expression,
const char* error,
bool* ok) {
ASSERT(!top_scope_->is_classic_mode());
VariableProxy* lhs = expression != NULL
? expression->AsVariableProxy()
: NULL;
if (lhs != NULL && !lhs->is_this() && IsEvalOrArguments(lhs->name())) {
ReportMessage(error, Vector<const char*>::empty());
*ok = false;
}
}
// Checks whether an octal literal was last seen between beg_pos and end_pos.
// If so, reports an error. Only called for strict mode.
void Parser::CheckOctalLiteral(int beg_pos, int end_pos, bool* ok) {
Scanner::Location octal = scanner().octal_position();
if (octal.IsValid() &&
beg_pos <= octal.beg_pos &&
octal.end_pos <= end_pos) {
ReportMessageAt(octal, "strict_octal_literal",
Vector<const char*>::empty());
scanner().clear_octal_position();
*ok = false;
}
}
void Parser::CheckConflictingVarDeclarations(Scope* scope, bool* ok) {
Declaration* decl = scope->CheckConflictingVarDeclarations();
if (decl != NULL) {
// In harmony mode we treat conflicting variable bindinds as early
// errors. See ES5 16 for a definition of early errors.
Handle<String> name = decl->proxy()->name();
SmartArrayPointer<char> c_string = name->ToCString(DISALLOW_NULLS);
const char* elms[2] = { "Variable", *c_string };
Vector<const char*> args(elms, 2);
int position = decl->proxy()->position();
Scanner::Location location = position == RelocInfo::kNoPosition
? Scanner::Location::invalid()
: Scanner::Location(position, position + 1);
ReportMessageAt(location, "redeclaration", args);
*ok = false;
}
}
// This function reads an identifier name and determines whether or not it
// is 'get' or 'set'.
Handle<String> Parser::ParseIdentifierNameOrGetOrSet(bool* is_get,
bool* is_set,
bool* ok) {
Handle<String> result = ParseIdentifierName(ok);
if (!*ok) return Handle<String>();
if (scanner().is_literal_ascii() && scanner().literal_length() == 3) {
const char* token = scanner().literal_ascii_string().start();
*is_get = strncmp(token, "get", 3) == 0;
*is_set = !*is_get && strncmp(token, "set", 3) == 0;
}
return result;
}
// ----------------------------------------------------------------------------
// Parser support
bool Parser::TargetStackContainsLabel(Handle<String> label) {
for (Target* t = target_stack_; t != NULL; t = t->previous()) {
BreakableStatement* stat = t->node()->AsBreakableStatement();
if (stat != NULL && ContainsLabel(stat->labels(), label))
return true;
}
return false;
}
BreakableStatement* Parser::LookupBreakTarget(Handle<String> label, bool* ok) {
bool anonymous = label.is_null();
for (Target* t = target_stack_; t != NULL; t = t->previous()) {
BreakableStatement* stat = t->node()->AsBreakableStatement();
if (stat == NULL) continue;
if ((anonymous && stat->is_target_for_anonymous()) ||
(!anonymous && ContainsLabel(stat->labels(), label))) {
RegisterTargetUse(stat->break_target(), t->previous());
return stat;
}
}
return NULL;
}
IterationStatement* Parser::LookupContinueTarget(Handle<String> label,
bool* ok) {
bool anonymous = label.is_null();
for (Target* t = target_stack_; t != NULL; t = t->previous()) {
IterationStatement* stat = t->node()->AsIterationStatement();
if (stat == NULL) continue;
ASSERT(stat->is_target_for_anonymous());
if (anonymous || ContainsLabel(stat->labels(), label)) {
RegisterTargetUse(stat->continue_target(), t->previous());
return stat;
}
}
return NULL;
}
void Parser::RegisterTargetUse(Label* target, Target* stop) {
// Register that a break target found at the given stop in the
// target stack has been used from the top of the target stack. Add
// the break target to any TargetCollectors passed on the stack.
for (Target* t = target_stack_; t != stop; t = t->previous()) {
TargetCollector* collector = t->node()->AsTargetCollector();
if (collector != NULL) collector->AddTarget(target);
}
}
Literal* Parser::NewNumberLiteral(double number) {
return NewLiteral(isolate()->factory()->NewNumber(number, TENURED));
}
Expression* Parser::NewThrowReferenceError(Handle<String> type) {
return NewThrowError(isolate()->factory()->MakeReferenceError_symbol(),
type, HandleVector<Object>(NULL, 0));
}
Expression* Parser::NewThrowSyntaxError(Handle<String> type,
Handle<Object> first) {
int argc = first.is_null() ? 0 : 1;
Vector< Handle<Object> > arguments = HandleVector<Object>(&first, argc);
return NewThrowError(
isolate()->factory()->MakeSyntaxError_symbol(), type, arguments);
}
Expression* Parser::NewThrowTypeError(Handle<String> type,
Handle<Object> first,
Handle<Object> second) {
ASSERT(!first.is_null() && !second.is_null());
Handle<Object> elements[] = { first, second };
Vector< Handle<Object> > arguments =
HandleVector<Object>(elements, ARRAY_SIZE(elements));
return NewThrowError(
isolate()->factory()->MakeTypeError_symbol(), type, arguments);
}
Expression* Parser::NewThrowError(Handle<String> constructor,
Handle<String> type,
Vector< Handle<Object> > arguments) {
int argc = arguments.length();
Handle<FixedArray> elements = isolate()->factory()->NewFixedArray(argc,
TENURED);
for (int i = 0; i < argc; i++) {
Handle<Object> element = arguments[i];
if (!element.is_null()) {
elements->set(i, *element);
}
}
Handle<JSArray> array = isolate()->factory()->NewJSArrayWithElements(elements,
TENURED);
ZoneList<Expression*>* args = new(zone()) ZoneList<Expression*>(2);
args->Add(NewLiteral(type));
args->Add(NewLiteral(array));
CallRuntime* call_constructor = new(zone()) CallRuntime(isolate(),
constructor,
NULL,
args);
return new(zone()) Throw(isolate(),
call_constructor,
scanner().location().beg_pos);
}
// ----------------------------------------------------------------------------
// Regular expressions
RegExpParser::RegExpParser(FlatStringReader* in,
Handle<String>* error,
bool multiline)
: isolate_(Isolate::Current()),
error_(error),
captures_(NULL),
in_(in),
current_(kEndMarker),
next_pos_(0),
capture_count_(0),
has_more_(true),
multiline_(multiline),
simple_(false),
contains_anchor_(false),
is_scanned_for_captures_(false),
failed_(false) {
Advance();
}
uc32 RegExpParser::Next() {
if (has_next()) {
return in()->Get(next_pos_);
} else {
return kEndMarker;
}
}
void RegExpParser::Advance() {
if (next_pos_ < in()->length()) {
StackLimitCheck check(isolate());
if (check.HasOverflowed()) {
ReportError(CStrVector(Isolate::kStackOverflowMessage));
} else if (isolate()->zone()->excess_allocation()) {
ReportError(CStrVector("Regular expression too large"));
} else {
current_ = in()->Get(next_pos_);
next_pos_++;
}
} else {
current_ = kEndMarker;
has_more_ = false;
}
}
void RegExpParser::Reset(int pos) {
next_pos_ = pos;
Advance();
}
void RegExpParser::Advance(int dist) {
next_pos_ += dist - 1;
Advance();
}
bool RegExpParser::simple() {
return simple_;
}
RegExpTree* RegExpParser::ReportError(Vector<const char> message) {
failed_ = true;
*error_ = isolate()->factory()->NewStringFromAscii(message, NOT_TENURED);
// Zip to the end to make sure the no more input is read.
current_ = kEndMarker;
next_pos_ = in()->length();
return NULL;
}
// Pattern ::
// Disjunction
RegExpTree* RegExpParser::ParsePattern() {
RegExpTree* result = ParseDisjunction(CHECK_FAILED);
ASSERT(!has_more());
// If the result of parsing is a literal string atom, and it has the
// same length as the input, then the atom is identical to the input.
if (result->IsAtom() && result->AsAtom()->length() == in()->length()) {
simple_ = true;
}
return result;
}
// Disjunction ::
// Alternative
// Alternative | Disjunction
// Alternative ::
// [empty]
// Term Alternative
// Term ::
// Assertion
// Atom
// Atom Quantifier
RegExpTree* RegExpParser::ParseDisjunction() {
// Used to store current state while parsing subexpressions.
RegExpParserState initial_state(NULL, INITIAL, 0);
RegExpParserState* stored_state = &initial_state;
// Cache the builder in a local variable for quick access.
RegExpBuilder* builder = initial_state.builder();
while (true) {
switch (current()) {
case kEndMarker:
if (stored_state->IsSubexpression()) {
// Inside a parenthesized group when hitting end of input.
ReportError(CStrVector("Unterminated group") CHECK_FAILED);
}
ASSERT_EQ(INITIAL, stored_state->group_type());
// Parsing completed successfully.
return builder->ToRegExp();
case ')': {
if (!stored_state->IsSubexpression()) {
ReportError(CStrVector("Unmatched ')'") CHECK_FAILED);
}
ASSERT_NE(INITIAL, stored_state->group_type());
Advance();
// End disjunction parsing and convert builder content to new single
// regexp atom.
RegExpTree* body = builder->ToRegExp();
int end_capture_index = captures_started();
int capture_index = stored_state->capture_index();
SubexpressionType type = stored_state->group_type();
// Restore previous state.
stored_state = stored_state->previous_state();
builder = stored_state->builder();
// Build result of subexpression.
if (type == CAPTURE) {
RegExpCapture* capture = new(zone()) RegExpCapture(body, capture_index);
captures_->at(capture_index - 1) = capture;
body = capture;
} else if (type != GROUPING) {
ASSERT(type == POSITIVE_LOOKAHEAD || type == NEGATIVE_LOOKAHEAD);
bool is_positive = (type == POSITIVE_LOOKAHEAD);
body = new(zone()) RegExpLookahead(body,
is_positive,
end_capture_index - capture_index,
capture_index);
}
builder->AddAtom(body);
// For compatability with JSC and ES3, we allow quantifiers after
// lookaheads, and break in all cases.
break;
}
case '|': {
Advance();
builder->NewAlternative();
continue;
}
case '*':
case '+':
case '?':
return ReportError(CStrVector("Nothing to repeat"));
case '^': {
Advance();
if (multiline_) {
builder->AddAssertion(
new(zone()) RegExpAssertion(RegExpAssertion::START_OF_LINE));
} else {
builder->AddAssertion(
new(zone()) RegExpAssertion(RegExpAssertion::START_OF_INPUT));
set_contains_anchor();
}
continue;
}
case '$': {
Advance();
RegExpAssertion::Type type =
multiline_ ? RegExpAssertion::END_OF_LINE :
RegExpAssertion::END_OF_INPUT;
builder->AddAssertion(new(zone()) RegExpAssertion(type));
continue;
}
case '.': {
Advance();
// everything except \x0a, \x0d, \u2028 and \u2029
ZoneList<CharacterRange>* ranges =
new(zone()) ZoneList<CharacterRange>(2);
CharacterRange::AddClassEscape('.', ranges);
RegExpTree* atom = new(zone()) RegExpCharacterClass(ranges, false);
builder->AddAtom(atom);
break;
}
case '(': {
SubexpressionType type = CAPTURE;
Advance();
if (current() == '?') {
switch (Next()) {
case ':':
type = GROUPING;
break;
case '=':
type = POSITIVE_LOOKAHEAD;
break;
case '!':
type = NEGATIVE_LOOKAHEAD;
break;
default:
ReportError(CStrVector("Invalid group") CHECK_FAILED);
break;
}
Advance(2);
} else {
if (captures_ == NULL) {
captures_ = new(zone()) ZoneList<RegExpCapture*>(2);
}
if (captures_started() >= kMaxCaptures) {
ReportError(CStrVector("Too many captures") CHECK_FAILED);
}
captures_->Add(NULL);
}
// Store current state and begin new disjunction parsing.
stored_state = new(zone()) RegExpParserState(stored_state,
type,
captures_started());
builder = stored_state->builder();
continue;
}
case '[': {
RegExpTree* atom = ParseCharacterClass(CHECK_FAILED);
builder->AddAtom(atom);
break;
}
// Atom ::
// \ AtomEscape
case '\\':
switch (Next()) {
case kEndMarker:
return ReportError(CStrVector("\\ at end of pattern"));
case 'b':
Advance(2);
builder->AddAssertion(
new(zone()) RegExpAssertion(RegExpAssertion::BOUNDARY));
continue;
case 'B':
Advance(2);
builder->AddAssertion(
new(zone()) RegExpAssertion(RegExpAssertion::NON_BOUNDARY));
continue;
// AtomEscape ::
// CharacterClassEscape
//
// CharacterClassEscape :: one of
// d D s S w W
case 'd': case 'D': case 's': case 'S': case 'w': case 'W': {
uc32 c = Next();
Advance(2);
ZoneList<CharacterRange>* ranges =
new(zone()) ZoneList<CharacterRange>(2);
CharacterRange::AddClassEscape(c, ranges);
RegExpTree* atom = new(zone()) RegExpCharacterClass(ranges, false);
builder->AddAtom(atom);
break;
}
case '1': case '2': case '3': case '4': case '5': case '6':
case '7': case '8': case '9': {
int index = 0;
if (ParseBackReferenceIndex(&index)) {
RegExpCapture* capture = NULL;
if (captures_ != NULL && index <= captures_->length()) {
capture = captures_->at(index - 1);
}
if (capture == NULL) {
builder->AddEmpty();
break;
}
RegExpTree* atom = new(zone()) RegExpBackReference(capture);
builder->AddAtom(atom);
break;
}
uc32 first_digit = Next();
if (first_digit == '8' || first_digit == '9') {
// Treat as identity escape
builder->AddCharacter(first_digit);
Advance(2);
break;
}
}
// FALLTHROUGH
case '0': {
Advance();
uc32 octal = ParseOctalLiteral();
builder->AddCharacter(octal);
break;
}
// ControlEscape :: one of
// f n r t v
case 'f':
Advance(2);
builder->AddCharacter('\f');
break;
case 'n':
Advance(2);
builder->AddCharacter('\n');
break;
case 'r':
Advance(2);
builder->AddCharacter('\r');
break;
case 't':
Advance(2);
builder->AddCharacter('\t');
break;
case 'v':
Advance(2);
builder->AddCharacter('\v');
break;
case 'c': {
Advance();
uc32 controlLetter = Next();
// Special case if it is an ASCII letter.
// Convert lower case letters to uppercase.
uc32 letter = controlLetter & ~('a' ^ 'A');
if (letter < 'A' || 'Z' < letter) {
// controlLetter is not in range 'A'-'Z' or 'a'-'z'.
// This is outside the specification. We match JSC in
// reading the backslash as a literal character instead
// of as starting an escape.
builder->AddCharacter('\\');
} else {
Advance(2);
builder->AddCharacter(controlLetter & 0x1f);
}
break;
}
case 'x': {
Advance(2);
uc32 value;
if (ParseHexEscape(2, &value)) {
builder->AddCharacter(value);
} else {
builder->AddCharacter('x');
}
break;
}
case 'u': {
Advance(2);
uc32 value;
if (ParseHexEscape(4, &value)) {
builder->AddCharacter(value);
} else {
builder->AddCharacter('u');
}
break;
}
default:
// Identity escape.
builder->AddCharacter(Next());
Advance(2);
break;
}
break;
case '{': {
int dummy;
if (ParseIntervalQuantifier(&dummy, &dummy)) {
ReportError(CStrVector("Nothing to repeat") CHECK_FAILED);
}
// fallthrough
}
default:
builder->AddCharacter(current());
Advance();
break;
} // end switch(current())
int min;
int max;
switch (current()) {
// QuantifierPrefix ::
// *
// +
// ?
// {
case '*':
min = 0;
max = RegExpTree::kInfinity;
Advance();
break;
case '+':
min = 1;
max = RegExpTree::kInfinity;
Advance();
break;
case '?':
min = 0;
max = 1;
Advance();
break;
case '{':
if (ParseIntervalQuantifier(&min, &max)) {
if (max < min) {
ReportError(CStrVector("numbers out of order in {} quantifier.")
CHECK_FAILED);
}
break;
} else {
continue;
}
default:
continue;
}
RegExpQuantifier::Type type = RegExpQuantifier::GREEDY;
if (current() == '?') {
type = RegExpQuantifier::NON_GREEDY;
Advance();
} else if (FLAG_regexp_possessive_quantifier && current() == '+') {
// FLAG_regexp_possessive_quantifier is a debug-only flag.
type = RegExpQuantifier::POSSESSIVE;
Advance();
}
builder->AddQuantifierToAtom(min, max, type);
}
}
#ifdef DEBUG
// Currently only used in an ASSERT.
static bool IsSpecialClassEscape(uc32 c) {
switch (c) {
case 'd': case 'D':
case 's': case 'S':
case 'w': case 'W':
return true;
default:
return false;
}
}
#endif
// In order to know whether an escape is a backreference or not we have to scan
// the entire regexp and find the number of capturing parentheses. However we
// don't want to scan the regexp twice unless it is necessary. This mini-parser
// is called when needed. It can see the difference between capturing and
// noncapturing parentheses and can skip character classes and backslash-escaped
// characters.
void RegExpParser::ScanForCaptures() {
// Start with captures started previous to current position
int capture_count = captures_started();
// Add count of captures after this position.
int n;
while ((n = current()) != kEndMarker) {
Advance();
switch (n) {
case '\\':
Advance();
break;
case '[': {
int c;
while ((c = current()) != kEndMarker) {
Advance();
if (c == '\\') {
Advance();
} else {
if (c == ']') break;
}
}
break;
}
case '(':
if (current() != '?') capture_count++;
break;
}
}
capture_count_ = capture_count;
is_scanned_for_captures_ = true;
}
bool RegExpParser::ParseBackReferenceIndex(int* index_out) {
ASSERT_EQ('\\', current());
ASSERT('1' <= Next() && Next() <= '9');
// Try to parse a decimal literal that is no greater than the total number
// of left capturing parentheses in the input.
int start = position();
int value = Next() - '0';
Advance(2);
while (true) {
uc32 c = current();
if (IsDecimalDigit(c)) {
value = 10 * value + (c - '0');
if (value > kMaxCaptures) {
Reset(start);
return false;
}
Advance();
} else {
break;
}
}
if (value > captures_started()) {
if (!is_scanned_for_captures_) {
int saved_position = position();
ScanForCaptures();
Reset(saved_position);
}
if (value > capture_count_) {
Reset(start);
return false;
}
}
*index_out = value;
return true;
}
// QuantifierPrefix ::
// { DecimalDigits }
// { DecimalDigits , }
// { DecimalDigits , DecimalDigits }
//
// Returns true if parsing succeeds, and set the min_out and max_out
// values. Values are truncated to RegExpTree::kInfinity if they overflow.
bool RegExpParser::ParseIntervalQuantifier(int* min_out, int* max_out) {
ASSERT_EQ(current(), '{');
int start = position();
Advance();
int min = 0;
if (!IsDecimalDigit(current())) {
Reset(start);
return false;
}
while (IsDecimalDigit(current())) {
int next = current() - '0';
if (min > (RegExpTree::kInfinity - next) / 10) {
// Overflow. Skip past remaining decimal digits and return -1.
do {
Advance();
} while (IsDecimalDigit(current()));
min = RegExpTree::kInfinity;
break;
}
min = 10 * min + next;
Advance();
}
int max = 0;
if (current() == '}') {
max = min;
Advance();
} else if (current() == ',') {
Advance();
if (current() == '}') {
max = RegExpTree::kInfinity;
Advance();
} else {
while (IsDecimalDigit(current())) {
int next = current() - '0';
if (max > (RegExpTree::kInfinity - next) / 10) {
do {
Advance();
} while (IsDecimalDigit(current()));
max = RegExpTree::kInfinity;
break;
}
max = 10 * max + next;
Advance();
}
if (current() != '}') {
Reset(start);
return false;
}
Advance();
}
} else {
Reset(start);
return false;
}
*min_out = min;
*max_out = max;
return true;
}
uc32 RegExpParser::ParseOctalLiteral() {
ASSERT('0' <= current() && current() <= '7');
// For compatibility with some other browsers (not all), we parse
// up to three octal digits with a value below 256.
uc32 value = current() - '0';
Advance();
if ('0' <= current() && current() <= '7') {
value = value * 8 + current() - '0';
Advance();
if (value < 32 && '0' <= current() && current() <= '7') {
value = value * 8 + current() - '0';
Advance();
}
}
return value;
}
bool RegExpParser::ParseHexEscape(int length, uc32 *value) {
int start = position();
uc32 val = 0;
bool done = false;
for (int i = 0; !done; i++) {
uc32 c = current();
int d = HexValue(c);
if (d < 0) {
Reset(start);
return false;
}
val = val * 16 + d;
Advance();
if (i == length - 1) {
done = true;
}
}
*value = val;
return true;
}
uc32 RegExpParser::ParseClassCharacterEscape() {
ASSERT(current() == '\\');
ASSERT(has_next() && !IsSpecialClassEscape(Next()));
Advance();
switch (current()) {
case 'b':
Advance();
return '\b';
// ControlEscape :: one of
// f n r t v
case 'f':
Advance();
return '\f';
case 'n':
Advance();
return '\n';
case 'r':
Advance();
return '\r';
case 't':
Advance();
return '\t';
case 'v':
Advance();
return '\v';
case 'c': {
uc32 controlLetter = Next();
uc32 letter = controlLetter & ~('A' ^ 'a');
// For compatibility with JSC, inside a character class
// we also accept digits and underscore as control characters.
if ((controlLetter >= '0' && controlLetter <= '9') ||
controlLetter == '_' ||
(letter >= 'A' && letter <= 'Z')) {
Advance(2);
// Control letters mapped to ASCII control characters in the range
// 0x00-0x1f.
return controlLetter & 0x1f;
}
// We match JSC in reading the backslash as a literal
// character instead of as starting an escape.
return '\\';
}
case '0': case '1': case '2': case '3': case '4': case '5':
case '6': case '7':
// For compatibility, we interpret a decimal escape that isn't
// a back reference (and therefore either \0 or not valid according
// to the specification) as a 1..3 digit octal character code.
return ParseOctalLiteral();
case 'x': {
Advance();
uc32 value;
if (ParseHexEscape(2, &value)) {
return value;
}
// If \x is not followed by a two-digit hexadecimal, treat it
// as an identity escape.
return 'x';
}
case 'u': {
Advance();
uc32 value;
if (ParseHexEscape(4, &value)) {
return value;
}
// If \u is not followed by a four-digit hexadecimal, treat it
// as an identity escape.
return 'u';
}
default: {
// Extended identity escape. We accept any character that hasn't
// been matched by a more specific case, not just the subset required
// by the ECMAScript specification.
uc32 result = current();
Advance();
return result;
}
}
return 0;
}
CharacterRange RegExpParser::ParseClassAtom(uc16* char_class) {
ASSERT_EQ(0, *char_class);
uc32 first = current();
if (first == '\\') {
switch (Next()) {
case 'w': case 'W': case 'd': case 'D': case 's': case 'S': {
*char_class = Next();
Advance(2);
return CharacterRange::Singleton(0); // Return dummy value.
}
case kEndMarker:
return ReportError(CStrVector("\\ at end of pattern"));
default:
uc32 c = ParseClassCharacterEscape(CHECK_FAILED);
return CharacterRange::Singleton(c);
}
} else {
Advance();
return CharacterRange::Singleton(first);
}
}
static const uc16 kNoCharClass = 0;
// Adds range or pre-defined character class to character ranges.
// If char_class is not kInvalidClass, it's interpreted as a class
// escape (i.e., 's' means whitespace, from '\s').
static inline void AddRangeOrEscape(ZoneList<CharacterRange>* ranges,
uc16 char_class,
CharacterRange range) {
if (char_class != kNoCharClass) {
CharacterRange::AddClassEscape(char_class, ranges);
} else {
ranges->Add(range);
}
}
RegExpTree* RegExpParser::ParseCharacterClass() {
static const char* kUnterminated = "Unterminated character class";
static const char* kRangeOutOfOrder = "Range out of order in character class";
ASSERT_EQ(current(), '[');
Advance();
bool is_negated = false;
if (current() == '^') {
is_negated = true;
Advance();
}
ZoneList<CharacterRange>* ranges = new(zone()) ZoneList<CharacterRange>(2);
while (has_more() && current() != ']') {
uc16 char_class = kNoCharClass;
CharacterRange first = ParseClassAtom(&char_class CHECK_FAILED);
if (current() == '-') {
Advance();
if (current() == kEndMarker) {
// If we reach the end we break out of the loop and let the
// following code report an error.
break;
} else if (current() == ']') {
AddRangeOrEscape(ranges, char_class, first);
ranges->Add(CharacterRange::Singleton('-'));
break;
}
uc16 char_class_2 = kNoCharClass;
CharacterRange next = ParseClassAtom(&char_class_2 CHECK_FAILED);
if (char_class != kNoCharClass || char_class_2 != kNoCharClass) {
// Either end is an escaped character class. Treat the '-' verbatim.
AddRangeOrEscape(ranges, char_class, first);
ranges->Add(CharacterRange::Singleton('-'));
AddRangeOrEscape(ranges, char_class_2, next);
continue;
}
if (first.from() > next.to()) {
return ReportError(CStrVector(kRangeOutOfOrder) CHECK_FAILED);
}
ranges->Add(CharacterRange::Range(first.from(), next.to()));
} else {
AddRangeOrEscape(ranges, char_class, first);
}
}
if (!has_more()) {
return ReportError(CStrVector(kUnterminated) CHECK_FAILED);
}
Advance();
if (ranges->length() == 0) {
ranges->Add(CharacterRange::Everything());
is_negated = !is_negated;
}
return new(zone()) RegExpCharacterClass(ranges, is_negated);
}
// ----------------------------------------------------------------------------
// The Parser interface.
ParserMessage::~ParserMessage() {
for (int i = 0; i < args().length(); i++)
DeleteArray(args()[i]);
DeleteArray(args().start());
}
ScriptDataImpl::~ScriptDataImpl() {
if (owns_store_) store_.Dispose();
}
int ScriptDataImpl::Length() {
return store_.length() * sizeof(unsigned);
}
const char* ScriptDataImpl::Data() {
return reinterpret_cast<const char*>(store_.start());
}
bool ScriptDataImpl::HasError() {
return has_error();
}
void ScriptDataImpl::Initialize() {
// Prepares state for use.
if (store_.length() >= PreparseDataConstants::kHeaderSize) {
function_index_ = PreparseDataConstants::kHeaderSize;
int symbol_data_offset = PreparseDataConstants::kHeaderSize
+ store_[PreparseDataConstants::kFunctionsSizeOffset];
if (store_.length() > symbol_data_offset) {
symbol_data_ = reinterpret_cast<byte*>(&store_[symbol_data_offset]);
} else {
// Partial preparse causes no symbol information.
symbol_data_ = reinterpret_cast<byte*>(&store_[0] + store_.length());
}
symbol_data_end_ = reinterpret_cast<byte*>(&store_[0] + store_.length());
}
}
int ScriptDataImpl::ReadNumber(byte** source) {
// Reads a number from symbol_data_ in base 128. The most significant
// bit marks that there are more digits.
// If the first byte is 0x80 (kNumberTerminator), it would normally
// represent a leading zero. Since that is useless, and therefore won't
// appear as the first digit of any actual value, it is used to
// mark the end of the input stream.
byte* data = *source;
if (data >= symbol_data_end_) return -1;
byte input = *data;
if (input == PreparseDataConstants::kNumberTerminator) {
// End of stream marker.
return -1;
}
int result = input & 0x7f;
data++;
while ((input & 0x80u) != 0) {
if (data >= symbol_data_end_) return -1;
input = *data;
result = (result << 7) | (input & 0x7f);
data++;
}
*source = data;
return result;
}
// Create a Scanner for the preparser to use as input, and preparse the source.
static ScriptDataImpl* DoPreParse(UC16CharacterStream* source,
int flags,
ParserRecorder* recorder) {
Isolate* isolate = Isolate::Current();
HistogramTimerScope timer(isolate->counters()->pre_parse());
Scanner scanner(isolate->unicode_cache());
scanner.SetHarmonyScoping(FLAG_harmony_scoping);
scanner.Initialize(source);
intptr_t stack_limit = isolate->stack_guard()->real_climit();
preparser::PreParser::PreParseResult result =
preparser::PreParser::PreParseProgram(&scanner,
recorder,
flags,
stack_limit);
if (result == preparser::PreParser::kPreParseStackOverflow) {
isolate->StackOverflow();
return NULL;
}
// Extract the accumulated data from the recorder as a single
// contiguous vector that we are responsible for disposing.
Vector<unsigned> store = recorder->ExtractData();
return new ScriptDataImpl(store);
}
// Preparse, but only collect data that is immediately useful,
// even if the preparser data is only used once.
ScriptDataImpl* ParserApi::PartialPreParse(Handle<String> source,
v8::Extension* extension,
int flags) {
bool allow_lazy = FLAG_lazy && (extension == NULL);
if (!allow_lazy) {
// Partial preparsing is only about lazily compiled functions.
// If we don't allow lazy compilation, the log data will be empty.
return NULL;
}
flags |= kAllowLazy;
PartialParserRecorder recorder;
int source_length = source->length();
if (source->IsExternalTwoByteString()) {
ExternalTwoByteStringUC16CharacterStream stream(
Handle<ExternalTwoByteString>::cast(source), 0, source_length);
return DoPreParse(&stream, flags, &recorder);
} else {
GenericStringUC16CharacterStream stream(source, 0, source_length);
return DoPreParse(&stream, flags, &recorder);
}
}
ScriptDataImpl* ParserApi::PreParse(UC16CharacterStream* source,
v8::Extension* extension,
int flags) {
Handle<Script> no_script;
if (FLAG_lazy && (extension == NULL)) {
flags |= kAllowLazy;
}
CompleteParserRecorder recorder;
return DoPreParse(source, flags, &recorder);
}
bool RegExpParser::ParseRegExp(FlatStringReader* input,
bool multiline,
RegExpCompileData* result) {
ASSERT(result != NULL);
RegExpParser parser(input, &result->error, multiline);
RegExpTree* tree = parser.ParsePattern();
if (parser.failed()) {
ASSERT(tree == NULL);
ASSERT(!result->error.is_null());
} else {
ASSERT(tree != NULL);
ASSERT(result->error.is_null());
result->tree = tree;
int capture_count = parser.captures_started();
result->simple = tree->IsAtom() && parser.simple() && capture_count == 0;
result->contains_anchor = parser.contains_anchor();
result->capture_count = capture_count;
}
return !parser.failed();
}
bool ParserApi::Parse(CompilationInfo* info, int parsing_flags) {
ASSERT(info->function() == NULL);
FunctionLiteral* result = NULL;
Handle<Script> script = info->script();
ASSERT((parsing_flags & kLanguageModeMask) == CLASSIC_MODE);
if (!info->is_native() && FLAG_harmony_scoping) {
// Harmony scoping is requested.
parsing_flags |= EXTENDED_MODE;
}
if (FLAG_allow_natives_syntax || info->is_native()) {
// We requre %identifier(..) syntax.
parsing_flags |= kAllowNativesSyntax;
}
if (info->is_lazy()) {
ASSERT(!info->is_eval());
Parser parser(script, parsing_flags, NULL, NULL);
result = parser.ParseLazy(info);
} else {
ScriptDataImpl* pre_data = info->pre_parse_data();
Parser parser(script, parsing_flags, info->extension(), pre_data);
if (pre_data != NULL && pre_data->has_error()) {
Scanner::Location loc = pre_data->MessageLocation();
const char* message = pre_data->BuildMessage();
Vector<const char*> args = pre_data->BuildArgs();
parser.ReportMessageAt(loc, message, args);
DeleteArray(message);
for (int i = 0; i < args.length(); i++) {
DeleteArray(args[i]);
}
DeleteArray(args.start());
ASSERT(info->isolate()->has_pending_exception());
} else {
result = parser.ParseProgram(info);
}
}
info->SetFunction(result);
return (result != NULL);
}
} } // namespace v8::internal
| [
"[email protected]"
] | [
[
[
1,
5663
]
]
] |
0772014b9a22c60b2c7bd4a27cca0d5cdddcf6bf | 2bf60292f4a81cc99284103e2c6052f35e313081 | /kitty.cpp | 13f3fd1af62f00dd6d9a2aa182765bca3382eaaa | [] | no_license | alessandrostone/kitty-vst | 9f6affd00d70051296986bf6d1db274df90f6c91 | 9ff955558a15aadf23dadfb553fdf1cbeb770eef | refs/heads/master | 2016-09-06T02:55:19.454457 | 2009-02-03T21:50:20 | 2009-02-03T21:50:20 | 39,379,847 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,685 | cpp | #include <juce.h>
#include "kitty.h"
#include "kittyEditor.h"
AudioProcessor* JUCE_CALLTYPE createPluginFilter()
{
return new kitty();
}
kitty::kitty()
{
bitDepth = 32;
sampleRate = 1.0;
}
kitty::~kitty()
{
}
const String kitty::getName() const
{
return "kitty decimator";
}
int kitty::getNumParameters()
{
return (2);
}
float kitty::getParameter (int index)
{
if (index == kBitDepth)
{
return ((float)bitDepth/32);
}
if (index == kSampleRate)
{
return (sampleRate);
}
return (0.0);
}
void kitty::setParameter (int index, float newValue)
{
if (index == kBitDepth)
{
if (bitDepth != roundFloatToInt(newValue))
{
bitDepth = (int)(newValue * 32);
sendChangeMessage (this);
}
}
if (index == kSampleRate)
{
if (sampleRate != newValue)
{
sampleRate = newValue;
sendChangeMessage (this);
}
}
}
const String kitty::getParameterName (int index)
{
if (index == kBitDepth)
{
return T("Bit Depth");
}
if (index == kSampleRate)
{
return T("Sample Rate");
}
return String::empty;
}
const String kitty::getParameterText (int index)
{
if (index == kBitDepth)
{
return String::formatted (T("bits:%d"), bitDepth);
}
if (index == kSampleRate)
{
return String::formatted (T("sr:%.2f"), sampleRate);
}
return String::empty;
}
const String kitty::getInputChannelName (const int channelIndex) const
{
return String (channelIndex + 1);
}
const String kitty::getOutputChannelName (const int channelIndex) const
{
return String (channelIndex + 1);
}
bool kitty::isInputChannelStereoPair (int index) const
{
return false;
}
bool kitty::isOutputChannelStereoPair (int index) const
{
return false;
}
bool kitty::acceptsMidi() const
{
return false;
}
bool kitty::producesMidi() const
{
return false;
}
void kitty::prepareToPlay (double sampleRate, int samplesPerBlock)
{
}
void kitty::releaseResources()
{
}
void kitty::processBlock (AudioSampleBuffer& buffer,
MidiBuffer& midiMessages)
{
y=cnt=0;
m=1<<(bitDepth-1);
for (int channel = 0; channel < getNumInputChannels(); ++channel)
{
float *p = buffer.getSampleData (channel);
int size = buffer.getNumSamples();
for (int x=0; x<size; x++)
{
*(p+x) = decimate (*(p+x));
}
}
for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
{
buffer.clear (i, 0, buffer.getNumSamples());
}
}
float kitty::decimate(float i)
{
cnt += sampleRate;
if (cnt >= 1)
{
cnt -= 1;
y = (long int)(i*m)/(float)m;
}
return y;
}
AudioProcessorEditor* kitty::createEditor()
{
return new kittyEditor (this);
}
void kitty::getStateInformation (MemoryBlock& destData)
{
XmlElement xmlState (T("kittySettings"));
xmlState.setAttribute (T("bitDepth"), bitDepth);
xmlState.setAttribute (T("sampleRate"), sampleRate);
copyXmlToBinary (xmlState, destData);
}
void kitty::setStateInformation (const void* data, int sizeInBytes)
{
XmlElement* const xmlState = getXmlFromBinary (data, sizeInBytes);
if (xmlState != 0)
{
if (xmlState->hasTagName (T("kittySettings")))
{
bitDepth = xmlState->getIntAttribute (T("bitDepth"), bitDepth);
sampleRate = (float)xmlState->getDoubleAttribute (T("sampleRate"), sampleRate);
sendChangeMessage (this);
}
delete xmlState;
}
}
void kitty::setBitDepth(int d)
{
bitDepth = d;
}
void kitty::setSampleRate (float r)
{
sampleRate = r;
}
| [
"kubiak.roman@a6f206e7-e34c-0410-924b-53c493b60f4e"
] | [
[
[
1,
207
]
]
] |
7a0dc19b6e9f3b75823449cc71baf9143b8846ce | 14bc620a0365e83444dad45611381c7f6bcd052b | /ITUEngine/Events/Input/KeyPressedEvent.hpp | 8c2796f22493f820aef9e09dbc9e98c9db93a0a8 | [] | no_license | jumoel/itu-gameengine | a5750bfdf391ae64407217bfc1df8b2a3db551c7 | 062dd47bc1be0f39a0add8615e81361bcaa2bd4c | refs/heads/master | 2020-05-03T20:39:31.307460 | 2011-12-19T10:54:10 | 2011-12-19T10:54:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 702 | hpp | #ifndef ITUENGINE_KEYPRESSEDEVENT_H
#define ITUENGINE_KEYPRESSEDEVENT_H
#include <SDL_events.h>
#include <Events/EventObject.hpp>
#include <Macros/EventMacros.hpp>
#include <iostream>
class KeyPressedEvent :
public EventObject
{
public:
KeyPressedEvent(SDL_KeyboardEvent *input, short eventtype);
~KeyPressedEvent(void);
SDL_KeyboardEvent* GetInput();
void TestPrint();
private:
SDL_KeyboardEvent *input;
};
class IKeyboardEvent
{
DECLARE_EVENT_INTERFACE(IKeyboardEvent);
public:
DEFINE_1_ARG_EVENT(IKeyboardEvent, KeyDown, KeyPressedEvent*);
DEFINE_1_ARG_EVENT(IKeyboardEvent, KeyUp, KeyPressedEvent*);
};
IMPLEMENT_EVENT_INTERFACE(IKeyboardEvent);
#endif | [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
3
],
[
8,
16
],
[
18,
31
]
],
[
[
4,
6
]
],
[
[
7,
7
],
[
17,
17
],
[
32,
32
]
]
] |
5ca475e8376de029b7ccc0dc991881c9e800ac4d | 3295945a48440441f8a552ba8cfccc18004beb12 | /FixedTibiaDLL/Socket.h | f3b28d10a926b5832ebe616e321a5ad9de09d0e0 | [] | no_license | gareox/tugbot | b96717c791c712200ed09ee84f7ff571a0d4467d | 18a7176ddb5e6ec64263c17fa14d31839f48b5e3 | refs/heads/master | 2021-01-10T11:11:55.585345 | 2011-09-03T22:12:32 | 2011-09-03T22:12:32 | 47,921,522 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 2,213 | h | /*
Socket.h
Copyright (C) 2002-2004 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger [email protected]
*/
#pragma once
#ifndef SOCKET_H
#define SOCKET_H
#include <WinSock2.h>
#include <string>
enum TypeSocket {BlockingSocket, NonBlockingSocket};
class Socket {
public:
virtual ~Socket();
Socket(const Socket&);
Socket& operator=(Socket&);
BYTE* Socket::ReceiveBytes(int &len);
void Close();
void Socket::SendBytes(BYTE* s, int len);
protected:
friend class SocketServer;
friend class SocketSelect;
Socket(SOCKET s);
Socket();
SOCKET s_;
int* refCounter_;
private:
static void Start();
static void End();
static int nofSockets_;
};
class SocketClient : public Socket {
public:
SocketClient(const std::string& host, int port);
};
class SocketServer : public Socket {
public:
SocketServer(int port, int connections, TypeSocket type=BlockingSocket);
Socket* Accept();
};
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/wsapiref_2tiq.asp
class SocketSelect {
public:
SocketSelect(Socket const * const s1, Socket const * const s2=NULL, TypeSocket type=BlockingSocket);
bool Readable(Socket const * const s);
private:
fd_set fds_;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
90
]
]
] |
d3dce052ff5d3dd8060d1da46a03616f30e792d6 | 47f2ee8c2ec135b02b960387a0cb42126e5028ec | /PlasmaGL/src/plglRenderer.cpp | 05fadd0fbcfd22a5302ff94ba04b27b084c71455 | [] | no_license | nsundin/PlasmaViewer | 010beca29ac98fdea73b9741973403cfa764d301 | b482c0481b28d4506be72e5f8da4aa23b98d5489 | refs/heads/master | 2020-06-04T05:25:54.050496 | 2010-03-07T08:34:37 | 2010-03-07T08:34:37 | 12,849,019 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,606 | cpp | #include "plglRenderer.h"
#ifdef WIN32
#include <GL/wglext.h>
#else
#include <GL/glxext.h>
#endif
#define GBRA2RGBA(val) \
((val & 0x0000FFFF) << 8 | (val & 0x00FF0000) >> 16 | (val & 0xFF000000))
PFNGLCOMPRESSEDTEXIMAGE2DARBPROC glCompressedTexImage2DARB = NULL;
plglRenderer::plglRenderer(plResManager* rm){
this->rm = rm;
icanhaslightz = false;
#ifdef WIN32
glCompressedTexImage2DARB = (PFNGLCOMPRESSEDTEXIMAGE2DARBPROC)wglGetProcAddress("glCompressedTexImage2DARB");
#else
glCompressedTexImage2DARB = (PFNGLCOMPRESSEDTEXIMAGE2DARBPROC)glXGetProcAddress((const GLubyte*)"glCompressedTexImage2DARB");
#endif
}
void plglRenderer::SetUpRenderer() {
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glViewport(0,0,(GLsizei)800,(GLsizei)600);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f, (double)800 / (double)600, 1.0f, 1000000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void plglRenderer::Render(plglCamera2 *camera) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glPushMatrix();
RenderAll();
glPopMatrix();
SDL_GL_SwapBuffers();
}
void plglRenderer::RenderAll() {
for (size_t si=0; si < spankeys.size(); ++si) {
plDrawableSpans* dspans = plDrawableSpans::Convert(spankeys[si]->getObj());
for (size_t span_i=0; span_i < dspans->getNumSpans(); span_i++) {
RenderSpan((plIcicle*)dspans->getSpan(span_i),dspans);
}
}
}
void plglRenderer::SetUpAll() {
std::vector<plLocation> locs = rm->getLocations();
for (size_t i=0; i < locs.size(); ++i) {
std::vector<plKey> mms = rm->getKeys(locs[i], kMipmap);
for (size_t i2=0; i2 < mms.size(); ++i2) {
RegisterTexture(mms[i2]);
}
}
for (size_t si=0; si < spankeys.size(); ++si) {
plDrawableSpans* dspans = plDrawableSpans::Convert(spankeys[si]->getObj());
for (size_t span_i=0; span_i < dspans->getNumSpans(); span_i++) {
FixAllVBuffers(dspans);
SetUpSpan((plIcicle*)dspans->getSpan(span_i),dspans);
}
}
}
void plglRenderer::SetUpSpan(plIcicle* span, plDrawableSpans* dspans) {
plglRenderer::spaninfo newspaninfo;
plGBufferGroup* buff = dspans->getBuffer(span->getGroupIdx());
//vertex stuff
size_t vert_idx = span->getVBufferIdx();
size_t vert_start = span->getVStartIdx();
size_t vert_count = span->getVLength();
unsigned char* cp = (unsigned char*)buff->getMutableVertBuffer(vert_idx) + (buff->getStride() * vert_start);
if (vert_count == (size_t)-1)
vert_count = (buff->getVertBufferSize(vert_idx) / buff->getStride()) - vert_start;
//index stuff
size_t ind_idx = span->getIBufferIdx();
size_t ind_start = span->getIStartIdx();
size_t ind_offset = span->getVStartIdx();
size_t ind_count = span->getILength();
if (ind_count == (size_t)-1)
ind_count = buff->getIdxBufferCount(span->getIBufferIdx()) - ind_start;
newspaninfo.ind_idx = ind_idx;
newspaninfo.ind_start = ind_start;
newspaninfo.ind_offset = ind_offset;
newspaninfo.ind_count = ind_count;
newspaninfo.vert_count = vert_count;
unsigned int numUVs = buff->getFormat() & plGBufferGroup::kUVCountMask;
unsigned int normalsoffset = sizeof(float)*3;
int weightCount = (buff->getFormat() & plGBufferGroup::kSkinWeightMask) >> 4;
if (weightCount > 0) {
normalsoffset += sizeof(float)*weightCount;
if (buff->getFormat() & plGBufferGroup::kSkinIndices) {
normalsoffset += sizeof(int);
}
}
unsigned int coloroffset = normalsoffset+(sizeof(float)*3);
newspaninfo.buff_stride = buff->getStride();
newspaninfo.cpstart = cp;
newspaninfo.coloroffset = coloroffset;
newspaninfo.normalsoffset = normalsoffset;
newspaninfo.uvoffset = buff->getStride()-((buff->getFormat() & plGBufferGroup::kUVCountMask)*sizeof(float)*3); //GIGANTIC HACK
//set up lights
newspaninfo.lights = span->getPermaLights();
//add the collected info to our list
spaninfos[span] = newspaninfo;
}
void plglRenderer::FixAllVBuffers(plDrawableSpans* dspans) {
for (size_t i=0; i < dspans->getNumBufferGroups(); i++) {
plGBufferGroup* buff = dspans->getBuffer(i);
for (size_t jb=0; jb < buff->getNumVertBuffers(); jb++) {
unsigned int count = buff->getVertBufferSize(jb)/buff->getStride();
unsigned char* cp = buff->getMutableVertBuffer(jb);
for (size_t iv=0; iv<count; iv++) {
cp += (sizeof(float)*3);//pos
int weightCount = (buff->getFormat() & plGBufferGroup::kSkinWeightMask) >> 4;
if (weightCount > 0) {
for (int j=0; j<weightCount; j++) {
cp += sizeof(float);
}
if (buff->getFormat() & plGBufferGroup::kSkinIndices) {
cp += sizeof(int);
}
}
cp += (sizeof(float)*3); //normal
//fix the colors GBRA > RGBA
*(unsigned int*)cp = GBRA2RGBA(*(unsigned int*)cp);//color
cp += sizeof(unsigned int);
cp += sizeof(unsigned int);
for (size_t j=0; j<(size_t)(buff->getFormat() & plGBufferGroup::kUVCountMask); j++) {
cp += (sizeof(float)*3);//UV
}
}
}
}
}
void plglRenderer::SetLayerParams(plLayerInterface* layer, bool isWaveset) {
if (layer->getTexture()) {
if (layer->getTexture().isLoaded()) {
unsigned int texID = textures[layer->getTexture()];
if (texID) {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texID);
}
else {
//printf("Bad texture: %s\n", layer->getTexture()->getName().cstr());
glDisable(GL_TEXTURE_2D);
}
}
else {
// printf("Texture not loaded: %s\n", layer->getTexture()->getName().cstr());
glDisable(GL_TEXTURE_2D);
}
}
else {
glDisable(GL_TEXTURE_2D);
}
bool is2Sided = (layer->getState().fMiscFlags & hsGMatState::kMiscTwoSided) != 0;
if (is2Sided || isWaveset) {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glDisable(GL_CULL_FACE);
}
else {
glPolygonMode(GL_FRONT, GL_FILL);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
}
float amb[4] = { layer->getAmbient().r, layer->getAmbient().g,
layer->getAmbient().b, layer->getAmbient().a };
float dif[4] = { layer->getRuntime().r, layer->getRuntime().g,
layer->getRuntime().b, layer->getRuntime().a };
float spec[4] = { layer->getSpecular().r, layer->getSpecular().g,
layer->getSpecular().b, layer->getSpecular().a };
glMaterialfv(is2Sided ? GL_FRONT : GL_FRONT_AND_BACK, GL_AMBIENT, amb);
glMaterialfv(is2Sided ? GL_FRONT : GL_FRONT_AND_BACK, GL_DIFFUSE, dif);
glMaterialfv(is2Sided ? GL_FRONT : GL_FRONT_AND_BACK, GL_SPECULAR, spec);
if (layer->getState().fShadeFlags & hsGMatState::kShadeEmissive)
glMaterialfv(is2Sided ? GL_FRONT : GL_FRONT_AND_BACK, GL_EMISSION, amb);
// glPixelTransferf(GL_ALPHA_SCALE, layer->getOpacity());
glDisable(GL_BLEND);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE);
if ((layer->getState().fBlendFlags & hsGMatState::kBlendAlpha) != 0) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
}
if ((layer->getState().fBlendFlags & hsGMatState::kBlendAdd) != 0) {
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
}
if ((layer->getState().fBlendFlags & hsGMatState::kBlendNoTexColor) != 0) {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE);
}
}
void plglRenderer::RenderSpan(plIcicle* span, plDrawableSpans* dspans) {
spaninfo si = spaninfos[span];
plGBufferGroup* buff = dspans->getBuffer(span->getGroupIdx());
//Set up and enable the lights
size_t num_lights = si.lights.getSize();
if (this->icanhaslightz) {
glEnable(GL_LIGHTING);
if (num_lights > 8) num_lights = 8; //make sure we don't have too many lights
for (size_t i=0; i < num_lights; i++) {
if (si.lights[i]->getType() == kOmniLightInfo) {
plOmniLightInfo* l_info = plOmniLightInfo::Convert(si.lights[i]->getObj());
GLfloat light_position[] = { l_info->getWorldToLight()(3,0), l_info->getWorldToLight()(3,0), l_info->getWorldToLight()(3,0), 1.0 };
GLfloat ambientColor[] = {l_info->getAmbient().r,l_info->getAmbient().g,l_info->getAmbient().b};
GLfloat diffuseColor[] = {l_info->getDiffuse().r,l_info->getDiffuse().g,l_info->getDiffuse().b};
GLfloat specularColor[] = {l_info->getSpecular().r,l_info->getSpecular().g,l_info->getSpecular().b};
glLightfv(GL_LIGHT0+i, GL_AMBIENT, ambientColor);
glLightfv(GL_LIGHT0+i, GL_DIFFUSE, diffuseColor);
glLightfv(GL_LIGHT0+i, GL_SPECULAR, specularColor);
glLightf(GL_LIGHT0+i, GL_CONSTANT_ATTENUATION, l_info->getAttenConst());
glLightf(GL_LIGHT0+i, GL_LINEAR_ATTENUATION, l_info->getAttenLinear());
glLightf(GL_LIGHT0+i, GL_QUADRATIC_ATTENUATION, l_info->getAttenQuadratic());
glLightfv(GL_LIGHT0+i, GL_POSITION, light_position);
glEnable(GL_LIGHT0+i);
}
}
}
//Render the span
glPushMatrix();
glMultMatrixf(span->getWorldToLocal().glMatrix());
hsGMaterial* material = hsGMaterial::Convert(dspans->getMaterial(span->getMaterialIdx())->getObj());
for (size_t i=0; i < material->getNumLayers(); i++) {
plLayerInterface* layer = plLayerInterface::Convert(material->getLayer(i)->getObj());
SetLayerParams(layer, false);
glMatrixMode(GL_TEXTURE);
glPushMatrix();
glMultMatrixf(layer->getTransform().glMatrix());
glMatrixMode(GL_MODELVIEW);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glNormalPointer(GL_FLOAT, si.buff_stride, (GLvoid*)(si.cpstart+si.normalsoffset));
glColorPointer(4, GL_UNSIGNED_BYTE, si.buff_stride, (GLvoid*)(si.cpstart+si.coloroffset));
glTexCoordPointer(3, GL_FLOAT,si.buff_stride, (GLvoid*)(si.cpstart+si.uvoffset));//+(sizeof(float)*(layer->getUVWSrc() & plLayerInterface::kUVWIdxMask)))); //crazy insanity
glVertexPointer(3, GL_FLOAT, si.buff_stride, (GLvoid*)si.cpstart);
glBegin(GL_TRIANGLES);
for (size_t j=0; j < si.ind_count; j++) {
unsigned short ind = buff->getIdxBufferStorage(si.ind_idx)[j + si.ind_start] - si.ind_offset;
glArrayElement(ind);
}
glEnd();
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glMatrixMode(GL_TEXTURE);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
}
glPopMatrix();
if (this->icanhaslightz) {
//disable lights
for (size_t i=0; i< num_lights; i++) {
glDisable(GL_LIGHT0+i);
}
glDisable(GL_LIGHTING);
}
}
void plglRenderer::SetSpanKeys() {
std::vector<plLocation> locs = rm->getLocations();
// printf("Adding %i location(s)\n", locs.size());
for (size_t i=0; i < locs.size(); ++i) {
std::vector<plKey> sk = rm->getKeys(locs[i], kDrawableSpans);
for (size_t i2=0; i2 < sk.size(); ++i2) {
spankeys.push_back(sk[i2]);
}
}
}
int loadMipmapTexture(plKey mipmapkey, unsigned int texname) {
#ifdef WIN32
glCompressedTexImage2DARB = (PFNGLCOMPRESSEDTEXIMAGE2DARBPROC)wglGetProcAddress("glCompressedTexImage2DARB");
#else
glCompressedTexImage2DARB = (PFNGLCOMPRESSEDTEXIMAGE2DARBPROC)glXGetProcAddress((const GLubyte*)"glCompressedTexImage2DARB");
#endif
plMipmap* mipmapimage = plMipmap::Convert(mipmapkey->getObj());
if(mipmapimage->getImageData()==0){
printf("No image data for: %s\n", mipmapkey->getName().cstr());
}
if (mipmapimage->getCompressionType() == plBitmap::kDirectXCompression){
unsigned int DXCompressionType = 0;
if (mipmapimage->getDXCompression() == plBitmap::kDXT1)
DXCompressionType = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
else if (mipmapimage->getDXCompression() == plBitmap::kDXT3)
DXCompressionType = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
else if (mipmapimage->getDXCompression() == plBitmap::kDXT5)
DXCompressionType = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
else return 0;
glBindTexture(GL_TEXTURE_2D, texname); //that thar is the ID
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
for(unsigned int il = 0; il < mipmapimage->getNumLevels(); ++il) {
glCompressedTexImage2DARB(GL_TEXTURE_2D, il, DXCompressionType, mipmapimage->getLevelWidth(il), mipmapimage->getLevelHeight(il), 0, mipmapimage->getLevelSize(il),(const unsigned long *)mipmapimage->getLevelData(il));
}
return 1;
} else {
for (unsigned int il = 0; il < mipmapimage->getNumLevels(); ++il) {
glBindTexture(GL_TEXTURE_2D, texname);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexImage2D(GL_TEXTURE_2D, il, GL_RGBA, mipmapimage->getLevelWidth(il), mipmapimage->getLevelHeight(il), 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, mipmapimage->getLevelData(il));
}
return 1;
}
return 0;
}
void plglRenderer::RegisterTexture(plKey texture) {
if (textures[texture]) { //if it's already there
printf("%s already exists: skipping load.\n",texture->getName().cstr());
return;
}
unsigned int texid;
glGenTextures(1, &texid);
if (!loadMipmapTexture(texture, texid)) {
glDeleteTextures(1,&texid);
printf("Warning: %s failed to load.\n",texture->getName().cstr());
}
else {
//celebrate
textures[texture] = texid;
printf("Loaded %s\n",texture->getName().cstr());
}
}
| [
"lontahv@46d49313-71c2-4fea-ab98-6c881a270271",
"Paradox@46d49313-71c2-4fea-ab98-6c881a270271"
] | [
[
[
1,
4
],
[
7,
372
]
],
[
[
5,
6
]
]
] |
544978d1b767e89be0410450fc40a0786ac21b64 | be3d7c318d79cd33d306aba58a1159147cac91fd | /modules/wgd_models/include/wgd/animationset.h | 6abca279d4b0ac5ad61bcc99445b3cf345135afe | [] | no_license | knicos/Cadence | 827149b53bb3e92fe532b0ad4234b7d0de11ca43 | 7e1e1cf1bae664f77afce63407b61c7b2b0a4fff | refs/heads/master | 2020-05-29T13:19:07.595099 | 2011-10-31T13:05:48 | 2011-10-31T13:05:48 | 1,238,039 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,117 | h | #ifndef _ANIMATION_SET_
#define _ANIMATION_SET_
#include <wgd/vector.h>
#include <wgd/quaternion.h>
#include <vector>
namespace wgd {
class AnimationSet {
public:
struct KeyScale {
int frame;
vector3d scale;
};
struct KeyPosition {
int frame;
vector3d position;
};
struct KeyOrientation {
int frame;
quaternion orientation;
};
// constructor - set size (number of bones with animations) //
AnimationSet(int size);
~AnimationSet();
// get values at frames //
vector3d scale(int id, float frame) const;
vector3d position(int id, float frame) const;
quaternion orientation(int id, float frame) const;
// add keyframes //
void keyScale(int id, int frame, const vector3d &scale);
void keyPosition(int id, int frame, const vector3d &position);
void keyOrientation(int id, int frame, const quaternion &orientation);
private:
std::vector<KeyScale*> *m_scale;
std::vector<KeyPosition*> *m_position;
std::vector<KeyOrientation*> *m_orientation;
int m_size;
};
};
#endif
| [
"[email protected]"
] | [
[
[
1,
55
]
]
] |
d52641c33e3cd0e519ea7dddd8e81a67e5a04338 | 18760393ff08e9bdefbef1d5ef054065c59cedbc | /Source/KaroTestGUI/KaroEngine/KaroEngineWrapper.h | 6c31542e8de23fa32615310b620b5344c2f8197f | [] | no_license | robertraaijmakers/koppijn | 530d0b0111c8416ea7a688c3e5627fd421b41068 | 5af4f9c8472570aa2f2a70e170e671c6e338c3c6 | refs/heads/master | 2021-01-17T22:13:45.697435 | 2011-06-23T19:27:59 | 2011-06-23T19:27:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 821 | h | #pragma once
#include "KaroEngine.h"
#include <string>
using namespace System;
namespace KaroEngine {
public ref class KaroEngineWrapper{
private:
KaroEngine *_karoEngine; // native pointer
public:
KaroEngineWrapper(void);
~KaroEngineWrapper(void);
Tile GetByXY(int x, int y);
bool InsertByXY(int x, int y);
bool DoMove(int from,int to,int tile);
GameState GetGameState();
Player GetTurn();
array<int>^ CalculateComputerMove();
String^ GetMessageLog();
int GetEvaluationScore();
array<array<int>^>^ GetPossibleMoves(int x, int y,int tileFromX,int tileFromY);
int KaroEngineWrapper::GetBoardBottom();
int KaroEngineWrapper::GetBoardLeft();
int KaroEngineWrapper::GetBoardRight();
int KaroEngineWrapper::GetBoardTop();
array<int>^ UndoLastMove();
};
} | [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
3
],
[
5,
7
],
[
9,
14
],
[
30,
31
]
],
[
[
4,
4
],
[
8,
8
],
[
15,
19
],
[
22,
22
],
[
24,
28
]
],
[
[
20,
20
]
],
[
[
21,
21
],
[
23,
23
]
],
[
[
29,
29
]
]
] |
6579627c5e3a7c4ab52d1d92deb50e6e1dff23fd | ffe0a7d058b07d8f806d610fc242d1027314da23 | /dev/threads/ThreadConfig.h | b0a99565b362b05f327e5b4e01ca213596b0291d | [] | 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 | 1,158 | h | /* MULTI THREADING MANAGER
*
* Copyright (C) 2008 Cybr@x Cybersp@ce <[email protected]>
*
* 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.
*
* for a copy of the GNU General Public License write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef __THREAD_CONF__
#define __THREAD_CONF__
#include "common.h"
#define CYT_NS CyTHREAD
namespace CYT_NS
{
#define TC_TIMEOUT INFINITE
#define TS_EXIT 0
#define TS_INIT 1
#define TS_START 2
#define TS_ENTRY 3
#define TS_RUN 4
#define TS_EXEC 5
#define DEBUG(what) printf(what)
#define DEBUG2(what) //printf(what)
}
#endif
//DWORD WINAPI
| [
"cybraxvd@dfcbb000-c142-0410-b1aa-f54c88fa44bd"
] | [
[
[
1,
42
]
]
] |
5f4fd33bd6ddb49895ac72fe1a1f53c4f4371d51 | 585293085e12dbd8339c49098c0882f9e001f2c1 | / nupix/NuPix/include/InputInfo.h | 84edebf484348cb012bac285d7677e366dfe20fe | [] | no_license | fmd/nupix | ba4d9fc5fe56e08abe03b2b39302c4d7129dd45c | 49ada30fdbe091df3f1d2b341cce1ea4bcc0a011 | refs/heads/master | 2021-01-02T09:53:47.099303 | 2010-03-17T03:01:53 | 2010-03-17T03:01:53 | 32,323,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 498 | h | #pragma once
class InputInfo
{
public:
enum InputState
{
INPUT_PRESSED,
INPUT_DOWN,
INPUT_RELEASED,
INPUT_UP,
};
InputInfo() :
mX(0),
mY(0),
mZ(0),
mXRel(0),
mYRel(0),
mZRel(0)
{
for (int i=0;i<350;i++)
mKeyState[i] = INPUT_UP;
for (int i=0;i<10;i++)
mMouseState[i] = INPUT_UP;
}
~InputInfo()
{
}
uint16 mX,
mY,
mZ;
int mXRel,
mYRel,
mZRel;
InputState mMouseState[10],
mKeyState[350];
}; | [
"fareeddudhia@c567426a-3e4a-1c2b-9c7e-01d812d4f56b"
] | [
[
[
1,
44
]
]
] |
7706d0e6ccf9d90aa635b24a563dd01541093505 | a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561 | /SlonEngine/src/Graphics/Detail/ParameterTable.cpp | 68a9c16cd9531ace96f9f35c81b1da60e317fe5e | [] | no_license | BackupTheBerlios/slon | e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6 | dc10b00c8499b5b3966492e3d2260fa658fee2f3 | refs/heads/master | 2016-08-05T09:45:23.467442 | 2011-10-28T16:19:31 | 2011-10-28T16:19:31 | 39,895,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | cpp | #include "stdafx.h"
#include "Graphics/Detail/GraphicsManager.h"
namespace slon {
namespace graphics {
namespace detail {
ParameterTable& currentParameterTable()
{
return static_cast<detail::GraphicsManager&>( currentGraphicsManager() ).getParameterTable();
}
} // namespace detail
} // namespace graphics
} // namespace slon
| [
"devnull@localhost"
] | [
[
[
1,
15
]
]
] |
079fba32c6c96f1f10aa748174739c8026a0eaf2 | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/C++/vc源码/计算器/QiuXpEdit.h | f894d9b131a4e903893b8c33852a1138fa1ae999 | [] | no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,104 | h | #if !defined(AFX_QIUXPEDIT_H__AA3BA55D_63D3_4B50_9CB7_5ED770F3C32E__INCLUDED_)
#define AFX_QIUXPEDIT_H__AA3BA55D_63D3_4B50_9CB7_5ED770F3C32E__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// QiuXpEdit.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CQiuXpEdit window
class CQiuXpEdit : public CEdit
{
// Construction
public:
CQiuXpEdit();
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CQiuXpEdit)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CQiuXpEdit();
// Generated message map functions
protected:
//{{AFX_MSG(CQiuXpEdit)
afx_msg void OnPaint();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_QIUXPEDIT_H__AA3BA55D_63D3_4B50_9CB7_5ED770F3C32E__INCLUDED_)
| [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
] | [
[
[
1,
48
]
]
] |
8255152feec902aa0d35d68d8ef6a6f2b90a251e | 753fbd0173d85d6fdd7a6b406c5ae55f4215aa70 | /SFE/SFE_FontMap.cpp | 2fab5d180f3ff05dda4394357aa74e15c97e5760 | [] | no_license | MetaCipher/simplefontengineopengl | 34ebf4297c4dc7d326ff53aa3c73b261dbf8442b | dccde5372a449127da5cad4061dd229bcbb8a2ef | refs/heads/master | 2021-01-22T09:54:53.922836 | 2007-11-10T18:58:42 | 2007-11-10T18:58:42 | 32,318,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,670 | cpp | //==============================================================================
#include "SFE_FontMap.h"
//==============================================================================
DevThinkTank::SFE_FontMap::SFE_FontMap() {
PointSize = 0;
}
//==============================================================================
void DevThinkTank::SFE_FontMap::OnRender(int Char, int X, int Y) {
if(Char <= 0 || Char >= 255) return;
int OffsetX = CharList[Char].OffsetX;
int OffsetY = -CharList[Char].OffsetY;
glBindTexture(GL_TEXTURE_2D, CharList[Char].Texture);
glBegin(GL_QUADS);
glTexCoord2f(0, 1); glVertex3f(X + OffsetX, Y + CharList[Char].Height + OffsetY, 0);
glTexCoord2f(0, 0); glVertex3f(X + OffsetX, Y + OffsetY, 0);
glTexCoord2f(1, 0); glVertex3f(X + CharList[Char].Width + OffsetX, Y + OffsetY, 0);
glTexCoord2f(1, 1); glVertex3f(X + CharList[Char].Width + OffsetX, Y + CharList[Char].Height + OffsetY, 0);
glEnd();
}
//------------------------------------------------------------------------------
void DevThinkTank::SFE_FontMap::OnCleanup() {
for(int i = 0;i < 255;i++) {
glDeleteTextures(1, &CharList[i].Texture);
CharList[i].Texture = 0;
}
}
//==============================================================================
DevThinkTank::SFE_Char* DevThinkTank::SFE_FontMap::GetChar(int Char) {
if(Char <= 0 || Char >= 255) return NULL;
return &CharList[Char];
}
//==============================================================================
| [
"farris.shane@7c90bf9e-413d-0410-a83f-3989eb8f22bf"
] | [
[
[
1,
42
]
]
] |
e946ca9c8a2207d769dbc499cf2d6a3ca79750c2 | 13f30850677b4b805aeddbad39cd9369d7234929 | / astrocytes --username [email protected]/CT_tutorial/GeomFunc.cpp | b7288148a608c459bbe35e7a0fc12a72630337c3 | [] | no_license | hksonngan/astrocytes | 2548c73bbe45ea4db133e465fa8a90d29dc60f64 | e14544d21a077cdbc05356b05148cc408c255e04 | refs/heads/master | 2021-01-10T10:04:14.265392 | 2011-11-09T07:42:06 | 2011-11-09T07:42:06 | 46,898,541 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 10,763 | cpp | #include "GeomFunc.h"
#include "AllDef.h"
#include "vec.h"
#include <math.h>
vec3 last_triangles_cross;
void getnorm (float a[3],float b[3],float c[3],float *n)
{
n[0]=(b[1]-a[1])*(c[2]-a[2])-(b[2]-a[2])*(c[1]-a[1]);
n[1]=(c[0]-a[0])*(b[2]-a[2])-(b[0]-a[0])*(c[2]-a[2]);
n[2]=(b[0]-a[0])*(c[1]-a[1])-(c[0]-a[0])*(b[1]-a[1]);
}
void ToSphereCoord(vec3 center, Lines& lines)
{
for(int i=0;i<lines.size();i++)
for(int j=0;j<2;j++)
{
vec3* vv = lines[i].v+j;
vec3 v = *vv-center;
if(!v.x)v.x=0.00001f;
float l = sqrt(v.x*v.x + v.y*v.y)+0.00001f;
vv->x = atan(v.y/v.x);
if(v.x<0) vv->x += PI*sgn(v.y);
vv->y = atan(v.z/l);
vv->z = 0;
}
}
Triangle::Triangle(const Triangle& tr)
{
v[0]=tr.v[0];
v[1]=tr.v[1];
v[2]=tr.v[2];
norm=tr.norm;
}
//точка t вне треугольника tr?
bool OutsideTriangle3d(vec3 t,Triangle& tr)
{
vec3 t0 = (tr.v[0]+tr.v[1]+tr.v[2])/3.0f , nv=t0+tr.norm,f;
getnorm(&tr.v[0].x,&tr.v[1].x,&nv.x,&f.x);
if((vec3::dot(f,(t-nv)))*(vec3::dot(f,(t0-nv)))<0)return true;
getnorm(&tr.v[0].x,&tr.v[2].x,&nv.x,&f.x);
if((vec3::dot(f,(t-nv)))*(vec3::dot(f,(t0-nv)))<0)return true;
getnorm(&tr.v[1].x,&tr.v[2].x,&nv.x,&f.x);
if((vec3::dot(f,(t-nv)))*(vec3::dot(f,(t0-nv)))<0)return true;
return false;
}
//void AddPoint(vec3);
//пересечение отрезка с плоскостью
bool CrossFlatLine(vec3 a,vec3 b,vec3 d,vec3 n,vec3*x0)
{
float t=vec3::dot((b-a),n);
if(t==0)return 0;
t=(vec3::dot(d-a,n))/t;
if(t<0||t>1)return 0;
*x0=a+(b-a)*t;
last_triangles_cross = *x0;
//AddPoint(*x0);
return 1;
}
bool CrossTriangles(Triangle& t1,Triangle& t2)
{
vec3 x0;
if(CrossFlatLine(t2.v[0],t2.v[1], t1.v[0],t1.norm,&x0))if(!OutsideTriangle3d(x0,t1))return true;
if(CrossFlatLine(t2.v[0],t2.v[2], t1.v[0],t1.norm,&x0))if(!OutsideTriangle3d(x0,t1))return true;
if(CrossFlatLine(t2.v[1],t2.v[2], t1.v[0],t1.norm,&x0))if(!OutsideTriangle3d(x0,t1))return true;
if(CrossFlatLine(t1.v[0],t1.v[1], t2.v[0],t2.norm,&x0))if(!OutsideTriangle3d(x0,t2))return true;
if(CrossFlatLine(t1.v[0],t1.v[2], t2.v[0],t2.norm,&x0))if(!OutsideTriangle3d(x0,t2))return true;
if(CrossFlatLine(t1.v[1],t1.v[2], t2.v[0],t2.norm,&x0))if(!OutsideTriangle3d(x0,t2))return true;
return false;
}
//res_conf[4]:
//0-номер ребра треугольника, на котором лежит 1-ая вершина отрезка
//1-номер этого треугольника
//2-номер ребра треугольника, на котором лежит 2-ая вершина отрезка
//3-номер этого треугольника
bool CrossTriangles(Triangle& t1,Triangle& t2,Line*res,char* res_conf)
{
vec3 x0;
int id=0;
if(CrossFlatLine(t2.v[0],t2.v[1], t1.v[0],t1.norm,&x0))if(!OutsideTriangle3d(x0,t1))
{res->v[id] = x0;res_conf[0]=0;res_conf[1]=1;id++;}
if(CrossFlatLine(t2.v[0],t2.v[2], t1.v[0],t1.norm,&x0))if(!OutsideTriangle3d(x0,t1))
{res->v[id] = x0;res_conf[id*2]=2;res_conf[id*2+1]=1;id++;if(id==2)return true;}
if(CrossFlatLine(t2.v[1],t2.v[2], t1.v[0],t1.norm,&x0))if(!OutsideTriangle3d(x0,t1))
{res->v[id] = x0;res_conf[id*2]=1;res_conf[id*2+1]=1;id++;if(id==2)return true;}
if(CrossFlatLine(t1.v[0],t1.v[1], t2.v[0],t2.norm,&x0))if(!OutsideTriangle3d(x0,t2))
{res->v[id] = x0;res_conf[id*2]=0;res_conf[id*2+1]=0;id++;if(id==2)return true;}
if(CrossFlatLine(t1.v[0],t1.v[2], t2.v[0],t2.norm,&x0))if(!OutsideTriangle3d(x0,t2))
{res->v[id] = x0;res_conf[id*2]=2;res_conf[id*2+1]=0;id++;if(id==2)return true;}
if(CrossFlatLine(t1.v[1],t1.v[2], t2.v[0],t2.norm,&x0))if(!OutsideTriangle3d(x0,t2))
{res->v[id] = x0;res_conf[id*2]=1;res_conf[id*2+1]=0;id++;if(id==2)return true;}
return false;
}
/*
bool CrossTriangles(Triangle& a,Triangle& b)
{
return CrossTriangles(a.v[0],a.v[1],a.v[2],b.v[0],b.v[1],b.v[2],a.norm,b.norm);
}
*/
bool CrossTrianglesSet(Triangles& a,Triangles& b)
{
int i,j,n=a.size(),m=b.size();
for(i=0;i<n;i++)
for(j=0;j<m;j++)
if(CrossTriangles(a[i],b[j]))return true;
return false;
}
void Triangle::CalcNorm()
{
getnorm(&v[0].x,&v[1].x,&v[2].x,&norm.x);
norm.normalize();
}
bool FlatCrossTriangle(Triangle& t1,flat&fl ,Line*res)
{
vec3 x0;
int id=0;
if(CrossFlatLine(t1.v[0],t1.v[1], fl.d,fl.n,&x0))
{res->v[id] = x0;id++;}
if(CrossFlatLine(t1.v[0],t1.v[2], fl.d,fl.n,&x0))
{res->v[id] = x0;id++;if(id==2)return true;}
if(CrossFlatLine(t1.v[1],t1.v[2], fl.d,fl.n,&x0))
{res->v[id] = x0;id++;if(id==2)return true;}
return false;
}
// vx должно быть перпендикулярно vy
void ProectOnFlat(Lines& lines,vec3 d,vec3 vx,vec3 vy,Lines2& res)
{
for(int i=0;i<lines.size();i++)
{
Line2 l2;
for(int j=0;j<2;j++)
{
vec3 tmpv = lines[i].v[j]-d;
l2.v[j].set( vec3::dot(tmpv,vx) , vec3::dot(tmpv,vy) );
}
res.push_back(l2);
}
}
bool fill_gaps_error=0;
void FillCircleSegment(float r,Line2 ll,Lines2&lines,bool inside_circle)
{
Lines2 tmpll;
tmpll.push_back(ll);
int id=0;
vec2 tmpv=ll.v[1]-ll.v[0];
bool bb = (vec2::vect_mult(tmpv,ll.v[0])<0);
if(inside_circle)bb=!bb;
if(bb)
{
vec2 nt = (ll.v[0]+ll.v[1])*(-1);
nt.normalize();
nt*=r;
tmpll.push_back(Line2(nt,ll.v[1]));
tmpll.push_back(Line2(ll.v[0],nt));
id++;
}
while(id<tmpll.size())
{
vec2 a=tmpll[id].v[0];
vec2 b=tmpll[id].v[1];
if(a.lengthSQR(b)<r*r/100)
{
lines.push_back(tmpll[id]);
}else
{
vec2 nt = (a+b);
nt.normalize();
nt*=r;
tmpll.push_back(Line2(a,nt));
tmpll.push_back(Line2(nt,b));
}
id++;
if(id>1000)break;
}
if(id>1000){printf("!");fill_gaps_error=1;}
}
void FillCircleGaps(float r,Lines2& lines, iv2vec* crossed,Lines2&contour,bool inside_circle)
{
v2vec vr;
vec ang;
bvec to_surf;
if(crossed->size()<2)return;
for(int i=0;i<crossed->size();i++)
{
ivec2 cc = (*crossed)[i];
vec2 tmpv2 = lines[cc.x].v[cc.y];
vr.push_back(tmpv2);
ang.push_back(tmpv2.GetAngle());
to_surf.push_back(cc.y);
}
for(int i=0;i<vr.size()-1;i++)
for(int j=i+1;j<vr.size();j++)
if(ang[i]>ang[j])
{
swap(vr[i],vr[j]);
swap(ang[i],ang[j]);
swap(to_surf[i],to_surf[j]);
}
int i=0;//!to_surf[0];
while(i<vr.size())
{
int i1=i;
int i2=(i+1)%vr.size();
if(!inside_circle)swap(i1,i2);
if(to_surf[i1] && !to_surf[i2])
{
//lines.push_back(Line2(vr[i1],vr[i2]));
FillCircleSegment(r,Line2(vr[i1],vr[i2]),contour,inside_circle);
//i++;
}else if(to_surf[i1] || !to_surf[i2]){printf("C");fill_gaps_error=1;}
i++;
}
}
// сечение кругом. в crossed_inside и crossed_outside записываются (если не переданы нулевые указатели) номера (в результирующих массивах lines_inside и lines_outside) пересечённых кругом отрезков
// x-это номер, а y-сторона отрезка.
void CutByCircle(Lines2& lines, float r,Lines2* lines_inside,Lines2* lines_outside,iv2vec*crossed_inside,iv2vec*crossed_outside)
{
for(int i=0;i<lines.size();i++)
{
vec2 v0=lines[i].v[0];
vec2 v1=lines[i].v[1];
vec2 v=v1-v0;
float a = v.x*v.x+v.y*v.y;
float b = 2*(v0.x*v.x+v0.y*v.y);
float c = v0.x*v0.x+v0.y*v0.y-r*r;
float d = 4*a*c-b*b;
if(d>=0)
{
if(lines_outside)lines_outside->push_back(lines[i]);
}else
{
d = sqrt(-d);
float t1 = (-b+d)/(2*a);
float t2 = (-b-d)/(2*a);
bool was_swap=0;
if(t1>t2){swap(t1,t2);was_swap=1;}
if(t1>1 || t2<0)
{if(lines_outside)lines_outside->push_back(lines[i]);}
else
{
if(t1<=0 && t2>=1)
{if(lines_inside)lines_inside->push_back(lines[i]);}
else
{
if(t1>=0)
{
if(lines_outside)
{
if(crossed_outside)crossed_outside->push_back(ivec2(lines_outside->size(),was_swap));
lines_outside->push_back(Line2(v0,v0+v*t1));
}
}else t1=0;
if(t2<=1)
{
if(lines_outside)
{
if(crossed_outside)crossed_outside->push_back(ivec2(lines_outside->size(),!was_swap));
lines_outside->push_back(Line2(v0+v*t2,v1));
}
}else t2=1;
if(lines_inside)
{
if(crossed_inside)
{
if(t1!=0)crossed_inside->push_back(ivec2(lines_inside->size(),!was_swap));
if(t2!=1)crossed_inside->push_back(ivec2(lines_inside->size(),was_swap));
}
lines_inside->push_back(Line2(v0+v*t1,v0+v*t2));
}
}
}
}
}
}
void CutByX(Lines2&lines,float x0,Lines2* lines_less,Lines2* lines_grater)
{
for(int i=0;i<lines.size();i++)
{
Line2 ll = lines[i];
if(lines_less)
if(ll.v[0].x<=x0 && ll.v[1].x<=x0)
{
lines_less->push_back(ll);
continue;
}
if(lines_grater)
if(ll.v[0].x>=x0 && ll.v[1].x>=x0)
{
lines_grater->push_back(ll);
continue;
}
//if(ll.v[0].x>ll.v[1].x) swap(ll.v[0],ll.v[1]);
float y0=ll.v[0].y + (ll.v[1].y-ll.v[0].y)*(x0-ll.v[0].x)/(ll.v[1].x-ll.v[0].x);
if(lines_less)
lines_less->push_back(Line2(ll.v[0],vec2(x0,y0)));
if(lines_grater)
lines_grater->push_back(Line2(vec2(x0,y0),ll.v[1]));
}
}
void CutByX(Lines2&lines,float x0)
{
for(int i=0;i<lines.size();i++)
{
Line2 ll = lines[i];
if((ll.v[0].x>x0 && ll.v[1].x<x0)||(ll.v[0].x<x0 && ll.v[1].x>x0))
{
float y0=ll.v[0].y + (ll.v[1].y-ll.v[0].y)*(x0-ll.v[0].x)/(ll.v[1].x-ll.v[0].x);
lines[i].v[0]=ll.v[0];
lines[i].v[1].set(x0,y0);
lines.push_back(Line2(vec2(x0,y0),ll.v[1]));
}
}
}
void MoveLinesX(Lines2&lines,float dx)
{
for(int i=0;i<lines.size();i++)
for(int j=0;j<2;j++)
lines[i].v[j].x += dx;
}
//возвращает площадь поверхности вращения для контура
float RotationSurfaceArea(Lines2& lines)
{
float res=0;
for(int i=0;i<lines.size();i++)
{
float x0 = lines[i].v[0].x;
float x1 = lines[i].v[1].x;
float ll = lines[i].v[0].length(lines[i].v[1]);
float ss = abs(x1+x0)*ll;
res += ss;
}
return res*PI;
}
//возвращает объём фигуры вращения области внутри контура
float RotationSurfaceVolume(Lines2& lines)
{
float res=0;
for(int i=0;i<lines.size();i++)
{
float x0 = lines[i].v[0].x;
float x1 = lines[i].v[1].x;
float dx = x1-x0;
float h = (lines[i].v[0].y-lines[i].v[1].y);
res += ((x0<0 || x1<0)?1:-1)*(x0*x0+dx*dx/3+dx*x0)*h;
}
return res*PI;
} | [
"[email protected]"
] | [
[
[
1,
407
]
]
] |
7742e5b1f6c67ecff43c678e5df83da69bbf97f8 | 44a6253596a3b1b81e56560b22b8ed4a0dc3b9bc | /Octree.cpp | f2310662781e0cc381ef2c32e4978002132989b9 | [] | no_license | Nuos/terraingpu | 9a2329aea3761c61c816759889a46a3ea82be7ea | 1ee3214d6e9e2190556bec2a90a52beec25f7df7 | refs/heads/master | 2020-12-11T07:19:38.181573 | 2009-04-11T17:45:16 | 2009-04-11T17:45:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,869 | cpp | #include "Octree.h"
#include "Block.h"
#include "Frustum.h"
Octree::Octree(INT base_x, INT base_y, INT base_z, UINT depth)
: x_(base_x),
y_(base_y),
z_(base_z),
depth_(depth),
size_(1<<depth),
block_(NULL),
is_empty_(false),
should_cull_(false),
bounding_box_(D3DXVECTOR3(x_, y_, z_),
D3DXVECTOR3(x_+size_, y_+size_, z_+size_)) {
Init();
}
Octree::~Octree(void) {
if (block_) {
block_->Deactivate();
block_->set_used(false);
}
for (UINT i = 0; i < 8; ++i) SAFE_DELETE(children_[i]);
}
void Octree::Init(void) {
UINT child_size = size_ / 2;
if (depth_ > 0) {
children_[X_POS_Y_POS_Z_POS] = new Octree(x_ + child_size, y_ + child_size, z_ + child_size, depth_ - 1);
children_[X_POS_Y_POS_Z_NEG] = new Octree(x_ + child_size, y_ + child_size, z_, depth_ - 1);
children_[X_POS_Y_NEG_Z_POS] = new Octree(x_ + child_size, y_, z_ + child_size, depth_ - 1);
children_[X_POS_Y_NEG_Z_NEG] = new Octree(x_ + child_size, y_, z_, depth_ - 1);
children_[X_NEG_Y_POS_Z_POS] = new Octree(x_, y_ + child_size, z_ + child_size, depth_ - 1);
children_[X_NEG_Y_POS_Z_NEG] = new Octree(x_, y_ + child_size, z_, depth_ - 1);
children_[X_NEG_Y_NEG_Z_POS] = new Octree(x_, y_, z_ + child_size, depth_ - 1);
children_[X_NEG_Y_NEG_Z_NEG] = new Octree(x_, y_, z_, depth_ - 1);
} else {
for (UINT i = 0; i < 8; ++i) children_[i] = NULL;
block_ = Block::GetBlockByID(BLOCK_ID(x_, y_, z_));
}
}
void Octree::Relocate(INT base_x, INT base_y, INT base_z) {
if (x_ == base_x && y_ == base_y && z_ == base_z) return;
x_ = base_x;
y_ = base_y;
z_ = base_z;
bounding_box_ = AxisAlignedBox(D3DXVECTOR3(x_, y_, z_),
D3DXVECTOR3(x_+size_, y_+size_, z_+size_));
UINT child_size = size_ / 2;
if (depth_ > 0) {
children_[X_POS_Y_POS_Z_POS]->Relocate(x_ + child_size, y_ + child_size, z_ + child_size);
children_[X_POS_Y_POS_Z_NEG]->Relocate(x_ + child_size, y_ + child_size, z_);
children_[X_POS_Y_NEG_Z_POS]->Relocate(x_ + child_size, y_, z_ + child_size);
children_[X_POS_Y_NEG_Z_NEG]->Relocate(x_ + child_size, y_, z_);
children_[X_NEG_Y_POS_Z_POS]->Relocate(x_, y_ + child_size, z_ + child_size);
children_[X_NEG_Y_POS_Z_NEG]->Relocate(x_, y_ + child_size, z_);
children_[X_NEG_Y_NEG_Z_POS]->Relocate(x_, y_, z_ + child_size);
children_[X_NEG_Y_NEG_Z_NEG]->Relocate(x_, y_, z_);
} else {
block_->Deactivate();
block_->set_used(false);
block_ = Block::GetBlockByID(BLOCK_ID(x_, y_, z_));
}
}
HRESULT Octree::ActivateBlocks(ID3D10Device *device) {
HRESULT hr;
if (block_) {
block_->Activate();
block_->set_used(true);
is_empty_ = block_->empty();
} else {
is_empty_ = true;
for (UINT i = 0; i < 8; ++i) {
if (children_[i]) {
V_RETURN(children_[i]->ActivateBlocks(device));
is_empty_ = is_empty_ && children_[i]->is_empty_;
}
}
}
return S_OK;
}
void Octree::Cull(const Frustum &frustum) {
should_cull_ = !frustum.AABInside(bounding_box_);
if (!should_cull_) {
for (UINT i = 0; i < 8; ++i) {
if (children_[i]) children_[i]->Cull(frustum);
}
}
}
void Octree::Draw(ID3D10Device *device, ID3D10EffectTechnique *technique) const {
if (is_empty_) return;
if (should_cull_) return;
if (block_) block_->Draw(device, technique);
for (UINT i = 0; i < 8; ++i) {
if (children_[i]) children_[i]->Draw(device, technique);
}
} | [
"[email protected]",
"[email protected]"
] | [
[
[
1,
2
],
[
4,
11
],
[
16,
48
],
[
51,
87
],
[
97,
98
],
[
101,
104
]
],
[
[
3,
3
],
[
12,
15
],
[
49,
50
],
[
88,
96
],
[
99,
100
]
]
] |
491f6ca02b8b3a71e92fa30e27b48012ea1774fb | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/Coding/CodingComponent/src/CodingComponentPrecompiledHeaders.cpp | be22cc7312def5e0402cb8782d0a49302941d63a | [] | 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 | 43 | cpp | #include "CodingComponentStableHeaders.h"
| [
"[email protected]"
] | [
[
[
1,
1
]
]
] |
e4883c4c241c302af79afef5e18e302ffc60496b | 55196303f36aa20da255031a8f115b6af83e7d11 | /include/bikini/base/color.inl | 8c41e1b5c6bc6a67439b49a0165d979129ec335e | [] | no_license | Heartbroken/bikini | 3f5447647d39587ffe15a7ae5badab3300d2a2ff | fe74f51a3a5d281c671d303632ff38be84d23dd7 | refs/heads/master | 2021-01-10T19:48:40.851837 | 2010-05-25T19:58:52 | 2010-05-25T19:58:52 | 37,190,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,827 | inl | /*---------------------------------------------------------------------------------------------*//*
Binary Kinematics 3 - C++ Game Programming Library
Copyright (C) 2008-2010 Viktor Reutskyy
[email protected]
*//*---------------------------------------------------------------------------------------------*/
#pragma once
// color
template<typename _T>
inline color_<_T>::color_()
{}
template<typename _T>
inline color_<_T>::color_(_T _r, _T _g, _T _b, _T _a)
:
r(_r), g(_g), b(_b), a(_a)
{}
template<typename _T>
inline color_<_T>::color_(u8 _r, u8 _g, u8 _b, u8 _a)
:
r(_T(_r)/_T(255)), g(_T(_g)/_T(255)), b(_T(_b)/_T(255)), a(_T(_a)/_T(255))
{}
template<typename _T>
inline color_<_T>::color_(u32 _c)
:
r(_T((_c>>16)&0xff)/_T(255)), g(_T((_c>>8)&0xff)/_T(255)), b(_T((_c>>0)&0xff)/_T(255)), a(_T((_c>>24)&0xff)/_T(255))
{
}
template<typename _T>
inline color_<_T>::operator vector_<_T, 4> () const
{
return *(vector_<_T, 4>*)this;
}
template<typename _T>
inline color_<_T>::operator u32 () const
{
return
(
((0xff & u32(a * _T(255))) << 24)|
((0xff & u32(r * _T(255))) << 16)|
((0xff & u32(g * _T(255))) << 8)|
((0xff & u32(b * _T(255))) << 0)
);
}
// cxform
template<typename _T>
inline cxform_<_T>::cxform_()
:
m_mul(white), m_add(black)
{
}
template<typename _T>
inline cxform_<_T>::cxform_(const color &_mul, const color &_add)
:
m_mul(_mul), m_add(_add)
{
}
template<typename _T>
inline const typename cxform_<_T>::color cxform_<_T>::transform(const color &_c) const
{
return color
(
clamp(_c.r * m_mul.r + m_add.r, _Type(0), _Type(1)),
clamp(_c.g * m_mul.g + m_add.g, _Type(0), _Type(1)),
clamp(_c.b * m_mul.b + m_add.b, _Type(0), _Type(1)),
clamp(_c.a * m_mul.a + m_add.a, _Type(0), _Type(1))
);
}
| [
"[email protected]",
"viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587"
] | [
[
[
1,
3
],
[
6,
13
],
[
15,
15
],
[
20,
20
],
[
25,
25
],
[
37,
37
],
[
72,
72
]
],
[
[
4,
5
],
[
14,
14
],
[
16,
19
],
[
21,
24
],
[
26,
36
],
[
38,
71
]
]
] |
f2527e27c8b31347f4f0def3ebbb1a98248d12e3 | 96e96a73920734376fd5c90eb8979509a2da25c0 | /C3DE/ParticleSystem.cpp | a11c07e7c3935f2214e288f0d16ffb74f99c0ecd | [] | 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 | 3,689 | cpp | #include "ParticleSystem.h"
#include "D3DRenderer.h"
#include "DebugMemory.h"
IDirect3DVertexDeclaration9* VertexParticle::Decl = 0;
ParticleSystem::ParticleSystem(const D3DXVECTOR3& accel,
// const AABB& box,
int maxNumParticles,
float timePerParticle, bool a_isFinite) : D3DMesh()
{
m_isFinite = a_isFinite;
m_isFinished = false;
m_emmittedParticles = 0;
//m_device = a_device;
m_accel = accel;
m_time = 0.0f;
m_maxNumParticles = maxNumParticles;
m_timePerParticle = timePerParticle;
// Allocate memory for maximum number of particles.
m_particles = new std::vector<VertexParticle*>;
m_aliveParticles = new std::vector<VertexParticle*>;
m_deadParticles = new std::vector<VertexParticle*>;
//m_particles->resize(m_maxNumParticles);
m_aliveParticles->reserve(m_maxNumParticles);
m_deadParticles->reserve(m_maxNumParticles);
// They start off all dead.
for(int i = 0; i < m_maxNumParticles; ++i)
{
#if 1
VertexParticle *t_particle = new VertexParticle();
t_particle->lifeTime = -1.0f;
t_particle->initialTime = 0.0f;
m_particles->push_back(t_particle);
//m_deadParticles.push_back(t_particle);
#endif
}
IDirect3DDevice9 *t_device = D3DRenderer::GetDevice();
HR(t_device->CreateVertexBuffer(m_maxNumParticles*sizeof(VertexParticle),
D3DUSAGE_DYNAMIC|D3DUSAGE_WRITEONLY|D3DUSAGE_POINTS,
0, D3DPOOL_DEFAULT, &m_vertexBuffer, 0));
}
ParticleSystem::~ParticleSystem()
{
int t_allCount = m_particles->size();
for(int i = 0; i < t_allCount; i++)
{
VertexParticle *t_particle = (*m_particles)[i];
delete t_particle;
t_particle = NULL;
}
delete m_particles;
m_particles = NULL;
delete m_aliveParticles;
m_aliveParticles = NULL;
delete m_deadParticles;
m_deadParticles = NULL;
}
void ParticleSystem::AddParticle()
{
if( m_deadParticles->size() > 0)
{
// Reinitialize a particle.
VertexParticle* p = m_deadParticles->back();
InitParticle(*p);
// No longer dead.
m_deadParticles->pop_back();
m_aliveParticles->push_back(p);
}
}
bool ParticleSystem::GetIsFinished()
{
return m_isFinished;
}
void ParticleSystem::Update(int deltaTime)
{
if(m_isFinished && m_isFinite)
{
return;
}
float dt = deltaTime/1000.0f;
//dt = 0.0001f;
m_time += dt;
// Rebuild the dead and alive list. Note that resize(0) does
// not deallocate memory (i.e., the capacity of the vector does
// not change).
m_deadParticles->resize(0);
m_aliveParticles->resize(0);
// For each particle.
for(int i = 0; i < m_maxNumParticles; ++i)
{
// Is the particle dead?
//VertexParticle *t = m_particles->operator[i];
if( (m_time - (*m_particles)[i]->initialTime) > (*m_particles)[i]->lifeTime)
{
m_deadParticles->push_back((*m_particles)[i]);
}
else
{
m_aliveParticles->push_back((*m_particles)[i]);
}
}
// A negative or zero mTimePerParticle value denotes
// not to emit any particles.
if( m_timePerParticle > 0.0f )
{
// Emit particles.
static float timeAccum = 0.0f;
timeAccum += dt;
while( timeAccum >= m_timePerParticle )
{
m_emmittedParticles++;
if(m_isFinite)
{
if(m_emmittedParticles > m_maxNumParticles)
{
int t_deadParticlesCount = m_deadParticles->size();
m_isFinished = t_deadParticlesCount == m_maxNumParticles;
//return;
}
else
{
AddParticle();
}
}
else
{
AddParticle();
}
timeAccum -= m_timePerParticle;
}
}
}
bool ParticleSystem::GetIsFinite()
{
return m_isFinite;
} | [
"caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158"
] | [
[
[
1,
177
]
]
] |
190306723d2a5d1a2ce9bc272470c6eecce79a95 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/iostreams/src/file_descriptor.cpp | c6cbf9b17f228bac9640acb78bf5ac5bb6c2c9b8 | [
"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 | 8,429 | cpp | // (C) Copyright Jonathan Turkanis 2003.
// Distributed under 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.)
// See http://www.boost.org/libs/iostreams for documentation.
// Inspired by fdstream.hpp, (C) Copyright Nicolai M. Josuttis 2001,
// available at http://www.josuttis.com/cppcode/fdstream.html.
// Define BOOST_IOSTREAMS_SOURCE so that <boost/iostreams/detail/config.hpp>
// knows that we are building the library (possibly exporting code), rather
// than using it (possibly importing code).
#define BOOST_IOSTREAMS_SOURCE
#include <boost/config.hpp> // BOOST_JOIN
#include <boost/iostreams/detail/error.hpp>
#include <boost/iostreams/detail/config/dyn_link.hpp>
#include <boost/iostreams/detail/config/windows_posix.hpp>
#include <boost/iostreams/detail/ios.hpp> // openmodes, failure.
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/integer_traits.hpp>
// OS-specific headers for low-level i/o.
#include <cassert>
#include <cstdio> // SEEK_SET, etc.
#include <errno.h>
#include <fcntl.h> // file opening flags.
#include <sys/stat.h> // file access permissions.
#ifdef BOOST_IOSTREAMS_WINDOWS
# include <io.h> // low-level file i/o.
# define WINDOWS_LEAN_AND_MEAN
# include <windows.h>
#else
# include <sys/types.h> // mode_t.
# include <unistd.h> // low-level file i/o.
#endif
// Names of runtime library routines vary.
#if defined(__BORLANDC__)
# define BOOST_RTL(x) BOOST_JOIN(_rtl_, x)
#else
# if defined(BOOST_IOSTREAMS_WINDOWS) && !defined(__CYGWIN__)
# define BOOST_RTL(x) BOOST_JOIN(_, x)
# else
# define BOOST_RTL(x) ::x
# endif
#endif
namespace boost { namespace iostreams {
//------------------Implementation of file_descriptor-------------------------//
void file_descriptor::open
( const std::string& path, BOOST_IOS::openmode m,
BOOST_IOS::openmode base )
{
using namespace std;
m |= base;
#ifdef BOOST_IOSTREAMS_WINDOWS //---------------------------------------------//
DWORD dwDesiredAccess;
DWORD dwCreationDisposition;
if ( (m & (BOOST_IOS::in | BOOST_IOS::out))
==
(BOOST_IOS::in | BOOST_IOS::out) )
{
assert(!(m & BOOST_IOS::app));
dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
dwCreationDisposition =
(m & BOOST_IOS::trunc) ?
OPEN_ALWAYS :
OPEN_EXISTING;
} else if (m & BOOST_IOS::in) {
assert(!(m & (BOOST_IOS::app |BOOST_IOS::trunc)));
dwDesiredAccess = GENERIC_READ;
dwCreationDisposition = OPEN_EXISTING;
} else if (m & BOOST_IOS::out) {
dwDesiredAccess = GENERIC_WRITE;
dwCreationDisposition = OPEN_ALWAYS;
if (m & BOOST_IOS::app)
pimpl_->flags_ |= impl::append;
}
HANDLE handle =
::CreateFileA( path.c_str(),
dwDesiredAccess,
0, // dwShareMode
NULL, // lpSecurityAttributes
dwCreationDisposition,
FILE_ATTRIBUTE_NORMAL,
NULL ); // hTemplateFile
if (handle != INVALID_HANDLE_VALUE) {
pimpl_->handle_ = handle;
pimpl_->flags_ |= impl::close_on_exit | impl::has_handle;
} else {
pimpl_->flags_ = 0;
throw BOOST_IOSTREAMS_FAILURE("bad open");
}
#else // #ifdef BOOST_IOSTREAMS_WINDOWS //------------------------------------//
// Calculate oflag argument to open.
int oflag = 0;
if ( (m & (BOOST_IOS::in | BOOST_IOS::out))
==
(BOOST_IOS::in | BOOST_IOS::out) )
{
assert(!(m & BOOST_IOS::app));
oflag |= O_RDWR;
} else if (m & BOOST_IOS::in) {
assert(!(m & (BOOST_IOS::app |BOOST_IOS::trunc)));
oflag |= O_RDONLY;
} else if (m & BOOST_IOS::out) {
oflag |= O_WRONLY;
m |= BOOST_IOS::trunc;
if (m & BOOST_IOS::app)
oflag |= O_APPEND;
}
if (m & BOOST_IOS::trunc)
oflag |= O_CREAT;
// Calculate pmode argument to open.
mode_t pmode = S_IRUSR | S_IWUSR |
S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH;
// Open file.
int fd = BOOST_RTL(open)(path.c_str(), oflag, pmode);
if (fd == -1) {
throw BOOST_IOSTREAMS_FAILURE("bad open");
} else {
pimpl_->fd_ = fd;
pimpl_->flags_ = impl::close_on_exit;
}
#endif // #ifndef BOOST_IOSTREAMS_WINDOWS //----------------------------------//
}
std::streamsize file_descriptor::read(char_type* s, std::streamsize n)
{
#ifdef BOOST_IOSTREAMS_WINDOWS
if (pimpl_->flags_ & impl::has_handle) {
DWORD result;
if (!::ReadFile(pimpl_->handle_, s, n, &result, NULL))
throw detail::bad_read();
return static_cast<std::streamsize>(result);
}
#endif
errno = 0;
std::streamsize result = BOOST_RTL(read)(pimpl_->fd_, s, n);
if (errno != 0)
throw detail::bad_read();
return result == 0 ? -1 : result;
}
std::streamsize file_descriptor::write(const char_type* s, std::streamsize n)
{
#ifdef BOOST_IOSTREAMS_WINDOWS
if (pimpl_->flags_ & impl::has_handle) {
if (pimpl_->flags_ & impl::append) {
::SetFilePointer(pimpl_->handle_, 0, NULL, FILE_END);
if (::GetLastError() != NO_ERROR)
throw detail::bad_seek();
}
DWORD ignore;
if (!::WriteFile(pimpl_->handle_, s, n, &ignore, NULL))
throw detail::bad_write();
return n;
}
#endif
int amt = BOOST_RTL(write)(pimpl_->fd_, s, n);
if (amt < n)
throw detail::bad_write(); // Handles blocking fd's only.
return n;
}
std::streampos file_descriptor::seek
(stream_offset off, BOOST_IOS::seekdir way)
{
using namespace std;
#ifdef BOOST_IOSTREAMS_WINDOWS
if (pimpl_->flags_ & impl::has_handle) {
LONG lDistanceToMove = static_cast<LONG>(off & 0xffffffff);
LONG lDistanceToMoveHigh = static_cast<LONG>(off >> 32);
DWORD dwResultLow =
::SetFilePointer( pimpl_->handle_,
lDistanceToMove,
&lDistanceToMoveHigh,
way == BOOST_IOS::beg ?
FILE_BEGIN :
way == BOOST_IOS::cur ?
FILE_CURRENT :
FILE_END );
if (::GetLastError() != NO_ERROR) {
throw detail::bad_seek();
} else {
return offset_to_position((lDistanceToMoveHigh << 32) + dwResultLow);
}
}
#endif // #ifdef BOOST_IOSTREAMS_WINDOWS
#ifndef BOOST_IOSTREAMS_HAS_LSEEK64
if ( off > integer_traits<long>::const_max ||
off < integer_traits<long>::const_min )
{
throw BOOST_IOSTREAMS_FAILURE("bad offset");
}
#endif
stream_offset result =
#ifdef BOOST_IOSTREAMS_HAS_LSEEK64
lseek64
#else
lseek
#endif
( pimpl_->fd_,
#ifdef BOOST_IOSTREAMS_HAS_LSEEK64
off,
#else
static_cast<long>(off),
#endif
way == BOOST_IOS::beg ?
SEEK_SET :
way == BOOST_IOS::cur ?
SEEK_CUR :
SEEK_END );
if (result == -1)
throw detail::bad_seek();
return offset_to_position(result);
}
void file_descriptor::close() { close_impl(*pimpl_); }
void file_descriptor::close_impl(impl& i)
{
#ifdef BOOST_IOSTREAMS_WINDOWS
if (i.flags_ & impl::has_handle) {
if (!::CloseHandle(i.handle_))
throw BOOST_IOSTREAMS_FAILURE("bad close");
i.fd_ = -1;
i.flags_ = 0;
return;
}
#endif
if (i.fd_ != -1) {
if (BOOST_RTL(close)(i.fd_) == -1)
throw BOOST_IOSTREAMS_FAILURE("bad close");
i.fd_ = -1;
i.flags_ = 0;
}
}
} } // End namespaces iostreams, boost.
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
254
]
]
] |
43494f4409c807fc937166e4479119623dd931e0 | ea613c6a4d531be9b5d41ced98df1a91320c59cc | /SQLCEHelper/Source/Currency.cpp | 0d16a3b45fbb25ce1a8486081f41a9fca1a8f168 | [] | no_license | f059074251/interested | 939f938109853da83741ee03aca161bfa9ce0976 | b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2 | refs/heads/master | 2021-01-15T14:49:45.217066 | 2010-09-16T10:42:30 | 2010-09-16T10:42:30 | 34,316,088 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,264 | cpp |
#include "stdafx.h"
#include "Currency.h"
CString CCurrency::Format(NumberFormat fmt, LCID lcid)
{
TCHAR szNum[32]; // Must hold between 922337203685477.5807 and -922337203685477.5808
TCHAR* psz = szNum + 31; // Set psz to last char
__int64 ii = m_cy.int64 < 0 ? -m_cy.int64 : m_cy.int64;
int nDec = 4; // Four decimals max
*psz = 0; // Set terminating null
do
{
--psz; // Move back
if(nDec-- == 0)
*psz = _T('.'); // Decimal point
else
{
unsigned lsd = (unsigned)(ii % 10); // Get least significant
// digit
ii /= 10; // Prepare for next most
// significant digit
*psz = _T('0') + lsd; // Place the digit
}
} while(ii != 0);
// Check if we need to add trailing zeroes
if(nDec >= 0)
{
while(nDec-- > 0)
*--psz = _T('0');
*--psz = _T('.');
}
if(m_cy.int64 < 0)
*--psz = _T('-');
if(fmt == Number)
{
TCHAR szFmt[32];
GetNumberFormat(LOCALE_USER_DEFAULT, NULL, psz, NULL, szFmt, 32);
return CString(szFmt);
}
if(fmt == Currency)
{
TCHAR szFmt[32];
GetCurrencyFormat(LOCALE_USER_DEFAULT, NULL, psz, NULL, szFmt, 32);
return CString(szFmt);
}
return CString(psz);
}
| [
"[email protected]@8d1da77e-e9f6-11de-9c2a-cb0f5ba72f9d"
] | [
[
[
1,
57
]
]
] |
fb5e1c990c8d8b00ac851a16d7b9fdb70fcdf137 | 5ff30d64df43c7438bbbcfda528b09bb8fec9e6b | /tests/graphics/step02/TriMesh.h | ee7a57aea73f12baed5d7aa98a1e5388fc485459 | [] | no_license | lvtx/gamekernel | c80cdb4655f6d4930a7d035a5448b469ac9ae924 | a84d9c268590a294a298a4c825d2dfe35e6eca21 | refs/heads/master | 2016-09-06T18:11:42.702216 | 2011-09-27T07:22:08 | 2011-09-27T07:22:08 | 38,255,025 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,232 | h | #pragma once
#include <d3d9.h>
namespace gfx {
struct Uv {
float u;
float v;
};
/**
* @struct TriMesh
*
* Default mesh with one tex
*/
struct TriMesh
{
static const uint FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1;
static const uint STRIDE = 32;
float x, y, z; // vertex pos
float nx, ny, nz; // vertex normal
Uv tex1; // tex coords
};
/**
* @struct TriSkinMesh
*
* Mesh for skinning with 4 weights
*/
struct TriSkinMesh
{
static const uint FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1;
static const uint STRIDE = 64;
float x, y, z; // vertex pos
float nx, ny, nz; // vertex normal
Uv tex1; // tex coords
float w[4]; // weights up to 4 bones
int b[4]; // bone indices
};
/**
* @struct TriBumpSkinMesh
*
* Mesh for 4 tex and 4 weights
*/
struct TriBumpSkinMesh
{
static const uint FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 | D3DFVF_TEX2 | D3DFVF_TEX3;
static const uint STRIDE = 80;
float x, y, z; // vertex pos
float nx, ny, nz; // vertex normal
Uv tex[3]; // up to 4 textures (diffuse, normal, bump)
float w[4]; // weights up to 4 bones
int b[4]; // bone indices
};
} // namespace gfx
| [
"darkface@localhost"
] | [
[
[
1,
61
]
]
] |
6027e0891e4002eee8751735631554b3666f815e | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXBitmapMenu.h | 4a02de07ad5f3d2b1995e3e3dc18a63c87f113fd | [] | no_license | weimingtom/sls | 7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8 | d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd | refs/heads/master | 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 28,172 | h | // ==========================================================================
// Class Specification : COXBitmapMenu
// ==========================================================================
// Header file : OXBitmapMenu.h
// Version: 9.3
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at [email protected], or by calling 416-849-8900.
// //////////////////////////////////////////////////////////////////////////
// Properties:
// NO Abstract class
// YES Derived from CMenu
// NO Is a Cwnd. (Its a CMenu)
// NO Two stage creation
// NO Has a message map
// NO Needs a resource
// NO Persistent objects (saveable on disk)
// NO Uses exceptions
// //////////////////////////////////////////////////////////////////////////
// Desciption :
// COXBitmapMenu implements drawing of the menu items
// Remark:
// User doesn't need to use this object directly. COXBitmapMenuOrganizer
// handles creation and destruction of COXBitmapMenu Objects.
// Prerequisites (necessary conditions):
//
/////////////////////////////////////////////////////////////////////////////
#ifndef BITMAPMENU_H
#define BITMAPMENU_H
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#ifndef __AFXTEMPL_H__
#include <afxtempl.h>
#define __AFXTEMPL_H_H
#endif
#include "OXDllExt.h"
// for drag and drop support
#include "OXDragDropSupport.h"
#include "OXMainRes.h"
#include "OXToolTipCtrl.h"
//////////////////////////////////////////////////////////
typedef struct _tagNMBMCUSTOMIZE
{
NMHDR nmhdr;
UINT nCustomizeEventID;
LPARAM lParam;
} NMBMCUSTOMIZE;
//////////////////////////////////////////////////////////////////////////
// ID of the expansion item
#ifndef ID_OX_SHOWALLITEMS
#define ID_OX_SHOWALLITEMS 0x0000ff56
#endif // ID_OX_SHOWALLITEMS
#ifndef ID_OXBITMAPMENU_SEPARATOR_HEIGHT
#define ID_OXBITMAPMENU_SEPARATOR_HEIGHT 8
#endif // ID_OXBITMAPMENU_SEPARATOR_HEIGHT
#ifndef ID_OXBITMAPMENUPOPUPWND_DEFAULT_WIDTH
#define ID_OXBITMAPMENUPOPUPWND_DEFAULT_WIDTH 50
#endif // ID_OXBITMAPMENUPOPUPWND_DEFAULT_WIDTH
#ifndef ID_OXBITMAPMENUPOPUPWND_DEFAULT_HEIGHT
#define ID_OXBITMAPMENUPOPUPWND_DEFAULT_HEIGHT 18
#endif // ID_OXBITMAPMENUPOPUPWND_DEFAULT_HEIGHT
#ifndef IDT_OXCHECKFORDRAGDROPEVENT
#define IDT_OXCHECKFORDRAGDROPEVENT 412
#endif // IDT_OXCHECKFORDRAGDROPEVENT
#ifndef ID_OXCHECKFORDRAGDROPEVENT_DELAY
#define ID_OXCHECKFORDRAGDROPEVENT_DELAY 200
#endif // ID_OXCHECKFORDRAGDROPEVENT_DELAY
#ifndef OXODS_HIDDEN
#define OXODS_HIDDEN 0x1000
#endif // OXODS_HIDDEN
#ifndef OXODS_HIDDENFIRST
#define OXODS_HIDDENFIRST 0x2000
#endif // OXODS_HIDDENFIRST
#ifndef OXODS_HIDDENLAST
#define OXODS_HIDDENLAST 0x4000
#endif // OXODS_HIDDENLAST
class COXImageInfo;
class COXItemInfo;
class COXBitmapMenuOrganizer;
class COXMenuSkin;
class COXShadowedItemWnd;
class COXCoolToolBar;
struct OXDIMENSIONCONSTANTS
{
// The gap between left edge of menu item and bitmap in pixels
int m_nGapLeftBitmap;
// The gap between the right edge of the bitmap and the end of the icon area (XP skin only)
int m_nGapRightBitmap;
// The gap between bitmap and menu text in pixels
int m_nGapBitmapText;
// The gap between menu text and accelerator
int m_nGapTextAcclrtr;
// The gap between accelerator and right edge of menu item
int m_nGapAcclrtrRight;
// Extra vertical space on top and bottom of text in pixels
int m_nGapVertText;
// --- Extra vertical space on top and bottom of bitmap in pixels
int m_nGapVertBitmap;
// Height of the menu separator
int m_nSeparatorHeight;
// Minimum width of the bitmap
int m_nMinBitmapWidth;
// Gap between two menu items
int m_nGapMenuItems;
};
typedef CArray<COLORREF, COLORREF> OXSHADOWARRAY;
struct OXPOPUPWND
{
OXPOPUPWND(HWND hWindow)
{
hWnd = hWindow;
arPixels.SetSize(0, 1024);
};
HWND hWnd;
OXSHADOWARRAY arPixels;
};
class COXPopupWndStack : public CTypedPtrList<CPtrList, OXPOPUPWND*>
{
public:
void Push(HWND hWnd) { AddHead(new OXPOPUPWND(hWnd)); };
HWND Pop()
{
if (IsEmpty())
return NULL;
return GetHead()->hWnd;
};
// Remove the OXPOPUPWND from the stack
void Remove(HWND hWnd)
{
POSITION pos = GetHeadPosition();
while (pos != NULL)
{
OXPOPUPWND* pPW = GetAt(pos);
if (pPW->hWnd == hWnd)
{
RemoveAt(pos);
delete pPW;
break;
}
GetNext(pos);
}
};
// Returns the shadow array of the given window
OXSHADOWARRAY* GetShadowArray(HWND hWnd)
{
POSITION pos = GetHeadPosition();
while (pos != NULL)
{
OXPOPUPWND* pPW = GetNext(pos);
if (pPW->hWnd == hWnd)
return &pPW->arPixels;
}
return NULL;
}
};
/////////////////////////////////////////////////////////////////////////////
// COXShadowedItemWnd window
class COXShadowedItemWnd : public CWnd
{
friend class COXMenuSkinClassic;
friend class COXMenuSkinXP;
friend class COXMenuSkin2003;
// Construction
public:
COXShadowedItemWnd(COXCoolToolBar* pCoolToolBar, int iMenuItem, UINT nFlags);
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(COXShadowedItemWnd)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~COXShadowedItemWnd();
// Generated message map functions
protected:
//{{AFX_MSG(COXShadowedItemWnd)
afx_msg void OnPaint();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
COXCoolToolBar* m_pCoolToolbar;
int m_iMenuItem;
UINT m_nPosFlags;
};
// Flags to indicate the ralative position of the popup menu from the selected item
#define OX_TPM_BOTTOM 0x1 // the menu is displayed on the bottom of the selected item
#define OX_TPM_RIGHT 0x2
#define OX_TPM_LEFT 0x4
#define OX_TPM_TOP 0x8
class OX_CLASS_DECL COXBitmapMenu : public CMenu
{
friend class COXBitmapMenuOrganizer;
friend class COXMenuSkinClassic;
friend class COXMenuSkinXP;
friend class COXMenuSkin2003;
friend class COXMenuBar;
friend class COXBitmapMenuPopupWnd;
friend class COXShadowedItemWnd;
DECLARE_DYNAMIC(COXBitmapMenu)
//Data members --------------------------------------------------------
protected:
// map of accelerator keys
CMap<TCHAR, TCHAR, int, int> m_KeyAccessMap;
// holds the largest width of all the bitmaps in the menu
int m_nBitmapExtent;
// holds the height of the text
int m_nTextHeight;
// holds the largest width of the all the accelerator texts of menu items
int m_nAcceleratorExtent;
// holds the largest width of the texts of menu items
int m_nStringExtent;
// Maintains a list of item infos for cleaning purpose
// while destructing the object
CList<COXItemInfo*, COXItemInfo*> m_ItemInfoList;
// flag that specifies that menu supports customization
BOOL m_bCutomizable;
// index of the menu item being currently customized
int m_nCustomizedItemIndex;
// flag that specifies that the menu is in the customization mode
BOOL m_bInCutomizationMode;
// recipient of customization related notifications
HWND m_hWndCustomizeOrganizer;
// default COleDropSource for drag'n'drop operation
COXSHBDropSource m_oleDropSource;
// default COleDropTarget for drag'n'drop operation
COXSHBDropTarget m_oleDropTarget;
// flag that specifies whether we launched drag'n'drop operation or not
BOOL m_bDragDropOwner;
// flag that specifies if any drag and drop operation is undergoing
BOOL m_bDragDropOperation;
// popup window that displays the menu in customization mode
class COXBitmapMenuPopupWnd* m_pPopupWnd;
// index of the item before which the insertion mark is drawn
int m_nInsertMarkIndex;
// index of the dragged item
int m_nDraggedItemIndex;
// The rectangle of the toolbar or menubar drop down button which is
// responsible for displaying the menu. This rectangle is in screen coordinates.
CRect m_rectDropDownItem;
static LRESULT CALLBACK PopupWndProc(HWND hwnd, UINT nMsg, WPARAM wParam, LPARAM lParam);
COXPopupWndStack m_PopupWndStack; // a stack of all popup container windows
COXToolTipCtrl m_ToolTipCtrl;
private:
BOOL IsPopupItem(UINT nItemID);
static BOOL RegisterWindowClass(HINSTANCE hInstance);
static CSize GetPopupMenuSize(CMenu* pMenu);
static void DeterminePosition(CMenu* pMenu, LPCRECT lpItemRect, DWORD dwStyle, CPoint& ptTopLeft, UINT& nFlags, UINT& nPosFlags);
static COXMenuSkin* m_pMenuSkin;
static COXMenuSkin* COXBitmapMenu::GetMenuSkin();
//Member functions-----------------------------------------------------------------------
public:
// --- In :
// --- Out :
// --- Returns :
// --- Effect : Object Constructions and defaults are initialised
COXBitmapMenu();
// --- In :
// --- Out :
// --- Returns :
// --- Effect : Cleanup and Object Destruction
virtual ~COXBitmapMenu();
// --- In : lpDrawItemStruct - A pointer to a DRAWITEMSTRUCT
// containing information about
// the item to draw.
// --- Out :
// --- Returns:
// --- Effect : This function is called by the MFC framework when a visual
// aspect of the menu has changed. If you override this function
// to implement drawing of the menu you must restore all GDI
// object selected for the display context supplied in
// lpDrawItemStruct before the member function exits
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
// --- In : lpMeasureItemStruct - A pointer to a MEASUREITEMSTRUCT structure
// --- Out :
// --- Returns:
// --- Effect : This function is called by the framework to determine menu
// dimensions the menu is created
virtual void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct);
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Calculates the largest extents of bitmaps, menu texts,
// and accelerator texts
void CalcExtents();
// --- In : ppt - pointer to POINT structure that defines the point
// to test in client coordinates of the menu popup
// window
// --- Out : pbBefore - pointer to BOOL variable that will be set to
// TRUE if specified point is located over the top
// part of found menu item; othrwise it will be set
// to FALSE
// --- Returns: The index of the found menu item
// --- Effect : Finds menu item that is located under the specified point
int HitTest(LPPOINT ppt, BOOL* pbBefore=NULL);
// --- In : bCustomizable - if TRUE the menu ca be customized
// --- Out :
// --- Returns:
// --- Effect : Sets the flag that specifies whether the menu can be
// customized or not
inline void SetCustomizable(BOOL bCustomizable) { m_bCutomizable=bCustomizable; }
// --- In :
// --- Out :
// --- Returns: TRUE if the menu can be customized; otherwise FALSE
// --- Effect: Retrieves the flag that specifies whether the menu can be
// customized or not
virtual BOOL IsCustomizable() const { return m_bCutomizable; }
// --- In : bInCutomizationMode - if TRUE the menu will be set in to
// customization mode
// hWndCustomizeOrganizer - handle to window that will be a
// recipient of customization related
// notifications
// --- Out :
// --- Returns:
// --- Effect : Sets the menu in to customization/normal mode
inline void SetCutomizationMode(BOOL bInCutomizationMode,
HWND hWndCustomizeOrganizer=NULL)
{
if(bInCutomizationMode && !IsCustomizable())
SetCustomizable(TRUE);
if(!bInCutomizationMode)
SetCustomizedItem(-1);
else
m_hWndCustomizeOrganizer=hWndCustomizeOrganizer;
m_bInCutomizationMode=bInCutomizationMode;
}
// --- In :
// --- Out :
// --- Returns: TRUE if the menu is in customization mode; FALSE if it is in
// normal mode
// --- Effect: Retrieves the flag that specifies whether the menu is in
// customization or normal mode
inline BOOL IsInCustomizationMode() const { return m_bInCutomizationMode; }
// --- In : nIndex - menu item index to be set as customized
// --- Out :
// --- Returns: The index of previous customized menu item. -1 if there were
// no customized menu item before
// --- Effect : Sets customized menu item. Specify -1 as a parameter in order
// to reset customized menu item
int SetCustomizedItem(int nIndex);
// --- In :
// --- Out :
// --- Returns: The index of the customized menu item. -1 if there is no
// customized menu item
// --- Effect : Retrieves customized menu item
inline int GetCustomizedItem() const { return m_nCustomizedItemIndex; }
// --- In : nIndex - menu item index to test
// --- Out :
// --- Returns: TRUE if specified menu item is customized; otherwise FALSE
// --- Effect : Retrieves the flag that specifies if given item is customized
// one or not
inline BOOL IsItemCustomized(int nIndex) const
{
return (nIndex==m_nCustomizedItemIndex);
}
// --- In : nIndex - menu item index before which the insert mark
// will be set
// --- Out :
// --- Returns: The insert mark previous position. -1 if there were no
// insert mark set before
// --- Effect : Sets insert mark at specified position. Specify -1 as a
// parameter in order to reset insert mark position
int SetInsertMark(int nItemIndex);
// --- In :
// --- Out :
// --- Returns: The insert mark position. -1 if there is no insert mark set
// --- Effect : Retrives insert mark position
inline int GetInsertMark() const { return m_nInsertMarkIndex; }
// --- In : nIndex - menu item index to be set as dragged
// --- Out :
// --- Returns: The index of previous dragged menu item. -1 if there were
// no dragged menu item before
// --- Effect : Sets dragged menu item. Specify -1 as a parameter in order
// to reset dragged menu item
inline void SetDraggedItem(int nIndex) { m_nDraggedItemIndex=nIndex; }
// --- In :
// --- Out :
// --- Returns: The index of the dragged menu item. -1 if there is no
// dragged menu item
// --- Effect : Retrieves dragged menu item
inline int GetDraggedItem() const { return m_nDraggedItemIndex; }
// --- In : nIndex - menu item index to test
// --- Out :
// --- Returns: TRUE if specified menu item is dragged; otherwise FALSE
// --- Effect : Retrieves the flag that specifies if given item is dragged
// one or not
inline BOOL IsItemDragged(int nIndex) const
{
return (nIndex==m_nDraggedItemIndex);
}
// --- In : nIndex - menu item index to display customize menu for
// point - screen coordinates of the Top/Left point at which
// the context menu should be displayed
// --- Out :
// --- Returns: TRUE if context menu was successfully created and displayed;
// otherwise FALSE
// --- Effect : Display context menu with customization commands for the
// specified menu item
virtual BOOL DisplayCustomizeItemContextMenu(int nItemIndex, CPoint point);
// --- In : pWndOwner - pointer to a window that will be assigned as
// an owner of returned COleDropSource object
// --- Out :
// --- Returns: A pointer to internal COleDropSource object
// --- Effect : Retrieves a pointer to internal COleDropSource object that will
// allow this object to handle drag'n'drop operation
virtual COleDropSource* GetDropSource(CWnd* pWndOwner)
{
ASSERT(pWndOwner!=NULL);
// owner window (recipient window) must exist at that moment
ASSERT(::IsWindow(pWndOwner->GetSafeHwnd()));
m_oleDropSource.SetOwner(pWndOwner);
return &m_oleDropSource;
}
// --- In :
// --- Out :
// --- Returns: A pointer to internal COleDropTarget object
// --- Effect : Retrieves a pointer to internal COleDropTarget object that will
// allow this object to handle drag'n'drop operation
virtual COleDropTarget* GetDropTarget() { return &m_oleDropTarget; }
// --- In :
// --- Out :
// --- Returns: TRUE if this object has started current drag'n'drop operation;
// otherwise FALSE
// --- Effect : Retrieves the flag that specifies whether this object has
// started current drag'n'drop operation
inline BOOL IsDragDropOwner() const { return m_bDragDropOwner; }
// --- In : pPopupWnd - a pointer to COXBitmapMenuPopupWnd object that
// will be used to display the menu in customization
// mode
// --- Out :
// --- Returns:
// --- Effect : Sets a pointer to COXBitmapMenuPopupWnd object that will be used
// to display the menu in customization mode
inline void SetPopupWnd(COXBitmapMenuPopupWnd* pPopupWnd)
{
m_pPopupWnd=pPopupWnd;
}
// --- In : pPopupWnd - a pointer to COXBitmapMenuPopupWnd object that
// will be used to display the menu in customization
// mode
// --- Out :
// --- Returns: A pointer to COXBitmapMenuPopupWnd object that will be used to
// display the menu in customization mode
// --- Effect : Retrieves a pointer to COXBitmapMenuPopupWnd object that will be used
// to display the menu in customization mode
virtual COXBitmapMenuPopupWnd* GetPopupWnd() const { return m_pPopupWnd; }
// --- In : nIndex - index of the menu item that is about to become the
// dragged one
// --- Out :
// --- Returns:
// --- Effect: Initializes drag'n'drop operation
virtual void OnBeginDragDrop(int nIndex);
// --- In : rgbFace - base color
// rgbHilight - hilight color
// --- Out :
// --- Returns: A handle to created brush object that combines base and highlight
// colors in a specific way
// --- Effect: Creates new brush object for drawing routines (allows to draw
// the background in the way similar to drawing the background
// of pressed toolbar button). Caller is responsible for deleting
// thie returned brush
static HBRUSH HBrushDitherCreate(COLORREF rgbFace, COLORREF rgbHilight);
BOOL TrackPopupMenu(COXCoolToolBar* pCoolToolBar, CWnd* pWnd, LPCRECT lpRect = NULL);
// --- Effect: This method should be called by a CMDMSG handler in the main app,
// and it's job is to handle menu buttons for restore/close/minimize in an MDI app
static BOOL HandleMDICommandMessage(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo);
private:
static void RestoreMDI();
static void CloseMDI();
static void MinimizeMDI();
protected:
static WNDPROC m_origWndProc;
// calculates rectangles for displaying item's image, text and accelerator text
virtual void DistributeSpace(UINT nState, COXImageInfo* pImageInfo,
CRect itemRect, CRect& buttonRect, CRect& imageRect, CRect& text1Rect,
CRect& text2Rect);
// draws the background of menu item
virtual void DrawBackground(CDC* pDC, UINT nState, COXImageInfo* pImageInfo,
CRect itemRect, CRect buttonRect);
// draws the button that frames menu item image
virtual void DrawButton(CDC* pDC, UINT nState, COXImageInfo* pImageInfo,
CRect buttonRect);
// draws menu item image
virtual void DrawImage(CDC* pDC, UINT nState, COXImageInfo* pImageInfo,
CRect imageRect);
// draws menu item text
virtual void DrawText(CDC* pDC, UINT nState, CString sText, CRect text1Rect,
CRect text2Rect);
// draws separator menu item
virtual void DrawSeparator(CDC* pDC, CRect itemRect);
// draws customized menu item
virtual void DrawCustomized(CDC* pDC, CRect itemRect);
// draws insert mark
virtual void DrawInsertMark(CDC* pDC, CRect itemRect, BOOL bBefore);
// draws submenu item
virtual void DrawSubmenuItem(CDC* pDC, UINT nState, CString sText,
COXImageInfo* pImageInfo, CRect itemRect, CRect buttonRect,
CRect text1Rect, CRect text2Rect);
// draws ezpansion item
virtual void DrawExpansionItem(CDC* pDC, CRect itemRect, UINT nState);
// Saves new created COXItemInfo object in the internal array
void AddItemInfo(COXItemInfo* pItemInfo);
// handle update routines for the menu commands
void OnUpdateCmdUI(CWnd* pWnd, UINT nIndex, BOOL bSysMenu);
// sends customization related notifications
LRESULT SendCustomizeNotification(UINT nCustomizeCmdID);
// update the contents of the displayed menu
void UpdateContents();
public:
// drag and drop support
virtual LONG OnDragEnter(WPARAM wParam, LPARAM lParam);
virtual LONG OnDragOver(WPARAM wParam, LPARAM lParam);
virtual LONG OnDragLeave(WPARAM wParam, LPARAM lParam);
virtual LONG OnDrop(WPARAM wParam, LPARAM lParam);
// --- In : lpData - reference to a pointer of data that contains
// item info in specific drag'n'drop format
// hMenu - handle to a menu where dropped item will be
// inserted
// nItemIndex - position at which dropped item will be inserted
//
// --- Out :
// --- Returns:
// --- Effect: Retrieves item info from dropped data and insert it at specified
// position in specified menu
virtual void RetrieveDragDropMenuItem(BYTE*& lpData, HMENU hMenu, int nItemIndex);
// advanced customization commands handlers
virtual void OnCustBMDelete();
virtual void OnCustBMAppearance();
virtual void OnCustBMSeparatorBefore();
virtual void OnCustBMSeparatorAfter();
virtual void OnCustBMRecentlyUsed();
};
/////////////////////////////////////////////////////////////////////////////
class OX_CLASS_DECL COXBitmapMenuPopupWnd : public CWnd
{
friend class COXMenuSkinClassic;
friend class COXMenuSkinXP;
DECLARE_DYNAMIC(COXBitmapMenuPopupWnd)
//Data members --------------------------------------------------------
public:
protected:
COXBitmapMenu* m_pBitmapMenu;
CRect m_rectWindow;
CArray<CRect,CRect&> m_arrItemRects;
CFont m_fontMenu;
INT_PTR m_nCheckForDragDropEventTimerID;
//Member functions-----------------------------------------------------------------------
public:
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Constructs the object
COXBitmapMenuPopupWnd();
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Destructs the object
virtual ~COXBitmapMenuPopupWnd();
// --- In :
// --- Out :
// --- Returns: pointer to associated bitmap menu object
// --- Effect : retrieves the associated bitmap menu object
virtual COXBitmapMenu* GetBitmapMenu() const { return m_pBitmapMenu; }
// --- In : pMenu - pointer to the popup bitmap menu to be displayed
// nFlags - Specifies a screen-position flag. It can be
// one of the following:
//
// TPM_CENTERALIGN Centers the pop-up menu horizontally
// relative to the coordinate specified
// by x.
// TPM_LEFTALIGN Positions the pop-up menu so that its
// left side is aligned with the
// coordinate specified by x.
// TPM_RIGHTALIGN Positions the pop-up menu so that its
// right side is aligned with the
// coordinate specified by x.
//
// x - Specifies the horizontal position in screen
// coordinates of the pop-up menu. Depending on the
// value of the nFlags parameter, the menu can be
// left-aligned, right-aligned, or centered relative
// to this position
// y - Specifies the vertical position in screen
// coordinates of the top of the menu on the screen
// pWnd - Identifies the window that owns the pop-up menu.
// --- Out :
// --- Returns: TRUE if the function is successful; otherwise FALSE
// --- Effect : Displays a floating pop-up menu at the specified location and
// tracks the selection of items on the pop-up menu. A floating
// pop-up menu can appear anywhere on the screen
virtual BOOL TrackPopupMenu(COXBitmapMenu* pMenu, UINT nFlags,
int x, int y, CWnd* pWnd);
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Hides the popup window and reset all internal data
virtual void ResetPopupMenu();
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Called by bitmap menu object in order to notify that
// the contents of the menu have been changed
virtual void OnMenuChanged();
// --- In : nIndex - index of the item in the associated menu that
// must be redrawn
// --- Out :
// --- Returns:
// --- Effect : Redraws the specified menu item
void RedrawItem(int nIndex);
// --- In : nIndex - index of the item in the associated menu which
// rectangle in client coordinates is being retrieved
// --- Out :
// --- Returns: rectangle taken by the specified menu item
// --- Effect : Retrieves the rectangle taken by the specified menu item
inline CRect GetItemRect(int nIndex) const
{
ASSERT(nIndex>=0 && nIndex<m_arrItemRects.GetSize());
return m_arrItemRects[nIndex];
}
protected:
// --- In : nFlags - Specifies a screen-position flag. It can be one of the
// following:
//
// TPM_CENTERALIGN Centers the pop-up menu horizontally
// relative to the coordinate specified
// by x.
// TPM_LEFTALIGN Positions the pop-up menu so that its
// left side is aligned with the
// coordinate specified by x.
// TPM_RIGHTALIGN Positions the pop-up menu so that its
// right side is aligned with the
// coordinate specified by x.
//
// x - Specifies the horizontal position in screen
// coordinates of the pop-up menu. Depending on the
// value of the nFlags parameter, the menu can be
// left-aligned, right-aligned, or centered relative
// to this position
// y - Specifies the vertical position in screen
// coordinates of the top of the menu on the screen
// --- Out :
// --- Returns: TRUE if the function is successful; otherwise FALSE
// --- Effect : Displays a floating pop-up menu at the specified location and
// tracks the selection of items on the pop-up menu. A floating
// pop-up menu can appear anywhere on the screen
virtual BOOL CalcLayout(UINT nFlags, int x, int y);
protected:
void UpdateMenuMetrics();
// Generated message map functions
protected:
//{{AFX_MSG(COXBitmapMenuPopupWnd)
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnMButtonDown(UINT nFlags, CPoint point);
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
afx_msg void OnPaint();
afx_msg int OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT message);
afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnNcPaint();
//}}AFX_MSG
// drag and drop support
virtual LONG OnDragEnter(WPARAM wParam, LPARAM lParam);
virtual LONG OnDragOver(WPARAM wParam, LPARAM lParam);
virtual LONG OnDragLeave(WPARAM wParam, LPARAM lParam);
virtual LONG OnDrop(WPARAM wParam, LPARAM lParam);
// advanced customization commands handlers
afx_msg void OnCustBMDelete();
afx_msg void OnCustBMAppearance();
afx_msg void OnCustBMSeparatorBefore();
afx_msg void OnCustBMSeparatorAfter();
afx_msg void OnCustBMRecentlyUsed();
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
#endif
| [
"[email protected]"
] | [
[
[
1,
827
]
]
] |
0bb02d4120e1f8a8191c079b8652b7a9d4008268 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Common/billboard.h | ce97dd2451e22d5298592e9bfe067199a9ec2be7 | [] | no_license | 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 | UHC | C++ | false | false | 1,711 | h | // BeastView.h : interface of the CBeastView class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_BILLBOARD_H__25FE7788_56AD_4D50_8D9E_E69C969DE0F9__INCLUDED_)
#define AFX_BILLBOARD_H__25FE7788_56AD_4D50_8D9E_E69C969DE0F9__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CBillboard;
typedef struct tagBILLBOARD
{
TCHAR m_lpszFileName [32];
TCHAR m_lpszName [32];
CRect rect;
CPoint ptCenter;
D3DCOLOR dwColor;
BOOL bAnimation;
DWORD dwAniMethod;
DWORD dwFrame;
BOOL bEffect;
FLOAT fScale;
CBillboard* m_pBillboard;
}* LPBILLBOARD, BILLBOARD;
class CBillboard : public CModel
{
LPBILLBOARD m_pBillboard;
CTexture* m_pTexture;
LPDIRECT3DVERTEXBUFFER9 m_pVertexBuffer;
DWORD m_nVertexNum;
public:
float m_fScale;
CBillboard();
~CBillboard();
void AddFrame( FLOAT fAddFrame ) { }
void SetFrame( FLOAT fFrame ) { }
CTexture* GetTexture(void) { return m_pTexture; }
virtual BOOL Render( LPDIRECT3DDEVICE9 pd3dDevice, const D3DXMATRIX* pmatWorld = NULL );
virtual void FrameMove() { }
// dx 초기화 관련
HRESULT InitDeviceObjects( LPDIRECT3DDEVICE9 pd3dDevice, LPBILLBOARD lpBillboard, CTexture* pTexture );
HRESULT RestoreDeviceObjects();
HRESULT InvalidateDeviceObjects();
HRESULT DeleteDeviceObjects();
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BILLBOARD_H__25FE7788_56AD_4D50_8D9E_E69C969DE0F9__INCLUDED_)
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
67
]
]
] |
f5cd8495a6daf5d8785eb54f83b0b56a2577120d | fa28ff7783f4bf1308ba11e4c2a98016b10355cc | /ArtConfig.h | 2b4c116dc4281d3cc7d3efd9c3b235323663de92 | [] | no_license | AlanZheng/heeksart | 79bc9c75fa106e55c77e4d93b3daef8e64d21354 | 4691026bf5f90caed659c06017a2c78da74f373a | refs/heads/master | 2020-12-30T09:26:21.567782 | 2010-10-17T09:37:52 | 2010-10-17T09:37:52 | 39,455,743 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 321 | h | // ArtConfig.h
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include <wx/config.h>
#include <wx/confbase.h>
#include <wx/fileconf.h>
class ArtConfig: public wxConfig
{
public:
ArtConfig():wxConfig(_T("HeeksArt")){}
~ArtConfig(){}
};
| [
"danheeks@4f205954-0d8c-11de-85a1-fd18384f7567"
] | [
[
[
1,
13
]
]
] |
9bea70110930075aff2189c8cf55bdac988b819d | a6d5d811222889c750c786ef5487f9b49edb2de1 | /motion/RST/GUI/TreeView.h | 6660aba97a1e39a287bf7ac987f5e919869ab2d4 | [] | no_license | oarslan3/gt-cs-rip-projects | 1f29f979b5ca57f87cd154bfa1c88b93fb09ccb9 | 0b8f470679d5c107c7f10dbe9a67cdda392a9329 | refs/heads/master | 2021-01-10T05:50:57.921487 | 2009-12-13T16:48:49 | 2009-12-13T16:48:49 | 52,402,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,714 | h | //---------------------------------------------------------------------
// Copyright (c) 2008 Saul Reynolds-Haertle & Mike Stilman
// All Rights Reserved.
//
// Permission to duplicate or use this software in whole or in part
// is only granted by consultation with the author.
//
// Mike Stilman [email protected]
//
// Robotics and Intelligent Machines
// Georgia Tech
//--------------------------------------------------------------------
#ifndef TREEVIEW_H
#define TREEVIEW_H
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/image.h"
#include "wx/imaglist.h"
#include "wx/treectrl.h"
class Robot;
class Link;
#define TreeViewHandle 1001
enum DataType
{
Return_Type_Object,
Return_Type_Robot,
Return_Type_Link,
Return_Type_Tree_Root,
Return_Type_Other
};
enum TreeIcon
{
Tree_Icon_Robot = 0,
Tree_Icon_Object = 1,
Tree_Icon_Prismatic = 2,
Tree_Icon_Revolute = 3,
Tree_Icon_Free = 4,
Tree_Icon_Fixed = 5
};
class TreeViewReturn : public wxTreeItemData
{
public:
TreeViewReturn(){}
void* data;
DataType dType;
};
class TreeView : public wxTreeCtrl
{
public:
TreeView(){}
TreeView(wxWindow *parent, const wxWindowID id,
const wxPoint& pos, const wxSize& size,
long style);
virtual ~TreeView(){}
void CreateFromWorld();
wxTreeItemId AddLinkTree(Link*, wxTreeItemId hPrev, wxTreeItemId hParent, bool inChain);
void OnSelChanged(wxTreeEvent& event);
void ExpandAll();
wxImageList* imageList;
wxTreeItemId rootId;
DECLARE_DYNAMIC_CLASS(TreeView)
DECLARE_EVENT_TABLE()
};
#endif | [
"alexgcunningham@e642834e-98c8-11de-b255-e1213ca11573"
] | [
[
[
1,
83
]
]
] |
bc0ec0be6c3fdb1d1a21542f6be4fe8d29e7f8be | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Graphic/Renderer/D3D9CubeTexture.cpp | 4759fa37119c9374586e38ce1a0da29c1c60a8d4 | [] | 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 | 2,774 | cpp | #include "D3D9CubeTexture.h"
#include "D3D9RenderWindow.h"
namespace Flagship
{
D3D9CubeTexture::D3D9CubeTexture()
{
m_pD3D9CubeTexture = NULL;
m_iClassType = Base::Texture_Cube;
}
D3D9CubeTexture::~D3D9CubeTexture()
{
SAFE_RELEASE( m_pD3D9CubeTexture );
}
LPDIRECT3DCUBETEXTURE9 D3D9CubeTexture::GetImpliment()
{
return m_pD3D9CubeTexture;
}
bool D3D9CubeTexture::CreateFromMemory()
{
// 获取D3D9设备指针
LPDIRECT3DDEVICE9 pD3D9Device = ( ( D3D9RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice();
// 创建D3D9贴图对象
HRESULT hr = D3DXCreateCubeTextureFromFileInMemory( pD3D9Device, m_kFileBuffer.GetPointer(), m_kFileBuffer.GetSize(), &m_pD3D9CubeTexture );
if ( FAILED( hr ) )
{
char szLog[10240];
char szFile[256];
wcstombs( szFile, m_szPathName.c_str(), 256 );
sprintf( szLog, "D3D9CubeTexture::Cache() Fail! File:%s", szFile );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9CubeTexture::CreateRenderTarget( UINT uiWidth, UINT uiHeight, DWORD dwFormat )
{
// 获取D3D9设备指针
LPDIRECT3DDEVICE9 pD3D9Device = ( ( D3D9RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice();
// 创建D3D9贴图对象
HRESULT hr = D3DXCreateCubeTexture( pD3D9Device, uiWidth, 1, D3DUSAGE_RENDERTARGET, (D3DFORMAT) dwFormat, D3DPOOL_DEFAULT, &m_pD3D9CubeTexture );
if ( FAILED( hr ) )
{
char szLog[10240];
sprintf( szLog, "D3D9CubeTexture::CreateRenderTexture() Fail! Format:%d", (int)dwFormat );
LogManager::GetSingleton()->WriteLog( szLog );
return false;
}
return true;
}
bool D3D9CubeTexture::ClearTexture()
{
// 获取D3D9设备指针
LPDIRECT3DDEVICE9 pD3D9Device = ( ( D3D9RenderWindow * ) RenderWindow::GetActiveRenderWindow() )->GetDevice();
LPDIRECT3DSURFACE9 pSurface[6];
m_pD3D9CubeTexture->GetCubeMapSurface( D3DCUBEMAP_FACE_POSITIVE_X, 0, &pSurface[0] );
m_pD3D9CubeTexture->GetCubeMapSurface( D3DCUBEMAP_FACE_NEGATIVE_X, 0, &pSurface[1] );
m_pD3D9CubeTexture->GetCubeMapSurface( D3DCUBEMAP_FACE_POSITIVE_Y, 0, &pSurface[2] );
m_pD3D9CubeTexture->GetCubeMapSurface( D3DCUBEMAP_FACE_NEGATIVE_Y, 0, &pSurface[3] );
m_pD3D9CubeTexture->GetCubeMapSurface( D3DCUBEMAP_FACE_POSITIVE_Z, 0, &pSurface[4] );
m_pD3D9CubeTexture->GetCubeMapSurface( D3DCUBEMAP_FACE_NEGATIVE_Z, 0, &pSurface[5] );
for ( int i = 0; i < 6; i++ )
{
pD3D9Device->ColorFill( pSurface[i], NULL, D3DCOLOR_ARGB(0, 0, 0, 0) );
SAFE_RELEASE( pSurface[i] );
}
return true;
}
void D3D9CubeTexture::UnCache()
{
Texture::UnCache();
SAFE_RELEASE( m_pD3D9CubeTexture );
}
} | [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
] | [
[
[
1,
89
]
]
] |
e66b5d8cff6378d6d61d0543f646ce086e1791f3 | 21da454a8f032d6ad63ca9460656c1e04440310e | /src/wcpp/wscom/main/wscMainModule.cpp | 6357b6e5cd2330436616632420d2568b36a6aa6c | [] | no_license | merezhang/wcpp | d9879ffb103513a6b58560102ec565b9dc5855dd | e22eb48ea2dd9eda5cd437960dd95074774b70b0 | refs/heads/master | 2021-01-10T06:29:42.908096 | 2009-08-31T09:20:31 | 2009-08-31T09:20:31 | 46,339,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,396 | cpp | #include "wscMainModule.h"
#include <wcpp/lang/wsoLangService.h>
#include <wcpp/lang/service/wscLangService.h>
/*
*************************************************************************************************
* wscModule
*************************************************************************************************
*/
void wscModule::NewCurrentModule(wsiModule ** ret)
{
NewObj<wscMainModule>( ret );
}
/*
*************************************************************************************************
* wscMainModule
*************************************************************************************************
*/
const ws_char * const wscMainModule::s_class_name = "wcpp.wscom.main.wscMainModule";
wscMainModule::wscMainModule(void)
{
}
wscMainModule::~wscMainModule(void)
{
}
ws_result wscMainModule::IndexToClassId(ws_cid & rCid , ws_int index)
{
ws_result ret( WS_RLT_SUCCESS );
switch (index) {
case 0: rCid = wsoLangService::sCID; break;
default: ret = WS_RLT_CLASS_NOT_FOUND;
}
return ret;
}
ws_result wscMainModule::NewClassFactory(wsiFactory ** ret , const ws_cid & aClass)
{
if (aClass == wsoLangService::sCID) {
return NewObj<wscLangService::t_factory>( ret );
}
else {
return WS_RLT_CLASS_NOT_FOUND;
}
}
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
] | [
[
[
1,
60
]
]
] |
56dbb54bd43415a2275a89217c3dec669dc21bc0 | 41371839eaa16ada179d580f7b2c1878600b718e | /UVa/Volume CXV/11565.cpp | 44b4d881c28282e5e239bef29da64569b4ecc0f1 | [] | 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 | 601 | cpp | /////////////////////////////////
// 11565 - Simple Equations
/////////////////////////////////
#include<cstdio>
#include<cstdlib>
int A,B,C,cases;
int k,x,y,z,v1,v2,v3;
void solve(){
for(x = -B; x < B; x++){
if(!x || B%x) continue;
k = B/abs(x);
for(y = x+1; y < k; y++){
if(!y || B%y) continue;
v1 = (A-x-y);v1 *= v1;
v2 = B/x/y; v2*=v2;
v3 = C-x*x-y*y;
if(v1 == v2 && v2 == v3){ printf("%d %d %d\n",x,y,A-x-y); return;}
}
}
printf("No solution.\n");
}
int main(void){
scanf("%u\n",&cases);
while(cases--){
scanf("%d %d %d\n",&A,&B,&C);
solve();
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
29
]
]
] |
72f0d0f0e0ffaadfce7b17e4b6a6a71f0ad10faa | 8a223ca4416c60f4ad302bc045a182af8b07c2a5 | /Orders-ListeningFakeProblem-Cpp/Orders-Untouchable-Cpp/include/counted_ptr.h | 2481102767c86d3a4c9bbd0eab4275176042baf4 | [] | no_license | sinojelly/sinojelly | 8a773afd0fcbae73b1552a217ed9cee68fc48624 | ee40852647c6a474a7add8efb22eb763a3be12ff | refs/heads/master | 2016-09-06T18:13:28.796998 | 2010-03-06T13:22:12 | 2010-03-06T13:22:12 | 33,052,404 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,327 | h | /// ***************************************************************************
/// Copyright (c) 2009, Industrial Logic, Inc., All Rights Reserved.
///
/// This code is the exclusive property of Industrial Logic, Inc. It may ONLY be
/// used by students during Industrial Logic's workshops or by individuals
/// who are being coached by Industrial Logic on a project.
///
/// This code may NOT be copied or used for any other purpose without the prior
/// written consent of Industrial Logic, Inc.
/// ****************************************************************************
#ifndef COUNTED_PTR_H_
#define COUNTED_PTR_H_
/*
* counted_ptr - simple reference counted pointer.
*
* The is a non-intrusive implementation that allocates an additional
* int and pointer for every counted object.
*/
/* For ANSI-challenged compilers, you may want to #define
* NO_MEMBER_TEMPLATES or explicit */
//#define NO_MEMBER_TEMPLATES
#include <assert.h>
template <class X> class counted_ptr
{
public:
typedef X element_type;
explicit counted_ptr(X* p = 0) // Allocate a new counter
: itsCounter(0) {if (p) itsCounter = new counter(p);}
~counted_ptr()
{release();}
counted_ptr(const counted_ptr& r) throw()
{acquire(r.itsCounter);}
counted_ptr& operator=(const counted_ptr& r)
{
if (this != &r) {
release();
acquire(r.itsCounter);
}
return *this;
}
bool operator!() const {
return get()==0;
}
void* getCounter() const {
return itsCounter;
}
#ifndef NO_MEMBER_TEMPLATES
template <class Y>bool operator==(const counted_ptr<Y>& r) const {
return r.get()==get();
}
template <class Y> counted_ptr(const counted_ptr<Y>& r) throw()
{acquire(reinterpret_cast<counter*>(r.getCounter()));}
template <class Y> counted_ptr& operator=(const counted_ptr<Y>& r) {
if (this != &r) {
release();
acquire(r.itsCounter);
}
return *this;
}
#endif // NO_MEMBER_TEMPLATES
X& operator*() const throw() {
// Crash determinstically on NULL ptr...
assert(itsCounter != 0 && itsCounter->ptr != 0);
return *itsCounter->ptr;
}
X* operator->() const throw() {
// Crash determinstically on NULL ptr...
assert(itsCounter != 0 && itsCounter->ptr != 0);
return itsCounter->ptr;
}
X* get() const throw() {return itsCounter ? itsCounter->ptr : 0;}
bool unique() const throw()
{return (itsCounter ? itsCounter->count == 1 : true);}
private:
struct counter {
counter(X* p = 0, unsigned c = 1) : ptr(p), count(c) {}
X* ptr;
unsigned count;
}* itsCounter;
void acquire(counter* c) throw() {
// Increment the count
itsCounter = c;
if (c) ++c->count;
}
void release() {
// Decrement the count, delete if it is 0
if (itsCounter) {
if (--itsCounter->count == 0) {
delete itsCounter->ptr;
delete itsCounter;
}
itsCounter = 0;
}
}
};
#endif // COUNTED_PTR_H
| [
"chenguodong@localhost"
] | [
[
[
1,
111
]
]
] |
d87d1b79bcc31d29041a9f4b1ae7ba326f57850c | 1c4a1cd805be8bc6f32b0a616de751ad75509e8d | /jacknero/src/pku_src/1468/.svn/text-base/3584329_AC_1172MS_532K.cc.svn-base | 9046d6ec7aaeafdf910c3977a1ba906af0a4c309 | [] | no_license | jacknero/mycode | 30313261d7e059832613f26fa453abf7fcde88a0 | 44783a744bb5a78cee403d50eb6b4a384daccf57 | refs/heads/master | 2016-09-06T18:47:12.947474 | 2010-05-02T10:16:30 | 2010-05-02T10:16:30 | 180,950 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,556 | #include <iostream>
using namespace std;
struct Rectangle
{
int minx;
int maxx;
int miny;
int maxy;
};
int main()
{
int Area[5000],Area1[5000],a[5000];
Rectangle Rec[5000];
int i ,j ,temp ;
int num, Index ,sum;
while(scanf("%d",&num )!=EOF )
{
for(i=0; i<num; i++)
{
scanf("%d %d %d %d", &Rec[i].minx, &Rec[i].maxx, &Rec[i].miny, &Rec[i].maxy );
Area[i] = ( Rec[i].maxx - Rec[i].minx ) *( Rec[i].maxy-Rec[i].miny);
Area1[i] =Area[i];
}
for(i=0;i<num-1;i++)
{
int min=i;
for(j = i+1; j < num; j ++)
if( Area1[j] < Area1[min])
min = j;
temp = Area1[min];
Area1[min] = Area1[i];
Area1[i] = temp;
}
for(i = 0; i < num; i ++)
for(j=0 ; j < num; j ++)
if(Area1[i] == Area[j])
{
Area[j]=0;
a[i]=j;
break;
}
for(sum=0,j=0;j<num-1;j++)
for(i=j+1;i<num;i++)
if(Rec[a[j]].maxx<=Rec[a[i]].maxx&&Rec[a[j]].minx>=Rec[a[i]].minx
&&Rec[a[j]].maxy<=Rec[a[i]].maxy&&Rec[a[j]].miny>=Rec[a[i]].miny )
{
sum++;
break;
}
for(i=0;i<num-1;i++)
if(Rec[i].maxx==Rec[num-1].maxx && Rec[i].minx==Rec[num-1].minx
&&Rec[i].maxy==Rec[num-1].maxy&&Rec[i].miny==Rec[num-1].miny)
{
sum+=1;
break;
}
printf("%d\n",sum);
}
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
64
]
]
] |
|
a76c0da9d47dfc35529def3c544cb1eeb5aab84b | 30e4267e1a7fe172118bf26252aa2eb92b97a460 | /code/pkg_Core/Modules/ConfigXml/XmlUtil/XmlUtil.h | f64c3a7f9f0ac1dc6e72e14a3455c587602ad826 | [
"Apache-2.0"
] | permissive | thinkhy/x3c_extension | f299103002715365160c274314f02171ca9d9d97 | 8a31deb466df5d487561db0fbacb753a0873a19c | refs/heads/master | 2020-04-22T22:02:44.934037 | 2011-01-07T06:20:28 | 2011-01-07T06:20:28 | 1,234,211 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 22,403 | h | // https://sourceforge.net/projects/x3c/
//
// 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.
//! \file XmlUtil.h
//! \brief 定义MSXML4.0 DOM 操作类CXmlUtil
#ifndef __XMLUTIL_NONMFC_INCLUDED_
#define __XMLUTIL_NONMFC_INCLUDED_
#pragma once
#include "XTPXMLhelpers.h"
//! XML文件加解密的接口
interface IXmlFileCrypt
{
//! 装载一个加密的XML文件
/*!
\param[out] doc 输出新的XML文档对象
\param[in] pszFileName 文件全名,可以是能输出XML内容的URL地址
\return 是否装载成功,如果失败将由CXmlUtil按普通方式装载
*/
virtual bool Decrypt(CXTPDOMDocumentPtr& doc, LPCWSTR pszFileName) = 0;
//! 对一个刚保存的XML文件进行加密
/*!
\param[in] pszFileName 本地的文件全名
\return 是否执行成功
*/
virtual bool CryptFile(LPCWSTR pszFileName) = 0;
};
//! MSXML4.0 DOM 操作类, 不需要MFC支持
class CXmlUtil
{
public:
//--------------------------------------
// 文件操作
//--------------------------------------
//! 创建一个XML文档对象
/*! 新创建的XML文档对象还未保存到文件中
\param[out] doc 输出新的XML文档对象
\param[in] pszRootName 根节点名称,用于自动创建根节点
\param[in] pszEncoding XML语言编码,默认为Unicode格式的“UTF-8”
\param[in] pszNameSpace XML命名空间
\param[in] pszComment 根节点的说明内容
\return 是否创建成功
*/
static bool NewXMLFile(
CXTPDOMDocumentPtr& doc,
LPCWSTR pszRootName,
LPCWSTR pszEncoding = L"UTF-8",
LPCWSTR pszNameSpace = L"",
LPCWSTR pszComment = L"");
//! 创建一个XML文档对象,并得到根节点
/*! 新创建的XML文档对象还未保存到文件中
\param[out] doc 输出新的XML文档对象
\param[in] root 输出根节点对象
\param[in] pszRootName 根节点名称,用于自动创建根节点
\param[in] pszEncoding XML语言编码,默认为Unicode格式的“UTF-8”
\param[in] pszNameSpace XML命名空间
\return 是否创建成功
*/
static bool NewXMLFile2(
CXTPDOMDocumentPtr& doc,
CXTPDOMElementPtr& root,
LPCWSTR pszRootName,
LPCWSTR pszEncoding = L"UTF-8",
LPCWSTR pszNameSpace = L"");
//! 装载一个XML文件
/*!
\param[out] doc 输出新的XML文档对象
\param[in] pszFileName 文件全名,可以是能输出XML内容的URL地址
\param[in] pCryptHandler 加解密的操作对象
\return 是否装载成功,失败原因是不能读取文件或不能创建XML文档对象
*/
static bool LoadXMLFile(
CXTPDOMDocumentPtr& doc,
LPCWSTR pszFileName,
IXmlFileCrypt* pCryptHandler = NULL);
//! 装载一个XML文件,并检查根节点
/*!
\param[out] doc 输出新的XML文档对象
\param[in] pszFileName 文件全名,可以是能输出XML内容的URL地址
\param[in] root 输出根节点对象
\param[in] pszRootName 根节点名称
\param[in] pCryptHandler 加解密的操作对象
\return 是否装载成功,失败原因是不存在指定的根节点等错误
*/
static bool LoadXMLFile(
CXTPDOMDocumentPtr& doc,
LPCWSTR pszFileName,
CXTPDOMElementPtr& root,
LPCWSTR pszRootName,
IXmlFileCrypt* pCryptHandler = NULL);
//! 保存到一个XML文件
/*!
\param[in] doc 要保存的XML文档对象
\param[in] pszFileName 文件全名
\param[in] pCryptHandler 加解密的操作对象
\return 是否保存成功
*/
static bool SaveXMLFile(
const CXTPDOMDocumentPtr& doc,
LPCWSTR pszFileName,
IXmlFileCrypt* pCryptHandler = NULL);
//! 从字符串中装载XML文件
/*!
\param[out] doc 输出新创建的XML文档对象
\param[in] pszXML XML格式的字符串
\return 是否装载成功
*/
static bool LoadXMLFromString(
CXTPDOMDocumentPtr& doc,
LPCSTR pszXML);
//! 从字符串中装载XML文件,自动跳过Unicode前缀标志
/*!
\param[out] doc 输出新创建的XML文档对象
\param[in] pszXML XML格式的字符串
\return 是否装载成功
*/
static bool LoadXMLFromString(
CXTPDOMDocumentPtr& doc,
LPCWSTR pszXML);
//! 获取XML字符串
/*!
\param[in] doc XML文档对象
\return XML格式的字符串
\see GetNodeXMLString
*/
static std::wstring GetXMLString(
const CXTPDOMDocumentPtr& doc);
//! 获取根节点名称
/*!
\param[in] doc XML文档对象
\return 根节点名称
\see GetTagName
*/
static std::wstring GetRootName(
const CXTPDOMDocumentPtr& doc);
//--------------------------------------
// 节点操作
//--------------------------------------
//! 得到根节点
/*!
\param[out] root 输出XML根节点对象
\param[in] doc XML文档对象
\param[in] pszRootName 根节点名称
\return 是否存在给定名称的根节点
\see GetRootName
*/
static bool GetRoot(
CXTPDOMElementPtr& root,
const CXTPDOMDocumentPtr& doc,
LPCWSTR pszRootName);
//! 得到子节点个数
/*!
\param[in] ele XML元素对象
\param[in] pszChildName 子元素名称
\return 给定元素ele下的名称为pszChildName的子节点个数
*/
static long GetChildCount(
const CXTPDOMElementPtr& ele,
LPCWSTR pszChildName);
//! 得到一个子节点
/*!
\param[out] outEle 输出子元素对象
\param[in] parent XML元素对象
\param[in] pszChildName 子元素名称
\param[in] nIndex 第几个子元素,从0开始
\return 是否有对应的子元素对象
*/
static bool GetChild(
CXTPDOMElementPtr& outEle,
const CXTPDOMElementPtr& parent,
LPCWSTR pszChildName,
long nIndex = 0);
//! 得到或创建一个子节点
/*!
\param[out] outEle 输出子元素对象
\param[in] doc XML文档对象
\param[in] parent XML元素对象
\param[in] pszChildName 子元素名称
\return 是否执行成功
*/
static bool GetChildOrAdd(
CXTPDOMElementPtr& outEle,
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& parent,
LPCWSTR pszChildName);
//! 添加一个子节点
/*!
\param[out] outEle 输出子元素对象
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszChildName 子元素名称
\return 是否执行成功
*/
static bool AddChild(
CXTPDOMElementPtr& outEle,
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszChildName);
//! 删除一个子节点
/*!
\param[in] ele XML元素对象
\param[in] pszChildName 子元素名称
\param[in] nIndex 要删除第几个子元素,从0开始
\return 是否有对应的子元素对象被删除
*/
static bool DelChild(
const CXTPDOMElementPtr& ele,
LPCWSTR pszChildName,
long nIndex);
//! 删除一个子节点
/*!
\param[in] parent XML父元素对象
\param[in,out] eleDel 要删除的XML子元素对象
\return 是否有对应的子元素对象被删除
*/
static bool DelChild(
const CXTPDOMElementPtr& parent,
CXTPDOMElementPtr& eleDel);
//! 删除所有子节点
/*! 删除给定元素下的所有名称为pszChildName的子节点
\param[in] ele XML元素对象
\param[in] pszChildName 子元素名称
\param[in] pszAttrName 子元素的标识属性名,可选值
\param[in] pszAttrValue 标识属性名对应的值,pszAttrName不为空时有效
\return 删除的子元素个数
*/
static long DelChildren(
const CXTPDOMElementPtr& ele,
LPCWSTR pszChildName,
LPCWSTR pszAttrName = L"", LPCWSTR pszAttrValue = L"");
//! 查找节点数组中的子节点序号
/*!
\param[out] outEle 输出查找到的子元素对象
\param[in] parent XML元素对象,在该节点下查找
\param[in] pszElement 子元素名称
\param[in] pszField 子元素的下一级元素名称
\param[in] pszValue 子元素的下一级元素的内容
\return 找到的是第几个子元素,-1表示找不到
*/
static long FindElement(
CXTPDOMElementPtr& outEle,
const CXTPDOMElementPtr& parent,
LPCWSTR pszElement,
LPCWSTR pszField,
LPCWSTR pszValue);
//! 查找节点数组中的子节点序号
/*! 查找元素parent的子元素节点,条件是该子元素中有名称为pszAttr1、
内容为pszValue1的属性节点,可以有两个属性条件。\n
下面是数组内容示例:\n
\<parent_item\>\n
\<item id="12" type="font" other=""\>\<otherinfo/\>\</item\>\n
\<item id="34" type="char" other=".."\>\<otherinfo/\>\</item\>\n
\<item id="34" type="para" other="info"\>\<otherinfo/\>\</item\>\n
\</parent_item\>\n
调用FindElement(outEle, parent, "item", "id", "34", "type", "char")返回1
\param[out] outEle 输出查找到的子元素对象
\param[in] parent XML元素对象,在该节点下查找
\param[in] pszElement 子元素名称
\param[in] pszAttr1 子元素的属性名称
\param[in] pszValue1 子元素的属性值
\param[in] pszAttr2 子元素的另一个属性名称,为空则忽略
\param[in] pszValue2 子元素的另一个属性对应的值,pszAttr2不为空时有效
\return 找到的是第几个子元素,-1表示找不到
*/
static long FindElementByAttr(
CXTPDOMElementPtr& outEle,
const CXTPDOMElementPtr& parent,
LPCWSTR pszElement,
LPCWSTR pszAttr1,
LPCWSTR pszValue1,
LPCWSTR pszAttr2,
LPCWSTR pszValue2);
//--------------------------------------
// 节点内容
//--------------------------------------
//! 得到节点的名称
/*!
\param[in] ele XML元素对象
\return 给定节点的XML标记名称
\see GetRootName
*/
static std::wstring GetTagName(
const CXTPDOMElementPtr& ele);
//! 得到节点内容,识别CDATA
/*! 节点的内容既可以是简单的文字内容,也可以是CDATA节点
\param[in] pNode XML元素对象
\param[in] pszDefault 节点内容的默认值
\return 给定节点的内容
*/
static std::wstring GetText(
const CXTPDOMNodePtr& pNode,
LPCWSTR pszDefault = L"");
//! 得到一个节点的CDATA值
/*!
\param[in] ele XML元素对象
\param[in] pszDefault 节点的CDATA内容的默认值
\return 该节点的CDATA内容
*/
static std::wstring GetTextCDATA(
const CXTPDOMElementPtr& ele,
LPCWSTR pszDefault = L"");
//! 设置节点内容
/*!
\param[in] pNode XML元素对象
\param[in] pszText 给定节点的内容
\return 是否设置成功
*/
static bool SetText(
const CXTPDOMNodePtr& pNode,
LPCWSTR pszText);
//! 设置节点内容
/*!
本函数用于不论是否定义了_UNICODE条件编译宏,都能直接设置宽字节字符串内容,
避免在ANSI编译模式下将LPCWSTR转换为BSTR时自动进行编码转换而出现乱码。
使用情况举例:从非UNICODE文本文件中读取单字节字符流,用MultiByteToWideChar
函数转换为宽字节字符串,再用本函数设置节点内容,这样就能将特定语言编码的
内容转换为UNICODE的XML内容。
\param[in] pNode XML元素对象
\param[in] pszText 给定节点的UNICODE内容,末尾有零结束符
\return 是否设置成功
*/
static bool SetTextW(
const CXTPDOMNodePtr& pNode,
LPCWSTR pszText);
//! 设置一个节点的CDATA值
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszValue 节点的CDATA内容
\return 是否设置成功
*/
static bool SetTextCDATA(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszValue);
//! 获取一个节点的XML字符串
/*!
\param[in] ele XML元素对象
\return XML字符串
\see GetXMLString
*/
static std::wstring GetNodeXMLString(
const CXTPDOMElementPtr& ele);
//--------------------------------------
// 属性操作
//--------------------------------------
//! 删除一个属性
/*!
\param[in] ele XML元素对象
\param[in] pszName 要删除的属性名称
\return 是否删除了属性
*/
static bool DelAttribute(
const CXTPDOMElementPtr& ele,
LPCWSTR pszName);
//! 得到一个属性节点内容
/*!
\param[in] ele XML元素对象
\param[in] pszName 该元素的属性节点名称
\param[in] pszDefault 属性内容的默认值
\return 该元素的属性内容
*/
static std::wstring GetAttribute(
const CXTPDOMElementPtr& ele,
LPCWSTR pszName,
LPCWSTR pszDefault = L"");
//! 得到一个属性节点整数内容
/*!
\param[in] ele XML元素对象
\param[in] pszName 该元素的属性节点名称
\param[in] nDef 属性内容的默认整数值
\return 该元素的属性内容整数值
*/
static UINT GetAttributeInt(
const CXTPDOMElementPtr& ele,
LPCWSTR pszName,
INT nDef = 0);
//! 得到一个属性节点布尔值内容
/*!
\param[in] ele XML元素对象
\param[in] pszName 该元素的属性节点名称
\param[in] bDef 属性内容的默认布尔值
\return 该元素的属性内容布尔值
*/
static bool GetAttributeBool(
const CXTPDOMElementPtr& ele,
LPCWSTR pszName,
BOOL bDef = FALSE);
//! 得到一个属性节点浮点型内容
/*!
\param[in] ele XML元素对象
\param[in] pszName 该元素的属性节点名称
\param[in] dDef 属性内容的默认浮点型值
\param[out] pstrUnit 如果传入变量地址,则存放属性内容尾部的的单位名称
\return 该元素的属性内容浮点型值
*/
static double GetAttributeFloat(
const CXTPDOMElementPtr& ele,
LPCWSTR pszName,
double dDef = 0,
std::wstring* pstrUnit = NULL);
//! 设置一个属性节点内容
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszName 该元素的属性节点名称,没有则自动创建属性节点
\param[in] pszValue 属性内容
\return 是否设置成功
*/
static bool SetAttribute(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszName,
LPCWSTR pszValue);
//! 设置一个属性节点整数内容
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszName 该元素的属性节点名称,没有则自动创建属性节点
\param[in] nVal 属性的整数内容
\return 是否设置成功
*/
static bool SetAttributeInt(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszName,
INT nVal);
//! 设置一个属性节点布尔值属性值
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszName 该元素的属性节点名称,没有则自动创建属性节点
\param[in] bVal 属性的布尔内容,自动转换成“true”或“false”
\return 是否设置成功
*/
static bool SetAttributeBool(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszName,
BOOL bVal);
//! 设置一个属性节点浮点型内容
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszName 该元素的属性节点名称,没有则自动创建属性节点
\param[in] dVal 属性的浮点型内容
\param[in] pszUnit 在属性内容尾部附加的单位名称,为空则忽略
\param[in] decimal 保留小数点后第几位数,超出部分四舍五入
\return 是否设置成功
*/
static bool SetAttributeFloat(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszName,
double dVal,
LPCWSTR pszUnit = L"",
int decimal = 4);
//! 得到一个节点的属性值,识别CDATA
/*! 子节点的内容既可以是简单的文字内容,也可以是CDATA节点
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称
\param[in] pszDefault 子节点内容的默认值
\return 该子节点的内容
*/
static std::wstring GetField(
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
LPCWSTR pszDefault = L"");
//! 设置一个节点的属性值
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称,没有则自动创建节点
\param[in] pszValue 子节点内容
\return 是否设置成功
*/
static bool SetField(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
LPCWSTR pszValue);
//! 得到一个节点的整数属性值,识别十六进制数
/*!
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称
\param[in] nDef 子节点内容的默认整数值
\return 该子节点内容整数值
*/
static UINT GetFieldInt(
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
INT nDef = 0);
//! 得到一个节点的布尔值属性值
/*!
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称
\param[in] bDef 子节点内容的默认布尔值
\return 该子节点内容布尔值
*/
static bool GetFieldBool(
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
BOOL bDef = FALSE);
//! 得到一个节点的浮点型属性值
/*!
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称
\param[in] dDef 子节点内容的默认浮点型值
\param[out] pstrUnit 如果传入变量地址,则存放子节点内容尾部的的单位名称
\return 该子节点内容浮点型值
*/
static double GetFieldFloat(
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
double dDef = 0,
std::wstring* pstrUnit = NULL);
//! 设置一个节点的整数属性值
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称,没有则自动创建节点
\param[in] nVal 子节点的整数内容
\return 是否设置成功
*/
static bool SetFieldInt(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
INT nVal);
//! 设置一个节点的布尔值属性值
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称,没有则自动创建节点
\param[in] bVal 子节点的布尔内容,自动转换成“true”或“false”
\return 是否设置成功
*/
static bool SetFieldBool(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
BOOL bVal);
//! 设置一个节点的浮点型属性值
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称,没有则自动创建节点
\param[in] dVal 子节点的浮点型内容
\param[in] pszUnit 在子节点内容尾部附加的单位名称,为空则忽略
\param[in] decimal 保留小数点后第几位数,超出部分四舍五入
\return 是否设置成功
*/
static bool SetFieldFloat(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
double dVal,
LPCWSTR pszUnit = L"",
int decimal = 4);
//! 设置一个节点的十六进制属性值
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称,没有则自动创建节点
\param[in] nVal 子节点的整数内容
\param[in] nDigits 当为1到6时,整数字符串至少有指定个数字,不够就在前补零,例如"0x00012A"
\return 是否设置成功
*/
static bool SetFieldHex(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
INT nVal,
INT nDigits = 0);
//! 得到一个节点的CDATA属性值
/*!
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称
\param[in] pszDefault 子节点的CDATA内容的默认值
\return 该子节点的CDATA内容
*/
static std::wstring GetFieldCDATA(
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
LPCWSTR pszDefault = L"");
//! 设置一个节点的CDATA属性值
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszFieldName 该元素的子元素节点名称,没有则自动创建节点
\param[in] pszValue 子节点的CDATA内容
\return 是否设置成功
*/
static bool SetFieldCDATA(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszFieldName,
LPCWSTR pszValue);
//--------------------------------------
// 其他操作
//--------------------------------------
//! 返回上次调用的HRESULT值
static HRESULT GetLastErrorResult();
//! 在根节点前创建注释节点
/*!
\param[in] doc XML文档对象
\param[in] pszComment 注释内容
\return 是否执行成功
*/
static bool CreateDocComment(
const CXTPDOMDocumentPtr& doc,
LPCWSTR pszComment);
//! 在指定节点前创建注释节点
/*!
\param[in] doc XML文档对象
\param[in] ele XML元素对象
\param[in] pszComment 注释内容
\return 是否执行成功
*/
static bool CreateNodeComment(
const CXTPDOMDocumentPtr& doc,
const CXTPDOMElementPtr& ele,
LPCWSTR pszComment);
//! 得到四舍五入的字符串(去掉小数点后末尾的'0')
/*!
\param[in] value 要转换的浮点数
\param[in] decimal 保留小数点后第几位数,超出部分四舍五入
\return 转换后的字符串
*/
static std::wstring RoundStr(
double value,
int decimal = 4);
};
#endif // __XMLUTIL_NONMFC_INCLUDED_ | [
"rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3"
] | [
[
[
1,
708
]
]
] |
8a76263d3965968eb31d1bffdbc9bf7bfccb8d53 | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /ConfigurationManager.cpp | 054365eabc8bfb232c09812a81490326af91e630 | [] | 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 | 1,720 | 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 "ConfigurationManager.h"
ConfigurationManager::ConfigurationManager()
{
}
ConfigurationManager::~ConfigurationManager()
{
}
//=== ITranslationManager
void ConfigurationManager::RegisterConfigurable(IConfigurable& configurable)
{
m_configurables.insert(&configurable);
}
void ConfigurationManager::UnRegisterConfigurable(IConfigurable& configurable)
{
std::set<IConfigurable*>::iterator it = m_configurables.find(&configurable);
if (it != m_configurables.end())
m_configurables.erase(it);
else
ASSERT(0);
}
void ConfigurationManager::UpdateConfigurables()
{
std::set<IConfigurable*>::iterator it = m_configurables.begin();
for (;it != m_configurables.end(); it++)
(*it)->UpdateConfiguration();
}
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
] | [
[
[
1,
55
]
]
] |
f041b84d1a542cbfd17f4ab8a59d6bbef6ad113f | 5d3c1be292f6153480f3a372befea4172c683180 | /trunk/Event Heap/c++/Mac OS X/samples/1_tutorial/tutorial.cpp | f737ad7afe27674af7e3da15c7f15e7e6e8c89a2 | [
"Artistic-2.0"
] | permissive | BackupTheBerlios/istuff-svn | 5f47aa73dd74ecf5c55f83765a5c50daa28fa508 | d0bb9963b899259695553ccd2b01b35be5fb83db | refs/heads/master | 2016-09-06T04:54:24.129060 | 2008-05-02T22:33:26 | 2008-05-02T22:33:26 | 40,820,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,242 | cpp | #include <eh2.h> // include eh2 package
#include <idk_io.h> // include idk_io package
class Tutorial : protected eh2_Consts
// by inheriting eh2_Consts, you can omit prefix eh2_Const::
// when you use constant values.
{
public:
void initialize()
{
// initialize the event heap client library.
// you can specify appName and deviceName, but you don't have to.
eh2_init(NULL, NULL);
//
// if you want to trace the activity of the library,
// set up the tracer.
//
// create a tracer. keep it in a smart pointer.
eh2_TracerPtr tracerPtr = eh2_Tracer::cs_create(
idk_io_FileOutStream::cs_createBufferedByFileName("trace.txt"),
TMM_ALL
);
// set the tracer.
eh2_Tracer::cs_setTracer(tracerPtr);
}
void finalize()
{
// gracefully finalize the library.
eh2_finalize();
}
eh2_EventHeapPtr createEventHeap()
{
// at first, get the event heap factory.
// you can get only the reference to the factory because it is the
// singleton. you are not responsible for releasing it.
eh2_EventHeapFactory* factory = eh2_EventHeapFactory::cs_getInstance();
// then, ask to the factory for creating the event heap client instance.
// you have the ownership of the returned object, so you have to keep it
// in smart pointer.
eh2_EventHeapPtr eventHeapPtr = factory->createEventHeap(
NULL, // not specifying source name
"localhost", // event heap host
-1 // default port
);
// when you return an object with ownership, the return type must be
// smart pointer. the caller must receive it by smart pointer also.
return eventHeapPtr;
}
void doPutEvent(eh2_EventHeap* eh)
{
// this function does not have the ownership of the event heap but only use it,
// so the parameter type should be normal pointer.
// create a new event object. keep it in smart pointer.
eh2_EventPtr eventPtr = eh2_Event::cs_create("MyEventType");
// you can set values to the event like this.
eventPtr->setPostValueString("NAME", "Tomoto Shimizu");
eventPtr->setPostValueInt("AGE", 30);
// then, put it.
eh->putEvent(eventPtr);
// (note the passed event may be modified since autoset values
// are set. if you examine the event after this call, you will
// see the exact values which has been sent.)
// let's put a couple more.
eventPtr->setPostValueString("NAME", "Ryusuke Ito");
eventPtr->setPostValueInt("AGE", 32);
eh->putEvent(eventPtr);
eventPtr->setPostValueString("NAME", "Itaru Nishizawa");
eventPtr->setPostValueInt("AGE", 34);
eh->putEvent(eventPtr);
}
void printEvent(const char* title, const eh2_Event* event)
{
// now let's discuss about how to retrieve values in a event.
// you can get the type of this event like this.
const char* eventType = event->getEventType();
if (strcmp(event->getEventType(), "MyEventType") != 0) {
// now we leave events which are not our concern.
printf("%s: unknown event type %s\n", title, eventType);
return;
}
// this is the easiest way to get a value.
// if something is wrong, an exception should occur.
const char* name = event->getPostValueString("NAME");
// if you want to be more careful, the following is the complete way.
int age = -1;
const eh2_Field* field = event->getField("AGE");
if (field == NULL) {
// the event has no AGE field.
}
else if (! field->getType()->equals(eh2_FieldType::cs_int())) {
// the field is not expected type.
}
else if (field->getPostValueType() != FVT_ACTUAL) {
// the field does not have an actual value.
}
else if (field->isPostValueNull()) {
// the content of the actual value is null.
}
else {
// the field has a non-null actual value.
age = field->getPostValueInt();
}
// you can access to standard fields by using eh2_Consts::FN_XXX.
int seq = event->getPostValueInt(FN_SEQUENCENUM);
const char* source = event->getPostValueString(FN_SOURCE);
printf("%s: SOURCE=%s SEQ=%d NAME=%s AGE=%d\n", title, source, seq, name, age);
}
void printEventsInXML(const char* file, const eh2_EventCollection* events)
{
// this is a convenient way to debug -- outputs the events content
// in XML format.
// create an output stream
idk_io_IByteOutStreamPtr outStreamPtr =
idk_io_FileOutStream::cs_createBufferedByFileName(file);
// create the event-to-XML converter
eh2_EventToXMLPtr converterPtr = eh2_EventToXML::cs_create();
converterPtr->convert(outStreamPtr, events);
}
void doWaitForEvent(eh2_EventHeap* eh)
{
// create a new event object to use as template.
eh2_EventPtr templatePtr = eh2_Event::cs_create();
templatePtr->setEventType("MyEventType"); // yet another way to set event type
templatePtr->setTemplateValueInt("AGE", 30); // we'll search 30-year-old stuff.
// the following does exactly the same as above in the normalized way.
// first, create (or retrieve if exists) a field.
// then, set the value to the field.
eh2_Field* field;
field = templatePtr->allocateField("AGE", eh2_FieldType::cs_int());
field->setTemplateValueInt(30);
// if you want to set the value to some special value like,
// you should do as follows, using the normalized way mentioned above.
field = templatePtr->allocateField("NAME", eh2_FieldType::cs_string());
field->setTemplateValueType(FVT_FORMAL);
// as long as you are sure that the field is already exist, you can set
// special value like this also. note that it raises an error if the
// field does not exist, unlike when setting actual values.
templatePtr->setTemplateValueType("NAME", FVT_FORMAL);
// invoke the waitForEvent operation.
// again, you must keep the returned event in a smart pointer.
eh2_EventPtr resultEventPtr = eh->waitForEvent(templatePtr);
// (note: during this call, the passed template may be modified
// since autoset values were supplied. if you examine the template
// events after the call, you will see exact values which was sent
// to the server.)
// we'll discuss about how to retrieve values in events in this function.
printEvent("doWaitForEvent", resultEventPtr);
}
void doGetAll(eh2_EventHeap* eh)
{
// here you will see how to handle event collections.
// invoke getAll operation. it results a collection of events.
// keep it in a smart pointer.
eh2_EventCollectionPtr eventsPtr = eh->getAll();
int i;
for (i = 0; i < eventsPtr->size(); i++) {
// use get(i) method to see an event in the collection.
const eh2_Event* event = eventsPtr->get(i);
// you can also use a smart pointer to assign the return value of get(i).
// it is useful in case you want to "carry" the event still after the
// collection is discarded.
// e.g. eh2_EventPtr eventPtr = eventsPtr->get(i);
printEvent("doGetAll", event);
}
}
void doGetEvent2(eh2_EventHeap* eh)
{
// now let's see how to use a number of templates for getEvent etc.
// create an event collection by yourself.
eh2_EventCollectionPtr templatesPtr = eh2_EventCollection::cs_create();
// create a template event.
eh2_EventPtr templatePtr;
templatePtr = eh2_Event::cs_create("MyEventType");
templatePtr->setTemplateValueInt("AGE", 32);
// add the template to the collection. the template will obtain the
// ownership of the passed event, so you may release your smart poitner.
templatesPtr->add(templatePtr);
// let's add another template.
templatePtr = eh2_Event::cs_create("MyEventType");
templatePtr->setTemplateValueInt("AGE", 34);
templatesPtr->add(templatePtr);
// then invoke getEvent.
eh2_EventPtr resultEventPtr;
resultEventPtr = eh->getEvent(templatesPtr, NULL);
printEvent("doGetEvent2", resultEventPtr);
// you can examine which templates matched to the retrieved event
// by following the steps below.
// create another event collection.
eh2_EventCollectionPtr matchedTemplatePtr = eh2_EventCollection::cs_create();
// pass the collection as the 2nd argument of getEvent.
resultEventPtr = eh->getEvent(templatesPtr, matchedTemplatePtr);
if (resultEventPtr != NULL) {
printEvent("doGetEvent2", resultEventPtr);
// when an event is returned, the matched templates are set to
// the matchedTemplate.
printEventsInXML("matchedEventsOfDoGetEvents2.xml", matchedTemplatePtr);
}
}
};
int main(int argc, char* argv[]) {
Tutorial test;
test.initialize();
try {
eh2_EventHeapPtr eventHeapPtr = test.createEventHeap();
// never forget to assign objects which you own to smart pointer.
test.doPutEvent(eventHeapPtr);
// you can pass smart pointers to a parameter whose type is normal
// pointer. it means you "show" (not "give") the object to the function.
test.doWaitForEvent(eventHeapPtr);
test.doGetAll(eventHeapPtr);
test.doGetEvent2(eventHeapPtr);
}
catch (idk_ut_Exception& ex) {
puts(ex.getMessage());
}
test.finalize();
fprintf(stderr, "press ENTER to finish\n");
getchar();
return 0;
}
| [
"ballagas@2a53cb5c-8ff1-0310-8b75-b3ec22923d26",
"reiny@2a53cb5c-8ff1-0310-8b75-b3ec22923d26"
] | [
[
[
1,
162
],
[
164,
285
]
],
[
[
163,
163
]
]
] |
6b67a29f11858479af9e3217d086aba2e9cd9c0c | db4b7dac5ea1593f60229f4dd916e4d275d2f6ac | /VirtualDrafter.cpp | 94b8df8621ed2970abafcf00c5f4a6ecce267c2a | [] | no_license | riyuexing/virtualdrafter | 77337e757ea41bb2e3b184a123627a69cc47b5e6 | 1e8de27bb176b395c2220de71f8360424d85be9a | refs/heads/master | 2022-04-05T12:19:08.060306 | 2009-05-09T11:21:02 | 2018-01-07T20:11:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
USERES("VirtualDrafter.res");
USEFORM("main.cpp", fmMain);
USEFORM("Pick.cpp", fmPick);
USEUNIT("CardData.cpp");
USEUNIT("db.cpp");
USEUNIT("MyStrUtil.cpp");
USEUNIT("Player.cpp");
USEUNIT("CardValues.cpp");
USEUNIT("DrawMTGC.cpp");
USEFORM("Options.cpp", fmOptions);
USEUNIT("NetPlayer.cpp");
USEFORM("Server.cpp", fmServer);
USEFORM("Client.cpp", fmClient);
USEFORM("About.cpp", AboutBox);
//---------------------------------------------------------------------------
WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
try
{
Application->Initialize();
Application->Title = "VirtualDrafter";
Application->CreateForm(__classid(TfmMain), &fmMain);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
return 0;
}
//---------------------------------------------------------------------------
| [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
c20d80d777a8ce0a877d69f8fe3b70b55954e06c | d9bf74086d94169f0e0c9e976965662f6639a9ae | /src/game.cpp | fe9ba3206223c64990386db7d4c2532016eda925 | [] | no_license | th0m/projet-genie-logiciel-gstl | 75e77387b95c328f7e34428ca4f4b74198774d10 | c2d283897d36ba2e5bf4ec0bf3dbea6ab65884a8 | refs/heads/master | 2021-01-25T09:00:30.529804 | 2011-04-19T21:22:12 | 2011-04-19T21:22:12 | 32,145,361 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 10,834 | cpp | #include "game.hpp"
#include "r1.hpp"
#include "r2.hpp"
#include "r3.hpp"
#include "score.hpp"
#include <SDL/SDL_image.h>
#include <stdexcept>
#include <iostream>
/* On initialise les variables statiques constantes */
const Uint32 Game::m_width = 600;
const Uint32 Game::m_height = 400;
const Uint32 Game::m_shapeSize = 20;
const Uint32 Game::m_turboTime = 2000;
const Uint32 Game::m_time2SpeedMax = 1000;
const float Game::m_fwdSpeed = 2;
const float Game::m_revSpeed = m_fwdSpeed / 2;
const Uint32 Game::m_nbLap = 2;
float Game::m_speedIA = 1;
const std::string Game::m_title = "Projet Genie Logiciel 3A - GSTL";
const Uint32 Game::m_framerate = 60;
const float Game::m_difficultyIApercentage = 0.30;
Uint32 Game::time_left(Uint32 &next_time)
{
Uint32 now;
now = SDL_GetTicks();
if(next_time <= now)
return 0;
else
return next_time - now;
}
Game::Game()
: m_currentRace(NULL), m_isOk(true), m_window(NULL), m_ico(NULL),
m_rNumber(Race1), m_score(0)
{
/* # Chargement des composants vidéos de la librairie */
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
/* # On charge et on place l'icone de l'application */
m_ico = IMG_Load("sprites/gstl");
SDL_WM_SetIcon(m_ico, NULL);
/* # On utilise le double-buffering et la mémoire vidéo */
m_window = SDL_SetVideoMode(m_width, m_height, 16, SDL_HWSURFACE | SDL_DOUBLEBUF);
if(m_window == NULL)
{
/* # On gère correctement les erreurs qui peuvent se produire */
fprintf(stderr, "SDL_SetVideoMode failed with this error : %s.\n", SDL_GetError());
/* On oublie pas de quitter proprement avec un appel explicite au destructeur */
this->~Game();
/* # On informe le code appelant que la construction c'est mal passée */
throw std::runtime_error("SDL_SetVideoMode failed.");
}
/* # On renome la fenetre */
SDL_WM_SetCaption(m_title.c_str(), NULL);
/* # On commence par la première course */
m_currentRace = new R1(m_window);
}
Game::~Game()
{
/* # On detruit les courses */
delete m_currentRace;
/* # On décharge la librarie proprement à la mort de l'instance du jeux */
SDL_Quit();
}
void Game::start()
{
/* # Chargement du niveau */
m_currentRace->load();
eventloop();
}
void Game::updateEvents(Input* in, bool& continuer)
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_KEYDOWN:
in->key[event.key.keysym.sym] = 1;
break;
case SDL_KEYUP:
in->key[event.key.keysym.sym] = 0;
break;
case SDL_QUIT:
continuer = false;
break;
default:
break;
}
}
}
void Game::eventloop()
{
int nbLap = 0;
Input in = {0};
bool continuer = true, launchIAs = false;
Uint32 tick_interval = 1000 / m_framerate, beforefwd = SDL_GetTicks(),
beforerev = SDL_GetTicks(), next_time = SDL_GetTicks() + tick_interval, turbo = 0,
turbotime = m_turboTime, collision = SDL_GetTicks();
m_currentRace->initNbLapCompetitors();
while(continuer)
{
/* # On met a jour le tableau des touches enfoncees */
updateEvents(&in, continuer);
/* # On rafraichit l'affichage et on deplace l'IA */
m_currentRace->actualize();
if(launchIAs)
m_currentRace->moveIAs();
if(SDL_GetTicks() >= collision + m_time2SpeedMax || SDL_GetTicks() >= turbo + turbotime || !m_currentRace->getPlayerCar()->isFlaque())
m_currentRace->getPlayerCar()->setNormalState();
if(turbo != 0 && SDL_GetTicks() >= turbo + turbotime)
{
turbo = 0;
turbotime = m_turboTime;
}
if(SDL_GetTicks() < turbo + turbotime && turbo != 0)
m_currentRace->getPlayerCar()->setTurboMode();
if(SDL_GetTicks() < collision + m_time2SpeedMax)
{
if(m_currentRace->getPlayerCar()->isTurbo())
turbo = 0, turbotime = m_turboTime;
m_currentRace->getPlayerCar()->setCollisionRecovering();
}
if(m_currentRace->getPlayerCar()->isFlaque())
{
if(m_currentRace->getPlayerCar()->isTurbo())
turbo = 0, turbotime = m_turboTime;
m_currentRace->getPlayerCar()->setFlaqueState();
}
m_currentRace->getPlayerCar()->setSpeed();
/* # Tant qu'on est bloque on affecte le timer au temps courant */
if(m_currentRace->getPlayerCar()->isBlocked())
collision = SDL_GetTicks();
/* # Tant qu'on n'enfonce pas la touche pour avancer ou reculer ou les deux on affecte nos tick au temps actuel */
if(!in.key[SDLK_UP])
beforefwd = SDL_GetTicks();
if(!in.key[SDLK_DOWN])
beforerev = SDL_GetTicks();
if(in.key[SDLK_UP] && in.key[SDLK_DOWN])
{
beforefwd = SDL_GetTicks();
beforerev = SDL_GetTicks();
}
/* # Si on appuie sur la touche pour avancer sans appuyer sur celle pour reculer on va pouvoir avancer */
if(in.key[SDLK_UP] && !in.key[SDLK_DOWN])
{
/* # On attend une seconde avant de demarrer */
if(SDL_GetTicks() > (beforefwd + m_time2SpeedMax))
{
launchIAs = true;
m_currentRace->movePlayerCar(SDLK_UP);
if(m_currentRace->checkCheckPoint() == Race::Finished)
{
nbLap++;
if(nbLap == Game::m_nbLap)
{
nbLap = 0;
beforefwd = SDL_GetTicks();
/* # Pour perdre il faut avoir une place differente de la 1ère & de la seconde */
int rank = m_currentRace->checkSuccessRace();
if(rank != 1 && rank != 2)
{
handleScore();
continuer = false;
break;
}
/* # On sait qu'on à le droit de passer à la course suivante, donc si on a ete premier on gagne 3 pts, sinon 2 */
m_score += (rank == 1) ? 3 : 2;
m_currentRace->initNbLapCompetitors();
/* # On oublie pas de rebloquer les IAs pour la prochaine course */
launchIAs = false;
/* # On remet a zero les timers de turbo */
turbo = 0;
turbotime = m_turboTime;
delete m_currentRace;
switch(m_rNumber)
{
case Race1 :
m_currentRace = new R2(m_window);
m_rNumber = Race2;
break;
case Race2 :
m_currentRace = new R3(m_window);
m_rNumber = Race3;
break;
case Race3 :
/* # On vient de finir un cycle, on incremente la difficulte des IAs de 20% */
m_speedIA += m_speedIA * 0.2;
m_currentRace = new R1(m_window);
m_rNumber = Race1;
break;
}
cleanScreen();
m_currentRace->load();
}
}
}
}
/* # Si on appuie sur la touche pour reculer sans appuyer sur celle pour avancer et on va pouvoir reculer */
if(in.key[SDLK_DOWN] && !in.key[SDLK_UP])
{
/* On attend une seconde avant de demarrer */
if(SDL_GetTicks() > (beforerev + m_time2SpeedMax))
m_currentRace->movePlayerCar(SDLK_DOWN);
}
/* # Si on enfonce la touche droite ou gauche on change la direction de la voiture */
if(in.key[SDLK_LEFT])
{
m_currentRace->getPlayerCar()->loadAnotherPosition(SDLK_LEFT);
in.key[SDLK_LEFT] = 0;
}
if(in.key[SDLK_RIGHT])
{
m_currentRace->getPlayerCar()->loadAnotherPosition(SDLK_RIGHT);
in.key[SDLK_RIGHT] = 0;
}
/* # Si on appuie sur espace ca pousse ! */
if(in.key[SDLK_SPACE])
{
/* # Si il reste des turbos en stock */
if(m_currentRace->useTurbo())
{
m_currentRace->getPlayerCar()->setTurboMode();
/* # Si on a deja un turbo d'active on incremente le temps de turbo */
if(turbo != 0)
turbotime += Game::m_turboTime;
else
turbo = SDL_GetTicks();
}
in.key[SDLK_SPACE] = 0;
}
/* # On fait un delay (ie un sleep) avec le temps qu'il nous reste avant le prochain rafraichissement pour avoir un framerate fixe */
SDL_Delay(time_left(next_time));
next_time += tick_interval;
}
}
Uint32 Game::getNbHorizontalSprites()
{
return m_height / m_shapeSize;
}
Uint32 Game::getNbVerticalSprites()
{
return m_width / m_shapeSize;
}
Uint32 Game::getShapeSize()
{
return m_shapeSize;
}
Uint32 Game::getSpeedIA()
{
return m_speedIA;
}
float Game::getFwdSpeed()
{
return m_fwdSpeed;
}
void Game::cleanScreen()
{
SDL_FillRect(m_window, NULL, SDL_MapRGB(m_window->format, 0xff, 0xff, 0xff));
}
float Game::getDifficultyIAPercentage()
{
return m_difficultyIApercentage;
}
void Game::handleScore()
{
Score score;
std::string pseudo;
std::cout << "Tu viens de perdre, voici ton score : " << m_score << std::endl;
std::cout << "Entre ton pseudo a present : ";
std::getline(std::cin, pseudo);
score.ajoutScore(pseudo, m_score);
std::set<std::pair<unsigned int, std::string>, Sort > prems = score.premiers();
std::cout << "Voici le classement des 5 meilleures joueurs (du meilleur au plus mauvais) :" << std::endl;
for(std::set<std::pair<unsigned int, std::string> >::iterator it = prems.begin(); it != prems.end(); it++)
std::cout << it->second << " -> " << it->first << std::endl;
}
| [
"axelscht@468702e1-5092-14fc-779a-dee4b53e0e13",
"[email protected]@468702e1-5092-14fc-779a-dee4b53e0e13",
"goussen.maxime@468702e1-5092-14fc-779a-dee4b53e0e13"
] | [
[
[
1,
17
],
[
19,
21
],
[
23,
23
],
[
35,
86
],
[
89,
89
],
[
94,
95
],
[
97,
99
],
[
101,
103
],
[
105,
106
],
[
112,
113
],
[
115,
118
],
[
121,
122
],
[
124,
126
],
[
128,
133
],
[
136,
136
],
[
142,
142
],
[
145,
145
],
[
150,
150
],
[
153,
153
],
[
158,
158
],
[
167,
169
],
[
171,
171
],
[
174,
174
],
[
180,
181
],
[
184,
188
],
[
190,
190
],
[
192,
192
],
[
194,
194
],
[
196,
196
],
[
200,
211
],
[
213,
215
],
[
220,
221
],
[
235,
236
],
[
245,
246
],
[
249,
249
],
[
254,
254
],
[
257,
259
],
[
264,
265
],
[
271,
272
],
[
274,
276
],
[
278,
284
],
[
286,
288
],
[
291,
313
],
[
315,
347
]
],
[
[
18,
18
],
[
22,
22
],
[
24,
34
],
[
87,
88
],
[
90,
93
],
[
96,
96
],
[
100,
100
],
[
104,
104
],
[
107,
111
],
[
119,
120
],
[
123,
123
],
[
127,
127
],
[
134,
135
],
[
137,
141
],
[
143,
144
],
[
146,
149
],
[
151,
152
],
[
154,
157
],
[
159,
166
],
[
170,
170
],
[
172,
173
],
[
175,
179
],
[
182,
183
],
[
189,
189
],
[
191,
191
],
[
193,
193
],
[
195,
195
],
[
197,
199
],
[
212,
212
],
[
216,
219
],
[
222,
234
],
[
237,
244
],
[
247,
248
],
[
250,
253
],
[
255,
256
],
[
260,
263
],
[
266,
270
],
[
273,
273
],
[
277,
277
],
[
285,
285
],
[
289,
290
],
[
314,
314
]
],
[
[
114,
114
]
]
] |
20e7c496891915be8da9ce6d1dc328bcc9dd8024 | a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561 | /SlonEngine/src/Physics/Constraint.cpp | ad8027fc6ae297f0a84cc48064f978b89160e43e | [] | no_license | BackupTheBerlios/slon | e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6 | dc10b00c8499b5b3966492e3d2260fa658fee2f3 | refs/heads/master | 2016-08-05T09:45:23.467442 | 2011-10-28T16:19:31 | 2011-10-28T16:19:31 | 39,895,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,788 | cpp | #include "stdafx.h"
#include "Database/Archive.h"
#include "Physics/Constraint.h"
#include "Physics/DynamicsWorld.h"
#include "Physics/RigidBody.h"
#include "Physics/ServoMotor.h"
#include "Physics/VelocityMotor.h"
#ifdef SLON_ENGINE_USE_BULLET
# include "Physics/Bullet/BulletConstraint.h"
#endif
namespace slon {
namespace physics {
Constraint::Constraint(const DESC& desc_)
: desc(desc_)
{
if (desc.rigidBodies[0]) {
desc.rigidBodies[0]->addConstraint(this);
}
if (desc.rigidBodies[1]) {
desc.rigidBodies[1]->addConstraint(this);
}
}
Constraint::~Constraint()
{
}
// Override Serializable
const char* Constraint::serialize(database::OArchive& ar) const
{
ar.writeStringChunk("name", desc.name.data(), desc.name.length());
ar.writeSerializable(desc.rigidBodies[0].get());
ar.writeSerializable(desc.rigidBodies[1].get());
ar.writeChunk("frame0", desc.frames[0].data(), desc.frames[0].num_elements);
ar.writeChunk("frame1", desc.frames[1].data(), desc.frames[1].num_elements);
ar.writeChunk("linearLimits0", desc.linearLimits[0].arr, desc.linearLimits[0].num_elements);
ar.writeChunk("linearLimits1", desc.linearLimits[1].arr, desc.linearLimits[1].num_elements);
ar.writeChunk("angularLimits0", desc.angularLimits[0].arr, desc.angularLimits[0].num_elements);
ar.writeChunk("angularLimits1", desc.angularLimits[1].arr, desc.angularLimits[1].num_elements);
ar.writeChunk("ignoreCollisions", &desc.ignoreCollisions);
return "Constraint";
}
void Constraint::deserialize(database::IArchive& ar)
{
if (desc.rigidBodies[0]) {
desc.rigidBodies[0]->removeConstraint(this);
}
if (desc.rigidBodies[1]) {
desc.rigidBodies[1]->removeConstraint(this);
}
ar.readStringChunk("name", desc.name);
desc.rigidBodies[0] = ar.readSerializable<RigidBody>();
if (desc.rigidBodies[0]) {
desc.rigidBodies[0]->addConstraint(this);
}
desc.rigidBodies[1] = ar.readSerializable<RigidBody>();
if (desc.rigidBodies[1]) {
desc.rigidBodies[1]->addConstraint(this);
}
ar.readChunk("frame0", desc.frames[0].data(), desc.frames[0].num_elements);
ar.readChunk("frame1", desc.frames[1].data(), desc.frames[1].num_elements);
ar.readChunk("linearLimits0", desc.linearLimits[0].arr, desc.linearLimits[0].num_elements);
ar.readChunk("linearLimits1", desc.linearLimits[1].arr, desc.linearLimits[1].num_elements);
ar.readChunk("angularLimits0", desc.angularLimits[0].arr, desc.angularLimits[0].num_elements);
ar.readChunk("angularLimits1", desc.angularLimits[1].arr, desc.angularLimits[1].num_elements);
ar.readChunk("ignoreCollisions", &desc.ignoreCollisions);
instantiate();
}
RigidBody* Constraint::getRigidBodyA() const
{
return desc.rigidBodies[0].get();
}
const math::RigidTransformr& Constraint::getFrameInA() const
{
return desc.frames[0];
}
RigidBody* Constraint::getRigidBodyB() const
{
return desc.rigidBodies[1].get();
}
const math::RigidTransformr& Constraint::getFrameInB() const
{
return desc.frames[1];
}
const Motor* Constraint::getMotor(DOF dof) const
{
return motors[dof].get();
}
Motor* Constraint::getMotor(DOF dof)
{
return motors[dof].get();
}
ServoMotor* Constraint::createServoMotor(DOF dof)
{
assert( getRestriction(dof) != AXIS_LOCKED );
motors[dof].reset( new ServoMotor(this, dof) );
if (impl) {
motors[dof]->instantiate();
}
return static_cast<ServoMotor*>(motors[dof].get());
}
VelocityMotor* Constraint::createVelocityMotor(DOF dof)
{
assert( getRestriction(dof) != AXIS_LOCKED );
motors[dof].reset( new VelocityMotor(this, dof) );
if (impl) {
motors[dof]->instantiate();
}
return static_cast<VelocityMotor*>(motors[dof].get());
}
SpringMotor* Constraint::createSpringMotor(DOF dof)
{
assert( getRestriction(dof) != AXIS_LOCKED );
//motors[dof].reset( new SpringMotor(this, dof) );
//return motors[dof].get();
return 0;
}
math::Vector3r Constraint::getAxis(unsigned int axis) const
{
return impl->getAxis(axis);
}
real Constraint::getPosition(DOF dof) const
{
return impl->getPosition(dof);
}
Constraint::AXIS_RESTRICTION Constraint::getRestriction(DOF dof) const
{
if (dof < 3)
{
if ( desc.linearLimits[0][dof] == -std::numeric_limits<real>::infinity() && desc.linearLimits[1][dof] == std::numeric_limits<real>::infinity() ) {
return AXIS_FREE;
}
else if (desc.linearLimits[0][dof] < desc.linearLimits[1][dof]) {
return AXIS_RESTRICTED;
}
}
else
{
int i = dof - 3;
if ( desc.angularLimits[0][i] == -std::numeric_limits<real>::infinity() && desc.angularLimits[1][i] == std::numeric_limits<real>::infinity() ) {
return AXIS_FREE;
}
else if (desc.angularLimits[0][i] < desc.angularLimits[1][i]) {
return AXIS_RESTRICTED;
}
}
return AXIS_LOCKED;
}
const std::string& Constraint::getName() const
{
return desc.name;
}
const Constraint::DESC& Constraint::getDesc() const
{
return desc;
}
const DynamicsWorld* Constraint::getDynamicsWorld() const
{
return world.get();
}
void Constraint::reset(const DESC& desc_)
{
if (desc.rigidBodies[0]) {
desc.rigidBodies[0]->removeConstraint(this);
}
if (desc.rigidBodies[1]) {
desc.rigidBodies[1]->removeConstraint(this);
}
desc = desc_;
if (desc.rigidBodies[0]) {
desc.rigidBodies[0]->addConstraint(this);
}
if (desc.rigidBodies[1]) {
desc.rigidBodies[1]->addConstraint(this);
}
instantiate();
}
void Constraint::setWorld(const dynamics_world_ptr& world_)
{
assert( desc.rigidBodies[0] && desc.rigidBodies[1] && "Constraint must specify affected rigid bodies.");
release();
world = world_;
instantiate();
}
void Constraint::instantiate()
{
if (!desc.rigidBodies[0] || !desc.rigidBodies[1]) {
return;
}
if ( !impl && world && desc.rigidBodies[0]->getDynamicsWorld() && desc.rigidBodies[1]->getDynamicsWorld() )
{
assert( world == desc.rigidBodies[0]->getDynamicsWorld()
&& desc.rigidBodies[0]->getDynamicsWorld() == desc.rigidBodies[0]->getDynamicsWorld()
&& "Linked bodies and constraint should be in same dynamics world." );
impl.reset( new BulletConstraint(this, world->getImpl()) );
for (int i = 0; i<6; ++i)
{
if (motors[i]) {
motors[i]->instantiate();
}
}
}
}
void Constraint::release()
{
for (int i = 0; i<6; ++i)
{
if (motors[i]) {
motors[i]->release();
}
}
impl.reset();
}
} // namespace physics
} // namespace slon
| [
"devnull@localhost"
] | [
[
[
1,
240
]
]
] |
f100cc630534cdf326cf1709dbc60c4923820394 | 3856c39683bdecc34190b30c6ad7d93f50dce728 | /LastProject/Source/Stdafx.h | 451da0ef5aafe9a0730426f55f8fd0c3d92556de | [] | no_license | yoonhada/nlinelast | 7ddcc28f0b60897271e4d869f92368b22a80dd48 | 5df3b6cec296ce09e35ff0ccd166a6937ddb2157 | refs/heads/master | 2021-01-20T09:07:11.577111 | 2011-12-21T22:12:36 | 2011-12-21T22:12:36 | 34,231,967 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,766 | h | #ifndef _STDAFX_H_
#define _STDAFX_H_
// DirectX 라이브러리
#pragma comment( lib, "d3d9.lib" )
#pragma comment( lib, "d3dx9.lib" )
// Window 라이브러리
#pragma comment ( lib, "winmm.lib" )
#pragma comment( lib, "ws2_32.lib" )
// Sound 라이브러리
#pragma comment( lib, "fmodex_vc.lib" )
// TBB 라이브러리
//#pragma comment ( lib, "tbb.lib" )
// AntTwearBar 라이브러리
#pragma comment (lib, "AntTweakBar.lib")
#include "AntTweakBar.h"
// 헤더
#include <winsock2.h>
#include <Windows.h>
#include <process.h>
#include <assert.h>
//#include <WindowsX.h>
//#include <CommCtrl.h>
//#include <process.h>
#include <list>
#include <vector>
#include <algorithm>
//#include <string>
//#include <cstdio>
//#include <fstream>
#include <tchar.h>
#include <time.h>
#include <d3d9.h>
#include <d3dx9core.h>
#include <D3dx9math.h>
// FMOD
#include <fmod.h>
#include <fmod_errors.h>
// TBB
//#include <tbb/tbb.h>
// 디파인
#include "Define.h"
// Singleton
#include "Singleton.h"
// Singleton Module
#include "Matrices.h"
#include "Frequency.h"
#include "DebugConsole.h"
#include "Tree.h"
#include "Physics.h"
#include "TextureManage.h"
#include "Input.h"
#include "Mouse.h"
#include "DebugInterface.h"
#include "Astar.h"
#include "Network.h"
#include "GameEvent.h"
#include "Sound.h"
// None Sigleton Module
#include "Light.h"
// 추상화 헤더
#include "Object.h"
// Object
#include "ObjectSRT.h"
#include "Grid.h"
#include "BoundBox.h"
// Manage
#include "SceneManage.h"
#include "ObjectManage.h"
// DirectX
#include "DirectX9.h"
// win
#include "WinBase.h"
// 보안함수 경고 무시
#pragma warning( disable:4996 )
#endif | [
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0",
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0",
"[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0"
] | [
[
[
1,
27
],
[
29,
33
],
[
35,
70
],
[
72,
72
],
[
74,
98
],
[
100,
100
]
],
[
[
28,
28
],
[
34,
34
],
[
73,
73
],
[
99,
99
]
],
[
[
71,
71
]
]
] |
95d68738767e0f1776f49aa7b98ec32dfcfcddef | 2ca3ad74c1b5416b2748353d23710eed63539bb0 | /Src/Lokapala/Raptor/CommunicationFacade.cpp | 4f33fc7021f14c41f7a876e7b41529ef0c367976 | [] | no_license | sjp38/lokapala | 5ced19e534bd7067aeace0b38ee80b87dfc7faed | dfa51d28845815cfccd39941c802faaec9233a6e | refs/heads/master | 2021-01-15T16:10:23.884841 | 2009-06-03T14:56:50 | 2009-06-03T14:56:50 | 32,124,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,501 | cpp | /**@file CommunicationFacade.cpp
* @brief CCM의 Facade의 멤버함수 구현
* @author siva
*/
#include "stdafx.h"
#include "CommunicationFacade.h"
#include "CommunicationManager.h"
/**@brief 소켓을 생성한 후, 오퍼레이터에게 connect 한다.
*/
void CCommunicationFacade::Initiallize(DWORD a_ServerAddress)
{
CCommunicationManager::Instance()->Initiallize(a_ServerAddress);
}
/**@brief 오퍼레이터와의 연결을 끊는다.
*/
void CCommunicationFacade::CloseConnection()
{
CCommunicationManager::Instance()->CloseConnection();
}
/**@brief 텍스트 메세지를 오퍼레이터에게 보낸다.
*/
void CCommunicationFacade::SendTextMessageToOperator(CString *a_message)
{
CCommunicationManager::Instance()->SendTextMessageToOperator(a_message);
}
/**@brief 오퍼레이터에게 로그인 요청을 보낸다.
*/
void CCommunicationFacade::SendLoginRequest(void *a_userInfo)
{
CCommunicationManager::Instance()->SendLoginRequest(a_userInfo);
}
/**@brief 오퍼레이터에게 실행된 프로세스 이름을 보낸다.
*/
void CCommunicationFacade::SendExecutedProcessReport(CString *a_executedProcess)
{
CCommunicationManager::Instance()->SendExecutedProcessReport(a_executedProcess);
}
/**@brief 상황 보고를 오퍼레이터에게 전송한다.
*/
void CCommunicationFacade::SendStatusReport(void *a_statusReport)
{
CCommunicationManager::Instance()->SendStatusReport(a_statusReport);
}
| [
"nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c"
] | [
[
[
1,
55
]
]
] |
e512b40e6d152c4c8afe338e3aa45580c5345dc8 | d609fb08e21c8583e5ad1453df04a70573fdd531 | /trunk/OpenXP/测试用例/ClientPlaza.cpp | eb4120d33e74c8f325ccad2eab3b4852b42cf91d | [] | no_license | svn2github/openxp | d68b991301eaddb7582b8a5efd30bc40e87f2ac3 | 56db08136bcf6be6c4f199f4ac2a0850cd9c7327 | refs/heads/master | 2021-01-19T10:29:42.455818 | 2011-09-17T10:27:15 | 2011-09-17T10:27:15 | 21,675,919 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,014 | cpp | // ClientPlaza.cpp : 定义应用程序的类行为。
//
#include "stdafx.h"
#include "ClientPlaza.h"
#include "ClientPlazaDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CClientPlazaApp
BEGIN_MESSAGE_MAP(CClientPlazaApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CClientPlazaApp 构造
CClientPlazaApp::CClientPlazaApp()
{
// TODO: 在此处添加构造代码,
// 将所有重要的初始化放置在 InitInstance 中
}
// 唯一的一个 CClientPlazaApp 对象
CClientPlazaApp theApp;
// CClientPlazaApp 初始化
BOOL CClientPlazaApp::InitInstance()
{
// 如果一个运行在 Windows XP 上的应用程序清单指定要
// 使用 ComCtl32.dll 版本 6 或更高版本来启用可视化方式,
//则需要 InitCommonControlsEx()。否则,将无法创建窗口。
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// 将它设置为包括所有要在应用程序中使用的
// 公共控件类。
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// 标准初始化
// 如果未使用这些功能并希望减小
// 最终可执行文件的大小,则应移除下列
// 不需要的特定初始化例程
// 更改用于存储设置的注册表项
// TODO: 应适当修改该字符串,
// 例如修改为公司或组织名
SetRegistryKey(_T("应用程序向导生成的本地应用程序"));
CClientPlazaDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: 在此处放置处理何时用“确定”来关闭
// 对话框的代码
}
else if (nResponse == IDCANCEL)
{
// TODO: 在此放置处理何时用“取消”来关闭
// 对话框的代码
}
// 由于对话框已关闭,所以将返回 FALSE 以便退出应用程序,
// 而不是启动应用程序的消息泵。
return FALSE;
}
| [
"[email protected]@f92b348d-55a1-4afa-8193-148a6675784b"
] | [
[
[
1,
78
]
]
] |
a9d10dc4a2a7bbddbd202d7a998636f47fa5961e | ad59241b534bd17660dfbff28cdf8145f53aac92 | /CLIENT Avant refonte GUI/store.cpp | 03b518cffc058cd18ce88433802c5ebea3d996e0 | [] | no_license | CromFr/CromTPS | dc0e5c42d8c37b6169e014975d9f0ca8c9d3ad1f | 145ff39c2ab319e1d53e065ca8e92f137131cb38 | refs/heads/master | 2021-01-19T22:14:01.984408 | 2011-09-21T22:09:10 | 2011-09-21T22:09:10 | 2,282,991 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,018 | cpp | #include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <SFML/Graphics.hpp>
#include "main.h"
#include "convert.h"
#include "guifunc.h"
#include "Items.h"
#include "Buttons.h"
#include "store.h"
using namespace sf;
//Application :
extern RenderWindow oApp;
void Store(PC::PC* oPC)
{
ButtonHandler::ButtonHandler Buttons;
Buttons.AddButton(DIM_WINDOW_WIDTH/2, 400, "Armes", 1);
Buttons.AddButton(DIM_WINDOW_WIDTH/2, 500, "Armures", 2);
Buttons.AddButton(DIM_WINDOW_WIDTH/2, 600, "Blocs", 3);
Buttons.AddButton(DIM_WINDOW_WIDTH/2, 700, "Divers", 4);
int nButtonPressed=0;
Event eEvent;
Vector2<float>::Vector2<float> vPosMouse;
while(oApp.IsOpened())
{
//Gestion des evènements
while(oApp.GetEvent(eEvent))
{
switch(eEvent.Type)
{
case Event::MouseMoved:
vPosMouse = Vector2f(eEvent.MouseMove.X, eEvent.MouseMove.Y);
break;
case Event::KeyPressed:
switch(eEvent.Key.Code)
{
case Key::Escape:
return;
break;
default:
break;
}
break;
case Event::Closed:
oApp.Close();
return;
break;
default:
break;
}
nButtonPressed = Buttons.OnEvent(eEvent);
}
if(nButtonPressed == 1)
{//Armes
while(oApp.GetEvent(eEvent));
Store_Weapons(oPC);
}
if(nButtonPressed == 2)
{//Armures
while(oApp.GetEvent(eEvent))
{
}
std::cout<<"Armures"<<std::endl;
}
if(nButtonPressed == 3)
{//Blocs
while(oApp.GetEvent(eEvent))
{
}
std::cout<<"Blocs"<<std::endl;
}
if(nButtonPressed == 4)
{//Divers
while(oApp.GetEvent(eEvent))
{
}
std::cout<<"Divers"<<std::endl;
}
//Nettoyage de l'écran
oApp.Clear();
//Draw du Screen
DrawScreen(1);
Buttons.DrawButtons();
//Draw du curseur
DrawCursor(vPosMouse);
//Affichage
oApp.Display();
}
return;
}
void Store_Weapons(PC::PC* oPC)
{
ButtonHandler::ButtonHandler Buttons;
Buttons.AddButton(DIM_WINDOW_WIDTH/4, 200, "", 1, 101);
Buttons.AddButton(DIM_WINDOW_WIDTH/4, 350, "", 2, 102);
Buttons.AddButton(DIM_WINDOW_WIDTH/4, 500, "", 3, 103);
Buttons.AddButton(DIM_WINDOW_WIDTH/2, 200, "", 4, 111);
Buttons.AddButton(DIM_WINDOW_WIDTH/2, 350, "", 5, 112);
Buttons.AddButton(DIM_WINDOW_WIDTH/2, 500, "", 6, 113);
Buttons.AddButton(3*DIM_WINDOW_WIDTH/4, 200, "", 7, 121);
Buttons.AddButton(3*DIM_WINDOW_WIDTH/4, 350, "", 8, 122);
Buttons.AddButton(3*DIM_WINDOW_WIDTH/4, 500, "", 9, 123);
Buttons.AddButton(3*DIM_WINDOW_WIDTH/4, 650, "", 10, 124);
int nButtonPressed=0;
Event eEvent;
Vector2<float>::Vector2<float> vPosMouse;
while(oApp.IsOpened())
{
//Gestion des evènements
while(oApp.GetEvent(eEvent))
{
switch(eEvent.Type)
{
case Event::MouseMoved:
vPosMouse = Vector2f(eEvent.MouseMove.X, eEvent.MouseMove.Y);
break;
case Event::KeyPressed:
switch(eEvent.Key.Code)
{
case Key::Escape:
return;
break;
default:
break;
}
break;
case Event::Closed:
oApp.Close();
return;
break;
default:
break;
}
nButtonPressed = Buttons.OnEvent(eEvent);
}
switch(nButtonPressed)
{
case 1://bullet pistol
while(oApp.GetEvent(eEvent));
switch(QuestionBox("Voulez-vous vraiment acheter\ncet objet?"))
{
case -1: case 0: break;
case 1: oPC->BuyItem(MakeItemTemplate(ITEM_TYPE_WEAPON, WEAPON_TYPE_BULLET_PISTOL)); break;
}
break;
case 2://bullet rifle
while(oApp.GetEvent(eEvent));
switch(QuestionBox("Voulez-vous vraiment acheter\ncet objet?"))
{
case -1: case 0: break;
case 1: oPC->BuyItem(MakeItemTemplate(ITEM_TYPE_WEAPON, WEAPON_TYPE_BULLET_RIFLE)); break;
}
break;
case 3://bullet minigun
while(oApp.GetEvent(eEvent));
switch(QuestionBox("Voulez-vous vraiment acheter\ncet objet?"))
{
case -1: case 0: break;
case 1: oPC->BuyItem(MakeItemTemplate(ITEM_TYPE_WEAPON, WEAPON_TYPE_BULLET_MINIGUN)); break;
}
break;
case 4://laser pistol
while(oApp.GetEvent(eEvent));
switch(QuestionBox("Voulez-vous vraiment acheter\ncet objet?"))
{
case -1: case 0: break;
case 1: oPC->BuyItem(MakeItemTemplate(ITEM_TYPE_WEAPON, WEAPON_TYPE_LASER_PISTOL)); break;
}
break;
case 5://laser rifle
while(oApp.GetEvent(eEvent));
switch(QuestionBox("Voulez-vous vraiment acheter\ncet objet?"))
{
case -1: case 0: break;
case 1: oPC->BuyItem(MakeItemTemplate(ITEM_TYPE_WEAPON, WEAPON_TYPE_LASER_RIFLE)); break;
}
break;
case 6://laser minigun
while(oApp.GetEvent(eEvent));
switch(QuestionBox("Voulez-vous vraiment acheter\ncet objet?"))
{
case -1: case 0: break;
case 1: oPC->BuyItem(MakeItemTemplate(ITEM_TYPE_WEAPON, WEAPON_TYPE_LASER_MINIGUN)); break;
}
break;
case 7://gauss pistol
while(oApp.GetEvent(eEvent));
switch(QuestionBox("Voulez-vous vraiment acheter\ncet objet?"))
{
case -1: case 0: break;
case 1: oPC->BuyItem(MakeItemTemplate(ITEM_TYPE_WEAPON, WEAPON_TYPE_GAUSS_PISTOL)); break;
}
break;
case 8://gauss rifle
while(oApp.GetEvent(eEvent));
switch(QuestionBox("Voulez-vous vraiment acheter\ncet objet?"))
{
case -1: case 0: break;
case 1: oPC->BuyItem(MakeItemTemplate(ITEM_TYPE_WEAPON, WEAPON_TYPE_GAUSS_RIFLE)); break;
}
break;
case 9://gauss minigun
while(oApp.GetEvent(eEvent));
switch(QuestionBox("Voulez-vous vraiment acheter\ncet objet?"))
{
case -1: case 0: break;
case 1: oPC->BuyItem(MakeItemTemplate(ITEM_TYPE_WEAPON, WEAPON_TYPE_GAUSS_MINIGUN)); break;
}
break;
case 10://gauss destructeur
while(oApp.GetEvent(eEvent));
switch(QuestionBox("Voulez-vous vraiment acheter\ncet objet?"))
{
case -1: case 0: break;
case 1: oPC->BuyItem(MakeItemTemplate(ITEM_TYPE_WEAPON, WEAPON_TYPE_GAUSS_DESTRUCTEUR)); break;
}
break;
}
if(nButtonPressed!=0)while(oApp.GetEvent(eEvent));
//Nettoyage de l'écran
oApp.Clear();
//Draw du Screen
DrawScreen(1);
Buttons.DrawButtons();
//Draw du curseur
DrawCursor(vPosMouse);
//Affichage
oApp.Display();
}
return;
}
| [
"[email protected]"
] | [
[
[
1,
281
]
]
] |
dac48b6e542ca279e8806353f077803f368931d0 | 89147ec4f5c9a5cf4ad59c83517da2179a2f040e | /bottom1/bottom.cpp | 1545a52ea2752cad2486a5b83c6a985ea71b0ec0 | [] | no_license | swarnaprakash/my-acm-problemset | 3f977867a6637a28b486021634e30efabe30ef52 | e07654590c2691839b01291e5237082971b8cc85 | refs/heads/master | 2016-09-05T10:39:59.726651 | 2011-09-04T15:01:01 | 2011-09-04T15:01:01 | 2,323,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 395 | cpp | //Author - Swarnaprakash.U
#include<iostream>
using namespace std;
main()
{
int t;
int tot,points;
int i;
bool found;
cin>>t;
while(t--)
{
cin>>tot>>points;
found=false;
for(i=0;i<=tot && !found;++i)
{
if((i*50 -(tot-i)*25)==points)
{
found=true;
cout<<i<<endl;
}
}
if(!found)
cout<<"INVALID DATA"<<endl;
}
return 0;
} | [
"[email protected]"
] | [
[
[
1,
31
]
]
] |
b0204fc21a8c2ca5acf05ed7d232dca39c720f0d | 368acbbc055ee3a84dd9ce30777ae3bbcecec610 | /project/jni/third_party/fcollada/FCollada_FREE_3.05B/FCollada/FUtils/FUEvent.h | 5c1a427813040b723caffacc0a9fc72adf3b09ff | [
"MIT",
"LicenseRef-scancode-x11-xconsortium-veillard"
] | permissive | jcayzac/androido3d | 298559ebbe657482afe6b3b616561a1127320388 | 18e0a4cd4799b06543588cf7bea33f12500fb355 | HEAD | 2016-09-06T06:31:09.984535 | 2011-09-17T09:47:51 | 2011-09-17T09:47:51 | 1,816,466 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,301 | h | /*
Copyright (C) 2005-2007 Feeling Software Inc.
Portions of the code are:
Copyright (C) 2005-2007 Sony Computer Entertainment America
MIT License: http://www.opensource.org/licenses/mit-license.php
*/
/*
This file was taken off the Protect project on 26-09-2005
*/
/**
@file FUEvent.h
This file contains templates to contain and trigger callback events.
*/
#ifndef _FU_EVENT_H_
#define _FU_EVENT_H_
#ifndef _FU_FUNCTOR_H_
#include "FUtils/FUFunctor.h"
#endif // _FU_FUNCTOR_H_
/**
An event with no argument.
@ingroup FUtils
*/
class FUEvent0
{
private:
typedef IFunctor0<void> Handler;
typedef fm::pvector<Handler> HandlerList;
HandlerList handlers;
public:
/** Constructor. */
FUEvent0() {}
/** Destructor. */
~FUEvent0()
{
FUAssert(handlers.empty(), CLEAR_POINTER_VECTOR(handlers));
}
/** Retrieves the number of callbacks registered for this event.
@return The number of callbacks registered. */
size_t GetHandlerCount() { return handlers.size(); }
/** Adds a new callback that handles the event.
@param handle The object that contains the member function.
@param _function The member function to callback. */
template <class Class>
void InsertHandler(Class* handle, void (Class::*_function)())
{
handlers.push_back(new FUFunctor0<Class, void>(handle, _function));
}
/** Adds a functor that handles the event.
Note that the event will own the memory for the functor.
@param functor The functor that handlers the event. */
void InsertHandler(Handler* functor)
{
handlers.push_back(functor);
}
/** Adds a new callback that handles the event.
@param _function The static function to callback. */
void InsertHandler(void (*_function)())
{
handlers.push_back(new FUStaticFunctor0<void>(_function));
}
/** Releases and unregisters a callback that handles the event.
@param handle The handle of the function container.
This pointer will be NULL for static functions.
@param function The address of the function callback to unregister. */
void ReleaseHandler(void* handle, void* function)
{
HandlerList::iterator it;
for (it = handlers.begin(); it != handlers.end(); ++it)
{
if ((*it)->Compare(handle, function))
{
delete (*it);
handlers.erase(it);
break;
}
}
}
/** Releases and unregisters a callback that handles the event.
@param handle The object that contains the member function.
@param _function The member function callback to unregister. */
template <class Class>
void ReleaseHandler(Class* handle, void (Class::*_function)())
{
void* function = *(void**)(size_t)&_function;
ReleaseHandler((void*) handle, function);
}
/** Releases and unregisters a callback that handles the event.
@param _function The static function callback to unregister. */
void ReleaseHandler(void (*_function)())
{
ReleaseHandler(NULL, (void*) _function);
}
/** Triggers the event.
All the registered callbacks will be called, in reverse-order
of their registration. */
void operator()()
{
intptr_t index = handlers.size() - 1;
for (; index >= 0; --index)
{
(*handlers[index])();
}
}
};
/**
An event with one argument.
@ingroup FUtils
*/
template <class Arg1>
class FUEvent1
{
private:
typedef IFunctor1<Arg1, void> Handler;
typedef fm::pvector<Handler> HandlerList;
HandlerList handlers;
public:
/** Constructor. */
FUEvent1() {}
/** Destructor. */
~FUEvent1()
{
FUAssert(handlers.empty(), CLEAR_POINTER_VECTOR(handlers));
}
/** Retrieves the number of callbacks registered for this event.
@return The number of callbacks registered. */
size_t GetHandlerCount() { return handlers.size(); }
/** Adds a new callback that handles the event.
@param handle The object that contains the member function.
@param _function The member function to callback. */
template <class Class>
void InsertHandler(Class* handle, void (Class::*_function)(Arg1))
{
handlers.push_back(NewFUFunctor1(handle, _function));
}
/** Adds a functor that handles the event.
Note that the event will own the memory for the functor.
@param functor The functor that handlers the event. */
void InsertHandler(Handler* functor)
{
handlers.push_back(functor);
}
/** Adds a new callback that handles the event.
@param _function The static function to callback. */
void InsertHandler(void (*_function)(Arg1))
{
handlers.push_back(new FUStaticFunctor1<Arg1, void>(_function));
}
/** Releases and unregisters a callback that handles the event.
@param handle The handle of the function container.
This pointer will be NULL for static functions.
@param function The address of the function callback to unregister. */
void ReleaseHandler(void* handle, void* function)
{
typename HandlerList::iterator it;
for (it = handlers.begin(); it != handlers.end(); ++it)
{
if ((*it)->Compare(handle, function))
{
delete (*it);
handlers.erase(it);
break;
}
}
}
/** Releases and unregisters a callback that handles the event.
@param handle The object that contains the member function.
@param _function The member function callback to unregister. */
template <class Class>
void ReleaseHandler(Class* handle, void (Class::*_function)(Arg1))
{
void* function = *(void**)(size_t)&_function;
ReleaseHandler((void*) handle, function);
}
/** Releases and unregisters a callback that handles the event.
@param _function The static function callback to unregister. */
void ReleaseHandler(void (*_function)(Arg1))
{
void* function = *(void**)(size_t)&_function;
ReleaseHandler(NULL, function);
}
/** Triggers the event.
All the registered callbacks will be called, in reverse-order
of their registration.
@param argument1 A first argument. */
void operator()(Arg1 argument1)
{
intptr_t index = handlers.size() - 1;
for (; index >= 0; --index)
{
(*handlers[index])(argument1);
}
}
};
/**
An event with two argument.
@ingroup FUtils
*/
template <class Arg1, class Arg2>
class FUEvent2
{
private:
typedef IFunctor2<Arg1, Arg2, void> Handler;
typedef fm::pvector<Handler> HandlerList;
HandlerList handlers;
public:
/** Constructor. */
FUEvent2() {}
/** Destructor. */
~FUEvent2()
{
FUAssert(handlers.empty(), CLEAR_POINTER_VECTOR(handlers));
}
/** Retrieves the number of callbacks registered for this event.
@return The number of callbacks registered. */
size_t GetHandlerCount() { return handlers.size(); }
/** Adds a new callback that handles the event.
@param handle The object that contains the member function.
@param _function The member function to callback. */
template <class Class>
void InsertHandler(Class* handle, void (Class::*_function)(Arg1, Arg2))
{
handlers.push_back(new FUFunctor2<Class, Arg1, Arg2, void>(handle, _function));
}
/** Adds a functor that handles the event.
Note that the event will own the memory for the functor.
@param functor The functor that handlers the event. */
void InsertHandler(Handler* functor)
{
handlers.push_back(functor);
}
/** Adds a new callback that handles the event.
@param _function The static function to callback. */
void InsertHandler(void (*_function)(Arg1, Arg2))
{
handlers.push_back(new FUStaticFunctor2<Arg1, Arg2, void>(_function));
}
/** Releases and unregisters a callback that handles the event.
@param handle The handle of the function container.
This pointer will be NULL for static functions.
@param function The address of the function callback to unregister. */
void ReleaseHandler(void* handle, void* function)
{
typename HandlerList::iterator it;
for (it = handlers.begin(); it != handlers.end(); ++it)
{
if ((*it)->Compare(handle, function))
{
delete (*it);
handlers.erase(it);
break;
}
}
}
/** Releases and unregisters a callback that handles the event.
@param handle The object that contains the member function.
@param _function The member function callback to unregister. */
template <class Class>
void ReleaseHandler(Class* handle, void (Class::*_function)(Arg1, Arg2))
{
void* function = *(void**)(size_t)&_function;
ReleaseHandler((void*) handle, function);
}
/** Releases and unregisters a callback that handles the event.
@param _function The static function callback to unregister. */
void ReleaseHandler(void (*_function)(Arg1, Arg2))
{
void* function = *(void**)(size_t)&_function;
ReleaseHandler(NULL, function);
}
/** Triggers the event.
All the registered callbacks will be called, in reverse-order
of their registration.
@param argument1 A first argument.
@param argument2 A second argument. */
void operator()(Arg1 argument1, Arg2 argument2)
{
intptr_t index = handlers.size() - 1;
for (; index >= 0; --index)
{
(*handlers[index])(argument1, argument2);
}
}
};
/**
An event with three argument.
@ingroup FUtils
*/
template <class Arg1, class Arg2, class Arg3>
class FUEvent3
{
private:
typedef IFunctor3<Arg1, Arg2, Arg3, void> Handler;
typedef fm::pvector<Handler> HandlerList;
HandlerList handlers;
public:
/** Constructor. */
FUEvent3() {}
/** Destructor. */
~FUEvent3()
{
FUAssert(handlers.empty(), CLEAR_POINTER_VECTOR(handlers));
}
/** Retrieves the number of callbacks registered for this event.
@return The number of callbacks registered. */
size_t GetHandlerCount() { return handlers.size(); }
/** Adds a new callback that handles the event.
@param handle The object that contains the member function.
@param _function The member function to callback. */
template <class Class>
void InsertHandler(Class* handle, void (Class::*_function)(Arg1, Arg2, Arg3))
{
handlers.push_back(new FUFunctor3<Class, Arg1, Arg2, Arg3, void>(handle, _function));
}
/** Adds a functor that handles the event.
Note that the event will own the memory for the functor.
@param functor The functor that handlers the event. */
void InsertHandler(Handler* functor)
{
handlers.push_back(functor);
}
/** Adds a new callback that handles the event.
@param _function The static function to callback. */
void InsertHandler(void (*_function)(Arg1, Arg2, Arg3))
{
handlers.push_back(new FUStaticFunctor3<Arg1, Arg2, Arg3, void>(_function));
}
/** Releases and unregisters a callback that handles the event.
@param handle The handle of the function container.
This pointer will be NULL for static functions.
@param function The address of the function callback to unregister. */
void ReleaseHandler(void* handle, void* function)
{
typename HandlerList::iterator it;
for (it = handlers.begin(); it != handlers.end(); ++it)
{
if ((*it)->Compare(handle, function))
{
delete (*it);
handlers.erase(it);
break;
}
}
}
/** Releases and unregisters a callback that handles the event.
@param handle The object that contains the member function.
@param _function The member function callback to unregister. */
template <class Class>
void ReleaseHandler(Class* handle, void (Class::*_function)(Arg1, Arg2, Arg3))
{
void* function = *(void**)(size_t)&_function;
ReleaseHandler((void*) handle, function);
}
/** Releases and unregisters a callback that handles the event.
@param _function The static function callback to unregister. */
void ReleaseHandler(void (*_function)(Arg1, Arg2, Arg3))
{
void* function = *(void**)(size_t)&_function;
ReleaseHandler(NULL, function);
}
/** Triggers the event.
All the registered callbacks will be called, in reverse-order
of their registration.
@param argument1 A first argument.
@param argument2 A second argument.
@param argument3 A third argument. */
void operator()(Arg1 argument1, Arg2 argument2, Arg3 argument3)
{
intptr_t index = handlers.size() - 1;
for (; index >= 0; --index)
{
(*handlers[index])(argument1, argument2, argument3);
}
}
};
#endif // _FU_EVENT_H_
| [
"[email protected]"
] | [
[
[
1,
426
]
]
] |
fda5f789e3536d7670b58b244ba8c6c64e5bb13c | f177993b13e97f9fecfc0e751602153824dfef7e | /ImProSln/GSDXRenderer/GSDXRendererApp.h | 532bd04c966ab86c98be3ddf8065e60a45f001e5 | [] | no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | h | // GSDXRenderer.h : main header file for the GSDXRenderer DLL
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CGSDXRendererApp
// See GSDXRenderer.cpp for the implementation of this class
//
class CGSDXRendererApp : public CWinApp
{
public:
CGSDXRendererApp();
// Overrides
public:
virtual BOOL InitInstance();
DECLARE_MESSAGE_MAP()
};
| [
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
] | [
[
[
1,
27
]
]
] |
594a9cf949540b2ed41f93110ae2565e91e75375 | 3970f1a70df104f46443480d1ba86e246d8f3b22 | /imebra/src/base/src/baseStream.cpp | 04080f5a69d26162e081e89bc21613a93b581d49 | [] | no_license | zhan2016/vimrid | 9f8ea8a6eb98153300e6f8c1264b2c042c23ee22 | 28ae31d57b77df883be3b869f6b64695df441edb | refs/heads/master | 2021-01-20T16:24:36.247136 | 2009-07-28T18:32:31 | 2009-07-28T18:32:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,927 | cpp | /*
0.0.46
Imebra: a C++ dicom library.
Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 by Paolo Brandoli
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3
as published by the Free Software Foundation.
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 AFFERO GENERAL PUBLIC LICENSE Version 3 for more details.
You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3
along with this program; If not, see http://www.gnu.org/licenses/
-------------------
If you want to use Imebra commercially then you have to buy the commercial
license available at http://puntoexe.com
After you buy the commercial license then you can use Imebra according
to the terms described in the Imebra Commercial License Version 1.
A copy of the Imebra Commercial License Version 1 is available in the
documentation pages.
Imebra is available at http://puntoexe.com
The author can be contacted by email at [email protected] or by mail at
the following address:
Paolo Brandoli
Preglov trg 6
1000 Ljubljana
Slovenia
*/
/*! \file baseStream.cpp
\brief Implementation of the baseStream class.
*/
#include "../include/baseStream.h"
#include <list>
namespace puntoexe
{
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//
//
//
// baseStream
//
//
//
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
} // namespace puntoexe
| [
"[email protected]"
] | [
[
[
1,
70
]
]
] |
01362c359dfc591ae3ddd0237c5847a83d4ca172 | ea2786bfb29ab1522074aa865524600f719b5d60 | /MultimodalSpaceShooter/src/gui/Menu.cpp | 49d87cc0aca063ba3ce761a51a636159a88ce096 | [] | no_license | jeremysingy/multimodal-space-shooter | 90ffda254246d0e3a1e25558aae5a15fed39137f | ca6e28944cdda97285a2caf90e635a73c9e4e5cd | refs/heads/master | 2021-01-19T08:52:52.393679 | 2011-04-12T08:37:03 | 2011-04-12T08:37:03 | 1,467,691 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,176 | cpp | #include "gui/Menu.h"
#include "core/Managers.h"
#include "core/Game.h"
#include "ButtonListener.h"
#include <SFML/Graphics.hpp>
const float Menu::MARGIN(10.f);
Menu::Menu(const std::string& title, const sf::Image& backgroundImage, const sf::Color& titleColor) :
myBackground(backgroundImage),
myTitle(title, sf::Font::GetDefaultFont(), 40),
myNextButtonPos(250.f)
{
const sf::Vector2i screenSize = Game::instance().getScreenSize();
const sf::Vector2f spriteSize = myBackground.GetSize();
myBackground.SetPosition(screenSize.x / 2.f - spriteSize.x / 2.f, screenSize.y / 2.f - spriteSize.y / 2.f);
const sf::FloatRect titleSize = myTitle.GetRect();
myTitle.SetPosition(screenSize.x / 2.f - titleSize.Width / 2.f, myBackground.GetPosition().y + 10);
myTitle.SetColor(titleColor);
}
Menu::~Menu()
{
}
void Menu::addButton(const std::string& id, const std::string& text, ButtonListener* listener)
{
sf::Image& img = *imageManager().get("button.png");
sf::Image& imgOver = *imageManager().get("button_sel.png");
const sf::Vector2i screenSize = Game::instance().getScreenSize();
Button button(id, sf::Vector2f(screenSize.x / 2.f - 500.f / 2.f, myNextButtonPos), text, img, imgOver);
if(listener)
button.addListener(listener);
myButtons.push_back(button);
myNextButtonPos += img.GetHeight() + MARGIN;
}
void Menu::onEvent(const sf::Event& event)
{
for(std::vector<Button>::iterator i = myButtons.begin(); i != myButtons.end(); ++i)
i->onEvent(event);
}
void Menu::onMultimodalEvent(Multimodal::Event event)
{
for(std::vector<Button>::iterator i = myButtons.begin(); i != myButtons.end(); ++i)
i->onMultimodalEvent(event);
}
void Menu::update(float frameTime)
{
for(std::vector<Button>::iterator i = myButtons.begin(); i != myButtons.end(); ++i)
i->update(frameTime);
}
void Menu::draw(sf::RenderTarget& window) const
{
window.Draw(myBackground);
window.Draw(myTitle);
for(std::vector<Button>::const_iterator i = myButtons.begin(); i != myButtons.end(); ++i)
i->draw(window);
}
| [
"[email protected]"
] | [
[
[
1,
70
]
]
] |
5dfec5370a764f0f812ceb65714ce92148462d75 | 159f8788c712e4cd19628e6c1162ef80c95435e0 | /f_accueil.cpp | 8a8352a7c8ecb80a890931a60f67ba63b4c552d6 | [] | no_license | Boussadia/Train-Your-Brain | fa9621cfb6994a3cca4c560ef38b02787d31a9c3 | cf159b41abc9b09b2d2082a5004e9ce2e41148ab | refs/heads/master | 2021-01-01T05:30:32.672677 | 2011-12-01T19:21:15 | 2011-12-01T19:21:15 | 2,891,437 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,070 | cpp | #include "f_accueil.h"
#include "ui_f_accueil.h"
#include <QString>
#include <QFile>
#include <QIODevice>
#include <QTextStream>
#include <QMessageBox>
F_Accueil::F_Accueil() :
QWidget(),
ui(new Ui::F_Accueil)
{
ui->setupUi(this);
_liste_sessions = new QFile("liste_sessions.txt");
QTextStream flux(_liste_sessions);
QString Nom_Session;
_liste_sessions->open(QIODevice::ReadOnly | QIODevice::Text);
while (!flux.atEnd())
{
Nom_Session = flux.readLine();
QPushButton * Session = new QPushButton(Nom_Session);
Session->setFont(QFont("MS Shell Dlg 2", 14,75));
Session->setCursor(Qt::PointingHandCursor);
Session->setFixedSize(250,50);
QObject::connect(Session, SIGNAL(clicked()), this, SLOT(Envoi_Signal_Ouvrir_Session()));
QListWidgetItem *item = new QListWidgetItem();
ui->liste_session->insertItem(0,item);
ui->liste_session->setItemWidget(item,Session);
}
_liste_sessions->close();
//lorqu'on clique sur nouvelle session, on on crée une nouvelle session :
QObject::connect(ui->Creer_Button, SIGNAL(clicked()), this, SLOT(CreerSession()));
//lorsqu'on appuie sur le bouton entrée, on crée une nouvelle session :
QObject::connect(ui->Saisie, SIGNAL(returnPressed()), this, SLOT(CreerSession()));
}
F_Accueil::~F_Accueil()
{
delete ui;
}
void F_Accueil::CreerSession(void)
{
QString Nom_Session=ui->Saisie->text() ;
_liste_sessions->open(QIODevice::ReadWrite | QIODevice::Text);
QString contenu=_liste_sessions->readAll();
if ((Nom_Session != "") && (!contenu.contains(Nom_Session)))
{
//on créé tout de même le bouton qu'on insère dans la liste déroulante
QPushButton * Session = new QPushButton(Nom_Session);
Session->setFont(QFont("MS Shell Dlg 2", 14,75));
Session->setCursor(Qt::PointingHandCursor);
Session->setFixedSize(250,50);
QObject::connect(Session, SIGNAL(clicked()), this, SLOT(Envoi_Signal_Ouvrir_Session()));
QListWidgetItem *item = new QListWidgetItem();
ui->liste_session->insertItem(0,item);
ui->liste_session->setItemWidget(item,Session);
ui->Saisie->setText("Entrer votre nom d'Utilisateur...");
emit Signal_Ouvrir_Session(Nom_Session);
Nom_Session += "\n";
_liste_sessions->write(Nom_Session.toLatin1(),Nom_Session.size());
}
else if (contenu.contains(Nom_Session))
{
QMessageBox::warning(this,"EUuuuuu... Problème","Cette session existe déjà");
}
else
{
QMessageBox::warning(this,"EUuuuuu... Problème","Veuillez entrer un Nom d'Utilisateur");
}
_liste_sessions->close();
}
void F_Accueil::Envoi_Signal_Ouvrir_Session()
{
QPushButton *bouton = (QPushButton *)sender();
emit Signal_Ouvrir_Session(bouton->text());
}
QFile* F_Accueil::get_Liste_Sessions()
{
return _liste_sessions;
}
| [
"[email protected]"
] | [
[
[
1,
104
]
]
] |
55b5a6a73c1feed808bc03a45ec9b670b5eef3ff | 3eae8bea68fd2eb7965cca5afca717b86700adb5 | /Engine/Project/Core/GnMesh/Source/GStateItem.cpp | 9875e4086a7e5126c563e3a2699d3f67aed17532 | [] | no_license | mujige77/WebGame | c0a218ee7d23609076859e634e10e29c92bb595b | 73d36f9d8bfbeaa944c851e8a1cfa5408ce1d3dd | refs/heads/master | 2021-01-01T15:51:20.045414 | 2011-10-03T01:02:59 | 2011-10-03T01:02:59 | 455,950 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 77 | cpp | #include "GnGamePCH.h"
#include "GStateUILayer.h"
#include "GStateItem.h"
| [
"[email protected]"
] | [
[
[
1,
3
]
]
] |
54dcd7497e967778f26fcfff6595a5de8e910059 | 028d6009f3beceba80316daa84b628496a210f8d | /uidesigner/com.nokia.sdt.referenceprojects.test/data2/TUI_5_0/reference/inc/TUI_5_0Application.h | 0d18987a7363b6b947b69166c53a86b374b38bf9 | [] | no_license | JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp | fa50cafa69d3e317abf0db0f4e3e557150fd88b3 | 4420f338bc4e522c563f8899d81201857236a66a | refs/heads/master | 2020-12-30T16:45:28.474973 | 2010-10-20T16:19:31 | 2010-10-20T16:19:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | h | #ifndef TUI_5_0APPLICATION_H
#define TUI_5_0APPLICATION_H
// [[[ begin generated region: do not modify [Generated Includes]
#include <aknapp.h>
// ]]] end generated region [Generated Includes]
// [[[ begin generated region: do not modify [Generated Constants]
const TUid KUidTUI_5_0Application = { 0xE03C1A0F };
// ]]] end generated region [Generated Constants]
/**
*
* @class CTUI_5_0Application TUI_5_0Application.h
* @brief A CAknApplication-derived class is required by the S60 application
* framework. It is subclassed to create the application's document
* object.
*/
class CTUI_5_0Application : public CAknApplication
{
private:
TUid AppDllUid() const;
CApaDocument* CreateDocumentL();
};
#endif // TUI_5_0APPLICATION_H
| [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
75f4f2d4aeacae70e43b0a57cc83fb9891233605 | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/lineardial/lineardialgadgetwidget.h | 62adbcc453e80f700707ad8a0376bc7595acc070 | [] | 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 | 3,728 | h | /**
******************************************************************************
*
* @file lineardialgadgetwidget.h
* @author Edouard Lafargue Copyright (C) 2010.
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup LinearDialPlugin Linear Dial Plugin
* @{
* @brief Impliments a gadget that displays linear gauges
*****************************************************************************/
/*
* 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 LINEARDIALGADGETWIDGET_H_
#define LINEARDIALGADGETWIDGET_H_
#include "lineardialgadgetconfiguration.h"
#include "extensionsystem/pluginmanager.h"
#include "uavobjects/uavobjectmanager.h"
#include "uavobjects/uavobject.h"
#include <QGraphicsView>
#include <QtSvg/QSvgRenderer>
#include <QtSvg/QGraphicsSvgItem>
#include <QFile>
#include <QTimer>
class LineardialGadgetWidget : public QGraphicsView
{
Q_OBJECT
public:
LineardialGadgetWidget(QWidget *parent = 0);
~LineardialGadgetWidget();
void setDialFile(QString dfn);
void paint();
void setRange(double min, double max) { minValue=min; maxValue=max;}
void setGreenRange(double min, double max) {greenMin=min; greenMax=max;}
void setYellowRange(double min, double max) {yellowMin=min; yellowMax=max;}
void setRedRange(double min, double max) {redMin=min; redMax=max;}
void connectInput(QString obj, QString field);
void setIndex(double val);
void setDialFont(QString fontProps);
void setFactor (double val) { factor = val;}
void setDecimalPlaces(int val) { places = val;}
public slots:
void updateIndex(UAVObject *object1);
protected:
void paintEvent(QPaintEvent *event);
void resizeEvent(QResizeEvent *event);
private:
private slots:
void moveIndex();
private:
QSvgRenderer *m_renderer;
QGraphicsSvgItem *background;
QGraphicsSvgItem *foreground;
QGraphicsSvgItem *index;
QGraphicsSvgItem *green;
QGraphicsSvgItem *yellow;
QGraphicsSvgItem *red;
QGraphicsSvgItem *fieldSymbol;
QGraphicsTextItem *fieldName;
QGraphicsTextItem *fieldValue;
// Simple flag to skip rendering if the
bool fgenabled; // layer does not exist.
bool verticalDial; // True if the dials scales vertically.
qreal startX; // Where we should draw the bargraph
qreal startY; // green/yellow/red zones.
qreal bargraphSize;
qreal indexHeight;
qreal indexWidth;
double minValue;
double maxValue;
double greenMin;
double greenMax;
double yellowMin;
double yellowMax;
double redMin;
double redMax;
double factor;
int places;
// The Value and target variables
// are expressed in degrees
double indexTarget;
double indexValue;
// Rotation timer
QTimer dialTimer;
// Name of the fields to read when an update is received:
UAVDataObject* obj1;
QString field1;
QString subfield1;
bool haveSubField1;
};
#endif /* LINEARDIALGADGETWIDGET_H_ */
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
] | [
[
[
1,
123
]
]
] |
647dea92e9d3061f58a81c69ec0868131f7617f9 | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Graphic/Material/D3D10PostShadow.h | 81a13442c7e349811a9871a6517b51896170f4fd | [] | 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 | 705 | h | #ifndef _D3D10POSTSHADOW_H_
#define _D3D10POSTSHADOW_H_
#include <Common/Prerequisites.h>
#include "../Renderer/D3D10Material.h"
namespace Flagship
{
class _DLL_Export D3D10PostShadow : public D3D10Material
{
public:
D3D10PostShadow();
virtual ~D3D10PostShadow();
public:
// 初始化
virtual bool Initialize();
// 建立参数表
virtual void BuildParamMap();
// 更新材质节点参数
virtual void Update( Renderable * pParent );
protected:
// 阴影贴图
Key m_kShadowMap;
// 光源矩阵
Key m_kLightMatrix;
private:
};
}
#endif | [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
] | [
[
[
1,
37
]
]
] |
685be69490f70731896d4ea8bacffcd91cd36235 | 8ddac2310fb59dfbfb9b19963e3e2f54e063c1a8 | /Logiciel_PC/WishBoneMonitor/wbreadregisterview.h | bee5df118e52e569a30d598ef9cab1cbcbdcbc21 | [] | no_license | Julien1138/WishBoneMonitor | 75efb53585acf4fd63e75fb1ea967004e6caa870 | 3062132ecd32cd0ffdd89e8a56711ae9a93a3c48 | refs/heads/master | 2021-01-12T08:25:34.115470 | 2011-05-02T16:35:54 | 2011-05-02T16:35:54 | 76,573,671 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 714 | h | #ifndef WBREADREGISTERVIEW_H
#define WBREADREGISTERVIEW_H
#include "WishBoneWidgetView.h"
#include "WBReadRegisterDoc.h"
#include "WBReadRegisterDlg.h"
#include <QLineEdit>
#include <QLabel>
#include <QPushButton>
class WBReadRegisterView : public WishBoneWidgetView
{
Q_OBJECT
public:
WBReadRegisterView(WBReadRegisterDoc* pDoc, WBReadRegisterDlg* pDlg, QWidget *parent = 0);
signals:
public slots:
void ModeChanged();
void ReadRegister();
void Refresh();
private:
QLineEdit m_EditValue;
QLabel m_LabelUnit;
QPushButton* m_pSetButton;
void UpdateWidget();
};
#endif // WBREADREGISTERVIEW_H
| [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
0d6d8914e729626d0dedfa7e2b66f2ccecf5e534 | 3533c9f37def95dcc9d6b530c59138f7570ca239 | /guCORE/src/guCORE_CGameCenter.cpp | 3fbc948dfa4c573b886d7bdde1cd2f85156e874e | [] | no_license | LiberatorUSA/GU | 7e8af0dccede7edf5fc9c96c266b9888cff6d76e | 2493438447e5cde3270e1c491fe2a6094dc0b4dc | refs/heads/master | 2021-01-01T18:28:53.809051 | 2011-06-04T00:12:42 | 2011-06-04T00:12:42 | 41,840,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,412 | cpp | /*
* guCORE: Main module of the Galaxy Unlimited system
* Copyright (C) 2002 - 2008. Dinand Vanvelzen
*
* 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.
*
* This library 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 this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*-------------------------------------------------------------------------//
// //
// INCLUDE //
// //
//-------------------------------------------------------------------------*/
#ifndef GUCEF_CORE_CGUCEFAPPLICATION_H
#include "CGUCEFApplication.h"
#define GUCEF_CORE_CGUCEFAPPLICATION_H
#endif /* GUCEF_CORE_CGUCEFAPPLICATION_H ? */
#ifndef GUCEF_CORE_DVCPPSTRINGUTILS_H
#include "dvcppstringutils.h"
#define GUCEF_CORE_DVCPPSTRINGUTILS_H
#endif /* GUCEF_CORE_DVCPPSTRINGUTILS_H ? */
#ifndef GUCE_CORE_CGUCEAPPLICATION_H
#include "CGUCEApplication.h"
#define GUCE_CORE_CGUCEAPPLICATION_H
#endif /* GUCE_CORE_CGUCEAPPLICATION_H ? */
#ifndef GUCE_CORE_MISCUTILS_H
#include "miscutils.h"
#define GUCE_CORE_MISCUTILS_H
#endif /* GUCE_CORE_MISCUTILS_H ? */
#ifndef GUCE_GUI_CGUIMANAGER_H
#include "CGUIManager.h"
#define GUCE_GUI_CGUIMANAGER_H
#endif /* GUCE_GUI_CGUIMANAGER_H ? */
#include "guCORE_CGameCenter.h"
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GU {
namespace CORE {
/*-------------------------------------------------------------------------//
// //
// GLOBAL VARS //
// //
//-------------------------------------------------------------------------*/
CGameCenter* CGameCenter::g_instance = NULL;
/*-------------------------------------------------------------------------//
// //
// UTILITIES //
// //
//-------------------------------------------------------------------------*/
CGameCenter::CGameCenter( void )
: m_gameRegistry() ,
m_mpGameRegistry() ,
m_gameFactory() ,
m_mpGameFactory() ,
m_configRoot() ,
m_nameOfGameConfigFile( "config.dat" ) ,
m_gameConfigFileCodec( "xml" ) ,
m_appArgsList() ,
m_console( NULL ) ,
m_ogreDebugOverlay( NULL ) ,
m_menuController() ,
m_startupComplete( false )
{GU_TRACE;
SubscribeTo( GUCEF::CORE::CGUCEFApplication::Instance(), GUCEF::CORE::CGUCEFApplication::AppInitEvent );
SubscribeTo( GUCE::GUI::CGUIManager::Instance(), GUCE::GUI::CGUIManager::GUIInitializedEvent );
SubscribeTo( &GUCEF::CORE::CGUCEFApplication::Instance()->GetPulseGenerator() ,
GUCEF::CORE::CPulseGenerator::PulseEvent ,
&TEventCallback( this, &GU::CORE::CGameCenter::OnPulse ) );
}
/*-------------------------------------------------------------------------*/
CGameCenter::~CGameCenter()
{GU_TRACE;
}
/*-------------------------------------------------------------------------*/
CGameCenter*
CGameCenter::Instance( void )
{GU_TRACE;
if ( g_instance == NULL )
{
g_instance = new CGameCenter();
}
return g_instance;
}
/*-------------------------------------------------------------------------*/
CMenuController&
CGameCenter::GetMenuController( void )
{GU_TRACE;
return m_menuController;
}
/*-------------------------------------------------------------------------*/
CGameRegistry&
CGameCenter::GetGameRegistry( void )
{GU_TRACE;
return m_gameRegistry;
}
/*-------------------------------------------------------------------------*/
CGameFactory&
CGameCenter::GetGameFactory( void )
{GU_TRACE;
return m_gameFactory;
}
/*-------------------------------------------------------------------------*/
CMultiplayerGameRegistry&
CGameCenter::GetMultiplayerGameRegistry( void )
{GU_TRACE;
return m_mpGameRegistry;
}
/*-------------------------------------------------------------------------*/
CMultiplayerGameFactory&
CGameCenter::GetMultiplayerGameFactory( void )
{GU_TRACE;
return m_mpGameFactory;
}
/*-------------------------------------------------------------------------*/
void
CGameCenter::Deinstance( void )
{GU_TRACE;
delete g_instance;
g_instance = NULL;
}
/*-------------------------------------------------------------------------*/
CString
CGameCenter::GetGameConfigPath( const CString& gameTitle ) const
{GU_TRACE;
CString gameConfigRoot( m_configRoot );
GUCEF::CORE::AppendToPath( gameConfigRoot, gameTitle );
GUCEF::CORE::AppendToPath( gameConfigRoot, m_nameOfGameConfigFile );
return gameConfigRoot;
}
/*-------------------------------------------------------------------------*/
bool
CGameCenter::GetGameConfig( const CString& gameTitle ,
GUCEF::CORE::CDataNode& config ) const
{GU_TRACE;
CString gameConfigPath( GetGameConfigPath( gameTitle ) );
return GUCE::CORE::VFSLoadDataTree( gameConfigPath ,
m_gameConfigFileCodec ,
&config );
}
/*-------------------------------------------------------------------------*/
bool
CGameCenter::LaunchSPGame( const CString& gameTitle )
{GU_TRACE;
GUCEF::CORE::CDataNode gameConfig;
if ( GetGameConfig( gameTitle ,
gameConfig ) )
{
CGame* newGame = m_gameFactory.Create( gameTitle ,
gameConfig );
if ( NULL != newGame )
{
if ( newGame->StartSPGame() )
{
m_gameRegistry.Register( gameTitle ,
CGamePtr( newGame ) );
return true;
}
m_gameFactory.Destroy( newGame );
}
}
return false;
}
/*-------------------------------------------------------------------------*/
bool
CGameCenter::LaunchMPGame( const CString& gameTitle )
{GU_TRACE;
GUCEF::CORE::CDataNode gameConfig;
if ( GetGameConfig( gameTitle ,
gameConfig ) )
{
CMultiplayerGame* newGame = m_mpGameFactory.Create( gameTitle ,
gameConfig );
if ( NULL != newGame )
{ //@TODO: fix
if ( newGame->StartSPGame() )
{
m_mpGameRegistry.Register( gameTitle ,
CMultiplayerGamePtr( newGame ) );
return true;
}
m_mpGameFactory.Destroy( newGame );
}
}
return false;
}
/*-------------------------------------------------------------------------*/
const GUCEF::CORE::CValueList&
CGameCenter::GetAppArgs( void ) const
{GU_TRACE;
return m_appArgsList;
}
/*-------------------------------------------------------------------------*/
void
CGameCenter::OnAppInitEvent( GUCEF::CORE::CICloneable* eventdata )
{GU_TRACE;
GUCEF::CORE::CGUCEFApplication::SAppInitEventData& appArgs = static_cast< GUCEF::CORE::CGUCEFApplication::TAppInitEventData* >( eventdata )->GetData();
// first we concatenate all the argument strings
CString args;
for ( Int32 i=0; i<appArgs.argc; ++i )
{
args += appArgs.argv[ i ];
}
// We now parse the application arguments
m_appArgsList.DeleteAll();
m_appArgsList.SetMultiple( args, '\"' );
}
/*-------------------------------------------------------------------------*/
void
CGameCenter::ShowMenu( void )
{GU_TRACE;
m_menuController.SetVisibility( true );
}
/*-------------------------------------------------------------------------*/
void
CGameCenter::OnStartupComplete( GUCE::CORE::TWindowContextPtr& windowContext )
{GU_TRACE;
if ( m_menuController.InitGUIForms( windowContext ) )
{
if ( m_appArgsList.HasKey( "LaunchSPGame" ) )
{
LaunchSPGame( m_appArgsList.GetValue( "LaunchSPGame" ) );
}
else
if ( m_appArgsList.HasKey( "LaunchMPGame" ) )
{
LaunchMPGame( m_appArgsList.GetValue( "LaunchMPGame" ) );
}
else
{
ShowMenu();
}
m_startupComplete = true;
}
else
{
GUCE::CORE::CGUCEApplication::Instance()->Stop();
}
}
/*-------------------------------------------------------------------------*/
void
CGameCenter::OnPulse( GUCEF::CORE::CNotifier* notifier ,
const GUCEF::CORE::CEvent& eventid ,
GUCEF::CORE::CICloneable* eventdata /* = NULL */ )
{GU_TRACE;
if ( m_startupComplete )
{
try
{
if ( !Ogre::Root::getSingletonPtr()->renderOneFrame() )
{
GUCE::CORE::CGUCEApplication::Instance()->Stop();
return;
}
}
catch ( Ogre::Exception& /* e */ )
{
GUCEF_ERROR_LOG( 0, "CGameCenter::OnPulse(): Exception during Ogre frame rendering" );
}
}
}
/*-------------------------------------------------------------------------*/
void
CGameCenter::OnNotify( GUCEF::CORE::CNotifier* notifier ,
const GUCEF::CORE::CEvent& eventid ,
GUCEF::CORE::CICloneable* eventdata /* = NULL */ )
{GU_TRACE;
if ( GUCEF::CORE::CGUCEFApplication::AppInitEvent == eventid )
{
OnAppInitEvent( eventdata );
}
else
if ( GUCE::GUI::CGUIManager::GUIInitializedEvent == eventid )
{
GUCE::GUI::CGUIManager::TGUIInitializedEventData* eData = static_cast< GUCE::GUI::CGUIManager::TGUIInitializedEventData* >( eventdata );
OnStartupComplete( eData->GetData() );
}
}
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
}; /* namespace CORE */
}; /* namespace GU */
/*-------------------------------------------------------------------------*/
| [
"[email protected]"
] | [
[
[
1,
380
]
]
] |
d48347c15d2ef27ec9b0d81db83636ef18010d8b | a48646eddd0eec81c4be179511493cbaf22965b9 | /src/ims/AG/sipcp/sip_cp_func.inc | 3a03de50877cb83b5d89e5ce647724708939e2c9 | [] | no_license | lengue/tsip | 0449f791a5cbe9e9fdaa1b4d7f1d1e28eff2f0ec | da8606bd7d865d4b4a389ec1594248a4044bc890 | refs/heads/master | 2021-01-10T08:40:32.925501 | 2010-06-05T12:44:10 | 2010-06-05T12:44:10 | 53,989,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 670 | inc | #ifndef SIP_CP_FUNC_INC
#define SIP_CP_FUNC_INC
extern ULONG SIPCP_GetServiceMaskFromID(UCHAR ucEnum,ULONG *pulMask);
extern ULONG SIPCP_GetServiceIDFromMask(ULONG ulMask,UCHAR *pucEnum);
extern ULONG SIPCP_GetConditionMaskFromEnum(UCHAR ucEnum,ULONG *pulMask);
extern ULONG SIPCP_GetConditionIDFromMask(ULONG ulMask,UCHAR *pucEnum);
extern ULONG SIPCP_GetSpecFlagMaskFromID(UCHAR ucEnum,ULONG *pulMask);
extern ULONG SIPCP_GetSpecFlagIDFromMask(ULONG ulMask,UCHAR *pucEnum);
extern ULONG VOS_MemCpy(UCHAR *pucDisStr,UCHAR *pucSource,ULONG ulSize);
extern ULONG SIP_StartDmm();
extern ULONG SIP_SendMduMsg(SIPCP_MDU_MSG_S *pMduMsg);
#endif | [
"[email protected]"
] | [
[
[
1,
22
]
]
] |
0011589f283652cb4a34d06fadad5d6b3f452805 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/xpressive/detail/utility/save_restore.hpp | 3b3702792109bd4a4fa78b8e4b16b79623a8dd91 | [
"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 | 1,230 | hpp | ///////////////////////////////////////////////////////////////////////////////
// save_restore.hpp
//
// Copyright 2004 Eric Niebler. Distributed under 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)
#ifndef BOOST_XPRESSIVE_DETAIL_UTILITY_SAVE_RESTORE_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_DETAIL_UTILITY_SAVE_RESTORE_HPP_EAN_10_04_2005
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
#include <boost/noncopyable.hpp>
namespace boost { namespace xpressive { namespace detail
{
template<typename T>
struct save_restore
: private noncopyable
{
explicit save_restore(T &t)
: ref(t)
, val(t)
{
}
save_restore(T &t, T const &n)
: ref(t)
, val(t)
{
this->ref = n;
}
~save_restore()
{
this->ref = this->val;
}
void restore()
{
this->ref = this->val;
}
private:
T &ref;
T const val;
};
}}}
#endif
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
55
]
]
] |
4dcb35b47d660128df766cc95f8c84771e6b45d1 | 5fb9b06a4bf002fc851502717a020362b7d9d042 | /developertools/MapRenderer/include/loaders/LocalMapPatches.h | 584d2f236afde110a2b9893b7f931320b46b72d5 | [] | no_license | bravesoftdz/iris-svn | 8f30b28773cf55ecf8951b982370854536d78870 | c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4 | refs/heads/master | 2021-12-05T18:32:54.525624 | 2006-08-21T13:10:54 | 2006-08-21T13:10:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,056 | h | //
// File: LocalMapPatches.h
// Created by: Alexander Oster - [email protected]
//
/*****
*
* 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
*
*****/
#ifndef _LOCALMAPPATCHES_H_
#define _LOCALMAPPATCHES_H_
#ifdef WIN32
#include <windows.h>
#endif
#include "SDL/SDL.h"
#include <iostream>
#include <fstream>
#include <cstring>
#include "../uotype.h"
#include "Map.h"
#include "../Debug.h"
#include "MapPatches.h"
struct PatchEntry {
struct StaticPatch patch;
struct PatchEntry * next;
} STRUCT_PACKED;
class LocalMapPatches : public UOMapPatches
{
private:
struct PatchEntry * root;
int count;
public:
LocalMapPatches ();
virtual ~LocalMapPatches ();
void Clear();
void AddPatch(struct StaticPatch patch);
void DelPatch(unsigned int blockx, unsigned int blocky, unsigned int obj_id);
int GetNewID(int blockx, int blocky);
StaticPatch * GetPatch(unsigned int blockx, unsigned int blocky, unsigned int objid);
int GetNewStaticSize(int orig_count, unsigned int blockx, unsigned int blocky, bool &apply_needed);
void ApplyPatch(unsigned int blockx, unsigned int blocky, unsigned int oldcount, unsigned int newcount, struct staticinfo * src, struct staticinfo * dst);
int Load (char * filename);
int Save (char * filename);
};
#endif //_MAP_H_
| [
"sience@a725d9c3-d2eb-0310-b856-fa980ef11a19"
] | [
[
[
1,
77
]
]
] |
54ec9233147dcccbfe7306eb86408c3cd81e35a2 | 011359e589f99ae5fe8271962d447165e9ff7768 | /src/burn/konami/d_crimfght.cpp | 8b6cbccc1474ad76e90820e4f0485f3e9ebba430 | [] | 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 | 21,842 | cpp | // FB Alpha Crime Fighters driver module
// Based on MAME driver by Manuel Abadia
#include "tiles_generic.h"
#include "konami_intf.h"
#include "konamiic.h"
#include "burn_ym2151.h"
#include "k007232.h"
static unsigned char *AllMem;
static unsigned char *MemEnd;
static unsigned char *AllRam;
static unsigned char *RamEnd;
static unsigned char *DrvKonROM;
static unsigned char *DrvZ80ROM;
static unsigned char *DrvGfxROM0;
static unsigned char *DrvGfxROM1;
static unsigned char *DrvGfxROMExp0;
static unsigned char *DrvGfxROMExp1;
static unsigned char *DrvSndROM;
static unsigned char *DrvBankRAM;
static unsigned char *DrvKonRAM;
static unsigned char *DrvPalRAM;
static unsigned char *DrvZ80RAM;
static unsigned int *DrvPalette;
static unsigned char DrvRecalc;
static unsigned char *soundlatch;
static unsigned char *nDrvRamBank;
static unsigned char *nDrvKonamiBank;
static unsigned char DrvJoy1[8];
static unsigned char DrvJoy2[8];
static unsigned char DrvJoy3[8];
static unsigned char DrvJoy4[8];
static unsigned char DrvJoy5[8];
static unsigned char DrvDips[3];
static unsigned char DrvInputs[5];
static unsigned char DrvReset;
static struct BurnInputInfo CrimfghtInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvJoy5 + 0, "p1 coin" },
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 2, "p1 up" },
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 3, "p1 down" },
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 0, "p1 left" },
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 1, "p1 right" },
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1" },
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2" },
{"P2 Coin", BIT_DIGITAL, DrvJoy5 + 1, "p2 coin" },
{"P2 Up", BIT_DIGITAL, DrvJoy2 + 2, "p2 up" },
{"P2 Down", BIT_DIGITAL, DrvJoy2 + 3, "p2 down" },
{"P2 Left", BIT_DIGITAL, DrvJoy2 + 0, "p2 left" },
{"P2 Right", BIT_DIGITAL, DrvJoy2 + 1, "p2 right" },
{"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1" },
{"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 5, "p2 fire 2" },
{"P3 Coin", BIT_DIGITAL, DrvJoy5 + 2, "p3 coin" },
{"P3 Up", BIT_DIGITAL, DrvJoy3 + 2, "p3 up" },
{"P3 Down", BIT_DIGITAL, DrvJoy3 + 3, "p3 down" },
{"P3 Left", BIT_DIGITAL, DrvJoy3 + 0, "p3 left" },
{"P3 Right", BIT_DIGITAL, DrvJoy3 + 1, "p3 right" },
{"P3 Button 1", BIT_DIGITAL, DrvJoy3 + 4, "p3 fire 1" },
{"P3 Button 2", BIT_DIGITAL, DrvJoy3 + 5, "p3 fire 2" },
{"P4 Coin", BIT_DIGITAL, DrvJoy5 + 3, "p4 coin" },
{"P4 Up", BIT_DIGITAL, DrvJoy4 + 2, "p4 up" },
{"P4 Down", BIT_DIGITAL, DrvJoy4 + 3, "p4 down" },
{"P4 Left", BIT_DIGITAL, DrvJoy4 + 0, "p4 left" },
{"P4 Right", BIT_DIGITAL, DrvJoy4 + 1, "p4 right" },
{"P4 Button 1", BIT_DIGITAL, DrvJoy4 + 4, "p4 fire 1" },
{"P4 Button 2", BIT_DIGITAL, DrvJoy4 + 5, "p4 fire 2" },
{"Reset", BIT_DIGITAL, &DrvReset, "reset" },
{"Service", BIT_DIGITAL, DrvJoy5 + 4, "service" },
{"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" },
{"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" },
{"Dip C", BIT_DIPSWITCH, DrvDips + 2, "dip" },
};
STDINPUTINFO(Crimfght)
static struct BurnInputInfo CrimfghtjInputList[] = {
{"P1 Coin", BIT_DIGITAL, DrvJoy5 + 0, "p1 coin"},
{"P1 Start", BIT_DIGITAL, DrvJoy1 + 7, "p1 start"},
{"P1 Up", BIT_DIGITAL, DrvJoy1 + 2, "p1 up"},
{"P1 Down", BIT_DIGITAL, DrvJoy1 + 3, "p1 down"},
{"P1 Left", BIT_DIGITAL, DrvJoy1 + 0, "p1 left"},
{"P1 Right", BIT_DIGITAL, DrvJoy1 + 1, "p1 right"},
{"P1 Button 1", BIT_DIGITAL, DrvJoy1 + 4, "p1 fire 1"},
{"P1 Button 2", BIT_DIGITAL, DrvJoy1 + 5, "p1 fire 2"},
{"P1 Button 3", BIT_DIGITAL, DrvJoy1 + 6, "p1 fire 3"},
{"P2 Coin", BIT_DIGITAL, DrvJoy5 + 1, "p2 coin"},
{"P2 Start", BIT_DIGITAL, DrvJoy2 + 7, "p2 start"},
{"P2 Up", BIT_DIGITAL, DrvJoy2 + 2, "p2 up"},
{"P2 Down", BIT_DIGITAL, DrvJoy2 + 3, "p2 down"},
{"P2 Left", BIT_DIGITAL, DrvJoy2 + 0, "p2 left"},
{"P2 Right", BIT_DIGITAL, DrvJoy2 + 1, "p2 right"},
{"P2 Button 1", BIT_DIGITAL, DrvJoy2 + 4, "p2 fire 1"},
{"P2 Button 2", BIT_DIGITAL, DrvJoy2 + 5, "p2 fire 2"},
{"P2 Button 3", BIT_DIGITAL, DrvJoy2 + 6, "p2 fire 3"},
{"Reset", BIT_DIGITAL, &DrvReset, "reset"},
{"Service", BIT_DIGITAL, DrvJoy5 + 4, "service"},
{"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip"},
{"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip"},
{"Dip C", BIT_DIPSWITCH, DrvDips + 2, "dip"},
};
STDINPUTINFO(Crimfghtj)
static struct BurnDIPInfo CrimfghtDIPList[]=
{
{0x1e, 0xff, 0xff, 0xff, NULL },
{0x1f, 0xff, 0xff, 0x5f, NULL },
{0x20, 0xff, 0xff, 0xfb, NULL },
{0 , 0xfe, 0 , 16, "Coinage" },
{0x1e, 0x01, 0x0f, 0x02, "4 Coins 1 Credits " },
{0x1e, 0x01, 0x0f, 0x05, "3 Coins 1 Credits " },
{0x1e, 0x01, 0x0f, 0x08, "2 Coins 1 Credits " },
{0x1e, 0x01, 0x0f, 0x04, "3 Coins 2 Credits " },
{0x1e, 0x01, 0x0f, 0x01, "4 Coins 3 Credits " },
{0x1e, 0x01, 0x0f, 0x0f, "1 Coin 1 Credits " },
{0x1e, 0x01, 0x0f, 0x03, "3 Coins 4 Credits " },
{0x1e, 0x01, 0x0f, 0x07, "2 Coins 3 Credits " },
{0x1e, 0x01, 0x0f, 0x0e, "1 Coin 2 Credits " },
{0x1e, 0x01, 0x0f, 0x06, "2 Coins 5 Credits " },
{0x1e, 0x01, 0x0f, 0x0d, "1 Coin 3 Credits " },
{0x1e, 0x01, 0x0f, 0x0c, "1 Coin 4 Credits " },
{0x1e, 0x01, 0x0f, 0x0b, "1 Coin 5 Credits " },
{0x1e, 0x01, 0x0f, 0x0a, "1 Coin 6 Credits " },
{0x1e, 0x01, 0x0f, 0x09, "1 Coin 7 Credits " },
{0x1e, 0x01, 0x0f, 0x00, "1 Coin/99 Credits" },
{0 , 0xfe, 0 , 4, "Difficulty" },
{0x1f, 0x01, 0x60, 0x60, "Easy" },
{0x1f, 0x01, 0x60, 0x40, "Normal" },
{0x1f, 0x01, 0x60, 0x20, "Difficult" },
{0x1f, 0x01, 0x60, 0x00, "Very difficult" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x1f, 0x01, 0x80, 0x80, "Off" },
{0x1f, 0x01, 0x80, 0x00, "On" },
// {0 , 0xfe, 0 , 2, "Flip Screen" },
// {0x20, 0x01, 0x01, 0x01, "Off" },
// {0x20, 0x01, 0x01, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Service Mode" },
{0x20, 0x01, 0x04, 0x00, "Off" },
{0x20, 0x01, 0x04, 0x04, "On" },
};
STDDIPINFO(Crimfght)
static struct BurnDIPInfo CrimfghtjDIPList[]=
{
{0x14, 0xff, 0xff, 0xff, NULL },
{0x15, 0xff, 0xff, 0x5f, NULL },
{0x16, 0xff, 0xff, 0xfb, NULL },
{0 , 0xfe, 0 , 16, "Coin A" },
{0x14, 0x01, 0x0f, 0x02, "4 Coins 1 Credits" },
{0x14, 0x01, 0x0f, 0x05, "3 Coins 1 Credits" },
{0x14, 0x01, 0x0f, 0x08, "2 Coins 1 Credits" },
{0x14, 0x01, 0x0f, 0x04, "3 Coins 2 Credits" },
{0x14, 0x01, 0x0f, 0x01, "4 Coins 3 Credits" },
{0x14, 0x01, 0x0f, 0x0f, "1 Coin 1 Credits" },
{0x14, 0x01, 0x0f, 0x03, "3 Coins 4 Credits" },
{0x14, 0x01, 0x0f, 0x07, "2 Coins 3 Credits" },
{0x14, 0x01, 0x0f, 0x0e, "1 Coin 2 Credits" },
{0x14, 0x01, 0x0f, 0x06, "2 Coins 5 Credits" },
{0x14, 0x01, 0x0f, 0x0d, "1 Coin 3 Credits" },
{0x14, 0x01, 0x0f, 0x0c, "1 Coin 4 Credits" },
{0x14, 0x01, 0x0f, 0x0b, "1 Coin 5 Credits" },
{0x14, 0x01, 0x0f, 0x0a, "1 Coin 6 Credits" },
{0x14, 0x01, 0x0f, 0x09, "1 Coin 7 Credits" },
{0x14, 0x01, 0x0f, 0x00, "Free Play" },
{0 , 0xfe, 0 , 16, "Coin B" },
{0x14, 0x01, 0xf0, 0x20, "4 Coins 1 Credits" },
{0x14, 0x01, 0xf0, 0x50, "3 Coins 1 Credits" },
{0x14, 0x01, 0xf0, 0x80, "2 Coins 1 Credits" },
{0x14, 0x01, 0xf0, 0x40, "3 Coins 2 Credits" },
{0x14, 0x01, 0xf0, 0x10, "4 Coins 3 Credits" },
{0x14, 0x01, 0xf0, 0xf0, "1 Coin 1 Credits" },
{0x14, 0x01, 0xf0, 0x30, "3 Coins 4 Credits" },
{0x14, 0x01, 0xf0, 0x70, "2 Coins 3 Credits" },
{0x14, 0x01, 0xf0, 0xe0, "1 Coin 2 Credits" },
{0x14, 0x01, 0xf0, 0x60, "2 Coins 5 Credits" },
{0x14, 0x01, 0xf0, 0xd0, "1 Coin 3 Credits" },
{0x14, 0x01, 0xf0, 0xc0, "1 Coin 4 Credits" },
{0x14, 0x01, 0xf0, 0xb0, "1 Coin 5 Credits" },
{0x14, 0x01, 0xf0, 0xa0, "1 Coin 6 Credits" },
{0x14, 0x01, 0xf0, 0x90, "1 Coin 7 Credits" },
{0x14, 0x01, 0xf0, 0x00, "No Coin B" },
{0 , 0xfe, 0 , 4, "Lives" },
{0x15, 0x01, 0x03, 0x03, "1" },
{0x15, 0x01, 0x03, 0x02, "2" },
{0x15, 0x01, 0x03, 0x01, "3" },
{0x15, 0x01, 0x03, 0x00, "4" },
{0 , 0xfe, 0 , 4, "Difficulty" },
{0x15, 0x01, 0x60, 0x60, "Easy" },
{0x15, 0x01, 0x60, 0x40, "Normal" },
{0x15, 0x01, 0x60, 0x20, "Difficult" },
{0x15, 0x01, 0x60, 0x00, "Very Difficult" },
{0 , 0xfe, 0 , 2, "Demo Sounds" },
{0x15, 0x01, 0x80, 0x80, "Off" },
{0x15, 0x01, 0x80, 0x00, "On" },
// {0 , 0xfe, 0 , 2, "Flip Screen" },
// {0x16, 0x01, 0x01, 0x01, "Off" },
// {0x16, 0x01, 0x01, 0x00, "On" },
{0 , 0xfe, 0 , 2, "Service Mode" },
{0x16, 0x01, 0x04, 0x00, "Off" },
{0x16, 0x01, 0x04, 0x04, "On" },
};
STDDIPINFO(Crimfghtj)
static void set_ram_bank(int data)
{
nDrvRamBank[0] = data;
if (data & 0x20) {
konamiMapMemory(DrvPalRAM, 0x0000, 0x03ff, KON_RAM);
} else {
konamiMapMemory(DrvBankRAM, 0x0000, 0x03ff, KON_RAM);
}
}
void crimfght_main_write(unsigned short address, unsigned char data)
{
switch (address)
{
case 0x3f8c:
*soundlatch = data;
ZetSetVector(0xff);
ZetSetIRQLine(0, ZET_IRQSTATUS_ACK);
break;
}
if (address >= 0x2000 && address <= 0x5fff) {
K052109_051960_w(address - 0x2000, data);
return;
}
}
unsigned char crimfght_main_read(unsigned short address)
{
switch (address)
{
case 0x3f80:
return DrvInputs[4];
case 0x3f81:
return DrvInputs[0];
case 0x3f82:
return DrvInputs[1];
case 0x3f83:
return DrvDips[1];
case 0x3f84:
return DrvDips[2];
case 0x3f85:
return DrvInputs[2];
case 0x3f86:
return DrvInputs[3];
case 0x3f87:
return DrvDips[0];
case 0x3f88:
// watchdog reset
return 0;
}
if (address >= 0x2000 && address <= 0x5fff) {
return K052109_051960_r(address - 0x2000);
}
return 0;
}
void __fastcall crimfght_sound_write(unsigned short address, unsigned char data)
{
if ((address & 0xfff0) == 0xe000) {
K007232WriteReg(0, address & 0x0f, data);
return;
}
switch (address)
{
case 0xa000:
BurnYM2151SelectRegister(data);
return;
case 0xa001:
BurnYM2151WriteRegister(data);
return;
}
}
unsigned char __fastcall crimfght_sound_read(unsigned short address)
{
if ((address & 0xfff0) == 0xe000) {
return K007232ReadReg(0, address & 0x0f);
}
switch (address)
{
case 0xa000:
case 0xa001:
return BurnYM2151ReadStatus();
case 0xc000:
ZetSetIRQLine(0, ZET_IRQSTATUS_NONE);
return *soundlatch;
}
return 0;
}
static void DrvK007232VolCallback(int v)
{
K007232SetVolume(0, 0, (v >> 0x4) * 0x11, 0);
K007232SetVolume(0, 1, 0, (v & 0x0f) * 0x11);
}
static void DrvYM2151WritePort(unsigned int, unsigned int data)
{
int bank_A = ((data >> 1) & 0x01);
int bank_B = ((data) & 0x01);
k007232_set_bank(0, bank_A, bank_B);
}
static void crimfght_set_lines(int lines)
{
nDrvKonamiBank[0] = lines;
set_ram_bank(lines & 0x20);
K052109RMRDLine = lines & 0x40;
int nBank = 0x10000 + ((lines & 0x0f) * 0x2000);
konamiMapMemory(DrvKonROM + nBank, 0x6000, 0x7fff, KON_ROM);
}
static void K052109Callback(int layer, int bank, int *code, int *color, int *flipx, int *)
{
*flipx = *color & 0x20;
*code |= ((*color & 0x1f) << 8) | (bank << 13);
*code &= 0x3fff;
*color = (layer << 2) + ((*color & 0xc0) >> 6);
}
static void K051960Callback(int *code, int *color,int *priority, int *shadow)
{
switch (*color & 0x70)
{
case 0x10: *priority = 0; break;
case 0x00: *priority = 1; break;
case 0x40: *priority = 2; break;
case 0x20: *priority = 3; break;
}
*code |= (*color & 0x80) << 6;
*code &= 0x1fff;
*color = 16 + (*color & 0x0f);
*shadow = 0;
}
static int DrvDoReset()
{
DrvReset = 0;
memset (AllRam, 0, RamEnd - AllRam);
konamiOpen(0);
konamiReset();
konamiClose();
ZetOpen(0);
ZetReset();
ZetClose();
BurnYM2151Reset();
KonamiICReset();
return 0;
}
static int MemIndex()
{
unsigned char *Next; Next = AllMem;
DrvKonROM = Next; Next += 0x040000;
DrvZ80ROM = Next; Next += 0x010000;
DrvGfxROM0 = Next; Next += 0x080000;
DrvGfxROM1 = Next; Next += 0x100000;
DrvGfxROMExp0 = Next; Next += 0x100000;
DrvGfxROMExp1 = Next; Next += 0x200000;
DrvSndROM = Next; Next += 0x040000;
DrvPalette = (unsigned int*)Next; Next += 0x200 * sizeof(int);
AllRam = Next;
DrvBankRAM = Next; Next += 0x000400;
DrvKonRAM = Next; Next += 0x001c00;
DrvPalRAM = Next; Next += 0x000400;
DrvZ80RAM = Next; Next += 0x000800;
soundlatch = Next; Next += 0x000001;
nDrvRamBank = Next; Next += 0x000001;
nDrvKonamiBank = Next; Next += 0x000001;
RamEnd = Next;
MemEnd = Next;
return 0;
}
static int DrvGfxDecode()
{
int Plane0[4] = { 0x018, 0x010, 0x008, 0x000 };
int Plane1[4] = { 0x000, 0x008, 0x010, 0x018 };
int XOffs[16] = { 0x000, 0x001, 0x002, 0x003, 0x004, 0x005, 0x006, 0x007,
0x100, 0x101, 0x102, 0x103, 0x104, 0x105, 0x106, 0x107 };
int YOffs[16] = { 0x000, 0x020, 0x040, 0x060, 0x080, 0x0a0, 0x0c0, 0x0e0,
0x200, 0x220, 0x240, 0x260, 0x280, 0x2a0, 0x2c0, 0x2e0 };
konami_rom_deinterleave_2(DrvGfxROM0, 0x080000);
konami_rom_deinterleave_2(DrvGfxROM1, 0x100000);
GfxDecode(0x4000, 4, 8, 8, Plane0, XOffs, YOffs, 0x100, DrvGfxROM0, DrvGfxROMExp0);
GfxDecode(0x2000, 4, 16, 16, Plane1, XOffs, YOffs, 0x400, DrvGfxROM1, DrvGfxROMExp1);
return 0;
}
static int DrvInit()
{
AllMem = NULL;
MemIndex();
int nLen = MemEnd - (unsigned char *)0;
if ((AllMem = (unsigned char *)malloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
{
if (BurnLoadRom(DrvKonROM + 0x010000, 0, 1)) return 1;
memcpy (DrvKonROM + 0x08000, DrvKonROM + 0x28000, 0x8000);
memset (DrvKonROM + 0x28000, 0, 0x8000);
if (BurnLoadRom(DrvZ80ROM + 0x000000, 1, 1)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x000000, 2, 1)) return 1;
if (BurnLoadRom(DrvGfxROM0 + 0x040000, 3, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x000000, 4, 1)) return 1;
if (BurnLoadRom(DrvGfxROM1 + 0x080000, 5, 1)) return 1;
if (BurnLoadRom(DrvSndROM + 0x000000, 6, 1)) return 1;
DrvGfxDecode();
}
konamiInit(1);
konamiOpen(0);
konamiMapMemory(DrvBankRAM, 0x0000, 0x03ff, KON_RAM);
konamiMapMemory(DrvKonRAM, 0x0400, 0x1fff, KON_RAM);
konamiMapMemory(DrvKonROM + 0x10000, 0x6000, 0x7fff, KON_ROM);
konamiMapMemory(DrvKonROM + 0x08000, 0x8000, 0xffff, KON_ROM);
konamiSetWriteHandler(crimfght_main_write);
konamiSetReadHandler(crimfght_main_read);
konamiSetlinesCallback(crimfght_set_lines);
konamiClose();
ZetInit(1);
ZetOpen(0);
ZetMapArea(0x0000, 0x7fff, 0, DrvZ80ROM);
ZetMapArea(0x0000, 0x7fff, 2, DrvZ80ROM);
ZetMapArea(0x8000, 0x87ff, 0, DrvZ80RAM);
ZetMapArea(0x8000, 0x87ff, 1, DrvZ80RAM);
ZetMapArea(0x8000, 0x87ff, 2, DrvZ80RAM);
ZetSetWriteHandler(crimfght_sound_write);
ZetSetReadHandler(crimfght_sound_read);
ZetMemEnd();
ZetClose();
BurnYM2151Init(3579545, 100.0);
BurnYM2151SetPortHandler(&DrvYM2151WritePort);
K007232Init(0, 3579545, DrvSndROM, 0x40000);
K007232SetPortWriteHandler(0, DrvK007232VolCallback);
K052109Init(DrvGfxROM0, 0x7ffff);
K052109SetCallback(K052109Callback);
K051960Init(DrvGfxROM1, 0xfffff);
K051960SetCallback(K051960Callback);
GenericTilesInit();
DrvDoReset();
return 0;
}
static int DrvExit()
{
GenericTilesExit();
KonamiICExit();
konamiExit();
ZetExit();
K007232Exit();
BurnYM2151Exit();
free (AllMem);
AllMem = NULL;
return 0;
}
static int DrvDraw()
{
if (DrvRecalc) {
KonamiRecalcPal(DrvPalRAM, DrvPalette, 0x400);
}
K052109UpdateScroll();
K052109RenderLayer(1, 1, DrvGfxROMExp0);
K051960SpritesRender(DrvGfxROMExp1, 2);
K052109RenderLayer(2, 0, DrvGfxROMExp0);
K051960SpritesRender(DrvGfxROMExp1, 1);
K052109RenderLayer(0, 0, DrvGfxROMExp0);
K051960SpritesRender(DrvGfxROMExp1, 0);
BurnTransferCopy(DrvPalette);
return 0;
}
static int DrvFrame()
{
if (DrvReset) {
DrvDoReset();
}
{
memset (DrvInputs, 0xff, 5);
for (int i = 0; i < 8; i++) {
DrvInputs[0] ^= (DrvJoy1[i] & 1) << i;
DrvInputs[1] ^= (DrvJoy2[i] & 1) << i;
DrvInputs[2] ^= (DrvJoy3[i] & 1) << i;
DrvInputs[3] ^= (DrvJoy4[i] & 1) << i;
DrvInputs[4] ^= (DrvJoy5[i] & 1) << i;
}
}
konamiNewFrame();
ZetNewFrame();
int nSoundBufferPos = 0;
int nInterleave = 100;
int nCyclesTotal[2] = { (((3000000 / 60) * 133) / 100) /* 33% overclock */, 3579545 / 60 };
int nCyclesDone[2] = { 0, 0 };
ZetOpen(0);
konamiOpen(0);
for (int i = 0; i < nInterleave; i++)
{
int nSegment = (nCyclesTotal[0] / nInterleave) * (i + 1);
nCyclesDone[0] += konamiRun(nSegment - nCyclesDone[0]);
nSegment = (nCyclesTotal[1] / nInterleave) * (i + 1);
nCyclesDone[1] += ZetRun(nSegment - nCyclesDone[1]);
if (pBurnSoundOut) {
int nSegmentLength = nBurnSoundLen - nSoundBufferPos;
short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1);
BurnYM2151Render(pSoundBuf, nSegmentLength);
K007232Update(0, pSoundBuf, nSegmentLength);
nSoundBufferPos += nSegmentLength;
}
}
konamiSetIrqLine(KONAMI_IRQ_LINE, KONAMI_HOLD_LINE);
if (pBurnSoundOut) {
int nSegmentLength = nBurnSoundLen - nSoundBufferPos;
if (nSegmentLength) {
short* pSoundBuf = pBurnSoundOut + (nSoundBufferPos << 1);
BurnYM2151Render(pSoundBuf, nSegmentLength);
K007232Update(0, pSoundBuf, nSegmentLength);
}
}
konamiClose();
ZetClose();
if (pBurnDraw) {
DrvDraw();
}
return 0;
}
static int DrvScan(int nAction,int *pnMin)
{
struct BurnArea ba;
if (pnMin) {
*pnMin = 0x029704;
}
if (nAction & ACB_VOLATILE) {
memset(&ba, 0, sizeof(ba));
ba.Data = AllRam;
ba.nLen = RamEnd - AllRam;
ba.szName = "All Ram";
BurnAcb(&ba);
konamiCpuScan(nAction, pnMin);
ZetScan(nAction);
BurnYM2151Scan(nAction);
K007232Scan(nAction, pnMin);
KonamiICScan(nAction);
}
if (nAction & ACB_WRITE) {
konamiOpen(0);
set_ram_bank(nDrvRamBank[0]);
crimfght_set_lines(nDrvKonamiBank[0]);
konamiClose();
}
return 0;
}
// Crime Fighters (US 4 players)
static struct BurnRomInfo crimfghtRomDesc[] = {
{ "821l02.f24", 0x20000, 0x588e7da6, 1 | BRF_PRG | BRF_ESS }, // 0 Konami CPU Code
{ "821l01.h4", 0x08000, 0x0faca89e, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code
{ "821k06.k13", 0x40000, 0xa1eadb24, 3 | BRF_GRA }, // 2 Background Tiles
{ "821k07.k19", 0x40000, 0x060019fa, 3 | BRF_GRA }, // 3
{ "821k04.k2", 0x80000, 0x00e0291b, 4 | BRF_GRA }, // 4 Sprites
{ "821k05.k8", 0x80000, 0xe09ea05d, 4 | BRF_GRA }, // 5
{ "821k03.e5", 0x40000, 0xfef8505a, 5 | BRF_SND }, // 6 K007232 Samples
{ "821a08.i15", 0x00100, 0x7da55800, 6 | BRF_OPT }, // 7 Proms
};
STD_ROM_PICK(crimfght)
STD_ROM_FN(crimfght)
struct BurnDriver BurnDrvCrimfght = {
"crimfght", NULL, NULL, "1989",
"Crime Fighters (US 4 players)\0", NULL, "Konami", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING, 2, HARDWARE_PREFIX_KONAMI,
NULL, crimfghtRomInfo, crimfghtRomName, CrimfghtInputInfo, CrimfghtDIPInfo,
DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc,
304, 224, 4, 3
};
// Crime Fighters (Japan 2 Players)
static struct BurnRomInfo crimfghtjRomDesc[] = {
{ "821p02.bin", 0x20000, 0xf33fa2e1, 1 | BRF_PRG | BRF_ESS }, // 0 Konami CPU Code
{ "821l01.h4", 0x08000, 0x0faca89e, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code
{ "821k06.k13", 0x40000, 0xa1eadb24, 3 | BRF_GRA }, // 2 Background Tiles
{ "821k07.k19", 0x40000, 0x060019fa, 3 | BRF_GRA }, // 3
{ "821k04.k2", 0x80000, 0x00e0291b, 4 | BRF_GRA }, // 4 Sprites
{ "821k05.k8", 0x80000, 0xe09ea05d, 4 | BRF_GRA }, // 5
{ "821k03.e5", 0x40000, 0xfef8505a, 5 | BRF_SND }, // 6 K007232 Samples
{ "821a08.i15", 0x00100, 0x7da55800, 6 | BRF_OPT }, // 7 Proms
};
STD_ROM_PICK(crimfghtj)
STD_ROM_FN(crimfghtj)
struct BurnDriver BurnDrvCrimfghtj = {
"crimfghtj", "crimfght", NULL, "1989",
"Crime Fighters (Japan 2 Players)\0", NULL, "Konami", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_KONAMI,
NULL, crimfghtjRomInfo, crimfghtjRomName, CrimfghtjInputInfo, CrimfghtjDIPInfo,
DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc,
304, 224, 4, 3
};
// Crime Fighters (World 2 Players)
static struct BurnRomInfo crimfght2RomDesc[] = {
{ "crimefb.r02",0x20000, 0x4ecdd923, 1 | BRF_PRG | BRF_ESS }, // 0 Konami CPU Code
{ "821l01.h4", 0x08000, 0x0faca89e, 2 | BRF_PRG | BRF_ESS }, // 1 Z80 Code
{ "821k06.k13", 0x40000, 0xa1eadb24, 3 | BRF_GRA }, // 2 Background Tiles
{ "821k07.k19", 0x40000, 0x060019fa, 3 | BRF_GRA }, // 3
{ "821k04.k2", 0x80000, 0x00e0291b, 4 | BRF_GRA }, // 4 Sprites
{ "821k05.k8", 0x80000, 0xe09ea05d, 4 | BRF_GRA }, // 5
{ "821k03.e5", 0x40000, 0xfef8505a, 5 | BRF_SND }, // 6 K007232 Samples
{ "821a08.i15", 0x00100, 0x7da55800, 6 | BRF_OPT }, // 7 Proms
};
STD_ROM_PICK(crimfght2)
STD_ROM_FN(crimfght2)
struct BurnDriver BurnDrvCrimfght2 = {
"crimfght2", "crimfght", NULL, "1989",
"Crime Fighters (World 2 Players)\0", NULL, "Konami", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_CLONE, 2, HARDWARE_PREFIX_KONAMI,
NULL, crimfght2RomInfo, crimfght2RomName, CrimfghtjInputInfo, CrimfghtjDIPInfo,
DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc,
304, 224, 4, 3
};
| [
"[email protected]"
] | [
[
[
1,
762
]
]
] |
fd0d50e4e518c7f4006be35cc0b73afd7ab8af61 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/devicesrv/SystemSW/SystemSWMisc52Test/inc/SystemSWMisc52Test.h | 2419e47bafaeeb9bda340406ebcd5004eefc1dd1 | [] | no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,187 | h | /*
* 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:
*
* Description: STIF hardcoded module declaration
*
*/
#ifndef SYSTEMSWMISC52TEST_H
#define SYSTEMSWMISC52TEST_H
// INCLUDES
#include "StifTestModule.h"
#include <StifLogger.h>
#include <hwrmlight.h>
#include <sysutil.h>
#include "TestScheduler.h"
#include "TestScheduler.h"
#include <featdiscovery.h>
// CONSTANTS
//const ?type ?constant_var = ?constant;
// MACROS
//#define ?macro ?macro_def
#define TEST_MODULE_VERSION_MAJOR 52
#define TEST_MODULE_VERSION_MINOR 9
#define TEST_MODULE_VERSION_BUILD 50
// Logging path
_LIT( KSystemSWMisc52TestLogPath, "\\logs\\testframework\\SystemSWMisc52Test\\" );
// Log file
_LIT( KSystemSWMisc52TestLogFile, "SystemSWMisc52Test.txt" );
_LIT( KSystemSWMisc52TestLogFileWithTitle, "SystemSWMisc52Test_[%S].txt" );
#define GETPTR &
#define ENTRY(str,func) {_S(str), GETPTR func,0,0,0}
#define FUNCENTRY(func) {_S(#func), GETPTR func,0,0,0}
#define OOM_ENTRY(str,func,a,b,c) {_S(str), GETPTR func,a,b,c}
#define OOM_FUNCENTRY(func,a,b,c) {_S(#func), GETPTR func,a,b,c}
// FUNCTION PROTOTYPES
//?type ?function_name(?arg_list);
// FORWARD DECLARATIONS
//class ?FORWARD_CLASSNAME;
class CSystemSWMisc52Test;
// DATA TYPES
//enum ?declaration
//typedef ?declaration
//extern ?data_type;
// A typedef for function that does the actual testing,
// function is a type
// TInt CSystemSWMisc52Test::<NameOfFunction> ( TTestResult& aResult )
typedef TInt (CSystemSWMisc52Test::* TestFunction)(TTestResult&);
// CLASS DECLARATION
/**
* An internal structure containing a test case name and
* the pointer to function doing the test
*
* @lib ?library
* @since ?Series60_version
*/
class TCaseInfoInternal
{
public:
const TText* iCaseName;
TestFunction iMethod;
TBool iIsOOMTest;
TInt iFirstMemoryAllocation;
TInt iLastMemoryAllocation;
};
// CLASS DECLARATION
/**
* A structure containing a test case name and
* the pointer to function doing the test
*
* @lib ?library
* @since ?Series60_version
*/
class TCaseInfo
{
public:
TPtrC iCaseName;
TestFunction iMethod;
TBool iIsOOMTest;
TInt iFirstMemoryAllocation;
TInt iLastMemoryAllocation;
TCaseInfo( const TText* a ) : iCaseName( (TText*) a )
{
};
};
// CLASS DECLARATION
/**
* This a SystemSWMisc52Test class.
* ?other_description_lines
*
* @lib ?library
* @since ?Series60_version
*/
NONSHARABLE_CLASS(CSystemSWMisc52Test) : public CTestModuleBase
{
public: // Constructors and destructor
/**
* Two-phased constructor.
*/
static CSystemSWMisc52Test* NewL();
/**
* Destructor.
*/
virtual ~CSystemSWMisc52Test();
public: // New functions
/**
* ?member_description.
* @since ?Series60_version
* @param ?arg1 ?description
* @return ?description
*/
//?type ?member_function( ?type ?arg1 );
public: // Functions from base classes
/**
* From CTestModuleBase InitL is used to initialize the
* SystemSWMisc52Test. It is called once for every instance of
* TestModuleSystemSWMisc52Test after its creation.
* @since ?Series60_version
* @param aIniFile Initialization file for the test module (optional)
* @param aFirstTime Flag is true when InitL is executed for first
* created instance of SystemSWMisc52Test.
* @return Symbian OS error code
*/
TInt InitL( TFileName& aIniFile, TBool aFirstTime );
/**
* From CTestModuleBase GetTestCasesL is used to inquiry test cases
* from SystemSWMisc52Test.
* @since ?Series60_version
* @param aTestCaseFile Test case file (optional)
* @param aTestCases Array of TestCases returned to test framework
* @return Symbian OS error code
*/
TInt GetTestCasesL( const TFileName& aTestCaseFile,
RPointerArray<TTestCaseInfo>& aTestCases );
/**
* From CTestModuleBase RunTestCaseL is used to run an individual
* test case.
* @since ?Series60_version
* @param aCaseNumber Test case number
* @param aTestCaseFile Test case file (optional)
* @param aResult Test case result returned to test framework (PASS/FAIL)
* @return Symbian OS error code (test case execution error, which is
* not reported in aResult parameter as test case failure).
*/
TInt RunTestCaseL( const TInt aCaseNumber,
const TFileName& aTestCaseFile,
TTestResult& aResult );
/**
* From CTestModuleBase; OOMTestQueryL is used to specify is particular
* test case going to be executed using OOM conditions
* @param aTestCaseFile Test case file (optional)
* @param aCaseNumber Test case number (optional)
* @param aFailureType OOM failure type (optional)
* @param aFirstMemFailure The first heap memory allocation failure value (optional)
* @param aLastMemFailure The last heap memory allocation failure value (optional)
* @return TBool
*/
virtual TBool OOMTestQueryL( const TFileName& /* aTestCaseFile */,
const TInt /* aCaseNumber */,
TOOMFailureType& aFailureType,
TInt& /* aFirstMemFailure */,
TInt& /* aLastMemFailure */ );
/**
* From CTestModuleBase; OOMTestInitializeL may be used to initialize OOM
* test environment
* @param aTestCaseFile Test case file (optional)
* @param aCaseNumber Test case number (optional)
* @return None
*/
virtual void OOMTestInitializeL( const TFileName& /* aTestCaseFile */,
const TInt /* aCaseNumber */ );
/**
* From CTestModuleBase; OOMHandleWarningL
* @param aTestCaseFile Test case file (optional)
* @param aCaseNumber Test case number (optional)
* @param aFailNextValue FailNextValue for OOM test execution (optional)
* @return None
*
* User may add implementation for OOM test warning handling. Usually no
* implementation is required.
*/
virtual void OOMHandleWarningL( const TFileName& /* aTestCaseFile */,
const TInt /* aCaseNumber */,
TInt& /* aFailNextValue */);
/**
* From CTestModuleBase; OOMTestFinalizeL may be used to finalize OOM
* test environment
* @param aTestCaseFile Test case file (optional)
* @param aCaseNumber Test case number (optional)
* @return None
*
*/
virtual void OOMTestFinalizeL( const TFileName& /* aTestCaseFile */,
const TInt /* aCaseNumber */ );
/**
* Method used to log version of test module
*/
void SendTestModuleVersion();
protected: // New functions
/**
* ?member_description.
* @since ?Series60_version
* @param ?arg1 ?description
* @return ?description
*/
//?type ?member_function( ?type ?arg1 );
protected: // Functions from base classes
/**
* From ?base_class ?member_description
*/
//?type ?member_function();
private:
/**
* C++ default constructor.
*/
CSystemSWMisc52Test();
/**
* By default Symbian 2nd phase constructor is private.
*/
void ConstructL();
// Prohibit copy constructor if not deriving from CBase.
// ?classname( const ?classname& );
// Prohibit assigment operator if not deriving from CBase.
// ?classname& operator=( const ?classname& );
/**
* Function returning test case name and pointer to test case function.
* @since ?Series60_version
* @param aCaseNumber test case number
* @return TCaseInfo
*/
const TCaseInfo Case ( const TInt aCaseNumber ) const;
/**
* [test case declarations] - do not remove
*/
//ADD NEW METHOD DEC HERE"
/**
* Printing test case.
* @since ?Series60_version
* @param aResult Test case result (PASS/FAIL)
* @return Symbian OS error code (test case execution error
* that is not returned as test case result in aResult)
*/
TInt PrintTest( TTestResult& aResult );
/**
* Printing loop test case.
* @since ?Series60_version
* @param aResult Test case result (PASS/FAIL)
* @return Symbian OS error code (test case execution error
* that is not returned as test case result in aResult)
*/
// light API testcases
TInt LightBlinkTestL( TTestResult& aResult );
TInt LightBlinkTest2L( TTestResult& aResult );
TInt SetLightColorTestL( TTestResult& aResult );
TInt SetLightDefaultColorTestL( TTestResult& aResult );
TInt LightOnTestL( TTestResult& aResult );
TInt LightOnTest2L( TTestResult& aResult );
// Sysutil API testcases
TInt GetAttributeTestL( TTestResult& aResult );
TInt GetModelCodeTestL( TTestResult& aResult );
TInt GetModelNameTestL( TTestResult& aResult );
TInt GetOSVersionTestL( TTestResult& aResult );
TInt GetOSVersionTest2L( TTestResult& aResult );
TInt GetRevisionIDTestL( TTestResult& aResult );
TInt GetUIPlatformNameTestL( TTestResult& aResult );
TInt GetManufacturerNameTestL( TTestResult& aResult );
TInt GetDefaultDeviceNameTestL( TTestResult& aResult );
TInt GetUIPlatformVersionTestL( TTestResult& aResult );
TInt GetUIPlatformVersionTest2L( TTestResult& aResult );
TInt TFeatureSetTestL( TTestResult& aResult );
TInt AppendTestL( TTestResult& aResult );
TInt IsFeatureSupportedTestL( TTestResult& aResult );
TInt AreAllFeaturesSupportedTestL( TTestResult& aResult );
TInt IsSupportedTestL( TTestResult& aResult );
TInt FeaturesSupportedLTestL( TTestResult& aResult );
TInt FeaturesSupportedTestL( TTestResult& aResult );
TInt IsFeatureSupportedLTestL( TTestResult& aResult );
TInt MMCSpaceBelowCriticalLevelTestL( TTestResult& aResult );
TInt GetPRInformationTestL( TTestResult& aResult );
public: // Data
// ?one_line_short_description_of_data
//?data_declaration;
protected: // Data
// ?one_line_short_description_of_data
//?data_declaration;
private: // Data
// Pointer to test (function) to be executed
TestFunction iMethod;
// Pointer to logger
CStifLogger * iLog;
TInt iTarget;
CHWRMLight::TLightStatus iStatus;
CActiveScheduler* myActiveScheduler;
// Normal logger
CStifLogger* iStdLog;
// Test case logger
CStifLogger* iTCLog;
// Flag saying if test case title should be added to log file name
TBool iAddTestCaseTitleToLogName;
// Flag saying if version of test module was already sent
TBool iVersionLogged;
// ?one_line_short_description_of_data
//?data_declaration;
// Reserved pointer for future extension
//TAny* iReserved;
public: // Friend classes
//?friend_class_declaration;
protected: // Friend classes
//?friend_class_declaration;
private: // Friend classes
//?friend_class_declaration;
};
#endif // SYSTEMSWMISC52TEST_H
// End of File
| [
"none@none"
] | [
[
[
1,
381
]
]
] |
8598378c3b4be0682d153c7c29eba90e0771f4db | b369aabb8792359175aedfa50e949848ece03180 | /src/wblib/wblib/MD2Loader.h | 92e931e48d253d498a66c0a92ef55a5c699c9a00 | [] | no_license | LibreGamesArchive/magiccarpet | 6d49246817ab913f693f172fcfc53bf4cc153842 | 39210d57096d5c412de0f33289fbd4d08c20899b | refs/heads/master | 2021-05-08T02:00:46.182694 | 2009-01-06T20:25:36 | 2009-01-06T20:25:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,787 | h | #ifndef _MD2LOADER
#define _MD2LOADER
#include <GL/glew.h>
#include <GL/glut.h>
#include <string>
#include <iostream>
#include <fstream>
#include <list>
#include <map>
#include <vector>
#include <math.h>
#include "PCXLoader.h"
#ifdef _WIN32
#pragma(1)
#endif
// md2 header
struct MD2Header
{
int ident; // magic number. must be equal to "IDP2"
int version; // md2 version. must be equal to 8
int skinwidth; // width of the texture
int skinheight; // height of the texture
int framesize; // size of one frame in bytes
int num_skins; // number of textures
int num_xyz; // number of vertices
int num_st; // number of texture coordinates
int num_tris; // number of triangles
int num_glcmds; // number of opengl commands
int num_frames; // total number of frames
int ofs_skins; // offset to skin names (64 bytes each)
int ofs_st; // offset to s-t texture coordinates
int ofs_tris; // offset to triangles
int ofs_frames; // offset to frame data
int ofs_glcmds; // offset to opengl commands
int ofs_end; // offset to end of file
};
typedef float vec3[3];
// texture coordinates
struct texCoord
{
short s;
short t;
};
// vertex
struct vertex
{
unsigned char v[3]; // compressed vertex (x, y, z) coordinates
unsigned char lightnormalindex; // index to a normal vector for the lighting
};
// frame
struct frame
{
float scale[3]; // scale values
float translate[3]; // translation vector
char name[16]; // frame name
vertex verts[1]; // first vertex of this frame
};
// triangle
struct triangle
{
short index_xyz[3]; // indexes to triangle's vertices
short index_st[3]; // indexes to vertices' texture coorinates
};
struct anim_t
{
int first_frame; // first frame of the animation
int last_frame; // number of frames
int fps; // number of frames per second
};
#ifdef _WIN32
#pragma()
#endif
// animation list
enum animType_t {
STAND,
RUN,
ATTACK,
PAIN_A,
PAIN_B,
PAIN_C,
JUMP,
FLIP,
SALUTE,
FALLBACK,
WAVE,
POINT,
CROUCH_STAND,
CROUCH_WALK,
CROUCH_ATTACK,
CROUCH_PAIN,
CROUCH_DEATH,
DEATH_FALLBACK,
DEATH_FALLFORWARD,
DEATH_FALLBACKSLOW,
BOOM,
MAX_ANIMATIONS
};
class MD2Loader {
public:
MD2Loader(const std::string _md2FileName,
const std::string _textureFileName);
void CleanUp();
void DrawVertices();
void DrawMesh();
void DrawFrame();
void DrawCurrentAnimation();
void SetCurrentAnimType(animType_t _currentAnimType) {
currentAnimType = _currentAnimType;
}
bool Good() {
return good;
}
private:
// opens the file, loads content into buffer
int PerformFileHandling(const std::string _md2FileName,
const std::string _textureFileName);
// Parses the buffer, extracts the Q3BSP content
void Parse();
void CalculateNormal(float * p1, float * p2, float * p);
public:
static anim_t animlist[21]; // animation list
private:
char * buffer;
MD2Header * header;
vec3 * vertices;
triangle * mesh;
int * glcmds;
texCoord * texCoords;
int textureObjectID;
animType_t currentAnimType;
int currentFrame;
int nextFrame;
float interpol;
bool good;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
159
]
]
] |
18a9374b8199ee17bca950164385369d076fc626 | df5277b77ad258cc5d3da348b5986294b055a2be | /Spaceships/IVisitor.h | 26db9762e82ef76abe3fa2b4628c1bab375d2867 | [] | no_license | beentaken/cs260-last2 | 147eaeb1ab15d03c57ad7fdc5db2d4e0824c0c22 | 61b2f84d565cc94a0283cc14c40fb52189ec1ba5 | refs/heads/master | 2021-03-20T16:27:10.552333 | 2010-04-26T00:47:13 | 2010-04-26T00:47:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 428 | h | #pragma once
#include "Controller.h"
// TODO: get time machine, find person who implemented this build crap, and destroy them!
class Controller;
class IVisitor
{
public:
virtual void Visit(GameObject* object) = 0;
virtual void Leave() = 0;
virtual void VisitorAccepted(GameObject* objectToVisit, Controller* controller) = 0;
virtual void PassMessage(Message* msg) = 0;
virtual void ProcessMessages() = 0;
}; | [
"ProstheticMind43@af704e40-745a-32bd-e5ce-d8b418a3b9ef"
] | [
[
[
1,
15
]
]
] |
e3135d9413b949af81dc28b5ab8ccce9e1c54fc5 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Modules/include/Parameter.h | 4e45d8591df8bac1a377157b4bc3e12580146db9 | [
"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 | 10,738 | 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.
*/
/* The public interface to the Parameter module. This module
* stores permanent parameters that needs to be kept over a
* system restart. */
#ifndef MODULE_Parameter_H
#define MODULE_Parameter_H
namespace isab {
/** A module to convert function calls into messages that are
* sent to another module. That other module must implement
* ParameterConsumerInterface. */
class ParameterConsumerPublic : public ModulePublic {
public:
ParameterConsumerPublic(Module *m) :
ModulePublic(m) { };
virtual uint32 paramValue(uint32 paramId,
const int32 * data,
int32 numEntries,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
virtual uint32 paramValue(uint32 paramId,
const float * data,
int32 numEntries,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
virtual uint32 paramValue(uint32 paramId,
int length,
const char * data,
int32 numEntries,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
/** Binary block */
virtual uint32 paramValue(uint32 paramId, const uint8* data, int size,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
virtual uint32 paramNoValue(uint32 paramId,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
};
/** A module to convert function calls into messages that are
* sent to another module. That other module must implement
* ParameterProviderInterface. */
class ParameterProviderPublic : public ModulePublic {
public:
ParameterProviderPublic(Module *m) :
ModulePublic(m) {
setDefaultDestination(Module::addrFromId(Module::ParameterModuleId));
};
private:
virtual uint32 clearParam(uint32 paramId,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
virtual uint32 setParam(uint32 paramId, const int32 * data,
int32 numEntries = 1,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
virtual uint32 setParam(uint32 paramId, const float * data,
int32 numEntries = 1,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
virtual uint32 setParam(uint32 paramId, const char * const * data,
int32 numEntries = 1,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
/** Binary block */
virtual uint32 setParam(uint32 paramId, const uint8* data, int size,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
virtual uint32 getParam(uint32 paramId,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
public:
uint32 clearParam(enum ParameterEnums::ParamIds paramId,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT)
{
return clearParam(uint32(paramId), dst);
}
uint32 setParam(enum ParameterEnums::ParamIds paramId, const int32* data,
int32 numEntries = 1, uint32 dst = MsgBufferEnums::ADDR_DEFAULT)
{
return setParam(uint32(paramId), data, numEntries, dst);
}
uint32 setParam(enum ParameterEnums::ParamIds paramId, const float * data,
int32 numEntries = 1, uint32 dst = MsgBufferEnums::ADDR_DEFAULT)
{
return setParam(uint32(paramId), data, numEntries, dst);
}
uint32 setParam(enum ParameterEnums::ParamIds paramId, const char * const * data,
int32 numEntries = 1, uint32 dst = MsgBufferEnums::ADDR_DEFAULT)
{
return setParam(uint32(paramId), data, numEntries, dst);
}
uint32 setParam(enum ParameterEnums::ParamIds paramId, const uint8* data, int size,
uint32 dst = MsgBufferEnums::ADDR_DEFAULT)
{
return setParam(uint32(paramId), data, size, dst);
}
uint32 getParam(enum ParameterEnums::ParamIds paramId, uint32 dst = MsgBufferEnums::ADDR_DEFAULT)
{
return getParam(uint32(paramId), dst);
}
static uint16 paramIdToMulticastGroup(enum ParameterEnums::ParamIds paramId)
{
return paramIdToMulticastGroup(uint32(paramId));
}
static bool paramIdIsMulticast(enum ParameterEnums::ParamIds paramId)
{
return paramIdIsMulticast(uint32(paramId));
}
virtual uint32 rewriteOrigFile(uint32 dst = MsgBufferEnums::ADDR_DEFAULT);
private:
static uint16 paramIdToMulticastGroup(uint32 paramId)
{
return uint16((paramId & 0x7fff0000) >> 16);
}
static bool paramIdIsMulticast(uint32 paramId)
{
return ((paramId & 0x80000000) != 0);
}
};
/* Next are the interfaces. These should be implemented by the
* module that wishes to receive the corresponding messages.
* The classes below are pure virtual and correspond in function
* to "interfaces" in java. */
/** An interface that must be implemented to receive messages in a
* NavTask provider-consumer relationship. This is implemented
* in the _upper_ module.
*/
class ParameterConsumerInterface {
public:
virtual void decodedParamValue(uint32 paramId,
const int32 * data,
int32 numEntries,
uint32 src,
uint32 dst) = 0;
virtual void decodedParamValue(uint32 paramId,
const float * data,
int32 numEntries,
uint32 src,
uint32 dst) = 0;
virtual void decodedParamValue(uint32 paramId,
const char * const * data,
int32 numEntries,
uint32 src,
uint32 dst) = 0;
/** Delivers a binary block parameter.*/
virtual void decodedParamValue(uint32 paramId,
const uint8* data,
int size,
uint32 src,
uint32 dst) = 0;
virtual void decodedParamNoValue(uint32 paramId,
uint32 src,
uint32 dst) = 0;
};
/** An interface that must be implemented to receive messages in a
* NavTask provider-consumer relationship. This is implemented
* in the _lower_ module.
*/
class ParameterProviderInterface {
public:
virtual void decodedClearParam(uint32 paramId,
uint32 src) = 0;
virtual void decodedSetParam(uint32 paramId,
const int32 * data,
int32 numEntries,
uint32 src) = 0;
virtual void decodedSetParam(uint32 paramId,
const float * data,
int32 numEntries,
uint32 src) = 0;
virtual void decodedSetParam(uint32 paramId,
int length,
const char * data,
int32 numEntries,
uint32 src) = 0;
/** Sets a binary block parameter.*/
virtual void decodedSetParam(uint32 paramId,
const uint8* data,
int size,
uint32 src) = 0;
virtual void decodedGetParam(uint32 paramId,
uint32 src) = 0;
virtual void decodedRewriteOrigFile(uint32 src) = 0;
};
/** An object of this class is owned by each module that implements
* the NavTaskConsumerInterface. This object contains a dispatch()
* function that does the actual decoding of an incoming buffer.
* It then call the apropriate methods in NavTaskConsumerInterface.
*/
class ParameterConsumerDecoder {
public:
class MsgBuffer * dispatch(class MsgBuffer *buf, ParameterConsumerInterface *m );
};
/** An object of this class is owned by each module that implements
* the NavTaskProviderInterface. This object contains a dispatch()
* function that does the actual decoding of an incoming buffer.
* It then call the apropriate methods in NavTaskProviderInterface.
*
* @return the buffer if further processing may be done or NULL if
* the buffer was processed and either passed on or
* destroyed and thus no further processing should be done.
*/
class ParameterProviderDecoder {
public:
class MsgBuffer * dispatch(class MsgBuffer *buf, ParameterProviderInterface *m );
};
} /* namespace isab */
#endif /* MODULE_Parameter_H */
| [
"[email protected]"
] | [
[
[
1,
243
]
]
] |
63dadd7bef96c6380571bda14b2cb1c0283c98dc | 216ae2fd7cba505c3690eaae33f62882102bd14a | /utils/nxogre/include/NxOgreScene.h | 749df03a7f16a173bac931a59ca0bc876eaff9f8 | [] | no_license | TimelineX/balyoz | c154d4de9129a8a366c1b8257169472dc02c5b19 | 5a0f2ee7402a827bbca210d7c7212a2eb698c109 | refs/heads/master | 2021-01-01T05:07:59.597755 | 2010-04-20T19:53:52 | 2010-04-20T19:53:52 | 56,454,260 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 14,343 | h | /** File: NxOgreScene.h
Created on: 6-Nov-08
Author: Robin Southern "betajaen"
SVN: $Id$
© Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org
This file is part of NxOgre.
NxOgre 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.
NxOgre 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 NxOgre. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NXOGRE_SCENE_H
#define NXOGRE_SCENE_H
#include "NxOgreStable.h"
#include "NxOgreCommon.h"
#include "NxOgrePointerClass.h"
#include "NxOgreRigidBodyDescription.h"
#include "NxOgreMaterialDescription.h"
#include "NxOgreJointDescription.h"
#include "NxOgreSphericalJointDescription.h"
#include "NxOgreRevoluteJointDescription.h"
#include "NxOgreClothDescription.h"
#include "NxOgreCompartmentDescription.h"
#include "NxOgreCompartment.h"
#include "NxOgreTimeListener.h"
namespace NxOgre_Namespace
{
/** \brief
*/
class NxOgrePublicClass Scene : public PointerClass<Classes::_Scene>, public TimeListener
{
friend class World;
friend class Functions::ArrayFunctions<Scene*>::Write;
public: // Functions
/** \brief Get the name of the Scene if it has one; otherwise NULL is returned.
*/
const char* getName(void) const;
/** \brief Set the name of the Scene.
*/
void setName(const char*);
/** \brief
*/
unsigned int getNbActors(void) const;
/** \brief
*/
ArrayIterator<Actor*> getActors(void);
/** \brief
*/
Actor* createActor(RigidBodyPrototype*);
/** \brief Create an actor somewhere in the scene
*/
Actor* createActor(Shape*, const Matrix44& = Matrix44_Identity, const RigidBodyDescription& = RigidBodyDescription());
/** \brief Create an actor somewhere in the scene
*/
Actor* createActor(Shapes, const Matrix44& = Matrix44_Identity, const RigidBodyDescription& = RigidBodyDescription());
/** \brief
*/
SceneGeometry* createSceneGeometry(Shapes, const Matrix44& = Matrix44_Identity, const RigidBodyDescription& = RigidBodyDescription());
/** \brief
*/
SceneGeometry* createSceneGeometry(Shape*, const Matrix44& = Matrix44_Identity, const RigidBodyDescription& = RigidBodyDescription());
/** \brief
*/
KinematicActor* createKinematicActor(Shape*, const Matrix44& = Matrix44_Identity, const RigidBodyDescription& = RigidBodyDescription());
/** \brief
*/
KinematicActor* createKinematicActor(Shapes, const Matrix44& = Matrix44_Identity, const RigidBodyDescription& = RigidBodyDescription());
/** \brief Create a volume for collision detection in a shape, based on the PhysX Trigger system.
\note Volumes are RigidBodies can be treated as so, but can never be moved via forces.
*/
Volume* createVolume(Shape*, const Matrix44&, Callback*, Enums::VolumeCollisionType = Enums::VolumeCollisionType_All);
/** \brief;
*/
Volume* createVolume(Shapes, const Matrix44&, Callback*, Enums::VolumeCollisionType = Enums::VolumeCollisionType_All);
/** \brief
*/
KinematicController* createKinematicController(const Vec3& size, const Vec3& globalPosition);
/** \brief
*/
Material* createMaterial(const MaterialDescription& = MaterialDescription());
/** \brief
*/
Material* createMaterial(MaterialPrototype*);
/** \brief
*/
void registerMachine(Machine*);
/** \brief
*/
void unregisterMachine(Machine*);
/** \brief
*/
void destroyJoint(Joint*);
/** \brief
*/
SphericalJoint* createSphericalJoint(RigidBody* first, const SphericalJointDescription& = SphericalJointDescription());
/** \brief
*/
SphericalJoint* createSphericalJoint(RigidBody* first, RigidBody* second, const SphericalJointDescription& = SphericalJointDescription());
/** \brief
*/
FixedJoint* createFixedJoint(RigidBody* first, const FixedJointDescription& = FixedJointDescription());
/** \brief
*/
FixedJoint* createFixedJoint(RigidBody* first, RigidBody* second, const FixedJointDescription& = FixedJointDescription());
/** \brief
*/
RevoluteJoint* createRevoluteJoint(RigidBody* first, const RevoluteJointDescription& = RevoluteJointDescription());
/** \brief
*/
RevoluteJoint* createRevoluteJoint(RigidBody* first, RigidBody* second, const RevoluteJointDescription& = RevoluteJointDescription());
/** \brief
*/
void destroyMaterial(Material*);
/** \brief
*/
Material* getMaterial(const MaterialIdentifier&);
/** \brief
*/
Cloth* createCloth(const ClothDescription&, Renderable*, Enums::Priority render_priority = Enums::Priority_MediumLow);
/** \brief
*/
void destroyCloth(Cloth*);
/** \brief
*/
SoftBody* createSoftBody(const SoftBodyDescription&, Renderable*, Enums::Priority render_priority = Enums::Priority_MediumLow);
/** \brief
*/
void destroySoftBody(SoftBody*);
/** \brief
*/
Compartment* createCompartment(const CompartmentDescription&);
/** \brief Find a NxOgre Compartment based upon it's PhysX pointer equilvent.
\note This function is a little un-efficent. Try not to use it thousands of times at once in a frame if you have a huge amount of compartments.
*/
Compartment* findCompartment(NxCompartment*);
/** \brief
*/
void setGravity(const Vec3&);
/** \brief
*/
Vec3 getGravity(void) const;
/** \brief Returns true if any aligned bounding box is hit by the ray, but not what the box is and where it is relation to the ray.
\warning Make sure the ray's direction is normalised before using.
*/
bool raycastAnyBounds(const Ray&, Enums::ShapesType, unsigned int groups = INT_MAX, Real maxDistance = NxOgreRealMax) const;
/** \brief Returns true if any aligned bounding box is hit by the ray, but not what the box is and where it is relation to the ray.
\warning Make sure the ray's direction is normalised before using.
*/
bool raycastAnyBounds(const Ray&, Enums::ShapesType, int4 groupsMask, Real maxDistance = NxOgreRealMax) const;
/** \brief A more accurate version of raycastAnyBounds, but again does not give what shape was hit, or the distance to the ray.
\warning Make sure the ray's direction is normalised before using.
*/
bool raycastAnyShape(const Ray&, Enums::ShapesType, unsigned int groups = INT_MAX, Real maxDistance = NxOgreRealMax, RaycastCache = 0) const;
/** \brief Call the report's hitCallback
\warning This is not thread safe.
*/
unsigned int raycastAllBounds(const Ray&, Callback*, Enums::ShapesType, unsigned int group = INT_MAX, Real maxDistance = NxOgreRealMax, unsigned int hintFlags = -1) const;
/** \brief Call the report's hitCallback
*/
unsigned int raycastAllBounds(const Ray&, Callback*, Enums::ShapesType, int4 groupsMask, Real maxDistance = NxOgreRealMax, unsigned int hintFlags = -1) const;
/** \brief Return the closest RigidBody (and hit information), to accuracy of the bounds of the RigidBody.
*/
RaycastHit raycastClosestBounds(const Ray&, Enums::ShapesType, unsigned int groups = INT_MAX, Real maxDistance = NxOgreRealMax, unsigned int hintFlags = -1) const;
/** \brief Return the closest RigidBody, to shape accuracy, to the accuracy of the shape(s) of the RigidBody.
*/
RaycastHit raycastClosestShape(const Ray&, Enums::ShapesType, unsigned int groups = INT_MAX, Real maxDistance = NxOgreRealMax, unsigned int hintFlags = -1, RaycastCache = 0) const;
/** \brief Block all parallel raycast/overlap queries.
*/
void lockQueries();
/** \brief Unlock all parallel raycast/overlap queries.
*/
void unlockQueries();
/** \brief Required by TimeController. Advances the simulation state of this scene.
\note Do not use manually.
*/
bool advance(float user_deltaTime, const Enums::Priority&);
/** \brief Is the scene currently processing the physics for the next time step. You cannot
adjust the scene's state whilst it is processing.
*/
bool isProcessing(void) const;
/** \brief Get this timestep's debug renderable of the scene.
*/
DebugRenderable getDebugRenderable(void);
/** \internal
*/
NxScene* getScene(void);
/** \internal
*/
PhysXCallback* getPhysXCallback(void);
/** \brief Get the current timestep in the Scene.
*/
TimeStep& getTimeStep(void);
/** \brief
*/
void setActorFlags(RigidBody*, RigidBody*, unsigned int contact_flags);
protected: // Functions
/** \internal Use World::createScene()
*/
Scene(ScenePrototype*, NxPhysicsSDK*);
/** \internal Use World::destroyScene()
*/
~Scene(void);
protected: // Variables
/** \brief Name as a String. Use Scene::getName() to fetch, or Scene::setName() to set.
*/
String mName;
/** \internal What Scene is associated with
*/
NxScene* mScene;
/** \internal Local SDK pointer
*/
NxPhysicsSDK* mSDK;
/** \internal Master actors array
*/
Array<Actor*> mActors;
/** \internal Master scene geometries array
*/
Array<SceneGeometry*> mSceneGeometries;
/** \internal Master kinematic actors array
*/
Array<KinematicActor*> mKinematicActors;
/** \internal Master kinematic controllers array
*/
Array<KinematicController*> mKinematicControllers;
/** \internal Master volumes array
*/
Array<Volume*> mVolumes;
/** \internal Master materials array
*/
Array<Material*> mMaterials;
/** \internal Master joints array
*/
Array<Joint*> mJoints;
/** \internal Master machines array
*/
Array<Machine*> mMachines;
/** \internal
*/
Array<Machine*>::Iterator mMachineIterator;
/** \internal
*/
Array<Cloth*> mCloths;
/** \internal
*/
Array<SoftBody*> mSoftBodies;
/** \internal
*/
Array<Compartment*> mCompartments;
/** \internal
*/
Array<CompartmentArrayPair> mCompartmentsPair;
/** \internal Is Scene processing flag
*/
bool mProcessing;
/** \internal Scene processing priority
*/
Enums::Priority mProcessingPriority;
/** \internal Scene fetching priority
*/
Enums::Priority mFetchingPriority;
/** \internal Scene user callback.
*/
PhysXCallback* mPhysXCallback;
/** \internal Current SceneTimer
*/
SceneTimer* mSceneTimer;
/** \internal Can the scene be rendered
*/
bool mCanRender;
/** \internal
*/
TimeStep mTimeStep;
}; // class Scene
} // namespace NxOgre_Namespace
#endif
| [
"umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b"
] | [
[
[
1,
388
]
]
] |
8f6ffcb672d23b2bc99ebcf4dee05ecfe7e25899 | 02c6546f877536589f13ec4114b90072fb218092 | /Firewheel/CarTextured.h | d4279b74f20cda6de154753786d95b48b781cdc6 | [] | no_license | marksands/Themepark | 4f47b04facfb3283909233fd1fb99c44668d2cb2 | ecba18c41498a1d1b6c8d0d1c06b776d937ac0ac | refs/heads/master | 2020-04-06T01:37:05.907189 | 2011-12-01T09:39:35 | 2011-12-01T09:39:35 | 2,873,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,682 | h | //
// CarTextured.h
// Firewheel
//
// Created by Mark Sands on 11/9/11.
// Copyright (c) 2011 Mark Sands. All rights reserved.
//
////////////////////////////////////////////////////
// Implementation of the Ferris Wheel's Car Class //
///////////////////////////////////////////////////
#ifndef CAR_H
#define CAR_H
#include <GLTools.h>
#include <GLShaderManager.h>
#include <GLFrustum.h>
#include <GLBatch.h>
#include <GLFrame.h>
#include <GLMatrixStack.h>
#include <GLGeometryTransform.h>
#include <StopWatch.h>
#include <cmath>
#include <ctime>
const GLfloat BAR_BASE_RADIUS = 0.003f;
const GLfloat BAR_TOP_RADIUS = 0.003f;
const GLfloat BAR_LENGTH = 0.1f;
const int BAR_NUMBER_SLICES = 10;
const int BAR_NUMBER_STACKS = 10;
const GLfloat ROOF_BASE_RADIUS = 0.0f;
const GLfloat ROOF_TOP_RADIUS = 0.045f;
const GLfloat ROOF_LENGTH = 0.02f;
const int ROOF_NUMBER_SLICES = 10;
const int ROOF_NUMBER_STACKS = 10;
const GLfloat POLE_BASE_RADIUS = 0.005f;
const GLfloat POLE_TOP_RADIUS = 0.005f;
const GLfloat POLE_LENGTH = 0.1f;
const int POLE_NUMBER_SLICES = 10;
const int POLE_NUMBER_STACKS = 10;
const GLfloat FLOOR_SCALE[] = { 1.0f, 1.0f, 0.4f };
const GLfloat FLOOR_RADIUS = 0.0375f;
const int FLOOR_NUMBER_SLICES = 10;
const int FLOOR_NUMBER_STACKS = 10;
const GLfloat WALL_BASE_RADIUS = 0.04f;
const GLfloat WALL_TOP_RADIUS = 0.04f;
const GLfloat WALL_LENGTH = 0.04f;
const int WALL_NUMBER_SLICES = 10;
const int WALL_NUMBER_STACKS = 10;
const GLfloat WHITE_COLOR[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat LIGHT_POSITION[] = { 2.0f, 8.0f, 5.0f, 1.0f };
class Car
{
public:
Car();
void SetupRenderingContext();
void Update();
void Draw(GLMatrixStack &modelViewMatrix, GLShaderManager &shaderManager, GLGeometryTransform &transformPipeline,
M3DVector4f &vLightEyePos, GLfloat totalCarRot, GLuint wallTexture, GLuint carTexture[]);
private:
GLTriangleBatch barBatch;
GLTriangleBatch roofBatch;
GLTriangleBatch poleBatch;
GLTriangleBatch floorBatch;
GLTriangleBatch wallBatch;
};
// Default Constructor
Car::Car()
{
}
// Set up all structures needed to render the Ferris wheel car objects.
void Car::SetupRenderingContext()
{
gltMakeCylinder(barBatch, BAR_BASE_RADIUS, BAR_TOP_RADIUS, BAR_LENGTH, BAR_NUMBER_SLICES, BAR_NUMBER_STACKS);
gltMakeCylinder(roofBatch, ROOF_BASE_RADIUS, ROOF_TOP_RADIUS, ROOF_LENGTH, ROOF_NUMBER_SLICES, ROOF_NUMBER_STACKS);
gltMakeCylinder(poleBatch, POLE_BASE_RADIUS, POLE_TOP_RADIUS, POLE_LENGTH, POLE_NUMBER_SLICES, POLE_NUMBER_STACKS);
gltMakeSphere(floorBatch, FLOOR_RADIUS, FLOOR_NUMBER_SLICES, FLOOR_NUMBER_STACKS);
gltMakeCylinder(wallBatch, WALL_BASE_RADIUS, WALL_TOP_RADIUS, WALL_LENGTH, WALL_NUMBER_SLICES, WALL_NUMBER_STACKS);
}
// Timer-driven function to update positions, orientations,
// etc., of all changing parts of the Ferris wheel car.
void Car::Update()
{
}
// Render the components of the Ferris wheel car.
void Car::Draw(GLMatrixStack &modelViewMatrix, GLShaderManager &shaderManager, GLGeometryTransform &transformPipeline,
M3DVector4f &vLightEyePos, GLfloat totalCarRot, GLuint wallTexture, GLuint carTexture[])
{
// Get the light position in eye space
M3DVector4f vLightTransformed;
M3DMatrix44f mCamera;
modelViewMatrix.GetMatrix(mCamera);
m3dTransformVector4(vLightTransformed, LIGHT_POSITION, mCamera);
modelViewMatrix.PushMatrix();
modelViewMatrix.PushMatrix();
glBindTexture(GL_TEXTURE_2D, carTexture[0]);
modelViewMatrix.Translate(0.0f, 0.0f, -0.5f * BAR_LENGTH);
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF, modelViewMatrix.GetMatrix(),
transformPipeline.GetProjectionMatrix(), vLightTransformed, WHITE_COLOR, 0);
barBatch.Draw();
modelViewMatrix.PopMatrix();
modelViewMatrix.Rotate(-totalCarRot, 0.0f, 0.0f, 1.0f);
modelViewMatrix.Rotate(90.0f, 1.0f, 0.0f, 0.0f);
modelViewMatrix.PushMatrix();
glBindTexture(GL_TEXTURE_2D, carTexture[1]);
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF, modelViewMatrix.GetMatrix(),
transformPipeline.GetProjectionMatrix(), vLightTransformed, WHITE_COLOR, 0);
roofBatch.Draw();
modelViewMatrix.PopMatrix();
modelViewMatrix.PushMatrix();
glBindTexture(GL_TEXTURE_2D, carTexture[2]);
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF, modelViewMatrix.GetMatrix(),
transformPipeline.GetProjectionMatrix(), vLightTransformed, WHITE_COLOR, 0);
poleBatch.Draw();
modelViewMatrix.PopMatrix();
modelViewMatrix.PushMatrix();
glBindTexture(GL_TEXTURE_2D, carTexture[4]);
modelViewMatrix.Translate(0.0f, 0.0f, POLE_LENGTH);
modelViewMatrix.Scale(FLOOR_SCALE[0], FLOOR_SCALE[1], FLOOR_SCALE[2]);
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF, modelViewMatrix.GetMatrix(),
transformPipeline.GetProjectionMatrix(), vLightTransformed, WHITE_COLOR, 0);
floorBatch.Draw();
modelViewMatrix.PopMatrix();
modelViewMatrix.PushMatrix();
glBindTexture(GL_TEXTURE_2D, wallTexture);
modelViewMatrix.Translate(0.0f, 0.0f, POLE_LENGTH);// POLE_LENGTH - WALL_LENGTH);
modelViewMatrix.Rotate(90.0f, 0.0f, 0.0f, 1.0f);
modelViewMatrix.Rotate(180.0f, 0.0f, 1.0f, 0.0f);
shaderManager.UseStockShader(GLT_SHADER_TEXTURE_POINT_LIGHT_DIFF, modelViewMatrix.GetMatrix(),
transformPipeline.GetProjectionMatrix(), vLightTransformed, WHITE_COLOR, 0);
wallBatch.Draw();
modelViewMatrix.PopMatrix();
modelViewMatrix.PopMatrix();
}
#endif | [
"[email protected]"
] | [
[
[
1,
151
]
]
] |
d082f1b2467950703272967454a0513da7ef385a | d1dc408f6b65c4e5209041b62cd32fb5083fe140 | /src/gameobjects/structures/cRocketTurret.cpp | 907b855cb44513ffc32f115a88dfd13bee81a5e6 | [] | no_license | dmitrygerasimuk/dune2themaker-fossfriendly | 7b4bed2dfb2b42590e4b72bd34bb0f37f6c81e37 | 89a6920b216f3964241eeab7cf1a631e1e63f110 | refs/heads/master | 2020-03-12T03:23:40.821001 | 2011-02-19T12:01:30 | 2011-02-19T12:01:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,673 | cpp | #include "../../include/d2tmh.h"
// Constructor
cRocketTurret::cRocketTurret() {
// other variables (class specific)
iHeadFacing=FACE_UP; // (for turrets only) what is this structure facing at?
iShouldHeadFacing=FACE_UP; // where should we look face at?
iTargetID=-1; // target id
TIMER_fire=0;
TIMER_turn=0;
TIMER_guard=0; // timed 'area scanning'
}
int cRocketTurret::getType() {
return RTURRET;
}
cRocketTurret::~cRocketTurret()
{
}
void cRocketTurret::think()
{
int iMyIndex=-1;
for (int i=0; i < MAX_STRUCTURES; i++) {
if (structure[i] == this)
{
iMyIndex=i;
break;
}
}
// this should not happen, but just in case
if (iMyIndex < 0) {
return;
}
if (player[getOwner()].bEnoughPower() == false) {
return; // do not fire a thing now
}
// turning & shooting
if (iTargetID > -1)
{
if (unit[iTargetID].isValid())
{
// first make sure we face okay!
int iCellX=iCellGiveX(getCell());
int iCellY=iCellGiveY(getCell());
int iTargetX = iCellGiveX(unit[iTargetID].iCell);
int iTargetY = iCellGiveY(unit[iTargetID].iCell);
int d = fDegrees(iCellX, iCellY, iTargetX, iTargetY);
int f = face_angle(d); // get the angle
// set facing
iShouldHeadFacing = f;
if (iShouldHeadFacing == iHeadFacing || (unit[iTargetID].iType == ORNITHOPTER))
{
TIMER_fire++;
int iDistance=9999;
int iSlowDown=250;
if (getType() == RTURRET)
iSlowDown=450;
if (unit[iTargetID].isValid())
{
// calculate distance
iDistance = ABS_length(iCellX, iCellY, iTargetX, iTargetY);
if (iDistance > structures[getType()].sight)
iTargetID=-1;
}
else
iTargetID=-1;
if (iTargetID < 0)
return;
if (TIMER_fire > iSlowDown)
{
int iTargetCell = unit[iTargetID].iCell;
int iBullet = BULLET_TURRET;
if (getType() == RTURRET && iDistance > 3)
iBullet = ROCKET_RTURRET;
else
{
int iShootX=(iDrawX() + 16 ) + (mapCamera->getX()*32);
int iShootY=(iDrawY() + 16 ) + (mapCamera->getY()*32);
int bmp_head = convert_angle(iHeadFacing);
PARTICLE_CREATE(iShootX, iShootY, OBJECT_TANKSHOOT, -1, bmp_head);
}
int iBull = create_bullet(iBullet, getCell(), iTargetCell, -1, iMyIndex);
if (unit[iTargetID].iType == ORNITHOPTER)
{
// it is a homing missile!
bullet[iBull].iHoming = iTargetID;
bullet[iBull].TIMER_homing = 200;
}
TIMER_fire=0;
}
}
else
{
TIMER_turn++;
int iSlowDown = 200;
if (TIMER_turn > iSlowDown)
{
TIMER_turn=0;
int d = 1;
int toleft = (iHeadFacing + 8) - iShouldHeadFacing;
if (toleft > 7) toleft -= 8;
int toright = abs(toleft-8);
if (toright == toleft) d = -1+(rnd(2));
if (toleft > toright) d = 1;
if (toright > toleft) d = -1;
iHeadFacing += d;
if (iHeadFacing < 0)
iHeadFacing = 7;
if (iHeadFacing > 7)
iHeadFacing = 0;
} // turning
}
}
else
iTargetID=-1;
}
// think like base class
cAbstractStructure::think();
}
void cRocketTurret::think_animation() {
cAbstractStructure::think_animation();
}
void cRocketTurret::think_guard() {
// no power = no defense
if (player[getOwner()].bEnoughPower() == false) {
return;
}
TIMER_guard++;
if (TIMER_guard > 10) {
int iCellX = iCellGiveX(getCell());
int iCellY = iCellGiveY(getCell());
int iDistance=9999; // closest distance
int iAir=-1; // aircraft (prioritized!)
int iWorm=-1; // worm lowest priority
int iDanger=-1; // danger id (unit to attack)
iTargetID=-1; // no target
// scan area for units
for (int i=0; i < MAX_UNITS; i++)
{
// is valid
if (unit[i].isValid())
{
bool bAlly=player[getOwner()].iTeam == player[unit[i].iPlayer].iTeam;
// not ours and its visible
if (unit[i].iPlayer != getOwner() &&
mapUtils->isCellVisibleForPlayerId(getOwner(), unit[i].iCell) &&
bAlly == false) {
int distance = ABS_length(iCellX, iCellY, iCellGiveX(unit[i].iCell), iCellGiveY(unit[i].iCell));
// when worm or ornithopter is in range, they are not limited to the iDistance (closest
// unit) range.
if (distance <= structures[getType()].sight) {
if (unit[i].iType == ORNITHOPTER) {
iAir=i;
} else if (unit[i].iType == SANDWORM) {
iWorm=i;
}
}
// when distance < closest range so far, this one is the most dangerous.
if (distance <= structures[getType()].sight && distance < iDistance)
{
// ATTACK
iDistance = distance;
iDanger=i;
}
}
}
}
// set target
if (iAir > -1) {
iTargetID = iAir;
} else if (iDanger > -1) {
iTargetID = iDanger;
} else if (iWorm > -1) {
iTargetID = iWorm; // else pick worm
}
TIMER_guard=0-rnd(20); // redo
}
}
/* STRUCTURE SPECIFIC FUNCTIONS */
| [
"stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151"
] | [
[
[
1,
246
]
]
] |
5a2ced00e326bcce0c5a6ef0f6f4e4972a3116fc | b308f1edaab2be56eb66b7c03b0bf4673621b62f | /Code/Game/GameDll/GameStateRecorder.cpp | e165609069c18e2d1e2d028ddb618c963b00de09 | [] | no_license | blockspacer/project-o | 14e95aa2692930ee90d098980a7595759a8a1f74 | 403ec13c10757d7d948eafe9d0a95a7f59285e90 | refs/heads/master | 2021-05-31T16:46:36.814786 | 2011-09-16T14:34:07 | 2011-09-16T14:34:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,141 | cpp | ////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: GameStateRecorder.cpp
// Version: v1.00
// Created: 3/2008 by Luciano Morpurgo.
// Compilers: Visual Studio.NET
// Description: Checks the player and other game specific objects' states and communicate them to the TestManager
// Implements IGameStateRecorder
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "IGame.h"
#include "IGameFramework.h"
#include "IActorSystem.h"
#include "GameStateRecorder.h"
#include "CryAction.h"
#include "Player.h"
#include "Item.h"
#include "Weapon.h"
#include "Accessory.h"
#include "AmmoPickup.h"
#include "Inventory.h"
#include "OffHand.h"
#include <IAgent.h>
#include <IAIObjectManager.h>
// avoid fake mistakes when health is raising progressively
// there can be small mismatches due to time-dependent health regeneration
#define CHECK_MISMATCH(cur,rec,thr) (cur < rec-thr || cur > rec+thr)
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
bool IsAmmoPickup(CItem* pItem)
{
return strcmp(pItem->GetEntity()->GetClass()->GetName(), "CustomAmmoPickup")==0;
}
///////////////////////////////////////////////////////////////////////
bool IsAmmoPickup(const char* className)
{
return strcmp(className, "CustomAmmoPickup")==0;
}
///////////////////////////////////////////////////////////////////////
bool IsGrenade(const char* className)
{
return className && (!strcmp(className,"OffhandGrenade") ||
!strcmp(className,"OffhandSmoke") ||
!strcmp(className,"OffhandFlashbang") ||
!strcmp(className,"OffhandNanoDistuptor"));
}
///////////////////////////////////////////////////////////////////////
bool IsAmmoGrenade(const char* className)
{
return className && (!strcmp(className,"explosivegrenade") ||
!strcmp(className,"flashbang") ||
!strcmp(className,"smokegrenade") ||
!strcmp(className,"empgrenade"));
}
///////////////////////////////////////////////////////////////////////
CGameStateRecorder::CGameStateRecorder()
{
m_mode = GPM_Disabled;
m_bRecording = false;
m_bEnable = false;
m_bLogWarning = true;
m_currentFrame = 0;
m_pSingleActor = NULL;
//m_pRecordGameEventFtor = new RecordGameEventFtor(this);
m_demo_actorInfo = REGISTER_STRING( "demo_actor_info","player",0,"name of actor which game state info is displayed" );
m_demo_actorFilter = REGISTER_STRING( "demo_actor_filter","player",0,"name of actor which game state is recorded ('player','all',<entity name>" );
REGISTER_CVAR2( "demo_force_game_state",&m_demo_forceGameState,2,0,"Forces game state values into game while playing timedemo: only health and suit energy (1) or all (2)" );
}
////////////////////////////////////////////////////////////////////////////
CGameStateRecorder::~CGameStateRecorder()
{
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::Release()
{
// if(m_pRecordGameEventFtor)
//delete m_pRecordGameEventFtor;
IConsole* pConsole = gEnv->pConsole;
if(pConsole)
{
pConsole->UnregisterVariable( "demo_force_game_state", true );
pConsole->UnregisterVariable( "demo_actor_info", true );
pConsole->UnregisterVariable( "demo_actor_filter", true );
}
delete this;
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::Enable(bool bEnable, bool bRecording)
{
m_bRecording = bRecording;
m_bEnable = bEnable;
//m_mode = mode;
if(!bEnable)
m_mode = GPM_Disabled;
if(m_bEnable && bRecording)
{
gEnv->pGame->GetIGameFramework()->GetIGameplayRecorder()->RegisterListener(this);
//CActor *pActor = static_cast<CActor *>(gEnv->pGame->GetIGameFramework()->GetClientActor());
//if(pActor && !pActor->GetSpectatorMode() && pActor->IsPlayer() && ((CPlayer*)pActor)->GetNanoSuit())
//((CPlayer*)pActor)->GetNanoSuit()->AddListener(this);
}
else
{
gEnv->pGame->GetIGameFramework()->GetIGameplayRecorder()->UnregisterListener(this);
//CActor *pActor = static_cast<CActor *>(gEnv->pGame->GetIGameFramework()->GetClientActor());
//if(pActor && !pActor->GetSpectatorMode() && pActor->IsPlayer() && ((CPlayer*)pActor)->GetNanoSuit())
//((CPlayer*)pActor)->GetNanoSuit()->RemoveListener(this);
}
if(m_bEnable)
StartSession();
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::AddActorToStats(const CActor* pActor)
{
if(m_bRecording)
DumpWholeGameState(pActor);
else
{
IEntity* pEntity = pActor->GetEntity();
EntityId id;
if(pEntity && (id=pEntity->GetId()))
{
m_GameStates.insert(std::make_pair(id,SActorGameState()));
}
}
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::StartSession()
{
m_GameStates.clear();
m_itSingleActorGameState = m_GameStates.end();
m_IgnoredEvents.clear();
const char* filterName = m_demo_actorFilter->GetString();
// send game events to record the initial game state
/* if(m_mode)
{
CActor *pActor = static_cast<CActor *>(gEnv->pGame->GetIGameFramework()->GetClientActor());
*/
m_pSingleActor = GetActorOfName(filterName);
if(m_pSingleActor)// && !pActor->GetSpectatorMode() && pActor->IsPlayer())
{
m_mode = GPM_SingleActor;
AddActorToStats(m_pSingleActor);
m_itSingleActorGameState = m_GameStates.begin();// position of requested actor's id (player by default)
}
// }
else if (!strcmpi(filterName,"all"))
{
IAIObjectManager* pAIObjMgr = gEnv->pAISystem->GetAIObjectManager();
m_mode = GPM_AllActors;
{
AutoAIObjectIter it(pAIObjMgr->GetFirstAIObject(OBJFILTER_TYPE, AIOBJECT_ACTOR));
for(; it->GetObject(); it->Next())
{
IAIObject* pObject = it->GetObject();
if(pObject)
{
CActor* pActor = static_cast<CActor *>(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(pObject->GetEntityID()));
if(pActor)
AddActorToStats(pActor);
}
}
}
{
AutoAIObjectIter it(pAIObjMgr->GetFirstAIObject(OBJFILTER_TYPE, AIOBJECT_VEHICLE));
for(; it->GetObject(); it->Next())
{
IAIObject* pObject = it->GetObject();
if(pObject)
{
CActor* pActor = static_cast<CActor *>(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(pObject->GetEntityID()));
if(pActor)
AddActorToStats(pActor);
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::DumpWholeGameState(const CActor* pActor)
{
GameplayEvent event;
IEntity* pEntity = pActor->GetEntity();
// health
float health = (float)pActor->GetHealth();
event.event = eGE_HealthChanged;
event.value = health;
SendGamePlayEvent(pEntity,event);
// Inventory
CInventory *pInventory = (CInventory*)(pActor->GetInventory());
if(!pInventory)
return;
int count = pInventory->GetCount();
for(int i=0; i<count; ++i)
{
EntityId itemId = pInventory->GetItem(i);
CItem* pItem=NULL;
TItemName itemName = GetItemName(itemId,&pItem);
if(pItem && itemName)
{
event.event = eGE_ItemPickedUp;
event.description = itemName;
SendGamePlayEvent(pEntity,event);
if(pActor->GetCurrentItem() == pItem)
{
event.event = eGE_ItemSelected;
event.description = itemName;
event.value = 1; // for initialization
SendGamePlayEvent(pEntity,event);
}
CWeapon* pWeapon = (CWeapon*)(pItem->GetIWeapon());
if(pWeapon)
{
IEntityClass* pItemClass = pWeapon->GetEntity()->GetClass();
if(pItemClass && !strcmpi(pItemClass->GetName(),"binoculars"))
continue; // no fire mode or ammo recorded for binocular (which is a weapon)
// fire mode
int fireModeIdx = pWeapon->GetCurrentFireMode();
event.event = eGE_WeaponFireModeChanged;
event.value = (float)fireModeIdx;
event.description = itemName;
SendGamePlayEvent(pEntity,event);
// count ammo
for(SWeaponAmmo weaponAmmo = pWeapon->GetFirstAmmo(); weaponAmmo.pAmmoClass ; weaponAmmo = pWeapon->GetNextAmmo())
{
const char* ammoClass;
if(weaponAmmo.pAmmoClass && (ammoClass = weaponAmmo.pAmmoClass->GetName()))
{
event.event = eGE_AmmoCount;
event.value = (float)weaponAmmo.count;
event.extra = (void*)ammoClass;
event.description = (const char*)itemName;
SendGamePlayEvent(pEntity,event);
}
}
}
}
}
count = pInventory->GetAccessoryCount();
for(int i=0; i< count; i++)
{
const char* accessory = pInventory->GetAccessory(i);
if(accessory && strlen(accessory))
{
IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(accessory);
if(pClass)
{
TItemName classItem = pClass->GetName();
event.event = eGE_AccessoryPickedUp;
//event.value = classIdx;
event.description = classItem;
SendGamePlayEvent(pEntity,event);
}
}
}
int nInvAmmo = pInventory->GetAmmoPackCount();
pInventory->AmmoIteratorFirst();
for(int j=0 ; !pInventory->AmmoIteratorEnd(); j++, pInventory->AmmoIteratorNext())
{
const IEntityClass* pAmmoClass = pInventory->AmmoIteratorGetClass();
if(pAmmoClass)
{
const char* ammoClassName = pAmmoClass->GetName();
int ammoCount = pInventory->AmmoIteratorGetCount();
GameplayEvent event;
event.event = eGE_AmmoPickedUp;
event.description = ammoClassName;
event.value = (float)ammoCount;
SendGamePlayEvent(pEntity,event);
}
}
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::Update()
{
if(m_bRecording)
{
switch(m_mode)
{
case GPM_SingleActor:
{
//CActor *pActor = static_cast<CActor *>(gEnv->pGame->GetIGameFramework()->GetClientActor());
//if(pActor && !pActor->GetSpectatorMode() && pActor->IsPlayer())
if(m_pSingleActor)
{
float health = (float)m_pSingleActor->GetHealth();
if(m_itSingleActorGameState != m_GameStates.end())
{
SActorGameState& playerState = m_itSingleActorGameState->second;
//if( health!= playerState.health)
{
// playerState.health = health;
GameplayEvent event;
event.event = eGE_HealthChanged;
event.value = health;
OnGameplayEvent(m_pSingleActor->GetEntity(),event);
}
}
}
}
break;
case GPM_AllActors:
default:
break;
}
}
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::OnRecordedGameplayEvent(IEntity *pEntity, const GameplayEvent &event, int currentFrame, bool bRecording)
{
EntityId id;
m_currentFrame = currentFrame;
int demo_forceGameState = 0;
if(!bRecording)
{
ICVar *pVar = gEnv->pConsole->GetCVar( "demo_force_game_state" );
if(pVar)
demo_forceGameState = pVar->GetIVal();
}
if(!pEntity || !(id = pEntity->GetId()))
return;
if(m_IgnoredEvents.size())
if(event.event == m_IgnoredEvents[0])
{
m_IgnoredEvents.erase(m_IgnoredEvents.begin());
return;
}
TGameStates::iterator itActor = m_GameStates.find(id);
if(itActor == m_GameStates.end())
{
m_GameStates.insert(std::make_pair(id,SActorGameState()));
itActor = m_GameStates.find(id);
}
if(itActor == m_GameStates.end())
{
GameWarning("TimeDemo:GameState: actor %s not found in records",pEntity->GetName());
return;
}
SActorGameState& gstate = itActor->second;
switch(event.event)
{
case eGE_HealthChanged:
{
gstate.health = event.value;
if(!m_bRecording)
{
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor)
{
if(m_bLogWarning)
{
if(CHECK_MISMATCH(pActor->GetHealth(), gstate.health,10))
{
if(!gstate.bHealthDifferent)
{
GameWarning("TimeDemo:GameState: Frame %d - Actor %s - HEALTH mismatch (%d, %d)",m_currentFrame,pEntity->GetName(), static_cast<int>(pActor->GetHealth()), static_cast<int>(gstate.health));
gstate.bHealthDifferent = true;
}
}
else
gstate.bHealthDifferent = false;
}
if( demo_forceGameState)
pActor->SetHealth(gstate.health);
}
}
}
break;
case eGE_WeaponFireModeChanged:
{
TItemName sel = (event.description);
if(sel)
{
TItemContainer& Items = gstate.Items;
TItemContainer::iterator iti = Items.find(sel);
uint8 recFireModeIdx = uint8(event.value);
if(iti != Items.end())
iti->second.fireMode = recFireModeIdx;
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor && pActor->GetInventory())
{
IItem* pItem = pActor->GetInventory()->GetItemByName(sel);
CWeapon* pWeapon;
if(pItem && (pWeapon = (CWeapon*)(pItem->GetIWeapon())))
{
int fireModeIdx = pWeapon->GetCurrentFireMode();
if(m_bLogWarning)
{
CheckDifference(recFireModeIdx,fireModeIdx,"TimeDemo:GameState: Frame %d - Actor %s - FIRE MODE mismatch for weapon %s (rec:%d, cur:%d)",pEntity,pItem->GetEntity() ? pItem->GetEntity()->GetName() : "(null)");
}
if(demo_forceGameState==2 && fireModeIdx!= recFireModeIdx)
pWeapon->SetCurrentFireMode(recFireModeIdx);
}
}
}
}
break;
case eGE_WeaponReload:
{
const char* ammoType = event.description;
TAmmoContainer& ammoMags = gstate.AmmoMags;
TAmmoContainer::iterator it = ammoMags.find(ammoType);
if(it!=ammoMags.end())
{
it->second -= (uint16)event.value;
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor)
{
CInventory* pInventory = (CInventory*)(pActor->GetInventory());
if(pInventory)
{
{
IEntityClass* pAmmoClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(ammoType);
if(pAmmoClass)
{
if(m_bLogWarning)
CheckDifference(it->second,pInventory->GetAmmoCount(pAmmoClass),"TimeDemo:GameState: Frame %d - Actor %s - WEAPON RELOAD, ammo count mismatch for ammo class %s (rec:%d, cur:%d)",pEntity,ammoType);
if(demo_forceGameState == 2)
pInventory->SetAmmoCount(pAmmoClass,it->second);
}
}
}
}
}
}
break;
case eGE_ItemSelected:
{
TItemName itemName = event.description;
gstate.itemSelected = itemName;
if(itemName)
{
if( !bRecording && (event.value > 0 || demo_forceGameState==2)) // EVENT.VALUE > 0 means initialization
{
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor && pActor->GetInventory())
{
IItem* pItem = pActor->GetInventory()->GetItemByName(itemName);
if(pItem)
pActor->SelectItem(pItem->GetEntityId(),false);
}
}
}
if(m_bLogWarning)
{
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor)
{
IItem* pItem = pActor->GetCurrentItem();
const char* curItemName= pItem && pItem->GetEntity() ? pItem->GetEntity()->GetName(): NULL;
CheckDifferenceString(itemName,curItemName,"TimeDemo:GameState: Frame %d - Actor %s - SELECTED ITEM mismatch (rec:%s, cur:%s)",pEntity);
}
}
break;
}
break;
case eGE_ItemExchanged:
{
// prevent unwanted record/play mismatch error with current item during item exchanging
// two unneeded game events are sent (selecting fists)
m_IgnoredEvents.push_back(eGE_ItemSelected);
m_IgnoredEvents.push_back(eGE_ItemSelected);
}
break;
case eGE_ItemPickedUp:
{
TItemName sel = (TItemName)event.description;
// gstate.itemSelected = sel;
TItemContainer& Items = gstate.Items;
TItemContainer::iterator it = Items.find(sel);
if(it == Items.end())
{
Items.insert(std::make_pair(sel,SItemProperties()));
it = Items.find(sel);
}
if(it != Items.end())
{
it->second.count++;
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor && !m_bRecording)
{
CInventory* pInventory = (CInventory*)(pActor->GetInventory());
if(pInventory)
{
// just check if the item is the inventory
if(m_bLogWarning && !pInventory->GetItemByName(sel))
GameWarning("TimeDemo:GameState: Frame %d - Actor %s - Recorded PICKED UP ITEM class '%s' not found in current inventory",m_currentFrame,pEntity->GetName(),sel);
if(demo_forceGameState == 2)
{
IEntity* pItemEntity = gEnv->pEntitySystem->FindEntityByName(sel);
if(pItemEntity)
pInventory->AddItem(pItemEntity->GetId());
else
GameWarning("TimeDemo:GameState: Frame %d - Actor %s - PICKED UP ITEM entity %s not found in level",m_currentFrame,pEntity->GetName(),sel);
}
}
}
}
else if(m_bLogWarning)
{
if(!sel)
sel = "(null)";
GameWarning("TimeDemo:GameState: Frame %d - Actor %s - PICKED UP ITEM %s not found in recorded inventory",m_currentFrame,pEntity->GetName(),sel);
}
}
break;
case eGE_AmmoPickedUp:
{
uint16 ammoCount = (uint16)(event.value);
TItemName sel = (TItemName)event.description;
TAmmoContainer& Ammo = gstate.AmmoMags;
TAmmoContainer::iterator it = Ammo.find(sel);
if(it == Ammo.end())
Ammo.insert(std::make_pair(sel,ammoCount));
else
it->second = ammoCount;
if( !m_bRecording)
{
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor)
{
CInventory* pInventory = (CInventory*)(pActor->GetInventory());
if(pInventory)
{
IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(sel);
if(m_bLogWarning)
CheckDifference(ammoCount,pInventory->GetAmmoCount(pClass),"TimeDemo:GameState: Frame %d - Actor %s - AMMO PICKEDUP: count mismatch for ammo class %s (rec:%d, cur:%d)", pEntity,sel);
if(demo_forceGameState == 2)
pInventory->SetAmmoCount(pClass,ammoCount);
}
}
}
}
break;
case eGE_AccessoryPickedUp:
{
TItemName sel = (TItemName)event.description;
// gstate.itemSelected = sel;
TAccessoryContainer& Accessories = gstate.Accessories;
TAccessoryContainer::iterator it = Accessories.find(sel);
if(it == Accessories.end())
{
Accessories.insert(std::make_pair(sel,1));
}
else
it->second++;
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor)
{
CInventory* pInventory = (CInventory*)(pActor->GetInventory());
if(pInventory)
{
IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(sel);
if(m_bLogWarning && !pInventory->HasAccessory(pClass))
GameWarning("TimeDemo:GameState: Frame %d - Actor %s - ACCESSORY PICKEDUP %s not found in current inventory", m_currentFrame, pEntity->GetName(),sel ? sel:"(null)");
if(demo_forceGameState == 2 && pClass)
pInventory->AddAccessory(pClass);// doesn't actually add it if it's there already
}
}
}
break;
case eGE_ItemDropped:
{
TItemName sel = (TItemName)event.description;
//gstate.itemSelected = sel;
TItemContainer& Items = gstate.Items;
TItemContainer::iterator it = Items.find(sel);
if(it != Items.end())
{
it->second.count--;
if(it->second.count<=0)
Items.erase(it);
if(demo_forceGameState == 2)
{
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor)
{
CInventory* pInventory = (CInventory*)(pActor->GetInventory());
if(pInventory)
{
IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(sel);
if(pClass)
{
EntityId itemId = pInventory->GetItemByClass(pClass);
if(itemId)
pInventory->RemoveItem(itemId);
}
}
}
}
}
else
GameWarning("TimeDemo:GameState: Frame %d - Actor %s - ITEM DROPPED, wrong item selected (%s)",m_currentFrame,pEntity->GetName(),sel);
}
break;
case eGE_AmmoCount:
{
TItemContainer& Items = gstate.Items;
TItemName itemClassDesc = event.description;
TItemContainer::iterator it = Items.find(itemClassDesc);
if(it != Items.end())
{
SItemProperties& item = it->second;
const char* ammoClassDesc = (const char*)(event.extra);
if(ammoClassDesc)
{
string szAmmoClassDesc(ammoClassDesc);
bool bAmmoMag = IsAmmoGrenade(ammoClassDesc);
TAmmoContainer& itemAmmo = bAmmoMag ? gstate.AmmoMags : item.Ammo;
if(itemAmmo.find(szAmmoClassDesc)==itemAmmo.end())
itemAmmo.insert(std::make_pair(szAmmoClassDesc,int(event.value)));
else
itemAmmo[szAmmoClassDesc] = (uint16)event.value;
if(!bRecording && (m_bLogWarning || demo_forceGameState==2))
{
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor)
{
CInventory* pInventory = (CInventory*)(pActor->GetInventory());
if(pInventory)
{
IItem* pItem = pInventory->GetItemByName(itemClassDesc);
if(pItem)
{
CWeapon* pWeapon = (CWeapon*)(pItem->GetIWeapon());
if(pWeapon)
{
IEntityClass* pAmmoClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(ammoClassDesc);
if(pAmmoClass)
{
if(m_bLogWarning)
{
int curAmmoCount = (bAmmoMag ? pInventory->GetAmmoCount(pAmmoClass) :
pWeapon->GetAmmoCount(pAmmoClass));
CheckDifference( int(event.value),curAmmoCount,"TimeDemo:GameState: Frame %d - Actor %s - AMMO COUNT mismatch for ammo class %s (rec:%d, cur:%d)",pEntity,ammoClassDesc);
}
if(demo_forceGameState==2)
pWeapon->SetAmmoCount(pAmmoClass,int(event.value));
}
}
}
}
}
}
}
else
GameWarning("TimeDemo:GameState: Frame %d - Actor %s - AMMO COUNT null ammoClass descriptor",m_currentFrame,pEntity->GetName());
}
else
GameWarning("TimeDemo:GameState: Frame %d - Actor %s - AMMO COUNT wrong item selected (%s)",m_currentFrame,pEntity->GetName(),itemClassDesc);
}
break;
case eGE_AttachedAccessory:
{
// always force attachment of accessory to the current weapon
// kind of a workaround, the HUD weapon modifier menu is spawned during timedemo playback
// but it doesn't use recorded input events
if(!bRecording)
{
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor)
{
CInventory* pInventory = (CInventory*)(pActor->GetInventory());
if(pInventory)
{
const char* sel = event.description;
IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(sel);
if(!sel)
sel = "(null)";
if(!pInventory->HasAccessory(pClass))
{
if(m_bLogWarning)
GameWarning("TimeDemo:GameState: Frame %d - Actor %s - ATTACHED ACCESSORY %s not found in current inventory", m_currentFrame,pEntity->GetName(),sel);
}
else
{
CItem* pCurrentItem = (CItem*)(pActor->GetCurrentItem());
if(pCurrentItem)
pCurrentItem->SwitchAccessory(sel);
}
}
}
}
}
break;
case eGE_EntityGrabbed:
{
if(demo_forceGameState==2)
{
TItemName itemName = event.description;
if(itemName)
{
IEntity * pGrabbedEntity = gEnv->pEntitySystem->FindEntityByName(itemName);
if(pGrabbedEntity)
{
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(pActor)
{
IItem* pItem = GetItemOfName(pActor,itemName);
if(!pItem)
{
// it's a pickable entity, won't end up in the inventory
//(otherwise it would be managed by eGE_ItemPickedUp)
COffHand* pOffHand = static_cast<COffHand*>(pActor->GetWeaponByClass(CItem::sOffHandClass));
if(pOffHand && !pOffHand->GetPreHeldEntityId())
pOffHand->ForcePickUp(pGrabbedEntity->GetId());
}
}
}
}
}
}
break;
default:
break;
}
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::OnGameplayEvent(IEntity *pEntity, const GameplayEvent &event)
{
EntityId id;
if(!pEntity || !(id = pEntity->GetId()))
{
GameWarning("TimeDemo:GameState::OnGamePlayEvent: Entity not found");
return;
}
CActor *pActor = (CActor*)(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(id));
if(!pActor)
{
GameWarning("TimeDemo:GameState::OnGamePlayEvent: Entity %s has no actor", pEntity->GetName());
return;
}
GameplayEvent event2 = event;
event2.extra = 0;// event2 is the forwarded event, extra either will be not used by the listener or re-set as a string
uint8 eType = event.event;
bool bPlayer = (pActor->IsPlayer() && m_mode);
if(bPlayer || m_mode==GPM_AllActors)
{
//items
switch(eType)
{
case eGE_ItemPickedUp:
{
CheckInventory(pActor,0);//,*m_pRecordGameEventFtor);
}
break;
case eGE_ItemDropped:
{
TItemName itemName = GetItemName(EntityId(event.extra));
if(!itemName ) //if(itemIdx < 0)
break;
event2.description = itemName;
SendGamePlayEvent(pEntity,event2);
IEntity* pItemEntity = gEnv->pEntitySystem->FindEntityByName(itemName);
if(!pItemEntity)
break;
IItem* pItem = g_pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pItemEntity->GetId());
if(!pItem)
break;
IEntityClass* pItemClass = pItem->GetEntity()->GetClass();
if(pItemClass && !strcmpi(pItemClass->GetName(),"SOCOM"))
{
IItem* pCurrentItem = pActor->GetCurrentItem();
if(pCurrentItem)
{
IEntityClass* pCurrentItemClass = pCurrentItem->GetEntity()->GetClass();
if(pCurrentItemClass && !strcmpi(pCurrentItemClass->GetName(),"SOCOM"))
{
GameplayEvent event3;
event3.event = eGE_ItemSelected;
TItemName itemName = GetItemName(pCurrentItem->GetEntity()->GetId());
if(!itemName)
break;
event3.value = 0;
event3.description = (const char*)itemName;
SendGamePlayEvent(pEntity,event3);
}
}
}
}
break;
case eGE_WeaponFireModeChanged:
{
TItemName itemIdx = GetItemName(EntityId(event.extra));
if(!itemIdx)//if(itemIdx < 0)
break;
event2.description = (const char*)itemIdx;
SendGamePlayEvent(pEntity,event2);
}
break;
case eGE_ItemSelected:
{
EntityId itemId = EntityId(event.extra);
TItemName itemIdx = GetItemName(itemId);
if(itemId && !itemIdx)
break;
event2.value = 0;
event2.description = (const char*)itemIdx;
SendGamePlayEvent(pEntity,event2);
}
break;
case eGE_AttachedAccessory:
{
if(!IsGrenade(event.description)) // NOT OffHandGrenade
SendGamePlayEvent(pEntity,event2);
}
break;
case eGE_AmmoCount:
{
const char* itemIdx = event.description;
if(!itemIdx)
break;
TGameStates::iterator itGS;
/*if(pActor->IsPlayer())
itGS = m_itSingleActorGameState;
else */if(pActor->GetEntity())
itGS = m_GameStates.find(pActor->GetEntity()->GetId());
else
break;
if(itGS == m_GameStates.end())
break;
SActorGameState& gstate = itGS->second;
IEntity* pItemEntity = gEnv->pEntitySystem->FindEntityByName(itemIdx);
if(!pItemEntity)
break;
IItem* pItem = g_pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pItemEntity->GetId());
if(!pItem)
break;
CWeapon* pWeapon = (CWeapon*)(pItem->GetIWeapon());
if(pWeapon && pWeapon->GetEntity())
{
TItemContainer::iterator it = gstate.Items.find(itemIdx);
if(it==gstate.Items.end())
break;
SItemProperties& recItem = it->second;
SWeaponAmmo weaponAmmo = pWeapon->GetFirstAmmo();
bool bGrenade = false;
if(!weaponAmmo.pAmmoClass)
{
// special case for grenades
if(IsAmmoGrenade((const char*)(event.extra)))
{
weaponAmmo.pAmmoClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass((const char*)event.extra);
weaponAmmo.count = (int)event.value;
bGrenade = true;
}
}
for(; weaponAmmo.pAmmoClass ; weaponAmmo = pWeapon->GetNextAmmo())
{
int ammoCount = weaponAmmo.count;
const char* ammoClass;
if(weaponAmmo.pAmmoClass && (ammoClass = weaponAmmo.pAmmoClass->GetName()))
{
TAmmoContainer& recAmmo = bGrenade? gstate.AmmoMags : recItem.Ammo;
if(recAmmo.find(ammoClass) == recAmmo.end())
recAmmo.insert(std::make_pair(ammoClass,0));
if(ammoCount != recAmmo[ammoClass])
{
event2.event = eGE_AmmoCount;
event2.value = (float)ammoCount;
if(event2.value < 0)
event2.value = 0;
event2.extra = (void*)ammoClass;
event2.description = (const char*)itemIdx;
SendGamePlayEvent(pEntity,event2);
}
}
}
}
}
break;
case eGE_EntityGrabbed:
{
EntityId entityId = EntityId(event.extra);
IEntity * pGrabbedEntity = gEnv->pEntitySystem->GetEntity(entityId);
if(pGrabbedEntity)
{
event2.description = pGrabbedEntity->GetName();
SendGamePlayEvent(pEntity,event2);
}
}
break;
case eGE_WeaponReload:
case eGE_ZoomedIn:
case eGE_ZoomedOut:
case eGE_HealthChanged:
case eGE_ItemExchanged:
SendGamePlayEvent(pEntity,event2);
break;
default:
break;
}
}
}
void CGameStateRecorder::SendGamePlayEvent(IEntity *pEntity, const GameplayEvent &event)
{
for(TListeners::iterator it = m_listeners.begin(), itEnd = m_listeners.end(); it!=itEnd; ++it)
(*it)->OnGameplayEvent(pEntity,event);
OnRecordedGameplayEvent(pEntity,event,0,true); //updates actor game state during recording
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::GetMemoryStatistics(ICrySizer * s)
{
SIZER_SUBCOMPONENT_NAME(s, "GameStateRecorder");
s->Add(*this);
s->AddContainer(m_listeners);
s->AddContainer(m_GameStates);
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::RegisterListener(IGameplayListener* pL)
{
if(pL)
stl::push_back_unique(m_listeners,pL);
}
////////////////////////////////////////////////////////////////////////////
void CGameStateRecorder::UnRegisterListener(IGameplayListener* pL)
{
stl::find_and_erase(m_listeners, pL);
}
//////////////////////////////////////////////////////////////////////////
float CGameStateRecorder::RenderInfo(float y, bool bRecording)
{
float retY = 0;
IRenderer *pRenderer = gEnv->pRenderer;
if (bRecording)
{
float fColor[4] = {1,0,0,1};
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," Recording game state");
retY +=15;
}
else
{
const float xp = 300;
const float xr = 400;
const float xri = 600;
float fColor[4] = {0,1,0,1};
float fColorWarning[4] = {1,1,0,1};
const char* actorName = m_demo_actorInfo->GetString();
CActor *pActor = GetActorOfName(actorName);
if(pActor)
{
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," Game state - Actor: %s --------------------------------------------------",pActor->GetEntity()? pActor->GetEntity()->GetName(): "(no entity)");
retY +=15;
if(m_itSingleActorGameState != m_GameStates.end() && pActor->GetEntity() && m_itSingleActorGameState->first == pActor->GetEntity()->GetId())
{
ICVar *pVar = gEnv->pConsole->GetCVar( "demo_force_game_state" );
if(pVar)
{
int demo_forceGameState = pVar->GetIVal();
if(demo_forceGameState)
{
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false,demo_forceGameState==1 ?
" Override mode = (health, suit energy)" : " Override mode = (all)");
retY +=15;
}
}
pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColor,false,"Current");
pRenderer->Draw2dLabel( xr,y+retY, 1.3f, fColor,false,"Recorded");
retY +=15;
SActorGameState& gstate = m_itSingleActorGameState->second;
float recordedHealth = (float)gstate.health;
float health = (float)pActor->GetHealth();
bool bError = CHECK_MISMATCH(health, recordedHealth,10);
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," Health:");
pRenderer->Draw2dLabel( xp,y+retY, 1.3f, bError? fColorWarning : fColor, false,"%d",(int)health);
pRenderer->Draw2dLabel( xr,y+retY, 1.3f, bError? fColorWarning : fColor, false,"%d",(int)recordedHealth);
retY +=15;
// items
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," Inventory ---------------------------------------------------------------------------------------");
retY +=15;
pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColor,false,"Current");
pRenderer->Draw2dLabel( xri,y+retY, 1.3f, fColor,false,"Recorded");
retY +=15;
CInventory *pInventory = (CInventory*)(pActor->GetInventory());
if(pInventory)
{
int nInvItems = pInventory->GetCount();
TItemContainer& Items = gstate.Items;
int nRecItems = Items.size();
int maxItems = max(nRecItems,nInvItems);
int i=0;
EntityId curSelectedId = pActor->GetCurrentItemId();
TItemName curSelClass = GetItemName(curSelectedId);
bool bSelectedError = !equal_strings(gstate.itemSelected,curSelClass);
for(; i< nInvItems; i++)
{
IItem *pItem = g_pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pInventory->GetItem(i));
if(pItem)
{
TItemName szItemName = GetItemName(pItem->GetEntityId());
TItemContainer::iterator it = Items.find(szItemName);
bError = it==Items.end();
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," %2d)",i+1);
EntityId curId = pItem->GetEntityId();
TItemName curClass = GetItemName(curId);
if(equal_strings(curClass,curSelClass) )
pRenderer->Draw2dLabel( xp-16,y+retY, 1.3f,bSelectedError ? fColorWarning:fColor, false, "[]");
if(equal_strings(szItemName, gstate.itemSelected))
pRenderer->Draw2dLabel( xri-16,y+retY, 1.3f,bSelectedError ? fColorWarning:fColor, false, "[]");
char itemName[32];
const char* originalItemName = pItem->GetEntity() ? pItem->GetEntity()->GetName():"(null)";
int length = strlen(originalItemName);
length = min(length,31);
strncpy(itemName,originalItemName,length);
itemName[length]=0;
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, bError? fColorWarning : fColor, false," %s",itemName);
if(bError)
pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColorWarning, false, "Missing");
else
{
SItemProperties& recItem = it->second;
CWeapon *pWeapon = (CWeapon*)(pItem->GetIWeapon());
IEntityClass* pItemClass = pItem->GetEntity()->GetClass();
if(pItemClass && !strcmpi(pItemClass->GetName(),"binoculars"))
pWeapon = NULL; // no fire mode or ammo recorded for binocular (which is a weapon)
if(pWeapon)
{
int idx = 0;
// ammo
float xa = 0;
for(SWeaponAmmo weaponAmmo = pWeapon->GetFirstAmmo(); weaponAmmo.pAmmoClass ; weaponAmmo = pWeapon->GetNextAmmo())
{
int ammoCount = weaponAmmo.count;
const char* ammoClass;
if(weaponAmmo.pAmmoClass && (ammoClass = weaponAmmo.pAmmoClass->GetName()))
{
TAmmoContainer::iterator it = recItem.Ammo.find(ammoClass);
if(it!=recItem.Ammo.end())
{
int recAmmoCount = recItem.Ammo[ammoClass];
bool bError2 = ammoCount!=recAmmoCount;
pRenderer->Draw2dLabel( xp+xa,y+retY, 1.3f, bError2? fColorWarning : fColor, false,"Am%d:%d",idx,ammoCount);
pRenderer->Draw2dLabel( xri+xa,y+retY, 1.3f, bError2? fColorWarning : fColor, false,"Am%d:%d",idx,recAmmoCount);
xa += 50;
++idx;
if(idx%5 ==0)
{
xa=0;
retY+=15;
}
}
}
}
// current fire mode
int curFireModeIdx = pWeapon->GetCurrentFireMode();
int recFireModeIdx = recItem.fireMode;
bool bError3 = curFireModeIdx!= recFireModeIdx;
pRenderer->Draw2dLabel( xp+xa,y+retY, 1.3f, bError3? fColorWarning : fColor, false,"FMode:%d",curFireModeIdx);
pRenderer->Draw2dLabel( xri+xa,y+retY, 1.3f, bError3? fColorWarning : fColor, false,"FMode:%d",recFireModeIdx);
}
else
{
pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColor, false, "Ok");
}
}
}
retY +=15;
}
/// Accessories
int nInvAccessories = pInventory->GetAccessoryCount();
TAccessoryContainer& Accessories = gstate.Accessories;
int nRecAccessories = Accessories.size();
if(nRecAccessories)
{
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, bError? fColorWarning : fColor, false," Accessories");
retY +=15;
}
for(int j=0 ; j< nInvAccessories; j++,i++)
{
const char* accessory = pInventory->GetAccessory(j);
if(accessory && strlen(accessory))
{
IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(accessory);
if(pClass)
{
TItemName szItemName = pClass->GetName();
TAccessoryContainer::iterator it = Accessories.find(szItemName);
bError = it==Accessories.end();
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false," %2d)",i+1);
char itemName[32];
int length = strlen(accessory);
length = min(length,31);
strncpy(itemName,accessory,length);
itemName[length]=0;
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, bError? fColorWarning : fColor, false," %s",itemName);
if(bError)
pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColorWarning, false, "Missing");
else
pRenderer->Draw2dLabel( xp,y+retY, 1.3f, fColor, false, "Ok");
retY +=15;
}
}
}
/// Ammo Mags
TAmmoContainer& Ammo = gstate.AmmoMags;
int nRecAmmo = Ammo.size();
int nInvAmmo = pInventory->GetAmmoPackCount();
if(nInvAmmo)
{
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, bError? fColorWarning : fColor, false," Ammo Packs");
retY +=15;
}
pInventory->AmmoIteratorFirst();
for(int j=0 ; !pInventory->AmmoIteratorEnd(); j++, pInventory->AmmoIteratorNext())
{
TAmmoContainer& Mags = gstate.AmmoMags;
const IEntityClass* pAmmoClass = pInventory->AmmoIteratorGetClass();
if(pAmmoClass)
{
int invAmmoCount = pInventory->AmmoIteratorGetCount();
const char* ammoClassName = pAmmoClass->GetName();
bool bNotFound = Mags.find(ammoClassName) == Mags.end();
int recAmmoCount = bNotFound ? 0 :Mags[ammoClassName];
bool bError = bNotFound || invAmmoCount!= recAmmoCount;
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, bError? fColorWarning : fColor, false," %s:",ammoClassName);
pRenderer->Draw2dLabel( xp,y+retY, 1.3f, bError? fColorWarning : fColor, false,"%d",invAmmoCount);
if(bNotFound)
pRenderer->Draw2dLabel( xr,y+retY, 1.3f, fColorWarning, false,"NotRecd");
else
pRenderer->Draw2dLabel( xr,y+retY, 1.3f, bError? fColorWarning : fColor, false,"%d",recAmmoCount);
retY +=15;
}
}
}
}
else // m_itSingleActorGameState != m_GameStates.end()
{
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false, "<<Not Recorded>>");
retY +=15;
}
}
else // pActor
{
pRenderer->Draw2dLabel( 1,y+retY, 1.3f, fColor,false, "<<Actor %s not in the map>>",actorName ? actorName:"(no name)");
retY +=15;
}
}
return retY;
}
///////////////////////////////////////////////////////////////////////
TItemName CGameStateRecorder::GetItemName(EntityId id, CItem** pItemOut)
{
if(id)
{
CItem* pItem = (CItem*)(gEnv->pGame->GetIGameFramework()->GetIItemSystem()->GetItem(id));
if(pItem && pItem->GetEntity())
{
if(pItemOut)
*pItemOut = pItem;
return pItem->GetEntity()->GetName();
}
}
return 0;
}
///////////////////////////////////////////////////////////////////////
CItem* CGameStateRecorder::GetItemOfName(CActor* pActor, TItemName itemName)
{
CInventory* pInventory= (CInventory*)(pActor->GetInventory());
if(pInventory && itemName)
return (CItem*)(pInventory->GetItemByName(itemName));
return 0;
}
///////////////////////////////////////////////////////////////////////
/*template <class EventHandlerFunc> */void CGameStateRecorder::CheckInventory(CActor* pActor, IItem *pItem)//, EventHandlerFunc eventHandler)
{
if(pActor)
{
TGameStates::iterator itGS;
if(pActor->IsPlayer())
itGS = m_itSingleActorGameState;
else if(pActor->GetEntity())
itGS = m_GameStates.find(pActor->GetEntity()->GetId());
else
return;
if(itGS != m_GameStates.end())
{
SActorGameState& gstate = itGS->second;
// items
CInventory *pInventory = (CInventory*)(pActor->GetInventory());
if(pInventory)
{
bool bSingleItem = (pItem!=0);
int nInvItems = (bSingleItem ? 1 : pInventory->GetCount());
TItemContainer& Items = gstate.Items;
for(int i=0; i< nInvItems; i++)
{
if(!bSingleItem)
pItem = g_pGame->GetIGameFramework()->GetIItemSystem()->GetItem(pInventory->GetItem(i));
if(pItem)
{
TItemName szItemName = GetItemName(pItem->GetEntityId());
TItemContainer::iterator it = Items.find(szItemName);
if(it==Items.end())
{
it = (Items.insert(std::make_pair(szItemName,SItemProperties()))).first;
GameplayEvent event;
event.event = eGE_ItemPickedUp;
event.description = szItemName;
//eventHandler(pActor,event);
SendGamePlayEvent(pActor->GetEntity(),event);
SItemProperties& recItem = it->second;
CWeapon *pWeapon = (CWeapon*)(pItem->GetIWeapon());
if(pWeapon)
{
// ammo
for(SWeaponAmmo weaponAmmo = pWeapon->GetFirstAmmo(); weaponAmmo.pAmmoClass ; weaponAmmo = pWeapon->GetNextAmmo())
{
int ammoCount = weaponAmmo.count;
string ammoClass;
if(weaponAmmo.pAmmoClass && (ammoClass = weaponAmmo.pAmmoClass->GetName()))
{
TAmmoContainer& recAmmo = recItem.Ammo;
if(recAmmo.find(ammoClass) == recAmmo.end())
recAmmo.insert(std::make_pair(ammoClass,0));
int recAmmoCount = recAmmo[ammoClass];
if(ammoCount!=recAmmoCount)
{
GameplayEvent event;
event.event = eGE_AmmoCount;
event.value = (float)ammoCount;
event.extra = (void*)(ammoClass.c_str());
event.description = (const char*)szItemName;
//eventHandler(pActor,event);
SendGamePlayEvent(pActor->GetEntity(),event);
}
}
}
// current fire mode
int curFireModeIdx = pWeapon->GetCurrentFireMode();
int recFireModeIdx = recItem.fireMode;
if(curFireModeIdx!= recFireModeIdx)
{
GameplayEvent event;
event.event = eGE_WeaponFireModeChanged;
event.value = (float)curFireModeIdx;
event.description = (const char*)szItemName;
//eventHandler(pActor,event);
SendGamePlayEvent(pActor->GetEntity(),event);
}
}
}
}
}
/// Accessories
int nInvAccessories = pInventory->GetAccessoryCount();
TAccessoryContainer& Accessories = gstate.Accessories;
int nRecAccessories = Accessories.size();
for(int j=0 ; j< nInvAccessories; j++)
{
const char* accessory = pInventory->GetAccessory(j);
if(accessory && strlen(accessory))
{
IEntityClass* pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass(accessory);
if(pClass)
{
TItemName itemClass = pClass->GetName();
TAccessoryContainer::iterator it = Accessories.find(itemClass);
if(it==Accessories.end())
{
GameplayEvent event;
event.event = eGE_AccessoryPickedUp;
//event.value = accIdx;
event.description = itemClass;
// eventHandler(pActor,event);
SendGamePlayEvent(pActor->GetEntity(),event);
}
}
}
}
/// Ammo
TAmmoContainer& Ammo = gstate.AmmoMags;
int nRecAmmo = Ammo.size();
int nInvAmmo = pInventory->GetAmmoPackCount();
pInventory->AmmoIteratorFirst();
for(int j=0 ; !pInventory->AmmoIteratorEnd(); j++, pInventory->AmmoIteratorNext())
{
TAmmoContainer& Mags = gstate.AmmoMags;
const IEntityClass* pAmmoClass = pInventory->AmmoIteratorGetClass();
if(pAmmoClass)
{
const char* ammoClassName = pAmmoClass->GetName();
int ammoCount = pInventory->AmmoIteratorGetCount();
if(Mags.find(ammoClassName) == Mags.end() || ammoCount!= Mags[ammoClassName])
{
GameplayEvent event;
event.event = eGE_AmmoPickedUp;
event.description = ammoClassName;
event.value = (float)ammoCount;
// eventHandler(pActor,event);
SendGamePlayEvent(pActor->GetEntity(),event);
}
}
}
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////
CActor* CGameStateRecorder::GetActorOfName( const char* name)
{
if(!strcmpi(name,"all"))
return NULL;
if(!strcmpi(name,"player"))
return static_cast<CActor *>(gEnv->pGame->GetIGameFramework()->GetClientActor());
else
{
IEntity* pEntity = gEnv->pEntitySystem->FindEntityByName(name);
if(pEntity)
return static_cast<CActor *>(gEnv->pGame->GetIGameFramework()->GetIActorSystem()->GetActor(pEntity->GetId()));
}
return NULL;
}
#include UNIQUE_VIRTUAL_WRAPPER(IGameStateRecorder)
| [
"[email protected]"
] | [
[
[
1,
1491
]
]
] |
3d7abd2aa53c129105b43ca323d4cff43c401987 | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /CollectionsList.cpp | 4c978d0c1e91925588c023f1393e4cf1947f2e61 | [] | 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 | 14,379 | 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 "CollectionsList.h"
#include "PrgAPI.h"
#include "SQLManager.h"
#include "ActionManager.h"
#include "CollectionManager.h"
#include "GdiplusUtilities.h"
#include "DataRecordsXmlSerializer.h"
#define ID_COL_IMPORTCOLLECTION 300
#define ID_COL_EXPORTCOLLECTION 301
#define ID_COL_MERGECOLLECTION 302
#define ID_COL_UPDATEL2 400
#define ID_COL_RENAME 401
#define ID_COL_REMOVE 402
#define ID_COL_ADDFOLDER 403
#define ID_COL_UPDATEL1 404
// CCollectionsList
CCollectionsList::CCollectionsList()
:m_pBkBrush(NULL),
m_pTextBrush(NULL),
m_pTextBkBrush(NULL),
m_pTextSelBrush(NULL),
m_pTextSelBkBrush(NULL),
m_pTextAltBkBrush(NULL),
m_pTextWorkingBrush(NULL),
m_pMainMenu(NULL)
{
SetItemHeight(52);//36);
SetSingleSelection(FALSE);
LOGFONT lf;
HDC hdc = ::GetDC(0);
// ::GetObject(::GetStockObject(DEFAULT_GUI_FONT), sizeof(LOGFONT), &lf);
memset(&lf, 0, sizeof(LOGFONT));
_tcscpy(lf.lfFaceName, _T("Tahoma"));
lf.lfWeight = 400;
lf.lfHeight = 13;
m_pMainTextFont = new Gdiplus::Font(hdc, &lf);
lf.lfWeight += 200;
lf.lfHeight += 2;
m_pTitleTextFont = new Gdiplus::Font(hdc, &lf);
::ReleaseDC(0, hdc);
SetColor(COL_Bk, RGB(255,255,255));
SetColor(COL_Text, RGB(0,0,0));
SetColor(COL_TextBk, RGB(255,255,255));
SetColor(COL_TextBkAlt, RGB(240,240,240));
SetColor(COL_TextWorking, RGB(150,0,0));
SetColor(COL_TextSel, RGB(255,255,255));
SetColor(COL_TextSelBk, RGB(0,0,150));
m_pBorderPen = new Gdiplus::Pen(Gdiplus::Color::LightGray, 1);
m_pMainStringFormat = new Gdiplus::StringFormat();
m_pMainStringFormat->SetLineAlignment(Gdiplus::StringAlignmentCenter);
m_pMainStringFormat->SetFormatFlags(Gdiplus::StringFormatFlagsNoWrap);
}
CCollectionsList::~CCollectionsList()
{
delete m_pBkBrush;
delete m_pTextBrush;
delete m_pTextBkBrush;
delete m_pTextSelBrush;
delete m_pTextSelBkBrush;
delete m_pTextAltBkBrush;
delete m_pTextWorkingBrush;
delete m_pBorderPen;
delete m_pMainStringFormat;
delete m_pMainMenu;
}
void CCollectionsList::InitMenus()
{
PrgAPI* pAPI = PRGAPI();
if (m_pMainMenu == NULL)
m_pMainMenu = pAPI->CreatePopupMenu();
if (m_pMainMenu->GetInternalHandler())
return;
m_pMainMenu->Create();
m_pMainMenu->AppendMenu(ITSMenu::MIT_String, ID_COL_ADDFOLDER, (LPTSTR) pAPI->GetString(IDS_ADDCOLLECTION));
TCHAR bf[500];
_sntprintf(bf, 500, _T("%s (%s)"), pAPI->GetString(IDS_UPDATE), pAPI->GetString(IDS_QUICK));
m_pMainMenu->AppendMenu(ITSMenu::MIT_String, ID_COL_UPDATEL1, bf);
m_pMainMenu->AppendMenu(ITSMenu::MIT_String, ID_COL_UPDATEL2, (LPTSTR) pAPI->GetString(IDS_UPDATE));
m_pMainMenu->AppendMenu(ITSMenu::MIT_String, ID_COL_RENAME, (LPTSTR) pAPI->GetString(IDS_RENAME));
m_pMainMenu->AppendMenu(ITSMenu::MIT_Separator, NULL, NULL);
m_pMainMenu->AppendMenu(ITSMenu::MIT_String, ID_COL_REMOVE, (LPTSTR) pAPI->GetString(IDS_REMOVE));
m_pMainMenu->AppendMenu(ITSMenu::MIT_Separator, NULL, NULL);
m_pMainMenu->AppendMenu(ITSMenu::MIT_String, ID_COL_IMPORTCOLLECTION, (LPTSTR) pAPI->GetString(IDS_IMPORTVIRTUALTRACKS));
m_pMainMenu->AppendMenu(ITSMenu::MIT_String, ID_COL_EXPORTCOLLECTION, (LPTSTR) pAPI->GetString(IDS_EXPORTVIRTUALTRACKS));
}
void CCollectionsList::OnContextMenu(CWnd* pWnd, CPoint point)
{
CPoint p = point;
ScreenToClient(&point);
INT item = GetItemFromPoint(point.x, point.y);
if (item != -1 && !IsItemSelected(item))
{
ClearSelection();
SetItemSelection(item, TRUE);
}
InitMenus();
m_pMainMenu->EnableMenuItem(ID_COL_UPDATEL1, FALSE);
m_pMainMenu->EnableMenuItem(ID_COL_UPDATEL2, FALSE);
m_pMainMenu->EnableMenuItem(ID_COL_REMOVE, FALSE);
m_pMainMenu->EnableMenuItem(ID_COL_RENAME, FALSE);
if (item != -1)
{
m_pMainMenu->EnableMenuItem(ID_COL_RENAME, GetSelectedItemCount() == 1);
m_pMainMenu->EnableMenuItem(ID_COL_REMOVE, TRUE);
switch (m_CRC[item]->type)
{
case CTYPE_LocalFolder:
case CTYPE_NetFolder:
case CTYPE_Removable:
m_pMainMenu->EnableMenuItem(ID_COL_UPDATEL1, TRUE);
m_pMainMenu->EnableMenuItem(ID_COL_UPDATEL2, TRUE);
break;
case CTYPE_Media:
break;
case CTYPE_Virtual:
break;
case CTYPE_AudioCD:
break;
case CTYPE_HTTPLinks:
break;
default:
ASSERT(0);
break;
}
}
m_pMainMenu->TrackPopupMenu(p.x, p.y, this->GetSafeHwnd());
}
void CCollectionsList::UpdateControl()
{
SQLManager* pSM = PRGAPI()->GetSQLManager();
m_CRC.clear();
pSM->GetCollectionRecordCollectionByTracksFilter(m_CRC, TracksFilter(), TRUE);
if (GetItemCount() != m_CRC.size())
SetItemCount(m_CRC.size());
Refresh();
}
void CCollectionsList::DrawItem(Gdiplus::Graphics& g, INT nItem, Gdiplus::Rect& itemRC)
{
PrgAPI* pAPI = PRGAPI();
//Calculate Colors
Gdiplus::Brush* pTextBrush = m_pTextBrush ;
Gdiplus::Brush* pBkBrush = nItem % 2 ? m_pTextBkBrush : m_pTextAltBkBrush;
if (IsItemSelected(nItem))
{
pTextBrush = m_pTextSelBrush;
pBkBrush = m_pTextSelBkBrush;
}
g.FillRectangle(pBkBrush, itemRC);
CollectionRecord& rec = *(m_CRC)[nItem];
std::map<CollectionTypesEnum, Gdiplus::Bitmap*>::iterator it = m_pBitmaps.find(rec.type);
Gdiplus::Bitmap* pBmpIcon = NULL;
if (it == m_pBitmaps.end())
{
pBmpIcon = GdiplusUtilities::FromHICON32(pAPI->GetIconForCollectionType(rec.type));
m_pBitmaps[rec.type] = pBmpIcon;
}
else
pBmpIcon = (*it).second;
INT xmargin = 1;
INT ymargin = 1;
g.DrawImage(pBmpIcon, itemRC.X + xmargin, itemRC.Y + ymargin, 0,0, 16, 16, Gdiplus::UnitPixel);
BOOL bWorking = pAPI->GetCollectionManager()->IsCollectionPending(rec);
if (bWorking)
pTextBrush = m_pTextWorkingBrush;
TCHAR sWorking[100];
_sntprintf(sWorking, 100, _T("[%s] - "), pAPI->GetString(IDS_WORKING));
TCHAR msg[1000];
INT strLen = _sntprintf(msg, 1000,
_T("%s%s (%s) | %s: '%s' [0x%0.8X])"),
bWorking ? sWorking : _T(""),
rec.name.c_str(),
pAPI->GetStringForCollectionType(rec.type),
pAPI->GetString(IDS_LOCATION), rec.location.c_str(), rec.serial);
Gdiplus::Rect rcText(itemRC);
rcText.X += 20;
rcText.Width -= 22;
rcText.Height = GetItemHeight() / 2;
INT X = itemRC.X + 20;
g.DrawString(msg,
strLen,
m_pTitleTextFont,
Gdiplus::RectF(
(Gdiplus::REAL)(X),
(Gdiplus::REAL)(itemRC.Y),
(Gdiplus::REAL)(itemRC.GetRight() - X),
(Gdiplus::REAL)( 4 * itemRC.Height / 10)),
m_pMainStringFormat,
pTextBrush);
//X = itemRC.X;
TCHAR dateAddedStr[100];
PrgAPI::FormatDate(dateAddedStr, 100, rec.dateAdded, FALSE);
TCHAR dateUpdatedStr[100];
PrgAPI::FormatDate(dateUpdatedStr, 100, rec.dateUpdated, FALSE);
strLen = _sntprintf(msg, 1000,
_T("%s: %s | %s: %s"),
pAPI->GetString(IDS_DATEADDED), dateAddedStr,
pAPI->GetString(IDS_DATEUPDATED), dateUpdatedStr);
g.DrawString(msg,
strLen,
m_pMainTextFont,
Gdiplus::RectF(
(Gdiplus::REAL)(X),
(Gdiplus::REAL)(itemRC.Y + 4 * itemRC.Height / 10),
(Gdiplus::REAL)(itemRC.GetRight() - X),
(Gdiplus::REAL)(3 * itemRC.Height / 10)),
m_pMainStringFormat,
pTextBrush);
strLen = _sntprintf(msg, 1000,
_T("%s: %d | %s: %2.1f MB | %s: %2.1f h"),
pAPI->GetString(IDS_TRACKS), rec.trackCount,
pAPI->GetString(IDS_SIZE), rec.sumSize / 1024.0,
pAPI->GetString(IDS_DURATION), rec.sumDuration / 3600.0);
g.DrawString(msg,
strLen,
m_pMainTextFont,
Gdiplus::RectF(
(Gdiplus::REAL)(X),
(Gdiplus::REAL)(itemRC.Y + 7 * itemRC.Height / 10),
(Gdiplus::REAL)(itemRC.GetRight() - X),
(Gdiplus::REAL)(3 * itemRC.Height / 10)),
m_pMainStringFormat,
pTextBrush);
g.DrawLine(m_pBorderPen, itemRC.GetLeft() + 1, itemRC.GetBottom() - 1, itemRC.GetRight() - 2, itemRC.GetBottom() - 1);
}
void CCollectionsList::DrawBackground(Gdiplus::Graphics& g, const Gdiplus::Rect& r)
{
g.FillRectangle(m_pBkBrush, r);
if (r.Y == 0)
{
Gdiplus::StringFormat centeredStringFormat;
centeredStringFormat.SetAlignment(Gdiplus::StringAlignmentCenter);
centeredStringFormat.SetFormatFlags(Gdiplus::StringFormatFlagsNoWrap);
g.DrawString(PRGAPI()->GetString(IDS_EMPTY),
-1,
m_pMainTextFont,
Gdiplus::RectF(
(Gdiplus::REAL)(r.X + 5),
(Gdiplus::REAL)(r.Y + 5),
(Gdiplus::REAL)(r.Width),
(Gdiplus::REAL)(r.Y + 30)),
¢eredStringFormat,
m_pTextBrush);
}
}
//---------------------------------------------------
//ICtrlColors ---------------------------------------
//---------------------------------------------------
void CCollectionsList::SetColor(UINT idx, COLORREF value)
{
ASSERT(idx < COL_Last);
if (idx < COL_Last)
m_colors[idx] = value;
switch (idx)
{
case COL_Bk:
delete m_pBkBrush;
m_pBkBrush = new Gdiplus::SolidBrush(GdiplusUtilities::COLORREF2Color(m_colors[idx]));
break;
case COL_Text:
delete m_pTextBrush;
m_pTextBrush = new Gdiplus::SolidBrush(GdiplusUtilities::COLORREF2Color(m_colors[idx]));
break;
case COL_TextBk:
delete m_pTextBkBrush;
m_pTextBkBrush = new Gdiplus::SolidBrush(GdiplusUtilities::COLORREF2Color(m_colors[idx]));
break;
case COL_TextSel:
delete m_pTextSelBrush;
m_pTextSelBrush = new Gdiplus::SolidBrush(GdiplusUtilities::COLORREF2Color(m_colors[idx]));
break;
case COL_TextSelBk:
delete m_pTextSelBkBrush;
m_pTextSelBkBrush = new Gdiplus::SolidBrush(GdiplusUtilities::COLORREF2Color(m_colors[idx]));
break;
case COL_TextBkAlt:
delete m_pTextAltBkBrush;
m_pTextAltBkBrush = new Gdiplus::SolidBrush(GdiplusUtilities::COLORREF2Color(m_colors[idx]));
break;
case COL_TextWorking:
delete m_pTextWorkingBrush;
m_pTextWorkingBrush = new Gdiplus::SolidBrush(GdiplusUtilities::COLORREF2Color(m_colors[idx]));
break;
}
if (m_hWnd)
Invalidate();
}
COLORREF CCollectionsList::GetColor(UINT idx)
{
ASSERT(idx < COL_Last);
if (idx < COL_Last)
return m_colors[idx];
return 0;
}
const TCHAR* const cColorNames[] = {
_T("Bk"),
_T("Text"),
_T("TextBk"),
_T("TextSel"),
_T("TextSelBk"),
NULL
};
LPCTSTR CCollectionsList::GetColorName(UINT idx)
{
ASSERT(idx <= COL_Last);
if (idx < COL_Last)
return cColorNames[idx];
return NULL;
}
//---------------------------------------------------
//---------------------------------------------------
//---------------------------------------------------
BOOL CCollectionsList::OnCommand(WPARAM wParam, LPARAM lParam)
{
TRACEST(_T("CCollectionsList::OnCommand"), wParam);
ASSERT(m_CRC.size() == GetItemCount());
PrgAPI* pAPI = PRGAPI();
CollectionManager* pCM = pAPI->GetCollectionManager();
ActionManager* pAM = pAPI->GetActionManager();
SQLManager* pSM = pAPI->GetSQLManager();
INT nPos = GetNextSelectedItem(-1);
switch (wParam)
{
case ID_COL_ADDFOLDER:
pAM->ShowAddNewCollectionDlg(this);
break;
case ID_COL_IMPORTCOLLECTION:
{
CFileDialog fd(TRUE, _T(".xtc"), NULL, OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY,
_T("Track Collection Files (*.xtc)|*.xtc|Xml Files (*.xml)|*.xml|All Files (*.*)|*.*||"), NULL);
if (fd.DoModal() == IDOK)
{
FullTrackRecordCollection col;
if (DataRecordsXmlSerializer::Import(fd.GetPathName(), col))
{
CollectionRecord cr;
cr.location = fd.GetPathName();
cr.name = fd.GetFileTitle();
cr.serial = 0;
cr.type = CTYPE_Virtual;
if (pSM->AddNewCollectionRecord(cr))
pCM->ImportFullTrackRecordCollection(cr, col);
}
}
}
break;
case ID_COL_EXPORTCOLLECTION:
{
INT nPos = GetNextSelectedItem();
if (nPos != -1)
{
CFileDialog fd(FALSE, _T(".xtc"), NULL, OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY,
_T("Track Collection Files (*.xtc)|*.xtc|Xml Files (*.xml)|*.xml|All Files (*.*)|*.*||"), NULL);
if (fd.DoModal() == IDOK)
{
FullTrackRecordCollection col;
TracksFilter tf;
tf.CollectionID.match = NUMM_Exact;
tf.CollectionID.val = m_CRC[nPos]->ID;
if (pSM->GetFullTrackRecordCollectionByTracksFilter(col, tf))
{
if (DataRecordsXmlSerializer::Export(fd.GetPathName(), col))
pAPI->NotifyUser(IDS_SUCCESS);
else
pAPI->NotifyUser(IDS_FAILURE);
}
}
}
}
break;
case ID_COL_UPDATEL1:
case ID_COL_UPDATEL2:
while (nPos != -1)
{
pCM->UpdateCollection(m_CRC[nPos], TRUE, wParam == ID_COL_UPDATEL2, TRUE);
nPos = GetNextSelectedItem(nPos);
}
break;
case ID_COL_REMOVE:
if (nPos != -1)
{
CollectionManager* pCM = pAPI->GetCollectionManager();
while (nPos != -1)
{
//pSM->DeleteCollectionRecord(m_CRC[nPos]->ID, TRUE);
pCM->RemoveCollection(m_CRC[nPos]->ID);
nPos = GetNextSelectedItem(nPos);
}
//pAPI->SendMessage(SM_CollectionManagerEvent);
}
break;
case ID_COL_RENAME:
if (nPos != -1)
{
if (pAM->ShowRenameCollectionDlg(*m_CRC[nPos], this))
{
//pAPI->SendMessage(SM_DatabaseUpdated);
//Refresh();
}
}
break;
default:
return GetParent()->SendMessage(WM_COMMAND, wParam, lParam);
}
return TRUE;
}
BEGIN_MESSAGE_MAP(CCollectionsList, CFlexListCtrl)
ON_WM_LBUTTONUP()
ON_WM_CONTEXTMENU()
END_MESSAGE_MAP()
void CCollectionsList::OnLButtonUp(UINT nFlags, CPoint point)
{
GetParent()->PostMessage(MsgIDLeftClick);
__super::OnLButtonUp(nFlags, point);
}
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
] | [
[
[
1,
488
]
]
] |
72fd2880c812de383c23d276e970fb572db39ad2 | 723202e673511cf9f243177d964dfeba51cb06a3 | /10/lpd/java-reduced/LL-gram/CoCo/Taste.cpp | 855c59ca5cb6be822922ba13189d0091efed02db | [] | no_license | aeremenok/a-team-777 | c2ffe04b408a266f62c523fb8d68c87689f2a2e9 | 0945efbe00c3695c9cc3dbcdb9177ff6f1e9f50b | refs/heads/master | 2020-12-24T16:50:12.178873 | 2009-06-16T14:55:41 | 2009-06-16T14:55:41 | 32,388,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 767 | cpp | #include "Stdio.h"
#include "SymbolTable.h"
#include "Parser.h"
#include "Scanner.h"
#include <sys/timeb.h>
#include <wchar.h>
int main (int argc, char *argv[]) {
if (argc == 2) {
wchar_t *fileName = coco_string_create(argv[1]);
Taste::Scanner *scanner = new Taste::Scanner(fileName);
Taste::Parser *parser = new Taste::Parser(scanner);
parser->tab = new Taste::SymbolTable(parser);
parser->gen = new Taste::CodeGenerator();
parser->Parse();
if (parser->errors->count == 0) {
parser->gen->Decode();
parser->gen->Interpret("Taste.IN");
}
coco_string_delete(fileName);
delete parser->gen;
delete parser->tab;
delete parser;
delete scanner;
} else
printf("-- No source file specified\n");
return 0;
}
| [
"[email protected]@9273621a-9230-0410-b1c6-9ffd80c20a0c"
] | [
[
[
1,
35
]
]
] |
7e45f9e6c59dd6f41a829b88cf7d6d8501f85304 | 1e01b697191a910a872e95ddfce27a91cebc57dd | /GrfDelay.cpp | 279a318a39bb743208da1ba118481a74d2a38c55 | [] | no_license | canercandan/codeworker | 7c9871076af481e98be42bf487a9ec1256040d08 | a68851958b1beef3d40114fd1ceb655f587c49ad | refs/heads/master | 2020-05-31T22:53:56.492569 | 2011-01-29T19:12:59 | 2011-01-29T19:12:59 | 1,306,254 | 7 | 5 | null | null | null | null | IBM852 | C++ | false | false | 2,389 | cpp | /* "CodeWorker": a scripting language for parsing and generating text.
Copyright (C) 1996-1997, 1999-2002 CÚdric Lemaire
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.
This library 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 this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
To contact the author: [email protected]
*/
#ifdef WIN32
#pragma warning (disable : 4786)
#endif
#include "DtaScriptVariable.h"
#include "DtaProject.h"
#include "ScpStream.h"
#include "UtlTimer.h"
#include "CppCompilerEnvironment.h"
#include "GrfDelay.h"
namespace CodeWorker {
class GrfDelayTimer {
private:
UtlTimer* _pOldTimer;
UtlTimer _timer;
public:
GrfDelayTimer() {
_pOldTimer = DtaProject::getInstance().getDelayTimer();
DtaProject::getInstance().setDelayTimer(&_timer);
_timer.start();
}
~GrfDelayTimer() {
_timer.stop();
double dDuration = _timer.getTimeInSec();
DtaProject::getInstance().setLastDelay(dDuration);
DtaProject::getInstance().setDelayTimer(_pOldTimer);
}
};
GrfDelay::~GrfDelay() {}
SEQUENCE_INTERRUPTION_LIST GrfDelay::executeInternal(DtaScriptVariable& visibility) {
SEQUENCE_INTERRUPTION_LIST result;
GrfDelayTimer theTimer;
result = GrfBlock::executeInternal(visibility);
return result;
}
void GrfDelay::compileCpp(CppCompilerEnvironment& theCompilerEnvironment) const {
CW_BODY_INDENT << "clock_t _compiler_start = clock();";
CW_BODY_ENDL;
CW_BODY_INDENT << "clock_t _compiler_finish = clock();";
CW_BODY_ENDL;
CW_BODY_INDENT;
GrfBlock::compileCpp(theCompilerEnvironment);
CW_BODY_INDENT << "double _compiler_duration = (double)(_compiler_finish - _compiler_start) / CLOCKS_PER_SEC;";
CW_BODY_ENDL;
CW_BODY_INDENT << "CGRuntime::setLastDelay(_compiler_duration);";
CW_BODY_ENDL;
}
}
| [
"cedric.p.r.lemaire@28b3f5f3-d42e-7560-b87f-5f53cf622bc4"
] | [
[
[
1,
74
]
]
] |
19840d88f987a1662f0bc8a41c654b0d74030230 | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Components/Transforms/SimilarityTransform/itkAdvancedSimilarity2DTransform.h | ded6fd4ed78074ad37f179b86c880190b15cd7af | [] | no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,059 | h | /*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: $RCSfile: itkAdvancedSimilarity2DTransform.h,v $
Language: C++
Date: $Date: 2006-06-07 16:06:32 $
Version: $Revision: 1.11 $
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.
=========================================================================*/
#ifndef __itkAdvancedSimilarity2DTransform_h
#define __itkAdvancedSimilarity2DTransform_h
#include <iostream>
#include "itkAdvancedRigid2DTransform.h"
namespace itk
{
/** \brief AdvancedSimilarity2DTransform of a vector space (e.g. space coordinates)
*
* This transform applies a homogenous scale and rigid transform in
* 2D space. The transform is specified as a scale and rotation around
* a arbitrary center and is followed by a translation.
* given one angle for rotation, a homogeneous scale and a 2D offset for translation.
*
* The parameters for this transform can be set either using
* individual Set methods or in serialized form using
* SetParameters() and SetFixedParameters().
*
* The serialization of the optimizable parameters is an array of 3 elements
* ordered as follows:
* p[0] = scale
* p[1] = angle
* p[2] = x component of the translation
* p[3] = y component of the translation
*
* The serialization of the fixed parameters is an array of 2 elements
* ordered as follows:
* p[0] = x coordinate of the center
* p[1] = y coordinate of the center
*
* Access methods for the center, translation and underlying matrix
* offset vectors are documented in the superclass MatrixOffsetTransformBase.
*
* Access methods for the angle are documented in superclass Rigid2DTransform.
*
* \sa Transform
* \sa MatrixOffsetTransformBase
* \sa Rigid2DTransform
*
* \ingroup Transforms
*/
template < class TScalarType=double > // Data type for scalars (float or double)
class ITK_EXPORT AdvancedSimilarity2DTransform :
public AdvancedRigid2DTransform< TScalarType >
{
public:
/** Standard class typedefs. */
typedef AdvancedSimilarity2DTransform Self;
typedef AdvancedRigid2DTransform< TScalarType > Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** New macro for creation of through a Smart Pointer. */
itkNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( AdvancedSimilarity2DTransform, AdvancedRigid2DTransform );
/** Dimension of parameters. */
itkStaticConstMacro(SpaceDimension, unsigned int, 2);
itkStaticConstMacro(InputSpaceDimension, unsigned int, 2);
itkStaticConstMacro(OutputSpaceDimension, unsigned int, 2);
itkStaticConstMacro(ParametersDimension, unsigned int, 4);
/** Scalar type. */
typedef typename Superclass::ScalarType ScalarType;
typedef TScalarType ScaleType;
/** Parameters type. */
typedef typename Superclass::ParametersType ParametersType;
/** Jacobian type. */
typedef typename Superclass::JacobianType JacobianType;
/** Offset type. */
typedef typename Superclass::OffsetType OffsetType;
/** Matrix type. */
typedef typename Superclass::MatrixType MatrixType;
/** Point type. */
typedef typename Superclass::InputPointType InputPointType;
typedef typename Superclass::OutputPointType OutputPointType;
/** Vector type. */
typedef typename Superclass::InputVectorType InputVectorType;
typedef typename Superclass::OutputVectorType OutputVectorType;
/** CovariantVector type. */
typedef typename Superclass::InputCovariantVectorType InputCovariantVectorType;
typedef typename Superclass::OutputCovariantVectorType OutputCovariantVectorType;
/** VnlVector type. */
typedef typename Superclass::InputVnlVectorType InputVnlVectorType;
typedef typename Superclass::OutputVnlVectorType OutputVnlVectorType;
typedef typename Superclass
::NonZeroJacobianIndicesType NonZeroJacobianIndicesType;
typedef typename Superclass::SpatialJacobianType SpatialJacobianType;
typedef typename Superclass
::JacobianOfSpatialJacobianType JacobianOfSpatialJacobianType;
typedef typename Superclass::SpatialHessianType SpatialHessianType;
typedef typename Superclass
::JacobianOfSpatialHessianType JacobianOfSpatialHessianType;
typedef typename Superclass::InternalMatrixType InternalMatrixType;
/** Set the Scale part of the transform. */
void SetScale( ScaleType scale );
itkGetConstReferenceMacro( Scale, ScaleType );
/** Set the transformation from a container of parameters
* This is typically used by optimizers.
* There are 4 parameters. The first one represents the
* scale, the second represents the angle of rotation
* and the last two represent the translation.
* The center of rotation is fixed.
*
* \sa Transform::SetParameters()
* \sa Transform::SetFixedParameters() */
void SetParameters( const ParametersType & parameters );
/** Get the parameters that uniquely define the transform
* This is typically used by optimizers.
* There are 4 parameters. The first one represents the
* scale, the second represents the angle of rotation,
* and the last two represent the translation.
* The center of rotation is fixed.
*
* \sa Transform::GetParameters()
* \sa Transform::GetFixedParameters() */
const ParametersType & GetParameters( void ) const;
/** This method computes the Jacobian matrix of the transformation
* at a given input point.
*
* \sa Transform::GetJacobian() */
/** Compute the Jacobian of the transformation. */
virtual void GetJacobian(
const InputPointType &,
JacobianType &,
NonZeroJacobianIndicesType & ) const;
/** Set the transformation to an identity. */
virtual void SetIdentity( void );
/**
* This method creates and returns a new AdvancedSimilarity2DTransform object
* which is the inverse of self.
**/
void CloneInverseTo( Pointer & newinverse ) const;
/**
* This method creates and returns a new AdvancedSimilarity2DTransform object
* which has the same parameters.
**/
void CloneTo( Pointer & clone ) const;
/**
* Set the rotation Matrix of a Similarity 2D Transform
*
* This method sets the 2x2 matrix representing a similarity
* transform. The Matrix is expected to be a valid
* similarity transform with a certain tolerance.
*
* \warning This method will throw an exception if the matrix
* provided as argument is not valid.
*
* \sa MatrixOffsetTransformBase::SetMatrix()
*
**/
virtual void SetMatrix( const MatrixType & matrix );
protected:
AdvancedSimilarity2DTransform();
AdvancedSimilarity2DTransform( unsigned int spaceDimension,
unsigned int parametersDimension);
~AdvancedSimilarity2DTransform(){};
void PrintSelf(std::ostream &os, Indent indent) const;
/** Compute matrix from angle and scale. This is used in Set methods
* to update the underlying matrix whenever a transform parameter
* is changed. */
virtual void ComputeMatrix(void);
/** Compute the angle and scale from the matrix. This is used to compute
* transform parameters from a given matrix. This is used in
* MatrixOffsetTransformBase::Compose() and
* MatrixOffsetTransformBase::GetInverse(). */
virtual void ComputeMatrixParameters(void);
/** Set the scale without updating underlying variables. */
void SetVarScale( ScaleType scale )
{ m_Scale = scale; }
/** Update the m_JacobianOfSpatialJacobian. */
virtual void PrecomputeJacobianOfSpatialJacobian(void);
private:
AdvancedSimilarity2DTransform(const Self&); //purposely not implemented
void operator=(const Self&); //purposely not implemented
ScaleType m_Scale;
}; //class AdvancedSimilarity2DTransform
} // namespace itk
// Define instantiation macro for this template.
#define ITK_TEMPLATE_AdvancedSimilarity2DTransform(_, EXPORT, x, y) namespace itk { \
_(1(class EXPORT AdvancedSimilarity2DTransform< ITK_TEMPLATE_1 x >)) \
namespace Templates { typedef AdvancedSimilarity2DTransform< ITK_TEMPLATE_1 x > AdvancedSimilarity2DTransform##y; } \
}
#if ITK_TEMPLATE_EXPLICIT
# include "Templates/itkAdvancedSimilarity2DTransform+-.h"
#endif
#if ITK_TEMPLATE_TXX
# include "itkAdvancedSimilarity2DTransform.txx"
#endif
#endif /* __itkAdvancedSimilarity2DTransform_h */
| [
"[email protected]"
] | [
[
[
1,
244
]
]
] |
bb2e461f5f9f17394296b60526366e2fab1a952f | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/emuleDlg.cpp | 08575954f5ff22c1994d14e81db2afc458550665 | [] | 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 | 209,589 | cpp | //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.
#include "stdafx.h"
#include <math.h>
#include <afxinet.h>
#define MMNODRV // mmsystem: Installable driver support
//#define MMNOSOUND // mmsystem: Sound support
#define MMNOWAVE // mmsystem: Waveform support
#define MMNOMIDI // mmsystem: MIDI support
#define MMNOAUX // mmsystem: Auxiliary audio support
#define MMNOMIXER // mmsystem: Mixer support
#define MMNOTIMER // mmsystem: Timer support
#define MMNOJOY // mmsystem: Joystick support
#define MMNOMCI // mmsystem: MCI support
#define MMNOMMIO // mmsystem: Multimedia file I/O support
#define MMNOMMSYSTEM // mmsystem: General MMSYSTEM functions
#include <Mmsystem.h>
#include <HtmlHelp.h>
#include <share.h>
#include "emule.h"
#include "emuleDlg.h"
#include "ServerWnd.h"
#include "KademliaWnd.h"
#include "TransferWnd.h"
#include "TransferDlg.h"
#include "SearchResultsWnd.h"
#include "SearchDlg.h"
#include "SharedFilesWnd.h"
#include "ChatWnd.h"
#include "IrcWnd.h"
#include "StatisticsDlg.h"
#include "CreditsDlg.h"
#include "PreferencesDlg.h"
#include "Sockets.h"
#include "KnownFileList.h"
#include "ServerList.h"
#include "Opcodes.h"
#include "SharedFileList.h"
#include "ED2KLink.h"
//Xman slpashscreen
/*
#include "Splashscreen.h"
*/
//Xman end
#include "PartFileConvert.h"
#include "EnBitmap.h"
#include "Exceptions.h"
#include "SearchList.h"
#include "HTRichEditCtrl.h"
#include "FrameGrabThread.h"
#include "kademlia/kademlia/kademlia.h"
#include "kademlia/kademlia/SearchManager.h"
#include "kademlia/routing/RoutingZone.h"
#include "kademlia/routing/contact.h"
#include "kademlia/kademlia/prefs.h"
#include "KadSearchListCtrl.h"
#include "KadContactListCtrl.h"
#include "PerfLog.h"
#include "DropTarget.h"
//Xman
/*
#include "LastCommonRouteFinder.h"
*/
//Xman end
#include "WebServer.h"
#include "MMServer.h"
#include "DownloadQueue.h"
#include "ClientUDPSocket.h"
#include "UploadQueue.h"
#include "ClientList.h"
#include "UploadBandwidthThrottler.h"
#include "FriendList.h"
#include "IPFilter.h"
#include "Statistics.h"
#include "MuleToolbarCtrl.h"
#include "TaskbarNotifier.h"
#include "MuleStatusbarCtrl.h"
#include "ListenSocket.h"
#include "Server.h"
#include "PartFile.h"
#include "Scheduler.h"
#include "ClientCredits.h"
#include "MenuCmds.h"
#include "MuleSystrayDlg.h"
#include "IPFilterDlg.h"
#include "WebServices.h"
#include "DirectDownloadDlg.h"
#include "PeerCacheFinder.h"
#include "Statistics.h"
#include "FirewallOpener.h"
#include "StringConversion.h"
#include "aichsyncthread.h"
#include "Log.h"
#include "MiniMule.h"
#include "UserMsgs.h"
//Xman
#include "BandWidthControl.h" // Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
#include "IP2Country.h" //EastShare - added by AndCycle, IP to Country
#include "DLP.h" //Xman DLP
//Xman End
#include "TextToSpeech.h"
#include "Collection.h"
#include "CollectionViewDialog.h"
#include "VisualStylesXP.h"
// ==> UPnP support [MoNKi] - leuk_he
/*
#include "UPnPImpl.h"
#include "UPnPImplWrapper.h"
*/
// <== UPnP support [MoNKi] - leuk_he
#include <dbt.h>
#include "XMessageBox.h"
//zz_fly
#include "SR13-ImportParts.h" //MORPH - Added by SiRoB, Import Parts
// MORPH START - Added by Commander, Friendlinks [emulEspaa]
#include "Friend.h"
// MORPH END - Added by Commander, Friendlinks [emulEspaa]
//zz_fly end
#include "HttpDownloadDlg.h" // Advanced Updates [MorphXT/Stulle] - Stulle
#include "NTservice.h" // Run eMule as NT Service [leuk_he/Stulle] - Stulle
#include "AskExitDlg.h" // Extended Prompt on Exit dialog [leuk_he] - Stulle
// >> add by Ken -- search GIFC
#include "SearchParamsWnd.h"
// << add by Ken
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern BOOL FirstTimeWizard();
#define SYS_TRAY_ICON_COOKIE_FORCE_UPDATE (UINT)-1
UINT g_uMainThreadId = 0;
const static UINT UWM_ARE_YOU_EMULE = RegisterWindowMessage(EMULE_GUID);
#ifdef HAVE_WIN7_SDK_H
const static UINT UWM_TASK_BUTTON_CREATED = RegisterWindowMessage(_T("TaskbarButtonCreated"));
#endif
// ==> Invisible Mode [TPT/MoNKi] - Stulle
// Allows "invisible mode" on multiple instances of eMule
#ifdef _DEBUG
#define EMULE_GUID_INVMODE "EMULE-{4EADC6FC-516F-4b7c-9066-97D893649569}-DEBUG-INVISIBLEMODE"
#else
#define EMULE_GUID_INVMODE "EMULE-{4EADC6FC-516F-4b7c-9066-97D893649569}-INVISIBLEMODE"
#endif
const static UINT UWM_RESTORE_WINDOW_IM=RegisterWindowMessage(_T(EMULE_GUID_INVMODE));
// <== Invisible Mode [TPT/MoNKi] - Stulle
///////////////////////////////////////////////////////////////////////////
// CemuleDlg Dialog
IMPLEMENT_DYNAMIC(CMsgBoxException, CException)
BEGIN_MESSAGE_MAP(CemuleDlg, CTrayDialog)
///////////////////////////////////////////////////////////////////////////
// Windows messages
//
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_ENDSESSION()
ON_WM_SIZE()
ON_WM_CLOSE()
ON_WM_MENUCHAR()
ON_WM_QUERYENDSESSION()
ON_WM_SYSCOLORCHANGE()
ON_WM_CTLCOLOR()
ON_MESSAGE(WM_COPYDATA, OnWMData)
ON_MESSAGE(WM_KICKIDLE, OnKickIdle)
ON_MESSAGE(WM_USERCHANGED, OnUserChanged)
ON_WM_SHOWWINDOW()
ON_WM_DESTROY()
ON_WM_SETTINGCHANGE()
ON_WM_DEVICECHANGE()
ON_MESSAGE(WM_POWERBROADCAST, OnPowerBroadcast)
ON_MESSAGE(WM_HOTKEY, OnHotKey) // Invisible Mode [TPT/MoNKi] - Stulle
ON_WM_MEASUREITEM() // XP Style Menu [Xanatos] - Stulle
///////////////////////////////////////////////////////////////////////////
// WM_COMMAND messages
//
ON_COMMAND(MP_CONNECT, StartConnection)
ON_COMMAND(MP_DISCONNECT, CloseConnection)
ON_COMMAND(MP_EXIT, OnClose)
ON_COMMAND(MP_RESTORE, RestoreWindow)
// quick-speed changer --
ON_COMMAND_RANGE(MP_QS_U10, MP_QS_UP10, QuickSpeedUpload)
ON_COMMAND_RANGE(MP_QS_D10, MP_QS_DC, QuickSpeedDownload)
//--- quickspeed - paralize all ---
ON_COMMAND_RANGE(MP_QS_PA, MP_QS_UA, QuickSpeedOther)
// quick-speed changer -- based on xrmb
ON_NOTIFY_EX_RANGE(RBN_CHEVRONPUSHED, 0, 0xFFFF, OnChevronPushed)
ON_REGISTERED_MESSAGE(UWM_ARE_YOU_EMULE, OnAreYouEmule)
// ==> Invisible Mode [TPT/MoNKi] - Stulle
ON_REGISTERED_MESSAGE(UWM_RESTORE_WINDOW_IM, OnRestoreWindowInvisibleMode)
// <== Invisible Mode [TPT/MoNKi] - Stulle
ON_BN_CLICKED(IDC_HOTMENU, OnBnClickedHotmenu)
///////////////////////////////////////////////////////////////////////////
// WM_USER messages
//
ON_MESSAGE(UM_TASKBARNOTIFIERCLICKED, OnTaskbarNotifierClicked)
ON_MESSAGE(UM_CLOSE_MINIMULE, OnCloseMiniMule)
// Webserver messages
ON_MESSAGE(WEB_GUI_INTERACTION, OnWebGUIInteraction)
ON_MESSAGE(WEB_CLEAR_COMPLETED, OnWebServerClearCompleted)
ON_MESSAGE(WEB_FILE_RENAME, OnWebServerFileRename)
ON_MESSAGE(WEB_ADDDOWNLOADS, OnWebAddDownloads)
ON_MESSAGE(WEB_CATPRIO, OnWebSetCatPrio)
ON_MESSAGE(WEB_ADDREMOVEFRIEND, OnAddRemoveFriend)
// Version Check DNS
ON_MESSAGE(UM_VERSIONCHECK_RESPONSE, OnVersionCheckResponse)
//Xman versions check
ON_MESSAGE(UM_MVERSIONCHECK_RESPONSE, OnMVersionCheckResponse)
ON_MESSAGE(UM_DLPVERSIONCHECK_RESPONSE, OnDLPVersionCheckResponse) //Xman DLP //MOD NOTE: if you are using DLP, don't remove/modify this versions-check
//Xman end
// ScarAngel Version Check - Stulle
ON_MESSAGE(UM_SVERSIONCHECK_RESPONSE, OnSVersionCheckResponse)
// Advanced Updates [MorphXT/Stulle] - Stulle
ON_MESSAGE(UM_DLPAUTOVERCHECK_RESPONSE, OnDLPAutoVerCheckResponse)
ON_MESSAGE(UM_IPFFILTERAUTOVERCHECK_RESPONSE, OnIPFilterAutoVerCheckResponse)
// Run eMule as NT Service [leuk_he/Stulle] - Stulle
ON_MESSAGE(WEB_COPYDATA, OnWMData)
ON_MESSAGE(UM_SERVERSTATUS, OnServiceStatus)
// PeerCache DNS
ON_MESSAGE(UM_PEERCHACHE_RESPONSE, OnPeerCacheResponse)
// UPnP
// ==> UPnP support [MoNKi] - leuk_he
/*
ON_MESSAGE(UM_UPNP_RESULT, OnUPnPResult)
*/
// <== UPnP support [MoNKi] - leuk_he
///////////////////////////////////////////////////////////////////////////
// WM_APP messages
//
ON_MESSAGE(TM_FINISHEDHASHING, OnFileHashed)
ON_MESSAGE(TM_FILEOPPROGRESS, OnFileOpProgress)
ON_MESSAGE(TM_HASHFAILED, OnHashFailed)
//Xman
// BEGIN SLUGFILLER: SafeHash
ON_MESSAGE(TM_PARTHASHEDOK, OnPartHashedOK)
ON_MESSAGE(TM_PARTHASHEDOKNOAICH, OnPartHashedOKNoAICH)
ON_MESSAGE(TM_PARTHASHEDCORRUPT, OnPartHashedCorrupt)
ON_MESSAGE(TM_PARTHASHEDCORRUPTNOAICH, OnPartHashedCorruptNoAICH)
ON_MESSAGE(TM_PARTHASHEDOKAICHRECOVER, OnPartHashedOKAICHRecover)
ON_MESSAGE(TM_PARTHASHEDCORRUPTAICHRECOVER, OnPartHashedCorruptAICHRecover)
// END SLUGFILLER: SafeHash
ON_MESSAGE(TM_READBLOCKFROMFILEDONE, OnReadBlockFromFileDone) // SiRoB: ReadBlockFromFileThread
ON_MESSAGE(TM_FLUSHDONE, OnFlushDone) // SiRoB: Flush Thread
ON_MESSAGE(TM_DOTIMER, DoTimer) //Xman process timer code via messages (Xanatos)
ON_MESSAGE(TM_IMPORTPART, OnImportPart) //MORPH - Added by SiRoB, Import Parts - added by zz_fly
//Xman end
ON_MESSAGE(TM_SAVEDONE, OnSaveDone) // File Settings [sivka/Stulle] - Stulle
ON_MESSAGE(TM_SAVEKNOWNDONE, OnSaveKnownDone) // Threaded Known Files Saving [Stulle] - Stulle
ON_MESSAGE(TM_FRAMEGRABFINISHED, OnFrameGrabFinished)
ON_MESSAGE(TM_FILEALLOCEXC, OnFileAllocExc)
ON_MESSAGE(TM_FILECOMPLETED, OnFileCompleted)
ON_MESSAGE(TM_CONSOLETHREADEVENT, OnConsoleThreadEvent)
#ifdef HAVE_WIN7_SDK_H
ON_REGISTERED_MESSAGE(UWM_TASK_BUTTON_CREATED, OnTaskbarBtnCreated)
#endif
END_MESSAGE_MAP()
CemuleDlg::CemuleDlg(CWnd* pParent /*=NULL*/)
: CTrayDialog(CemuleDlg::IDD, pParent)
{
g_uMainThreadId = GetCurrentThreadId();
preferenceswnd = new CPreferencesDlg;
serverwnd = new CServerWnd;
kademliawnd = new CKademliaWnd;
transferwnd = new CTransferDlg;
sharedfileswnd = new CSharedFilesWnd;
searchwnd = new CSearchDlg;
chatwnd = new CChatWnd;
ircwnd = new CIrcWnd;
statisticswnd = new CStatisticsDlg;
toolbar = new CMuleToolbarCtrl;
statusbar = new CMuleStatusBarCtrl;
m_wndTaskbarNotifier = new CTaskbarNotifier;
m_hIcon = NULL;
theApp.m_app_state = APP_STATE_RUNNING;
ready = false;
m_bStartMinimizedChecked = false;
m_bStartMinimized = false;
memset(&m_wpFirstRestore, 0, sizeof m_wpFirstRestore);
m_uUpDatarate = 0;
m_uDownDatarate = 0;
status = 0;
activewnd = NULL;
for (int i = 0; i < _countof(connicons); i++)
connicons[i] = NULL;
transicons[0] = NULL;
transicons[1] = NULL;
transicons[2] = NULL;
transicons[3] = NULL;
imicons[0] = NULL;
imicons[1] = NULL;
imicons[2] = NULL;
m_iMsgIcon = 0;
m_iMsgBlinkState = false;
m_icoSysTrayConnected = NULL;
m_icoSysTrayDisconnected = NULL;
m_icoSysTrayLowID = NULL;
usericon = NULL;
m_icoSysTrayCurrent = NULL;
m_hTimer = 0;
notifierenabled = false;
m_pDropTarget = new CMainFrameDropTarget;
//Xman new slpash-screen arrangement
/*
m_pSplashWnd = NULL;
m_dwSplashTime = (DWORD)-1;
*/
//Xman end
m_pSystrayDlg = NULL;
m_pMiniMule = NULL;
m_uLastSysTrayIconCookie = SYS_TRAY_ICON_COOKIE_FORCE_UPDATE;
// ==> UPnP support [MoNKi] - leuk_he
/*
m_hUPnPTimeOutTimer = 0;
m_bConnectRequestDelayedForUPnP = false;
*/
// <== UPnP support [MoNKi] - leuk_he
m_bEd2kSuspendDisconnect = false;
m_bKadSuspendDisconnect = false;
m_bInitedCOM = false;
//Xman versions check
m_bCheckwasDone=false;
//Xman end
// ==> Show in MSN7 [TPT] - Stulle
m_dwMSNtime = 0;
m_uMSNup2Date = 0;
// <== Show in MSN7 [TPT] - Stulle
b_HideApp = false; // Invisible Mode [TPT/MoNKi] - Stulle
// ==> Completed in Tray [Stulle] - Stulle
m_icoSysTrayConnectedPlus = NULL;
m_icoSysTrayDisconnectedPlus = NULL;
m_icoSysTrayLowIDPlus = NULL;
m_dwTrayTime = 0;
m_bTrayBool = false;
m_bTrayBoolOld = false;
// <== Completed in Tray [Stulle] - Stulle
}
CemuleDlg::~CemuleDlg()
{
CloseTTS();
DestroyMiniMule();
if (m_icoSysTrayCurrent) VERIFY( DestroyIcon(m_icoSysTrayCurrent) );
if (m_hIcon) VERIFY( ::DestroyIcon(m_hIcon) );
for (int i = 0; i < _countof(connicons); i++){
if (connicons[i]) VERIFY( ::DestroyIcon(connicons[i]) );
}
if (transicons[0]) VERIFY( ::DestroyIcon(transicons[0]) );
if (transicons[1]) VERIFY( ::DestroyIcon(transicons[1]) );
if (transicons[2]) VERIFY( ::DestroyIcon(transicons[2]) );
if (transicons[3]) VERIFY( ::DestroyIcon(transicons[3]) );
if (imicons[0]) VERIFY( ::DestroyIcon(imicons[0]) );
if (imicons[1]) VERIFY( ::DestroyIcon(imicons[1]) );
if (imicons[2]) VERIFY( ::DestroyIcon(imicons[2]) );
if (m_icoSysTrayConnected) VERIFY( ::DestroyIcon(m_icoSysTrayConnected) );
if (m_icoSysTrayDisconnected) VERIFY( ::DestroyIcon(m_icoSysTrayDisconnected) );
if (m_icoSysTrayLowID) VERIFY( ::DestroyIcon(m_icoSysTrayLowID) );
// ==> Completed in Tray [Stulle] - Stulle
if (m_icoSysTrayConnectedPlus) VERIFY( ::DestroyIcon(m_icoSysTrayConnectedPlus) );
if (m_icoSysTrayDisconnectedPlus) VERIFY( ::DestroyIcon(m_icoSysTrayDisconnectedPlus) );
if (m_icoSysTrayLowIDPlus) VERIFY( ::DestroyIcon(m_icoSysTrayLowIDPlus) );
// <== Completed in Tray [Stulle] - Stulle
if (usericon) VERIFY( ::DestroyIcon(usericon) );
#ifdef HAVE_WIN7_SDK_H
if (m_pTaskbarList != NULL)
{
m_pTaskbarList.Release();
ASSERT( m_bInitedCOM );
}
if (m_bInitedCOM)
CoUninitialize();
#endif
// already destroyed by windows?
//VERIFY( m_menuUploadCtrl.DestroyMenu() );
//VERIFY( m_menuDownloadCtrl.DestroyMenu() );
//VERIFY( m_SysMenuOptions.DestroyMenu() );
delete preferenceswnd;
delete serverwnd;
delete kademliawnd;
delete sharedfileswnd;
delete chatwnd;
delete ircwnd;
delete statisticswnd;
delete toolbar;
delete statusbar;
delete m_wndTaskbarNotifier;
delete m_pDropTarget;
theApp.DestroyExtraFonts(); // Design Settings [eWombat/Stulle] - Stulle
}
void CemuleDlg::DoDataExchange(CDataExchange* pDX)
{
CTrayDialog::DoDataExchange(pDX);
}
LRESULT CemuleDlg::OnAreYouEmule(WPARAM, LPARAM)
{
return UWM_ARE_YOU_EMULE;
}
void DialogCreateIndirect(CDialog *pWnd, UINT uID)
{
#if 0
// This could be a nice way to change the font size of the main windows without needing
// to re-design the dialog resources. However, that technique does not work for the
// SearchWnd and it also introduces new glitches (which would need to get resolved)
// in almost all of the main windows.
CDialogTemplate dlgTempl;
dlgTempl.Load(MAKEINTRESOURCE(uID));
dlgTempl.SetFont(_T("MS Shell Dlg"), 8);
pWnd->CreateIndirect(dlgTempl.m_hTemplate);
FreeResource(dlgTempl.Detach());
#else
pWnd->Create(uID);
#endif
}
//#include <winuser.h>
BOOL CemuleDlg::OnInitDialog()
{
#ifdef HAVE_WIN7_SDK_H
// allow the TaskbarButtonCreated- & (tbb-)WM_COMMAND message to be sent to our window if our app is running elevated
if (thePrefs.GetWindowsVersion() >= _WINVER_7_)
{
int res = CoInitialize(NULL);
if (res == S_OK || res == S_FALSE)
{
m_bInitedCOM = true;
typedef BOOL (WINAPI* PChangeWindowMessageFilter)(UINT message, DWORD dwFlag);
PChangeWindowMessageFilter ChangeWindowMessageFilter =
(PChangeWindowMessageFilter )(GetProcAddress(
GetModuleHandle(TEXT("user32.dll")), "ChangeWindowMessageFilter"));
if (ChangeWindowMessageFilter) {
ChangeWindowMessageFilter(UWM_TASK_BUTTON_CREATED,1);
ChangeWindowMessageFilter(WM_COMMAND, 1);
}
}
else
ASSERT( false );
}
#endif
m_bStartMinimized = thePrefs.GetStartMinimized();
if (!m_bStartMinimized)
m_bStartMinimized = theApp.DidWeAutoStart();
// ==> Invisible Mode [TPT/MoNKi] - Stulle
if (thePrefs.GetInvisibleMode() && (theApp.DidWeAutoStart() || thePrefs.GetInvisibleModeStart()))
m_bStartMinimized = true;
// <== Invisible Mode [TPT/MoNKi] - Stulle
// temporary disable the 'startup minimized' option, otherwise no window will be shown at all
if (thePrefs.IsFirstStart())
m_bStartMinimized = false;
//Xman new slpash-screen arrangement
/*
// show splashscreen as early as possible to "entertain" user while starting emule up
if (thePrefs.UseSplashScreen() && !m_bStartMinimized)
ShowSplash();
*/
//Xman end
// ==> Startupsound [Commander] - mav744
if (thePrefs.UseStartupSound()){
if(PathFileExists(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("startup.wav")))
PlaySound(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("startup.wav"), NULL, SND_FILENAME | SND_NOSTOP | SND_NOWAIT | SND_ASYNC);
else
AddLogLine(false,GetResString(IDS_MISSING_STARTUPSOUND));
}
// <== Startupsound [Commander] - mav744
// Create global GUI objects
theApp.CreateAllFonts();
theApp.CreateBackwardDiagonalBrush();
m_wndTaskbarNotifier->SetTextDefaultFont();
CTrayDialog::OnInitDialog();
InitWindowStyles(this);
CreateToolbarCmdIconMap();
// ==> Static Tray Icon [MorphXT] - MyTh88
if(thePrefs.GetStaticIcon())
// ==> TBH: minimule - Stulle
/*
TrayShow();
*/
TrayShow(false);
// <== TBH: minimule - Stulle
// <== Static Tray Icon [MorphXT] - MyTh88
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL){
pSysMenu->AppendMenu(MF_SEPARATOR);
ASSERT( (MP_ABOUTBOX & 0xFFF0) == MP_ABOUTBOX && MP_ABOUTBOX < 0xF000);
pSysMenu->AppendMenu(MF_STRING, MP_ABOUTBOX, GetResString(IDS_ABOUTBOX));
ASSERT( (MP_VERSIONCHECK & 0xFFF0) == MP_VERSIONCHECK && MP_VERSIONCHECK < 0xF000);
pSysMenu->AppendMenu(MF_STRING, MP_VERSIONCHECK, GetResString(IDS_VERSIONCHECK));
//Xman versions check
// ==> Removed Xtreme version check [Stulle] - Stulle
/*
ASSERT( (MP_MVERSIONCHECK & 0xFFF0) == MP_MVERSIONCHECK && MP_MVERSIONCHECK < 0xF000);
pSysMenu->AppendMenu(MF_STRING, MP_MVERSIONCHECK, _T("Xtreme-Version-Check"));
*/
// <== Removed Xtreme version check [Stulle] - Stulle
//Xman end
// ==> ScarAngel Version Check - Stulle
ASSERT( (MP_SVERSIONCHECK & 0xFFF0) == MP_SVERSIONCHECK && MP_SVERSIONCHECK < 0xF000);
pSysMenu->AppendMenu(MF_STRING, MP_SVERSIONCHECK, GetResString(IDS_SVERSIONCHECK));
// <== ScarAngel Version Check - Stulle
// remaining system menu entries are created later...
}
CWnd* pwndToolbarX = toolbar;
if (toolbar->Create(WS_CHILD | WS_VISIBLE, CRect(0,0,0,0), this, IDC_TOOLBAR))
{
toolbar->Init();
if (thePrefs.GetUseReBarToolbar())
{
if (m_ctlMainTopReBar.Create(WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
RBS_BANDBORDERS | RBS_AUTOSIZE | CCS_NODIVIDER,
CRect(0, 0, 0, 0), this, AFX_IDW_REBAR))
{
CSize sizeBar;
VERIFY( toolbar->GetMaxSize(&sizeBar) );
REBARBANDINFO rbbi = {0};
rbbi.cbSize = sizeof(rbbi);
rbbi.fMask = RBBIM_STYLE | RBBIM_SIZE | RBBIM_CHILD | RBBIM_CHILDSIZE | RBBIM_IDEALSIZE | RBBIM_ID;
rbbi.fStyle = RBBS_NOGRIPPER | RBBS_BREAK | RBBS_USECHEVRON;
rbbi.hwndChild = toolbar->m_hWnd;
rbbi.cxMinChild = sizeBar.cy;
rbbi.cyMinChild = sizeBar.cy;
rbbi.cxIdeal = sizeBar.cx;
rbbi.cx = rbbi.cxIdeal;
rbbi.wID = 0;
VERIFY( m_ctlMainTopReBar.InsertBand((UINT)-1, &rbbi) );
toolbar->SaveCurHeight();
toolbar->UpdateBackground();
pwndToolbarX = &m_ctlMainTopReBar;
}
}
}
theApp.CreateExtraFonts(GetFont()); // Design Settings [eWombat/Stulle] - Stulle
// set title
// Maella -Support for tag ET_MOD_VERSION 0x55
/*
SetWindowText(_T("eMule v") + theApp.m_strCurVersionLong);
*/
// ==> ModID [itsonlyme/SiRoB] - Stulle
/*
SetWindowText(_T("eMule v") + theApp.m_strCurVersionLong + _T(" ") + MOD_VERSION);
*/
SetWindowText(_T("eMule v") + theApp.m_strCurVersionLong + _T(" [") + theApp.m_strModLongVersion + _T("]"));
// <== ModID [itsonlyme/SiRoB] - Stulle
//Xman end
// Init taskbar notifier
m_wndTaskbarNotifier->Create(this);
LoadNotifier(thePrefs.GetNotifierConfiguration());
// ==> TBH: minimule - Max
if (theApp.minimule != NULL)
theApp.minimule->Create(IDD_MINI_MULE,this);
// <== TBH: minimule - Max
// set statusbar
// the statusbar control is created as a custom control in the dialog resource,
// this solves font and sizing problems when using large system fonts
statusbar->SubclassWindow(GetDlgItem(IDC_STATUSBAR)->m_hWnd);
statusbar->EnableToolTips(true);
statusbar->UpdateColor();// Design Settings [eWombat/Stulle] - Max
SetStatusBarPartsSize();
// create main window dialog pages
//zz_fly :: the fix(Xtreme 7.0&7.1) is not needed. but the gui in WinXP still has something wrong. see also: CTransferWnd::ResetTransToolbar
DialogCreateIndirect(serverwnd, IDD_SERVER);
DialogCreateIndirect(sharedfileswnd, IDD_FILES);
searchwnd->Create(this); // can not use 'DialogCreateIndirect' for the SearchWnd, grrr..
DialogCreateIndirect(chatwnd, IDD_CHAT);
transferwnd->Create(this);
DialogCreateIndirect(statisticswnd, IDD_STATISTICS);
DialogCreateIndirect(kademliawnd, IDD_KADEMLIAWND);
DialogCreateIndirect(ircwnd, IDD_IRC);
// with the top rebar control, some XP themes look better with some additional lite borders.. some not..
//serverwnd->ModifyStyleEx(0, WS_EX_STATICEDGE);
//sharedfileswnd->ModifyStyleEx(0, WS_EX_STATICEDGE);
//searchwnd->ModifyStyleEx(0, WS_EX_STATICEDGE);
//chatwnd->ModifyStyleEx(0, WS_EX_STATICEDGE);
//transferwnd->ModifyStyleEx(0, WS_EX_STATICEDGE);
//statisticswnd->ModifyStyleEx(0, WS_EX_STATICEDGE);
//kademliawnd->ModifyStyleEx(0, WS_EX_STATICEDGE);
//ircwnd->ModifyStyleEx(0, WS_EX_STATICEDGE);
// optional: restore last used main window dialog
if (thePrefs.GetRestoreLastMainWndDlg()){
switch (thePrefs.GetLastMainWndDlgID()){
case IDD_SERVER:
SetActiveDialog(serverwnd);
break;
case IDD_FILES:
SetActiveDialog(sharedfileswnd);
break;
case IDD_SEARCH:
SetActiveDialog(searchwnd);
break;
case IDD_CHAT:
SetActiveDialog(chatwnd);
break;
case IDD_TRANSFER:
SetActiveDialog(transferwnd);
break;
case IDD_STATISTICS:
SetActiveDialog(statisticswnd);
break;
case IDD_KADEMLIAWND:
SetActiveDialog(kademliawnd);
break;
case IDD_IRC:
SetActiveDialog(ircwnd);
break;
}
}
// if still no active window, activate server window
if (activewnd == NULL)
// >> add by Ken - if thePrefs.IsLessControl, active transfer window
if (thePrefs.IsLessControls())
SetActiveDialog(transferwnd);
else
// << add by Ken
SetActiveDialog(serverwnd);
SetAllIcons();
Localize();
// set updateintervall of graphic rate display (in seconds)
//ShowConnectionState(false);
// adjust all main window sizes for toolbar height and maximize the child windows
CRect rcClient, rcToolbar, rcStatusbar;
GetClientRect(&rcClient);
pwndToolbarX->GetWindowRect(&rcToolbar);
statusbar->GetWindowRect(&rcStatusbar);
rcClient.top += rcToolbar.Height();
rcClient.bottom -= rcStatusbar.Height();
CWnd* apWnds[] =
{
serverwnd,
kademliawnd,
transferwnd,
sharedfileswnd,
searchwnd,
chatwnd,
ircwnd,
statisticswnd
};
for (int i = 0; i < _countof(apWnds); i++)
apWnds[i]->SetWindowPos(NULL, rcClient.left, rcClient.top, rcClient.Width(), rcClient.Height(), SWP_NOZORDER);
// ==> High resolution speedmeter on toolbar [eFMod/Stulle] - Myth88
CRect rect;
CRect rect1,rect2;
toolbar->GetClientRect(&rect);
// set updateintervall of graphic rate display (in seconds)
//rect1.top = rect.top+2;
rect1.top = 2; // we need to make it clear on startup...
rect1.right = rect.right-2;
//rect1.bottom = rect.top+(rect.Height()/2)-1;
rect1.bottom = 26; // we need to make it clear on startup...
rect1.left = rect.right-150;
//rect2.top = rect.top+(rect.Height()/2)+1;
rect2.top = 28; // we need to make it clear on startup...
rect2.right = rect.right-2;
//rect2.bottom = rect.bottom-2;
rect2.bottom = 52; // we need to make it clear on startup...
rect2.left = rect.right-150;
CSize csMaxSize;
bool bTooSmall = false;
toolbar->GetMaxSize(&csMaxSize);
if (rect.left + csMaxSize.cx > rect.right - 150)
bTooSmall = true;
m_co_UpTrafficGraph.Create(IDD_SPEEDGRAPH,rect1,this);
m_co_DownTrafficGraph.Create(IDD_SPEEDGRAPH,rect2,this);
if(bTooSmall || thePrefs.GetShowSpeedMeter() == false)
{
m_co_UpTrafficGraph.ShowWindow(SW_HIDE);
m_co_DownTrafficGraph.ShowWindow(SW_HIDE);
}
// Traffic graph
m_co_UpTrafficGraph.Init_Graph(_T("Up"),(UINT)thePrefs.GetMaxGraphUploadRate());
m_co_DownTrafficGraph.Init_Graph(_T("Down"),(UINT)thePrefs.GetMaxGraphDownloadRate());
// <== High resolution speedmeter on toolbar [eFMod/Stulle] - Myth88
// anchors
AddAnchor(*serverwnd, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(*kademliawnd, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(*transferwnd, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(*sharedfileswnd, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(*searchwnd, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(*chatwnd, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(*ircwnd, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(*statisticswnd, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(*pwndToolbarX, TOP_LEFT, TOP_RIGHT);
AddAnchor(*statusbar, BOTTOM_LEFT, BOTTOM_RIGHT);
statisticswnd->ShowInterval();
// tray icon
TraySetMinimizeToTray(thePrefs.GetMinTrayPTR());
TrayMinimizeToTrayChange();
ShowTransferRate(true);
ShowPing();
searchwnd->UpdateCatTabs();
///////////////////////////////////////////////////////////////////////////
// Restore saved window placement
//
WINDOWPLACEMENT wp = {0};
wp.length = sizeof(wp);
wp = thePrefs.GetEmuleWindowPlacement();
if (m_bStartMinimized)
{
// To avoid the window flickering during startup we try to set the proper window show state right here.
// ==> Invisible Mode [TPT/MoNKi] - Stulle
/*
if (*thePrefs.GetMinTrayPTR())
*/
if (*thePrefs.GetMinTrayPTR() || thePrefs.GetInvisibleMode() && (theApp.DidWeAutoStart() || thePrefs.GetInvisibleModeStart()))
// <== Invisible Mode [TPT/MoNKi] - Stulle
{
// Minimize to System Tray
//
// Unfortunately this does not work. The eMule main window is a modal dialog which is invoked
// by CDialog::DoModal which eventually calls CWnd::RunModalLoop. Look at 'MLF_SHOWONIDLE' and
// 'bShowIdle' in the above noted functions to see why it's not possible to create the window
// right in hidden state.
//--- attempt #1
//wp.showCmd = SW_HIDE;
//TrayShow();
//--- doesn't work at all
//--- attempt #2
//if (wp.showCmd == SW_SHOWMAXIMIZED)
// wp.flags = WPF_RESTORETOMAXIMIZED;
//m_bStartMinimizedChecked = false; // post-hide the window..
//--- creates window flickering
//--- attempt #3
// Minimize the window into the task bar and later move it into the tray bar
if (wp.showCmd == SW_SHOWMAXIMIZED)
wp.flags = WPF_RESTORETOMAXIMIZED;
wp.showCmd = SW_MINIMIZE;
m_bStartMinimizedChecked = false;
// to get properly restored from tray bar (after attempt #3) we have to use a patched 'restore' window cmd..
m_wpFirstRestore = thePrefs.GetEmuleWindowPlacement();
m_wpFirstRestore.length = sizeof(m_wpFirstRestore);
if (m_wpFirstRestore.showCmd != SW_SHOWMAXIMIZED)
m_wpFirstRestore.showCmd = SW_SHOWNORMAL;
}
else {
// Minimize to System Taskbar
//
if (wp.showCmd == SW_SHOWMAXIMIZED)
wp.flags = WPF_RESTORETOMAXIMIZED;
wp.showCmd = SW_MINIMIZE; // Minimize window but do not activate it.
m_bStartMinimizedChecked = true;
}
}
else
{
// Allow only SW_SHOWNORMAL and SW_SHOWMAXIMIZED. Ignore SW_SHOWMINIMIZED to make sure the window
// becomes visible. If user wants SW_SHOWMINIMIZED, we already have an explicit option for this (see above).
if (wp.showCmd != SW_SHOWMAXIMIZED)
wp.showCmd = SW_SHOWNORMAL;
m_bStartMinimizedChecked = true;
}
SetWindowPlacement(&wp);
if (thePrefs.GetWSIsEnabled())
theApp.webserver->StartServer();
theApp.mmserver->Init();
VERIFY( (m_hTimer = ::SetTimer(NULL, NULL, 300, StartupTimer)) != NULL );
if (thePrefs.GetVerbose() && !m_hTimer)
AddDebugLogLine(true,_T("Failed to create 'startup' timer - %s"),GetErrorMessage(GetLastError()));
theStats.starttime = GetTickCount();
m_bTbhMiniMuleVis = false; // TBH: minimule - Stulle
// ==> UPnP support [MoNKi] - leuk_he
/*
// Start UPnP prot forwarding
#ifdef DUAL_UPNP //zz_fly :: dual upnp
if (!thePrefs.m_bUseACATUPnPCurrent && thePrefs.IsUPnPEnabled())
#else //zz_fly :: dual upnp
if (thePrefs.IsUPnPEnabled())
#endif //zz_fly :: dual upnp
StartUPnP();
*/
// <== UPnP support [MoNKi] - leuk_he
if (thePrefs.IsFirstStart())
{
// temporary disable the 'startup minimized' option, otherwise no window will be shown at all
m_bStartMinimized = false;
//Xman
// SLUGFILLER: SafeHash remove - wait until emule is ready before opening the wizard
/*
DestroySplash();
FirstTimeWizard();
*/
//Xman end
}
// ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle
// Set nt server from RUNNING to started
if (RunningAsService())
ServiceStartedSuccesfully(); //when started (multiple calls not a problem)
// <== Run eMule as NT Service [leuk_he/Stulle] - Stulle
// ==> Invisible Mode [TPT/MoNKi] - Stulle
if(thePrefs.GetInvisibleMode())
RegisterInvisibleHotKey();
// <== Invisible Mode [TPT/MoNKi] - Stulle
VERIFY( m_pDropTarget->Register(this) );
// initalize PeerCache
theApp.m_pPeerCache->Init(thePrefs.GetPeerCacheLastSearch(), thePrefs.WasPeerCacheFound(), thePrefs.IsPeerCacheDownloadEnabled(), thePrefs.GetPeerCachePort());
//Xman
// SiRoB: SafeHash fix (see StartupTimer)
/*
// start aichsyncthread
AfxBeginThread(RUNTIME_CLASS(CAICHSyncThread), THREAD_PRIORITY_BELOW_NORMAL,0);
*/
//Xman end
// debug info
DebugLog(_T("Using '%s' as config directory"), thePrefs.GetMuleDirectory(EMULE_CONFIGDIR));
if (!thePrefs.HasCustomTaskIconColor())
SetTaskbarIconColor();
return TRUE;
}
// modders: dont remove or change the original versioncheck! (additionals are ok)
void CemuleDlg::DoVersioncheck(bool manual) {
if (!manual && thePrefs.GetLastVC()!=0) {
CTime last(thePrefs.GetLastVC());
struct tm tmTemp;
time_t tLast = safe_mktime(last.GetLocalTm(&tmTemp));
time_t tNow = safe_mktime(CTime::GetCurrentTime().GetLocalTm(&tmTemp));
#ifndef _BETA
if ( (difftime(tNow,tLast) / 86400) < thePrefs.GetUpdateDays() ){
#else
if ( (difftime(tNow,tLast) / 86400) < 3 ){
#endif
return;
}
}
#ifndef _BETA
if (WSAAsyncGetHostByName(m_hWnd, UM_VERSIONCHECK_RESPONSE, "vcdns2.emule-project.org", m_acVCDNSBuffer, sizeof(m_acVCDNSBuffer)) == 0){
#else
if (WSAAsyncGetHostByName(m_hWnd, UM_VERSIONCHECK_RESPONSE, "vcdns1.emule-project.org", m_acVCDNSBuffer, sizeof(m_acVCDNSBuffer)) == 0){
#endif
AddLogLine(true,GetResString(IDS_NEWVERSIONFAILED));
}
}
void CALLBACK CemuleDlg::StartupTimer(HWND /*hwnd*/, UINT /*uiMsg*/, UINT /*idEvent*/, DWORD /*dwTime*/)
{
//Xman
// SLUGFILLER: doubleLucas - not ready to init, come back next cycle
if (!::IsWindow(theApp.emuledlg->m_hWnd))
return;
if (!::IsWindow(theApp.emuledlg->sharedfileswnd->sharedfilesctrl.m_hWnd))
return;
if (!::IsWindow(theApp.emuledlg->serverwnd->serverlistctrl.m_hWnd))
return;
if (!::IsWindow(theApp.emuledlg->transferwnd->GetDownloadList()->m_hWnd))
return;
//Xman end
// NOTE: Always handle all type of MFC exceptions in TimerProcs - otherwise we'll get mem leaks
try
{
switch(theApp.emuledlg->status){
case 0:
theApp.emuledlg->status++;
theApp.emuledlg->ready = true;
//Xman
// SLUGFILLER: SafeHash remove - moved down
/*
theApp.sharedfiles->SetOutputCtrl(&theApp.emuledlg->sharedfileswnd->sharedfilesctrl);
*/
//Xman end
theApp.emuledlg->status++;
break;
case 1:
break;
case 2:
theApp.emuledlg->status++;
try{
theApp.serverlist->Init();
}
catch(...){
ASSERT(0);
LogError(LOG_STATUSBAR,_T("Failed to initialize server list - Unknown exception"));
}
theApp.emuledlg->status++;
break;
case 3:
break;
case 4:{
bool bError = false;
theApp.emuledlg->status++;
theApp.UpdateSplash(_T("initializing files to download ...")); //Xman new slpash-screen arrangement
// NOTE: If we have an unhandled exception in CDownloadQueue::Init, MFC will silently catch it
// and the creation of the TCP and the UDP socket will not be done -> client will get a LowID!
try{
theApp.downloadqueue->Init();
}
catch(...){
ASSERT(0);
LogError(LOG_STATUSBAR,_T("Failed to initialize download queue - Unknown exception"));
bError = true;
}
if (!theApp.listensocket->StartListening()) {
CString strError;
strError.Format(GetResString(IDS_MAIN_SOCKETERROR), thePrefs.GetPort());
LogError(LOG_STATUSBAR, _T("%s"), strError);
if (thePrefs.GetNotifierOnImportantError())
theApp.emuledlg->ShowNotifier(strError, TBN_IMPORTANTEVENT);
bError = true;
}
if (!theApp.clientudp->Create()) {
CString strError;
strError.Format(GetResString(IDS_MAIN_SOCKETERROR), thePrefs.GetUDPPort());
LogError(LOG_STATUSBAR, _T("%s"), strError);
if (thePrefs.GetNotifierOnImportantError())
theApp.emuledlg->ShowNotifier(strError, TBN_IMPORTANTEVENT);
}
// ==> Random Ports [MoNKi] - Stulle
theApp.emuledlg->serverwnd->UpdateMyInfo();
// <== Random Ports [MoNKi] - Stulle
if (!bError) // show the success msg, only if we had no serious error
{ //Xman
//<<< eWombat [WINSOCK2] for Pawcio: BC
AddLogLine(false,_T("***************Winsock***************"));
AddLogLine(false,_T("Winsock: Version %d.%d [%.40s] %.40s"), HIBYTE( theApp.m_wsaData.wVersion ),LOBYTE(theApp.m_wsaData.wVersion ),
CString(theApp.m_wsaData.szDescription), CString(theApp.m_wsaData.szSystemStatus));
if (theApp.m_wsaData.iMaxSockets!=0)
AddLogLine(false,_T("Winsock: max. sockets %d"), theApp.m_wsaData.iMaxSockets);
else
AddLogLine(false,_T("Winsock: unlimited sockets"));
AddLogLine(false,_T("***************Winsock***************"));
//>>> eWombat [WINSOCK2]
// XMan // Maella -Support for tag ET_MOD_VERSION 0x55
/*
AddLogLine(true, GetResString(IDS_MAIN_READY), theApp.m_strCurVersionLong);
*/
// ==> ModID [itsonlyme/SiRoB] - Stulle
/*
AddLogLine(true, GetResString(IDS_MAIN_READY),theApp.m_strCurVersionLong + _T(" ") + MOD_VERSION);
*/
AddLogLine(true, GetResString(IDS_MAIN_READY),theApp.m_strCurVersionLong + _T(" ") + theApp.m_strModLongVersion);
// <== ModID [itsonlyme/SiRoB] - Stulle
//Xman end
//Xman
}
// SLUGFILLER: SafeHash remove - moved down
/*
if (thePrefs.DoAutoConnect())
theApp.emuledlg->OnBnClickedConnect();
*/
//Xman end
#ifdef HAVE_WIN7_SDK_H
theApp.emuledlg->UpdateStatusBarProgress();
#endif
break;
}
case 5:
if (thePrefs.IsStoringSearchesEnabled())
theApp.searchlist->LoadSearches();
theApp.emuledlg->status++;
break;
//Xman
// BEGIN SLUGFILLER: SafeHash - delay load shared files
case 6:
theApp.emuledlg->status++;
theApp.sharedfiles->SetOutputCtrl(&theApp.emuledlg->sharedfileswnd->sharedfilesctrl);
theApp.emuledlg->sharedfileswnd->historylistctrl.Init(); //Xman [MoNKi: -Downloaded History-]
// BEGIN SiRoB: SafeHash fix originaly in OnInitDialog (delay load shared files)
// start aichsyncthread
theApp.UpdateSplash(_T("Synchronize AICH-Hashes...")); //Xman new slpash-screen arrangement
AfxBeginThread(RUNTIME_CLASS(CAICHSyncThread), THREAD_PRIORITY_BELOW_NORMAL,0);
// END SiRoB: SafeHash
theApp.emuledlg->status++;
break;
case 7:
break;
case 255:
break;
// END SLUGFILLER: SafeHash
default:
//Xman
// BEGIN SLUGFILLER: SafeHash
theApp.emuledlg->status = 255;
theApp.UpdateSplash(_T("Ready")); //Xman new slpash-screen arrangement
//autoconnect only after emule loaded completely
if(thePrefs.DoAutoConnect())
theApp.emuledlg->OnBnClickedConnect();
// wait until emule is ready before opening the wizard
// >> modified by Ken
//if (thePrefs.IsFirstStart())
// << modified by Ken
if (!thePrefs.IsLessControls() && thePrefs.IsFirstStart())
{
//Xman new slpash-screen arrangement
//DestroySplash();
theApp.DestroySplash();
//Xman end
FirstTimeWizard();
}
// END SLUGFILLER: SafeHash
theApp.emuledlg->StopTimer();
}
}
CATCH_DFLT_EXCEPTIONS(_T("CemuleDlg::StartupTimer"))
// Maella -Code Improvement-
// Remark: The macro CATCH_DFLT_EXCEPTIONS will not catch all types of exception.
// The exceptions thrown in callback function are not intercepted by the dbghelp.dll (e.g. eMule Dump, crashRpt, etc...)
catch(...) {
ASSERT( false ); //zz_fly :: let me know it
if(theApp.emuledlg != NULL)
AddLogLine(true, _T("Unknown %s exception in "), __FUNCTION__);
}
// Maella end
}
void CemuleDlg::StopTimer()
{
if (m_hTimer){
VERIFY( ::KillTimer(NULL, m_hTimer) );
m_hTimer = 0;
}
theApp.spashscreenfinished=true; //Xman new slpash-screen arrangement
if (thePrefs.UpdateNotify())
DoVersioncheck(false);
//MOD NOTE: if you are using DLP, don't remove/modify this versions-check
//Xman versions check
if (thePrefs.UpdateNotifyMod())
DoMVersioncheck(false);
//Xman end
// ==> ScarAngel Version Check - Stulle
if (thePrefs.UpdateNotify())
DoSVersioncheck(false);
// <== ScarAngel Version Check - Stulle
if (theApp.pstrPendingLink != NULL){
OnWMData(NULL, (LPARAM)&theApp.sendstruct);
delete theApp.pstrPendingLink;
}
}
void CemuleDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
// Systemmenu-Speedselector
if (nID >= MP_QS_U10 && nID <= MP_QS_UP10) {
QuickSpeedUpload(nID);
return;
}
if (nID >= MP_QS_D10 && nID <= MP_QS_DC) {
QuickSpeedDownload(nID);
return;
}
if (nID == MP_QS_PA || nID == MP_QS_UA) {
QuickSpeedOther(nID);
return;
}
switch (nID /*& 0xFFF0*/)
{
case MP_ABOUTBOX: {
CCreditsDlg dlgAbout;
dlgAbout.DoModal();
break;
}
case MP_VERSIONCHECK:
DoVersioncheck(true);
break;
//Xman versions check
case MP_MVERSIONCHECK:
DoMVersioncheck(true);
break;
//Xman end
// ==> ScarAngel Version Check - Stulle
case MP_SVERSIONCHECK:
DoSVersioncheck(true);
break;
// <== ScarAngel Version Check - Stulle
case MP_CONNECT:
StartConnection();
break;
case MP_DISCONNECT:
CloseConnection();
break;
default:
CTrayDialog::OnSysCommand(nID, lParam);
}
if ((nID & 0xFFF0) == SC_MINIMIZE ||
(nID & 0xFFF0) == MP_MINIMIZETOTRAY ||
(nID & 0xFFF0) == SC_RESTORE ||
(nID & 0xFFF0) == SC_MAXIMIZE)
{
ShowTransferRate(true);
ShowPing();
transferwnd->UpdateCatTabTitles();
}
}
void CemuleDlg::PostStartupMinimized()
{
if (!m_bStartMinimizedChecked)
{
//TODO: Use full initialized 'WINDOWPLACEMENT' and remove the 'OnCancel' call...
// Isn't that easy.. Read comments in OnInitDialog..
m_bStartMinimizedChecked = true;
if (m_bStartMinimized)
{
if (theApp.DidWeAutoStart())
{
if (!thePrefs.mintotray) {
thePrefs.mintotray = true;
MinimizeWindow();
thePrefs.mintotray = false;
}
else
MinimizeWindow();
}
else
MinimizeWindow();
}
}
}
void CemuleDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this);
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
dc.DrawIcon(x, y, m_hIcon);
}
else
CTrayDialog::OnPaint();
}
HCURSOR CemuleDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CemuleDlg::OnBnClickedConnect(){
if (!theApp.IsConnected())
//connect if not currently connected
if (!theApp.serverconnect->IsConnecting() && !Kademlia::CKademlia::IsRunning() ){
StartConnection();
}
else {
CloseConnection();
}
else{
//disconnect if currently connected
CloseConnection();
}
}
void CemuleDlg::ResetServerInfo(){
serverwnd->servermsgbox->Reset();
}
void CemuleDlg::ResetLog(){
serverwnd->logbox->Reset();
}
void CemuleDlg::ResetDebugLog(){
serverwnd->debuglog->Reset();
}
//Xman Anti-Leecher-Log
void CemuleDlg::ResetLeecherLog()
{
serverwnd->leecherlog->Reset();
}
//Xman end
void CemuleDlg::AddLogText(UINT uFlags, LPCTSTR pszText)
{
if (GetCurrentThreadId() != g_uMainThreadId)
{
theApp.QueueLogLineEx(uFlags, _T("%s"), pszText);
return;
}
if (uFlags & LOG_STATUSBAR)
{
if (statusbar->m_hWnd /*&& ready*/)
{
if (theApp.m_app_state != APP_STATE_SHUTTINGDOWN)
statusbar->SetText(pszText, SBarLog, 0);
}
else
{ //Xman
theApp.DestroySplash(); //Xman new slpash-screen arrangement
AfxMessageBox(pszText);
} //Xman
}
#if defined(_DEBUG) || defined(USE_DEBUG_DEVICE)
Debug(_T("%s\n"), pszText);
#endif
if ((uFlags & LOG_DEBUG) && !thePrefs.GetVerbose())
return;
//Xman Anti-Leecher-Log
if ((uFlags & LOG_LEECHER) && !thePrefs.GetVerbose())
return;
TCHAR temp[1060];
int iLen = _sntprintf(temp, _countof(temp), _T("%s: %s\r\n"), CTime::GetCurrentTime().Format(thePrefs.GetDateTimeFormat4Log()), pszText);
if (iLen >= 0)
{
//Xman Anti-Leecher-Log
/*
if (!(uFlags & LOG_DEBUG))
*/
if (!(uFlags & LOG_DEBUG) && !(uFlags & LOG_LEECHER))
//Xman end
{
serverwnd->logbox->AddTyped(temp, iLen, uFlags & LOGMSGTYPEMASK);
if (IsWindow(serverwnd->StatusSelector) && serverwnd->StatusSelector.GetCurSel() != CServerWnd::PaneLog)
serverwnd->StatusSelector.HighlightItem(CServerWnd::PaneLog, TRUE);
if (!(uFlags & LOG_DONTNOTIFY) && ready)
ShowNotifier(pszText, TBN_LOG);
if (thePrefs.GetLog2Disk())
theLog.Log(temp, iLen);
}
//Xman Anti-Leecher-Log
else
if (thePrefs.GetVerbose() && (uFlags & LOG_LEECHER) )
{
serverwnd->leecherlog->AddTyped(temp, iLen, uFlags & LOGMSGTYPEMASK);
if (IsWindow(serverwnd->StatusSelector) && serverwnd->StatusSelector.GetCurSel() != CServerWnd::PaneLeecherLog)
serverwnd->StatusSelector.HighlightItem(CServerWnd::PaneLeecherLog, TRUE);
if (thePrefs.GetDebug2Disk())
theVerboseLog.Log(temp, iLen);
}
else
//Xman end
if (thePrefs.GetVerbose() && ((uFlags & LOG_DEBUG) || thePrefs.GetFullVerbose()))
{
serverwnd->debuglog->AddTyped(temp, iLen, uFlags & LOGMSGTYPEMASK);
if (IsWindow(serverwnd->StatusSelector) && serverwnd->StatusSelector.GetCurSel() != CServerWnd::PaneVerboseLog)
serverwnd->StatusSelector.HighlightItem(CServerWnd::PaneVerboseLog, TRUE);
if (thePrefs.GetDebug2Disk())
theVerboseLog.Log(temp, iLen);
}
}
}
CString CemuleDlg::GetLastLogEntry()
{
return serverwnd->logbox->GetLastLogEntry();
}
CString CemuleDlg::GetAllLogEntries()
{
return serverwnd->logbox->GetAllLogEntries();
}
CString CemuleDlg::GetLastDebugLogEntry()
{
return serverwnd->debuglog->GetLastLogEntry();
}
CString CemuleDlg::GetAllDebugLogEntries()
{
return serverwnd->debuglog->GetAllLogEntries();
}
CString CemuleDlg::GetServerInfoText()
{
return serverwnd->servermsgbox->GetText();
}
void CemuleDlg::AddServerMessageLine(UINT uFlags, LPCTSTR pszLine)
{
CString strMsgLine(pszLine);
strMsgLine += _T('\n');
if ((uFlags & LOGMSGTYPEMASK) == LOG_INFO)
serverwnd->servermsgbox->AppendText(strMsgLine);
else
serverwnd->servermsgbox->AddTyped(strMsgLine, strMsgLine.GetLength(), uFlags & LOGMSGTYPEMASK);
if (IsWindow(serverwnd->StatusSelector) && serverwnd->StatusSelector.GetCurSel() != CServerWnd::PaneServerInfo)
serverwnd->StatusSelector.HighlightItem(CServerWnd::PaneServerInfo, TRUE);
}
UINT CemuleDlg::GetConnectionStateIconIndex() const
{
if (theApp.serverconnect->IsConnected() && !Kademlia::CKademlia::IsConnected())
{
if (theApp.serverconnect->IsLowID())
return 3; // LowNot
else
return 6; // HighNot
}
else if (!theApp.serverconnect->IsConnected() && Kademlia::CKademlia::IsConnected())
{
if (Kademlia::CKademlia::IsFirewalled())
return 1; // NotLow
else
return 2; // NotHigh
}
else if (theApp.serverconnect->IsConnected() && Kademlia::CKademlia::IsConnected())
{
if (theApp.serverconnect->IsLowID() && Kademlia::CKademlia::IsFirewalled())
return 4; // LowLow
else if (theApp.serverconnect->IsLowID())
return 5; // LowHigh
else if (Kademlia::CKademlia::IsFirewalled())
return 7; // HighLow
else
return 8; // HighHigh
}
else
{
return 0; // NotNot
}
}
void CemuleDlg::ShowConnectionStateIcon()
{
UINT uIconIdx = GetConnectionStateIconIndex();
if (uIconIdx >= _countof(connicons)){
ASSERT(0);
uIconIdx = 0;
}
statusbar->SetIcon(SBarConnected, connicons[uIconIdx]);
}
CString CemuleDlg::GetConnectionStateString()
{
CString status;
if (theApp.serverconnect->IsConnected())
status = _T("eD2K:") + GetResString(IDS_CONNECTED);
else if (theApp.serverconnect->IsConnecting())
status = _T("eD2K:") + GetResString(IDS_CONNECTING);
else
status = _T("eD2K:") + GetResString(IDS_NOTCONNECTED);
if (Kademlia::CKademlia::IsConnected())
status += _T("|Kad:") + GetResString(IDS_CONNECTED);
else if (Kademlia::CKademlia::IsRunning())
status += _T("|Kad:") + GetResString(IDS_CONNECTING);
else
status += _T("|Kad:") + GetResString(IDS_NOTCONNECTED);
return status;
}
void CemuleDlg::ShowConnectionState()
{
theApp.downloadqueue->OnConnectionState(theApp.IsConnected());
serverwnd->UpdateMyInfo();
serverwnd->UpdateControlsState();
kademliawnd->UpdateControlsState();
ShowConnectionStateIcon();
statusbar->SetText(GetConnectionStateString(), SBarConnected, 0);
if (theApp.IsConnected())
{
// ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle
// Set nt server from RUNNING to started
if (RunningAsService())
ServiceStartedSuccesfully(); //when started (multiple calls not a problem)
// <== Run eMule as NT Service [leuk_he/Stulle] - Stulle
CString strPane(GetResString(IDS_MAIN_BTN_DISCONNECT));
TBBUTTONINFO tbi;
tbi.cbSize = sizeof(TBBUTTONINFO);
tbi.dwMask = TBIF_IMAGE | TBIF_TEXT;
tbi.iImage = 1;
tbi.pszText = const_cast<LPTSTR>((LPCTSTR)strPane);
toolbar->SetButtonInfo(TBBTN_CONNECT, &tbi);
}
else
{
if (theApp.serverconnect->IsConnecting() || Kademlia::CKademlia::IsRunning())
{
CString strPane(GetResString(IDS_MAIN_BTN_CANCEL));
TBBUTTONINFO tbi;
tbi.cbSize = sizeof(TBBUTTONINFO);
tbi.dwMask = TBIF_IMAGE | TBIF_TEXT;
tbi.iImage = 2;
tbi.pszText = const_cast<LPTSTR>((LPCTSTR)strPane);
toolbar->SetButtonInfo(TBBTN_CONNECT, &tbi);
}
else
{
CString strPane(GetResString(IDS_MAIN_BTN_CONNECT));
TBBUTTONINFO tbi;
tbi.cbSize = sizeof(TBBUTTONINFO);
tbi.dwMask = TBIF_IMAGE | TBIF_TEXT;
tbi.iImage = 0;
tbi.pszText = const_cast<LPTSTR>((LPCTSTR)strPane);
toolbar->SetButtonInfo(TBBTN_CONNECT, &tbi);
}
}
ShowUserCount();
#ifdef HAVE_WIN7_SDK_H
UpdateThumbBarButtons();
#endif
}
void CemuleDlg::ShowUserCount()
{
uint32 totaluser, totalfile;
totaluser = totalfile = 0;
theApp.serverlist->GetUserFileStatus( totaluser, totalfile );
CString buffer;
if (theApp.serverconnect->IsConnected() && Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsConnected())
buffer.Format(_T("%s:%s(%s)|%s:%s(%s)"), GetResString(IDS_UUSERS), CastItoIShort(totaluser, false, 1), CastItoIShort(Kademlia::CKademlia::GetKademliaUsers(), false, 1), GetResString(IDS_FILES), CastItoIShort(totalfile, false, 1), CastItoIShort(Kademlia::CKademlia::GetKademliaFiles(), false, 1));
else if (theApp.serverconnect->IsConnected())
buffer.Format(_T("%s:%s|%s:%s"), GetResString(IDS_UUSERS), CastItoIShort(totaluser, false, 1), GetResString(IDS_FILES), CastItoIShort(totalfile, false, 1));
else if (Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsConnected())
buffer.Format(_T("%s:%s|%s:%s"), GetResString(IDS_UUSERS), CastItoIShort(Kademlia::CKademlia::GetKademliaUsers(), false, 1), GetResString(IDS_FILES), CastItoIShort(Kademlia::CKademlia::GetKademliaFiles(), false, 1));
else
buffer.Format(_T("%s:0|%s:0"), GetResString(IDS_UUSERS), GetResString(IDS_FILES));
statusbar->SetText(buffer, SBarUsers, 0);
}
void CemuleDlg::ShowMessageState(UINT iconnr)
{
m_iMsgIcon = iconnr;
statusbar->SetIcon(SBarChatMsg, imicons[m_iMsgIcon]);
}
void CemuleDlg::ShowTransferStateIcon()
{
if (m_uUpDatarate && m_uDownDatarate)
statusbar->SetIcon(SBarUpDown, transicons[3]);
else if (m_uUpDatarate)
statusbar->SetIcon(SBarUpDown, transicons[2]);
else if (m_uDownDatarate)
statusbar->SetIcon(SBarUpDown, transicons[1]);
else
statusbar->SetIcon(SBarUpDown, transicons[0]);
}
//Xman Code Improvement
//it's enough to update the datarate in ShowTransferrate
/*
CString CemuleDlg::GetUpDatarateString(UINT uUpDatarate)
{
m_uUpDatarate = uUpDatarate != (UINT)-1 ? uUpDatarate : theApp.uploadqueue->GetDatarate();
*/
CString CemuleDlg::GetUpDatarateString(UINT /*uUpDatarate*/)
{
//Xman end
TCHAR szBuff[128];
if (thePrefs.ShowOverhead()) {
//Xman
// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
/*
_sntprintf(szBuff, _countof(szBuff), _T("%.1f (%.1f)"), (float)m_uUpDatarate/1024, (float)theStats.GetUpDatarateOverhead()/1024);
*/
_sntprintf(szBuff, _countof(szBuff), _T("%.1f (%.1f)"), (float)m_uUpDatarate/1024, (float)m_uploadOverheadRate/1024);
//Xman end
szBuff[_countof(szBuff) - 1] = _T('\0');
}
else {
_sntprintf(szBuff, _countof(szBuff), _T("%.1f"), (float)m_uUpDatarate/1024);
szBuff[_countof(szBuff) - 1] = _T('\0');
}
return szBuff;
}
//Xman Code Improvement
//it's enough to update the datarate in ShowTransferrate
/*
CString CemuleDlg::GetDownDatarateString(UINT uDownDatarate)
{
m_uDownDatarate = uDownDatarate != (UINT)-1 ? uDownDatarate : theApp.downloadqueue->GetDatarate();
*/
CString CemuleDlg::GetDownDatarateString(UINT /*uDownDatarate*/)
{
//Xman end
TCHAR szBuff[128];
if (thePrefs.ShowOverhead()) {
//Xman
// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
/*
_sntprintf(szBuff, _countof(szBuff), _T("%.1f (%.1f)"), (float)m_uDownDatarate/1024, (float)theStats.GetDownDatarateOverhead()/1024);
*/
_sntprintf(szBuff, _countof(szBuff), _T("%.1f (%.1f)"), (float)m_uDownDatarate/1024, (float)m_downloadOverheadRate/1024);
//Xman end
szBuff[_countof(szBuff) - 1] = _T('\0');
}
else {
_sntprintf(szBuff, _countof(szBuff), _T("%.1f"), (float)m_uDownDatarate/1024);
szBuff[_countof(szBuff) - 1] = _T('\0');
}
return szBuff;
}
CString CemuleDlg::GetTransferRateString()
{
TCHAR szBuff[128];
if (thePrefs.ShowOverhead()) {
_sntprintf(szBuff, _countof(szBuff), GetResString(IDS_UPDOWN),
//Xman
// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
/*
(float)m_uUpDatarate/1024, (float)theStats.GetUpDatarateOverhead()/1024,
(float)m_uDownDatarate/1024, (float)theStats.GetDownDatarateOverhead()/1024);
*/
(float)m_uUpDatarate/1024, (float)m_uploadOverheadRate/1024,
(float)m_uDownDatarate/1024, (float)m_downloadOverheadRate/1024);
//Xman end
szBuff[_countof(szBuff) - 1] = _T('\0');
}
else {
_sntprintf(szBuff, _countof(szBuff), GetResString(IDS_UPDOWNSMALL), (float)m_uUpDatarate/1024, (float)m_uDownDatarate/1024);
szBuff[_countof(szBuff) - 1] = _T('\0');
}
return szBuff;
}
void CemuleDlg::ShowTransferRate(bool bForceAll)
{
if (bForceAll)
m_uLastSysTrayIconCookie = SYS_TRAY_ICON_COOKIE_FORCE_UPDATE;
//Xman
// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
/*
m_uDownDatarate = theApp.downloadqueue->GetDatarate();
m_uUpDatarate = theApp.uploadqueue->GetDatarate();
*/
// Retrieve the current datarates
uint32 eMuleIn; uint32 eMuleInOverall;
uint32 eMuleOut; uint32 eMuleOutOverall;
uint32 notUsed;
theApp.pBandWidthControl->GetDatarates(thePrefs.GetDatarateSamples(),
eMuleIn, eMuleInOverall,
eMuleOut, eMuleOutOverall,
notUsed, notUsed);
m_uDownDatarate = eMuleIn;
m_uUpDatarate = eMuleOut;
m_uploadOverheadRate=eMuleOutOverall-eMuleOut;
m_downloadOverheadRate=eMuleInOverall-eMuleIn;
//Xman end
// ==> Show in MSN7 [TPT] - Stulle
const float uploadRate = (float)m_uUpDatarate/1024;
const float downloadRate = (float)m_uDownDatarate/1024;
const float uploadOverheadRate = (float)m_uploadOverheadRate/1024;
const float downloadOverheadRate = (float)m_downloadOverheadRate/1024;
// <== Show in MSN7 [TPT] - Stulle
// ==> Completed in Tray [Stulle] - Stulle
int iTotal;
if (thePrefs.GetTrayComplete() && ::GetTickCount() - m_dwTrayTime > SEC2MS(10))
{
m_bTrayBool = (theApp.emuledlg->transferwnd->GetDownloadList()->GetCompleteDownloads(-1, iTotal) > 0);
m_dwTrayTime = ::GetTickCount();
}
// <== Completed in Tray [Stulle] - Stulle
CString strTransferRate = GetTransferRateString();
if (TrayIsVisible() || bForceAll)
{
TCHAR buffer2[64];
// set trayicon-icon
int iDownRateProcent = (int)ceil((m_uDownDatarate/10.24) / thePrefs.GetMaxGraphDownloadRate());
if (iDownRateProcent > 100)
iDownRateProcent = 100;
UpdateTrayIcon(iDownRateProcent);
if (theApp.IsConnected()) {
_sntprintf(buffer2, _countof(buffer2), _T("eMule v%s (%s)\r\n%s"), theApp.m_strCurVersionLong, GetResString(IDS_CONNECTED), strTransferRate);
buffer2[_countof(buffer2) - 1] = _T('\0');
}
else {
_sntprintf(buffer2, _countof(buffer2), _T("eMule v%s (%s)\r\n%s"), theApp.m_strCurVersionLong, GetResString(IDS_DISCONNECTED), strTransferRate);
buffer2[_countof(buffer2) - 1] = _T('\0');
}
// ==> Drop Win95 support [MorphXT] - Stulle
/*
// Win98: '\r\n' is not displayed correctly in tooltip
if (afxIsWin95()) {
LPTSTR psz = buffer2;
while (*psz) {
if (*psz == _T('\r') || *psz == _T('\n'))
*psz = _T(' ');
psz++;
}
}
*/
// <== Drop Win95 support [MorphXT] - Stulle
TraySetToolTip(buffer2);
}
//Xman see all sources
if (activewnd == transferwnd && IsWindowVisible()){
transferwnd->GetDownloadList()->ShowFilesCount();
}
//Xman end
if (IsWindowVisible() || bForceAll)
{
//Xman GlobalMaxHarlimit for fairness
// ==> Enforce Ratio [Stulle] - Stulle
/*
if(theApp.downloadqueue->GetLimitState()==1)
strTransferRate.Append(_T(" r"));
else if(theApp.downloadqueue->GetLimitState()>=2)
strTransferRate.Append(_T(" R"));
*/
if(theApp.downloadqueue->GetLimitState()>=DLR_SOURCE)
strTransferRate.Append(_T(" R"));
else if(theApp.downloadqueue->GetLimitState()>=DLR_SESLIM)
strTransferRate.Append(_T(" r"));
// <== Enforce Ratio [Stulle] - Stulle
//Xman end
statusbar->SetText(strTransferRate, SBarUpDown, 0);
ShowTransferStateIcon();
}
// ==> Show sources on title - Stulle
// ==> show overhead on title - Stulle
/*
if (IsWindowVisible() && thePrefs.ShowRatesOnTitle())
{
TCHAR szBuff[128];
// Maella -Support for tag ET_MOD_VERSION 0x55
/*
_sntprintf(szBuff, _countof(szBuff), _T("(U:%.1f D:%.1f) eMule v%s"), (float)m_uUpDatarate/1024, (float)m_uDownDatarate/1024, theApp.m_strCurVersionLong);
*//*
_sntprintf(szBuff, _countof(szBuff), _T("(U:%.1f D:%.1f) eMule v%s"), (float)m_uUpDatarate/1024, (float)m_uDownDatarate/1024, theApp.m_strCurVersionLong + _T(" ") + MOD_VERSION);
//Xman end
szBuff[_countof(szBuff) - 1] = _T('\0');
SetWindowText(szBuff);
}
*/
uint16 m_uGlobalSources = theApp.downloadqueue->GetGlobalSourceCount();
if (IsWindowVisible() && thePrefs.ShowRatesOnTitle() && thePrefs.ShowSrcOnTitle())
{
TCHAR szBuff[128];
if (thePrefs.ShowOverheadOnTitle())
{
_sntprintf(szBuff,_countof(szBuff),_T("(U:%.1f(%.1f) D:%.1f(%.1f)) eMule v%s [%s] --> %s %u"),uploadRate, uploadOverheadRate, downloadRate, downloadOverheadRate, theApp.m_strCurVersionLong,theApp.m_strModLongVersion,GetResString(IDS_SHOWSRCSTRING),m_uGlobalSources);
szBuff[_countof(szBuff) - 1] = _T('\0');
}
else
{
_sntprintf(szBuff,_countof(szBuff),_T("(U:%.1f D:%.1f) eMule v%s [%s] --> %s %u"),uploadRate, downloadRate, theApp.m_strCurVersionLong,theApp.m_strModLongVersion,GetResString(IDS_SHOWSRCSTRING),m_uGlobalSources);
szBuff[_countof(szBuff) - 1] = _T('\0');
}
SetWindowText(szBuff);
}
else if (IsWindowVisible() && thePrefs.ShowRatesOnTitle())
{
TCHAR szBuff[128];
if (thePrefs.ShowOverheadOnTitle())
{
_sntprintf(szBuff,_countof(szBuff),_T("(U:%.1f(%.1f) D:%.1f(%.1f)) eMule v%s [%s]"),uploadRate, uploadOverheadRate, downloadRate, downloadOverheadRate, theApp.m_strCurVersionLong,theApp.m_strModLongVersion);
szBuff[_countof(szBuff) - 1] = _T('\0');
}
else
{
_sntprintf(szBuff,_countof(szBuff),_T("(U:%.1f D:%.1f) eMule v%s [%s]"),uploadRate, downloadRate, theApp.m_strCurVersionLong,theApp.m_strModLongVersion);
szBuff[_countof(szBuff) - 1] = _T('\0');
}
SetWindowText(szBuff);
}
// <== show overhead on title - Stulle
else if (IsWindowVisible() && thePrefs.ShowSrcOnTitle())
{
TCHAR szBuff[128];
_sntprintf(szBuff,_countof(szBuff),_T("eMule v%s [%s] --> %s %u"),theApp.m_strCurVersionLong,theApp.m_strModLongVersion,GetResString(IDS_SHOWSRCSTRING),m_uGlobalSources);
szBuff[_countof(szBuff) - 1] = _T('\0');
SetWindowText(szBuff);
}
// <== Show sources on title - Stulle
if (m_pMiniMule && m_pMiniMule->m_hWnd && m_pMiniMule->IsWindowVisible() && !m_pMiniMule->GetAutoClose())
{
m_pMiniMule->UpdateContent(m_uUpDatarate, m_uDownDatarate);
}
// ==> Show in MSN7 [TPT] - Stulle
//Only update every 10 seconds and if enabled
if(thePrefs.GetShowMSN7())
{
if (m_uMSNup2Date == 0 && ::GetTickCount() - m_dwMSNtime > SEC2MS(10))
{
UpdateMSN(uploadRate, uploadOverheadRate, downloadRate, downloadOverheadRate);
m_uMSNup2Date = 1;
}
else if (m_uMSNup2Date == 1 && ::GetTickCount() - m_dwMSNtime > SEC2MS(20))
{
UpdateMSN1(theApp.pBandWidthControl->GeteMuleIn(), theApp.pBandWidthControl->GeteMuleOut(),m_uGlobalSources);
m_uMSNup2Date = 2;
}
else if (m_uMSNup2Date == 2 && ::GetTickCount() - m_dwMSNtime > SEC2MS(30))
{
CString buffer = _T("");
if(Kademlia::CKademlia::IsConnected())
buffer.AppendFormat(_T("KAD"));
if(Kademlia::CKademlia::IsConnected() && theApp.serverconnect->IsConnected())
buffer.AppendFormat(_T(" + "));
else if (!Kademlia::CKademlia::IsConnected() && !theApp.serverconnect->IsConnected())
buffer.AppendFormat(_T("Not Connected"));
if(theApp.serverconnect->IsConnected())
buffer.AppendFormat(_T("%s"), theApp.serverconnect->GetCurrentServer()->GetListName());
UpdateMSN2(buffer);
m_uMSNup2Date = 0;
m_dwMSNtime = ::GetTickCount();
}
}
// <== Show in MSN7 [TPT] - Stulle
}
void CemuleDlg::ShowPing()
{
//Xman
/*
if (IsWindowVisible())
{
CString buffer;
if (thePrefs.IsDynUpEnabled())
{
CurrentPingStruct lastPing = theApp.lastCommonRouteFinder->GetCurrentPing();
if (lastPing.state.GetLength() == 0)
{
if (lastPing.lowest > 0 && !thePrefs.IsDynUpUseMillisecondPingTolerance())
buffer.Format(_T("%.1f | %ims | %i%%"),lastPing.currentLimit/1024.0f, lastPing.latency, lastPing.latency*100/lastPing.lowest);
else
buffer.Format(_T("%.1f | %ims"),lastPing.currentLimit/1024.0f, lastPing.latency);
}
else
buffer.SetString(lastPing.state);
}
statusbar->SetText(buffer, SBarChatMsg, 0);
}
*/
//Xman end
}
void CemuleDlg::OnOK()
{
}
void CemuleDlg::OnCancel()
{
if (!thePrefs.GetStraightWindowStyles())
MinimizeWindow();
}
void CemuleDlg::MinimizeWindow()
{
if (*thePrefs.GetMinTrayPTR())
{
// ==> Static Tray Icon [MorphXT] - MyTh88
m_bMaximized = IsZoomed();
// <== Static Tray Icon [MorphXT] - MyTh88
TrayShow();
ShowWindow(SW_HIDE);
// ==> Invisible Mode [TPT/MoNKi] - Stulle
if (thePrefs.GetInvisibleMode() && (theApp.DidWeAutoStart() || thePrefs.GetInvisibleModeStart()))
ToggleHide();
// <== Invisible Mode [TPT/MoNKi] - Stulle
}
else
{
ShowWindow(SW_MINIMIZE);
}
ShowTransferRate();
ShowPing();
}
void CemuleDlg::SetActiveDialog(CWnd* dlg)
{
if (dlg == activewnd)
return;
if (activewnd)
activewnd->ShowWindow(SW_HIDE);
dlg->ShowWindow(SW_SHOW);
dlg->SetFocus();
activewnd = dlg;
int iToolbarButtonID = MapWindowToToolbarButton(dlg);
if (iToolbarButtonID != -1)
toolbar->PressMuleButton(iToolbarButtonID);
if (dlg == transferwnd){
if (thePrefs.ShowCatTabInfos())
transferwnd->UpdateCatTabTitles();
}
else if (dlg == chatwnd){
chatwnd->chatselector.ShowChat();
}
else if (dlg == statisticswnd){
statisticswnd->ShowStatistics();
}
}
void CemuleDlg::SetStatusBarPartsSize()
{
CRect rect;
statusbar->GetClientRect(&rect);
int ussShift = 0;
//Xman
//only used for with USS
/*
if(thePrefs.IsDynUpEnabled())
{
if (thePrefs.IsDynUpUseMillisecondPingTolerance())
ussShift = 45;
else
ussShift = 90;
}
*/
//Xman end
//Xman changed
/*
int aiWidths[5] =
{
rect.right - 675 - ussShift,
rect.right - 440 - ussShift,
rect.right - 250 - ussShift,
rect.right - 25 - ussShift,
-1
};
*/
int aiWidths[5] =
{
rect.right - 675 - ussShift,
rect.right - 440 - ussShift,
rect.right - 235 - ussShift,
rect.right - 25 - ussShift,
-1
};
//Xman end
statusbar->SetParts(_countof(aiWidths), aiWidths);
}
void CemuleDlg::OnSize(UINT nType, int cx, int cy)
{
CTrayDialog::OnSize(nType, cx, cy);
SetStatusBarPartsSize();
// we might receive this message during shutdown -> bad
if (transferwnd != NULL && IsRunning())
transferwnd->VerifyCatTabSize();
}
void CemuleDlg::ProcessED2KLink(LPCTSTR pszData)
{
try {
CString link2;
CString link;
link2 = pszData;
link2.Replace(_T("%7c"),_T("|"));
link2.Replace(_T("%7C"),_T("|"));
link = OptUtf8ToStr(URLDecode(link2));
CED2KLink* pLink = CED2KLink::CreateLinkFromUrl(link);
_ASSERT( pLink !=0 );
switch (pLink->GetKind()) {
case CED2KLink::kFile:
{
// ==> Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle
/*
CED2KFileLink* pFileLink = pLink->GetFileLink();
_ASSERT(pFileLink !=0);
//Xman [MoNKi: -Check already downloaded files-]
if(theApp.knownfiles->CheckAlreadyDownloadedFileQuestion(pFileLink->GetHashKey(),pFileLink->GetName()))
{
theApp.downloadqueue->AddFileLinkToDownload(pFileLink,searchwnd->GetSelectedCat());
}
//Xman end
*/
CED2KFileLink* pFileLink = (CED2KFileLink*)CED2KLink::CreateLinkFromUrl(link.Trim());
_ASSERT(pFileLink !=0);
if(theApp.knownfiles->CheckAlreadyDownloadedFileQuestion(pFileLink->GetHashKey(),pFileLink->GetName()))
{
theApp.downloadqueue->AddFileLinkToDownload(pFileLink, -1, true);
}
// <== Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle
}
break;
case CED2KLink::kServerList:
{
CED2KServerListLink* pListLink = pLink->GetServerListLink();
_ASSERT( pListLink !=0 );
CString strAddress = pListLink->GetAddress();
if(strAddress.GetLength() != 0)
serverwnd->UpdateServerMetFromURL(strAddress);
}
break;
case CED2KLink::kNodesList:
{
CED2KNodesListLink* pListLink = pLink->GetNodesListLink();
_ASSERT( pListLink !=0 );
CString strAddress = pListLink->GetAddress();
// Becasue the nodes.dat is vital for kad and its routing and doesn't needs to be updated in general
// we request a confirm to avoid accidental / malicious updating of this file. This is a bit inconsitent
// as the same kinda applies to the server.met, but those require more updates and are easier to understand
CString strConfirm;
strConfirm.Format(GetResString(IDS_CONFIRMNODESDOWNLOAD), strAddress);
if(strAddress.GetLength() != 0 && AfxMessageBox(strConfirm, MB_YESNO | MB_ICONQUESTION, 0) == IDYES)
kademliawnd->UpdateNodesDatFromURL(strAddress);
}
break;
case CED2KLink::kServer:
{
CString defName;
CED2KServerLink* pSrvLink = pLink->GetServerLink();
_ASSERT( pSrvLink !=0 );
CServer* pSrv = new CServer(pSrvLink->GetPort(), pSrvLink->GetAddress());
_ASSERT( pSrv !=0 );
pSrvLink->GetDefaultName(defName);
pSrv->SetListName(defName);
// Barry - Default all new servers to high priority
if (thePrefs.GetManualAddedServersHighPriority())
pSrv->SetPreference(SRV_PR_HIGH);
if (!serverwnd->serverlistctrl.AddServer(pSrv,true))
delete pSrv;
else
AddLogLine(true,GetResString(IDS_SERVERADDED), pSrv->GetListName());
}
break;
case CED2KLink::kSearch:
{
CED2KSearchLink* pListLink = pLink->GetSearchLink();
_ASSERT( pListLink !=0 );
SetActiveDialog(searchwnd);
searchwnd->ProcessEd2kSearchLinkRequest(pListLink->GetSearchTerm());
}
break;
// MORPH START - Added by Commander, Friendlinks [emulEspaa] - added by zz_fly
case CED2KLink::kFriend:
{
// Better with dynamic_cast, but no RTTI enabled in the project
CED2KFriendLink* pFriendLink = static_cast<CED2KFriendLink*>(pLink);
uchar userHash[16];
pFriendLink->GetUserHash(userHash);
if ( ! theApp.friendlist->IsAlreadyFriend(userHash) )
theApp.friendlist->AddFriend(userHash, 0U, 0U, 0U, 0U, pFriendLink->GetUserName(), 1U);
else
{
CString msg;
msg.Format(GetResString(IDS_USER_ALREADY_FRIEND), pFriendLink->GetUserName());
AddLogLine(true, msg);
}
}
break;
case CED2KLink::kFriendList:
{
// Better with dynamic_cast, but no RTTI enabled in the project
CED2KFriendListLink* pFrndLstLink = static_cast<CED2KFriendListLink*>(pLink);
CString sAddress = pFrndLstLink->GetAddress();
if ( !sAddress.IsEmpty() )
this->chatwnd->UpdateEmfriendsMetFromURL(sAddress);
}
break;
// MORPH END - Added by Commander, Friendlinks [emulEspaa]
default:
break;
}
delete pLink;
}
catch(CString strError){
LogWarning(LOG_STATUSBAR, GetResString(IDS_LINKNOTADDED) + _T(" - ") + strError);
}
catch(...){
LogWarning(LOG_STATUSBAR, GetResString(IDS_LINKNOTADDED));
}
}
LRESULT CemuleDlg::OnWMData(WPARAM /*wParam*/, LPARAM lParam)
{
PCOPYDATASTRUCT data = (PCOPYDATASTRUCT)lParam;
if (data->dwData == OP_ED2KLINK)
{
if (thePrefs.IsBringToFront())
{
FlashWindow(TRUE);
if (IsIconic())
ShowWindow(SW_SHOWNORMAL);
// ==> Static Tray Icon [MorphXT] - MyTh88
/*
else if (TrayHide())
*/
else if (thePrefs.GetStaticIcon() || TrayHide())
// <== Static Tray Icon [MorphXT] - MyTh88
RestoreWindow();
else
SetForegroundWindow();
}
ProcessED2KLink((LPCTSTR)data->lpData);
}
else if(data->dwData == OP_COLLECTION){
FlashWindow(TRUE);
if (IsIconic())
ShowWindow(SW_SHOWNORMAL);
// ==> Static Tray Icon [MorphXT] - MyTh88
/*
else if (TrayHide())
*/
else if (thePrefs.GetStaticIcon() || TrayHide())
// <== Static Tray Icon [MorphXT] - MyTh88
RestoreWindow();
else
SetForegroundWindow();
CCollection* pCollection = new CCollection();
CString strPath = CString((LPCTSTR)data->lpData);
if (pCollection->InitCollectionFromFile(strPath, strPath.Right((strPath.GetLength()-1)-strPath.ReverseFind('\\')))){
CCollectionViewDialog dialog;
dialog.SetCollection(pCollection);
dialog.DoModal();
}
delete pCollection;
}
else if (data->dwData == OP_CLCOMMAND){
// command line command received
CString clcommand((LPCTSTR)data->lpData);
clcommand.MakeLower();
AddLogLine(true,_T("CLI: %s"),clcommand);
if (clcommand==_T("connect")) {StartConnection(); return true;}
if (clcommand==_T("disconnect")) {theApp.serverconnect->Disconnect(); return true;}
if (clcommand==_T("resume")) {theApp.downloadqueue->StartNextFile(); return true;}
if (clcommand==_T("exit"))
{
theApp.m_app_state = APP_STATE_SHUTTINGDOWN; // do no ask to close
OnClose();
return true;
}
if (clcommand==_T("restore")) {RestoreWindow();return true;}
if (clcommand==_T("reloadipf")) {theApp.ipfilter->LoadFromDefaultFile(); return true;}
if (clcommand.Left(7).MakeLower()==_T("limits=") && clcommand.GetLength()>8) {
CString down;
CString up=clcommand.Mid(7);
int pos=up.Find(_T(','));
if (pos>0) {
down=up.Mid(pos+1);
up=up.Left(pos);
}
//Xman
// Maella [FAF] -Allow Bandwidth Settings in <1KB Incremements-
/*
if (down.GetLength()>0) thePrefs.SetMaxDownload(_tstoi(down));
if (up.GetLength()>0) thePrefs.SetMaxUpload(_tstoi(up));
*/
if (down.GetLength()>0) thePrefs.SetMaxDownload((float)_tstof(down));
if (up.GetLength()>0) thePrefs.SetMaxUpload((float)_tstof(up));
//Xman Xtreme Upload:
thePrefs.CheckSlotSpeed();
//Xman end
theApp.scheduler->SaveOriginals(); // Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle
return true;
}
if (clcommand==_T("help") || clcommand==_T("/?")) {
// show usage
return true;
}
if (clcommand==_T("status")) {
CString strBuff;
strBuff.Format(_T("%sstatus.log"), thePrefs.GetMuleDirectory(EMULE_CONFIGBASEDIR));
FILE* file = _tfsopen(strBuff, _T("wt"), _SH_DENYWR);
if (file){
if (theApp.serverconnect->IsConnected())
strBuff = GetResString(IDS_CONNECTED);
else if (theApp.serverconnect->IsConnecting())
strBuff = GetResString(IDS_CONNECTING);
else
strBuff = GetResString(IDS_DISCONNECTED);
_ftprintf(file, _T("%s\n"), strBuff);
// Xman
// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
/*
strBuff.Format(GetResString(IDS_UPDOWNSMALL), (float)theApp.uploadqueue->GetDatarate()/1024, (float)theApp.downloadqueue->GetDatarate()/1024);
*/
uint32 eMuleIn;
uint32 eMuleOut;
uint32 notUsed;
theApp.pBandWidthControl->GetDatarates(thePrefs.GetDatarateSamples(),
eMuleIn, notUsed,
eMuleOut, notUsed,
notUsed, notUsed);
strBuff.Format(GetResString(IDS_UPDOWNSMALL), (float)eMuleOut/1024, (float)eMuleIn/1024);
// Maella end
_ftprintf(file, _T("%s"), strBuff); // next string (getTextList) is already prefixed with '\n'!
_ftprintf(file, _T("%s\n"), transferwnd->GetDownloadList()->getTextList());
fclose(file);
}
return true;
}
// show "unknown command";
}
return true;
}
LRESULT CemuleDlg::OnFileHashed(WPARAM wParam, LPARAM lParam)
{
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
CKnownFile* result = (CKnownFile*)lParam;
ASSERT( result->IsKindOf(RUNTIME_CLASS(CKnownFile)) );
if (wParam)
{
// File hashing finished for a part file when:
// - part file just completed
// - part file was rehashed at startup because the file date of part.met did not match the part file date
CPartFile* requester = (CPartFile*)wParam;
ASSERT( requester->IsKindOf(RUNTIME_CLASS(CPartFile)) );
// SLUGFILLER: SafeHash - could have been canceled
if (theApp.downloadqueue->IsPartFile(requester))
requester->PartFileHashFinished(result);
else
delete result;
// SLUGFILLER: SafeHash
}
else
{
ASSERT( !result->IsKindOf(RUNTIME_CLASS(CPartFile)) );
// File hashing finished for a shared file (none partfile)
// - reading shared directories at startup and hashing files which were not found in known.met
// - reading shared directories during runtime (user hit Reload button, added a shared directory, ...)
theApp.sharedfiles->FileHashingFinished(result);
}
return TRUE;
}
LRESULT CemuleDlg::OnFileOpProgress(WPARAM wParam, LPARAM lParam)
{
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
CKnownFile* pKnownFile = (CKnownFile*)lParam;
ASSERT( pKnownFile->IsKindOf(RUNTIME_CLASS(CKnownFile)) );
if (pKnownFile->IsKindOf(RUNTIME_CLASS(CPartFile)))
{
CPartFile* pPartFile = static_cast<CPartFile*>(pKnownFile);
pPartFile->SetFileOpProgress(wParam);
pPartFile->UpdateDisplayedInfo(true);
}
return 0;
}
LRESULT CemuleDlg::OnFileAllocExc(WPARAM wParam,LPARAM lParam)
{
//Xman
//MORPH START - Added by SiRoB, Fix crash at shutdown
CFileException* error = (CFileException*)lParam;
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN || !theApp.downloadqueue->IsPartFile((CPartFile*)wParam)) { //MORPH - Changed by SiRoB, Flush Thread
if (error != NULL)
error->Delete();
//MORPH START - Added by SiRoB, Flush Thread
if (theApp.downloadqueue->IsPartFile((CPartFile*)wParam)) {
delete[] ((CPartFile*)wParam)->m_FlushSetting->changedPart;
delete ((CPartFile*)wParam)->m_FlushSetting;
((CPartFile*)wParam)->m_FlushSetting = NULL;
}
//MORPH END - Added by SiRoB, Flush Thread
return FALSE;
}
//MORPH END - Added by SiRoB, Fix crash at shutdown
if (lParam == 0)
((CPartFile*)wParam)->FlushBuffersExceptionHandler();
else
((CPartFile*)wParam)->FlushBuffersExceptionHandler(error);
return 0;
}
LRESULT CemuleDlg::OnFileCompleted(WPARAM wParam, LPARAM lParam)
{
//MORPH START - Added by SiRoB, Fix crash at shutdown
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
//MORPH END - Added by SiRoB, Fix crash at shutdown
CPartFile* partfile = (CPartFile*)lParam;
ASSERT( partfile != NULL );
if (partfile)
partfile->PerformFileCompleteEnd(wParam);
return 0;
}
#ifdef _DEBUG
void BeBusy(UINT uSeconds, LPCSTR pszCaller)
{
UINT s = 0;
while (uSeconds--) {
theVerboseLog.Logf(_T("%hs: called=%hs, waited %u sec."), __FUNCTION__, pszCaller, s++);
Sleep(1000);
}
}
#endif
BOOL CemuleDlg::OnQueryEndSession()
{
AddDebugLogLine(DLP_VERYLOW, _T("%hs"), __FUNCTION__);
if (!CTrayDialog::OnQueryEndSession())
return FALSE;
AddDebugLogLine(DLP_VERYLOW, _T("%hs: returning TRUE"), __FUNCTION__);
return TRUE;
}
void CemuleDlg::OnEndSession(BOOL bEnding)
{
AddDebugLogLine(DLP_VERYLOW, _T("%hs: bEnding=%d"), __FUNCTION__, bEnding);
if (bEnding && theApp.m_app_state == APP_STATE_RUNNING)
{
// If eMule was *not* started with "RUNAS":
// When user is logging of (or reboots or shutdown system), Windows sends the
// WM_QUERYENDSESSION/WM_ENDSESSION to all top level windows.
// Here we can consume as much time as we need to perform our shutdown. Even if we
// take longer than 20 seconds, Windows will just show a dialog box that 'emule'
// is not terminating in time and gives the user a chance to cancel that. If the user
// does not cancel the Windows dialog, Windows will though wait until eMule has
// terminated by itself - no data loss, no file corruption, everything is fine.
theApp.m_app_state = APP_STATE_SHUTTINGDOWN;
OnClose();
}
CTrayDialog::OnEndSession(bEnding);
AddDebugLogLine(DLP_VERYLOW, _T("%hs: returning"), __FUNCTION__);
}
LRESULT CemuleDlg::OnUserChanged(WPARAM /*wParam*/, LPARAM /*lParam*/)
{
AddDebugLogLine(DLP_VERYLOW, _T("%hs"), __FUNCTION__);
// Just want to know if we ever get this message. Maybe it helps us to handle the
// logoff/reboot/shutdown problem when eMule was started with "RUNAS".
return Default();
}
LRESULT CemuleDlg::OnConsoleThreadEvent(WPARAM wParam, LPARAM lParam)
{
AddDebugLogLine(DLP_VERYLOW, _T("%hs: nEvent=%u, nThreadID=%u"), __FUNCTION__, wParam, lParam);
// If eMule was started with "RUNAS":
// This message handler receives a 'console event' from the concurrently and thus
// asynchronously running console control handler thread which was spawned by Windows
// in case the user logs off/reboots/shutdown. Even if the console control handler thread
// is waiting on the result from this message handler (is waiting until the main thread
// has finished processing this inter-application message), the application will get
// forcefully terminated by Windows after 20 seconds! There is no known way to prevent
// that. This means, that if we would invoke our standard shutdown code ('OnClose') here
// and the shutdown takes longer than 20 sec, we will get forcefully terminated by
// Windows, regardless of what we are doing. This means, MET-file and PART-file corruption
// may occure. Because the shutdown code in 'OnClose' does also shutdown Kad (which takes
// a noticeable amount of time) it is not that unlikely that we run into problems with
// not being finished with our shutdown in 20 seconds.
//
if (theApp.m_app_state == APP_STATE_RUNNING)
{
#if 1
// And it really should be OK to expect that emule can shutdown in 20 sec on almost
// all computers. So, use the proper shutdown.
theApp.m_app_state = APP_STATE_SHUTTINGDOWN;
OnClose(); // do not invoke if shutdown takes longer than 20 sec, read above
#else
// As a minimum action we at least set the 'shutting down' flag, this will help e.g.
// the CUploadQueue::UploadTimer to not start any file save actions which could get
// interrupted by windows and which would then lead to corrupted MET-files.
// Setting this flag also helps any possible running threads to stop their work.
theApp.m_app_state = APP_STATE_SHUTTINGDOWN;
#ifdef _DEBUG
// Simulate some work.
//
// NOTE: If the console thread has already exited, Windows may terminate the process
// even before the 20 sec. timeout!
//BeBusy(70, __FUNCTION__);
#endif
// Actually, just calling 'ExitProcess' should be the most safe thing which we can
// do here. Because we received this message via the main message queue we are
// totally in-sync with the application and therefore we know that we are currently
// not within a file save action and thus we simply can not cause any file corruption
// when we exit right now.
//
// Of course, there may be some data loss. But it's the same amount of data loss which
// could occure if we keep running. But if we keep running and wait until Windows
// terminates us after 20 sec, there is also the chance for file corruption.
if (thePrefs.GetDebug2Disk()) {
theVerboseLog.Logf(_T("%hs: ExitProcess"), __FUNCTION__);
theVerboseLog.Close();
}
ExitProcess(0);
#endif
}
AddDebugLogLine(DLP_VERYLOW, _T("%hs: returning"), __FUNCTION__);
return 1;
}
void CemuleDlg::OnDestroy()
{
AddDebugLogLine(DLP_VERYLOW, _T("%hs"), __FUNCTION__);
// If eMule was started with "RUNAS":
// When user is logging of (or reboots or shutdown system), Windows may or may not send
// a WM_DESTROY (depends on how long the application needed to process the
// CTRL_LOGOFF_EVENT). But, regardless of what happened and regardless of how long any
// application specific shutdown took, Windows fill forcefully terminate the process
// after 1-2 seconds after WM_DESTROY! So, we can not use WM_DESTROY for any lengthy
// shutdown actions in that case.
CTrayDialog::OnDestroy();
}
bool CemuleDlg::CanClose()
{
if (theApp.m_app_state == APP_STATE_RUNNING && thePrefs.IsConfirmExitEnabled())
{
// ==> Extended Prompt on Exit dialog [leuk_he] - Stulle
/*
int nResult = XMessageBox(GetSafeHwnd(), GetResString(IDS_MAIN_EXIT), GetResString(IDS_CLOSEEMULE), MB_YESNO | MB_DEFBUTTON2 | MB_DONOTASKAGAIN | MB_ICONQUESTION);
if ((nResult & MB_DONOTASKAGAIN) > 0)
thePrefs.SetConfirmExit(false);
if ((nResult & 0xFF) == IDNO)
*/
CAskExitDlg ExitDlg;
if (ExitDlg.DoModal()!= IDYES)
// <== Extended Prompt on Exit dialog [leuk_he] - Stulle
return false;
}
return true;
}
void CemuleDlg::OnClose()
{
if(theApp.IsSplash()) theApp.DestroySplash(); //Xman new slpash-screen arrangement
if (!CanClose())
return;
//Xman new slpash-screen arrangement
if (thePrefs.UseSplashScreen())
{
//Xman don't show splash on old windows->crash
switch (thePrefs.GetWindowsVersion())
{
case _WINVER_98_:
case _WINVER_95_:
case _WINVER_ME_:
break;
default:
theApp.ShowSplash(false);
}
}
theApp.UpdateSplash(_T("Shutting down ..."));
//Xman end
Log(_T("Closing eMule"));
CloseTTS();
m_pDropTarget->Revoke();
//zz_fly :: known2 buffer
//write all buffer in to file
//if lock fail, there must be another thread saving the hashset, not needed to save it again
CSingleLock lockSaveHashSet(&CAICHRecoveryHashSet::m_mutSaveHashSet, false);
if (lockSaveHashSet.Lock(3000)){
CAICHRecoveryHashSet::SaveHashSetToFile(true);
lockSaveHashSet.Unlock();
}
//zz_fly :: end
// ==> Show in MSN7 [TPT] - Stulle
//if we have enabled on close, we must send the kill message
if(thePrefs.GetShowMSN7())
UpdateMSN(0,0,0,0, true);
// <== Show in MSN7 [TPT] - Stulle
theApp.EndDirectoryWatcher(); // Automatic shared files updater [MoNKi] - Stulle
theApp.m_app_state = APP_STATE_SHUTTINGDOWN;
//Xman queued disc-access for read/flushing-threads
//theApp.ForeAllDiscAccessThreadsToFinish();
theApp.serverconnect->Disconnect();
theApp.OnlineSig(); // Added By Bouc7
// get main window placement
WINDOWPLACEMENT wp;
wp.length = sizeof(wp);
GetWindowPlacement(&wp);
ASSERT( wp.showCmd == SW_SHOWMAXIMIZED || wp.showCmd == SW_SHOWMINIMIZED || wp.showCmd == SW_SHOWNORMAL );
if (wp.showCmd == SW_SHOWMINIMIZED && (wp.flags & WPF_RESTORETOMAXIMIZED))
wp.showCmd = SW_SHOWMAXIMIZED;
wp.flags = 0;
thePrefs.SetWindowLayout(wp);
// get active main window dialog
if (activewnd){
if (activewnd->IsKindOf(RUNTIME_CLASS(CServerWnd)))
thePrefs.SetLastMainWndDlgID(IDD_SERVER);
else if (activewnd->IsKindOf(RUNTIME_CLASS(CSharedFilesWnd)))
thePrefs.SetLastMainWndDlgID(IDD_FILES);
else if (activewnd->IsKindOf(RUNTIME_CLASS(CSearchDlg)))
thePrefs.SetLastMainWndDlgID(IDD_SEARCH);
else if (activewnd->IsKindOf(RUNTIME_CLASS(CChatWnd)))
thePrefs.SetLastMainWndDlgID(IDD_CHAT);
else if (activewnd->IsKindOf(RUNTIME_CLASS(CTransferDlg)))
thePrefs.SetLastMainWndDlgID(IDD_TRANSFER);
else if (activewnd->IsKindOf(RUNTIME_CLASS(CStatisticsDlg)))
thePrefs.SetLastMainWndDlgID(IDD_STATISTICS);
else if (activewnd->IsKindOf(RUNTIME_CLASS(CKademliaWnd)))
thePrefs.SetLastMainWndDlgID(IDD_KADEMLIAWND);
else if (activewnd->IsKindOf(RUNTIME_CLASS(CIrcWnd)))
thePrefs.SetLastMainWndDlgID(IDD_IRC);
else{
ASSERT(0);
thePrefs.SetLastMainWndDlgID(0);
}
}
Kademlia::CKademlia::Stop(); // couple of data files are written
theApp.UpdateSplash(_T("waiting for hash end")); //Xman new slpash-screen arrangement
// try to wait untill the hashing thread notices that we are shutting down
CSingleLock sLock1(&theApp.hashing_mut); // only one filehash at a time
sLock1.Lock(2000);
//Xman queued disc-access for read/flushing-threads
//if we don't unlock we can cause a deadlock here:
//resuming the disc-access-thread with th above ForeAllDiscAccessThreadsToFinish
//doesn't mean the thread start at once... they start later and the main app has the mutex
//so the threads wait for ever.. and also the main app for the threads.
//sLock1.Unlock();
//Xman end
theApp.UpdateSplash(_T("saving settings ...")); //Xman new slpash-screen arrangement
// ==> TBH: Backup [TBH/EastShare/MorphXT] - Stulle
/*
// saving data & stuff
theApp.emuledlg->preferenceswnd->m_wndSecurity.DeleteDDB();
theApp.knownfiles->Save(); // CKnownFileList::Save
theApp.sharedfiles->Save();
//transferwnd->downloadlistctrl.SaveSettings();
//transferwnd->downloadclientsctrl.SaveSettings();
//transferwnd->uploadlistctrl.SaveSettings();
//transferwnd->queuelistctrl.SaveSettings();
//transferwnd->clientlistctrl.SaveSettings();
//sharedfileswnd->sharedfilesctrl.SaveSettings();
//chatwnd->m_FriendListCtrl.SaveSettings();
searchwnd->SaveAllSettings();
serverwnd->SaveAllSettings();
kademliawnd->SaveAllSettings();
//sharedfileswnd->historylistctrl.SaveSettings(CPreferences::tableHistory); //Xman [MoNKi: -Downloaded History-]
//Xman new adapter selection
if(theApp.pBandWidthControl->GetwasNAFCLastActive()==true)
thePrefs.SetNAFCFullControl(true);
//Xman end
theApp.m_pPeerCache->Save();
theApp.scheduler->RestoreOriginals();
theApp.searchlist->SaveSpamFilter();
if (thePrefs.IsStoringSearchesEnabled())
theApp.searchlist->StoreSearches();
// close uPnP Ports
#ifdef DUAL_UPNP //zz_fly :: dual upnp
if(!thePrefs.m_bUseACATUPnPCurrent)
#endif //zz_fly :: dual upnp
{
theApp.m_pUPnPFinder->GetImplementation()->StopAsyncFind();
if (thePrefs.CloseUPnPOnExit())
theApp.m_pUPnPFinder->GetImplementation()->DeletePorts();
}
//Xman don't overwrite bak files if last sessions crashed
//remark: it would be better to set the flag after all deletions, but this isn't possible, because the prefs need access to the objects when saving
thePrefs.m_this_session_aborted_in_an_unnormal_way=false;
//Xman end
thePrefs.Save();
thePerfLog.Shutdown();
*/
SaveSettings(true);
if (thePrefs.GetAutoBackup2())
theApp.emuledlg->preferenceswnd->m_wndScar.Backup3();
if (thePrefs.GetAutoBackup())
{
theApp.emuledlg->preferenceswnd->m_wndScar.Backup(_T("*.ini"), false);
theApp.emuledlg->preferenceswnd->m_wndScar.Backup(_T("*.dat"), false);
theApp.emuledlg->preferenceswnd->m_wndScar.Backup(_T("*.met"), false);
}
// <== TBH: Backup [TBH/EastShare/MorphXT] - Stulle
// ==> Invisible Mode [TPT/MoNKi] - Stulle
if(thePrefs.GetInvisibleMode())
UnRegisterInvisibleHotKey();
// <== Invisible Mode [TPT/MoNKi] - Stulle
theApp.UpdateSplash(_T("clearing displayed items ...")); //Xman new slpash-screen arrangement
// explicitly delete all listview items which may hold ptrs to objects which will get deleted
// by the dtors (some lines below) to avoid potential problems during application shutdown.
transferwnd->GetDownloadList()->DeleteAllItems();
chatwnd->chatselector.DeleteAllItems();
chatwnd->m_FriendListCtrl.DeleteAllItems();
theApp.clientlist->DeleteAll();
searchwnd->DeleteAllSearchListCtrlItems();
sharedfileswnd->sharedfilesctrl.DeleteAllItems();
transferwnd->GetQueueList()->DeleteAllItems();
transferwnd->GetClientList()->DeleteAllItems();
transferwnd->GetUploadList()->DeleteAllItems();
transferwnd->GetDownloadClientsList()->DeleteAllItems();
serverwnd->serverlistctrl.DeleteAllItems();
sharedfileswnd->historylistctrl.DeleteAllItems(); //Xman [MoNKi: -Downloaded History-]
CPartFileConvert::CloseGUI();
CPartFileConvert::RemoveAllJobs();
// ==> UPnP support [MoNKi] - leuk_he
AfxBeginThread(theApp.m_UPnP_IGDControlPoint->RemoveInstance,NULL); // seperate thread since devic may have hickups...
// <== UPnP support [MoNKi] - leuk_he
theApp.uploadBandwidthThrottler->EndThread();
//Xman
/*
theApp.lastCommonRouteFinder->EndThread();
*/
//Xman end
theApp.sharedfiles->DeletePartFileInstances();
searchwnd->SendMessage(WM_CLOSE);
transferwnd->SendMessage(WM_CLOSE);
theApp.UpdateSplash(_T("clearing lists ...")); //Xman new slpash-screen arrangement
//Xman
theApp.m_threadlock.WriteLock(); // SLUGFILLER: SafeHash - Last chance, let all running threads close before we start deleting
// NOTE: Do not move those dtors into 'CemuleApp::InitInstance' (althought they should be there). The
// dtors are indirectly calling functions which access several windows which would not be available
// after we have closed the main window -> crash!
delete theApp.mmserver; theApp.mmserver = NULL;
delete theApp.listensocket; theApp.listensocket = NULL;
delete theApp.clientudp; theApp.clientudp = NULL;
delete theApp.sharedfiles; theApp.sharedfiles = NULL;
delete theApp.serverconnect; theApp.serverconnect = NULL;
delete theApp.serverlist; theApp.serverlist = NULL; // CServerList::SaveServermetToFile
delete theApp.knownfiles; theApp.knownfiles = NULL;
delete theApp.searchlist; theApp.searchlist = NULL;
theApp.UpdateSplash(_T("saving credits ...")); //Xman new slpash-screen arrangement
delete theApp.clientcredits; theApp.clientcredits = NULL; // CClientCreditsList::SaveList
theApp.UpdateSplash(_T("clearing queues ...")); //Xman new slpash-screen arrangement
delete theApp.downloadqueue; theApp.downloadqueue = NULL; // N * (CPartFile::FlushBuffer + CPartFile::SavePartFile)
delete theApp.uploadqueue; theApp.uploadqueue = NULL;
delete theApp.clientlist; theApp.clientlist = NULL;
delete theApp.friendlist; theApp.friendlist = NULL; // CFriendList::SaveList
delete theApp.scheduler; theApp.scheduler = NULL;
theApp.UpdateSplash(_T("Unloading IPfilter ...")); //Xman new slpash-screen arrangement
delete theApp.ipfilter; theApp.ipfilter = NULL; // CIPFilter::SaveToDefaultFile
delete theApp.webserver; theApp.webserver = NULL;
delete theApp.m_pPeerCache; theApp.m_pPeerCache = NULL;
delete theApp.m_pFirewallOpener;theApp.m_pFirewallOpener = NULL;
theApp.UpdateSplash(_T("shutdown bandwidthcontrol ...")); //Xman new slpash-screen arrangement
delete theApp.uploadBandwidthThrottler; theApp.uploadBandwidthThrottler = NULL;
//Xman
/*
delete theApp.lastCommonRouteFinder; theApp.lastCommonRouteFinder = NULL;
*/
//Xman End
// ==> UPnP support [MoNKi] - leuk_he
/*
#ifdef DUAL_UPNP //zz_fly :: dual upnp
//UPnP chooser
if(thePrefs.m_bUseACATUPnPCurrent){
theApp.m_pUPnPNat->clearNATPortMapping(); //ACAT UPnP
delete theApp.m_pUPnPNat; theApp.m_pUPnPNat = NULL;
}
else
#endif //zz_fly :: dual upnp
delete theApp.m_pUPnPFinder; theApp.m_pUPnPFinder = NULL;
*/
// <== UPnP support [MoNKi] - leuk_he
//Xman
// Maella [patch] -Bandwidth: overall bandwidth measure-
delete theApp.pBandWidthControl;theApp.pBandWidthControl = NULL;
// Maella end
theApp.UpdateSplash(_T("unload IP to Country ...")); //Xman new slpash-screen arrangement
//EastShare Start - added by AndCycle, IP to Country
delete theApp.ip2country; theApp.ip2country = NULL;
//EastShare End - added by AndCycle, IP to Country
delete theApp.dlp; theApp.dlp=NULL; //Xman DLP
// ==> TBH: minimule - Max
theApp.UpdateSplash(_T("destroy TBH: MiniMule ..."));
theApp.minimule->DestroyWindow();
delete theApp.minimule; theApp.minimule = NULL;
// <== TBH: minimule - Max
// ==> CPU/MEM usage [$ick$/Stulle] - Max
theApp.UpdateSplash(_T("destroy SysInfo ..."));
delete theApp.sysinfo; theApp.sysinfo = NULL;
// <== CPU/MEM usage [$ick$/Stulle] - Max
theApp.UpdateSplash(_T("Shutdown done")); //Xman new slpash-screen arrangement
thePrefs.Uninit();
theApp.m_app_state = APP_STATE_DONE;
CTrayDialog::OnCancel();
AddDebugLogLine(DLP_VERYLOW, _T("Closed eMule"));
// ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle
if (RunningAsService())
ServiceStop();
// <== Run eMule as NT Service [leuk_he/Stulle] - Stulle
}
void CemuleDlg::DestroyMiniMule()
{
if (m_pMiniMule)
{
if (!m_pMiniMule->IsInCallback()) // for safety
{
TRACE("%s - m_pMiniMule->DestroyWindow();\n", __FUNCTION__);
m_pMiniMule->DestroyWindow();
ASSERT( m_pMiniMule == NULL );
m_pMiniMule = NULL;
}
else
ASSERT(0);
}
}
LRESULT CemuleDlg::OnCloseMiniMule(WPARAM wParam, LPARAM /*lParam*/)
{
TRACE("%s -> DestroyMiniMule();\n", __FUNCTION__);
DestroyMiniMule();
if (wParam)
RestoreWindow();
return 0;
}
// ==> TBH: minimule (open on tray) - Max
void CemuleDlg::RunMiniMule()
{
try
{
TRACE("%s - m_pMiniMule = new CMiniMule(this);\n", __FUNCTION__);
ASSERT( m_pMiniMule == NULL );
m_pMiniMule = new CMiniMule(this);
m_pMiniMule->Create(CMiniMule::IDD, this);
//m_pMiniMule->ShowWindow(SW_SHOW); // do not explicitly show the window, it will do that for itself when it's ready..
m_pMiniMule->SetForegroundWindow();
m_pMiniMule->BringWindowToTop();
}
catch(...)
{
ASSERT(0);
m_pMiniMule = NULL;
}
}
// <== TBH: minimule (open on tray) - Max
void CemuleDlg::OnTrayLButtonUp(CPoint /*pt*/)
{
if(!IsRunning())
return;
// Avoid reentrancy problems with main window, options dialog and mini mule window
if (IsPreferencesDlgOpen()) {
MessageBeep(MB_OK);
preferenceswnd->SetForegroundWindow();
preferenceswnd->BringWindowToTop();
return;
}
if (m_pMiniMule) {
TRACE("%s - m_pMiniMule->ShowWindow(SW_SHOW);\n", __FUNCTION__);
m_pMiniMule->ShowWindow(SW_SHOW);
m_pMiniMule->SetForegroundWindow();
m_pMiniMule->BringWindowToTop();
return;
}
// ==> TBH: minimule - Max
/*
if (thePrefs.GetEnableMiniMule())
{
try
{
TRACE("%s - m_pMiniMule = new CMiniMule(this);\n", __FUNCTION__);
ASSERT( m_pMiniMule == NULL );
m_pMiniMule = new CMiniMule(this);
m_pMiniMule->Create(CMiniMule::IDD, this);
//m_pMiniMule->ShowWindow(SW_SHOW); // do not explicitly show the window, it will do that for itself when it's ready..
m_pMiniMule->SetForegroundWindow();
m_pMiniMule->BringWindowToTop();
}
catch(...)
{
ASSERT(0);
m_pMiniMule = NULL;
}
}
*/
if (thePrefs.GetEnableMiniMule() && !thePrefs.IsMiniMuleEnabled())
RunMiniMule(); // TBH: minimule (open on tray) - Stulle
else if (thePrefs.IsMiniMuleEnabled())
{
if (thePrefs.GetMiniMuleLives())
theApp.minimule->RunMiniMule();
else
theApp.minimule->RunMiniMule(true);
theApp.minimule->ShowWindow(SW_SHOW);
}
// <== TBH: minimule - Max
}
void CemuleDlg::OnTrayRButtonUp(CPoint pt)
{
if (!IsRunning())
return;
// Avoid reentrancy problems with main window, options dialog and mini mule window
if (IsPreferencesDlgOpen()) {
MessageBeep(MB_OK);
preferenceswnd->SetForegroundWindow();
preferenceswnd->BringWindowToTop();
return;
}
if (m_pMiniMule)
{
if (m_pMiniMule->GetAutoClose())
{
TRACE("%s - m_pMiniMule->GetAutoClose() -> DestroyMiniMule();\n", __FUNCTION__);
DestroyMiniMule();
}
else
{
// Avoid reentrancy problems with main window, options dialog and mini mule window
if (m_pMiniMule->m_hWnd && !m_pMiniMule->IsWindowEnabled()) {
MessageBeep(MB_OK);
return;
}
}
}
if (m_pSystrayDlg) {
m_pSystrayDlg->BringWindowToTop();
return;
}
m_pSystrayDlg = new CMuleSystrayDlg(this, pt,
//Xman
// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
/*
thePrefs.GetMaxGraphUploadRate(true), thePrefs.GetMaxGraphDownloadRate(),
thePrefs.GetMaxUpload(), thePrefs.GetMaxDownload());
*/
thePrefs.GetMaxGraphUploadRate(), thePrefs.GetMaxGraphDownloadRate(),
thePrefs.GetMaxUpload(), thePrefs.GetMaxDownload());
//Xman end
if (m_pSystrayDlg)
{
// ==> Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle
float fMaxUploadOld = thePrefs.GetMaxUpload();
float fMaxDownloadOld = thePrefs.GetMaxDownload();
// <== Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle
UINT nResult = m_pSystrayDlg->DoModal();
delete m_pSystrayDlg;
m_pSystrayDlg = NULL;
switch (nResult)
{
case IDC_TOMAX:
QuickSpeedOther(MP_QS_UA);
break;
case IDC_TOMIN:
QuickSpeedOther(MP_QS_PA);
break;
case IDC_RESTORE:
RestoreWindow();
break;
case IDC_CONNECT:
StartConnection();
break;
case IDC_DISCONNECT:
CloseConnection();
break;
case IDC_EXIT:
OnClose();
break;
case IDC_PREFERENCES:
ShowPreferences();
break;
}
// ==> Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle
if (nResult != IDC_PREFERENCES &&
(fMaxUploadOld != thePrefs.GetMaxUpload() || fMaxDownloadOld != thePrefs.GetMaxDownload()))
theApp.scheduler->SaveOriginals();
// <== Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle
}
}
void CemuleDlg::AddSpeedSelectorMenus(CMenu* addToMenu)
{
CString text;
// Create UploadPopup Menu
ASSERT( m_menuUploadCtrl.m_hMenu == NULL );
if (m_menuUploadCtrl.CreateMenu())
{
//Xman modified
/*
text.Format(_T("20%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphUploadRate(true)*0.2),GetResString(IDS_KBYTESPERSEC)); m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_U20, text);
text.Format(_T("40%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphUploadRate(true)*0.4),GetResString(IDS_KBYTESPERSEC)); m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_U40, text);
text.Format(_T("60%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphUploadRate(true)*0.6),GetResString(IDS_KBYTESPERSEC)); m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_U60, text);
text.Format(_T("80%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphUploadRate(true)*0.8),GetResString(IDS_KBYTESPERSEC)); m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_U80, text);
text.Format(_T("100%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphUploadRate(true)),GetResString(IDS_KBYTESPERSEC)); m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_U100, text);
*/
text.Format(_T("20%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphUploadRate()*0.2),GetResString(IDS_KBYTESPERSEC)); m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_U20, text);
text.Format(_T("40%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphUploadRate()*0.4),GetResString(IDS_KBYTESPERSEC)); m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_U40, text);
text.Format(_T("60%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphUploadRate()*0.6),GetResString(IDS_KBYTESPERSEC)); m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_U60, text);
text.Format(_T("80%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphUploadRate()*0.8),GetResString(IDS_KBYTESPERSEC)); m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_U80, text);
text.Format(_T("90%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphUploadRate()*0.9),GetResString(IDS_KBYTESPERSEC)); m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_U90, text);
//Xman end
m_menuUploadCtrl.AppendMenu(MF_SEPARATOR);
if (GetRecMaxUpload() > 0) {
//Xman modified
/*
text.Format(GetResString(IDS_PW_MINREC) + GetResString(IDS_KBYTESPERSEC), GetRecMaxUpload());
*/
text.Format(GetResString(IDS_PW_MINREC) + GetResString(IDS_KBYTESPERSEC), (uint16)GetRecMaxUpload());
//Xman end
m_menuUploadCtrl.AppendMenu(MF_STRING, MP_QS_UP10, text);
}
text.Format(_T("%s:"), GetResString(IDS_PW_UPL));
addToMenu->AppendMenu(MF_STRING|MF_POPUP, (UINT_PTR)m_menuUploadCtrl.m_hMenu, text);
}
// Create DownloadPopup Menu
ASSERT( m_menuDownloadCtrl.m_hMenu == NULL );
if (m_menuDownloadCtrl.CreateMenu())
{
text.Format(_T("20%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphDownloadRate()*0.2),GetResString(IDS_KBYTESPERSEC)); m_menuDownloadCtrl.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D20, text);
text.Format(_T("40%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphDownloadRate()*0.4),GetResString(IDS_KBYTESPERSEC)); m_menuDownloadCtrl.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D40, text);
text.Format(_T("60%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphDownloadRate()*0.6),GetResString(IDS_KBYTESPERSEC)); m_menuDownloadCtrl.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D60, text);
text.Format(_T("80%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphDownloadRate()*0.8),GetResString(IDS_KBYTESPERSEC)); m_menuDownloadCtrl.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D80, text);
text.Format(_T("100%%\t%i %s"), (uint16)(thePrefs.GetMaxGraphDownloadRate()),GetResString(IDS_KBYTESPERSEC)); m_menuDownloadCtrl.AppendMenu(MF_STRING|MF_POPUP, MP_QS_D100, text);
text.Format(_T("%s:"), GetResString(IDS_PW_DOWNL));
addToMenu->AppendMenu(MF_STRING|MF_POPUP, (UINT_PTR)m_menuDownloadCtrl.m_hMenu, text);
}
addToMenu->AppendMenu(MF_SEPARATOR);
addToMenu->AppendMenu(MF_STRING, MP_CONNECT, GetResString(IDS_MAIN_BTN_CONNECT));
addToMenu->AppendMenu(MF_STRING, MP_DISCONNECT, GetResString(IDS_MAIN_BTN_DISCONNECT));
}
void CemuleDlg::StartConnection()
{
if ( (!theApp.serverconnect->IsConnecting() && !theApp.serverconnect->IsConnected())
|| !Kademlia::CKademlia::IsRunning())
{
// ==> UPnP support [MoNKi] - leuk_he
/*
#ifdef DUAL_UPNP //zz_fly :: dual upnp
//UPnP chooser
if (!thePrefs.m_bUseACATUPnPCurrent){
#endif //zz_fly :: dual upnp
// UPnP is still trying to open the ports. In order to not get a LowID by connecting to the servers / kad before
// the ports are opened we delay the connection untill UPnP gets a result or the timeout is reached
// If the user clicks two times on the button, let him have his will and connect regardless
if (m_hUPnPTimeOutTimer != 0 && !m_bConnectRequestDelayedForUPnP){
AddLogLine(false, GetResString(IDS_DELAYEDBYUPNP));
AddLogLine(true, GetResString(IDS_DELAYEDBYUPNP2));
m_bConnectRequestDelayedForUPnP = true;
return;
}
else{
m_bConnectRequestDelayedForUPnP = false;
if (m_hUPnPTimeOutTimer != 0){
VERIFY( ::KillTimer(NULL, m_hUPnPTimeOutTimer) );
m_hUPnPTimeOutTimer = 0;
}
*/
// <== UPnP support [MoNKi] - leuk_he
AddLogLine(true, GetResString(IDS_CONNECTING));
// ed2k
if ((thePrefs.GetNetworkED2K() || m_bEd2kSuspendDisconnect) && !theApp.serverconnect->IsConnecting() && !theApp.serverconnect->IsConnected()) {
theApp.serverconnect->ConnectToAnyServer();
}
// kad
if ((thePrefs.GetNetworkKademlia() || m_bKadSuspendDisconnect) && !Kademlia::CKademlia::IsRunning()) {
Kademlia::CKademlia::Start();
}
// ==> UPnP support [MoNKi] - leuk_he
/*
}
#ifdef DUAL_UPNP //zz_fly :: dual upnp
//UPnP chooser
}
else{
AddLogLine(true, GetResString(IDS_CONNECTING));
// ed2k
if ((thePrefs.GetNetworkED2K() || m_bEd2kSuspendDisconnect) && !theApp.serverconnect->IsConnecting() && !theApp.serverconnect->IsConnected()) {
theApp.serverconnect->ConnectToAnyServer();
}
// kad
if ((thePrefs.GetNetworkKademlia() || m_bKadSuspendDisconnect) && !Kademlia::CKademlia::IsRunning()) {
Kademlia::CKademlia::Start();
}
}
#endif //zz_fly :: dual upnp
*/
// <== UPnP support [MoNKi] - leuk_he
ShowConnectionState();
}
m_bEd2kSuspendDisconnect = false;
m_bKadSuspendDisconnect = false;
}
void CemuleDlg::CloseConnection()
{
if (theApp.serverconnect->IsConnected()){
theApp.serverconnect->Disconnect();
}
if (theApp.serverconnect->IsConnecting()){
theApp.serverconnect->StopConnectionTry();
}
Kademlia::CKademlia::Stop();
theApp.OnlineSig(); // Added By Bouc7
ShowConnectionState();
}
void CemuleDlg::RestoreWindow()
{
if (IsPreferencesDlgOpen()) {
MessageBeep(MB_OK);
preferenceswnd->SetForegroundWindow();
preferenceswnd->BringWindowToTop();
return;
}
// ==> Static Tray Icon [MorphXT] - MyTh88
/*
if (TrayIsVisible())
*/
if (thePrefs.GetStaticIcon() == false)
// <== Static Tray Icon [MorphXT] - MyTh88
TrayHide();
DestroyMiniMule();
if (m_wpFirstRestore.length)
{
SetWindowPlacement(&m_wpFirstRestore);
memset(&m_wpFirstRestore, 0, sizeof m_wpFirstRestore);
SetForegroundWindow();
BringWindowToTop();
}
else
CTrayDialog::RestoreWindow();
}
void CemuleDlg::UpdateTrayIcon(int iPercent)
{
// compute an id of the icon to be generated
UINT uSysTrayIconCookie = (iPercent > 0) ? (16 - ((iPercent*15/100) + 1)) : 0;
if (theApp.IsConnected()) {
if (!theApp.IsFirewalled())
uSysTrayIconCookie += 50;
}
else
uSysTrayIconCookie += 100;
// dont update if the same icon as displayed would be generated
// ==> Completed in Tray [Stulle] - Stulle
/*
if (m_uLastSysTrayIconCookie == uSysTrayIconCookie)
return;
*/
if (m_uLastSysTrayIconCookie == uSysTrayIconCookie && m_bTrayBoolOld == m_bTrayBool)
return;
m_bTrayBoolOld = m_bTrayBool;
// <== Completed in Tray [Stulle] - Stulle
m_uLastSysTrayIconCookie = uSysTrayIconCookie;
// prepare it up
if (m_iMsgIcon!=0 && thePrefs.DoFlashOnNewMessage()==true ) {
m_iMsgBlinkState=!m_iMsgBlinkState;
if (m_iMsgBlinkState)
m_TrayIcon.Init(imicons[1], 100, 1, 1, 16, 16, thePrefs.GetStatsColor(11));
} else m_iMsgBlinkState=false;
if (!m_iMsgBlinkState) {
// ==> Completed in Tray [Stulle] - Stulle
/*
if (theApp.IsConnected()) {
if (theApp.IsFirewalled())
m_TrayIcon.Init(m_icoSysTrayLowID, 100, 1, 1, 16, 16, thePrefs.GetStatsColor(11));
else
m_TrayIcon.Init(m_icoSysTrayConnected, 100, 1, 1, 16, 16, thePrefs.GetStatsColor(11));
}
else
m_TrayIcon.Init(m_icoSysTrayDisconnected, 100, 1, 1, 16, 16, thePrefs.GetStatsColor(11));
*/
if (theApp.IsConnected()) {
if (thePrefs.GetTrayComplete() && m_bTrayBool)
{
if (theApp.IsFirewalled())
m_TrayIcon.Init(m_icoSysTrayLowIDPlus, 100, 1, 1, 16, 16, thePrefs.GetStatsColor(11));
else
m_TrayIcon.Init(m_icoSysTrayConnectedPlus, 100, 1, 1, 16, 16, thePrefs.GetStatsColor(11));
}
else
{
if (theApp.IsFirewalled())
m_TrayIcon.Init(m_icoSysTrayLowID, 100, 1, 1, 16, 16, thePrefs.GetStatsColor(11));
else
m_TrayIcon.Init(m_icoSysTrayConnected, 100, 1, 1, 16, 16, thePrefs.GetStatsColor(11));
}
}
else if (thePrefs.GetTrayComplete() && m_bTrayBool)
m_TrayIcon.Init(m_icoSysTrayDisconnectedPlus, 100, 1, 1, 16, 16, thePrefs.GetStatsColor(11));
else
m_TrayIcon.Init(m_icoSysTrayDisconnected, 100, 1, 1, 16, 16, thePrefs.GetStatsColor(11));
// <== Completed in Tray [Stulle] - Stulle
}
// load our limit and color info
static const int aiLimits[1] = { 100 }; // set the limits of where the bar color changes (low-high)
COLORREF aColors[1] = { thePrefs.GetStatsColor(11) }; // set the corresponding color for each level
m_TrayIcon.SetColorLevels(aiLimits, aColors, _countof(aiLimits));
// generate the icon (do *not* destroy that icon using DestroyIcon(), that's done in 'TrayUpdate')
int aiVals[1] = { iPercent };
m_icoSysTrayCurrent = m_TrayIcon.Create(aiVals);
ASSERT( m_icoSysTrayCurrent != NULL );
if (m_icoSysTrayCurrent)
TraySetIcon(m_icoSysTrayCurrent, true);
TrayUpdate();
}
int CemuleDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
return CTrayDialog::OnCreate(lpCreateStruct);
}
void CemuleDlg::OnShowWindow(BOOL bShow, UINT nStatus)
{
if (IsRunning()){
ShowTransferRate(true);
if (bShow == TRUE && activewnd == chatwnd)
chatwnd->chatselector.ShowChat();
}
CTrayDialog::OnShowWindow(bShow, nStatus);
}
void CemuleDlg::ShowNotifier(LPCTSTR pszText, int iMsgType, LPCTSTR pszLink, bool bForceSoundOFF)
{
if (!notifierenabled)
return;
LPCTSTR pszSoundEvent = NULL;
int iSoundPrio = 0;
bool bShowIt = false;
switch (iMsgType)
{
case TBN_CHAT:
if (thePrefs.GetNotifierOnChat())
{
m_wndTaskbarNotifier->Show(pszText, iMsgType, pszLink);
bShowIt = true;
pszSoundEvent = _T("eMule_Chat");
iSoundPrio = 1;
}
break;
case TBN_DOWNLOADFINISHED:
if (thePrefs.GetNotifierOnDownloadFinished())
{
m_wndTaskbarNotifier->Show(pszText, iMsgType, pszLink);
bShowIt = true;
pszSoundEvent = _T("eMule_DownloadFinished");
iSoundPrio = 1;
SendNotificationMail(iMsgType, pszText);
}
break;
case TBN_DOWNLOADADDED:
if (thePrefs.GetNotifierOnNewDownload())
{
m_wndTaskbarNotifier->Show(pszText, iMsgType, pszLink);
bShowIt = true;
pszSoundEvent = _T("eMule_DownloadAdded");
iSoundPrio = 1;
}
break;
case TBN_LOG:
if (thePrefs.GetNotifierOnLog())
{
m_wndTaskbarNotifier->Show(pszText, iMsgType, pszLink);
bShowIt = true;
pszSoundEvent = _T("eMule_LogEntryAdded");
}
break;
case TBN_IMPORTANTEVENT:
if (thePrefs.GetNotifierOnImportantError())
{
m_wndTaskbarNotifier->Show(pszText, iMsgType, pszLink);
bShowIt = true;
pszSoundEvent = _T("eMule_Urgent");
iSoundPrio = 1;
SendNotificationMail(iMsgType, pszText);
}
break;
case TBN_NEWVERSION:
if (thePrefs.GetNotifierOnNewVersion())
{
m_wndTaskbarNotifier->Show(pszText, iMsgType, pszLink);
bShowIt = true;
pszSoundEvent = _T("eMule_NewVersion");
iSoundPrio = 1;
}
break;
//Xman versions check
case TBN_NEWMVERSION:
{
m_wndTaskbarNotifier->Show(pszText, iMsgType, pszLink);
bShowIt = true;
pszSoundEvent = _T("eMule_NewVersion");
iSoundPrio = 1;
}
break;
//Xman end
// ==> ScarAngel Version Check - Stulle
case TBN_NEWSVERSION:
{
m_wndTaskbarNotifier->Show(pszText, iMsgType, pszLink);
bShowIt = true;
pszSoundEvent = _T("eMule_NewVersion");
iSoundPrio = 1;
}
break;
// <== ScarAngel Version Check - Stulle
case TBN_NULL:
m_wndTaskbarNotifier->Show(pszText, iMsgType, pszLink);
bShowIt = true;
break;
}
if (bShowIt && !bForceSoundOFF && thePrefs.GetNotifierSoundType() != ntfstNoSound)
{
bool bNotifiedWithAudio = false;
if (thePrefs.GetNotifierSoundType() == ntfstSpeech)
bNotifiedWithAudio = Speak(pszText);
if (!bNotifiedWithAudio)
{
if (!thePrefs.GetNotifierSoundFile().IsEmpty())
{
PlaySound(thePrefs.GetNotifierSoundFile(), NULL, SND_FILENAME | SND_NOSTOP | SND_NOWAIT | SND_ASYNC);
}
else if (pszSoundEvent)
{
// use 'SND_NOSTOP' only for low priority events, otherwise the 'Log message' event may overrule a more important
// event which is fired nearly at the same time.
PlaySound(pszSoundEvent, NULL, SND_APPLICATION | SND_ASYNC | SND_NODEFAULT | SND_NOWAIT | ((iSoundPrio > 0) ? 0 : SND_NOSTOP));
}
}
}
}
void CemuleDlg::LoadNotifier(CString configuration)
{
notifierenabled = m_wndTaskbarNotifier->LoadConfiguration(configuration)!=FALSE;
}
LRESULT CemuleDlg::OnTaskbarNotifierClicked(WPARAM /*wParam*/, LPARAM lParam)
{
if (lParam)
{
LPTSTR pszLink = (LPTSTR)lParam;
ShellOpenFile(pszLink, NULL);
free(pszLink);
pszLink = NULL;
}
switch (m_wndTaskbarNotifier->GetMessageType())
{
case TBN_CHAT:
RestoreWindow();
SetActiveDialog(chatwnd);
break;
case TBN_DOWNLOADFINISHED:
// if we had a link and opened the downloaded file, dont restore the app window
if (lParam==0)
{
RestoreWindow();
SetActiveDialog(transferwnd);
}
break;
case TBN_DOWNLOADADDED:
RestoreWindow();
SetActiveDialog(transferwnd);
break;
case TBN_IMPORTANTEVENT:
RestoreWindow();
SetActiveDialog(serverwnd);
break;
case TBN_LOG:
RestoreWindow();
SetActiveDialog(serverwnd);
break;
case TBN_NEWVERSION:
{
CString theUrl;
theUrl.Format(_T("/en/version_check.php?version=%i&language=%i"),theApp.m_uCurVersionCheck,thePrefs.GetLanguageID());
theUrl = thePrefs.GetVersionCheckBaseURL()+theUrl;
ShellExecute(NULL, NULL, theUrl, NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
break;
}
//Xman versions check
case TBN_NEWMVERSION:
{
ShellExecute(NULL, NULL, MOD_HPLINK, NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
break;
}
//Xman end
// ==> ScarAngel Version Check - Stulle
case TBN_NEWSVERSION:
{
ShellExecute(NULL, NULL, _T("http://scarangel.sourceforge.net/"), NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
break;
}
// <== ScarAngel Version Check - Stulle
}
return 0;
}
void CemuleDlg::OnSettingChange(UINT uFlags, LPCTSTR lpszSection)
{
TRACE(_T("CemuleDlg::OnSettingChange: uFlags=0x%08x lpszSection=\"%s\"\n"), lpszSection);
// Do not update the Shell's large icon size, because we still have an image list
// from the shell which contains the old large icon size.
//theApp.UpdateLargeIconSize();
theApp.UpdateDesktopColorDepth();
CTrayDialog::OnSettingChange(uFlags, lpszSection);
}
void CemuleDlg::OnSysColorChange()
{
theApp.UpdateDesktopColorDepth();
CTrayDialog::OnSysColorChange();
SetAllIcons();
}
// ==> Design Settings [eWombat/Stulle] - Max
// See end of file for modded function
/*
HBRUSH CemuleDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = GetCtlColor(pDC, pWnd, nCtlColor);
if (hbr)
return hbr;
return __super::OnCtlColor(pDC, pWnd, nCtlColor);
}
*/
// <== Design Settings [eWombat/Stulle] - Max
HBRUSH CemuleDlg::GetCtlColor(CDC* /*pDC*/, CWnd* /*pWnd*/, UINT nCtlColor)
{
UNREFERENCED_PARAMETER(nCtlColor);
// This function could be used to give the entire eMule (at least all of the main windows)
// a somewhat more Vista like look by giving them all a bright background color.
// However, again, the ownerdrawn tab controls are noticeable disturbing that attempt. They
// do not change their background color accordingly. They don't use NMCUSTOMDRAW nor to they
// use WM_CTLCOLOR...
//
//if (theApp.m_ullComCtrlVer >= MAKEDLLVERULL(6,16,0,0) && g_xpStyle.IsThemeActive() && g_xpStyle.IsAppThemed()) {
// if (nCtlColor == CTLCOLOR_DLG || nCtlColor == CTLCOLOR_STATIC)
// return GetSysColorBrush(COLOR_WINDOW);
//}
return NULL;
}
void CemuleDlg::SetAllIcons()
{
// application icon (although it's not customizable, we may need to load a different color resolution)
if (m_hIcon)
VERIFY( ::DestroyIcon(m_hIcon) );
// NOTE: the application icon name is prefixed with "AAA" to make sure it's alphabetically sorted by the
// resource compiler as the 1st icon in the resource table!
m_hIcon = AfxGetApp()->LoadIcon(_T("AAAEMULEAPP"));
SetIcon(m_hIcon, TRUE);
// this scales the 32x32 icon down to 16x16, does not look nice at least under WinXP
//SetIcon(m_hIcon, FALSE);
// connection state
for (int i = 0; i < _countof(connicons); i++){
if (connicons[i]) VERIFY( ::DestroyIcon(connicons[i]) );
}
connicons[0] = theApp.LoadIcon(_T("ConnectedNotNot"), 16, 16);
connicons[1] = theApp.LoadIcon(_T("ConnectedNotLow"), 16, 16);
connicons[2] = theApp.LoadIcon(_T("ConnectedNotHigh"), 16, 16);
connicons[3] = theApp.LoadIcon(_T("ConnectedLowNot"), 16, 16);
connicons[4] = theApp.LoadIcon(_T("ConnectedLowLow"), 16, 16);
connicons[5] = theApp.LoadIcon(_T("ConnectedLowHigh"), 16, 16);
connicons[6] = theApp.LoadIcon(_T("ConnectedHighNot"), 16, 16);
connicons[7] = theApp.LoadIcon(_T("ConnectedHighLow"), 16, 16);
connicons[8] = theApp.LoadIcon(_T("ConnectedHighHigh"), 16, 16);
ShowConnectionStateIcon();
// transfer state
if (transicons[0]) VERIFY( ::DestroyIcon(transicons[0]) );
if (transicons[1]) VERIFY( ::DestroyIcon(transicons[1]) );
if (transicons[2]) VERIFY( ::DestroyIcon(transicons[2]) );
if (transicons[3]) VERIFY( ::DestroyIcon(transicons[3]) );
transicons[0] = theApp.LoadIcon(_T("UP0DOWN0"), 16, 16);
transicons[1] = theApp.LoadIcon(_T("UP0DOWN1"), 16, 16);
transicons[2] = theApp.LoadIcon(_T("UP1DOWN0"), 16, 16);
transicons[3] = theApp.LoadIcon(_T("UP1DOWN1"), 16, 16);
ShowTransferStateIcon();
// users state
if (usericon) VERIFY( ::DestroyIcon(usericon) );
usericon = theApp.LoadIcon(_T("StatsClients"), 16, 16);
ShowUserStateIcon();
// traybar icons
if (m_icoSysTrayConnected) VERIFY( ::DestroyIcon(m_icoSysTrayConnected) );
if (m_icoSysTrayDisconnected) VERIFY( ::DestroyIcon(m_icoSysTrayDisconnected) );
if (m_icoSysTrayLowID) VERIFY( ::DestroyIcon(m_icoSysTrayLowID) );
m_icoSysTrayConnected = theApp.LoadIcon(_T("TrayConnected"), 16, 16);
m_icoSysTrayDisconnected = theApp.LoadIcon(_T("TrayNotConnected"), 16, 16);
m_icoSysTrayLowID = theApp.LoadIcon(_T("TrayLowID"), 16, 16);
// ==> Completed in Tray [Stulle] - Stulle
if (m_icoSysTrayConnectedPlus) VERIFY( ::DestroyIcon(m_icoSysTrayConnectedPlus) );
if (m_icoSysTrayDisconnectedPlus) VERIFY( ::DestroyIcon(m_icoSysTrayDisconnectedPlus) );
if (m_icoSysTrayLowIDPlus) VERIFY( ::DestroyIcon(m_icoSysTrayLowIDPlus) );
m_icoSysTrayConnectedPlus = theApp.LoadIcon(_T("TrayConnectedPlus"), 16, 16);
m_icoSysTrayDisconnectedPlus = theApp.LoadIcon(_T("TrayNotConnectedPlus"), 16, 16);
m_icoSysTrayLowIDPlus = theApp.LoadIcon(_T("TrayLowIDPlus"), 16, 16);
// <== Completed in Tray [Stulle] - Stulle
ShowTransferRate(true);
if (imicons[0]) VERIFY( ::DestroyIcon(imicons[0]) );
if (imicons[1]) VERIFY( ::DestroyIcon(imicons[1]) );
if (imicons[2]) VERIFY( ::DestroyIcon(imicons[2]) );
imicons[0] = NULL;
imicons[1] = theApp.LoadIcon(_T("Message"), 16, 16);
imicons[2] = theApp.LoadIcon(_T("MessagePending"), 16, 16);
ShowMessageState(m_iMsgIcon);
}
void CemuleDlg::Localize()
{
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu)
{
VERIFY( pSysMenu->ModifyMenu(MP_ABOUTBOX, MF_BYCOMMAND | MF_STRING, MP_ABOUTBOX, GetResString(IDS_ABOUTBOX)) );
VERIFY( pSysMenu->ModifyMenu(MP_VERSIONCHECK, MF_BYCOMMAND | MF_STRING, MP_VERSIONCHECK, GetResString(IDS_VERSIONCHECK)) );
//Xman versions check
// ==> Removed Xtreme version check [Stulle] - Stulle
/*
VERIFY( pSysMenu->ModifyMenu(MP_MVERSIONCHECK, MF_BYCOMMAND | MF_STRING, MP_MVERSIONCHECK, _T("Xtreme_Version_Check")) );
*/
// <== Removed Xtreme version check [Stulle] - Stulle
//Xman end
// ==> ScarAngel Version Check - Stulle
VERIFY( pSysMenu->ModifyMenu(MP_SVERSIONCHECK, MF_BYCOMMAND | MF_STRING, MP_SVERSIONCHECK, GetResString(IDS_SVERSIONCHECK)) );
// <== ScarAngel Version Check - Stulle
switch (thePrefs.GetWindowsVersion())
{
case _WINVER_98_:
case _WINVER_95_:
case _WINVER_ME_:
// NOTE: I think the reason why the old version of the following code crashed under Win9X was because
// of the menus were destroyed right after they were added to the system menu. New code should work
// under Win9X too but I can't test it.
break;
default:{
// localize the 'speed control' sub menus by deleting the current menus and creating a new ones.
// remove any already available 'speed control' menus from system menu
UINT uOptMenuPos = pSysMenu->GetMenuItemCount() - 1;
CMenu* pAccelMenu = pSysMenu->GetSubMenu(uOptMenuPos);
if (pAccelMenu)
{
ASSERT( pAccelMenu->m_hMenu == m_SysMenuOptions.m_hMenu );
VERIFY( pSysMenu->RemoveMenu(uOptMenuPos, MF_BYPOSITION) );
pAccelMenu = NULL;
}
// destroy all 'speed control' menus
if (m_menuUploadCtrl)
VERIFY( m_menuUploadCtrl.DestroyMenu() );
if (m_menuDownloadCtrl)
VERIFY( m_menuDownloadCtrl.DestroyMenu() );
if (m_SysMenuOptions)
VERIFY( m_SysMenuOptions.DestroyMenu() );
// create new 'speed control' menus
if (m_SysMenuOptions.CreateMenu())
{
AddSpeedSelectorMenus(&m_SysMenuOptions);
pSysMenu->AppendMenu(MF_STRING|MF_POPUP, (UINT_PTR)m_SysMenuOptions.m_hMenu, GetResString(IDS_EM_PREFS));
}
}
}
}
ShowUserStateIcon();
toolbar->Localize();
ShowConnectionState();
ShowTransferRate(true);
ShowUserCount();
CPartFileConvert::Localize();
if (m_pMiniMule)
m_pMiniMule->Localize();
}
void CemuleDlg::ShowUserStateIcon()
{
statusbar->SetIcon(SBarUsers, usericon);
}
void CemuleDlg::QuickSpeedOther(UINT nID)
{
switch (nID) {
//Xman changed the values !
// Maella [FAF] -Allow Bandwidth Settings in <1KB Incremements-
/*
case MP_QS_PA:
thePrefs.SetMaxUpload(1);
thePrefs.SetMaxDownload(1);
break ;
case MP_QS_UA:
thePrefs.SetMaxUpload(thePrefs.GetMaxGraphUploadRate(true));
thePrefs.SetMaxDownload(thePrefs.GetMaxGraphDownloadRate());
*/
case MP_QS_PA: thePrefs.SetMaxUpload((float)(3));
thePrefs.SetMaxDownload((float)(1));
thePrefs.CheckSlotSpeed(); //XMan Xtreme Upload
break ;
case MP_QS_UA:
thePrefs.SetMaxUpload((float)(thePrefs.GetMaxGraphUploadRate()-2));
thePrefs.SetMaxDownload((float)(thePrefs.GetMaxGraphDownloadRate()));
thePrefs.CheckSlotSpeed(); //Xman Xtreme Upload
//Xman end
break ;
}
}
void CemuleDlg::QuickSpeedUpload(UINT nID)
{
switch (nID) {
//Xman
// Maella [FAF] -Allow Bandwidth Settings in <1KB Incremements-
/*
case MP_QS_U10: thePrefs.SetMaxUpload((UINT)(thePrefs.GetMaxGraphUploadRate(true)*0.1)); break ;
case MP_QS_U20: thePrefs.SetMaxUpload((UINT)(thePrefs.GetMaxGraphUploadRate(true)*0.2)); break ;
case MP_QS_U30: thePrefs.SetMaxUpload((UINT)(thePrefs.GetMaxGraphUploadRate(true)*0.3)); break ;
case MP_QS_U40: thePrefs.SetMaxUpload((UINT)(thePrefs.GetMaxGraphUploadRate(true)*0.4)); break ;
case MP_QS_U50: thePrefs.SetMaxUpload((UINT)(thePrefs.GetMaxGraphUploadRate(true)*0.5)); break ;
case MP_QS_U60: thePrefs.SetMaxUpload((UINT)(thePrefs.GetMaxGraphUploadRate(true)*0.6)); break ;
case MP_QS_U70: thePrefs.SetMaxUpload((UINT)(thePrefs.GetMaxGraphUploadRate(true)*0.7)); break ;
case MP_QS_U80: thePrefs.SetMaxUpload((UINT)(thePrefs.GetMaxGraphUploadRate(true)*0.8)); break ;
case MP_QS_U90: thePrefs.SetMaxUpload((UINT)(thePrefs.GetMaxGraphUploadRate(true)*0.9)); break ;
case MP_QS_U100: thePrefs.SetMaxUpload((UINT)thePrefs.GetMaxGraphUploadRate(true)); break ;
*/
case MP_QS_U10: thePrefs.SetMaxUpload((float)(thePrefs.GetMaxGraphUploadRate()*0.1)); break ;
case MP_QS_U20: thePrefs.SetMaxUpload((float)(thePrefs.GetMaxGraphUploadRate()*0.2)); break ;
case MP_QS_U30: thePrefs.SetMaxUpload((float)(thePrefs.GetMaxGraphUploadRate()*0.3)); break ;
case MP_QS_U40: thePrefs.SetMaxUpload((float)(thePrefs.GetMaxGraphUploadRate()*0.4)); break ;
case MP_QS_U50: thePrefs.SetMaxUpload((float)(thePrefs.GetMaxGraphUploadRate()*0.5)); break ;
case MP_QS_U60: thePrefs.SetMaxUpload((float)(thePrefs.GetMaxGraphUploadRate()*0.6)); break ;
case MP_QS_U70: thePrefs.SetMaxUpload((float)(thePrefs.GetMaxGraphUploadRate()*0.7)); break ;
case MP_QS_U80: thePrefs.SetMaxUpload((float)(thePrefs.GetMaxGraphUploadRate()*0.8)); break ;
case MP_QS_U90: thePrefs.SetMaxUpload((float)(thePrefs.GetMaxGraphUploadRate()*0.9)); break ;
case MP_QS_U100: thePrefs.SetMaxUpload(thePrefs.GetMaxGraphUploadRate()); break ;
//Xman end
// case MP_QS_UPC: thePrefs.SetMaxUpload(UNLIMITED); break ;
case MP_QS_UP10: thePrefs.SetMaxUpload(GetRecMaxUpload()); break ;
}
thePrefs.CheckSlotSpeed(); //Xman Xtreme Upload
theApp.scheduler->SaveOriginals(); // Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle
}
void CemuleDlg::QuickSpeedDownload(UINT nID)
{
switch (nID) {
//Xman
// Maella [FAF] -Allow Bandwidth Settings in <1KB Incremements-
/*
case MP_QS_D10: thePrefs.SetMaxDownload((UINT)(thePrefs.GetMaxGraphDownloadRate()*0.1)); break ;
case MP_QS_D20: thePrefs.SetMaxDownload((UINT)(thePrefs.GetMaxGraphDownloadRate()*0.2)); break ;
case MP_QS_D30: thePrefs.SetMaxDownload((UINT)(thePrefs.GetMaxGraphDownloadRate()*0.3)); break ;
case MP_QS_D40: thePrefs.SetMaxDownload((UINT)(thePrefs.GetMaxGraphDownloadRate()*0.4)); break ;
case MP_QS_D50: thePrefs.SetMaxDownload((UINT)(thePrefs.GetMaxGraphDownloadRate()*0.5)); break ;
case MP_QS_D60: thePrefs.SetMaxDownload((UINT)(thePrefs.GetMaxGraphDownloadRate()*0.6)); break ;
case MP_QS_D70: thePrefs.SetMaxDownload((UINT)(thePrefs.GetMaxGraphDownloadRate()*0.7)); break ;
case MP_QS_D80: thePrefs.SetMaxDownload((UINT)(thePrefs.GetMaxGraphDownloadRate()*0.8)); break ;
case MP_QS_D90: thePrefs.SetMaxDownload((UINT)(thePrefs.GetMaxGraphDownloadRate()*0.9)); break ;
case MP_QS_D100: thePrefs.SetMaxDownload((UINT)thePrefs.GetMaxGraphDownloadRate()); break ;
*/
case MP_QS_D10: thePrefs.SetMaxDownload(0.1f * thePrefs.GetMaxGraphDownloadRate()); break ;
case MP_QS_D20: thePrefs.SetMaxDownload(0.2f * thePrefs.GetMaxGraphDownloadRate()); break ;
case MP_QS_D30: thePrefs.SetMaxDownload(0.3f * thePrefs.GetMaxGraphDownloadRate()); break ;
case MP_QS_D40: thePrefs.SetMaxDownload(0.4f * thePrefs.GetMaxGraphDownloadRate()); break ;
case MP_QS_D50: thePrefs.SetMaxDownload(0.5f * thePrefs.GetMaxGraphDownloadRate()); break ;
case MP_QS_D60: thePrefs.SetMaxDownload(0.6f * thePrefs.GetMaxGraphDownloadRate()); break ;
case MP_QS_D70: thePrefs.SetMaxDownload(0.7f * thePrefs.GetMaxGraphDownloadRate()); break ;
case MP_QS_D80: thePrefs.SetMaxDownload(0.8f * thePrefs.GetMaxGraphDownloadRate()); break ;
case MP_QS_D90: thePrefs.SetMaxDownload(0.9f * thePrefs.GetMaxGraphDownloadRate()); break ;
case MP_QS_D100: thePrefs.SetMaxDownload(thePrefs.GetMaxGraphDownloadRate()); break ;
//Xman end
// case MP_QS_DC: thePrefs.SetMaxDownload(UNLIMITED); break ;
}
theApp.scheduler->SaveOriginals(); // Don't reset Connection Settings for Webserver/CML/MM [Stulle] - Stulle
}
// quick-speed changer -- based on xrmb
//Xman
// Maella [FAF] -Allow Bandwidth Settings in <1KB Incremements-
/*
int CemuleDlg::GetRecMaxUpload() {
if (thePrefs.GetMaxGraphUploadRate(true)<7) return 0;
if (thePrefs.GetMaxGraphUploadRate(true)<15) return thePrefs.GetMaxGraphUploadRate(true)-3;
return (thePrefs.GetMaxGraphUploadRate(true)-4);
}
*/
float CemuleDlg::GetRecMaxUpload() {
//Xman changed 6.0.1
if (thePrefs.GetMaxGraphUploadRate()<10) return thePrefs.GetMaxGraphUploadRate()-1.5f;
if (thePrefs.GetMaxGraphUploadRate()<20) return thePrefs.GetMaxGraphUploadRate()-2.5f;
if (thePrefs.GetMaxGraphUploadRate()<26) return thePrefs.GetMaxGraphUploadRate()-3.0f;
return (thePrefs.GetMaxGraphUploadRate()*0.9f);
}
//Xman end
BOOL CemuleDlg::OnCommand(WPARAM wParam, LPARAM lParam)
{
switch(wParam)
{
case TBBTN_CONNECT:
OnBnClickedConnect();
break;
case MP_HM_KAD:
case TBBTN_KAD:
SetActiveDialog(kademliawnd);
break;
case TBBTN_SERVER:
case MP_HM_SRVR:
SetActiveDialog(serverwnd);
break;
case TBBTN_TRANSFERS:
case MP_HM_TRANSFER:
SetActiveDialog(transferwnd);
break;
case TBBTN_SEARCH:
case MP_HM_SEARCH:
// >> add by Ken
searchwnd->m_pwndParams->m_bAutoDownload = false;
// << add by Ken
SetActiveDialog(searchwnd);
break;
// >> add by Ken
case MP_HM_GIFC:
case MP_HM_GIFC1:
searchwnd->m_pwndParams->m_ctlName.SetWindowText(L"GIFC");
searchwnd->m_pwndParams->m_ctlFileType.SelectItemDataStringA(ED2KFTSTR_ARCHIVE);
SetActiveDialog(searchwnd);
searchwnd->m_pwndParams->m_bAutoDownload = (wParam == MP_HM_GIFC);
searchwnd->m_pwndParams->OnBnClickedStart();
break;
case MP_HM_SHOWLESS:
thePrefs.SetLessControls(true);
thePrefs.SetExtControls(false);
break;
case MP_HM_SHOWMORE:
thePrefs.SetLessControls(false);
thePrefs.SetExtControls(false);
break;
case MP_HM_SHOWEXT:
thePrefs.SetLessControls(false);
thePrefs.SetExtControls(true);
break;
// << add by Ken
case TBBTN_SHARED:
case MP_HM_FILES:
SetActiveDialog(sharedfileswnd);
break;
case TBBTN_MESSAGES:
case MP_HM_MSGS:
SetActiveDialog(chatwnd);
break;
case TBBTN_IRC:
case MP_HM_IRC:
SetActiveDialog(ircwnd);
break;
case TBBTN_STATS:
case MP_HM_STATS:
SetActiveDialog(statisticswnd);
break;
case TBBTN_OPTIONS:
case MP_HM_PREFS:
toolbar->CheckButton(TBBTN_OPTIONS, TRUE);
ShowPreferences();
toolbar->CheckButton(TBBTN_OPTIONS, FALSE);
break;
case TBBTN_TOOLS:
ShowToolPopup(true);
break;
case MP_HM_OPENINC:
ShellExecute(NULL, _T("open"), thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR),NULL, NULL, SW_SHOW);
break;
// >> add by Ken
case MP_HM_OPENGIFC:
ShellExecute(NULL, _T("open"), thePrefs.GetMuleDirectory(EMULE_GIFCDIR), NULL, NULL, SW_SHOW);
break;
// << add by Ken
case MP_HM_HELP:
case TBBTN_HELP:
if (activewnd != NULL) {
HELPINFO hi;
ZeroMemory(&hi, sizeof(HELPINFO));
hi.cbSize = sizeof(HELPINFO);
activewnd->SendMessage(WM_HELP, 0, (LPARAM)&hi);
}
else
wParam = ID_HELP;
break;
case MP_HM_CON:
OnBnClickedConnect();
break;
case MP_HM_EXIT:
OnClose();
break;
case MP_HM_LINK1: // MOD: dont remove!
ShellExecute(NULL, NULL, thePrefs.GetHomepageBaseURL(), NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
break;
case MP_HM_LINK2:
ShellExecute(NULL, NULL, thePrefs.GetHomepageBaseURL()+ CString(_T("/faq/")), NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
break;
case MP_HM_LINK3: {
CString theUrl;
theUrl.Format( thePrefs.GetVersionCheckBaseURL() + CString(_T("/en/version_check.php?version=%i&language=%i")),theApp.m_uCurVersionCheck,thePrefs.GetLanguageID());
ShellExecute(NULL, NULL, theUrl, NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
break;
}
case MP_WEBSVC_EDIT:
theWebServices.Edit();
break;
case MP_HM_CONVERTPF:
CPartFileConvert::ShowGUI();
break;
case MP_HM_SCHEDONOFF:
thePrefs.SetSchedulerEnabled(!thePrefs.IsSchedulerEnabled());
theApp.scheduler->Check(true);
break;
case MP_HM_1STSWIZARD:
FirstTimeWizard();
break;
case MP_HM_IPFILTER:{
CIPFilterDlg dlg;
dlg.DoModal();
break;
}
case MP_HM_DIRECT_DOWNLOAD:{
CDirectDownloadDlg dlg;
dlg.DoModal();
break;
}
}
if (wParam>=MP_WEBURL && wParam<=MP_WEBURL+99) {
theWebServices.RunURL(NULL, wParam);
}
else if (wParam>=MP_SCHACTIONS && wParam<=MP_SCHACTIONS+99) {
theApp.scheduler->ActivateSchedule(wParam-MP_SCHACTIONS);
theApp.scheduler->SaveOriginals(); // use the new settings as original
}
#ifdef HAVE_WIN7_SDK_H
else if (HIWORD(wParam) == THBN_CLICKED) {
OnTBBPressed(LOWORD(wParam));
return TRUE;
}
#endif
return CTrayDialog::OnCommand(wParam, lParam);
}
LRESULT CemuleDlg::OnMenuChar(UINT nChar, UINT nFlags, CMenu* pMenu)
{
// ==> XP Style Menu [Xanatos] - Stulle
if (pMenu->IsKindOf(RUNTIME_CLASS(CTitleMenu)) )
return CTitleMenu::OnMenuChar(nChar, nFlags, pMenu);
// <== XP Style Menu [Xanatos] - Stulle
UINT nCmdID;
if (toolbar->MapAccelerator((TCHAR)nChar, &nCmdID)){
OnCommand(nCmdID, 0);
return MAKELONG(0,MNC_CLOSE);
}
return CTrayDialog::OnMenuChar(nChar, nFlags, pMenu);
}
// Barry - To find out if app is running or shutting/shut down
bool CemuleDlg::IsRunning()
{
return (theApp.m_app_state == APP_STATE_RUNNING);
}
void CemuleDlg::OnBnClickedHotmenu()
{
ShowToolPopup(false);
}
void CemuleDlg::ShowToolPopup(bool toolsonly)
{
POINT point;
::GetCursorPos(&point);
CTitleMenu menu;
menu.CreatePopupMenu();
if (!toolsonly)
menu.AddMenuTitle(GetResString(IDS_HOTMENU), true);
else
menu.AddMenuTitle(GetResString(IDS_TOOLS), true);
CTitleMenu Links;
Links.CreateMenu();
// ==> XP Style Menu [Xanatos] - Stulle
/*
Links.AddMenuTitle(NULL, true);
*/
Links.AddMenuTitle(GetResString(IDS_LINKS), true, false);
// <== XP Style Menu [Xanatos] - Stulle
Links.AppendMenu(MF_STRING, MP_HM_LINK1, GetResString(IDS_HM_LINKHP), _T("WEB"));
Links.AppendMenu(MF_STRING, MP_HM_LINK2, GetResString(IDS_HM_LINKFAQ), _T("WEB"));
Links.AppendMenu(MF_STRING, MP_HM_LINK3, GetResString(IDS_HM_LINKVC), _T("WEB"));
theWebServices.GetGeneralMenuEntries(&Links);
Links.InsertMenu(3, MF_BYPOSITION | MF_SEPARATOR);
Links.AppendMenu(MF_STRING, MP_WEBSVC_EDIT, GetResString(IDS_WEBSVEDIT));
// ==> XP Style Menu [Xanatos] - Stulle
/*
CMenu scheduler;
scheduler.CreateMenu();
*/
CTitleMenu scheduler;
scheduler.CreateMenu();
scheduler.AddMenuTitle(GetResString(IDS_SCHEDULER), true, false);
// <== XP Style Menu [Xanatos] - Stulle
CString schedonoff= (!thePrefs.IsSchedulerEnabled())?GetResString(IDS_HM_SCHED_ON):GetResString(IDS_HM_SCHED_OFF);
// ==> more icons - Stulle
/*
scheduler.AppendMenu(MF_STRING,MP_HM_SCHEDONOFF, schedonoff);
*/
scheduler.AppendMenu(MF_STRING,MP_HM_SCHEDONOFF, schedonoff, _T("SCHEDULER"));
// <== more icons - Stulle
if (theApp.scheduler->GetCount()>0) {
scheduler.AppendMenu(MF_SEPARATOR);
for (UINT i=0; i<theApp.scheduler->GetCount();i++)
scheduler.AppendMenu(MF_STRING,MP_SCHACTIONS+i, theApp.scheduler->GetSchedule(i)->title);
}
if (!toolsonly) {
if (theApp.serverconnect->IsConnected())
menu.AppendMenu(MF_STRING,MP_HM_CON,GetResString(IDS_MAIN_BTN_DISCONNECT), _T("DISCONNECT"));
else if (theApp.serverconnect->IsConnecting())
menu.AppendMenu(MF_STRING,MP_HM_CON,GetResString(IDS_MAIN_BTN_CANCEL), _T("STOPCONNECTING"));
else
menu.AppendMenu(MF_STRING,MP_HM_CON,GetResString(IDS_MAIN_BTN_CONNECT), _T("CONNECT"));
menu.AppendMenu(MF_STRING,MP_HM_KAD, GetResString(IDS_EM_KADEMLIA), _T("KADEMLIA") );
menu.AppendMenu(MF_STRING,MP_HM_SRVR, GetResString(IDS_EM_SERVER), _T("SERVER") );
menu.AppendMenu(MF_STRING,MP_HM_TRANSFER, GetResString(IDS_EM_TRANS),_T("TRANSFER") );
menu.AppendMenu(MF_STRING,MP_HM_SEARCH, GetResString(IDS_EM_SEARCH), _T("SEARCH"));
menu.AppendMenu(MF_STRING,MP_HM_FILES, GetResString(IDS_EM_FILES), _T("SharedFiles"));
menu.AppendMenu(MF_STRING,MP_HM_MSGS, GetResString(IDS_EM_MESSAGES), _T("MESSAGES"));
menu.AppendMenu(MF_STRING,MP_HM_IRC, GetResString(IDS_IRC), _T("IRC"));
menu.AppendMenu(MF_STRING,MP_HM_STATS, GetResString(IDS_EM_STATISTIC), _T("STATISTICS"));
menu.AppendMenu(MF_STRING,MP_HM_PREFS, GetResString(IDS_EM_PREFS), _T("PREFERENCES"));
menu.AppendMenu(MF_STRING,MP_HM_HELP, GetResString(IDS_EM_HELP), _T("HELP"));
menu.AppendMenu(MF_SEPARATOR);
}
menu.AppendMenu(MF_STRING,MP_HM_OPENINC, GetResString(IDS_OPENINC) + _T("..."), _T("INCOMING"));
// >> add by Ken
menu.AppendMenu(MF_STRING,MP_HM_OPENGIFC, GetResString(IDS_OPENGIFC) + _T("..."), _T("INGIFC"));
if (!thePrefs.IsLessControls()) {
// << add by Ken
menu.AppendMenu(MF_STRING,MP_HM_CONVERTPF, GetResString(IDS_IMPORTSPLPF) + _T("..."), _T("CONVERT"));
menu.AppendMenu(MF_STRING,MP_HM_1STSWIZARD, GetResString(IDS_WIZ1) + _T("..."), _T("WIZARD"));
menu.AppendMenu(MF_STRING,MP_HM_IPFILTER, GetResString(IDS_IPFILTER) + _T("..."), _T("IPFILTER"));
// >> add by Ken
}
// << add by Ken
menu.AppendMenu(MF_STRING,MP_HM_DIRECT_DOWNLOAD, GetResString(IDS_SW_DIRECTDOWNLOAD) + _T("..."), _T("PASTELINK"));
menu.AppendMenu(MF_SEPARATOR);
// >> GIFC menu - add by Ken
bool gifcEnable = !(!theApp.serverconnect->IsConnected() && (!Kademlia::CKademlia::IsRunning() || !Kademlia::CKademlia::IsConnected()));
menu.AppendMenu(MF_STRING|(gifcEnable?MF_ENABLED:MF_GRAYED), MP_HM_GIFC, GetResString(IDS_GIFC), _T("GIFC"));
menu.AppendMenu(MF_STRING|(gifcEnable?MF_ENABLED:MF_GRAYED), MP_HM_GIFC1, GetResString(IDS_GIFC1) + _T("..."), _T("GIFC1"));
menu.AppendMenu(MF_SEPARATOR);
menu.AppendMenu(MF_STRING|(thePrefs.IsLessControls()?MF_CHECKED:MF_UNCHECKED), MP_HM_SHOWLESS, GetResString(IDS_SHOWLESS), _T("SHOWLESS"));
menu.AppendMenu(MF_STRING|(!thePrefs.IsLessControls()&&!thePrefs.IsExtControlsEnabled())?MF_CHECKED:MF_UNCHECKED, MP_HM_SHOWMORE, GetResString(IDS_SHOWMORE), _T("SHOWMORE"));
menu.AppendMenu(MF_STRING|(!thePrefs.IsLessControls()&&thePrefs.IsExtControlsEnabled())?MF_CHECKED:MF_UNCHECKED, MP_HM_SHOWEXT, GetResString(IDS_SHOWEXT), _T("SHOWEXT"));
if (!thePrefs.IsLessControls()) {
menu.AppendMenu(MF_SEPARATOR);
// << add by Ken
menu.AppendMenu(MF_STRING|MF_POPUP,(UINT_PTR)Links.m_hMenu, GetResString(IDS_LINKS), _T("WEB") );
menu.AppendMenu(MF_STRING|MF_POPUP,(UINT_PTR)scheduler.m_hMenu, GetResString(IDS_SCHEDULER), _T("SCHEDULER") );
// >> add by Ken
}
// << add by Ken
if (!toolsonly) {
menu.AppendMenu(MF_SEPARATOR);
menu.AppendMenu(MF_STRING,MP_HM_EXIT, GetResString(IDS_EXIT), _T("EXIT"));
}
menu.TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, point.x, point.y, this);
VERIFY( Links.DestroyMenu() );
VERIFY( scheduler.DestroyMenu() );
VERIFY( menu.DestroyMenu() );
}
void CemuleDlg::ApplyHyperTextFont(LPLOGFONT plf)
{
theApp.m_fontHyperText.DeleteObject();
if (theApp.m_fontHyperText.CreateFontIndirect(plf))
{
thePrefs.SetHyperTextFont(plf);
serverwnd->servermsgbox->SetFont(&theApp.m_fontHyperText);
chatwnd->chatselector.UpdateFonts(&theApp.m_fontHyperText);
ircwnd->UpdateFonts(&theApp.m_fontHyperText);
}
}
void CemuleDlg::ApplyLogFont(LPLOGFONT plf)
{
theApp.m_fontLog.DeleteObject();
if (theApp.m_fontLog.CreateFontIndirect(plf))
{
thePrefs.SetLogFont(plf);
serverwnd->logbox->SetFont(&theApp.m_fontLog);
serverwnd->debuglog->SetFont(&theApp.m_fontLog);
serverwnd->leecherlog->SetFont(&theApp.m_fontLog); //Xman Anti-Leecher-Log
}
}
LRESULT CemuleDlg::OnFrameGrabFinished(WPARAM wParam,LPARAM lParam){
CKnownFile* pOwner = (CKnownFile*)wParam;
FrameGrabResult_Struct* result = (FrameGrabResult_Struct*)lParam;
//MORPH START - Added by SiRoB, Fix crash at shutdown
if (theApp.m_app_state != APP_STATE_SHUTTINGDOWN) {
//MORPH END - Added by SiRoB, Fix crash at shutdown
if (theApp.knownfiles->IsKnownFile(pOwner) || theApp.downloadqueue->IsPartFile(pOwner) ){
pOwner->GrabbingFinished(result->imgResults,result->nImagesGrabbed, result->pSender);
}
else{
ASSERT ( false );
}
}//MORPH - Added by SiRoB, Fix crash at shutdown
delete result;
return 0;
}
void StraightWindowStyles(CWnd* pWnd)
{
CWnd* pWndChild = pWnd->GetWindow(GW_CHILD);
while (pWndChild)
{
StraightWindowStyles(pWndChild);
pWndChild = pWndChild->GetNextWindow();
}
CHAR szClassName[MAX_PATH];
if (::GetClassNameA(*pWnd, szClassName, _countof(szClassName)))
{
if (__ascii_stricmp(szClassName, "Button") == 0)
pWnd->ModifyStyle(BS_FLAT, 0);
else if ( (__ascii_stricmp(szClassName, "EDIT") == 0 && (pWnd->GetExStyle() & WS_EX_STATICEDGE))
|| __ascii_stricmp(szClassName, "SysListView32") == 0
|| __ascii_stricmp(szClassName, "msctls_trackbar32") == 0
)
{
pWnd->ModifyStyleEx(WS_EX_STATICEDGE, WS_EX_CLIENTEDGE);
}
//else if (__ascii_stricmp(szClassName, "SysTreeView32") == 0)
//{
// pWnd->ModifyStyleEx(WS_EX_STATICEDGE, WS_EX_CLIENTEDGE);
//}
}
}
void ApplySystemFont(CWnd* pWnd)
{
CWnd* pWndChild = pWnd->GetWindow(GW_CHILD);
while (pWndChild)
{
ApplySystemFont(pWndChild);
pWndChild = pWndChild->GetNextWindow();
}
CHAR szClassName[MAX_PATH];
if (::GetClassNameA(*pWnd, szClassName, _countof(szClassName)))
{
if ( __ascii_stricmp(szClassName, "SysListView32") == 0
|| __ascii_stricmp(szClassName, "SysTreeView32") == 0)
{
pWnd->SendMessage(WM_SETFONT, NULL, FALSE);
}
}
}
static bool s_bIsXPStyle;
void FlatWindowStyles(CWnd* pWnd)
{
CWnd* pWndChild = pWnd->GetWindow(GW_CHILD);
while (pWndChild)
{
FlatWindowStyles(pWndChild);
pWndChild = pWndChild->GetNextWindow();
}
CHAR szClassName[MAX_PATH];
if (::GetClassNameA(*pWnd, szClassName, _countof(szClassName)))
{
if (__ascii_stricmp(szClassName, "Button") == 0)
{
if (!s_bIsXPStyle || (pWnd->GetStyle() & BS_ICON) == 0)
pWnd->ModifyStyle(0, BS_FLAT);
}
else if (__ascii_stricmp(szClassName, "SysListView32") == 0)
{
pWnd->ModifyStyleEx(WS_EX_CLIENTEDGE, WS_EX_STATICEDGE);
}
else if (__ascii_stricmp(szClassName, "SysTreeView32") == 0)
{
pWnd->ModifyStyleEx(WS_EX_CLIENTEDGE, WS_EX_STATICEDGE);
}
}
}
void InitWindowStyles(CWnd* pWnd)
{
//ApplySystemFont(pWnd);
if (thePrefs.GetStraightWindowStyles() < 0)
return;
else if (thePrefs.GetStraightWindowStyles() > 0)
/*StraightWindowStyles(pWnd)*/; // no longer needed
else
{
s_bIsXPStyle = g_xpStyle.IsAppThemed() && g_xpStyle.IsThemeActive();
if (!s_bIsXPStyle)
FlatWindowStyles(pWnd);
}
}
LRESULT CemuleDlg::OnVersionCheckResponse(WPARAM /*wParam*/, LPARAM lParam)
{
if (WSAGETASYNCERROR(lParam) == 0)
{
int iBufLen = WSAGETASYNCBUFLEN(lParam);
if (iBufLen >= sizeof(HOSTENT))
{
LPHOSTENT pHost = (LPHOSTENT)m_acVCDNSBuffer;
if (pHost->h_length == 4 && pHost->h_addr_list && pHost->h_addr_list[0])
{
uint32 dwResult = ((LPIN_ADDR)(pHost->h_addr_list[0]))->s_addr;
// last byte contains informations about mirror urls, to avoid effects of future DDoS Attacks against eMules Homepage
thePrefs.SetWebMirrorAlertLevel((uint8)(dwResult >> 24));
uint8 abyCurVer[4] = { (uint8)(CemuleApp::m_nVersionBld + 1), (uint8)(CemuleApp::m_nVersionUpd), (uint8)(CemuleApp::m_nVersionMin), (uint8)0};
dwResult &= 0x00FFFFFF;
if (dwResult > *(uint32*)abyCurVer){
if(theApp.IsSplash()) theApp.DestroySplash(); //Xman new slpash-screen arrangement
SetActiveWindow();
#ifndef _BETA
Log(LOG_SUCCESS|LOG_STATUSBAR,GetResString(IDS_NEWVERSIONAVL));
ShowNotifier(GetResString(IDS_NEWVERSIONAVLPOPUP), TBN_NEWVERSION);
thePrefs.UpdateLastVC();
if (!thePrefs.GetNotifierOnNewVersion()){
if (AfxMessageBox(GetResString(IDS_NEWVERSIONAVL)+GetResString(IDS_VISITVERSIONCHECK),MB_YESNO)==IDYES) {
CString theUrl;
theUrl.Format(_T("/en/version_check.php?version=%i&language=%i"),theApp.m_uCurVersionCheck,thePrefs.GetLanguageID());
theUrl = thePrefs.GetVersionCheckBaseURL()+theUrl;
ShellExecute(NULL, NULL, theUrl, NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
}
}
#else
Log(LOG_SUCCESS|LOG_STATUSBAR,GetResString(IDS_NEWVERSIONAVLBETA));
if (AfxMessageBox(GetResString(IDS_NEWVERSIONAVLBETA)+GetResString(IDS_VISITVERSIONCHECK),MB_OK)==IDOK) {
CString theUrl;
theUrl = _T("/beta");
theUrl = thePrefs.GetVersionCheckBaseURL()+theUrl;
ShellExecute(NULL, NULL, theUrl, NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
}
#endif
}
else{
thePrefs.UpdateLastVC();
AddLogLine(true,GetResString(IDS_NONEWERVERSION));
}
return 0;
}
}
}
LogWarning(LOG_STATUSBAR,GetResString(IDS_NEWVERSIONFAILED));
return 0;
}
//Xman new slpash-screen arrangement
//moved to emule.cpp
/*
void CemuleDlg::ShowSplash()
{
ASSERT( m_pSplashWnd == NULL );
if (m_pSplashWnd == NULL)
{
m_pSplashWnd = new CSplashScreen;
if (m_pSplashWnd != NULL)
{
ASSERT(m_hWnd);
if (m_pSplashWnd->Create(CSplashScreen::IDD, this))
{
m_pSplashWnd->ShowWindow(SW_SHOW);
m_pSplashWnd->UpdateWindow();
m_dwSplashTime = ::GetCurrentTime();
}
else
{
delete m_pSplashWnd;
m_pSplashWnd = NULL;
}
}
}
}
void CemuleDlg::DestroySplash()
{
if (m_pSplashWnd != NULL)
{
m_pSplashWnd->DestroyWindow();
delete m_pSplashWnd;
m_pSplashWnd = NULL;
}
#ifdef _BETA
if (!thePrefs.IsFirstStart())
AfxMessageBox(GetResString(IDS_BETANAG), MB_ICONINFORMATION | MB_OK, 0);
#endif
}
*/
//Xman end
BOOL CemuleApp::IsIdleMessage(MSG *pMsg)
{
// This function is closely related to 'CemuleDlg::OnKickIdle'.
//
// * See MFC source code for 'CWnd::RunModalLoop' to see how those functions are related
// to each other.
//
// * See MFC documentation for 'CWnd::IsIdleMessage' to see why WM_TIMER messages are
// filtered here.
//
// Generally we want to filter WM_TIMER messages because they are triggering idle
// processing (e.g. cleaning up temp. MFC maps) and because they are occuring very often
// in eMule (we have a rather high frequency timer in upload queue). To save CPU load but
// do not miss the chance to cleanup MFC temp. maps and other stuff, we do not use each
// occuring WM_TIMER message -- that would just be overkill! However, we can not simply
// filter all WM_TIMER messages. If eMule is running in taskbar the only messages which
// are received by main window are those WM_TIMER messages, thus those messages are the
// only chance to trigger some idle processing. So, we must use at last some of those
// messages because otherwise we would not do any idle processing at all in some cases.
//
static DWORD s_dwLastIdleMessage;
if (pMsg->message == WM_TIMER)
{
// Allow this WM_TIMER message to trigger idle processing only if we did not do so
// since some seconds.
DWORD dwNow = GetTickCount();
if (dwNow - s_dwLastIdleMessage >= SEC2MS(5))
{
s_dwLastIdleMessage = dwNow;
return TRUE;// Request idle processing (will send a WM_KICKIDLE)
}
return FALSE; // No idle processing
}
if (!CWinApp::IsIdleMessage(pMsg))
return FALSE; // No idle processing
s_dwLastIdleMessage = GetTickCount();
return TRUE; // Request idle processing (will send a WM_KICKIDLE)
}
LRESULT CemuleDlg::OnKickIdle(UINT /*nWhy*/, long lIdleCount)
{
LRESULT lResult = 0;
//Xman new slpash-screen arrangement
/*
if (m_pSplashWnd)
{
if (::GetCurrentTime() - m_dwSplashTime > 2500)
{
// timeout expired, destroy the splash window
DestroySplash();
*/
if (theApp.IsSplash() && theApp.spashscreenfinished)
{
if (::GetCurrentTime() - theApp.m_dwSplashTime > 3500)
{
// timeout expired, destroy the splash window
theApp.DestroySplash();
//Xman end
UpdateWindow();
}
else
{
// check again later...
lResult = 1;
}
}
if (m_bStartMinimized)
PostStartupMinimized();
if (searchwnd && searchwnd->m_hWnd)
{
if (theApp.m_app_state != APP_STATE_SHUTTINGDOWN)
{
//#ifdef _DEBUG
// TCHAR szDbg[80];
// wsprintf(szDbg, L"%10u: lIdleCount=%d, %s", GetTickCount(), lIdleCount, (lIdleCount > 0) ? L"FreeTempMaps" : L"");
// SetWindowText(szDbg);
// TRACE(_T("%s\n"), szDbg);
//#endif
// NOTE: See also 'CemuleApp::IsIdleMessage'. If 'CemuleApp::IsIdleMessage'
// would not filter most of the WM_TIMER messages we might get a performance
// problem here because the idle processing would be performed very, very often.
//
// The default MFC implementation of 'CWinApp::OnIdle' is sufficient for us. We
// will get called with 'lIdleCount=0' and with 'lIdleCount=1'.
//
// CWinApp::OnIdle(0) takes care about pending MFC GUI stuff and returns 'TRUE'
// to request another invocation to perform more idle processing
// CWinApp::OnIdle(>=1) frees temporary internally MFC maps and returns 'FALSE'
// because no more idle processing is needed.
//Xman Code Improvement
//enough to clean up handle maps every minute
/*
lResult = theApp.OnIdle(lIdleCount);
*/
static uint32 lastprocess;
if(lIdleCount>0)
{
theApp.OnIdle(lIdleCount); //free maps
lastprocess=::GetTickCount();
return 0;
}
if(theApp.OnIdle(0 /*lIdleCount*/) && ::GetTickCount() - lastprocess > MIN2MS(1))
lResult=1;
else
lResult=0;
//Xman end
}
}
return lResult;
}
int CemuleDlg::MapWindowToToolbarButton(CWnd* pWnd) const
{
int iButtonID = -1;
if (pWnd == transferwnd) iButtonID = TBBTN_TRANSFERS;
else if (pWnd == serverwnd) iButtonID = TBBTN_SERVER;
else if (pWnd == chatwnd) iButtonID = TBBTN_MESSAGES;
else if (pWnd == ircwnd) iButtonID = TBBTN_IRC;
else if (pWnd == sharedfileswnd)iButtonID = TBBTN_SHARED;
else if (pWnd == searchwnd) iButtonID = TBBTN_SEARCH;
else if (pWnd == statisticswnd) iButtonID = TBBTN_STATS;
else if (pWnd == kademliawnd) iButtonID = TBBTN_KAD;
else ASSERT(0);
return iButtonID;
}
CWnd* CemuleDlg::MapToolbarButtonToWindow(int iButtonID) const
{
CWnd* pWnd;
switch (iButtonID)
{
case TBBTN_TRANSFERS: pWnd = transferwnd; break;
case TBBTN_SERVER: pWnd = serverwnd; break;
case TBBTN_MESSAGES: pWnd = chatwnd; break;
case TBBTN_IRC: pWnd = ircwnd; break;
case TBBTN_SHARED: pWnd = sharedfileswnd; break;
case TBBTN_SEARCH: pWnd = searchwnd; break;
case TBBTN_STATS: pWnd = statisticswnd; break;
case TBBTN_KAD: pWnd = kademliawnd; break;
default: pWnd = NULL; ASSERT(0);
}
return pWnd;
}
bool CemuleDlg::IsWindowToolbarButton(int iButtonID) const
{
switch (iButtonID)
{
case TBBTN_TRANSFERS: return true;
case TBBTN_SERVER: return true;
case TBBTN_MESSAGES: return true;
case TBBTN_IRC: return true;
case TBBTN_SHARED: return true;
case TBBTN_SEARCH: return true;
case TBBTN_STATS: return true;
case TBBTN_KAD: return true;
}
return false;
}
int CemuleDlg::GetNextWindowToolbarButton(int iButtonID, int iDirection) const
{
ASSERT( iDirection == 1 || iDirection == -1 );
int iButtonCount = toolbar->GetButtonCount();
if (iButtonCount > 0)
{
int iButtonIdx = toolbar->CommandToIndex(iButtonID);
if (iButtonIdx >= 0 && iButtonIdx < iButtonCount)
{
int iEvaluatedButtons = 0;
while (iEvaluatedButtons < iButtonCount)
{
iButtonIdx = iButtonIdx + iDirection;
if (iButtonIdx < 0)
iButtonIdx = iButtonCount - 1;
else if (iButtonIdx >= iButtonCount)
iButtonIdx = 0;
TBBUTTON tbbt = {0};
if (toolbar->GetButton(iButtonIdx, &tbbt))
{
if (IsWindowToolbarButton(tbbt.idCommand))
return tbbt.idCommand;
}
iEvaluatedButtons++;
}
}
}
return -1;
}
BOOL CemuleDlg::PreTranslateMessage(MSG* pMsg)
{
BOOL bResult = CTrayDialog::PreTranslateMessage(pMsg);
//Xman new slpash-screen arrangement
/*
if (m_pSplashWnd && m_pSplashWnd->m_hWnd != NULL &&
*/
if (theApp.IsSplash() &&
//Xman end
(pMsg->message == WM_KEYDOWN ||
pMsg->message == WM_SYSKEYDOWN ||
pMsg->message == WM_LBUTTONDOWN ||
pMsg->message == WM_RBUTTONDOWN ||
pMsg->message == WM_MBUTTONDOWN ||
pMsg->message == WM_NCLBUTTONDOWN ||
pMsg->message == WM_NCRBUTTONDOWN ||
pMsg->message == WM_NCMBUTTONDOWN))
{
//Xman new slpash-screen arrangement
/*
DestroySplash();
*/
theApp.DestroySplash();
//Xman end
UpdateWindow();
}
else
{
if (pMsg->message == WM_KEYDOWN)
{
// Handle Ctrl+Tab and Ctrl+Shift+Tab
if (pMsg->wParam == VK_TAB && GetAsyncKeyState(VK_CONTROL) < 0)
{
int iButtonID = MapWindowToToolbarButton(activewnd);
if (iButtonID != -1)
{
int iNextButtonID = GetNextWindowToolbarButton(iButtonID, GetAsyncKeyState(VK_SHIFT) < 0 ? -1 : 1);
if (iNextButtonID != -1)
{
CWnd* pWndNext = MapToolbarButtonToWindow(iNextButtonID);
if (pWndNext)
SetActiveDialog(pWndNext);
}
}
}
}
}
return bResult;
}
void CemuleDlg::HtmlHelp(DWORD_PTR dwData, UINT nCmd)
{
CWinApp* pApp = AfxGetApp();
ASSERT_VALID(pApp);
ASSERT(pApp->m_pszHelpFilePath != NULL);
// to call HtmlHelp the m_fUseHtmlHelp must be set in
// the application's constructor
ASSERT(pApp->m_eHelpType == afxHTMLHelp);
CWaitCursor wait;
PrepareForHelp();
// need to use top level parent (for the case where m_hWnd is in DLL)
CWnd* pWnd = GetTopLevelParent();
TRACE(traceAppMsg, 0, _T("HtmlHelp: pszHelpFile = '%s', dwData: $%lx, fuCommand: %d.\n"), pApp->m_pszHelpFilePath, dwData, nCmd);
bool bHelpError = false;
CString strHelpError;
int iTry = 0;
while (iTry++ < 2)
{
if (!AfxHtmlHelp(pWnd->m_hWnd, pApp->m_pszHelpFilePath, nCmd, dwData))
{
bHelpError = true;
strHelpError.LoadString(AFX_IDP_FAILED_TO_LAUNCH_HELP);
typedef struct tagHH_LAST_ERROR
{
int cbStruct;
HRESULT hr;
BSTR description;
} HH_LAST_ERROR;
HH_LAST_ERROR hhLastError = {0};
hhLastError.cbStruct = sizeof hhLastError;
HWND hwndResult = AfxHtmlHelp(pWnd->m_hWnd, NULL, HH_GET_LAST_ERROR, reinterpret_cast<DWORD>(&hhLastError));
if (hwndResult != 0)
{
if (FAILED(hhLastError.hr))
{
if (hhLastError.description)
{
strHelpError = hhLastError.description;
::SysFreeString(hhLastError.description);
}
if ( hhLastError.hr == 0x8004020A /*no topics IDs available in Help file*/
|| hhLastError.hr == 0x8004020B) /*requested Help topic ID not found*/
{
// try opening once again without help topic ID
if (nCmd != HH_DISPLAY_TOC)
{
nCmd = HH_DISPLAY_TOC;
dwData = 0;
continue;
}
}
}
}
break;
}
else
{
bHelpError = false;
strHelpError.Empty();
break;
}
}
if (bHelpError)
{
if (AfxMessageBox(CString(pApp->m_pszHelpFilePath) + _T("\n\n") + strHelpError + _T("\n\n") + GetResString(IDS_ERR_NOHELP), MB_YESNO | MB_ICONERROR) == IDYES)
{
CString strUrl = thePrefs.GetHomepageBaseURL() + _T("/home/perl/help.cgi");
ShellExecute(NULL, NULL, strUrl, NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
}
}
}
LRESULT CemuleDlg::OnPeerCacheResponse(WPARAM wParam, LPARAM lParam)
{
return theApp.m_pPeerCache->OnPeerCacheCheckResponse(wParam,lParam);
}
void CemuleDlg::CreateToolbarCmdIconMap()
{
m_mapTbarCmdToIcon.SetAt(TBBTN_CONNECT, _T("Connect"));
m_mapTbarCmdToIcon.SetAt(TBBTN_KAD, _T("Kademlia"));
m_mapTbarCmdToIcon.SetAt(TBBTN_SERVER, _T("Server"));
m_mapTbarCmdToIcon.SetAt(TBBTN_TRANSFERS, _T("Transfer"));
m_mapTbarCmdToIcon.SetAt(TBBTN_SEARCH, _T("Search"));
m_mapTbarCmdToIcon.SetAt(TBBTN_SHARED, _T("SharedFiles"));
m_mapTbarCmdToIcon.SetAt(TBBTN_MESSAGES, _T("Messages"));
m_mapTbarCmdToIcon.SetAt(TBBTN_IRC, _T("IRC"));
m_mapTbarCmdToIcon.SetAt(TBBTN_STATS, _T("Statistics"));
m_mapTbarCmdToIcon.SetAt(TBBTN_OPTIONS, _T("Preferences"));
m_mapTbarCmdToIcon.SetAt(TBBTN_TOOLS, _T("Tools"));
m_mapTbarCmdToIcon.SetAt(TBBTN_HELP, _T("Help"));
}
LPCTSTR CemuleDlg::GetIconFromCmdId(UINT uId)
{
LPCTSTR pszIconId = NULL;
if (m_mapTbarCmdToIcon.Lookup(uId, pszIconId))
return pszIconId;
return NULL;
}
BOOL CemuleDlg::OnChevronPushed(UINT id, NMHDR* pNMHDR, LRESULT* plResult)
{
UNREFERENCED_PARAMETER(id);
if (!thePrefs.GetUseReBarToolbar())
return FALSE;
NMREBARCHEVRON* pnmrc = (NMREBARCHEVRON*)pNMHDR;
ASSERT( id == AFX_IDW_REBAR );
ASSERT( pnmrc->uBand == 0 );
ASSERT( pnmrc->wID == 0 );
ASSERT( m_mapTbarCmdToIcon.GetSize() != 0 );
// get visible area of rebar/toolbar
CRect rcVisibleButtons;
toolbar->GetClientRect(&rcVisibleButtons);
// search the first toolbar button which is not fully visible
int iButtons = toolbar->GetButtonCount();
int i;
for (i = 0; i < iButtons; i++)
{
CRect rcButton;
toolbar->GetItemRect(i, &rcButton);
CRect rcVisible;
if (!rcVisible.IntersectRect(&rcVisibleButtons, &rcButton) || !EqualRect(rcButton, rcVisible))
break;
}
// create menu for all toolbar buttons which are not (fully) visible
BOOL bLastMenuItemIsSep = TRUE;
CTitleMenu menu;
menu.CreatePopupMenu();
menu.AddMenuTitle(_T("eMule"), true);
while (i < iButtons)
{
TCHAR szString[256];
szString[0] = _T('\0');
TBBUTTONINFO tbbi = {0};
tbbi.cbSize = sizeof tbbi;
tbbi.dwMask = TBIF_BYINDEX | TBIF_COMMAND | TBIF_STYLE | TBIF_STATE | TBIF_TEXT;
tbbi.cchText = _countof(szString);
tbbi.pszText = szString;
if (toolbar->GetButtonInfo(i, &tbbi) != -1)
{
szString[_countof(szString) - 1] = _T('\0');
if (tbbi.fsStyle & TBSTYLE_SEP)
{
if (!bLastMenuItemIsSep)
bLastMenuItemIsSep = menu.AppendMenu(MF_SEPARATOR, 0, (LPCTSTR)NULL);
}
else
{
if (szString[0] != _T('\0') && menu.AppendMenu(MF_STRING, tbbi.idCommand, szString, GetIconFromCmdId(tbbi.idCommand)))
{
bLastMenuItemIsSep = FALSE;
if (tbbi.fsState & TBSTATE_CHECKED)
menu.CheckMenuItem(tbbi.idCommand, MF_BYCOMMAND | MF_CHECKED);
if ((tbbi.fsState & TBSTATE_ENABLED) == 0)
menu.EnableMenuItem(tbbi.idCommand, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
}
}
}
i++;
}
CPoint ptMenu(pnmrc->rc.left, pnmrc->rc.top);
ClientToScreen(&ptMenu);
ptMenu.y += rcVisibleButtons.Height();
menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_TOPALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, ptMenu.x, ptMenu.y, this);
VERIFY( menu.DestroyMenu() ); // XP Style Menu [Xanatos] - Stulle
*plResult = 1;
return FALSE;
}
bool CemuleDlg::IsPreferencesDlgOpen() const
{
return (preferenceswnd->m_hWnd != NULL);
}
int CemuleDlg::ShowPreferences(UINT uStartPageID)
{
if (IsPreferencesDlgOpen())
{
preferenceswnd->SetForegroundWindow();
preferenceswnd->BringWindowToTop();
return -1;
}
else
{
if (uStartPageID != (UINT)-1)
preferenceswnd->SetStartPage(uStartPageID);
return preferenceswnd->DoModal();
}
}
//////////////////////////////////////////////////////////////////
// Webserver related
LRESULT CemuleDlg::OnWebAddDownloads(WPARAM wParam, LPARAM lParam)
{
CString link=CString((TCHAR*)wParam);
if (link.GetLength()==32 && link.Left(4).CompareNoCase(_T("ed2k"))!=0) {
uchar fileid[16];
DecodeBase16(link, link.GetLength(), fileid, _countof(fileid));
theApp.searchlist->AddFileToDownloadByHash(fileid,(uint8)lParam);
} else
theApp.AddEd2kLinksToDownload((TCHAR*)wParam, (int)lParam);
return 0;
}
LRESULT CemuleDlg::OnAddRemoveFriend(WPARAM wParam, LPARAM lParam)
{
if (lParam==0) { // remove
theApp.friendlist->RemoveFriend((CFriend*)wParam);
} else { // add
theApp.friendlist->AddFriend((CUpDownClient*)wParam);
}
return 0;
}
LRESULT CemuleDlg::OnWebSetCatPrio(WPARAM wParam, LPARAM lParam)
{
theApp.downloadqueue->SetCatPrio(wParam,(uint8)lParam);
return 0;
}
LRESULT CemuleDlg::OnWebServerClearCompleted(WPARAM wParam, LPARAM lParam)
{
if(!wParam)
{
int cat=(int)lParam;
transferwnd->GetDownloadList()->ClearCompleted(cat);
}
else
{
uchar* pFileHash = reinterpret_cast<uchar*>(lParam);
CKnownFile* file=theApp.knownfiles->FindKnownFileByID(pFileHash);
if (file)
transferwnd->GetDownloadList()->RemoveFile((CPartFile*)file);
delete[] pFileHash;
}
return 0;
}
LRESULT CemuleDlg::OnWebServerFileRename(WPARAM wParam, LPARAM lParam)
{
CString sNewName = ((LPCTSTR)(lParam));
((CPartFile*)wParam)->SetFileName(sNewName);
((CPartFile*)wParam)->SavePartFile();
((CPartFile*)wParam)->UpdateDisplayedInfo();
sharedfileswnd->sharedfilesctrl.UpdateFile( (CKnownFile*)((CPartFile*)wParam));
return 0;
}
LRESULT CemuleDlg::OnWebGUIInteraction(WPARAM wParam, LPARAM lParam) {
switch (wParam) {
case WEBGUIIA_UPDATEMYINFO:
serverwnd->UpdateMyInfo();
break;
case WEBGUIIA_WINFUNC:{
// ==> Ionix advanced (multiuser) webserver [iOniX/Aireoreion/wizard/leuk_he/Stulle] - Stulle
// There should be no need for this as we check before sending the message.
// However, we do this all a little complicated to be sure that settings did not change
// during the webserver session and we allow something that should not be allowed.
/*
if (thePrefs.GetWebAdminAllowedHiLevFunc())
*/
bool bIsHiAdmin = false;
if (thePrefs.UseIonixWebsrv())
{
bIsHiAdmin = (lParam&4) ? true : false;
lParam &= 3;
}
else if (thePrefs.GetWebAdminAllowedHiLevFunc())
bIsHiAdmin = true;
if (bIsHiAdmin)
// <== Ionix advanced (multiuser) webserver [iOniX/Aireoreion/wizard/leuk_he/Stulle] - Stulle
{
try {
HANDLE hToken;
TOKEN_PRIVILEGES tkp; // Get a token for this process.
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
throw;
LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1; // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; // Get the shutdown privilege for this process.
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, (PTOKEN_PRIVILEGES)NULL, 0);
if (lParam==1) { // shutdown
ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, 0);
} else
if (lParam==2) {
ExitWindowsEx(EWX_REBOOT | EWX_FORCE, 0);
}
} catch(...)
{
AddLogLine(true, GetResString(IDS_WEB_REBOOT) + _T(' ') + GetResString(IDS_FAILED));
}
}
else
AddLogLine(true, GetResString(IDS_WEB_REBOOT) + _T(' ') + GetResString(IDS_ACCESSDENIED));
break;
}
case WEBGUIIA_UPD_CATTABS:
theApp.emuledlg->transferwnd->UpdateCatTabTitles();
break;
case WEBGUIIA_UPD_SFUPDATE: {
CKnownFile* kf=(CKnownFile*)lParam;
if (kf)
theApp.sharedfiles->UpdateFile(kf);
}
break;
case WEBGUIIA_UPDATESERVER:
serverwnd->serverlistctrl.RefreshServer((CServer*)lParam);
break;
case WEBGUIIA_STOPCONNECTING:
theApp.serverconnect->StopConnectionTry();
break;
case WEBGUIIA_CONNECTTOSERVER: {
CServer* server=(CServer*)lParam;
if (server==NULL)
theApp.serverconnect->ConnectToAnyServer();
else
theApp.serverconnect->ConnectToServer(server);
break;
}
case WEBGUIIA_DISCONNECT:
if (lParam!=2) // !KAD
theApp.serverconnect->Disconnect();
if (lParam!=1) // !ED2K
Kademlia::CKademlia::Stop();
break;
case WEBGUIIA_SERVER_REMOVE: {
serverwnd->serverlistctrl.RemoveServer((CServer*)lParam);
break;
}
case WEBGUIIA_SHARED_FILES_RELOAD: {
theApp.sharedfiles->Reload();
break;
}
case WEBGUIIA_ADD_TO_STATIC: {
serverwnd->serverlistctrl.StaticServerFileAppend((CServer*)lParam);
break;
}
case WEBGUIIA_REMOVE_FROM_STATIC: {
serverwnd->serverlistctrl.StaticServerFileRemove((CServer*)lParam);
break;
}
case WEBGUIIA_UPDATESERVERMETFROMURL:
theApp.emuledlg->serverwnd->UpdateServerMetFromURL((TCHAR*)lParam);
break;
case WEBGUIIA_SHOWSTATISTICS:
theApp.emuledlg->statisticswnd->ShowStatistics(lParam!=0);
break;
case WEBGUIIA_DELETEALLSEARCHES:
theApp.emuledlg->searchwnd->DeleteAllSearches();
break;
case WEBGUIIA_KAD_BOOTSTRAP:{
CString dest=CString((TCHAR*)lParam);
int pos=dest.Find(_T(':'));
if (pos!=-1) {
uint16 port = (uint16)_tstoi(dest.Right(dest.GetLength() - pos - 1));
CString ip = dest.Left(pos);
Kademlia::CKademlia::Bootstrap(ip, port);
}
break;
}
case WEBGUIIA_KAD_START:
Kademlia::CKademlia::Start();
break;
case WEBGUIIA_KAD_STOP:
Kademlia::CKademlia::Stop();
break;
case WEBGUIIA_KAD_RCFW:
Kademlia::CKademlia::RecheckFirewalled();
break;
}
return 0;
}
void CemuleDlg::TrayMinimizeToTrayChange()
{
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
if (!thePrefs.GetMinToTray())
{
// just for safety, ensure that we are not adding duplicate menu entries..
if (pSysMenu->EnableMenuItem(MP_MINIMIZETOTRAY, MF_BYCOMMAND | MF_ENABLED) == -1)
{
ASSERT( (MP_MINIMIZETOTRAY & 0xFFF0) == MP_MINIMIZETOTRAY && MP_MINIMIZETOTRAY < 0xF000);
VERIFY( pSysMenu->InsertMenu(SC_MINIMIZE, MF_BYCOMMAND, MP_MINIMIZETOTRAY, GetResString(IDS_PW_TRAY)) );
}
else
ASSERT(0);
}
else
{
(void)pSysMenu->RemoveMenu(MP_MINIMIZETOTRAY, MF_BYCOMMAND);
}
}
CTrayDialog::TrayMinimizeToTrayChange();
}
void CemuleDlg::SetToolTipsDelay(UINT uMilliseconds)
{
//searchwnd->SetToolTipsDelay(uMilliseconds);
transferwnd->SetToolTipsDelay(uMilliseconds);
sharedfileswnd->SetToolTipsDelay(uMilliseconds);
}
// ==> UPnP support [MoNKi] - leuk_he
//void CemuleDlg::UPnPTimeOutTimer(HWND /*hwnd*/, UINT /*uiMsg*/, UINT /*idEvent*/, DWORD /*dwTime*/){
/*
::PostMessage(theApp.emuledlg->GetSafeHwnd(), UM_UPNP_RESULT, (WPARAM)CUPnPImpl::UPNP_TIMEOUT, 0);
}
LRESULT CemuleDlg::OnUPnPResult(WPARAM wParam, LPARAM lParam){
#ifdef DUAL_UPNP //zz_fly :: dual upnp
if (thePrefs.m_bUseACATUPnPCurrent)
return 0;
#endif //zz_fly :: dual upnp
bool bWasRefresh = lParam != 0;
if (!bWasRefresh && wParam == CUPnPImpl::UPNP_FAILED){
// UPnP failed, check if we can retry it with another implementation
if (theApp.m_pUPnPFinder->SwitchImplentation()){
StartUPnP(false);
return 0;
}
else
DebugLog(_T("No more available UPnP implementations left"));
}
if (m_hUPnPTimeOutTimer != 0){
VERIFY( ::KillTimer(NULL, m_hUPnPTimeOutTimer) );
m_hUPnPTimeOutTimer = 0;
}
if(IsRunning() && m_bConnectRequestDelayedForUPnP){
StartConnection();
}
if (!bWasRefresh && wParam == CUPnPImpl::UPNP_OK){
// remember the last working implementation
thePrefs.SetLastWorkingUPnPImpl(theApp.m_pUPnPFinder->GetImplementation()->GetImplementationID());
Log(GetResString(IDS_UPNPSUCCESS), theApp.m_pUPnPFinder->GetImplementation()->GetUsedTCPPort()
, theApp.m_pUPnPFinder->GetImplementation()->GetUsedUDPPort());
}
else if (!bWasRefresh)
LogWarning(GetResString(IDS_UPNPFAILED));
serverwnd->UpdateMyInfo(); //zz_fly :: show UPnP status
return 0;
}
*/
// <== UPnP support [MoNKi] - leuk_he
LRESULT CemuleDlg::OnPowerBroadcast(WPARAM wParam, LPARAM lParam)
{
//DebugLog(_T("DEBUG:Power state change. wParam=%d lPararm=%ld"),wParam,lParam);
switch (wParam) {
case PBT_APMRESUMEAUTOMATIC:
{
if (m_bEd2kSuspendDisconnect || m_bKadSuspendDisconnect)
{
DebugLog(_T("Reconnect after Power state change. wParam=%d lPararm=%ld"),wParam,lParam);
// ==> UPnP support [MoNKi] - leuk_he
/*
#ifdef DUAL_UPNP //zz_fly :: dual upnp
if(!thePrefs.m_bUseACATUPnPCurrent)
#endif //zz_fly :: dual upnp
RefreshUPnP(true);
*/
theApp.RebindUPnP();
// <== UPnP support [MoNKi] - leuk_he
PostMessage(WM_SYSCOMMAND , MP_CONNECT, 0); // tell to connect.. a sec later...
}
return TRUE; // message processed.
break;
}
case PBT_APMSUSPEND:
{
// ==> Proper English [ginger] - Stulle
/*
DebugLog(_T("System is going is suspending operation, disconnecting. wParam=%d lPararm=%ld"),wParam,lParam);
*/
DebugLog(_T("System is suspending operation, disconnecting. wParam=%d lPararm=%ld"),wParam,lParam);
// <== Proper English [ginger] - Stulle
m_bEd2kSuspendDisconnect = theApp.serverconnect->IsConnected();
m_bKadSuspendDisconnect = Kademlia::CKademlia::IsConnected();
CloseConnection();
return TRUE; // message processed.
break;
}
default:
return FALSE; // we do not process this message
}
}
// ==> UPnP support [MoNKi] - leuk_he
/*
void CemuleDlg::StartUPnP(bool bReset, uint16 nForceTCPPort, uint16 nForceUDPPort) {
#ifdef DUAL_UPNP //zz_fly :: dual upnp
if(thePrefs.m_bUseACATUPnPCurrent)
return;
#endif //zz_fly :: dual upnp
if (theApp.m_pUPnPFinder != NULL && (m_hUPnPTimeOutTimer == 0 || !bReset)){
if (bReset){
theApp.m_pUPnPFinder->Reset();
Log(GetResString(IDS_UPNPSETUP));
}
try
{
if (theApp.m_pUPnPFinder->GetImplementation()->IsReady()){
theApp.m_pUPnPFinder->GetImplementation()->SetMessageOnResult(GetSafeHwnd(), UM_UPNP_RESULT);
if (bReset)
VERIFY( (m_hUPnPTimeOutTimer = ::SetTimer(NULL, NULL, SEC2MS(40), UPnPTimeOutTimer)) != NULL );
theApp.m_pUPnPFinder->GetImplementation()->StartDiscovery(((nForceTCPPort != 0) ? nForceTCPPort : thePrefs.GetPort())
, ((nForceUDPPort != 0) ? nForceUDPPort :thePrefs.GetUDPPort())
, thePrefs.GetWSUseUPnP() ? thePrefs.GetWSPort() : 0);
}
else
::PostMessage(theApp.emuledlg->GetSafeHwnd(), UM_UPNP_RESULT, (WPARAM)CUPnPImpl::UPNP_FAILED, 0);
}
catch ( CUPnPImpl::UPnPError& ) {}
catch ( CException* e ) { e->Delete(); }
}
else
ASSERT( false );
}
void CemuleDlg::RefreshUPnP(bool bRequestAnswer)
{
#ifdef DUAL_UPNP //zz_fly :: dual upnp
if(thePrefs.m_bUseACATUPnPCurrent)
return;
#endif //zz_fly :: dual upnp
if (!thePrefs.IsUPnPEnabled())
return;
if (theApp.m_pUPnPFinder != NULL && m_hUPnPTimeOutTimer == 0){
try
{
if (theApp.m_pUPnPFinder->GetImplementation()->IsReady())
{
if (bRequestAnswer)
theApp.m_pUPnPFinder->GetImplementation()->SetMessageOnResult(GetSafeHwnd(), UM_UPNP_RESULT);
if (theApp.m_pUPnPFinder->GetImplementation()->CheckAndRefresh() && bRequestAnswer)
{
VERIFY( (m_hUPnPTimeOutTimer = ::SetTimer(NULL, NULL, SEC2MS(10), UPnPTimeOutTimer)) != NULL );
}
else
theApp.m_pUPnPFinder->GetImplementation()->SetMessageOnResult(0, 0);
}
else
DebugLogWarning(_T("RefreshUPnP, implementation not ready"));
}
catch ( CUPnPImpl::UPnPError& ) {}
catch ( CException* e ) { e->Delete(); }
}
else
ASSERT( false );
}
*/
// <== UPnP support [MoNKi] - leuk_he
BOOL CemuleDlg::OnDeviceChange(UINT nEventType, DWORD_PTR dwData)
{
// WM_DEVICECHANGE is sent for:
// Drives which where created/deleted with "SUBST" command (handled like network drives)
// Drives which where created/deleted as regular network drives.
//
// WM_DEVICECHANGE is *NOT* sent for:
// Floppy disk drives
// ZIP disk drives (although Windows Explorer recognizes a changed media, we do not get a message)
// CD-ROM drives (although MSDN says different...)
//
if ((nEventType == DBT_DEVICEARRIVAL || nEventType == DBT_DEVICEREMOVECOMPLETE) && !IsBadReadPtr((void *)dwData, sizeof(DEV_BROADCAST_HDR)))
{
#ifdef _DEBUG
CString strMsg;
if (nEventType == DBT_DEVICEARRIVAL)
strMsg += _T("DBT_DEVICEARRIVAL");
else if (nEventType == DBT_DEVICEREMOVECOMPLETE)
strMsg += _T("DBT_DEVICEREMOVECOMPLETE");
#endif
const DEV_BROADCAST_HDR *pHdr = (DEV_BROADCAST_HDR *)dwData;
if (pHdr->dbch_devicetype == DBT_DEVTYP_VOLUME && !IsBadReadPtr((void *)dwData, sizeof(DEV_BROADCAST_VOLUME)))
{
const DEV_BROADCAST_VOLUME *pVol = (DEV_BROADCAST_VOLUME *)pHdr;
#ifdef _DEBUG
strMsg += _T(" Volume");
if (pVol->dbcv_flags & DBTF_MEDIA)
strMsg += _T(" Media");
if (pVol->dbcv_flags & DBTF_NET)
strMsg += _T(" Net");
if ((pVol->dbcv_flags & ~(DBTF_NET | DBTF_MEDIA)) != 0)
strMsg.AppendFormat(_T(" flags=0x%08x"), pVol->dbcv_flags);
#endif
bool bVolumesChanged = false;
for (UINT uDrive = 0; uDrive <= 25; uDrive++)
{
UINT uMask = 1 << uDrive;
if (pVol->dbcv_unitmask & uMask)
{
DEBUG_ONLY( strMsg.AppendFormat(_T(" %c:"), _T('A') + uDrive) );
if (pVol->dbcv_flags & (DBTF_MEDIA | DBTF_NET))
ClearVolumeInfoCache(uDrive);
bVolumesChanged = true;
}
}
if (bVolumesChanged && sharedfileswnd)
sharedfileswnd->OnVolumesChanged();
// ==> Automatic shared files updater [MoNKi] - Stulle
if(thePrefs.GetDirectoryWatcher())
{
// Get the drive char
// Note, this is not so nice because we do something similar above
// and we might even miss a changed drive - the message calling this
// function can also be send for more than one changed drive at once -
// but still this is better than having more complex structures to
// figure out if we should reload.
char drive;
ULONG umask = pVol->dbcv_unitmask;
for (drive = 'a'; drive <= 'z'; drive++)
{
if (umask & 0x1)
break;
umask = umask >> 1;
}
// Check if there are shared folders in this drive
// Get all shared directories
CStringList dirList;
CString curDir;
// Incoming Dir
curDir=thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR);
dirList.AddTail( curDir );
// Categories dirs
for (int i=1; i < thePrefs.GetCatCount(); i++)
{
curDir=CString( thePrefs.GetCatPath(i) );
if( dirList.Find( curDir ) == NULL ) {
dirList.AddTail( curDir );
}
}
// The other shared dirs
POSITION pos = thePrefs.shareddir_list.GetHeadPosition();
while(pos){
curDir = thePrefs.shareddir_list.GetNext(pos);
if( dirList.Find( curDir ) == NULL ) {
dirList.AddTail( curDir );
}
}
// Dirs of single shared files
if(thePrefs.GetSingleSharedDirWatcher()/* && theApp.sharedfiles->ProbablyHaveSingleSharedFiles()*/)
{
for (POSITION pos = theApp.sharedfiles->m_liSingleSharedFiles.GetHeadPosition(); pos != NULL; theApp.sharedfiles->m_liSingleSharedFiles.GetNext(pos))
{
curDir = theApp.sharedfiles->m_liSingleSharedFiles.GetAt(pos);
curDir = curDir.Left(curDir.ReverseFind(_T('\\'))+1);
if( dirList.Find( curDir ) == NULL ) {
dirList.AddTail( curDir );
}
}
}
bool reload = false;
// Checks if a shared drive is in this volume
// or if it don't exits
pos = dirList.GetHeadPosition();
while(pos){
curDir = dirList.GetNext(pos);
if (curDir.Right(1)==_T("\\"))
curDir = curDir.Left(curDir.GetLength() - 1);
//this is a dir and not a drive
if (curDir.Right(1) != _T(":")){
if(CFileFind().FindFile(curDir) == FALSE){
reload = true;
pos = NULL;
}
}
//this is a drive
if(curDir.MakeLower().GetAt(0) == _TCHAR(drive)){
reload = true;
pos = NULL;
}
}
if(reload){
// Reload shared files
if(theApp.emuledlg->IsRunning()){
theApp.DirectoryWatcherExternalReload();
}
}
}
// <== Automatic shared files updater [MoNKi] - Stulle
}
else
{
DEBUG_ONLY( strMsg.AppendFormat(_T(" devicetype=0x%08x"), pHdr->dbch_devicetype) );
}
#ifdef _DEBUG
TRACE(_T("CemuleDlg::OnDeviceChange: %s\n"), strMsg);
#endif
}
else
TRACE(_T("CemuleDlg::OnDeviceChange: nEventType=0x%08x dwData=0x%08x\n"), nEventType, dwData);
return __super::OnDeviceChange(nEventType, dwData);
}
//////////////////////////////////////////////////////////////////
// Windows 7 GUI goodies
#ifdef HAVE_WIN7_SDK_H
// update thumbbarbutton structs and add/update the GUI thumbbar
void CemuleDlg::UpdateThumbBarButtons(bool initialAddToDlg) {
if (!m_pTaskbarList)
return;
THUMBBUTTONMASK dwMask = THB_ICON | THB_FLAGS;
for (int i=TBB_FIRST; i<=TBB_LAST;i++) {
m_thbButtons[i].dwMask = dwMask;
m_thbButtons[i].iId = i;
m_thbButtons[i].iBitmap = 0;
m_thbButtons[i].dwFlags = THBF_DISMISSONCLICK;
CString tooltip;
switch(i) {
case TBB_CONNECT:
{
m_thbButtons[i].hIcon = theApp.LoadIcon(_T("CONNECT"), 16, 16);
tooltip = GetResString(IDS_MAIN_BTN_CONNECT);
if (theApp.IsConnected()==true)
m_thbButtons[i].dwFlags |= THBF_DISABLED;
break;
}
case TBB_DISCONNECT:
{
m_thbButtons[i].hIcon = theApp.LoadIcon(_T("DISCONNECT"), 16, 16);
tooltip = GetResString(IDS_MAIN_BTN_DISCONNECT);
if (theApp.IsConnected()==false)
m_thbButtons[i].dwFlags |= THBF_DISABLED;
break;
}
case TBB_THROTTLE:
{
m_thbButtons[i].hIcon = theApp.LoadIcon(_T("SPEEDMIN"), 16, 16);
tooltip = GetResString(IDS_PW_PA);
break;
}
case TBB_UNTHROTTLE:
{
m_thbButtons[i].hIcon = theApp.LoadIcon(_T("SPEEDMAX"), 16, 16);
tooltip = GetResString(IDS_PW_UA);
break;
}
case TBB_PREFERENCES:
m_thbButtons[i].hIcon = theApp.LoadIcon(_T("PREFERENCES"), 16, 16);
tooltip = GetResString(IDS_EM_PREFS);
break;
}
// set tooltips in widechar
if (!tooltip.IsEmpty()) {
tooltip.Remove('&');
wcscpy(m_thbButtons[i].szTip,tooltip);
m_thbButtons[i].dwMask |= THB_TOOLTIP;
}
}
if (initialAddToDlg)
m_pTaskbarList->ThumbBarAddButtons(m_hWnd, ARRAYSIZE(m_thbButtons), m_thbButtons);
else
m_pTaskbarList->ThumbBarUpdateButtons(m_hWnd, ARRAYSIZE(m_thbButtons), m_thbButtons);
// clean up icons, they were copied in the previous call
for (int i=TBB_FIRST; i<=TBB_LAST;i++) {
DestroyIcon(m_thbButtons[i].hIcon);
}
}
// Handle pressed thumbbar button
void CemuleDlg::OnTBBPressed(UINT id)
{
switch (id) {
case TBB_CONNECT:
OnBnClickedConnect();
break;
case TBB_DISCONNECT:
CloseConnection();
break;
case TBB_THROTTLE:
QuickSpeedOther(MP_QS_PA);
break;
case TBB_UNTHROTTLE:
QuickSpeedOther(MP_QS_UA);
break;
case TBB_PREFERENCES:
ShowPreferences();
break;
}
}
// When Windows tells us, the taskbarbutton was created, it is safe to initialize our taskbar stuff
LRESULT CemuleDlg::OnTaskbarBtnCreated ( WPARAM , LPARAM )
{
// Sanity check that the OS is Win 7 or later
if (thePrefs.GetWindowsVersion() >= _WINVER_7_ && IsRunning())
{
if (m_pTaskbarList)
m_pTaskbarList.Release();
if (m_pTaskbarList.CoCreateInstance ( CLSID_TaskbarList ) == S_OK)
{
m_pTaskbarList->SetProgressState ( m_hWnd, TBPF_NOPROGRESS );
m_currentTBP_state = TBPF_NOPROGRESS;
m_prevProgress=0;
m_ovlIcon = NULL;
UpdateThumbBarButtons(true);
UpdateStatusBarProgress();
}
else
ASSERT( false );
}
return 0;
}
// Updates global progress and /down state overlayicon
// Overlayicon looks rather annoying than useful, so its disabled by default for the common user and can be enabled by ini setting only (Ornis)
void CemuleDlg::EnableTaskbarGoodies(bool enable)
{
if (m_pTaskbarList) {
m_pTaskbarList->SetOverlayIcon ( m_hWnd, NULL, _T("") );
if (!enable) {
m_pTaskbarList->SetProgressState ( m_hWnd, TBPF_NOPROGRESS );
m_currentTBP_state=TBPF_NOPROGRESS;
m_prevProgress=0;
m_ovlIcon = NULL;
}
else
UpdateStatusBarProgress();
}
}
void CemuleDlg::UpdateStatusBarProgress()
{
if (m_pTaskbarList && thePrefs.IsWin7TaskbarGoodiesEnabled())
{
// calc global progress & status
float globalDone = theStats.m_fGlobalDone;
float globalSize = theStats.m_fGlobalSize;
float finishedsize = theApp.emuledlg->transferwnd->GetDownloadList()->GetFinishedSize();
globalDone += finishedsize;
globalSize += finishedsize;
float overallProgress = globalSize?(globalDone/globalSize):0;
TBPFLAG new_state=m_currentTBP_state;
if (globalSize==0) {
// if there is no download, disable progress
if (m_currentTBP_state!=TBPF_NOPROGRESS) {
m_currentTBP_state=TBPF_NOPROGRESS;
m_pTaskbarList->SetProgressState ( m_hWnd, TBPF_NOPROGRESS );
}
} else {
new_state=TBPF_PAUSED;
if (theStats.m_dwOverallStatus & STATE_DOWNLOADING) // smth downloading
new_state=TBPF_NORMAL;
if (theStats.m_dwOverallStatus & STATE_ERROROUS) // smth error
new_state=TBPF_ERROR;
if (new_state!=m_currentTBP_state) {
m_pTaskbarList->SetProgressState ( m_hWnd, new_state );
m_currentTBP_state=new_state;
}
if (overallProgress != m_prevProgress) {
m_pTaskbarList->SetProgressValue(m_hWnd,(ULONGLONG)(overallProgress*100) ,100);
m_prevProgress=overallProgress;
}
}
// overlay up/down-speed
if (thePrefs.IsShowUpDownIconInTaskbar())
{
bool bUp = theApp.emuledlg->transferwnd->GetUploadList()->GetItemCount() >0;
bool bDown = theStats.m_dwOverallStatus & STATE_DOWNLOADING;
HICON newicon = NULL;
if (bUp && bDown)
newicon=transicons[3];
else if (bUp)
newicon=transicons[2];
else if (bDown)
newicon=transicons[1];
else
newicon = NULL;
if (m_ovlIcon!=newicon) {
m_ovlIcon=newicon;
m_pTaskbarList->SetOverlayIcon ( m_hWnd, m_ovlIcon, _T("eMule Up/Down Indicator") );
}
}
}
}
#endif
void CemuleDlg::SetTaskbarIconColor()
{
bool bBrightTaskbarIconSpeed = false;
bool bTransparent = false;
COLORREF cr = RGB(0, 0, 0);
if (thePrefs.IsRunningAeroGlassTheme())
{
HMODULE hDWMAPI = LoadLibrary(_T("dwmapi.dll"));
if (hDWMAPI){
HRESULT (WINAPI *pfnDwmGetColorizationColor)(DWORD*, BOOL*);
(FARPROC&)pfnDwmGetColorizationColor = GetProcAddress(hDWMAPI, "DwmGetColorizationColor");
DWORD dwGlassColor = 0;
BOOL bOpaque;
if (pfnDwmGetColorizationColor != NULL)
{
if (pfnDwmGetColorizationColor(&dwGlassColor, &bOpaque) == S_OK)
{
uint8 byAlpha = (uint8)(dwGlassColor >> 24);
cr = 0xFFFFFF & dwGlassColor;
if (byAlpha < 200 && bOpaque == FALSE)
{
// on transparent themes we can never figure out which excact color is shown (may we could in real time?)
// but given that a color is blended against the background, it is a good guess that a bright speedbar will
// be the best solution in most cases
bTransparent = true;
}
}
}
FreeLibrary(hDWMAPI);
}
}
else
{
if (g_xpStyle.IsThemeActive() && g_xpStyle.IsAppThemed())
{
CWnd* ptmpWnd = new CWnd();
VERIFY( ptmpWnd->Create(_T("STATIC"), _T("Tmp"), 0, CRect(0, 0, 10, 10), this, 1235) );
VERIFY( g_xpStyle.SetWindowTheme(ptmpWnd->GetSafeHwnd(), L"TrayNotifyHoriz", NULL) == S_OK );
HTHEME hTheme = g_xpStyle.OpenThemeData(ptmpWnd->GetSafeHwnd(), L"TrayNotify");
if (hTheme != NULL)
{
if (!g_xpStyle.GetThemeColor(hTheme, TNP_BACKGROUND, 0, TMT_FILLCOLORHINT, &cr) == S_OK)
ASSERT( false );
g_xpStyle.CloseThemeData(hTheme);
}
else
ASSERT( false );
ptmpWnd->DestroyWindow();
delete ptmpWnd;
}
else
{
DEBUG_ONLY(DebugLog(_T("Taskbar Notifier Color: GetSysColor() used")));
cr = GetSysColor(COLOR_3DFACE);
}
}
uint8 iRed = GetRValue(cr);
uint8 iBlue = GetBValue(cr);
uint8 iGreen = GetGValue(cr);
uint16 iBrightness = (uint16)sqrt(((iRed * iRed * 0.241f) + (iGreen * iGreen * 0.691f) + (iBlue * iBlue * 0.068f)));
ASSERT( iBrightness <= 255 );
bBrightTaskbarIconSpeed = iBrightness < 132;
DebugLog(_T("Taskbar Notifier Color: R:%u G:%u B:%u, Brightness: %u, Transparent: %s"), iRed, iGreen, iBlue, iBrightness, bTransparent ? _T("Yes") : _T("No"));
if (bBrightTaskbarIconSpeed || bTransparent)
thePrefs.SetStatsColor(11, RGB(255, 255, 255));
else
thePrefs.SetStatsColor(11, RGB(0, 0, 0));
}
//Xman versions check
LRESULT CemuleDlg::OnMVersionCheckResponse(WPARAM /*wParam*/, LPARAM lParam)
{
//Xman Info:
//IP-samples:
//1.5.4.99 --> Xtreme version 4.5 (.0)
//2.5.4.99 --> Xtreme version 4.5.1
//1.6.4.99 --> Xtreme version 4.6 (.0)
//1.0.5.99 --> Xtreme version 5.0 (.0)
if (WSAGETASYNCERROR(lParam) == 0)
{
int iBufLen = WSAGETASYNCBUFLEN(lParam);
if (iBufLen >= sizeof(HOSTENT))
{
LPHOSTENT pHost = (LPHOSTENT)m_acMVCDNSBuffer;
if (pHost->h_length == 4 && pHost->h_addr_list && pHost->h_addr_list[0])
{
uint32 dwResult = ((LPIN_ADDR)(pHost->h_addr_list[0]))->s_addr;
uint8 abyCurVer[4] = { MOD_BUILD_VER , MOD_MIN_VER, MOD_MAIN_VER, 0};
dwResult &= 0x00FFFFFF;
thePrefs.UpdateLastMVC();
if (dwResult > *(uint32*)abyCurVer){
if(theApp.IsSplash()) theApp.DestroySplash(); //Xman new slpash-screen arrangement
SetActiveWindow();
Log(LOG_SUCCESS|LOG_STATUSBAR,GetResString(IDS_NEWXTREMEVERSION));
ShowNotifier(GetResString(IDS_NEWXTREMEVERSION), TBN_NEWMVERSION);
m_bCheckwasDone=true;
if (AfxMessageBox(GetResString(IDS_NEWXTREMEVERSIONDOWNLOAD),MB_YESNO)==IDYES) {
ShellExecute(NULL, NULL, MOD_HPLINK, NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
}
}
else{
AddLogLine(true,_T("No new Xtreme-Version found"));
}
return 0;
}
}
}
LogWarning(LOG_STATUSBAR,GetResString(IDS_NEWVERSIONFAILED));
return 0;
}
//MOD NOTE: if you are using DLP, don't remove/modify this versions-check
//Xman DLP
LRESULT CemuleDlg::OnDLPVersionCheckResponse(WPARAM /*wParam*/, LPARAM lParam)
{
//Xman Info:
//IP-samples:
//5.0.0.99 --> DLP version 5
//105.0.0.99 --> DLP version 105
//0.1.0.99 --> DLP version 256 not allowed!
//1.1.0.99 --> DLP version 257
if (WSAGETASYNCERROR(lParam) == 0)
{
int iBufLen = WSAGETASYNCBUFLEN(lParam);
if (iBufLen >= sizeof(HOSTENT))
{
LPHOSTENT pHost = (LPHOSTENT)m_acDLPBuffer;
if (pHost->h_length == 4 && pHost->h_addr_list && pHost->h_addr_list[0])
{
uint32 dwResult = ((LPIN_ADDR)(pHost->h_addr_list[0]))->s_addr;
dwResult &= 0x00FFFFFF;
thePrefs.UpdateLastMVC();
if (theApp.dlp->IsDLPavailable() && dwResult > theApp.dlp->GetDLPVersion()){
if(theApp.IsSplash()) theApp.DestroySplash(); //Xman new slpash-screen arrangement
SetActiveWindow();
Log(LOG_SUCCESS|LOG_STATUSBAR,GetResString(IDS_NEWDLP));
ShowNotifier(GetResString(IDS_NEWDLP), TBN_NEWMVERSION);
if (m_bCheckwasDone==false && AfxMessageBox(GetResString(IDS_NEWDLPDOWNLOAD),MB_YESNO)==IDYES) {
ShellExecute(NULL, NULL, MOD_HPLINK, NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
}
m_bCheckwasDone=false;
}
else{
AddLogLine(true,_T("No new DLP-Version found"));
}
return 0;
}
}
}
LogWarning(LOG_STATUSBAR,GetResString(IDS_NEWVERSIONFAILED));
return 0;
}
//Xman end (DLP and versionscheck)
//Xman versions check
void CemuleDlg::DoMVersioncheck(bool manual) {
if (!manual && thePrefs.GetLastMVC()!=0) {
CTime last(thePrefs.GetLastMVC());
struct tm tmTemp;
time_t tLast=safe_mktime(last.GetLocalTm(&tmTemp));
time_t tNow=safe_mktime(CTime::GetCurrentTime().GetLocalTm(&tmTemp));
if ( (difftime(tNow,tLast) / 86400)<thePrefs.GetUpdateDays() )
return;
}
// ==> Removed Xtreme version check [Stulle] - Stulle
/*
if (WSAAsyncGetHostByName(m_hWnd, UM_MVERSIONCHECK_RESPONSE, "xtreme.dyndns.info", m_acMVCDNSBuffer, sizeof(m_acMVCDNSBuffer)) == 0){
AddLogLine(true,GetResString(IDS_NEWVERSIONFAILED));
}
//Xman DLP //MOD NOTE: if you are using DLP, don't remove/modify this versions-check
else if(WSAAsyncGetHostByName(m_hWnd, UM_DLPVERSIONCHECK_RESPONSE, "dlp.dyndns.info", m_acDLPBuffer, sizeof(m_acDLPBuffer)) == 0){
AddLogLine(true,_T("DLP version check failed"));
}
//Xman End
*/
; // Do nothing
// <== Removed Xtreme version check [Stulle] - Stulle
}
//Xman end
//Xman
// BEGIN SLUGFILLER: SafeHash
LRESULT CemuleDlg::OnHashFailed(WPARAM /*wParam*/, LPARAM lParam)
{
// BEGIN SiRoB: Fix crash at shutdown
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN) {
UnknownFile_Struct* hashed = (UnknownFile_Struct*)lParam;
delete hashed;
return FALSE;
}
// END SiRoB: Fix crash at shutdown
theApp.sharedfiles->HashFailed((UnknownFile_Struct*)lParam);
return 0;
}
LRESULT CemuleDlg::OnPartHashedOK(WPARAM wParam,LPARAM lParam)
{
//Xman
// BEGIN SiRoB: Fix crash at shutdown
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
// END SiRoB: Fix crash at shutdown
CPartFile* pOwner = (CPartFile*)lParam;
if (theApp.downloadqueue->IsPartFile(pOwner)){ // could have been canceled
pOwner->PartHashFinished((UINT)wParam, true, false);
pOwner->UpdateDisplayedInfo() ; //MORPH Display update (if IsPartFile! )
}
return 0;
}
LRESULT CemuleDlg::OnPartHashedOKNoAICH(WPARAM wParam,LPARAM lParam)
{
//MORPH START - Added by SiRoB, Fix crash at shutdown
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
//MORPH END - Added by SiRoB, Fix crash at shutdown
CPartFile* pOwner = (CPartFile*)lParam;
if (theApp.downloadqueue->IsPartFile(pOwner)){ // could have been canceled
pOwner->PartHashFinished((UINT)wParam, false, false);
pOwner->UpdateDisplayedInfo() ; //MORPH Display update (if IsPartFile! )
}
return 0;
}
LRESULT CemuleDlg::OnPartHashedCorrupt(WPARAM wParam,LPARAM lParam)
{
//Xman
// BEGIN SiRoB: Fix crash at shutdown
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
// END SiRoB: Fix crash at shutdown
CPartFile* pOwner = (CPartFile*)lParam;
if (theApp.downloadqueue->IsPartFile(pOwner)) // could have been canceled
pOwner->PartHashFinished((UINT)wParam, true, true);
return 0;
}
LRESULT CemuleDlg::OnPartHashedCorruptNoAICH(WPARAM wParam,LPARAM lParam)
{
//MORPH START - Added by SiRoB, Fix crash at shutdown
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
//MORPH END - Added by SiRoB, Fix crash at shutdown
CPartFile* pOwner = (CPartFile*)lParam;
if (theApp.downloadqueue->IsPartFile(pOwner)) // could have been canceled
pOwner->PartHashFinished((UINT)wParam, false, true);
return 0;
}
LRESULT CemuleDlg::OnPartHashedOKAICHRecover(WPARAM wParam,LPARAM lParam)
{
//Xman
// BEGIN SiRoB: Fix crash at shutdown
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
// END SiRoB: Fix crash at shutdown
CPartFile* pOwner = (CPartFile*)lParam;
if (theApp.downloadqueue->IsPartFile(pOwner)){ // could have been canceled
pOwner->PartHashFinishedAICHRecover((UINT)wParam, false);
pOwner->UpdateDisplayedInfo() ; //MORPH Display update (if IsPartFile! )
}
return 0;
}
LRESULT CemuleDlg::OnPartHashedCorruptAICHRecover(WPARAM wParam,LPARAM lParam)
{
//Xman
// BEGIN SiRoB: Fix crash at shutdown
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
// END SiRoB: Fix crash at shutdown
CPartFile* pOwner = (CPartFile*)lParam;
if (theApp.downloadqueue->IsPartFile(pOwner)) { // could have been canceled
pOwner->PartHashFinishedAICHRecover((UINT)wParam, true);
pOwner->UpdateDisplayedInfo() ; //MORPH Display update (if IsPartFile! )
}
return 0;
}
// END SLUGFILLER: SafeHash
// BEGIN SiRoB: ReadBlockFromFileThread
LRESULT CemuleDlg::OnReadBlockFromFileDone(WPARAM wParam,LPARAM lParam)
{
CUpDownClient* client = (CUpDownClient*) lParam;
if (theApp.m_app_state == APP_STATE_RUNNING && theApp.uploadqueue && theApp.uploadqueue->IsDownloading(client)) { // could have been canceled
client->SetReadBlockFromFileBuffer((byte*)wParam);
client->CreateNextBlockPackage(); //Used to not wait uploadqueue timer (110ms) capping upload to 1ReadBlock/110ms~1.6MB/s
}
else if (wParam != -1 && wParam != -2 && wParam != NULL)
delete[] (byte*)wParam;
return 0;
}
// END SiRoB: ReadBlockFromFileThread
// BEGIN SiRoB: Flush Thread
LRESULT CemuleDlg::OnFlushDone(WPARAM /*wParam*/,LPARAM lParam)
{
CPartFile* partfile = (CPartFile*) lParam;
if (theApp.m_app_state == APP_STATE_RUNNING && theApp.downloadqueue && theApp.downloadqueue->IsPartFile(partfile)) // could have been canceled
partfile->FlushDone();
return 0;
}
// END SiRoB: Flush Thread
//Xman end
//MORPH START - Added by SiRoB, Import Parts - added by zz_fly
LRESULT CemuleDlg::OnImportPart(WPARAM wParam,LPARAM lParam)
{
CPartFile* partfile = (CPartFile*) lParam;
if (theApp.m_app_state != APP_STATE_SHUTTINGDOWN && AfxIsValidAddress(partfile,sizeof(CPartFile)) && theApp.downloadqueue->IsPartFile(partfile)) { // could have been canceled
ImportPart_Struct* importpart = (ImportPart_Struct*)wParam;
partfile->WriteToBuffer(importpart->end-importpart->start+1, importpart->data,importpart->start, importpart->end, NULL, NULL);
}
delete[] ((ImportPart_Struct*)wParam)->data;
delete (ImportPart_Struct*)wParam;
return 0;
}
//MORPH END - Added by SiRoB, Import Parts
//Xman process timer code via messages (Xanatos)
// Note: the timers does not crash on a exception so I use the messags to call the functions so when an error aprears it will be detected
afx_msg LRESULT CemuleDlg::DoTimer(WPARAM wParam, LPARAM /*lParam*/)
{
if (!theApp.emuledlg->IsRunning())
return 0;
if(wParam == NULL)
theApp.uploadqueue->UploadTimer();
/* only used for uploadtimer
else if(wParam == -1)
theApp.emuledlg->StartupTimer();
*/
else
ASSERT(0);
return 0;
}
// ==> ScarAngel Version Check - Stulle
void CemuleDlg::DoSVersioncheck(bool manual) {
if (!manual && thePrefs.GetLastSVC()!=0) {
CTime last(thePrefs.GetLastSVC());
struct tm tmTemp;
time_t tLast=safe_mktime(last.GetLocalTm(&tmTemp));
time_t tNow=safe_mktime(CTime::GetCurrentTime().GetLocalTm(&tmTemp));
if ( (difftime(tNow,tLast) / 86400)<thePrefs.GetUpdateDays() )
return;
}
if (WSAAsyncGetHostByName(m_hWnd, UM_SVERSIONCHECK_RESPONSE, "scarvercheck.dyndns.info", m_acSVCDNSBuffer, sizeof(m_acSVCDNSBuffer)) == 0){
AddLogLine(true,GetResString(IDS_NEWVERSIONFAILED));
}
}
LRESULT CemuleDlg::OnSVersionCheckResponse(WPARAM /*wParam*/, LPARAM lParam)
{
if (WSAGETASYNCERROR(lParam) == 0)
{
int iBufLen = WSAGETASYNCBUFLEN(lParam);
if (iBufLen >= sizeof(HOSTENT))
{
LPHOSTENT pHost = (LPHOSTENT)m_acSVCDNSBuffer;
if (pHost->h_length == 4 && pHost->h_addr_list && pHost->h_addr_list[0])
{
uint32 dwResult = ((LPIN_ADDR)(pHost->h_addr_list[0]))->s_addr;
uint8 abyCurVer[4] = { (uint8)(CemuleApp::m_nMVersionBld + 1), (uint8)(CemuleApp::m_nMVersionMin), (uint8)(CemuleApp::m_nMVersionMjr), 0};
dwResult &= 0x00FFFFFF;
if (dwResult > *(uint32*)abyCurVer){
thePrefs.UpdateLastSVC();
SetActiveWindow();
Log(LOG_SUCCESS|LOG_STATUSBAR,GetResString(IDS_NEWSVERSIONAVL));
ShowNotifier(GetResString(IDS_NEWSVERSIONAVLPOPUP), TBN_NEWSVERSION);
if (AfxMessageBox(GetResString(IDS_NEWSVERSIONAVL)+GetResString(IDS_VISITSVERSIONCHECK),MB_YESNO)==IDYES) {
ShellExecute(NULL, NULL, _T("http://scarangel.sourceforge.net/"), NULL, thePrefs.GetMuleDirectory(EMULE_EXECUTEABLEDIR), SW_SHOWDEFAULT);
}
}
else{
thePrefs.UpdateLastSVC();
AddLogLine(true,GetResString(IDS_NONEWSVERVERSION));
}
return 0;
}
}
}
LogWarning(LOG_STATUSBAR,GetResString(IDS_NEWVERSIONFAILED));
return 0;
}
// <== ScarAngel Version Check - Stulle
// ==> TBH: Backup [TBH/EastShare/MorphXT] - Stulle
void CemuleDlg::SaveSettings (bool _shutdown) {
if (_shutdown) {
theApp.emuledlg->preferenceswnd->m_wndSecurity.DeleteDDB();
}
// ==> Threaded Known Files Saving [Stulle] - Stulle
if (theApp.knownfiles->m_SaveKnownThread) // we just saved something
{
theApp.knownfiles->m_SaveKnownThread->EndThread();
delete theApp.knownfiles->m_SaveKnownThread;
theApp.knownfiles->m_SaveKnownThread = NULL;
}
else // we might have missed something
// <== Threaded Known Files Saving [Stulle] - Stulle
theApp.knownfiles->Save();
theApp.sharedfiles->Save();
//transferwnd->downloadlistctrl.SaveSettings();
//transferwnd->downloadclientsctrl.SaveSettings();
//transferwnd->uploadlistctrl.SaveSettings();
//transferwnd->queuelistctrl.SaveSettings();
//transferwnd->clientlistctrl.SaveSettings();
//sharedfileswnd->sharedfilesctrl.SaveSettings();
//chatwnd->m_FriendListCtrl.SaveSettings();
searchwnd->SaveAllSettings();
serverwnd->SaveAllSettings();
kademliawnd->SaveAllSettings();
//sharedfileswnd->historylistctrl.SaveSettings(CPreferences::tableHistory); //Xman [MoNKi: -Downloaded History-]
//Xman new adapter selection
if(_shutdown && theApp.pBandWidthControl->GetwasNAFCLastActive()==true)
thePrefs.SetNAFCFullControl(true);
//Xman end
//Xman don't overwrite bak files if last sessions crashed
//remark: it would be better to set the flag after all deletions, but this isn't possible, because the prefs need access to the objects when saving
if (_shutdown) {
thePrefs.m_this_session_aborted_in_an_unnormal_way=false;
}
//Xman end
theApp.m_pPeerCache->Save();
if (_shutdown) {
theApp.scheduler->RestoreOriginals();
theApp.searchlist->SaveSpamFilter();
if (thePrefs.IsStoringSearchesEnabled())
theApp.searchlist->StoreSearches();
}
thePrefs.Save();
if (_shutdown) {
thePerfLog.Shutdown();
}
theApp.scheduler->SaveToFile();
}
// <== TBH: Backup [TBH/EastShare/MorphXT] - Stulle
// ==> XP Style Menu [Xanatos] - Stulle
void CemuleDlg::OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct)
{
HMENU hMenu = AfxGetThreadState()->m_hTrackingMenu;
if(CMenu *pMenu = CMenu::FromHandle(hMenu))
pMenu->MeasureItem(lpMeasureItemStruct);
if(nIDCtl)
CTrayDialog::OnMeasureItem(nIDCtl, lpMeasureItemStruct);
}
// <== XP Style Menu [Xanatos] - Stulle
// ==> Invisible Mode [TPT/MoNKi] - Stulle
LRESULT CemuleDlg::OnHotKey(WPARAM wParam, LPARAM /*lParam*/)
{
if(wParam == HOTKEY_INVISIBLEMODE_ID)
b_HideApp = !b_HideApp;
if(b_HideApp)
{
EnumWindows(AskEmulesForInvisibleMode, INVMODE_HIDEWINDOW);
}
else
{
EnumWindows(AskEmulesForInvisibleMode, INVMODE_RESTOREWINDOW);
}
return 0;
}
void CemuleDlg::ToggleHide()
{
// ==> Static Tray Icon [MorphXT] - MyTh88
m_bMaximized = IsZoomed();
// <== Static Tray Icon [MorphXT] - MyTh88
m_bTbhMiniMuleVis = theApp.minimule->IsWindowVisible()?true:false; // TBH: minimule - Stulle
b_HideApp = true;
b_TrayWasVisible = TrayHide();
b_WindowWasVisible = IsWindowVisible();
ShowWindow(SW_HIDE);
}
void CemuleDlg::ToggleShow()
{
b_HideApp = false;
if(b_TrayWasVisible)
// ==> TBH: minimule - Stulle
/*
TrayShow();
*/
TrayShow(m_bTbhMiniMuleVis);
// <== TBH: minimule - Stulle
if(b_WindowWasVisible)
// ==> Static Tray Icon [MorphXT] - MyTh88
/*
ShowWindow(SW_SHOW);
*/
{
if(m_bMaximized)
ShowWindow(SW_SHOWMAXIMIZED);
else
ShowWindow(SW_SHOW);
}
// <== Static Tray Icon [MorphXT] - MyTh88
}
BOOL CemuleDlg::RegisterInvisibleHotKey()
{
if(m_hWnd && IsRunning()){
bool res = RegisterHotKey( this->m_hWnd, HOTKEY_INVISIBLEMODE_ID ,
thePrefs.GetInvisibleModeHKKeyModifier(),
thePrefs.GetInvisibleModeHKKey())!=0;
return res;
} else
return false;
}
BOOL CemuleDlg::UnRegisterInvisibleHotKey()
{
if(m_hWnd){
bool res = !(UnregisterHotKey(this->m_hWnd, HOTKEY_INVISIBLEMODE_ID));
// Allows "invisible mode" on multiple instances of eMule
// Only one app (eMule) can register the hotkey, if we unregister, we need
// to register the hotkey in other emule.
EnumWindows(AskEmulesForInvisibleMode, INVMODE_REGISTERHOTKEY);
return res;
} else
return false;
}
// Allows "invisible mode" on multiple instances of eMule
// LOWORD(WPARAM) -> HotKey KeyModifier
// HIWORD(WPARAM) -> HotKey VirtualKey
// LPARAM -> int: INVMODE_RESTOREWINDOW -> Restores the window
// INVMODE_REGISTERHOTKEY -> Registers the hotkey
LRESULT CemuleDlg::OnRestoreWindowInvisibleMode(WPARAM wParam, LPARAM lParam)
{
if (thePrefs.GetInvisibleMode() &&
(UINT)LOWORD(wParam) == thePrefs.GetInvisibleModeHKKeyModifier() &&
(char)HIWORD(wParam) == thePrefs.GetInvisibleModeHKKey()) {
switch(lParam){
case INVMODE_RESTOREWINDOW:
ToggleShow();
break;
case INVMODE_REGISTERHOTKEY:
RegisterInvisibleHotKey();
break;
case INVMODE_HIDEWINDOW:
ToggleHide();
}
return UWM_RESTORE_WINDOW_IM;
} else
return false;
}
// Allows "invisible mode" on multiple instances of eMule
BOOL CALLBACK CemuleDlg::AskEmulesForInvisibleMode(HWND hWnd, LPARAM lParam){
DWORD dwMsgResult;
WPARAM msgwParam;
msgwParam=MAKEWPARAM(thePrefs.GetInvisibleModeHKKeyModifier(),
thePrefs.GetInvisibleModeHKKey());
LRESULT res = ::SendMessageTimeout(hWnd,UWM_RESTORE_WINDOW_IM, msgwParam, lParam,
SMTO_BLOCK |SMTO_ABORTIFHUNG,10000,&dwMsgResult);
return res;
}
// <== Invisible Mode [TPT/MoNKi] - Stulle
// ==> Design Settings [eWombat/Stulle] - Max
HBRUSH CemuleDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
m_hbrWndClr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
pDC->SetBkMode(TRANSPARENT);
return m_hbrWndClr;
}
// <== Design Settings [eWombat/Stulle] - Max
// ==> Advanced Updates [MorphXT/Stulle] - Stulle
void CemuleDlg::DoDLPVersioncheck()
{
if (WSAAsyncGetHostByName(m_hWnd, UM_DLPAUTOVERCHECK_RESPONSE, "dlp.dyndns.info", m_acDLPAutoBuffer, sizeof(m_acDLPAutoBuffer)) == 0){
AddLogLine(true,GetResString(IDS_AUTODLPFAILED));
}
}
LRESULT CemuleDlg::OnDLPAutoVerCheckResponse(WPARAM /*wParam*/, LPARAM lParam)
{
//Xman Info:
//IP-samples:
//5.0.0.99 --> DLP version 5
//105.0.0.99 --> DLP version 105
//0.1.0.99 --> DLP version 256 not allowed!
//1.1.0.99 --> DLP version 257
if (WSAGETASYNCERROR(lParam) == 0)
{
int iBufLen = WSAGETASYNCBUFLEN(lParam);
if (iBufLen >= sizeof(HOSTENT))
{
LPHOSTENT pHost = (LPHOSTENT)m_acDLPAutoBuffer;
if (pHost->h_length == 4 && pHost->h_addr_list && pHost->h_addr_list[0])
{
uint32 dwResult = ((LPIN_ADDR)(pHost->h_addr_list[0]))->s_addr;
dwResult &= 0x00FFFFFF;
// uint8 uTest1 = (uint8)(dwResult >> 0);
if (theApp.dlp->IsDLPavailable())
{
if(dwResult > theApp.dlp->GetDLPVersion())
DownloadDLP();
}
else
DownloadDLP();
return 0;
}
}
}
LogWarning(LOG_STATUSBAR,GetResString(IDS_AUTODLPFAILED));
return 0;
}
void CemuleDlg::DownloadDLP()
{
CString sbuffer;
CString strURL = thePrefs.GetAntiLeechURL();
TCHAR szTempFilePath[_MAX_PATH];
_tmakepath(szTempFilePath, NULL, thePrefs.GetMuleDirectory(EMULE_CONFIGDIR), _T("antiLeech.dll"), _T("new"));
CHttpDownloadDlg dlgDownload;
dlgDownload.m_strTitle = GetResString(IDS_ANTILEECH_DWNFILE);
dlgDownload.m_sURLToDownload = strURL;
dlgDownload.m_sFileToDownloadInto = szTempFilePath;
if (dlgDownload.DoModal() != IDOK)
{
LogError(LOG_STATUSBAR, GetResString(IDS_LOG_ERRDWN), strURL);
return;
}
theApp.dlp->Reload();
}
void CemuleDlg::DoIPFilterVersioncheck()
{
if (WSAAsyncGetHostByName(m_hWnd, UM_IPFFILTERAUTOVERCHECK_RESPONSE, "ipfilter.dyndns.info", m_acIPFilterAutoBuffer, sizeof(m_acIPFilterAutoBuffer)) == 0){
AddLogLine(true,GetResString(IDS_AUTOIPFILTERFAILED));
}
}
LRESULT CemuleDlg::OnIPFilterAutoVerCheckResponse(WPARAM /*wParam*/, LPARAM lParam)
{
//Info:
//IP-samples:
//5.0.0.99 --> IPFilter version 5
//105.0.0.99 --> IPFilter version 105
//0.1.0.99 --> IPFilter version 256 not allowed!
//1.1.0.99 --> IPFilter version 257
if (WSAGETASYNCERROR(lParam) == 0)
{
int iBufLen = WSAGETASYNCBUFLEN(lParam);
if (iBufLen >= sizeof(HOSTENT))
{
LPHOSTENT pHost = (LPHOSTENT)m_acIPFilterAutoBuffer;
if (pHost->h_length == 4 && pHost->h_addr_list && pHost->h_addr_list[0])
{
uint32 dwResult = ((LPIN_ADDR)(pHost->h_addr_list[0]))->s_addr;
dwResult &= 0x00FFFFFF;
if (PathFileExists(theApp.ipfilter->GetDefaultFilePath()))
{
if(dwResult > thePrefs.GetIPFilterVersionNum())
theApp.ipfilter->UpdateIPFilterURL(dwResult);
}
else
theApp.ipfilter->UpdateIPFilterURL(dwResult);
return 0;
}
}
}
LogWarning(LOG_STATUSBAR,GetResString(IDS_AUTOIPFILTERFAILED));
return 0;
}
void CemuleDlg::CheckIPFilter()
{
if(thePrefs.IsIPFilterViaDynDNS())
DoIPFilterVersioncheck();
else
theApp.ipfilter->UpdateIPFilterURL();
}
// <== Advanced Updates [MorphXT/Stulle] - Stulle
// ==> High resolution speedmeter on toolbar [eFMod/Stulle] - Myth88
void CemuleDlg::Update_TrafficGraph()
{
// ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle
if(theApp.IsRunningAsService(SVC_GUI_OPT))
return;
// <== Run eMule as NT Service [leuk_he/Stulle] - Stulle
//Xman
// Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter-
// Retrieve the current datarates
uint32 downratekb; uint32 eMuleInOverall;
uint32 upratekb; uint32 eMuleOutOverall;
uint32 notUsed;
theApp.pBandWidthControl->GetDatarates(thePrefs.GetDatarateSamples(),
downratekb, eMuleInOverall,
upratekb, eMuleOutOverall,
notUsed, notUsed);
//Xman end
m_co_UpTrafficGraph.Set_TrafficValue(upratekb);
m_co_DownTrafficGraph.Set_TrafficValue(downratekb);
}
void CemuleDlg::Reposition_TrafficGraph()
{
if (m_co_UpTrafficGraph.m_hWnd &&
m_co_DownTrafficGraph.m_hWnd &&
thePrefs.GetShowSpeedMeter())
{
CRect rect;
CRect rect1,rect2;
toolbar->GetClientRect(&rect);
// set updateintervall of graphic rate display (in seconds)
//rect1.top = rect.top+2;
rect1.top = 2;
rect1.right = rect.right-2;
//rect1.bottom = rect.top+(rect.Height()/2)-1;
rect1.bottom = 26;
rect1.left = rect.right-150;
rect2.top = rect.top+(rect.Height()/2)+1;
rect2.top = 28;
rect2.right = rect.right-2;
//rect2.bottom = rect.bottom-2;
rect2.bottom = 52;
rect2.left = rect.right-150;
CSize csMaxSize;
toolbar->GetMaxSize(&csMaxSize);
if (rect.left + csMaxSize.cx > rect.right - 150)
{
m_co_UpTrafficGraph.ShowWindow(SW_HIDE);
m_co_DownTrafficGraph.ShowWindow(SW_HIDE);
return;
}
m_co_UpTrafficGraph.SetWindowPos( NULL, rect1.left, rect1.top,
rect1.Width(), rect1.Height(),
SWP_NOZORDER | SWP_SHOWWINDOW );
m_co_DownTrafficGraph.SetWindowPos( NULL, rect2.left, rect2.top,
rect2.Width(), rect2.Height(),
SWP_NOZORDER | SWP_SHOWWINDOW );
}
}
// <== High resolution speedmeter on toolbar [eFMod/Stulle] - Myth88
// ==> File Settings [sivka/Stulle] - Stulle
LRESULT CemuleDlg::OnSaveDone(WPARAM /*wParam*/,LPARAM /*lParam*/)
{
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
theApp.downloadqueue->SaveFileSettings(false);
return 0;
}
// <== File Settings [sivka/Stulle] - Stulle
// ==> Threaded Known Files Saving [Stulle] - Stulle
LRESULT CemuleDlg::OnSaveKnownDone(WPARAM /*wParam*/,LPARAM /*lParam*/)
{
if (theApp.m_app_state == APP_STATE_SHUTTINGDOWN)
return FALSE;
theApp.knownfiles->SaveKnown(false);
return 0;
}
// <== Threaded Known Files Saving [Stulle] - Stulle
// ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle
LRESULT CemuleDlg::OnServiceStatus(WPARAM ServiceStatus, LPARAM /*lParam */)
{
return ReportStatusToSCMgr(ServiceStatus, NO_ERROR, 0); // tell servicecrtrk we are alive.
}
// <== Run eMule as NT Service [leuk_he/Stulle] - Stulle
// >> add by Ken
// MORPH START show less controls
void setcolumns(CMuleListCtrl * control,CString Columnstohide, bool Show)
{
int pos=0;
int count=0;
CString foundString;
do {
foundString=Columnstohide.Tokenize(_T(","),pos);
if ((foundString==_T("1")) && Show==false
&& control->IsColumnHidden(count))
control->ShowColumn(count); // show the ",0" columns if disabled showlesscontrol
if (foundString==_T("1") && Show==true
&& (control->IsColumnHidden(count))==false)
control->HideColumn(count); // show less controls.
count++;
}
while (foundString != "");
}
void CemuleDlg::ShowLessControls (bool enable)
{
// toolbar:
NMHDR nmh;
nmh.code = TBN_RESET;
nmh.hwndFrom = /*theApp.emuledlg->*/toolbar->GetSafeHwnd();
nmh.idFrom = /*theApp.emuledlg->*/toolbar->GetDlgCtrlID();
/*theApp.emuledlg->*/toolbar->SendMessage(WM_NOTIFY, nmh.idFrom, (LPARAM)&nmh);
// Listcontrols
// note, the settings are eqaul to the xxxCtrlcolumnHidden=0,1... line in preferences.ini when less controls are displayed
setcolumns(transferwnd->GetDownloadList(),_T("0,0,1,1,0,0,0,0,0,0,1,1,1,1,1,0,1"),enable);
setcolumns(transferwnd->GetUploadList(), _T("0,0,0,0,1,1,0,1,1,1,1,0,1,1,0,1,1"),enable);
setcolumns(transferwnd->GetQueueList(), _T("0,0,0,0,0,1,1,1,1,0,1,1,1,1"),enable);
setcolumns(transferwnd->GetClientList(), _T("0,0,0,0,0,0,1,1,1,1,1"),enable);
setcolumns(transferwnd->GetDownloadClientsList(), _T("0,1,0,0,0,0,0,1,1,1,1,1,1"),enable);
setcolumns(&(serverwnd->serverlistctrl),_T("0,0,1,1,0,0,0,0,1,1,1,1,1,1,0,1,1"),enable);
setcolumns(&(searchwnd->m_pwndResults->searchlistctrl),_T("0,0,0,0,0,1,1,1,1,1,1,1,1,1,1"),enable);
setcolumns(&(sharedfileswnd->sharedfilesctrl),_T("0,0,0,0,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1"),enable);
//context menus
transferwnd->GetDownloadList()->CreateMenues();
sharedfileswnd->sharedfilesctrl.CreateMenues();
}
// MORPH END show less controls
// << add by Ken | [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b",
"[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b"
] | [
[
[
1,
38
],
[
40,
113
],
[
115,
125
],
[
127,
153
],
[
159,
273
],
[
275,
275
],
[
277,
290
],
[
296,
304
],
[
306,
360
],
[
362,
409
],
[
420,
466
],
[
469,
470
],
[
493,
535
],
[
537,
637
],
[
639,
860
],
[
864,
864
],
[
866,
878
],
[
880,
898
],
[
900,
908
],
[
914,
951
],
[
953,
987
],
[
989,
1047
],
[
1049,
1050
],
[
1055,
1081
],
[
1084,
1087
],
[
1089,
1098
],
[
1100,
1100
],
[
1102,
1122
],
[
1124,
1124
],
[
1126,
1170
],
[
1176,
1254
],
[
1256,
1511
],
[
1515,
1668
],
[
1670,
1710
],
[
1712,
1717
],
[
1720,
1723
],
[
1730,
1946
],
[
1951,
1960
],
[
1964,
1972
],
[
1974,
1987
],
[
1990,
2042
],
[
2053,
2068
],
[
2070,
2077
],
[
2079,
2145
],
[
2152,
2210
],
[
2212,
2280
],
[
2282,
2283
],
[
2291,
2296
],
[
2298,
2444
],
[
2449,
2485
],
[
2496,
2506
],
[
2508,
2531
],
[
2533,
2558
],
[
2560,
2594
],
[
2603,
2631
],
[
2633,
2637
],
[
2642,
2660
],
[
2662,
2697
],
[
2700,
2701
],
[
2710,
3003
],
[
3008,
3038
],
[
3054,
3376
],
[
3381,
3704
],
[
3706,
3792
],
[
3794,
3820
],
[
3822,
3840
],
[
3847,
4160
],
[
4162,
4178
],
[
4183,
4183
],
[
4186,
4186
],
[
4189,
4189
],
[
4192,
4719
],
[
4721,
4726
],
[
4728,
4754
],
[
4757,
4765
],
[
4770,
4860
],
[
4862,
4916
],
[
4922,
4965
],
[
4969,
5000
],
[
5006,
5032
],
[
5038,
5223
],
[
5750,
5906
],
[
5908,
6063
],
[
6065,
6133
],
[
6138,
6260
],
[
6266,
6270
],
[
6272,
6275
]
],
[
[
39,
39
],
[
114,
114
],
[
126,
126
],
[
154,
158
],
[
274,
274
],
[
276,
276
],
[
291,
295
],
[
305,
305
],
[
361,
361
],
[
410,
419
],
[
467,
468
],
[
471,
492
],
[
536,
536
],
[
638,
638
],
[
861,
863
],
[
865,
865
],
[
879,
879
],
[
899,
899
],
[
909,
913
],
[
952,
952
],
[
988,
988
],
[
1048,
1048
],
[
1051,
1054
],
[
1082,
1083
],
[
1088,
1088
],
[
1099,
1099
],
[
1101,
1101
],
[
1123,
1123
],
[
1125,
1125
],
[
1171,
1175
],
[
1255,
1255
],
[
1512,
1514
],
[
1669,
1669
],
[
1711,
1711
],
[
1718,
1719
],
[
1724,
1729
],
[
1947,
1950
],
[
1961,
1963
],
[
1973,
1973
],
[
1988,
1989
],
[
2043,
2052
],
[
2069,
2069
],
[
2078,
2078
],
[
2146,
2151
],
[
2211,
2211
],
[
2281,
2281
],
[
2284,
2290
],
[
2297,
2297
],
[
2445,
2448
],
[
2486,
2495
],
[
2507,
2507
],
[
2532,
2532
],
[
2559,
2559
],
[
2595,
2602
],
[
2632,
2632
],
[
2638,
2641
],
[
2661,
2661
],
[
2698,
2699
],
[
2702,
2709
],
[
3004,
3007
],
[
3039,
3053
],
[
3377,
3380
],
[
3705,
3705
],
[
3793,
3793
],
[
3821,
3821
],
[
3841,
3846
],
[
4161,
4161
],
[
4179,
4182
],
[
4184,
4185
],
[
4187,
4188
],
[
4190,
4191
],
[
4720,
4720
],
[
4727,
4727
],
[
4755,
4756
],
[
4766,
4769
],
[
4861,
4861
],
[
4917,
4921
],
[
4966,
4968
],
[
5001,
5005
],
[
5033,
5037
],
[
5224,
5749
],
[
5907,
5907
],
[
6064,
6064
],
[
6134,
6137
],
[
6261,
6265
],
[
6271,
6271
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.