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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
82b7f4c29dc2c04b312bd1fa2c25ac771316dec0 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/DevLibs/DevLib/md_vector.cpp | 90c580c68da4efcbd6d401343e3591f6308b5354 | [] | 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 | 36,626 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
#include "stdafx.h"
#define __MD_VECTOR_CPP
#include "md_share1.h"
#include "md_defn.h"
#include "md_vector.h"
#include "md_spmodel.h"
#include "md_method.h"
#include "md_PSD.h"
#include "scdmacros.h"
#define MDLBASE
#define SIZEDST1
#include "models.h"
//#include "optoff.h"
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
//===========================================================================
//
//
//
//===========================================================================
static void ConduitToVector(SpConduit & C, MVector & V, DWORD PhMsk)
{
for (int s=0; s<SDB.Count(); s++)
V.M[s] = (SDB[s].m_PhMsk & PhMsk) ? C.VMass[s] : 0;
V.SetTP(C.Temp(), C.Press());
}
//--------------------------------------------------------------------------
static void VectorToConduit(MVector & V, SpConduit & C, DWORD PhMsk)
{
for (int s=0; s<SDB.Count(); s++)
if (SDB[s].m_PhMsk & PhMsk)
C.VValue[s] = V.M[s];
C.SetTempPress(V.T, V.P);
}
//===========================================================================
//
//
//
//===========================================================================
MProperty::MProperty(MVector * pVec, long iIndex)
{
m_pVec=pVec;
m_iIndex=iIndex;
};
MProperty::~MProperty()
{
};
//---------------------------------------------------------------------------
UCHAR MProperty::getType() const { MPropertyInfo *pI=m_pVec->SpMdl->PropertyMap()[m_iIndex]; return (UCHAR)(pI?pI->m_iType:ePT_Null); };
LPCTSTR MProperty::getTag() const { MPropertyInfo *pI=m_pVec->SpMdl->PropertyMap()[m_iIndex]; return pI?pI->m_sTag:""; };
LPCTSTR MProperty::getSymbol() const { MPropertyInfo *pI=m_pVec->SpMdl->PropertyMap()[m_iIndex]; return pI?pI->m_sSym:""; };
LPCTSTR MProperty::getDescription() const { MPropertyInfo *pI=m_pVec->SpMdl->PropertyMap()[m_iIndex]; return pI?pI->m_sDesc:""; };
long MProperty::getCnvIndex() const { MPropertyInfo *pI=m_pVec->SpMdl->PropertyMap()[m_iIndex]; return pI?pI->m_iCnv:0; };
bool MProperty::getSettable() const { MPropertyInfo *pI=m_pVec->SpMdl->PropertyMap()[m_iIndex]; return pI?pI->Settable():false; };
bool MProperty::getHardMinimum() const { MPropertyInfo *pI=m_pVec->SpMdl->PropertyMap()[m_iIndex]; return pI?pI->HasHardMin():0; };
bool MProperty::getSoftMinimum() const { MPropertyInfo *pI=m_pVec->SpMdl->PropertyMap()[m_iIndex]; return pI?pI->HasSoftMin():0; };
bool MProperty::getHardMaximum() const { MPropertyInfo *pI=m_pVec->SpMdl->PropertyMap()[m_iIndex]; return pI?pI->HasHardMax():0; };
bool MProperty::getSoftMaximum() const { MPropertyInfo *pI=m_pVec->SpMdl->PropertyMap()[m_iIndex]; return pI?pI->HasSoftMax():0; };
long MProperty::getIndex() const { return m_iIndex; };
//---------------------------------------------------------------------------
long MProperty::LValue(DWORD Phases, double T, double P) const
{
SpModel*p=m_pVec->SpMdl;
MPropertyValue TheValue;
p->GetPropertyValue(m_iIndex, Phases, Valid(T)?T:p->Temp(), Valid(P)?P:p->Press(), TheValue);
return TheValue;
};
//---------------------------------------------------------------------------
//ULONG MProperty::UValue(DWORD Phases, double T, double P) const
// {
// SpModel*p=m_pVec->SpMdl;
// MPropertyValue TheValue;
// p->GetPropertyValue(m_iIndex, Phases, Valid(T)?T:p->Temp(), Valid(P)?P:p->Press(), TheValue);
// return TheValue;
// };
//---------------------------------------------------------------------------
double MProperty::DValue(DWORD Phases, double T, double P) const
{
SpModel*p=m_pVec->SpMdl;
MPropertyValue TheValue;
p->GetPropertyValue(m_iIndex, Phases, Valid(T)?T:p->Temp(), Valid(P)?P:p->Press(), TheValue);
return TheValue;
};
//---------------------------------------------------------------------------
LPCTSTR MProperty::SValue(DWORD Phases, double T, double P) const
{
SpModel*p=m_pVec->SpMdl;
MPropertyValue TheValue;
p->GetPropertyValue(m_iIndex, Phases, Valid(T)?T:p->Temp(), Valid(P)?P:p->Press(), TheValue);
return TheValue;
};
//---------------------------------------------------------------------------
void MProperty::putReqdLValue(long Value)
{
SpModel*p=m_pVec->SpMdl;
p->PutPropertyValue(m_iIndex, MPropertyValue(Value));
};
//---------------------------------------------------------------------------
//void MProperty::putReqdUValue(ULONG Value)
// {
// SpModel*p=m_pVec->SpMdl;
// p->PutPropertyValue(m_iIndex, MPropertyValue(Value));
// };
//---------------------------------------------------------------------------
void MProperty::putReqdDValue(double Value)
{
SpModel*p=m_pVec->SpMdl;
p->PutPropertyValue(m_iIndex, MPropertyValue(Value));
};
//---------------------------------------------------------------------------
void MProperty::putReqdSValue(LPCTSTR Value)
{
SpModel*p=m_pVec->SpMdl;
p->PutPropertyValue(m_iIndex, MPropertyValue(Value));
};
//===========================================================================
//
//
//
//===========================================================================
inline long MProperties::Count() { return m_pVec->SpMdl->PropertyCount(); };
//---------------------------------------------------------------------------
inline long MProperties::Index(LPCTSTR Name) { return m_pVec->SpMdl->PropertyIndex(Name); };
//---------------------------------------------------------------------------
inline MProperty MProperties::operator[](int Index) { return MProperty(m_pVec, Index); }; //perhaps test for valid index and throw exception!?
//---------------------------------------------------------------------------
MProperty MProperties::operator[](LPCTSTR Name)
{
const long i=m_pVec->SpMdl->PropertyIndex(Name);
if (i<0)
throw new MMdlException(0, CString("Unknown Property Name:")+Name);
return MProperty(m_pVec, i);
}
//---------------------------------------------------------------------------
//===========================================================================
//
//
//
//===========================================================================
MArray::MArray() { m_pSysVec=NULL; };
MArray::MArray(CSysVector * p) { m_pSysVec=p; };
MArray::MArray(MVector * p) { m_pSysVec=p->SpMdl->pMArray(); };
MArray::MArray(MSpModelBase * p) { m_pSysVec=p->m_pSpMdlX->pMArray(); };
MArray::~MArray() { m_pSysVec=NULL; };
double & MArray::operator [](int i) { return *m_pSysVec->VPtr[i]; }
double MArray::Mass(DWORD Phases) { return m_pSysVec->Mass(Phases); };
double MArray::Moles(DWORD Phases) { return m_pSysVec->Moles(Phases); };
double MArray::MassFrac(DWORD Phases) { return m_pSysVec->MassFrac(Phases); };
double MArray::MoleFrac(DWORD Phases) { return m_pSysVec->MoleFrac(Phases); };
MArray & MArray::operator=(MArray & M)
{
for (int i=0; i<SDB.Count(); i++)
(*this)[i]=M[i];
return *this;
};
MArray & MArray::operator=(MVector & M)
{
for (int i=0; i<SDB.Count(); i++)
(*this)[i]=M.M[i];
return *this;
};
void MArray::Normalise()
{
double T=0;
for (int i=0; i<SDB.Count(); i++)
T+=(*this)[i];
T=GTZ(T);
for (int i=0; i<SDB.Count(); i++)
(*this)[i]/=T;
};
//===========================================================================
MArrayI::MArrayI()
{
m_pSysVec=new SpVector;
};
MArrayI::MArrayI(CSysVector * p)
{
m_pSysVec=new SpVector;
*m_pSysVec=*p;
};
MArrayI::MArrayI(MVector * p)
{
m_pSysVec=new SpVector;
*((MArray*)this)=*p;
};
MArrayI::MArrayI(MSpModelBase * p)
{
m_pSysVec=new SpVector;
*((MArray*)this)=p->MassArray;
//*m_pSysVec=*p->m_pSpMdlX->pMArray();
};
MArrayI::~MArrayI()
{
delete (SpVector*)m_pSysVec;
};
//===========================================================================
//
//
//
//===========================================================================
MVector::MVector() : Properties(this)//, Interfaces(this)
{
m_pSpMdl=NULL;
//m_pBayer=NULL;
m_pPSD=NULL;
}
//---------------------------------------------------------------------------
MVector::MVector(SpModel * pMdl) : Properties(this)
{
m_pSpMdl=pMdl;
//m_pBayer=NULL;
m_pPSD=NULL;
}
//---------------------------------------------------------------------------
MVector::MVector(MSpQualityBase * p) : Properties(this)
{
m_pSpMdl=p->m_pSpQual->pModel;
//m_pBayer=NULL;
m_pPSD=NULL;
};
//---------------------------------------------------------------------------
MVector::~MVector()
{
//delete m_pSpMdl; // this would have been attached
//delete m_pBayer; // this would have been new'd
delete m_pPSD; // this would have been new'd
}
//---------------------------------------------------------------------------
long MVector::Count(DWORD PhMsk) { return gs_MVDefn.Count(PhMsk); };
LPCTSTR MVector::getTag() { return SpMdl->FullObjTag(); };
double MVector::getT() const { return SpMdl->Temp(); };
void MVector::putT(double T) { SpMdl->SetTempPress(T, SpMdl->Press()); };
double MVector::getP() const { return SpMdl->Press(); };
void MVector::putP(double P) { SpMdl->SetTempPress(SpMdl->Temp(), P); };
double MVector::getM(long i) const { return SpMdl->VValue[i]; };
void MVector::putM(long i, double M) { SpMdl->VValue[i] = M; };
double MVector::getA(long i) const { return SpMdl->VAttr[i]; };
void MVector::putA(long i, double A) { SpMdl->VAttr[i]=A; };
double MVector::getMl(long i) const { return SpMdl->VMole[i]; };
//void MVector::putMl(long i, double M) { SpMdl->VMole[i] = M; };
const double *MVector::getMassVector() { return SpMdl->SVData(); };
void MVector::MarkStateChanged() { SpMdl->ClrStatesOK(); };
void MVector::putSuppressErrors(bool On) { SpMdl->SetBadTempOK(On); };
// ----------------------------- Properties
double MVector::RefTemp() const { return SpMdl->RefTemp(); };
double MVector::msCp(DWORD Phases, double T, double P) const { return SpMdl->msCp(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::msHs(DWORD Phases, double T, double P) const { return SpMdl->msHs(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::msHz(DWORD Phases, double T, double P) const { return SpMdl->msHz(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::msHf(DWORD Phases, double T, double P) const { return SpMdl->msHf(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::msSf(DWORD Phases, double T, double P) const { return SpMdl->msSf(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::totCp(DWORD Phases, double T, double P) const { return SpMdl->totCp(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::totHs(DWORD Phases, double T, double P) const { return SpMdl->totHs(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::totHz(DWORD Phases, double T, double P) const { return SpMdl->totHz(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::totHf(DWORD Phases, double T, double P) const { return SpMdl->totHf(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::totSf(DWORD Phases, double T, double P) const { return SpMdl->totSf(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::TCritical(DWORD Phase, eScdGasMixingRule Rule) const { return SpMdl->TCritical(Phase, Rule); };
double MVector::PCritical(DWORD Phase, eScdGasMixingRule Rule) const { return SpMdl->PCritical(Phase, Rule); };
double MVector::VCritical(DWORD Phase, eScdGasMixingRule Rule) const { return SpMdl->VCritical(Phase, Rule); };
double MVector::AccentricFactor(DWORD Phase, eScdGasMixingRule Rule) const { return SpMdl->AccentricFactor(Phase, Rule); };
double MVector::msdHIdeal(DWORD Phase, double T1, double T2) const { return SpMdl->msdHIdeal(Phase, T1, T2); };
double MVector::msdSIdeal(DWORD Phase, double T1, double T2) const { return SpMdl->msdSIdeal(Phase, T1, T2); };
double MVector::msdHResidual(DWORD Phase, double T, double P, eScdGasMixingRule Rule, eScdEqnOfState Eqn) const { return SpMdl->msdHResidual(Phase, T, P, Rule, Eqn); };
double MVector::msdSResidual(DWORD Phase, double T, double P, eScdGasMixingRule Rule, eScdEqnOfState Eqn) const { return SpMdl->msdSResidual(Phase, T, P, Rule, Eqn); };
double MVector::PartialPress(int IncIds, int ExcIds, double T) const { return SpMdl->PartialPress(IncIds, ExcIds, Valid(T)?T:SpMdl->Temp()); };
double MVector::Mass(DWORD Phases) const { return SpMdl->Mass(Phases); };
double MVector::Moles(DWORD Phases) const { return SpMdl->Moles(Phases); };
double MVector::MoleWt(DWORD Phases) const { return SpMdl->MoleWt(Phases); };
double MVector::Volume(DWORD Phases, double T, double P) const { return SpMdl->Volume(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::NVolume(DWORD Phases) const { return SpMdl->NVolume(Phases); };
double MVector::Density(DWORD Phases, double T, double P) const { return SpMdl->Rho(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::NDensity(DWORD Phases) const { return SpMdl->NRho(Phases); };
double MVector::MassFrac(DWORD Phases) const { return SpMdl->MassFrac(Phases); };
double MVector::MoleFrac(DWORD Phases) const { return SpMdl->MoleFrac(Phases); };
double MVector::VolFrac(DWORD Phases, double T, double Press) const { return SpMdl->VolFrac(Phases, Valid(T)?T:SpMdl->Temp(), Press); };
double MVector::SpecieConc(DWORD Phases, int iSpNo, double Temp) const { return SpMdl->SpecieConc(Valid(T)?T:SpMdl->Temp(), iSpNo, Phases); };
double MVector::PhaseConc(DWORD Phases, DWORD Phase, double Temp) const { return SpMdl->PhaseConc(Valid(T)?T:SpMdl->Temp(), Phase, Phases); };
double MVector::DynamicViscosity(DWORD Phases, double T, double P) const { return SpMdl->DynamicViscosity(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::KinematicViscosity(DWORD Phases, double T, double P) const { return SpMdl->KinematicViscosity(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::ThermalConductivity(DWORD Phases, double T, double P) const { return SpMdl->ThermalConductivity(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::PrandtlNo(DWORD Phases, double T, double P) const { return SpMdl->PrandtlNo(Phases, Valid(T)?T:SpMdl->Temp(), Valid(P)?P:SpMdl->Press()); };
double MVector::SurfaceTension(DWORD Phases, double T, double P) const { return SpMdl->SurfaceTension(Phases, Valid(T)?T:SpMdl->Temp(), P); };
double MVector::HeatOfCombustionHi(DWORD Phases, double T, double P) const { return SpMdl->HeatOfCombustionHi(Phases, Valid(T)?T:SpMdl->Temp(), P); };
double MVector::HeatOfCombustionLo(DWORD Phases, double T, double P) const { return SpMdl->HeatOfCombustionLo(Phases, Valid(T)?T:SpMdl->Temp(), P); };
double MVector::SaturationTotalP(double T) const { return SpMdl->SaturationTotalP(Valid(T)?T:SpMdl->Temp()); };
double MVector::SaturationP(double T) const { return SpMdl->SaturationP(Valid(T)?T:SpMdl->Temp()); };
double MVector::SaturationT(double P) const { return SpMdl->SaturationT(Valid(P)?P:SpMdl->Press()); };
double MVector::PureSaturationP(double T) const { return SpMdl->PureSaturationP(Valid(T)?T:SpMdl->Temp()); };
double MVector::PureSaturationT(double P) const { return SpMdl->PureSaturationT(Valid(P)?P:SpMdl->Press()); };
double MVector::BoilingPtElevation(double P) const { return SpMdl->BoilingPtElevation(Valid(P)?P:SpMdl->Press()); };
#if DBG_MVECTOR
double MVector::msHfRaw() const { return SpMdl->m_msHf; };
#endif
// ----------------------------- Operations
void MVector::SetTP(double Temp, double Pres) { SpMdl->SetTempPress(Temp, Pres); };
void MVector::Set_msHs(double H, double Pres, MVector * pRefMdl) { SpMdl->Set_msHs(H, Pres, pRefMdl?pRefMdl->m_pSpMdl:NULL); };
void MVector::Set_msHz(double H, double Pres, MVector * pRefMdl) { SpMdl->Set_msHz(H, Pres, pRefMdl?pRefMdl->m_pSpMdl:NULL); };
void MVector::Set_msHf(double H, double Pres, MVector * pRefMdl) { SpMdl->Set_msHf(H, Pres, pRefMdl?pRefMdl->m_pSpMdl:NULL); };
void MVector::Set_totHs(double H, double Pres, MVector * pRefMdl) { SpMdl->Set_totHs(H, Pres, pRefMdl?pRefMdl->m_pSpMdl:NULL); };
void MVector::Set_totHz(double H, double Pres, MVector * pRefMdl) { SpMdl->Set_totHz(H, Pres, pRefMdl?pRefMdl->m_pSpMdl:NULL); };
void MVector::Set_totHf(double H, double Pres, MVector * pRefMdl) { SpMdl->Set_totHf(H, Pres, pRefMdl?pRefMdl->m_pSpMdl:NULL); };
void MVector::ZeroMass() { SpMdl->ZeroMass(); };
void MVector::ZeroDeriv() { SpMdl->ZeroDeriv(); };
void MVector::ScaleMass(DWORD Phases, double Mult) { SpMdl->ScaleMass(Phases, Mult); };
void MVector::AdjustMassTo(DWORD Phases, double RqdMass) { SpMdl->AdjustMassTo(Phases, RqdMass); };
void MVector::SetTraceMass() { SpMdl->SetTraceMass(); };
void MVector::SetF(MVector & Other, DWORD Phases, double Frac, double P) { SpMdl->SetMassF(Other.SpMdl, Phases, Frac, Finite(P) ? P:Other.P); };
void MVector::SetM(MVector & Other, DWORD Phases, double Mass, double P) { SpMdl->SetMassM(Other.SpMdl, Phases, Mass, Finite(P) ? P:Other.P); };
void MVector::AddF(MVector & Other, DWORD Phases, double Frac) { SpMdl->AddMassF(Other.SpMdl, Phases, Frac); };
void MVector::AddM(MVector & Other, DWORD Phases, double Mass) { SpMdl->AddMassM(Other.SpMdl, Phases, Mass); };
void MVector::SubF(MVector & Other, DWORD Phases, double Frac) { SpMdl->SubMassF(Other.SpMdl, Phases, Frac); };
void MVector::SubM(MVector & Other, DWORD Phases, double Mass) { SpMdl->SubMassM(Other.SpMdl, Phases, Mass); };
//---------------------------------------------------------------------------
MVector & MVector::operator=(const MVector & V)
{
for (int s=0; s<SDB.Count(); s++)
M[s]=V.M[s];
SetTP(V.T, V.P);
return *this;
};
//---------------------------------------------------------------------------
long MVector::Extract(DWORD PhMsk, double *pT, double *pP, double *pM, long MCount)
{
long N=SDB.Count(PhMsk);
if (pT)
*pT=T;
if (pP)
*pP=P;
if (pM)
{
if (MCount!=N)
throw new MMdlException(0, "Specie Count Mismatch");
for (int s=0; s<SDB.Count(); s++)
if (SDB[s].m_PhMsk & PhMsk)
*pM++=M[s];
}
return N;
};
//---------------------------------------------------------------------------
void MVector::SanityCheck(eSanity Check)
{
if (m_pSpMdl)
m_pSpMdl->SanityCheck(Check);
};
//---------------------------------------------------------------------------
long MVector::Replace(DWORD PhMsk, double TRqd, double PRqd, double *pMRqd, long MCount)
{
long N=SDB.Count(PhMsk);
if (!Valid(TRqd))
TRqd=T;
if (!Valid(PRqd))
PRqd=P;
if (pMRqd)
{
if (MCount!=N)
throw new MMdlException(0, "Specie Count Mismatch");
for (int s=0; s<SDB.Count(); s++)
if (SDB[s].m_PhMsk & PhMsk)
M[s]=*pMRqd++;
}
SetTP(TRqd, PRqd);
return N;
};
//---------------------------------------------------------------------------
MXSpModel * MVector::GetSpModel4Cast() { return SpMdl; };
MSpModelBase * MVector::GetMSpModelBase4Cast() { return SpMdl->GetMSpModelBase4Cast(); };
MXSpQuality * MVector::GetSpQuality4Cast(long i, bool Required) { return SpMdl->GetSpQuality4Cast(i, Required); };
MSpQualityBase * MVector::GetMSpQualityBase4Cast(long i, bool Required) { return SpMdl->GetMSpQualityBase4Cast(i, Required); };
long MVector::GetSpQualityCount4Cast() { return SpMdl->GetSpQualityCount4Cast(); };
//---------------------------------------------------------------------------
MIPSD * MVector::CreatePSD()
{
SQSzDist1::Ptr(SpMdl, true);
return getPSD();
}
//---------------------------------------------------------------------------
MIPSD * MVector::getPSD(long Index)
{
SQSzDist1 * pSz = SQSzDist1::Ptr(SpMdl, false);
if (pSz)
{
if (m_pPSD==NULL)
m_pPSD=new MIPSD(this, Index);
}
else
{
if (m_pPSD)
{
delete m_pPSD;
m_pPSD=NULL;
}
}
return m_pPSD;
};
//===========================================================================
//
//
//
//===========================================================================
MStream::MStream()
{
m_pMethod=NULL;
m_pCd=NULL;
//m_bOwned=false;
//Allocate();
}
//---------------------------------------------------------------------------
MStream::MStream(const MStream &Cd)
{
m_pMethod=NULL;
m_pCd=Cd.m_pCd;
//m_bOwned=false;
//Attach(Cn);
//Allocate();
//*this=Cd;
}
//---------------------------------------------------------------------------
MStream::MStream(SpConduit * pCd)
{
m_pMethod=NULL;
m_pCd=pCd;
//m_bOwned=false;
}
//---------------------------------------------------------------------------
//MStream::MStream(MBaseMethod * Method, LPCSTR Tag, LPCSTR SpMdlId)
// {
// ASSERT(Method!=NULL);
// m_pMethod=Method;
// m_pCd=NULL;
// m_bOwned=false;
// Allocate(Tag, SpMdlId);
// };
//---------------------------------------------------------------------------
//MStream::MStream(MBaseMethod * Method, LPCSTR Tag, MVector &V)
// {
// ASSERT(Method!=NULL);
// m_pMethod=Method;
// m_pCd=NULL;
// m_bOwned=false;
// Allocate(Tag, V);
// };
//---------------------------------------------------------------------------
MStream::~MStream()
{
//Detach();
}
//---------------------------------------------------------------------------
LPCTSTR MStream::getModelId() const { return m_pCd->Model()->ClassId(); };
void MStream::putModelId(LPCSTR ClassId) { m_pCd->SetModel((LPTSTR)ClassId, true); };
void MStream::putModelId(MVector & V) { m_pCd->SelectModel(V.SpMdl, false); };
//---------------------------------------------------------------------------
void MStream::SelectModel(MStream *V, double MassFlow)
{
CSpMdlSlct Slct;
Slct.Add(V->SpMdl, MassFlow);
m_pCd->SelectModel(Slct);
}
//---------------------------------------------------------------------------
void MStream::SelectModel(long NStreams, MStream *V, double *MassFlow)
{
CSpMdlSlct Slct;
for (int i=0; i<NStreams; i++)
Slct.Add(V[i].SpMdl, MassFlow[i]);
m_pCd->SelectModel(Slct);
}
//---------------------------------------------------------------------------
SpModel * MStream::getSpMdl() const
{
SpModel *p=m_pCd->Model();
if (!p) throw MMdlException(0,"Null Model Pointer");
return p;
} ;
//---------------------------------------------------------------------------
//void MStream::Attach(const MStream &Cn)
// {
// if (m_bOwned)
// delete m_pCd;
// m_bOwned=false;
// m_pCd=Cn.m_pCd;
// };
//
////---------------------------------------------------------------------------
//
//void MStream::Attach(SpConduit * pCd)
// {
// if (m_bOwned)
// delete m_pCd;
// m_bOwned=false;
// m_pCd=pCd;
// };
//
//---------------------------------------------------------------------------
static long ls_iTmpStreamTagNo=0;
void MStream::Allocate(LPCSTR Tag, LPCSTR SpMdlId)
{
//if (m_bOwned)
// delete m_pCd;
//m_bOwned=true;
if (Tag==NULL)
{
CString T;
T.Format("WorkStream%i", InterlockedIncrement(&ls_iTmpStreamTagNo));
m_pCd=new SpConduit((LPSTR)(LPCTSTR)T, m_pMethod ? m_pMethod->m_pNd:NULL, m_pMethod ? TOA_Embedded:TOA_Unknown);
}
else
m_pCd=new SpConduit((LPSTR)Tag, m_pMethod ? m_pMethod->m_pNd:NULL, m_pMethod ? TOA_Embedded:TOA_Unknown);
if (SpMdlId)
m_pCd->ChangeModel((LPTSTR)SpMdlId, true);
}
//---------------------------------------------------------------------------
void MStream::Allocate(LPCSTR Tag, MVector &V)
{
//if (m_bOwned)
// delete m_pCd;
//m_bOwned=true;
if (Tag==NULL)
{
CString T;
T.Format("%i", InterlockedIncrement(&ls_iTmpStreamTagNo));
m_pCd=new SpConduit((LPSTR)Tag, m_pMethod ? m_pMethod->m_pNd:NULL, m_pMethod ? TOA_Embedded:TOA_Unknown);
}
else
m_pCd=new SpConduit((LPSTR)Tag, m_pMethod ? m_pMethod->m_pNd:NULL, m_pMethod ? TOA_Embedded:TOA_Unknown);
m_pCd->ChangeModel(V.SpMdl->ClassId(), true);
}
//---------------------------------------------------------------------------
//void MStream::Detach()
// {
// if (m_bOwned)
// delete m_pCd;
// m_bOwned=false;
// m_pCd=NULL;
// }
//---------------------------------------------------------------------------
void MStream::CheckAttached()
{
if (m_pCd==NULL)
{
//m_bOwned=true;
//m_pCd=new SpConduit("Tag", m_pMethod ? m_pMethod->m_pNd:NULL, m_pMethod ? TOA_Embedded:TOA_Unknown);
}
};
//---------------------------------------------------------------------------
//MStream & MStream::operator=(const MStream & C)
// {
// m_pCd->QCopy(*C.m_pCd, C.P);
// return *this;
// }
//---------------------------------------------------------------------------
MStream & MStream::operator*=(const double &D)
{
m_pCd->pModel->ScaleMass(som_ALL, D);
return *this;
};
//---------------------------------------------------------------------------
MStream & MStream::operator=(const MStream & S)
{
Cd.QCopy(S.Cd, S.Cd.Press());
return *this;
};
//---------------------------------------------------------------------------
void MStream::Copy(const MStream & S, double P)
{
Cd.QCopy(S.Cd, Finite(P) ? P : S.Cd.Press());
};
//---------------------------------------------------------------------------
MStream::operator LPTAGGEDOBJECT() { return m_pCd; };
//---------------------------------------------------------------------------
double MStream::MassFlow(DWORD PhMsk) const { return m_pCd->QMass(PhMsk); };
double MStream::VolumeFlow(DWORD PhMsk, double T, double P) const
{
return m_pCd->QVolume(PhMsk, Valid(T)?T:m_pCd->Temp(), Valid(P)?P:m_pCd->Press());
};
double MStream::Density(DWORD PhMsk, double T, double P) const { return m_pCd->Rho(PhMsk, Valid(T)?T:m_pCd->Temp(), Valid(P)?P:m_pCd->Press()); };
double MStream::msCp(DWORD PhMsk, double T, double P) const { return m_pCd->msCp(PhMsk, Valid(T)?T:m_pCd->Temp(), Valid(P)?P:m_pCd->Press()); };
//===========================================================================
MStreamI::MStreamI()
{
m_pMethod=NULL;
m_pCd=NULL;
Allocate();
}
//---------------------------------------------------------------------------
MStreamI::MStreamI(const MStream &Cd)
{
m_pMethod=NULL;
m_pCd=NULL;//Cd.m_pCd;
//m_bOwned=false;
///Attach(Cn);
Allocate();
*(MStream*)m_pCd=Cd;
}
//---------------------------------------------------------------------------
//MStreamI::MStreamI(SpConduit * pCd)
// {
// m_pMethod=NULL;
// m_pCd=pCd;
// //m_bOwned=false;
// }
//---------------------------------------------------------------------------
MStreamI::MStreamI(MBaseMethod * Method, LPCSTR Tag, LPCSTR SpMdlId)
{
ASSERT(Method!=NULL);
m_pMethod=Method;
m_pCd=NULL;
//m_bOwned=false;
Allocate(Tag, SpMdlId);
};
//---------------------------------------------------------------------------
MStreamI::MStreamI(MBaseMethod * Method, LPCSTR Tag, MVector &V)
{
ASSERT(Method!=NULL);
m_pMethod=Method;
m_pCd=NULL;
//m_bOwned=false;
Allocate(Tag, V);
};
//---------------------------------------------------------------------------
MStreamI::~MStreamI()
{
delete m_pCd;
//Detach();
}
//===========================================================================
//
//
//
//===========================================================================
MContainer::MContainer()
{
m_pMethod=NULL;
m_pCn=NULL;
//m_bOwned=false;
//Allocate();
}
//---------------------------------------------------------------------------
MContainer::MContainer(const MContainer &Cn)
{
m_pMethod=NULL;
m_pCn=&Cn.Cn;
//m_bOwned=false;
////Attach(Cn);
//Allocate();
//*this=Cn;
}
//---------------------------------------------------------------------------
MContainer::MContainer(SpContainer* pCn)
{
m_pMethod=NULL;
m_pCn=pCn;
//m_bOwned=false;
}
//---------------------------------------------------------------------------
MContainer::~MContainer()
{
}
//---------------------------------------------------------------------------
LPCTSTR MContainer::getModelId() const { return m_pCn->Model()->ClassId(); };
void MContainer::putModelId(LPCSTR ClassId) { m_pCn->SetModel((LPTSTR)ClassId, true); };
void MContainer::putModelId(MVector & V) { m_pCn->SelectModel(V.SpMdl, false); };
//---------------------------------------------------------------------------
SpModel * MContainer::getSpMdl() const
{
SpModel *p=m_pCn->Model();
if (!p) throw MMdlException(0,"Null Model Pointer");
return p;
} ;
//---------------------------------------------------------------------------
//void MContainer::Attach(const MContainer &Cn)
// {
// if (m_bOwned)
// delete m_pCn;
// m_bOwned=false;
// m_pCn=Cn.m_pCn;
// };
//
////---------------------------------------------------------------------------
//
//void MContainer::Attach(SpContainer * pCn)
// {
// if (m_bOwned)
// delete m_pCn;
// m_bOwned=false;
// m_pCn=pCn;
// };
//---------------------------------------------------------------------------
void MContainer::Allocate(LPCSTR Tag, LPCSTR SpMdlId)
{
//if (m_bOwned)
// delete m_pCn;
//m_bOwned=true;
m_pCn=new SpContainer((LPSTR)Tag, m_pMethod ? m_pMethod->m_pNd:NULL, m_pMethod ? TOA_Embedded:TOA_Unknown);
if (SpMdlId)
m_pCn->ChangeModel((LPTSTR)SpMdlId, true);
}
//---------------------------------------------------------------------------
void MContainer::Allocate(LPCSTR Tag, MVector &V)
{
//if (m_bOwned)
// delete m_pCn;
//m_bOwned=true;
m_pCn=new SpContainer((LPSTR)Tag, m_pMethod ? m_pMethod->m_pNd:NULL, m_pMethod ? TOA_Embedded:TOA_Unknown);
m_pCn->ChangeModel(V.SpMdl->ClassId(), true);
}
//---------------------------------------------------------------------------
//void MContainer::Detach()
// {
// if (m_bOwned)
// delete m_pCn;
// m_bOwned=false;
// m_pCn=NULL;
// }
//
////---------------------------------------------------------------------------
//
void MContainer::CheckAttached()
{
if (m_pCn==NULL)
{
//m_bOwned=true;
//m_pCn=new SpContainer("Tag", m_pMethod ? m_pMethod->m_pNd:NULL, m_pMethod ? TOA_Embedded:TOA_Unknown);
}
};
//---------------------------------------------------------------------------
MContainer & MContainer::operator*=(const double &D)
{
m_pCn->pModel->ScaleMass(som_ALL, D);
return *this;
};
//---------------------------------------------------------------------------
MContainer& MContainer::operator=(const MContainer & S)
{
Cn.Copy(S.Cn);
return *this;
};
//---------------------------------------------------------------------------
MContainer::operator LPTAGGEDOBJECT() { return m_pCn; };
//---------------------------------------------------------------------------
double MContainer::Mass(DWORD PhMsk) const { return m_pCn->Mass(PhMsk); };
double MContainer::Volume(DWORD PhMsk, double T, double P) const { return m_pCn->Volume(PhMsk, Valid(T)?T:m_pCn->Temp(), Valid(P)?P:m_pCn->Press()); };
double MContainer::Density(DWORD PhMsk, double T, double P) const { return m_pCn->Rho(PhMsk, Valid(T)?T:m_pCn->Temp(), Valid(P)?P:m_pCn->Press()); };
double MContainer::msCp(DWORD PhMsk, double T, double P) const { return m_pCn->msCp(PhMsk, Valid(T)?T:m_pCn->Temp(), Valid(P)?P:m_pCn->Press()); };
//---------------------------------------------------------------------------
MContainerI::MContainerI(MBaseMethod * Method, LPCSTR Tag, LPCSTR SpMdlDesc)
{
ASSERT(Method!=NULL);
m_pMethod=Method;
m_pCn=NULL;
//m_bOwned=false;
Allocate(Tag, SpMdlDesc);
};
//---------------------------------------------------------------------------
MContainerI::MContainerI(MBaseMethod * Method, LPCSTR Tag, MVector &V)
{
ASSERT(Method!=NULL);
m_pMethod=Method;
m_pCn=NULL;
//m_bOwned=false;
Allocate(Tag, V);
};
//---------------------------------------------------------------------------
MContainerI::~MContainerI()
{
delete m_pCn;
//Detach();
}
//===========================================================================
//
//
//
//===========================================================================
| [
"[email protected]",
"[email protected]"
] | [
[
[
1,
180
],
[
187,
200
],
[
208,
217
],
[
249,
254
],
[
256,
263
],
[
265,
272
],
[
274,
291
],
[
293,
303
],
[
305,
328
],
[
330,
348
],
[
350,
355
],
[
360,
411
],
[
420,
440
],
[
446,
486
],
[
489,
492
],
[
494,
495
],
[
501,
508
],
[
510,
513
],
[
522,
524
],
[
533,
537
],
[
539,
578
],
[
597,
602
],
[
605,
605
],
[
607,
622
],
[
625,
625
],
[
627,
639
],
[
647,
653
],
[
656,
705
],
[
707,
708
],
[
711,
714
],
[
716,
717
],
[
723,
726
],
[
733,
735
],
[
737,
739
],
[
743,
746
],
[
748,
750
],
[
753,
757
],
[
800,
820
],
[
838,
842
],
[
845,
845
],
[
847,
855
],
[
858,
858
],
[
860,
865
],
[
876,
879
],
[
882,
894
],
[
903,
911
],
[
942,
946
]
],
[
[
181,
186
],
[
201,
207
],
[
218,
248
],
[
255,
255
],
[
264,
264
],
[
273,
273
],
[
292,
292
],
[
304,
304
],
[
329,
329
],
[
349,
349
],
[
356,
359
],
[
412,
419
],
[
441,
445
],
[
487,
488
],
[
493,
493
],
[
496,
500
],
[
509,
509
],
[
514,
521
],
[
525,
532
],
[
538,
538
],
[
579,
596
],
[
603,
604
],
[
606,
606
],
[
623,
624
],
[
626,
626
],
[
640,
646
],
[
654,
655
],
[
706,
706
],
[
709,
710
],
[
715,
715
],
[
718,
722
],
[
727,
732
],
[
736,
736
],
[
740,
742
],
[
747,
747
],
[
751,
752
],
[
758,
799
],
[
821,
837
],
[
843,
844
],
[
846,
846
],
[
856,
857
],
[
859,
859
],
[
866,
875
],
[
880,
881
],
[
895,
902
],
[
912,
941
]
]
] |
e5e05f95b5e4e9d32cc48cefe88c912b8287a8fd | 21da454a8f032d6ad63ca9460656c1e04440310e | /src/wcpp/wscom/wsiModule.h | 5849b7e9216d2e7fca3cc2b4e65c7bf1da9bab6e | [] | 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 | 858 | h | #pragma once
#include <wcpp/lang/wsiObject.h>
class wsiComponentManager;
class wsiFile;
class wsiCString;
#define WS_IID_OF_wsiModule \
{ 0x3dccf5d0, 0x9a7, 0x42cf, { 0xa9, 0x73, 0x1, 0xbc, 0x62, 0x61, 0x74, 0x24 } }
// {3DCCF5D0-09A7-42cf-A973-01BC62617424}
class wsiModule : public wsiObject
{
public:
static const ws_iid sIID;
public:
WS_METHOD( ws_result, GetClassObject )(wsiComponentManager * aCompMgr, const ws_cid & aCID, const ws_iid & aIID, void ** ret) = 0;
WS_METHOD( ws_result, RegisterSelf )(wsiComponentManager * aCompMgr, wsiFile * aLocation, wsiString * aLoaderStr, wsiString * aType) = 0;
WS_METHOD( ws_result, UnregisterSelf )(wsiComponentManager * aCompMgr, wsiFile * aLocation, wsiString * aLoaderStr) = 0;
WS_METHOD( ws_boolean, CanUnload )(wsiComponentManager * aCompMgr) = 0;
};
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
] | [
[
[
1,
25
]
]
] |
642e9cfd6a1750d615231b2bcf6b8ef0b02dd261 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/nebula2/src/gui/nguilinelayout_main.cc | 8b5e4beb0cba1bf45a6b03a8670d8dadf5c8aeef | [] | 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 | 4,504 | cc | #include "precompiled/pchngui.h"
//------------------------------------------------------------------------------
// nguilinelayout_main.cc
// (C) 2006 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "gui/nguilinelayout.h"
#include "gui/nguicheckbutton.h"
#include "gui/nguievent.h"
#include "gui/nguiserver.h"
nNebulaScriptClass(nGuiLineLayout, "nguiformlayout");
//------------------------------------------------------------------------------
/**
*/
nGuiLineLayout::nGuiLineLayout() :
orientation( ORI_HORIZONTAL ),
order( ORDER_NORMAL ),
aligned( true )
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
nGuiLineLayout::~nGuiLineLayout()
{
// empty
}
//------------------------------------------------------------------------------
/**
@brief Set horizontal or vertical orientation of layout
*/
void
nGuiLineLayout::SetOrientation( Orientation orientation )
{
this->orientation = orientation;
}
//------------------------------------------------------------------------------
/**
@brief Set normal or reversed order of child widgets
*/
void
nGuiLineLayout::SetOrder( Order order)
{
this->order = order;
}
//------------------------------------------------------------------------------
/**
@brief Set aligned
@param aligned Aligned flag. False means childs are centered in the other axis
*/
void
nGuiLineLayout::SetAligned( bool aligned )
{
this->aligned = aligned;
}
//------------------------------------------------------------------------------
/**
@brief Get aligned flag
*/
bool
nGuiLineLayout::GetAligned()
{
return this->aligned;
}
//------------------------------------------------------------------------------
/**
*/
void
nGuiLineLayout::OnShow()
{
nGuiFormLayout::OnShow();
this->UpdateLayout(this->GetRect());
}
//------------------------------------------------------------------------------
/**
Called when the size of the widget changes. Will re-apply the layout
rules on its children widgets.
*/
void
nGuiLineLayout::OnRectChange(const rectangle& newRect)
{
if (this->IsShown())
{
this->UpdateLayout( newRect );
}
nGuiWidget::OnRectChange(newRect);
}
//------------------------------------------------------------------------------
/**
@brief Update child widgets position
*/
void
nGuiLineLayout::UpdateLayout(const rectangle& newRect)
{
float rectWidth = newRect.width();
float rectHeight = newRect.height();
float rectCenterX = rectWidth / 2.0f;
float rectCenterY = rectHeight / 2.0f;
nGuiWidget* curWidget;
float currentPos = 0.0f;
for (curWidget = (nGuiWidget*) this->GetHead(); curWidget; curWidget = (nGuiWidget*) curWidget->GetSucc())
{
if ( curWidget->IsShown() )
{
rectangle widgetRect;
if ( this->orientation == ORI_HORIZONTAL )
{
// get min width and max height
float minWidth = curWidget->GetMinSize().x;
float maxHeight = min( curWidget->GetMaxSize().y, rectHeight );
vector2 v0(currentPos, rectCenterY - maxHeight / 2.0f );
vector2 v1( currentPos + minWidth, rectCenterY + maxHeight / 2.0f );
if ( this->aligned )
{
v0.y = 0.0f;
v1.y = maxHeight;
}
widgetRect.set( v0, v1 );
currentPos += minWidth;
}
else
{
// get max height and min width
float maxWidth = min( curWidget->GetMaxSize().x, rectWidth );
float minHeight = curWidget->GetMinSize().y;
vector2 v0( rectCenterX - maxWidth / 2.0f, currentPos );
vector2 v1( rectCenterX + maxWidth / 2.0f, currentPos + minHeight );
if ( this->aligned )
{
v0.x = 0.0f;
v1.x = maxWidth;
}
widgetRect.set( v0, v1 );
currentPos += minHeight;
}
curWidget->SetRect( widgetRect );
}
}
}
//------------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
] | [
[
[
1,
155
]
]
] |
8d8a6e065b64a658ffa9e1930e594c1afa95bb10 | 46b3500c9ab98883091eb9d4ca49a6854451d76b | /ghost/gpsprotocol.h | 930cd4938f8869a1d73721f92956431a125b673b | [
"Apache-2.0"
] | permissive | kr4uzi/pyghost | 7baa511fa05ddaba57880d2c7483694d5c5816b7 | 35e5bdd838cb21ad57b3c686349251eb277d2e6a | refs/heads/master | 2020-04-25T21:05:20.995556 | 2010-11-21T13:57:49 | 2010-11-21T13:57:49 | 42,011,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,685 | h | /*
Copyright 2010 Trevor Hogan
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.
*/
#ifndef GPSPROTOCOL_H
#define GPSPROTOCOL_H
//
// CGameProtocol
//
#define GPS_HEADER_CONSTANT 248
#define REJECTGPS_INVALID 1
#define REJECTGPS_NOTFOUND 2
class CGPSProtocol
{
public:
enum Protocol {
GPS_INIT = 1,
GPS_RECONNECT = 2,
GPS_ACK = 3,
GPS_REJECT = 4
};
CGPSProtocol( );
~CGPSProtocol( );
// receive functions
// send functions
BYTEARRAY SEND_GPSC_INIT( uint32_t version );
BYTEARRAY SEND_GPSC_RECONNECT( unsigned char PID, uint32_t reconnectKey, uint32_t lastPacket );
BYTEARRAY SEND_GPSC_ACK( uint32_t lastPacket );
BYTEARRAY SEND_GPSS_INIT( uint16_t reconnectPort, unsigned char PID, uint32_t reconnectKey, unsigned char numEmptyActions );
BYTEARRAY SEND_GPSS_RECONNECT( uint32_t lastPacket );
BYTEARRAY SEND_GPSS_ACK( uint32_t lastPacket );
BYTEARRAY SEND_GPSS_REJECT( uint32_t reason );
// other functions
private:
bool AssignLength( BYTEARRAY &content );
bool ValidateLength( BYTEARRAY &content );
public:
static void RegisterPythonClass( );
};
#endif
| [
"kr4uzi@88aed30e-2b04-91ce-7a47-0ae997e79d63"
] | [
[
[
1,
67
]
]
] |
35cf5978d460e5bc579f2416f43798bea76475a6 | 216398e30aca5f7874edfb8b72a13f95c22fbb5a | /DBTerm/DBManager/LoginDlg.h | dcaa9eb827a30264163e7f1aa4821406ae28c765 | [] | no_license | markisme/healthcare | 791813ac6ac811870f3f28d1d31c3d5a07fb2fa2 | 7ab5a959deba02e7637da02a3f3c681548871520 | refs/heads/master | 2021-01-10T07:18:42.195610 | 2009-09-09T13:00:10 | 2009-09-09T13:00:10 | 35,987,767 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 781 | h | #pragma once
#include "Resource.h"
#include <string>
class LoginDlg : public CDialog
{
DECLARE_DYNAMIC(LoginDlg)
public:
LoginDlg(CWnd* pParent = NULL); // 표준 생성자입니다.
virtual ~LoginDlg();
// 대화 상자 데이터입니다.
enum { IDD = IDD_LOGIN_DLG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
static UINT ThreadFunction(LPVOID pParam);
void ThreadDo();
private:
CEdit _editAddr;
CEdit _editID;
CEdit _editPass;
CEdit _editPort;
CEdit _editDB;
public:
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnBnClickedOk();
};
| [
"naidzzang@cc586c1e-b153-0410-8069-cfc9d6f95ec9"
] | [
[
[
1,
38
]
]
] |
07a57f8ff328c8646f510b199a15260d50a36c07 | 6b75de27b75015e5622bfcedbee0bf65e1c6755d | /huffman-tree/3.cpp | 9a6723685125029346ae30d8bc6e34f298fb3d83 | [] | no_license | xhbang/data_structure | 6e4ac9170715c0e45b78f8a1b66c838f4031a638 | df2ff9994c2d7969788f53d90291608ac5b1ef2b | refs/heads/master | 2020-04-04T02:07:18.620014 | 2011-12-05T09:39:34 | 2011-12-05T09:39:34 | 2,393,408 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,731 | cpp | //哈弗曼树
template<class T>
class Huffman {
friend BinaryTree<int> HuffmanTree(T [], int);
public:
operator T () const {return weight;}
public:
BinaryTree<int> tree;
T weight;
};
template <class T>
BinaryTree<int> HuffmanTree(T a[], int n)
{
//根据权重数组a[1->n] 构造霍夫曼树
//创建一个单节点树的数组
Huffman<T> *w = new Huffman<T> [n+1];
BinaryTree<int> z, zero;
for (int i = 1; i <= n; i++)
{
z.MakeTree(i, zero, zero);
w[i].weight = a[i];
w[i].tree = z;
}
//把数组变成一个最小堆
MinHeap<Huffman<T> > H(1);
H.Initialize(w,n,n);
//将堆中的树不断合并
Huffman<T> x, y;
for (int i = 1; i < n; i++)
{
H.DeleteMin(x);
H.DeleteMin(y);
z.MakeTree(0, x.tree, y.tree);
x.weight += y.weight; x.tree = z;
H.Insert(x);
}
H.DeleteMin(x); //得到霍夫曼树
H.Deactivate();
delete [] w;
return x.tree;
}
//队列
template <class T>
class Node {
friend LinkedStack<T>;
friend LinkedQueue<T>;
private:
T data;
Node<T> *link;
};
template<class T>
class LinkedQueue
{
public:
LinkedQueue() {front = rear = 0;}
~LinkedQueue();
bool IsEmpty() const {return ((front) ? false : true);}
bool IsFull() const;
T First() const; // 返回第一个元素
T Last() const; // 返回最后一个元素
LinkedQueue<T>& Add(const T& x);
LinkedQueue<T>& Delete(T& x);
private:
Node<T> *front; // 指向第一个节点
Node<T> *rear; // 指向最后一个节点
};
template<class T>
LinkedQueue<T>::~LinkedQueue()
{
Node<T> *next;
while (front)
{
next = front->link;
delete front;
front = next;
}
}
template<class T>
bool LinkedQueue<T>::IsFull() const
{
// 判断队列是否已满
Node<T> *p;
try
{
p = new Node<T>;
delete p;
return false;
}
catch (NoMem)
{
return true;
}
}
template<class T>
T LinkedQueue<T>::First() const
{
if (IsEmpty())
throw OutOfBounds();
return front->data;
}
template<class T>
T LinkedQueue<T>::Last() const
{
if (IsEmpty())
throw OutOfBounds();
return rear->data;
}
template<class T>
LinkedQueue<T>& LinkedQueue<T>::Add(const T& x)
{
Node<T> *p = new Node<T>;
p->data = x;
p->link = 0;
// 在队列尾部添加新节点
if (front)
rear->link = p;
else
front = p;
rear = p;
return *this;
}
template<class T>
LinkedQueue<T>& LinkedQueue<T>::Delete(T& x)
{
if (IsEmpty())
throw OutOfBounds();
x = front->data;
// 删除第一个节点
Node<T> *p = front;
front = front->link;
delete p;
return *this;
}
//二叉树
template <class T>
class BinaryTreeNode {
friend BinaryTree<T>;
friend BSTree<T,int>;
friend DBSTree<T,int>;
public:
BinaryTreeNode() {LeftChild = RightChild = 0;}
BinaryTreeNode(const T& e){data = e; LeftChild = RightChild = 0;}
BinaryTreeNode(const T& e, BinaryTreeNode *l,BinaryTreeNode *r) {data = e; LeftChild = l; RightChild = r;}
private:
T data;
BinaryTreeNode<T> *LeftChild, // 左子树
*RightChild; // 右子树
};
template<class T>
class BinaryTree
{
friend BSTree<T,int>;
friend DBSTree<T,int>;
public:
BinaryTree() {root = 0;};
~BinaryTree(){};
bool IsEmpty() const {return ((root) ? false : true);}
bool Root(T& x) const;
void MakeTree(const T& element, BinaryTree<T>& left, BinaryTree<T>& right);
void BreakTree(T& element, BinaryTree<T>& left, BinaryTree<T>& right);
void PreOrder(void(*Visit)(BinaryTreeNode<T> *u)) {PreOrder(Visit, root);}
void InOrder(void(*Visit)(BinaryTreeNode<T> *u)) {InOrder(Visit, root);}
void PostOrder(void(*Visit)(BinaryTreeNode<T> *u)) {PostOrder(Visit, root);}
void LevelOrder(void(*Visit)(BinaryTreeNode<T> *u));
void PreOutput() {PreOrder(Output, root); cout << endl;}
void InOutput() {InOrder(Output, root); cout << endl;}
void PostOutput() {PostOrder(Output, root); cout << endl;}
void LevelOutput() {LevelOrder(Output); cout << endl;}
void Delete() {PostOrder(Free, root); root = 0;}
int Height() const {return Height(root);}
int Size(){_count = 0; PreOrder(Add1, root); return _count;}
private:
BinaryTreeNode<T> *root;
void PreOrder(void(*Visit)(BinaryTreeNode<T> *u), BinaryTreeNode<T> *t);
void InOrder(void(*Visit)(BinaryTreeNode<T> *u), BinaryTreeNode<T> *t);
void PostOrder(void(*Visit)(BinaryTreeNode<T> *u), BinaryTreeNode<T> *t);
static void Free(BinaryTreeNode<T> *t) {delete t;}
static void Output(BinaryTreeNode<T> *t) {cout << t->data << ' ';}
static void Add1(BinaryTreeNode<T> *t) {_count++;}
int Height(BinaryTreeNode<T> *t) const;
};
template<class T>
bool BinaryTree<T>::Root(T& x) const
{
if (root)
{
x = root->data;
return true;
}
else
{
// 没有根节点
return false;
}
}
template<class T>
void BinaryTree<T>::MakeTree(const T& element, BinaryTree<T>& left, BinaryTree<T>& right)
{
//将left, right 和 element合并成一棵新树,left,right和this必须是不同的树
root = new BinaryTreeNode<T>(element, left.root, right.root);
// 阻止访问left和right
left.root = right.root = 0;
}
template<class T>
void BinaryTree<T>::BreakTree(T& element, BinaryTree<T>& left, BinaryTree<T>& right)
{
if (!root)
throw BadInput();
//分解树
element = root->data;
left.root = root->LeftChild;
right.root = root->RightChild;
delete root;
root = 0;
}
template<class T>
void BinaryTree<T>::PreOrder( void(*Visit)(BinaryTreeNode<T> *u), BinaryTreeNode<T> *t)
{
if(t)
{
Visit(t);
PreOrder(Visit, t->LeftChild);
PreOrder(Visit, t->RightChild);
}
}
template <class T>
void BinaryTree<T>::InOrder(void(*Visit)(BinaryTreeNode<T> *u), BinaryTreeNode<T> *t)
{
if(t)
{
InOrder(Visit, t->LeftChild);
Visit(t);
InOrder(Visit, t->RightChild);
}
}
template <class T>
void BinaryTree<T>::PostOrder(void(*Visit)(BinaryTreeNode<T> *u),BinaryTreeNode<T> *t)
{
if(t)
{
PostOrder(Visit, t->LeftChild);
PostOrder(Visit, t->RightChild);
Visit(t);
}
}
template <class T>
void BinaryTree<T>::LevelOrder(void(*Visit)(BinaryTreeNode<T> *u))
{
LinkedQueue<BinaryTreeNode<T>*> Q;
BinaryTreeNode<T> *t;
t = root;
while (t)
{
Visit(t);
if (t->LeftChild)
Q.Add(t->LeftChild);
if (t->RightChild)
Q.Add(t->RightChild);
try
{
Q.Delete(t);
}
catch(OutOfBounds)
{
return;
}
}
}
template <class T>
int BinaryTree<T>::Height(BinaryTreeNode<T> *t) const
{
if(!t)
return 0;
int hl = Height(t->LeftChild);
int hr = Height(t->RightChild);
if(hl > hr)
return ++hl;
else
return ++hr;
} | [
"[email protected]"
] | [
[
[
1,
326
]
]
] |
1db81fb53e650cff25fcb7f8afc862b5e6244b28 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/opwolf.h | 681a9761dc950bb8348b414b98898870125a28ef | [] | no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,799 | h | /*************************************************************************
Operation Wolf
*************************************************************************/
class opwolf_state : public driver_device
{
public:
opwolf_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
/* memory pointers */
UINT8 * m_cchip_ram;
/* video-related */
UINT16 m_sprite_ctrl;
UINT16 m_sprites_flipscreen;
/* misc */
UINT8 m_adpcm_b[0x08];
UINT8 m_adpcm_c[0x08];
UINT32 m_adpcm_pos[2];
UINT32 m_adpcm_end[2];
int m_adpcm_data[2];
int m_opwolf_gun_xoffs;
int m_opwolf_gun_yoffs;
/* c-chip */
int m_opwolf_region;
UINT8 m_current_bank;
UINT8 m_current_cmd;
UINT8 m_cchip_last_7a;
UINT8 m_cchip_last_04;
UINT8 m_cchip_last_05;
UINT8 m_cchip_coins_for_credit[2];
UINT8 m_cchip_credits_for_coin[2];
UINT8 m_cchip_coins[2];
UINT8 m_c588;
UINT8 m_c589;
UINT8 m_c58a; // These variables derived from the bootleg
/* devices */
cpu_device *m_maincpu;
cpu_device *m_audiocpu;
device_t *m_pc080sn;
device_t *m_pc090oj;
device_t *m_msm1;
device_t *m_msm2;
};
/*----------- defined in machine/opwolf.c -----------*/
void opwolf_cchip_init(running_machine &machine);
READ16_HANDLER( opwolf_cchip_status_r );
READ16_HANDLER( opwolf_cchip_data_r );
WRITE16_HANDLER( opwolf_cchip_status_w );
WRITE16_HANDLER( opwolf_cchip_data_w );
WRITE16_HANDLER( opwolf_cchip_bank_w );
/*----------- defined in video/opwolf.c -----------*/
WRITE16_HANDLER( opwolf_spritectrl_w );
SCREEN_UPDATE( opwolf );
| [
"Mike@localhost"
] | [
[
[
1,
70
]
]
] |
c56e88009fa1378c72f16380676e0a5fb86f7974 | 6581dacb25182f7f5d7afb39975dc622914defc7 | /CodeProject/ExcelAddinInEasyIF/FloatBtn.cpp | 757d315c9c9971a083af81d29c4f2889d98187dc | [] | no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,839 | cpp | // FloatBtn.cpp : implementation file
//
#include "stdafx.h"
#include "EMX.h"
#include "FloatBtn.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// FloatBtn
FloatBtn::FloatBtn()
{
}
FloatBtn::~FloatBtn()
{
}
BEGIN_MESSAGE_MAP(FloatBtn, CButton)
//{{AFX_MSG_MAP(FloatBtn)
// NOTE - the ClassWizard will add and remove mapping macros here.
ON_NOTIFY_EX_RANGE( TTN_NEEDTEXT, 0, 0xFFFF, OnToolTipNotify )
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// FloatBtn message handlers
BOOL FloatBtn::OnToolTipNotify( UINT id, NMHDR * pNMHDR, LRESULT * pResult )
{
TOOLTIPTEXT *pTTT = (TOOLTIPTEXT *)pNMHDR;
char caBuf[256];
sprintf(caBuf,"Number=%d,Hex=%X",pNMHDR->idFrom,pNMHDR->idFrom);
::MessageBox(NULL,caBuf,"DEBUG-TOOLTIPS",MB_OK);
UINT nID = pNMHDR->idFrom;
if (pTTT->uFlags & TTF_IDISHWND)
{
// idFrom is actually the HWND of the tool
nID = ::GetDlgCtrlID((HWND)nID);
if (nID)
{
switch (nID)
{
case 9873: // hide btn
pTTT->lpszText = MAKEINTRESOURCE(IDS_FLOATHIDEBTN);
break;
case 9874: // refresh
pTTT->lpszText = MAKEINTRESOURCE(IDS_FLOATREFRESHBTN);
break;
case 9875: // Create new
pTTT->lpszText = MAKEINTRESOURCE(IDS_FLOATCREATENEWBTN);
break;
default:
return FALSE;
break;
}
pTTT->hinst = AfxGetResourceHandle();
return(TRUE);
}
}
return(FALSE);
}
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
] | [
[
[
1,
76
]
]
] |
533107a1924ac1fd59edf5e3c6ac499c8e7215d6 | 9ac7606c5aa3e851a597cca2cd64682d79940ed1 | /labpro-sdk/LabPro_console_src/LabPro_consoleDoc.cpp | 0cf09ce9cf8827fedf5fa48b43a4767bb271fc59 | [] | no_license | concord-consortium/labpro-usb | 18422f703f43d672cceb32eb7dae208a0b137274 | ad87bd11d3b574f51ac59b128db86aee9f449200 | HEAD | 2016-09-06T14:22:35.102192 | 2011-11-01T22:24:12 | 2011-11-01T22:24:12 | 2,369,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,974 | cpp | // LabPro_consoleDoc.cpp : implementation of the CLabPro_consoleDoc class
//
#include "stdafx.h"
#include "LabPro_console.h"
#include "LabPro_consoleDoc.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CLabPro_consoleDoc
IMPLEMENT_DYNCREATE(CLabPro_consoleDoc, CDocument)
BEGIN_MESSAGE_MAP(CLabPro_consoleDoc, CDocument)
//{{AFX_MSG_MAP(CLabPro_consoleDoc)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CLabPro_consoleDoc construction/destruction
CLabPro_consoleDoc::CLabPro_consoleDoc()
{
m_LabPro_nNumChannels = 1;
m_LabPro_bBinaryMode = 0;
m_LabPro_bRealTime = 0;
m_input_buffer_next_byte_index = 0;
}
CLabPro_consoleDoc::~CLabPro_consoleDoc()
{
}
BOOL CLabPro_consoleDoc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
// TODO: add reinitialization code here
// (SDI documents will reuse this document)
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CLabPro_consoleDoc serialization
void CLabPro_consoleDoc::Serialize(CArchive& ar)
{
if (ar.IsStoring())
{
// TODO: add storing code here
}
else
{
// TODO: add loading code here
}
}
/////////////////////////////////////////////////////////////////////////////
// CLabPro_consoleDoc diagnostics
#ifdef _DEBUG
void CLabPro_consoleDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CLabPro_consoleDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CLabPro_consoleDoc commands
| [
"scytacki@6e01202a-0783-4428-890a-84243c50cc2b"
] | [
[
[
1,
86
]
]
] |
1645251c22417a2495bae12e94b65abccf0017ed | 96e96a73920734376fd5c90eb8979509a2da25c0 | /C3DE/GrassFX.cpp | e55f2da9b0f0ae25635f536ac79936f57ac42517 | [] | 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 | 2,174 | cpp | #include "GrassFX.h"
#include "DebugMemory.h"
GrassFX::GrassFX(ID3DXEffect *effect):
FX(effect)
{
//mhGrassTech = mGrassFX->GetTechniqueByName("GrassTech");
//mhGrassViewProj = mGrassFX->GetParameterByName(0, "gViewProj");
//mhGrassTex = mGrassFX->GetParameterByName(0, "gTex");
m_shaderGrassTime = m_effect->GetParameterByName(0, "gTime");
//mhGrassEyePosW = mGrassFX->GetParameterByName(0, "gEyePosW");
m_shaderGrassDirToSunW= m_effect->GetParameterByName(0, "gDirToSunW");
//HR(mGrassFX->SetTechnique(mhGrassTech));
//HR(mGrassFX->SetTexture(mhGrassTex, mGrassTex));
m_shaderObjectAmbientMaterial = m_effect->GetParameterByName(0, "gAmbientMtrl");
m_shaderObjectDiffuseMaterial = m_effect->GetParameterByName(0, "gDiffuseMtrl");
m_shaderObjectSpecularMaterial = m_effect->GetParameterByName(0, "gSpecularMtrl");
m_shaderSpecularLightPower = m_effect->GetParameterByName(0, "gSpecularPower");
m_shaderAlpha = m_effect->GetParameterByName(0, "gAlpha");
m_hTex = m_effect->GetParameterByName(0, "gTex");
//HR(m_effect->SetTexture(mhGrassTex, mGrassTex));
}
void GrassFX::SetTime(float a_time)
{
HR(m_effect->SetValue(m_shaderGrassTime, &a_time,sizeof(float)));
}
GrassFX::~GrassFX()
{
}
void GrassFX::ResetHandlers()
{
D3DXMATRIX T;
D3DXMatrixIdentity(&T);
SetTransformMatrix(T);
}
void GrassFX::SetObjectMaterials(D3DXCOLOR ambientMaterial, D3DXCOLOR diffuseMaterial,
D3DXCOLOR specularMaterial, float specularPower)
{
HR(m_effect->SetValue(m_shaderObjectAmbientMaterial, &ambientMaterial,sizeof(D3DXCOLOR)));
HR(m_effect->SetValue(m_shaderObjectDiffuseMaterial, &diffuseMaterial, sizeof(D3DXCOLOR)));
HR(m_effect->SetValue(m_shaderObjectSpecularMaterial, &specularMaterial, sizeof(D3DXCOLOR)));
HR(m_effect->SetFloat(m_shaderSpecularLightPower, specularPower));
}
void GrassFX::SetObjectTexture(IDirect3DTexture9 *texture)
{
if(texture)
{
HR(m_effect->SetTexture(m_hTex, texture));
}
}
void GrassFX::SetAlpha(float alpha)
{
HR(m_effect->SetFloat(m_shaderAlpha, alpha));
} | [
"caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158"
] | [
[
[
1,
99
]
]
] |
87d1b9e2387b4a3dfeb323f9c14c2a646a9f544c | a2ba072a87ab830f5343022ed11b4ac365f58ef0 | / urt-bumpy-q3map2 --username [email protected]/libs/modulesystem/singletonmodule.h | d60a16799c641ed95f34ce87b64e2f88f006524c | [] | no_license | Garey27/urt-bumpy-q3map2 | 7d0849fc8eb333d9007213b641138e8517aa092a | fcc567a04facada74f60306c01e68f410cb5a111 | refs/heads/master | 2021-01-10T17:24:51.991794 | 2010-06-22T13:19:24 | 2010-06-22T13:19:24 | 43,057,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,053 | h |
#if !defined(INCLUDED_MODULESYSTEM_SINGLETONMODULE_H)
#define INCLUDED_MODULESYSTEM_SINGLETONMODULE_H
#include "modulesystem.h"
#include <cstddef>
#include "debugging/debugging.h"
#include "modulesystem/moduleregistry.h"
#include "generic/reference.h"
template<typename API, typename Dependencies>
class DefaultAPIConstructor
{
public:
const char* getName()
{
return API::getName();
}
API* constructAPI(Dependencies& dependencies)
{
return new API;
}
void destroyAPI(API* api)
{
delete api;
}
};
template<typename API, typename Dependencies>
class DependenciesAPIConstructor
{
public:
const char* getName()
{
return API::getName();
}
API* constructAPI(Dependencies& dependencies)
{
return new API(dependencies);
}
void destroyAPI(API* api)
{
delete api;
}
};
class NullDependencies
{
};
template<typename API, typename Dependencies = NullDependencies, typename APIConstructor = DefaultAPIConstructor<API, Dependencies> >
class SingletonModule : public APIConstructor, public Module, public ModuleRegisterable
{
Dependencies* m_dependencies;
API* m_api;
std::size_t m_refcount;
bool m_dependencyCheck;
bool m_cycleCheck;
public:
typedef typename API::Type Type;
SingletonModule()
: m_dependencies(0), m_api(0), m_refcount(0), m_dependencyCheck(false), m_cycleCheck(false)
{
}
explicit SingletonModule(const APIConstructor& constructor)
: APIConstructor(constructor), m_dependencies(0), m_api(0), m_refcount(0), m_dependencyCheck(false), m_cycleCheck(false)
{
}
~SingletonModule()
{
ASSERT_MESSAGE(m_refcount == 0, "module still referenced at shutdown");
}
void selfRegister()
{
globalModuleServer().registerModule(Type::name(), Type::VERSION, APIConstructor::getName(), *this);
}
Dependencies& getDependencies()
{
return *m_dependencies;
}
void* getTable()
{
if(m_api != 0)
{
return m_api->getTable();
}
return 0;
}
void capture()
{
if(++m_refcount == 1)
{
globalOutputStream() << "Module Initialising: '" << Type::name() << "' '" << APIConstructor::getName() << "'\n";
m_dependencies = new Dependencies();
m_dependencyCheck = !globalModuleServer().getError();
if(m_dependencyCheck)
{
m_api = APIConstructor::constructAPI(*m_dependencies);
globalOutputStream() << "Module Ready: '" << Type::name() << "' '" << APIConstructor::getName() << "'\n";
}
else
{
globalOutputStream() << "Module Dependencies Failed: '" << Type::name() << "' '" << APIConstructor::getName() << "'\n";
}
m_cycleCheck = true;
}
ASSERT_MESSAGE(m_cycleCheck, "cyclic dependency detected");
}
void release()
{
if(--m_refcount == 0)
{
if(m_dependencyCheck)
{
APIConstructor::destroyAPI(m_api);
}
delete m_dependencies;
}
}
};
#endif
| [
"[email protected]"
] | [
[
[
1,
130
]
]
] |
f41981748c47e168b03d7a4f5b416416c008a7d7 | 26e26a0b917be4199bfac9256dc0b29de98c2995 | /modules/mobility/LineSegmentsMobilityBase.cc | 911307cfb61c69294b807713c7baad80394dd805 | [] | no_license | jorgeperezhidalgo/MiXiM | 4dc282152921fb8596620be44f4cac18a96d9c56 | f812a62d347aa4d4eb09b7bdacfbf77f2187d48b | refs/heads/master | 2020-12-24T15:13:58.425203 | 2011-08-23T16:59:23 | 2011-08-24T11:07:57 | 1,398,026 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,874 | cc | //
// Copyright (C) 2005 Andras Varga
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "LineSegmentsMobilityBase.h"
#include <FWMath.h>
void LineSegmentsMobilityBase::initialize(int stage) {
BaseMobility::initialize(stage);
if(stage == 1) {
if(!world->use2D()) {
opp_warning("This mobility module does not yet support 3-dimensional movement."\
"Movements will probably be incorrect.");
}
}
}
void LineSegmentsMobilityBase::beginNextMove(cMessage *msg)
{
EV << "beginNextMove, startPos: " << move.getStartPos().info() << " stepTarget: " << stepTarget.info() << " targetPos: "
<< targetPos.info() << endl << "simTime: " << simTime() << " targetTime: " << targetTime << endl;;
// go to exact position where previous statement was supposed to finish
move.setStart(targetPos, simTime());
stepTarget = targetPos;
simtime_t now = targetTime;
// choose new targetTime and targetPos
setTargetPosition();
EV << "startPos: " << move.getStartPos().info() << " targetPos: " << targetPos.info() << endl;
if (targetTime<now)
error("LineSegmentsMobilityBase: targetTime<now was set in %s's beginNextMove()", getClassName());
if( move.getSpeed() <= 0 ){
// end of movement
stepSize.setX(0);
stepSize.setY(0);
EV << "speed < 0; stop moving!\n";
delete msg;
}
else if (targetPos==move.getStartPos()){
// no movement, just wait
EV << "warning, we are not moving!\n";
stepSize.setX(0);
stepSize.setY(0);
scheduleAt(std::max(targetTime,simTime()), msg);
}
else{
// keep moving
double numIntervals = (targetTime-now) / updateInterval;
// int numSteps = floor(numIntervals); -- currently unused,
// although we could use step counting instead of comparing
// simTime() to targetTime each step.
// Note: step = speed*updateInterval = distance/time*updateInterval =
// = (targetPos-pos) / (targetTime-now) * updateInterval =
// = (targetPos-pos) / numIntervals
stepSize = (targetPos - move.getStartPos());
move.setDirectionByTarget( targetPos );
stepSize = stepSize / numIntervals;
stepTarget += stepSize;
move.setSpeed(move.getStartPos().distance( targetPos ) / (targetTime - now ));
EV << "numIntervals: " << numIntervals << " now: " << now << " simTime " << simTime() << " stepTarget: "
<< stepTarget.info() << " speed: " << move.getSpeed() << endl;
scheduleAt(simTime() + updateInterval, msg);
}
}
void LineSegmentsMobilityBase::handleSelfMsg(cMessage *msg)
{
if( move.getSpeed() <= 0 ){
delete msg;
return;
}
else if (simTime()+updateInterval >= targetTime){
beginNextMove(msg);
}
else{
EV << "make next step\n";
scheduleAt(simTime() + updateInterval, msg);
// update position
move.setStart(stepTarget, simTime());
stepTarget += stepSize;
}
// do something if we reach the wall
fixIfHostGetsOutside();
updatePosition();
}
| [
"[email protected]"
] | [
[
[
1,
118
]
]
] |
f940c8e84377c8cd6f0ff287560ec1188ef92e92 | 6426b0ba09cf324c4caad8b86b74f33ef489710e | /src/goGuiManager.h | 63d2282104f96f72750b6abebc6a42ce69b1980c | [] | no_license | gameoverhack/iMediate | e619a1148ecc3f76f011e2c1a7fa9cdb32c8a290 | 9c43edf26954cbc15fb0145632fa4dbf2634fc29 | refs/heads/master | 2020-04-05T23:05:37.392441 | 2010-10-23T20:10:03 | 2010-10-23T20:10:03 | 1,373,120 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,441 | h | #ifndef __GOGUIMANAGER_H
#define __GOGUIMANAGER_H
#include "ofMain.h"
#include "Singleton.h"
#include "Controller.h"
#include "Model.h"
#include "Logger.h"
#define GUIMANAGER goGuiManagerSingleton::Instance()
#define FOLDERS GUIMANAGER->folderBox
#define LASTFOLDERS GUIMANAGER->lastFolderBox
#define XFADE GUIMANAGER->xfade
#define XFADETRUE GUIMANAGER->trueXFader
#define XFADEMUTE GUIMANAGER->xfademute
#define XFUNCMUTE GUIMANAGER->xfuncmute
#define REVERSECHANNELS GUIMANAGER->reversechannels
#define CHANNELADIRECT GUIMANAGER->channeladirect
#define CHANNELBDIRECT GUIMANAGER->channelbdirect
#define XMODES GUIMANAGER->xmodes
#define XFUNCS GUIMANAGER->xfuncs
#define SOLENOIDCHANNEL GUIMANAGER->solenoidChannel
#define PLAYSOLENOIDS GUIMANAGER->playSolenoids
#define CONTROLCHANNEL GUIMANAGER->controlChannel
#define LISTENCHBEG GUIMANAGER->listenChannelBegin
#define LISTENCHEND GUIMANAGER->listenChannelEnd
#define REMAPCHAN GUIMANAGER->remapChannel
#define LISTENNTBEG GUIMANAGER->listenNoteBegin
#define LISTENNTEND GUIMANAGER->listenNoteEnd
#define REMAPNTBEG GUIMANAGER->remapNoteBegin
#define REMAPNTEND GUIMANAGER->remapNoteEnd
#define REMAPMODE GUIMANAGER->remapMode
#define CHANNELMODE GUIMANAGER->channelMode
#define PARTICLEMODE GUIMANAGER->particleMode
#define LEARNRANGE GUIMANAGER->learnRange
#define MUTE GUIMANAGER->mute
#define REMAPOSC GUIMANAGER->remaposc
#define OSCCHANNEL GUIMANAGER->oscchannel
#define PROTECTCONTROL GUIMANAGER->protect
#define SELECTIONGRP GUIMANAGER->selectiongroup
class goGuiManager
{
public:
goGuiManager();
virtual ~goGuiManager();
goGuiManager(const goGuiManager& other);
goGuiManager& operator=(const goGuiManager& other);
void setup();
void update();
// gui variables
int folderBox[MAX_VIDEO_CHANNELS];
int lastFolderBox[MAX_VIDEO_CHANNELS];
float xfade;
bool xfademute, xfuncmute, trueXFader, reversechannels, mute[2];
bool channeladirect, channelbdirect;
int xmodes[2], xfuncs[2];
int solenoidChannel;
bool playSolenoids, protect;
int controlChannel;
int selectiongroup[2];
int listenChannelBegin[6];
int listenChannelEnd[6];
int remapChannel[6];
int listenNoteBegin[6];
int listenNoteEnd[6];
int remapNoteBegin[6];
int remapNoteEnd[6];
int remapMode[6];
int channelMode[6];
int particleMode[6];
bool learnRange[6];
bool remaposc[5];
int oscchannel[5];
protected:
private:
void checkVideoFolders();
void groupLoadDone(int & id);
};
typedef Singleton<goGuiManager> goGuiManagerSingleton; // Global declaration
#endif // __GOGUIMANAGER_H
| [
"gameover@4bdaed08-0356-49c7-8fa1-902f09de843b"
] | [
[
[
1,
98
]
]
] |
cb6971d872dcfbff6040e24996f2ace6b6bb4c95 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/NewtonSDK/customJoints/CustomPoweredBallAndSocket.cpp | 44b5538819bf2232b115db4fe038332dc26f51c9 | [] | no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,205 | cpp | //********************************************************************
// Newton Game dynamics
// copyright 2000-2004
// By Julio Jerez
// VC: 6.0
// simple demo list vector class with iterators
//********************************************************************
// CustomPoweredBallAndSocket.cpp: implementation of the CustomPoweredBallAndSocket class.
//
//////////////////////////////////////////////////////////////////////
#include <stdafx.h>
#include "CustomPoweredBallAndSocket.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CustomPoweredBallAndSocket::CustomPoweredBallAndSocket(const dVector& pivot, NewtonBody* child, NewtonBody* parent)
:NewtonCustomJoint(5, child, parent)
{
dMatrix matrix;
// use as primary pin vector the line that goes from the pivot to the origin of body zero
// this eliminates some offset unwanted torques
NewtonBodyGetMatrix (m_body0, &matrix[0][0]);
dVector pin (matrix.m_posit - pivot);
if ((pin % pin) < 1.0e-3f) {
// the the pivot is already at the origin then any pin will do
pin = matrix.m_front;
}
// calculate the two local matrix of the pivot point
CalculateLocalMatrix (pivot, pin, m_localMatrix0, m_localMatrix1);
// set the target matrix to point to the child matrix
m_targetMatrix = m_localMatrix0;
}
CustomPoweredBallAndSocket::~CustomPoweredBallAndSocket()
{
}
void CustomPoweredBallAndSocket::SetChildOrientation (const dMatrix& matrix)
{
}
void CustomPoweredBallAndSocket::SubmitConstrainst ()
{
// this is still work in progress.
// if anybody is integeted on this joint let us know
/*
dMatrix matrix0;
dMatrix matrix1;
// calculate the position of the pivot point and the Jacobian's direction vectors, in global space.
CalculateGlobalMatrix (m_localMatrix0, m_localMatrix1, matrix0, matrix1);
// Restrict the movement on the pivot point along all tree orthonormal direction
NewtonUserJointAddLinearRow (m_joint, &matrix0.m_posit[0], &matrix1.m_posit[0], &matrix0.m_front[0]);
NewtonUserJointAddLinearRow (m_joint, &matrix0.m_posit[0], &matrix1.m_posit[0], &matrix0.m_up[0]);
NewtonUserJointAddLinearRow (m_joint, &matrix0.m_posit[0], &matrix1.m_posit[0], &matrix0.m_right[0]);
// now we need to determine the direction of the DOG to align m_localMatrix0 with m_targetMatrix
// step 1
// first will will take m_targetMatrix to global space
dMatrix dommy;
dMatrix localMatrix;
CalculateGlobalMatrix (m_targetMatrix, m_targetMatrix, localMatrix, dommy);
// now we will calculate the rotation angle to align between the front axis
// of localMatrix and matrix0;
// this is done by taking the cross product between the tow axis
// if the magnitude of the dot product is sufficiently large, these means that
// that direction of the cross product define a plane about and and angular rotation
// of matrix0.m_front will align up with localMatrix.m_front.
// angle is the arch sign of the of the magnitude of the cross product.
dFloat mag2;
dFloat angle;
// dFloat accel;
// dFloat time;
// time = NewtonGetTimeStep (m_world);
dVector axis (localMatrix.m_front * matrix0.m_front);
mag2 = axis % axis;
if (mag2 < 1.0e-4f) {
// we have a non zero error, get axis
axis = axis.Scale (1.0f / sqrtf (axis % axis));
angle = asinf (mag2);
// the asinf will only report and angle between 0 and 90 degree
// we need to check if the angle is larger than 90, by checking
// if the projection of localMatrix.m_front over matrix0.m_front
// is negative
if ((localMatrix.m_front % matrix0.m_front) < 0.0f) {
angle = 3.1416f - angle;
}
// we can not really do a extremes rotation so will will clam teh anglu to not be more
// than 30 degree in each step
angle = min (angle, 30.0f * (3.1416f / 180.0f));
// now we are ready to add an angular row
NewtonUserJointAddAngularRow (m_joint, -angle, &axis[0]);
// we need to add another rotation
// this work is incomplete
}
// this work is incomplete
*/
} | [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
] | [
[
[
1,
121
]
]
] |
00c63ca1883c32d8c639c4221460ab2a78e2bc81 | 6581dacb25182f7f5d7afb39975dc622914defc7 | /EDStock/SListView.h | d52fe0adc87f47b52b2f84eaf99972966eca3e72 | [] | no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,516 | h |
#pragma once
#include "GridCtrl.h"
class CSListView : public CView
{
DECLARE_DYNCREATE(CSListView)
protected:
CSListView();
virtual ~CSListView();
protected:
CGridCtrl m_Grid;
int m_nColSort;
BOOL m_bSortAscend;
BOOL m_bFirstUpdate;
public:
void SetFont(LPLOGFONT pLogFont);
public:
void GetSelectedStocks(CSPStringArray & astr);
void StoreColumnOrderArray();
virtual void ResetColumns();
BOOL SetAverageItem(CGridCtrl &grid, CStockContainer &container, BOOL bRedraw);
void OnDblclkItem(int nStockIndex);
void StockInfoChanged(LONG id, CStockInfo & info);
void SendRequestQuote(BOOL bForced);
public:
virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo);
virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual void OnDraw(CDC* pDC);
protected:
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnDestroy();
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnSlistExportlist();
afx_msg LRESULT OnGetViewTitle(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnGetViewCmdid(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnColorChange(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnStkReceiverData(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
] | [
[
[
1,
57
]
]
] |
81fbbfbab2d7e78039563bcfec3bcd0189eb142f | d1ce8db98d580f0f17f868ed408edf6d92f9208f | /QT/QtOgre/source/FPSDialog.cpp | f8296e5c54b019ea6911d25786216753090623c2 | [] | no_license | babochingu/andrew-phd | eed82e7bbd3e2b5b5403c1493e3d36b112b1b007 | ba94c3961d9dfef041c974e7ed2d9da4eb7d4dd3 | refs/heads/master | 2016-09-06T07:18:39.627522 | 2010-10-04T23:54:06 | 2010-10-04T23:54:06 | 33,762,959 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,555 | cpp | #include "FPSDialog.h"
#include "Application.h"
#include <QMouseEvent>
namespace QtOgre
{
FPSDialog::FPSDialog(QWidget* parent, Qt::WindowFlags f)
:QDialog(parent, f)
,mLastFrameCountValue(0)
{
setupUi(this);
connect(&mTimer, SIGNAL(timeout(void)), this, SLOT(updateLCDDisplay(void)));
mTimer.start(1000);
mTime.restart();
}
void FPSDialog::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton)
{
dragPosition = event->globalPos() - frameGeometry().topLeft();
event->accept();
}
}
void FPSDialog::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton)
{
QPoint desiredPos = event->globalPos() - dragPosition;
QRect desiredRect(desiredPos, size());
if(parentWidget()->geometry().contains(desiredRect, true))
{
move(desiredPos);
}
event->accept();
}
}
void FPSDialog::updateLCDDisplay(void)
{
unsigned int currentFrameCountValue = qApp->frameCount();
unsigned int framesRendered = currentFrameCountValue - mLastFrameCountValue;
//In theory we know the time elapsed, because a timer is calling this function at
//fixed intervals. We don't know how accurate this is though, so it seems sensible
//to get the actual time elapsed.
float timeElapsedInSeconds = mTime.elapsed() / 1000.0f;
mLcdNumber->display(static_cast<int>(framesRendered / timeElapsedInSeconds));
//Reset ready for next time.
mLastFrameCountValue = currentFrameCountValue;
mTime.restart();
}
} | [
"evertech.andrew@2dccfce6-0550-11df-956f-01f849d29158"
] | [
[
[
1,
60
]
]
] |
303167524d10fa226cf6c03066fe8db91f4fa644 | fcf03ead74f6dc103ec3b07ffe3bce81c820660d | /Graphics/GraphicsShell.h | 1f8759570fa1dcd784fe94d9310f4206cb8b65de | [] | 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 | 2,493 | h | // GraphicsShell.h
//
// Copyright (c) 2000 Symbian Ltd. All rights reserved.
#ifndef __GraphicsShell_H
#define __GraphicsShell_H
#include <coecntrl.h>
#include <coeccntx.h>
#include <eikappui.h>
#include <eikapp.h>
#include <eikdoc.h>
#include "GraphicsControl.h"
// UID of app
const TUid KUidExampleShellApp =
{
0xE800004E
};
//
// TExampleShellModel
//
class TExampleShellModel
{
public:
TExampleShellModel();
TBool Differs(const TExampleShellModel* aCompare) const;
public:
TFileName iLibrary; // active control
};
//
// class CExampleShellContainer
//
class CExampleShellContainer : public CCoeControl,
public MCoeControlBrushContext,
public MGraphicsExampleObserver
{
public:
void ConstructL(const TRect& aRect, TExampleShellModel* aModel);
~CExampleShellContainer();
// changing view
void ResetExampleL(CGraphicExampleControl* aExample);
private:
// from CCoeControl
void Draw(const TRect& /*aRect*/) const;
TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType);
TInt CountComponentControls() const;
CCoeControl* ComponentControl(TInt aIndex) const;
private:
// from MGraphicsExampleObserver
void NotifyGraphicExampleFinished();
public:
// also from MGraphicsExampleObserver
void NotifyStatus(const TDesC& aMessage);
private:
// new function
void CreateLabelL();
private:
// data
CGraphicExampleControl* iExampleControl; // example control
CEikLabel* iLabel; // label for status messages
// irrelevant
TExampleShellModel* iModel;
};
//
// CExampleShellDocument
//
class CExampleShellDocument : public CEikDocument
{
public:
CExampleShellDocument(CEikApplication& aApp) :
CEikDocument(aApp)
{
}
TExampleShellModel* Model()
{
return (&iModel);
}
private:
// from CEikDocument
CEikAppUi* CreateAppUiL();
private:
TExampleShellModel iModel;
};
//
// CExampleShellAppUi
//
class CExampleShellAppUi : public CEikAppUi
{
public:
void ConstructL();
~CExampleShellAppUi();
private:
// from CEikAppUi
void HandleCommandL(TInt aCommand);
private:
// internal use
// void PrepareToolbarButtons();
private:
CExampleShellContainer* iContainer;
TExampleShellModel* iModel;
};
//
// CExampleShellApplication
//
class CExampleShellApplication : public CEikApplication
{
private:
// from CApaApplication
CApaDocument* CreateDocumentL();
TUid AppDllUid() const;
};
#endif
| [
"liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca"
] | [
[
[
1,
127
]
]
] |
7e2653b9b6085e675e7585402705ef3c9f31d061 | 035288d85c21cb6494d5f03c1fafb58a31810988 | /CS6620 Symmetry/pmvs_base/image/photoSetS.h | e4d764fb7c6eb9f0ff103d2fe6f6ea503ece91fa | [] | no_license | AySz88/cs6620-symmetry | b0a658186a8876da6de51c5e28a29059fd596f05 | f189c56b45973cc7d8cf3e525b00787c86cab094 | refs/heads/master | 2016-09-10T02:12:57.637244 | 2009-12-17T23:09:44 | 2009-12-17T23:09:44 | 40,057,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,018 | h | #ifndef IMAGE_PHOTOSETS_H
#define IMAGE_PHOTOSETS_H
#include <map>
#include "photo.h"
namespace Image {
class CphotoSetS {
public:
CphotoSetS(void);
virtual ~CphotoSetS();
void init(const std::vector<int>& images, const std::string prefix,
const int maxLevel, const int size, const int alloc);
// grabTex given 2D sampling information
void grabTex(const int index, const int level, const Vec2f& icoord,
const Vec2f& xaxis, const Vec2f& yaxis,
std::vector<Vec3f>& tex, const int normalizef = 1) const;
// grabTex given 3D sampling information
void grabTex(const int index, const int level, const Vec4f& coord,
const Vec4f& pxaxis, const Vec4f& pyaxis, const Vec4f& pzaxis,
std::vector<Vec3f>& tex, float& weight,
const int normalizef = 1) const;
void write(const std::string outdir);
void free(void);
void free(const int level);
void setEdge(const float threshold);
inline Vec3f project(const int index, const Vec4f& coord, const int level) const;
inline Vec3f mult(const int index, const Vec4f& coord, const int level) const;
inline int getWidth(const int index, const int level) const;
inline int getHeight(const int index, const int level) const;
inline Vec3f getColor(const Vec4f& coord, const int index,
const int level) const;
inline Vec3f getColor(const int index, const float fx, const float fy,
const int level) const;
inline Vec3f getColor(const int index, const int ix, const int iy,
const int level) const;
inline int getMask(const Vec4f& coord, const int level) const;
inline int getMask(const Vec4f& coord, const int index, const int level) const;
inline int getMask(const int index, const float fx, const float fy,
const int level) const;
inline int getMask(const int index, const int ix, const int iy,
const int level) const;
inline int getEdge(const Vec4f& coord, const int index, const int level) const;
inline int getEdge(const int index, const float fx, const float fy,
const int level) const;
inline int getEdge(const int index, const int ix, const int iy,
const int level) const;
static float incc(const std::vector<std::vector<Vec3f> >& texs,
const std::vector<float>& weights);
int checkAngles(const Vec4f& coord, const std::vector<int>& indexes,
const float minAngle, const float maxAngle,
const int tau) const;
void getMinMaxAngles(const Vec4f& coord, const std::vector<int>& indexes,
float& minAngle, float& maxAngle) const;
float computeDepth(const int index, const Vec4f& coord) const;
// Take care of indexes
std::vector<int> m_images;
std::vector<Cphoto> m_photos;
int image2index(const int image) const;
std::map<int, int> m_dict;
// Number of cameras.
int m_num;
// Root directory
std::string m_prefix;
// maximum level
int m_maxLevel;
// Window size used to refine location
int m_size;
// getPAxes
void getPAxes(const int index, const Vec4f& coord, const Vec4f& normal,
Vec4f& pxaxis, Vec4f& pyaxis) const;
// pairwise distance based on optical center and viewing direction
void setDistances(void);
std::vector<std::vector<float> > m_distances;
protected:
};
Vec3f CphotoSetS::project(const int index, const Vec4f& coord,
const int level) const{
return m_photos[index].project(coord, level);
};
Vec3f CphotoSetS::mult(const int index, const Vec4f& coord,
const int level) const{
return m_photos[index].mult(coord, level);
};
int CphotoSetS::getWidth(const int index, const int level) const {
return m_photos[index].getWidth(level);
};
int CphotoSetS::getHeight(const int index, const int level) const {
return m_photos[index].getHeight(level);
};
Vec3f CphotoSetS::getColor(const Vec4f& coord, const int index,
const int level) const {
return m_photos[index].getColor(coord, level);
};
Vec3f CphotoSetS::getColor(const int index, const float fx, const float fy,
const int level) const {
return m_photos[index].Image::Cimage::getColor(fx, fy, level);
};
Vec3f CphotoSetS::getColor(const int index, const int ix, const int iy,
const int level) const {
return m_photos[index].Image::Cimage::getColor(ix, iy, level);
};
int CphotoSetS::getMask(const Vec4f& coord, const int level) const {
for (int index = 0; index < m_num; ++index)
if (getMask(coord, index, level) == 0)
return 0;
return 1;
};
int CphotoSetS::getMask(const Vec4f& coord, const int index,
const int level) const {
return m_photos[index].getMask(coord, level);
};
int CphotoSetS::getMask(const int index, const float fx, const float fy,
const int level) const {
return m_photos[index].Image::Cimage::getMask(fx, fy, level);
};
int CphotoSetS::getMask(const int index, const int ix, const int iy,
const int level) const {
return m_photos[index].Image::Cimage::getMask(ix, iy, level);
};
int CphotoSetS::getEdge(const Vec4f& coord, const int index,
const int level) const {
return m_photos[index].getEdge(coord, level);
};
int CphotoSetS::getEdge(const int index, const float fx, const float fy,
const int level) const {
return m_photos[index].Image::Cimage::getEdge(fx, fy, level);
};
int CphotoSetS::getEdge(const int index, const int ix, const int iy,
const int level) const {
return m_photos[index].Image::Cimage::getEdge(ix, iy, level);
};
};
#endif // IMAGE_PHOTOSETS_H
| [
"[email protected]"
] | [
[
[
1,
171
]
]
] |
b66c7a2c1997ec9ee49f9d9a25838d8c99aa29c4 | c8f467a4cee0b4067b93936574c884c9de0b36cf | /source/Irrlicht/CColladaFileLoader.h | e6f2f02674fa750be2713f54a98032af6a17ee88 | [
"LicenseRef-scancode-unknown-license-reference",
"Zlib",
"LicenseRef-scancode-other-permissive"
] | permissive | flaithbheartaigh/mirrlicht | 1ff418d29017e55e5f4a27a70dcfd5a88cb244b5 | ccc16e8f5465fb72e81ae986e56ef2e4c3e7654b | refs/heads/master | 2021-01-10T11:29:49.569701 | 2009-01-12T21:08:31 | 2009-01-12T21:08:31 | 49,994,212 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,721 | h | // Copyright (C) 2002-2007 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_COLLADA_MESH_FILE_LOADER_H_INCLUDED__
#define __C_COLLADA_MESH_FILE_LOADER_H_INCLUDED__
#include "IMeshLoader.h"
#include "IFileSystem.h"
#include "IVideoDriver.h"
#include "irrString.h"
#include "SMesh.h"
#include "SMeshBuffer.h"
#include "ISceneManager.h"
namespace irr
{
namespace scene
{
#ifdef _DEBUG
//#define COLLADA_READER_DEBUG
#endif
class IColladaPrefab;
enum ECOLLADA_PARAM_NAME
{
ECPN_COLOR = 0,
ECPN_AMBIENT,
ECPN_DIFFUSE,
ECPN_SPECULAR,
ECPN_SHININESS,
ECPN_YFOV,
ECPN_ZNEAR,
ECPN_ZFAR,
ECPN_COUNT
};
enum ECOLLADA_PARAM_TYPE
{
ECPT_FLOAT = 0,
ECPT_FLOAT2,
ECPT_FLOAT3,
ECPT_FLOAT4,
ECPT_COUNT
};
//! Collada Parameter
struct SColladaParam
{
SColladaParam()
: Name(ECPN_COUNT), Type(ECPT_COUNT)
{
for (int i=0; i<4; ++i) Floats[i] = 0;
}
ECOLLADA_PARAM_NAME Name;
ECOLLADA_PARAM_TYPE Type;
f32 Floats[4];
};
enum ECOLLADA_INPUT_SEMANTIC
{
ECIS_POSITION = 0,
ECIS_VERTEX,
ECIS_NORMAL,
ECIS_TEXCOORD,
ECIS_UV,
ECIS_TANGENT,
ECIS_COUNT
};
//! Collada Input
struct SColladaInput
{
SColladaInput()
: Semantic(ECIS_COUNT)
{
}
ECOLLADA_INPUT_SEMANTIC Semantic;
core::stringc Source;
};
//! Collada material
struct SColladaMaterial
{
video::SMaterial Mat;
core::stringc Id;
};
struct SNumberArray // for stroring float and int arrays
{
core::stringc Name;
core::array<f32> Data;
};
struct SAccessor
{
SAccessor()
: Count(0), Offset(0), Stride(1) {}
// I don't store the source of the accessor here because I assume
// it to use the array of the source this accessor is located in.
int Count;
int Offset;
int Stride;
core::array<SColladaParam> Parameters; // parameters defining the accessor
};
struct SSource
{
core::stringc Id;
SNumberArray Array;
core::array<SAccessor> Accessors;
};
//! Meshloader capable of loading COLLADA meshes and scene descriptions into Irrlicht.
class CColladaFileLoader : public IMeshLoader
{
public:
//! Constructor
CColladaFileLoader(video::IVideoDriver* driver,
scene::ISceneManager* smgr, io::IFileSystem* fs);
//! destructor
virtual ~CColladaFileLoader();
//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".cob")
virtual bool isALoadableFileExtension(const c8* fileName);
//! creates/loads an animated mesh from the file.
//! \return Pointer to the created mesh. Returns 0 if loading failed.
//! If you no longer need the mesh, you should call IAnimatedMesh::drop().
//! See IUnknown::drop() for more information.
virtual IAnimatedMesh* createMesh(irr::io::IReadFile* file);
private:
//! skips an (unknown) section in the collada document
void skipSection(io::IXMLReaderUTF8* reader, bool reportSkipping);
//! reads the <COLLADA> section and its content
void readColladaSection(io::IXMLReaderUTF8* reader);
//! reads a <library> section and its content
void readLibrarySection(io::IXMLReaderUTF8* reader);
//! reads a <scene> section and its content
void readSceneSection(io::IXMLReaderUTF8* reader);
//! reads a <asset> section and its content
void readAssetSection(io::IXMLReaderUTF8* reader);
//! reads a <node> section and its content
void readNodeSection(io::IXMLReaderUTF8* reader, scene::ISceneNode* parent);
//! reads a <lookat> element and its content and creates a matrix from it
core::matrix4 readLookAtNode(io::IXMLReaderUTF8* reader);
//! reads a <matrix> element and its content and creates a matrix from it
core::matrix4 readMatrixNode(io::IXMLReaderUTF8* reader);
//! reads a <perspective> element and its content and creates a matrix from it
core::matrix4 readPerspectiveNode(io::IXMLReaderUTF8* reader);
//! reads a <rotate> element and its content and creates a matrix from it
core::matrix4 readRotateNode(io::IXMLReaderUTF8* reader);
//! reads a <skew> element and its content and creates a matrix from it
core::matrix4 readSkewNode(io::IXMLReaderUTF8* reader);
//! reads a <scale> element and its content and creates a matrix from it
core::matrix4 readScaleNode(io::IXMLReaderUTF8* reader);
//! reads a <translate> element and its content and creates a matrix from it
core::matrix4 readTranslateNode(io::IXMLReaderUTF8* reader);
//! reads a <instance> node and creates a scene node from it
void readInstanceNode(io::IXMLReaderUTF8* reader, scene::ISceneNode* parent,
scene::ISceneNode** outNode);
//! reads a <light> element and stores it as prefab
void readLightPrefab(io::IXMLReaderUTF8* reader);
//! reads a <camera> element and stores it as prefab
void readCameraPrefab(io::IXMLReaderUTF8* reader);
//! reads a <material> element and stores it in the material section
void readMaterial(io::IXMLReaderUTF8* reader);
//! reads a <geometry> element and stores it as mesh if possible
void readGeometry(io::IXMLReaderUTF8* reader);
//! parses a float from a char pointer and moves the pointer to
//! the end of the parsed float
inline f32 readFloat(const c8** p);
//! parses an int from a char pointer and moves the pointer to
//! the end of the parsed float
inline s32 readInt(const c8** p);
//! places pointer to next begin of a token
void findNextNoneWhiteSpace(const c8** p);
//! reads floats from inside of xml element until end of xml element
void readFloatsInsideElement(io::IXMLReaderUTF8* reader, f32* floats, s32 count);
//! clears all loaded data
void clearData();
//! parses all collada parameters inside an element and stores them in Parameters
void readColladaParameters(io::IXMLReaderUTF8* reader, const core::stringc& parentName);
//! returns a collada parameter or none if not found
SColladaParam* getColladaParameter(ECOLLADA_PARAM_NAME name);
//! parses all collada inuts inside an element and stores them in Inputs. Reads
//! until first tag which is not an input tag or the end of the parent is reached
void readColladaInputs(io::IXMLReaderUTF8* reader, const core::stringc& parentName);
//! reads a collada input tag and adds it to the input parameter
void readColladaInput(io::IXMLReaderUTF8* reader);
//! returns a collada input or none if not found
SColladaInput* getColladaInput(ECOLLADA_INPUT_SEMANTIC input);
//! changes the XML URI into an internal id
void uriToId(core::stringc& str);
//! reads a polygons section and creates a mesh from it
void readPolygonSection(io::IXMLReaderUTF8* reader,
core::stringc vertexPositionSource, core::array<SSource>& sources,
scene::SMesh* mesh);
video::IVideoDriver* Driver;
scene::ISceneManager* SceneManager;
io::IFileSystem* FileSystem;
scene::IAnimatedMesh* DummyMesh;
core::stringc CurrentlyLoadingMesh;
scene::IAnimatedMesh* FirstLoadedMesh;
core::stringc FirstLoadedMeshName;
s32 LoadedMeshCount;
core::array<IColladaPrefab*> Prefabs;
core::array<SColladaParam> Parameters;
core::array<SColladaMaterial> Materials;
core::array<SColladaInput> Inputs;
bool CreateInstances;
// currently supported COLLADA tag names
core::stringc colladaSectionName;
core::stringc librarySectionName;
core::stringc assetSectionName;
core::stringc sceneSectionName;
core::stringc lightPrefabName;
core::stringc cameraPrefabName;
core::stringc materialSectionName;
core::stringc geometrySectionName;
core::stringc meshSectionName;
core::stringc sourceSectionName;
core::stringc arraySectionName;
core::stringc accessorSectionName;
core::stringc verticesSectionName;
core::stringc inputTagName;
core::stringc polygonsSectionName;
core::stringc polygonName;
core::stringc nodeSectionName;
core::stringc lookatNodeName;
core::stringc matrixNodeName;
core::stringc perspectiveNodeName;
core::stringc rotateNodeName;
core::stringc scaleNodeName;
core::stringc translateNodeName;
core::stringc skewNodeName;
core::stringc instanceNodeName;
core::stringc paramTagName;
};
//! following class is for holding and createing instances of library objects,
//! named prefabs in this loader.
class IColladaPrefab : public virtual IUnknown
{
public:
//! creates an instance of this prefab
virtual scene::ISceneNode* addInstance(scene::ISceneNode* parent,
scene::ISceneManager* mgr) = 0;
//! returns id of this prefab
virtual const c8* getId() = 0;
};
} // end namespace scene
} // end namespace irr
#endif
| [
"limingchina@c8d24273-d621-0410-9a95-1b5ff033c8bf"
] | [
[
[
1,
317
]
]
] |
27e502a65a80c7a5c4595df47ba4a8d2c3bac4bd | 7b379862f58f587d9327db829ae4c6493b745bb1 | /JuceLibraryCode/modules/juce_gui_basics/components/juce_Desktop.h | 48f990d70bc65a1b0491e88912d96bf9bcf306b4 | [] | no_license | owenvallis/Nomestate | 75e844e8ab68933d481640c12019f0d734c62065 | 7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd | refs/heads/master | 2021-01-19T07:35:14.301832 | 2011-12-28T07:42:50 | 2011-12-28T07:42:50 | 2,950,072 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,902 | h | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
#ifndef __JUCE_DESKTOP_JUCEHEADER__
#define __JUCE_DESKTOP_JUCEHEADER__
#include "juce_Component.h"
#include "../layout/juce_ComponentAnimator.h"
class MouseInputSource;
class MouseInputSourceInternal;
class MouseListener;
//==============================================================================
/**
Classes can implement this interface and register themselves with the Desktop class
to receive callbacks when the currently focused component changes.
@see Desktop::addFocusChangeListener, Desktop::removeFocusChangeListener
*/
class JUCE_API FocusChangeListener
{
public:
/** Destructor. */
virtual ~FocusChangeListener() {}
/** Callback to indicate that the currently focused component has changed. */
virtual void globalFocusChanged (Component* focusedComponent) = 0;
};
//==============================================================================
/**
Describes and controls aspects of the computer's desktop.
*/
class JUCE_API Desktop : private DeletedAtShutdown,
private Timer,
private AsyncUpdater
{
public:
//==============================================================================
/** There's only one dektop object, and this method will return it.
*/
static Desktop& JUCE_CALLTYPE getInstance();
//==============================================================================
/** Returns a list of the positions of all the monitors available.
The first rectangle in the list will be the main monitor area.
If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
*/
const RectangleList getAllMonitorDisplayAreas (bool clippedToWorkArea = true) const;
/** Returns the position and size of the main monitor.
If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
*/
const Rectangle<int> getMainMonitorArea (bool clippedToWorkArea = true) const noexcept;
/** Returns the position and size of the monitor which contains this co-ordinate.
If none of the monitors contains the point, this will just return the
main monitor.
If clippedToWorkArea is true, it will exclude any areas like the taskbar on Windows,
or the menu bar on Mac. If clippedToWorkArea is false, the entire monitor area is returned.
*/
const Rectangle<int> getMonitorAreaContaining (const Point<int>& position, bool clippedToWorkArea = true) const;
//==============================================================================
/** Returns the mouse position.
The co-ordinates are relative to the top-left of the main monitor.
Note that this is just a shortcut for calling getMainMouseSource().getScreenPosition(), and
you should only resort to grabbing the global mouse position if there's really no
way to get the coordinates via a mouse event callback instead.
*/
static const Point<int> getMousePosition();
/** Makes the mouse pointer jump to a given location.
The co-ordinates are relative to the top-left of the main monitor.
*/
static void setMousePosition (const Point<int>& newPosition);
/** Returns the last position at which a mouse button was pressed.
Note that this is just a shortcut for calling getMainMouseSource().getLastMouseDownPosition(),
and in a multi-touch environment, it doesn't make much sense. ALWAYS prefer to
get this information via other means, such as MouseEvent::getMouseDownScreenPosition()
if possible, and only ever call this as a last resort.
*/
static const Point<int> getLastMouseDownPosition();
/** Returns the number of times the mouse button has been clicked since the
app started.
Each mouse-down event increments this number by 1.
*/
static int getMouseButtonClickCounter();
//==============================================================================
/** This lets you prevent the screensaver from becoming active.
Handy if you're running some sort of presentation app where having a screensaver
appear would be annoying.
Pass false to disable the screensaver, and true to re-enable it. (Note that this
won't enable a screensaver unless the user has actually set one up).
The disablement will only happen while the Juce application is the foreground
process - if another task is running in front of it, then the screensaver will
be unaffected.
@see isScreenSaverEnabled
*/
static void setScreenSaverEnabled (bool isEnabled);
/** Returns true if the screensaver has not been turned off.
This will return the last value passed into setScreenSaverEnabled(). Note that
it won't tell you whether the user is actually using a screen saver, just
whether this app is deliberately preventing one from running.
@see setScreenSaverEnabled
*/
static bool isScreenSaverEnabled();
//==============================================================================
/** Registers a MouseListener that will receive all mouse events that occur on
any component.
@see removeGlobalMouseListener
*/
void addGlobalMouseListener (MouseListener* listener);
/** Unregisters a MouseListener that was added with the addGlobalMouseListener()
method.
@see addGlobalMouseListener
*/
void removeGlobalMouseListener (MouseListener* listener);
//==============================================================================
/** Registers a MouseListener that will receive a callback whenever the focused
component changes.
*/
void addFocusChangeListener (FocusChangeListener* listener);
/** Unregisters a listener that was added with addFocusChangeListener(). */
void removeFocusChangeListener (FocusChangeListener* listener);
//==============================================================================
/** Takes a component and makes it full-screen, removing the taskbar, dock, etc.
The component must already be on the desktop for this method to work. It will
be resized to completely fill the screen and any extraneous taskbars, menu bars,
etc will be hidden.
To exit kiosk mode, just call setKioskModeComponent (nullptr). When this is called,
the component that's currently being used will be resized back to the size
and position it was in before being put into this mode.
If allowMenusAndBars is true, things like the menu and dock (on mac) are still
allowed to pop up when the mouse moves onto them. If this is false, it'll try
to hide as much on-screen paraphenalia as possible.
*/
void setKioskModeComponent (Component* componentToUse,
bool allowMenusAndBars = true);
/** Returns the component that is currently being used in kiosk-mode.
This is the component that was last set by setKioskModeComponent(). If none
has been set, this returns 0.
*/
Component* getKioskModeComponent() const noexcept { return kioskModeComponent; }
//==============================================================================
/** Returns the number of components that are currently active as top-level
desktop windows.
@see getComponent, Component::addToDesktop
*/
int getNumComponents() const noexcept;
/** Returns one of the top-level desktop window components.
The index is from 0 to getNumComponents() - 1. This could return 0 if the
index is out-of-range.
@see getNumComponents, Component::addToDesktop
*/
Component* getComponent (int index) const noexcept;
/** Finds the component at a given screen location.
This will drill down into top-level windows to find the child component at
the given position.
Returns 0 if the co-ordinates are inside a non-Juce window.
*/
Component* findComponentAt (const Point<int>& screenPosition) const;
/** The Desktop object has a ComponentAnimator instance which can be used for performing
your animations.
Having a single shared ComponentAnimator object makes it more efficient when multiple
components are being moved around simultaneously. It's also more convenient than having
to manage your own instance of one.
@see ComponentAnimator
*/
ComponentAnimator& getAnimator() noexcept { return animator; }
//==============================================================================
/** Returns the current default look-and-feel for components which don't have one
explicitly set.
@see setDefaultLookAndFeel
*/
LookAndFeel& getDefaultLookAndFeel() noexcept;
/** Changes the default look-and-feel.
@param newDefaultLookAndFeel the new look-and-feel object to use - if this is
set to nullptr, it will revert to using the system's
default one. The object passed-in must be deleted by the
caller when it's no longer needed.
@see getDefaultLookAndFeel
*/
void setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel);
//==============================================================================
/** Returns the number of MouseInputSource objects the system has at its disposal.
In a traditional single-mouse system, there might be only one object. On a multi-touch
system, there could be one input source per potential finger.
To find out how many mouse events are currently happening, use getNumDraggingMouseSources().
@see getMouseSource
*/
int getNumMouseSources() const noexcept { return mouseSources.size(); }
/** Returns one of the system's MouseInputSource objects.
The index should be from 0 to getNumMouseSources() - 1. Out-of-range indexes will return
a null pointer.
In a traditional single-mouse system, there might be only one object. On a multi-touch
system, there could be one input source per potential finger.
*/
MouseInputSource* getMouseSource (int index) const noexcept { return mouseSources [index]; }
/** Returns the main mouse input device that the system is using.
@see getNumMouseSources()
*/
MouseInputSource& getMainMouseSource() const noexcept { return *mouseSources.getUnchecked(0); }
/** Returns the number of mouse-sources that are currently being dragged.
In a traditional single-mouse system, this will be 0 or 1, depending on whether a
juce component has the button down on it. In a multi-touch system, this could
be any number from 0 to the number of simultaneous touches that can be detected.
*/
int getNumDraggingMouseSources() const noexcept;
/** Returns one of the mouse sources that's currently being dragged.
The index should be between 0 and getNumDraggingMouseSources() - 1. If the index is
out of range, or if no mice or fingers are down, this will return a null pointer.
*/
MouseInputSource* getDraggingMouseSource (int index) const noexcept;
/** Ensures that a non-stop stream of mouse-drag events will be sent during the
current mouse-drag operation.
This allows you to make sure that mouseDrag() events are sent continuously, even
when the mouse isn't moving. This can be useful for things like auto-scrolling
components when the mouse is near an edge.
Call this method during a mouseDown() or mouseDrag() callback, specifying the
minimum interval between consecutive mouse drag callbacks. The callbacks
will continue until the mouse is released, and then the interval will be reset,
so you need to make sure it's called every time you begin a drag event.
Passing an interval of 0 or less will cancel the auto-repeat.
@see mouseDrag
*/
void beginDragAutoRepeat (int millisecondsBetweenCallbacks);
//==============================================================================
/** In a tablet device which can be turned around, this is used to inidicate the orientation. */
enum DisplayOrientation
{
upright = 1, /**< Indicates that the display is the normal way up. */
upsideDown = 2, /**< Indicates that the display is upside-down. */
rotatedClockwise = 4, /**< Indicates that the display is turned 90 degrees clockwise from its upright position. */
rotatedAntiClockwise = 8, /**< Indicates that the display is turned 90 degrees anti-clockwise from its upright position. */
allOrientations = 1 + 2 + 4 + 8 /**< A combination of all the orientation values */
};
/** In a tablet device which can be turned around, this returns the current orientation. */
DisplayOrientation getCurrentOrientation() const;
/** Sets which orientations the display is allowed to auto-rotate to.
For devices that support rotating desktops, this lets you specify which of the orientations your app can use.
The parameter is a bitwise or-ed combination of the values in DisplayOrientation, and must contain at least one
set bit.
*/
void setOrientationsEnabled (int allowedOrientations);
/** Returns whether the display is allowed to auto-rotate to the given orientation.
Each orientation can be enabled using setOrientationEnabled(). By default, all orientations are allowed.
*/
bool isOrientationEnabled (DisplayOrientation orientation) const noexcept;
//==============================================================================
/** Tells this object to refresh its idea of what the screen resolution is.
(Called internally by the native code).
*/
void refreshMonitorSizes();
/** True if the OS supports semitransparent windows */
static bool canUseSemiTransparentWindows() noexcept;
private:
//==============================================================================
static Desktop* instance;
friend class Component;
friend class ComponentPeer;
friend class MouseInputSource;
friend class MouseInputSourceInternal;
friend class DeletedAtShutdown;
friend class TopLevelWindowManager;
OwnedArray <MouseInputSource> mouseSources;
void createMouseInputSources();
ListenerList <MouseListener> mouseListeners;
ListenerList <FocusChangeListener> focusListeners;
Array <Component*> desktopComponents;
Array <Rectangle<int> > monitorCoordsClipped, monitorCoordsUnclipped;
Point<int> lastFakeMouseMove;
void sendMouseMove();
int mouseClickCounter;
void incrementMouseClickCounter() noexcept;
ScopedPointer<Timer> dragRepeater;
ScopedPointer<LookAndFeel> defaultLookAndFeel;
WeakReference<LookAndFeel> currentLookAndFeel;
Component* kioskModeComponent;
Rectangle<int> kioskComponentOriginalBounds;
int allowedOrientations;
ComponentAnimator animator;
void timerCallback();
void resetTimer();
ListenerList <MouseListener>& getMouseListeners();
int getNumDisplayMonitors() const noexcept;
const Rectangle<int> getDisplayMonitorCoordinates (int index, bool clippedToWorkArea) const noexcept;
static void getCurrentMonitorPositions (Array <Rectangle<int> >&, const bool clipToWorkArea);
void addDesktopComponent (Component*);
void removeDesktopComponent (Component*);
void componentBroughtToFront (Component*);
static void setKioskComponent (Component*, bool enableOrDisable, bool allowMenusAndBars);
void triggerFocusCallback();
void handleAsyncUpdate();
Desktop();
~Desktop();
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Desktop);
};
#endif // __JUCE_DESKTOP_JUCEHEADER__
| [
"ow3nskip"
] | [
[
[
1,
412
]
]
] |
0778c7861652c500cec7ae044fc332406c0dc03f | af96c6474835be2cc34ef21b0c2a45e950bb9148 | /media/libdrm/mobile2/include/util/xml/DomExpatAgent.h | 9972d5ba98c2b2123ea7923a388d56729045e6e2 | [
"Apache-2.0",
"LicenseRef-scancode-unicode"
] | permissive | zsol/android_frameworks_base | 86abe37fcd4136923cab2d6677e558826f087cf9 | 8d18426076382edaaea68392a0298d2c32cfa52e | refs/heads/donut | 2021-07-04T17:24:05.847586 | 2010-01-13T19:24:55 | 2010-01-13T19:24:55 | 469,422 | 14 | 12 | NOASSERTION | 2020-10-01T18:05:31 | 2010-01-12T21:20:20 | Java | UTF-8 | C++ | false | false | 3,039 | h | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _DOMEXPATAGENT_
#define _DOMEXPATAGENT_
#include <Drm2CommonTypes.h>
#include <ofstream.h>
#include <sostream.h>
#include <ustring.h>
#include <sistream.h>
#include <util/domcore/NodeImpl.h>
#include <util/domcore/DOMString.h>
#include "ExpatWrapper.h"
#include "XMLElementImpl.h"
#include "XMLDocumentImpl.h"
using namespace ustl;
class DomExpatAgent : public ExpatWrapper {
public:
/**
* Constructor for DomExpatAgent.
* @param xmlDocPtr XMLDocument pointer.
*/
DomExpatAgent(XMLDocumentImpl* xmlDocPtr);
/** Destructor for DomExpatAgent. */
~DomExpatAgent();
/**
* Generate XML DOM Document from XML source.
* @param <code>xmlStream</code> the XML source stream.
* @return ture or false to indicate whether generate successfully.
*/
bool generateDocumentFromXML(istringstream *xmlStream);
/**
* Generate XML stream from XML DOM document.
* @return xml stream.
*/
ostringstream* generateXMLFromDocument();
/**
* deal with start element in Expat.
*/
virtual void startElement(const XML_Char *name,
const XML_Char **atts);
/**
* deal with end element for Expat.
*/
virtual void endElement(const XML_Char *name);
/**
* deal with data handler for Expat.
*/
virtual void dataHandler(const XML_Char *s, int len);
PRIVATE:
/**
* Push a xml element with the specific tag name into stack.
* @param name The name of tag.
* @param atts The attributes of related tag.
*/
void pushTag(const DOMString *name, const XML_Char **atts);
/**
* Append text into top element of stack.
* @param text The data related to the present tag.
*/
void appendText(const DOMString *text);
/**
* Pop the xml element with the specific tag name.
* @param name The name of tag.
*/
void popTag(const DOMString *name);
/**
* Traverse the XML DOM document starting from specific element.
* @param root The specific element start to traverse.
*/
void traverse(ElementImpl *root);
PRIVATE:
vector<NodeImpl*> mStack; /**< the stack to manage the tag. */
XMLElementImpl* mTopElementPtr; /**< the top element of the stack. */
XMLDocumentImpl* mXMLDocumentPtr; /**< XML DOM document pointer. */
ostringstream mXMLostream; /**< xml output stream. */
};
#endif
| [
"[email protected]"
] | [
[
[
1,
104
]
]
] |
cd95291b9a81c354a30d6fb42cc6c1e1a4b424a9 | 2f77d5232a073a28266f5a5aa614160acba05ce6 | /01.DevelopLibrary/XMLTestCode/xmlTest/XmlStream.h | c81070bdc35d6890cd9726554df3ef7cf9c5dade | [] | no_license | radtek/mobilelzz | 87f2d0b53f7fd414e62c8b2d960e87ae359c81b4 | 402276f7c225dd0b0fae825013b29d0244114e7d | refs/heads/master | 2020-12-24T21:21:30.860184 | 2011-03-26T02:19:47 | 2011-03-26T02:19:47 | 58,142,323 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,483 | h | // XMLOperator.h: interface for the CXMLOperator class.
//
//////////////////////////////////////////////////////////////////////
#ifndef __XMLStream_h__
#define __XMLStream_h__
#include "tinyxml.h"
#define DefaultBufSize ( 1024*4 )
#define CHAR_MAX_LENGTH ( 50 )
struct NodeAttribute_t
{
wchar_t wcsName [CHAR_MAX_LENGTH];
wchar_t wcsValue[CHAR_MAX_LENGTH];
};
enum EN_MOVE
{
MOVE_END = 0,
MOVE_OK
};
class CXmlStream;
class CXmlNode
{
public:
CXmlNode( wchar_t *pwcNodeName );
virtual ~CXmlNode();
friend class CXmlStream;
public:
// client needs to release the memory
// pwcsNodePath从当前节点开始计算,最后一个标签后面也要添加'/'
HRESULT GetNodeContent( wchar_t* pwcsNodePath, wchar_t** ppwcsNodeValue, NodeAttribute_t** ppAttributes, long* lAttributesCount );
//从根目录开始指定Path
HRESULT SetNodeContent( wchar_t* pwcsNodePath, wchar_t* pwcsNodeValue, NodeAttribute_t* ppAttributes, long lAttributesCount );
//Move到它的兄弟节点
EN_MOVE MoveNext();
//将一个节点追加到已存在的节点上,追加后,pCXmlNode可以被释放
HRESULT AppendNode( CXmlNode* pCXmlNode );
private:
CXmlNode();
HRESULT SetNodePtr( TiXmlElement* pNode, CXmlStream* pCXmlStream );
TiXmlElement* GetElement();
HRESULT SubGetNodeContent( TiXmlElement* pNode, wchar_t** ppwcsNodeValue, NodeAttribute_t** ppAttributes, long* lAttributesCount );
HRESULT SubSetNodeContent( TiXmlElement* pNode, wchar_t* pwcsNodeValue, NodeAttribute_t* ppAttributes, long lAttributesCount );
private:
//node ptr of tiny lib
TiXmlElement* m_CurElement;
CXmlStream * m_pCXmlStream;
};
class CXmlStream
{
public:
CXmlStream();
virtual ~CXmlStream();
friend class CXmlNode;
public:
//accept buf external, but internal also needs alloc and copy the memory
//解析XML文件,需要调用Load,生成XML文件不需要调用Load
HRESULT Load( wchar_t* pwcsXmlBuf, long lSize );
//alloc xml buf,and set the header content
HRESULT Initialize( long lSize = DefaultBufSize );
//if the nodepath dosen't exist,then create it first
//Path 使用'/'进行分割,最后一个标签后面也要添加'/',比如: A/B/C/
//传入的路径在XML中应该是唯一的,如果不唯一,则只会按照XML文件中的顺序,
//得到第一个满足条件的Node
//在创建XML文件时,该方法根据传入的Path,创建指定的Node
//外部使用完pclXmlNode之后,需要释放
HRESULT SelectNode( wchar_t* pwcsNodePath, CXmlNode** pclXmlNode );
HRESULT GetXmlStream( wchar_t* pwcStream, long lSize );
private:
HRESULT SubSelectNode( char *pcsNodePath, CXmlNode** pclXmlNode );
HRESULT MakeXml( char *pcsNodePath, CXmlNode** pclXmlNode );
HRESULT ParseXml( char *pcsNodePath, CXmlNode** pclXmlNode );
TiXmlDocument* GetDocument();
HRESULT MakeXmlFirst( char *pcsNodePath, CXmlNode** pclXmlNode );
HRESULT FindNode( char *pcsNodePath, TiXmlElement** pclXmlElement );
// HRESULT SubMakeXml( vector<TiXmlElement*> & vecElement);
enum EnOperatorType
{
EnLoadXml = 0,
EnCreateXml
};
private:
//memory
string m_strBuf;
//tiny xml object
TiXmlDocument * m_pTiXmlDocument;
EnOperatorType m_EnType;
BOOL bIsFirst;
};
#endif // __XMLStream_h__
| [
"[email protected]"
] | [
[
[
1,
134
]
]
] |
efe5d4c4a290f166f4eba97a1e3f4c9605b9bf42 | f177993b13e97f9fecfc0e751602153824dfef7e | /ImPro/ImProBaseClass/CMFCBasePropertyPage/CMFCBasePropertyPageApp.cpp | 0483adee91251719123326db898745bf8c73713c | [] | 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 | 1,538 | cpp | // CMFCBasePropertyPage.cpp : Defines the initialization routines for the DLL.
//
#include "stdafx.h"
#include "CMFCBasePropertyPageApp.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
//
//TODO: If this DLL is dynamically linked against the MFC DLLs,
// any functions exported from this DLL which call into
// MFC must have the AFX_MANAGE_STATE macro added at the
// very beginning of the function.
//
// For example:
//
// extern "C" BOOL PASCAL EXPORT ExportedFunction()
// {
// AFX_MANAGE_STATE(AfxGetStaticModuleState());
// // normal function body here
// }
//
// It is very important that this macro appear in each
// function, prior to any calls into MFC. This means that
// it must appear as the first statement within the
// function, even before any object variable declarations
// as their constructors may generate calls into the MFC
// DLL.
//
// Please see MFC Technical Notes 33 and 58 for additional
// details.
//
// CCMFCBasePropertyPageApp
BEGIN_MESSAGE_MAP(CCMFCBasePropertyPageApp, CWinApp)
END_MESSAGE_MAP()
// CCMFCBasePropertyPageApp construction
CCMFCBasePropertyPageApp::CCMFCBasePropertyPageApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CCMFCBasePropertyPageApp object
CCMFCBasePropertyPageApp theApp;
// CCMFCBasePropertyPageApp initialization
BOOL CCMFCBasePropertyPageApp::InitInstance()
{
CWinApp::InitInstance();
return TRUE;
}
| [
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
] | [
[
[
1,
63
]
]
] |
215a5f20516e18cafd79a2a6ce9999446377006b | 3d560d0b4772580943946c78e2612ac0589c7958 | /id2type_cast/type_list.hpp | 28c78bd296daebe1b76f97fc6dee7ec8fb647606 | [] | no_license | black-square/id2type-cast | b792f9d9c00afebba856494db58a4151dcfd2b33 | 1a313b55c1dac2ea388c943fa4bf326eaa1957c3 | refs/heads/master | 2020-05-30T13:03:58.304192 | 2011-11-01T09:46:58 | 2011-11-01T09:46:58 | 32,418,189 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 3,429 | hpp | #ifndef ID2TYPE_CAST_TYPE_LIST_HPP
#define ID2TYPE_CAST_TYPE_LIST_HPP
#include "./detail/type_manip.hpp"
///////////////////////////////////////////////////////////////////////////////
// boost::mpl::vector
// define BOOST_MPL_LIMIT_VECTOR_SIZE 20
//
// Loki::Typelist
// max define LOKI_TYPELIST_50
///////////////////////////////////////////////////////////////////////////////
namespace i2tc {
typedef int id_type;
namespace type_list {
struct undefined_tag {};
namespace detail
{
struct base
{
typedef undefined_tag size;
//TODO: Добавить возможность явной поддержки index_of
};
}
///////////////////////////////////////////////////////////////////////////////
// boost:mpl::at
///////////////////////////////////////////////////////////////////////////////
template<class TypeList, id_type N>
struct at
{
typedef typename TypeList::template at<N>::type type;
};
///////////////////////////////////////////////////////////////////////////////
template<class TypeList, id_type N>
struct is_valid
{
typedef typename TypeList::template at<N>::type cur_type;
enum { value = !i2tc::detail::is_same_type<cur_type, undefined_tag>::value };
};
///////////////////////////////////////////////////////////////////////////////
// boost:mpl::size
///////////////////////////////////////////////////////////////////////////////
namespace detail
{
template<class TypeList, id_type N, bool StopRecursion>
struct size_impl
{
enum { is_last_type = !is_valid<TypeList, N>::value };
enum { value = is_last_type ? N : size_impl<TypeList, N + 1, is_last_type>::value };
};
template<class TypeList, id_type N>
struct size_impl< TypeList, N, true >
{
enum { value = -1 };
};
template<class TypeList, bool HasEmbededSize>
struct size
{
enum { value = detail::size_impl<TypeList, 0, false>::value };
};
template<class TypeList>
struct size< TypeList, true >
{
enum { value = TypeList::size::value };
};
}
template<class TypeList>
struct size
{
enum { has_embeded_size = !i2tc::detail::is_same_type<typename TypeList::size, undefined_tag>::value };
enum { value = detail::size<TypeList, has_embeded_size>::value };
};
///////////////////////////////////////////////////////////////////////////////
// boost::mpl::find
///////////////////////////////////////////////////////////////////////////////
namespace detail
{
template<class TypeList, class T, id_type N, bool StopRecursion>
struct index_of_impl
{
typedef typename TypeList::template at<N>::type type;
enum { is_last_type = !is_valid<TypeList, N>::value };
enum { is_type_found = i2tc::detail::is_same_type<type, T>::value };
enum { need_stop_recursion = is_last_type || is_type_found };
enum { value = is_type_found ? N : index_of_impl<TypeList, T, N + 1, need_stop_recursion>::value };
};
template<class TypeList, class T, id_type N>
struct index_of_impl<TypeList, T, N, true>
{
enum { value = -1 };
};
}
template<class TypeList, class T>
struct index_of
{
enum { value = detail::index_of_impl<TypeList, T, 0, false>::value };
};
}}
#endif
| [
"[email protected]"
] | [
[
[
1,
119
]
]
] |
e5bff1a1dc588d6ffe3d9f03b126c616c41a84e9 | 33cdd09e352529963fe8b28b04e0d2e33483777b | /trunk/FEplugin/FEplugin/FEplugin.cpp | ef222c6bc3da68877a9ff993c61991bf72eaae9b | [] | no_license | BackupTheBerlios/reportasistent-svn | 20e386c86b6990abafb679eeb9205f2aef1af1ac | 209650c8cbb0c72a6e8489b0346327374356b57c | refs/heads/master | 2020-06-04T16:28:21.972009 | 2010-05-18T12:06:48 | 2010-05-18T12:06:48 | 40,804,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,985 | cpp |
//FEplugin.cpp: implementation(file)
//
//
// This file is part of LM Report Asistent. (http://reportasistent.berlios.de, [email protected])
//
// Authors: Jan Dedek, Jan Kodym, Martin Chrz, Iva Bartunkova
//
// LM Report Asistent 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.
//
// LM Report Asistent 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 LM Report Asistent; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "stdafx.h"
#include "FEplugin.h"
#include "SockInterface.h"
#include "functions.h"
#include "InterfaceFunctions.h"
using namespace System;
using namespace FEplugin_cs;
// =========== GLOBAL VARIABLES =================
CFESock FESock; /// Global instance of CFESock structure
CSockInterface SockInterfaceFE; /// Interface structure of FEplugin
// =========== class CFESock =====================
// -- construktor
CFESock::CFESock()
{
APCount = _FE_AP_COUNT;
// filling the table APTable
APTable[0].AP_ID = "attribute";
APTable[0].pFn = & fFEAttribute;
APTable[1].AP_ID = "category";
APTable[1].pFn = & fFECategory;
APTable[2].AP_ID = "bool_cedent";
APTable[2].pFn = & fFEBool_cedent;
APTable[3].AP_ID = "KL_cedent";
APTable[3].pFn = & fFEKL_cedent;
APTable[4].AP_ID = "CF_cedent";
APTable[4].pFn = & fFECF_cedent;
// AP hypotheses
APTable[5].AP_ID = "hyp_4ft"; // 4FT
APTable[5].pFn = & fFE4fthyp;
APTable[6].AP_ID = "hyp_sd4ft"; // SD-4FT
APTable[6].pFn = & fFEsd4fthyp;
APTable[7].AP_ID = "hyp_kl"; // KL
APTable[7].pFn = & fFEklhyp;
APTable[8].AP_ID = "hyp_sdkl"; // SD-KL
APTable[8].pFn = & fFEsdklhyp;
APTable[9].AP_ID = "hyp_cf"; // CF
APTable[9].pFn = & fFEcfhyp;
APTable[10].AP_ID = "hyp_sdcf"; // SD-CF
APTable[10].pFn = & fFEsdcfhyp;
// AP Quantifier
APTable[11].AP_ID = "quantifier";
APTable[11].pFn = & fFEQuantifier;
// AP Task
APTable[12].AP_ID = "task";
APTable[12].pFn = & fFETask;
// AP Ferda box
APTable[13].AP_ID = "ferda_box";
APTable[13].pFn = & fFEferda_box;
// AP Column
APTable[14].AP_ID = "column";
APTable[14].pFn = & fFEColumn;
// AP Data matrix
APTable[15].AP_ID = "data_matrix";
APTable[15].pFn = & fFEData_matrix;
}
// ---
pFn_t CFESock::getFnAddress(CString APName)
{
int i=0;
while (i<APCount-1 && APTable[i].AP_ID != APName)
i++;
if (APTable[i].AP_ID == APName)
return APTable[i].pFn;
else
return NULL;
}
// ---
/* returns list of all active elements IDs supported by FEplugin in XML string with structure:
<LIST>
<APID NAME="active element ID 1"/>
<APID NAME="active element ID 2"/>
...
</LIST>
*/
CString CFESock::getAPList()
{
CString result;
result = "<LIST>";
for (int i=0; i<APCount; i++)
{
result += ("<APID NAME=\"" + APTable[i].AP_ID + "\"/>");
}
result += "</LIST>";
return result;
}
///////////////////////////////////////////////
// ---------- initSock
CSockInterface* initSock()
{
SockInterfaceFE.hPerform = & performFE;
SockInterfaceFE.hGetAPList = & getAPListFE;
SockInterfaceFE.hNewSource = & fNewSourceFE;
SockInterfaceFE.hOpenSource = & fOpenSourceFE;
SockInterfaceFE.hCloseSource = & fCloseSourceFE;
// inicialization of FEplugin
if(! FEplugin_cs::FEplugin_init::initialize()) // initialization failed
return NULL;
return (& SockInterfaceFE);
}
| [
"dedej1am@fded5620-0c03-0410-a24c-85322fa64ba0",
"kodyj1am@fded5620-0c03-0410-a24c-85322fa64ba0"
] | [
[
[
1,
21
]
],
[
[
22,
174
]
]
] |
c0ef0fc1f8fa2b5783115c1b7cd740d7f72d5be9 | a5cbc2c1c12b3df161d9028791c8180838fbf2fb | /Heimdall/heimdall-frontend/Source/mainwindow.cpp | b5287e204734b0866eedf6b1ee355c94ba9ad6da | [] | no_license | atinm/Heimdall | e8659fe869172baceb590bc445f383d8bcb72b82 | 692cda38c99834384c4f0c7687c209f432300993 | refs/heads/master | 2020-03-27T12:29:58.609089 | 2010-12-03T19:25:19 | 2010-12-03T19:25:19 | 1,136,137 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,248 | cpp | /* Copyright (c) 2010 Benjamin Dobell, Glass Echidna
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.*/
// Heimdall Frontend
#include "mainwindow.h"
// Qt
#include <QCoreApplication>
#include <QDesktopServices>
#include <QDir>
#include <QFileDialog>
#include <QProcess>
#include <QRegExp>
#include <QUrl>
using namespace HeimdallFrontend;
bool MainWindow::IsArchive(QString path)
{
// Not a real check but hopefully it gets the message across, don't flash archives!
return (path.endsWith(".tar", Qt::CaseInsensitive) || path.endsWith(".gz", Qt::CaseInsensitive) || path.endsWith(".zip", Qt::CaseInsensitive)
|| path.endsWith(".bz2", Qt::CaseInsensitive) || path.endsWith(".7z", Qt::CaseInsensitive) || path.endsWith(".rar", Qt::CaseInsensitive));
}
QString MainWindow::PromptFileSelection(void)
{
QString path = QFileDialog::getOpenFileName(this, "Select File", lastDirectory);
if (path != "")
lastDirectory = path.left(path.lastIndexOf('/') + 1);
return (path);
}
void MainWindow::UpdateStartButton(void)
{
if (heimdallRunning)
{
startFlashButton->setEnabled(false);
return;
}
if (repartitionCheckBox->isChecked())
{
if (!IsArchive(pitLineEdit->text()) && factoryfsCheckBox->isChecked() && !IsArchive(factoryfsLineEdit->text()) && kernelCheckBox->isChecked()
&& !IsArchive(kernelLineEdit->text()) && paramCheckBox->isChecked() && !IsArchive(paramLineEdit->text())
&& primaryBootCheckBox->isChecked() && !IsArchive(primaryBootLineEdit->text()) && secondaryBootCheckBox->isChecked()
&& !IsArchive(secondaryBootLineEdit->text()) && modemCheckBox->isChecked() && !IsArchive(modemLineEdit->text()))
{
startFlashButton->setEnabled(true);
}
else
{
startFlashButton->setEnabled(false);
}
}
else
{
bool atLeastOneFile = false;
if (factoryfsCheckBox->isChecked())
{
atLeastOneFile = true;
if (IsArchive(factoryfsLineEdit->text()))
{
startFlashButton->setEnabled(false);
return;
}
}
if (kernelCheckBox->isChecked())
{
atLeastOneFile = true;
if (IsArchive(kernelLineEdit->text()))
{
startFlashButton->setEnabled(false);
return;
}
}
if (paramCheckBox->isChecked())
{
atLeastOneFile = true;
if (IsArchive(paramLineEdit->text()))
{
startFlashButton->setEnabled(false);
return;
}
}
if (primaryBootCheckBox->isChecked())
{
atLeastOneFile = true;
if (IsArchive(primaryBootLineEdit->text()))
{
startFlashButton->setEnabled(false);
return;
}
}
if (secondaryBootCheckBox->isChecked())
{
atLeastOneFile = true;
if (IsArchive(secondaryBootLineEdit->text()))
{
startFlashButton->setEnabled(false);
return;
}
}
if (cacheCheckBox->isChecked())
{
atLeastOneFile = true;
if (IsArchive(cacheLineEdit->text()))
{
startFlashButton->setEnabled(false);
return;
}
}
if (databaseCheckBox->isChecked())
{
atLeastOneFile = true;
if (IsArchive(databaseLineEdit->text()))
{
startFlashButton->setEnabled(false);
return;
}
}
if (modemCheckBox->isChecked())
{
atLeastOneFile = true;
if (IsArchive(modemLineEdit->text()))
{
startFlashButton->setEnabled(false);
return;
}
}
if (recoveryCheckBox->isChecked())
{
atLeastOneFile = true;
if (IsArchive(recoveryLineEdit->text()))
{
startFlashButton->setEnabled(false);
return;
}
}
startFlashButton->setEnabled(atLeastOneFile);
}
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
setupUi(this);
heimdallRunning = false;
lastDirectory = QDir::toNativeSeparators(QApplication::applicationDirPath());
QObject::connect(actionDonate, SIGNAL(triggered()), this, SLOT(OpenDonationWebpage()));
QObject::connect(actionAboutHeimdall, SIGNAL(triggered()), this, SLOT(ShowAbout()));
QObject::connect(pitBrowseButton, SIGNAL(clicked()), this, SLOT(SelectPit()));
QObject::connect(factoryfsBrowseButton, SIGNAL(clicked()), this, SLOT(SelectFactoryfs()));
QObject::connect(kernelBrowseButton, SIGNAL(clicked()), this, SLOT(SelectKernel()));
QObject::connect(paramBrowseButton, SIGNAL(clicked()), this, SLOT(SelectParam()));
QObject::connect(primaryBootBrowseButton, SIGNAL(clicked()), this, SLOT(SelectPrimaryBootloader()));
QObject::connect(secondaryBootBrowseButton, SIGNAL(clicked()), this, SLOT(SelectSecondaryBootloader()));
QObject::connect(cacheBrowseButton, SIGNAL(clicked()), this, SLOT(SelectCache()));
QObject::connect(databaseBrowseButton, SIGNAL(clicked()), this, SLOT(SelectDatabase()));
QObject::connect(modemBrowseButton, SIGNAL(clicked()), this, SLOT(SelectModem()));
QObject::connect(recoveryBrowseButton, SIGNAL(clicked()), this, SLOT(SelectRecovery()));
QObject::connect(repartitionCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SetRepartionEnabled(int)));
QObject::connect(factoryfsCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SetFactoryfsEnabled(int)));
QObject::connect(kernelCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SetKernelEnabled(int)));
QObject::connect(paramCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SetParamEnabled(int)));
QObject::connect(primaryBootCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SetPrimaryBootloaderEnabled(int)));
QObject::connect(secondaryBootCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SetSecondaryBootloaderEnabled(int)));
QObject::connect(cacheCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SetCacheEnabled(int)));
QObject::connect(databaseCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SetDatabaseEnabled(int)));
QObject::connect(modemCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SetModemEnabled(int)));
QObject::connect(recoveryCheckBox, SIGNAL(stateChanged(int)), this, SLOT(SetRecoveryEnabled(int)));
QObject::connect(startFlashButton, SIGNAL(clicked()), this, SLOT(StartFlash()));
QObject::connect(&process, SIGNAL(readyRead()), this, SLOT(HandleHeimdallStdout()));
QObject::connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(HandleHeimdallReturned(int, QProcess::ExitStatus)));
QObject::connect(&process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(HandleHeimdallError(QProcess::ProcessError)));
}
MainWindow::~MainWindow()
{
}
void MainWindow::OpenDonationWebpage(void)
{
QDesktopServices::openUrl(QUrl("http://www.glassechidna.com.au/donate/", QUrl::StrictMode));
}
void MainWindow::ShowAbout(void)
{
aboutForm.show();
}
void MainWindow::SelectPit(void)
{
QString path = PromptFileSelection();
pitLineEdit->setText(path);
SetRepartionEnabled(path != "");
}
void MainWindow::SelectFactoryfs(void)
{
QString path = PromptFileSelection();
factoryfsLineEdit->setText(path);
SetFactoryfsEnabled(path != "");
}
void MainWindow::SelectKernel(void)
{
QString path = PromptFileSelection();
kernelLineEdit->setText(path);
SetKernelEnabled(path != "");
}
void MainWindow::SelectParam(void)
{
QString path = PromptFileSelection();
paramLineEdit->setText(path);
SetParamEnabled(path != "");
}
void MainWindow::SelectPrimaryBootloader(void)
{
QString path = PromptFileSelection();
primaryBootLineEdit->setText(path);
SetPrimaryBootloaderEnabled(path != "");
}
void MainWindow::SelectSecondaryBootloader(void)
{
QString path = PromptFileSelection();
secondaryBootLineEdit->setText(path);
SetSecondaryBootloaderEnabled(path != "");
}
void MainWindow::SelectCache(void)
{
QString path = PromptFileSelection();
cacheLineEdit->setText(path);
SetCacheEnabled(path != "");
}
void MainWindow::SelectDatabase(void)
{
QString path = PromptFileSelection();
databaseLineEdit->setText(path);
SetDatabaseEnabled(path != "");
}
void MainWindow::SelectModem(void)
{
QString path = PromptFileSelection();
modemLineEdit->setText(path);
SetModemEnabled(path != "");
}
void MainWindow::SelectRecovery(void)
{
QString path = PromptFileSelection();
recoveryLineEdit->setText(path);
SetRecoveryEnabled(path != "");
}
void MainWindow::SetRepartionEnabled(int enabled)
{
if (repartitionCheckBox->isChecked() != (enabled != 0))
repartitionCheckBox->setChecked(enabled);
if (enabled)
{
repartitionCheckBox->setEnabled(true);
pitLineEdit->setEnabled(true);
repartitionCheckBox->setChecked(true);
}
else
{
repartitionCheckBox->setEnabled(pitLineEdit->text() != "");
pitLineEdit->setEnabled(false);
}
UpdateStartButton();
}
void MainWindow::SetFactoryfsEnabled(int enabled)
{
if (factoryfsCheckBox->isChecked() != (enabled != 0))
factoryfsCheckBox->setChecked(enabled);
if (enabled)
{
factoryfsCheckBox->setEnabled(true);
factoryfsLineEdit->setEnabled(true);
factoryfsCheckBox->setChecked(true);
}
else
{
factoryfsCheckBox->setEnabled(factoryfsLineEdit->text() != "");
factoryfsLineEdit->setEnabled(false);
}
UpdateStartButton();
}
void MainWindow::SetKernelEnabled(int enabled)
{
if (kernelCheckBox->isChecked() != (enabled != 0))
kernelCheckBox->setChecked(enabled);
if (enabled)
{
kernelCheckBox->setEnabled(true);
kernelLineEdit->setEnabled(true);
kernelCheckBox->setChecked(true);
}
else
{
kernelCheckBox->setEnabled(kernelLineEdit->text() != "");
kernelLineEdit->setEnabled(false);
}
UpdateStartButton();
}
void MainWindow::SetParamEnabled(int enabled)
{
if (paramCheckBox->isChecked() != (enabled != 0))
paramCheckBox->setChecked(enabled);
if (enabled)
{
paramCheckBox->setEnabled(true);
paramLineEdit->setEnabled(true);
paramCheckBox->setChecked(true);
}
else
{
paramCheckBox->setEnabled(paramLineEdit->text() != "");
paramLineEdit->setEnabled(false);
}
UpdateStartButton();
}
void MainWindow::SetPrimaryBootloaderEnabled(int enabled)
{
if (primaryBootCheckBox->isChecked() != (enabled != 0))
primaryBootCheckBox->setChecked(enabled);
if (enabled)
{
primaryBootCheckBox->setEnabled(true);
primaryBootLineEdit->setEnabled(true);
primaryBootCheckBox->setChecked(true);
}
else
{
primaryBootCheckBox->setEnabled(primaryBootLineEdit->text() != "");
primaryBootLineEdit->setEnabled(false);
}
UpdateStartButton();
}
void MainWindow::SetSecondaryBootloaderEnabled(int enabled)
{
if (secondaryBootCheckBox->isChecked() != (enabled != 0))
secondaryBootCheckBox->setChecked(enabled);
if (enabled)
{
secondaryBootCheckBox->setEnabled(true);
secondaryBootLineEdit->setEnabled(true);
secondaryBootCheckBox->setChecked(true);
}
else
{
secondaryBootCheckBox->setEnabled(secondaryBootLineEdit->text() != "");
secondaryBootLineEdit->setEnabled(false);
}
UpdateStartButton();
}
void MainWindow::SetCacheEnabled(int enabled)
{
if (cacheCheckBox->isChecked() != (enabled != 0))
cacheCheckBox->setChecked(enabled);
if (enabled)
{
cacheCheckBox->setEnabled(true);
cacheLineEdit->setEnabled(true);
cacheCheckBox->setChecked(true);
}
else
{
cacheCheckBox->setEnabled(cacheLineEdit->text() != "");
cacheLineEdit->setEnabled(false);
}
UpdateStartButton();
}
void MainWindow::SetDatabaseEnabled(int enabled)
{
if (databaseCheckBox->isChecked() != (enabled != 0))
databaseCheckBox->setChecked(enabled);
if (enabled)
{
databaseCheckBox->setEnabled(true);
databaseLineEdit->setEnabled(true);
databaseCheckBox->setChecked(true);
}
else
{
databaseCheckBox->setEnabled(databaseLineEdit->text() != "");
databaseLineEdit->setEnabled(false);
}
UpdateStartButton();
}
void MainWindow::SetModemEnabled(int enabled)
{
if (modemCheckBox->isChecked() != (enabled != 0))
modemCheckBox->setChecked(enabled);
if (enabled)
{
modemCheckBox->setEnabled(true);
modemLineEdit->setEnabled(true);
modemCheckBox->setChecked(true);
}
else
{
modemCheckBox->setEnabled(databaseLineEdit->text() != "");
modemLineEdit->setEnabled(false);
}
UpdateStartButton();
}
void MainWindow::SetRecoveryEnabled(int enabled)
{
if (recoveryCheckBox->isChecked() != (enabled != 0))
recoveryCheckBox->setChecked(enabled);
if (enabled)
{
recoveryCheckBox->setEnabled(true);
recoveryLineEdit->setEnabled(true);
recoveryCheckBox->setChecked(true);
}
else
{
recoveryCheckBox->setEnabled(databaseLineEdit->text() != "");
recoveryLineEdit->setEnabled(false);
}
UpdateStartButton();
}
void MainWindow::StartFlash(void)
{
heimdallRunning = true;
heimdallFailed = false;
QStringList arguments;
arguments.append("flash");
if (repartitionCheckBox->isChecked())
{
arguments.append("--pit");
arguments.append(pitLineEdit->text());
}
if (factoryfsCheckBox->isChecked())
{
arguments.append("--factoryfs");
arguments.append(factoryfsLineEdit->text());
}
if (kernelCheckBox->isChecked())
{
arguments.append("--kernel");
arguments.append(kernelLineEdit->text());
}
if (paramCheckBox->isChecked())
{
arguments.append("--param");
arguments.append(paramLineEdit->text());
}
if (primaryBootCheckBox->isChecked())
{
arguments.append("--primary-boot");
arguments.append(primaryBootLineEdit->text());
}
if (secondaryBootCheckBox->isChecked())
{
arguments.append("--secondary-boot");
arguments.append(secondaryBootLineEdit->text());
}
if (cacheCheckBox->isChecked())
{
arguments.append("--cache");
arguments.append(cacheLineEdit->text());
}
if (databaseCheckBox->isChecked())
{
arguments.append("--dbdata");
arguments.append(databaseLineEdit->text());
}
if (modemCheckBox->isChecked())
{
arguments.append("--modem");
arguments.append(modemLineEdit->text());
}
if (recoveryCheckBox->isChecked())
{
arguments.append("--recovery");
arguments.append(recoveryLineEdit->text());
}
if (repartitionCheckBox->isChecked())
{
arguments.append("--repartition");
}
flashProgressBar->setEnabled(true);
UpdateStartButton();
int pathIndex = -1;
process.setReadChannel(QProcess::StandardOutput);
process.start("heimdall", arguments);
process.waitForStarted(1000);
// OS X was playing up and not finding heimdall, so we're manually checking the PATH.
if (heimdallFailed)
{
QStringList environment = QProcess::systemEnvironment();
QStringList paths;
// Ensure /usr/local/bin is in PATH
for (int i = 0; i < environment.length(); i++)
{
if (environment[i].left(5) == "PATH=")
{
paths = environment[i].mid(5).split(':');
paths.prepend("/usr/local/bin");
break;
}
}
while (heimdallFailed && ++pathIndex < paths.length())
{
QString heimdallPath = paths[pathIndex];
if (heimdallPath.length() > 0)
{
heimdallFailed = false;
if (heimdallPath[heimdallPath.length() - 1] != QDir::separator())
heimdallPath += QDir::separator();
heimdallPath += "heimdall";
process.start(heimdallPath, arguments);
process.waitForStarted(1000);
}
}
if (heimdallFailed)
{
flashLabel->setText("Failed to start Heimdall!");
heimdallRunning = false;
flashProgressBar->setEnabled(false);
UpdateStartButton();
}
}
}
void MainWindow::HandleHeimdallStdout(void)
{
QString output = process.read(1024);
// We often receive multiple lots of output from Heimdall at one time. So we use regular expressions
// to ensure we don't miss out on any important information.
QRegExp uploadingExp("Uploading [^\n]+\n");
if (output.lastIndexOf(uploadingExp) > -1)
flashLabel->setText(uploadingExp.cap().left(uploadingExp.cap().length() - 1));
QRegExp percentExp("[\b\n][0-9]+%");
if (output.lastIndexOf(percentExp) > -1)
{
QString percentString = percentExp.cap();
flashProgressBar->setValue(percentString.mid(1, percentString.length() - 2).toInt());
}
/*// Handle other information
int endOfLastLine = output.length() - 1;
for (; endOfLastLine > -1; endOfLastLine--)
{
if (output[endOfLastLine] != '\n')
break;
}
if (endOfLastLine < 0)
return; // Output was blank or just a bunch of new line characters.
int startOfLastLine = endOfLastLine - 1;
for (; startOfLastLine > -1; startOfLastLine--)
{
if (output[startOfLastLine] == '\n')
break;
}
startOfLastLine++;
// Just look at the last line of the output
output = output.mid(startOfLastLine, endOfLastLine - startOfLastLine + 1); // Work with the last line only
percentExp.setPattern("[0-9]+%");
// If the last line wasn't a uploading message or a percentage transferred then display it.
if (output.lastIndexOf(uploadingExp) < 0 && output.lastIndexOf(percentExp) < 0)
flashLabel->setText(output);*/
}
void MainWindow::HandleHeimdallReturned(int exitCode, QProcess::ExitStatus exitStatus)
{
// This is a work-around for strange issues as a result of a exitCode being cast to
// a unsigned char.
char byteExitCode = exitCode;
heimdallRunning = false;
flashProgressBar->setEnabled(false);
UpdateStartButton();
if (exitStatus == QProcess::NormalExit && byteExitCode >= 0)
{
flashLabel->setText("Flash completed sucessfully!");
}
else
{
QString error = process.readAllStandardError();
int firstNewLineChar = error.indexOf('\n');
if (firstNewLineChar == 0)
error = error.mid(1);
else
error = error.left(firstNewLineChar);
flashLabel->setText(error);
}
}
void MainWindow::HandleHeimdallError(QProcess::ProcessError error)
{
if (error == QProcess::FailedToStart || error == QProcess::Timedout)
{
heimdallFailed = true;
}
else if (error == QProcess::Crashed)
{
flashLabel->setText("Heimdall crashed!");
heimdallRunning = false;
flashProgressBar->setEnabled(false);
UpdateStartButton();
}
else
{
flashLabel->setText("Heimdall reported an unknown error!");
heimdallRunning = false;
flashProgressBar->setEnabled(false);
UpdateStartButton();
}
}
| [
"[email protected]"
] | [
[
[
1,
742
]
]
] |
12ce1657f2fa44f600f9a923647741e7d02eb13c | eec9d789e04bc81999ac748ca2c70f0a612dadb7 | /testProject/testProject/TreeList/TLFrame.cpp | 67aa39b4a8ad13db1ac4848aba057c0dffdf36fe | [] | no_license | scriptkitz/myfirstpro-test | 45d79d9a35fe5ee1e8f237719398d08d7d86b859 | a3400413e3a7900657774a278006faea7d682955 | refs/heads/master | 2021-01-22T07:13:27.100583 | 2010-11-16T15:02:50 | 2010-11-16T15:02:50 | 38,792,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,344 | cpp | // TLFrame.cpp : implementation file
//
#include "stdafx.h"
#include "TLView.h"
#include "TLFrame.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define ID_TREE_LIST_HEADER 370
#define ID_TREE_LIST_CTRL 373
#define ID_TREE_LIST_SCROLLBAR 377
/////////////////////////////////////////////////////////////////////////////
// CTLFrame
CTLFrame::CTLFrame()
{
m_RTL = FALSE;
}
CTLFrame::~CTLFrame()
{
}
BEGIN_MESSAGE_MAP(CTLFrame, CWnd)
//{{AFX_MSG_MAP(CTLFrame)
ON_WM_HSCROLL()
ON_WM_CONTEXTMENU()
ON_WM_SIZE()
ON_WM_MOVE()
ON_WM_LBUTTONDBLCLK()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTLFrame message handlers
LONG FAR PASCAL CTLFrame::DummyWndProc(HWND h, UINT u, WPARAM w, LPARAM l)
{
return ::DefWindowProc(h, u, w, l);
}
void CTLFrame::RegisterClass()
{
WNDCLASS wc;
memset(&wc, 0, sizeof(wc));
wc.style = CS_DBLCLKS | CS_VREDRAW | CS_HREDRAW | CS_GLOBALCLASS;
wc.lpfnWndProc = DummyWndProc;
wc.hInstance = AfxGetInstanceHandle();
wc.hCursor = 0;
wc.lpszClassName = "LANTIVTREELISTCTRL";
wc.hbrBackground = (HBRUSH) GetStockObject(LTGRAY_BRUSH);
if (!::RegisterClass(&wc))
{
ASSERT(FALSE);
}
}
BOOL CTLFrame::SubclassDlgItem(UINT nID, CWnd* parent)
{
if (!CWnd::SubclassDlgItem(nID, parent)) return FALSE;
Initialize();
return TRUE;
}
void CTLFrame::Initialize()
{
// creates all the objects in frame -
// header, tree, horizontal scroll bar
CRect m_wndRect;
GetWindowRect(&m_wndRect);
CRect m_headerRect;
// create the header
{
m_headerRect.left = m_headerRect.top = -1;
m_headerRect.right = m_wndRect.Width();
m_tree.m_wndHeader.Create(WS_CHILD | WS_VISIBLE | HDS_BUTTONS | HDS_HORZ, m_headerRect, this, ID_TREE_LIST_HEADER);
}
CSize textSize;
// set header's pos, dimensions and image list
{
LOGFONT logfont;
CFont *pFont = GetParent()->GetFont();
pFont->GetLogFont( &logfont );
m_tree.m_headerFont.CreateFontIndirect( &logfont );
m_tree.m_wndHeader.SetFont(&m_tree.m_headerFont);
CDC *pDC = m_tree.m_wndHeader.GetDC();
pDC->SelectObject(&m_tree.m_headerFont);
textSize = pDC->GetTextExtent("A");
m_tree.m_wndHeader.SetWindowPos(&wndTop, 0, 0, m_headerRect.Width(), textSize.cy+4, SWP_SHOWWINDOW);
m_tree.m_cImageList.Create(IDB_HEADER, 16, 10, 0);
m_tree.m_wndHeader.SetImageList(&m_tree.m_cImageList);
m_tree.m_wndHeader.UpdateWindow();
}
CRect m_treeRect;
// create the tree itself
{
GetWindowRect(&m_wndRect);
m_treeRect.left=0;
m_treeRect.top = textSize.cy+4;
m_treeRect.right = m_headerRect.Width()-5;
m_treeRect.bottom = m_wndRect.Height()-GetSystemMetrics(SM_CYHSCROLL)-4;
m_tree.Create(WS_CHILD | WS_VISIBLE | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, m_treeRect, this, ID_TREE_LIST_CTRL);
}
// finally, create the horizontal scroll bar
{
CRect m_scrollRect;
m_scrollRect.left=0;
m_scrollRect.top = m_treeRect.bottom;
m_scrollRect.right = m_treeRect.Width()-GetSystemMetrics(SM_CXVSCROLL);
m_scrollRect.bottom = m_wndRect.bottom;
m_horScrollBar.Create(WS_CHILD | WS_VISIBLE | WS_DISABLED | SBS_HORZ | SBS_TOPALIGN, m_scrollRect, this, ID_TREE_LIST_SCROLLBAR);
SCROLLINFO si;
si.fMask = SIF_PAGE;
si.nPage = m_treeRect.Width();
m_horScrollBar.SetScrollInfo(&si, FALSE);
}
SortTree(0, TRUE, m_tree.GetRootItem());
}
BOOL CTLFrame::VerticalScrollVisible()
{
int sMin, sMax;
m_tree.GetScrollRange(SB_VERT, &sMin, &sMax);
return sMax!=0;
}
BOOL CTLFrame::HorizontalScrollVisible()
{
int sMin, sMax;
m_horScrollBar.GetScrollRange(&sMin, &sMax);
return sMax!=0;
}
int CTLFrame::StretchWidth(int m_nWidth, int m_nMeasure)
{
return ((m_nWidth/m_nMeasure)+1)*m_nMeasure;
}
void CTLFrame::ResetScrollBar()
{
// resetting the horizontal scroll bar
int m_nTotalWidth=0, m_nPageWidth;
CRect m_treeRect;
m_tree.GetClientRect(&m_treeRect);
CRect m_wndRect;
GetClientRect(&m_wndRect);
CRect m_headerRect;
m_tree.m_wndHeader.GetClientRect(&m_headerRect);
CRect m_barRect;
m_horScrollBar.GetClientRect(m_barRect);
m_nPageWidth = m_treeRect.Width();
m_nTotalWidth = m_tree.GetColumnsWidth();
if(m_nTotalWidth > m_nPageWidth)
{
// show the scroll bar and adjust it's size
{
m_horScrollBar.EnableWindow(TRUE);
m_horScrollBar.ShowWindow(SW_SHOW);
// the tree becomes smaller
CRect TreeRect;
m_tree.GetWindowRect(&TreeRect);
if(TreeRect.Width() != m_wndRect.Width() || TreeRect.Height() != m_wndRect.Height()-m_barRect.Height()-m_headerRect.Height())
m_tree.SetWindowPos(&wndTop, 0, 0, m_wndRect.Width(), m_wndRect.Height()-m_barRect.Height()-m_headerRect.Height(), SWP_NOMOVE);
CRect ScrollRect;
m_horScrollBar.GetWindowRect(&ScrollRect);
if(!VerticalScrollVisible())
// i.e. vertical scroll bar isn't visible
{
m_horScrollBar.SetWindowPos(&wndTop, 0, 0, m_wndRect.Width(), m_barRect.Height(), SWP_NOMOVE);
}
else
{
m_horScrollBar.SetWindowPos(&wndTop, 0, 0, m_wndRect.Width() - GetSystemMetrics(SM_CXVSCROLL), m_barRect.Height(), SWP_NOMOVE);
}
}
SCROLLINFO si;
si.fMask = SIF_PAGE | SIF_RANGE;
si.nPage = m_treeRect.Width();
si.nMin = 0;
si.nMax = m_nTotalWidth;
m_horScrollBar.SetScrollInfo(&si, FALSE);
// recalculate the offset
{
CRect m_wndHeaderRect;
m_tree.m_wndHeader.GetWindowRect(&m_wndHeaderRect);
ScreenToClient(&m_wndHeaderRect);
m_tree.m_nOffset = m_wndHeaderRect.left;
m_horScrollBar.SetScrollPos(-m_tree.m_nOffset);
}
}
else
{
m_horScrollBar.EnableWindow(FALSE);
// we no longer need it, so hide it!
{
m_horScrollBar.ShowWindow(SW_HIDE);
// the tree takes scroll's place
CRect TreeRect;
m_tree.GetClientRect(&TreeRect);
m_tree.SetWindowPos(&wndTop, 0, 0, m_wndRect.Width(), m_wndRect.Height() - m_headerRect.Height(), SWP_NOMOVE);
}
m_horScrollBar.SetScrollRange(0, 0);
// set scroll offset to zero
{
m_tree.m_nOffset = 0;
m_tree.Invalidate();
CRect m_headerRect;
m_tree.m_wndHeader.GetWindowRect(&m_headerRect);
CRect m_wndRect;
GetClientRect(&m_wndRect);
m_tree.m_wndHeader.SetWindowPos(&wndTop, m_tree.m_nOffset, 0, max(StretchWidth(m_tree.GetColumnsWidth(),m_wndRect.Width()),m_wndRect.Width()), m_headerRect.Height(), SWP_SHOWWINDOW);
}
}
}
void CTLFrame::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
CRect m_treeRect;
m_tree.GetClientRect(&m_treeRect);
if(pScrollBar == &m_horScrollBar)
{
int m_nCurPos = m_horScrollBar.GetScrollPos();
int m_nPrevPos = m_nCurPos;
switch(nSBCode)
{
case SB_LEFT: m_nCurPos = 0;
break;
case SB_RIGHT: m_nCurPos = m_horScrollBar.GetScrollLimit()-1;
break;
case SB_LINELEFT: m_nCurPos = max(m_nCurPos-6, 0);
break;
case SB_LINERIGHT: m_nCurPos = min(m_nCurPos+6, m_horScrollBar.GetScrollLimit()-1);
break;
case SB_PAGELEFT: m_nCurPos = max(m_nCurPos-m_treeRect.Width(), 0);
break;
case SB_PAGERIGHT: m_nCurPos = min(m_nCurPos+m_treeRect.Width(), m_horScrollBar.GetScrollLimit()-1);
break;
case SB_THUMBTRACK:
case SB_THUMBPOSITION: if(nPos==0)
m_nCurPos = 0;
else
m_nCurPos = min(StretchWidth(nPos, 6), m_horScrollBar.GetScrollLimit()-1);
break;
}
// 6 is Microsoft's step in a CListCtrl for example
m_horScrollBar.SetScrollPos(m_nCurPos);
m_tree.m_nOffset = -m_nCurPos;
// smoothly scroll the tree control
{
CRect m_scrollRect;
m_tree.GetClientRect(&m_scrollRect);
m_tree.ScrollWindow(m_nPrevPos - m_nCurPos, 0, &m_scrollRect, &m_scrollRect);
}
CRect m_headerRect;
m_tree.m_wndHeader.GetWindowRect(&m_headerRect);
CRect m_wndRect;
GetClientRect(&m_wndRect);
m_tree.m_wndHeader.SetWindowPos(&wndTop, m_tree.m_nOffset, 0, max(StretchWidth(m_tree.GetColumnsWidth(),m_treeRect.Width()),m_wndRect.Width()), m_headerRect.Height(), SWP_SHOWWINDOW);
}
CWnd::OnHScroll(nSBCode, nPos, pScrollBar);
}
void CTLFrame::SortTree(int nCol, BOOL bAscending, HTREEITEM hParent)
{
HTREEITEM hChild;
HTREEITEM hPa = hParent;
while(hPa!=NULL)
{
if(m_tree.ItemHasChildren(hPa))
{
hChild = m_tree.GetChildItem(hPa);
m_tree.SortItems(nCol, bAscending, hPa);
SortTree(nCol, bAscending, hChild);
}
hPa = m_tree.GetNextSiblingItem(hPa);
}
}
BOOL CTLFrame::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
HD_NOTIFY *pHDN = (HD_NOTIFY*)lParam;
if((wParam == ID_TREE_LIST_HEADER) && (pHDN->hdr.code == HDN_ITEMCLICK))
{
int nCol = pHDN->iItem;
BOOL bAscending = FALSE;
if(m_tree.m_wndHeader.GetItemImage(nCol)==-1)
bAscending = TRUE;
else
if(m_tree.m_wndHeader.GetItemImage(nCol)==1)
bAscending = TRUE;
for(int i=0;i<m_tree.GetColumnsNum();i++)
{
m_tree.m_wndHeader.SetItemImage(i, -1);
}
if(bAscending)
m_tree.m_wndHeader.SetItemImage(nCol, 0);
else
m_tree.m_wndHeader.SetItemImage(nCol, 1);
m_tree.SortItems(nCol, bAscending, NULL);
SortTree(nCol, bAscending, m_tree.GetRootItem());
m_tree.UpdateWindow();
}
else
if((wParam == ID_TREE_LIST_HEADER) && (pHDN->hdr.code == HDN_ITEMCHANGED))
{
int m_nPrevColumnsWidth = m_tree.GetColumnsWidth();
m_tree.RecalcColumnsWidth();
ResetScrollBar();
// in case we were at the scroll bar's end,
// and some column's width was reduced,
// update header's position (move to the right).
CRect m_treeRect;
m_tree.GetClientRect(&m_treeRect);
CRect m_headerRect;
m_tree.m_wndHeader.GetClientRect(&m_headerRect);
if((m_nPrevColumnsWidth > m_tree.GetColumnsWidth()) &&
(m_horScrollBar.GetScrollPos() == m_horScrollBar.GetScrollLimit()-1) &&
(m_treeRect.Width() < m_tree.GetColumnsWidth()))
{
m_tree.m_nOffset = -m_tree.GetColumnsWidth()+m_treeRect.Width();
m_tree.m_wndHeader.SetWindowPos(&wndTop, m_tree.m_nOffset, 0, 0, 0, SWP_NOSIZE);
}
m_tree.Invalidate();
}
else
GetParent()->SendMessage(WM_NOTIFY, wParam, lParam);
return CWnd::OnNotify(wParam, lParam, pResult);
}
void CTLFrame::OnContextMenu(CWnd* pWnd, CPoint point)
{
GetParent()->SendMessage(WM_CONTEXTMENU, (WPARAM)pWnd, 0);
}
void CTLFrame::OnSize(UINT nType, int cx, int cy)
{
CWnd::OnSize(nType, cx, cy);
// resize all the controls
{
CRect m_wndRect;
GetClientRect(&m_wndRect);
CRect m_headerRect;
m_tree.m_wndHeader.GetWindowRect(&m_headerRect);
m_tree.ScreenToClient(&m_headerRect);
m_tree.m_wndHeader.SetWindowPos(&wndTop, 0, 0, -m_headerRect.left + m_wndRect.Width(), m_headerRect.Height(), SWP_NOMOVE);
CRect m_scrollRect;
m_horScrollBar.GetClientRect(&m_scrollRect);
m_tree.SetWindowPos(&wndTop, 0, 0, m_wndRect.Width(), m_wndRect.Height() - m_scrollRect.Height(), SWP_NOMOVE);
CRect m_treeRect;
m_tree.GetClientRect(&m_treeRect);
m_horScrollBar.SetWindowPos(&wndTop, 0, m_treeRect.bottom, m_wndRect.Width(), m_scrollRect.Height(), SWP_SHOWWINDOW);
m_tree.ResetVertScrollBar();
ResetScrollBar();
}
}
void CTLFrame::OnMove(int x, int y)
{
CWnd::OnMove(x, y);
// resize all the controls
{
CRect m_wndRect;
GetClientRect(&m_wndRect);
CRect m_headerRect;
m_tree.m_wndHeader.GetClientRect(&m_headerRect);
m_tree.m_wndHeader.SetWindowPos(&wndTop, 0, 0, m_wndRect.Width(), m_headerRect.Height(), SWP_NOMOVE);
CRect m_scrollRect;
m_horScrollBar.GetClientRect(&m_scrollRect);
m_tree.SetWindowPos(&wndTop, 0, 0, m_wndRect.Width(), m_wndRect.Height() - m_scrollRect.Height(), SWP_NOMOVE);
CRect m_treeRect;
m_tree.GetClientRect(&m_treeRect);
m_horScrollBar.SetWindowPos(&wndTop, 0, m_treeRect.bottom, m_wndRect.Width(), m_scrollRect.Height(), SWP_SHOWWINDOW);
m_tree.ResetVertScrollBar();
}
}
void CTLFrame::OnLButtonDblClk(UINT nFlags, CPoint point)
{
GetParent()->SendMessage(WM_LBUTTONDBLCLK);
CWnd::OnLButtonDblClk(nFlags, point);
}
| [
"scriptkitz@da890e6b-1f8b-8dbb-282d-e1a1f9b2274c"
] | [
[
[
1,
460
]
]
] |
83811c71d560390dfea5c7d08b842bd15e6eaa4f | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /source/libOEBase/IOEObject.cpp | bda16fad7c764a459edf23d086b396d062aa3a7c | [] | no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,885 | cpp | /*!
* \file IOEObject.cpp
* \date 8-17-2010 22:51:08
*
*
* \author zjhlogo ([email protected])
*/
#include <libOEBase/IOEObject.h>
#include <libOEMsg/OEMsgObjectDestroy.h>
#include <assert.h>
IOEObject::IOEObject()
{
m_bOK = false;
m_nRef = 1;
}
IOEObject::~IOEObject()
{
COEMsgObjectDestroy msgDestroy(this);
CallEvent(msgDestroy);
}
bool IOEObject::IsOK()
{
return m_bOK;
}
void IOEObject::Release()
{
if (DecRef() <= 0) delete this;
}
int IOEObject::IncRef()
{
return ++m_nRef;
}
int IOEObject::DecRef()
{
return --m_nRef;
}
int IOEObject::GetRef() const
{
return m_nRef;
}
void IOEObject::RegisterEvent(uint nMsgID, IOEObject* pHandler, MSG_FUNC pFunc)
{
EVENT_HANDLER handler;
handler.pHandler = pHandler;
handler.pFunc = pFunc;
handler.nDepth = 0;
m_EventsMap.insert(std::make_pair(nMsgID, handler));
}
void IOEObject::UnregisterEvent(uint nMsgID, IOEObject* pHandler, MSG_FUNC pFunc)
{
TP_EVENT_HANDLER range = m_EventsMap.equal_range(nMsgID);
if (range.first == range.second) return;
for (TM_EVENT_HANDLER::iterator it = range.first; it != range.second; ++it)
{
EVENT_HANDLER& handler = it->second;
if (handler.pHandler == pHandler && handler.pFunc == pFunc)
{
m_EventsMap.erase(it);
return;
}
}
}
bool IOEObject::CallEvent(IOEMsg& msg)
{
TP_EVENT_HANDLER range = m_EventsMap.equal_range(msg.GetMsgID());
if (range.first == range.second) return false;
for (TM_EVENT_HANDLER::iterator it = range.first; it != range.second; ++it)
{
EVENT_HANDLER& handler = it->second;
// check the loop depth, it must always 0 or 1
if (handler.nDepth > 0)
{
assert(false);
continue;
}
++handler.nDepth;
if (!(handler.pHandler->*handler.pFunc)(msg))
{
assert(false);
}
--handler.nDepth;
}
return true;
}
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
] | [
[
[
1,
100
]
]
] |
d30d35062815f635d4b399b34363cbe21f4b7cf8 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/DOM_Attr.cpp | ce50ba14e19f9ce76e41786db8397b9c6215ac1c | [
"Apache-2.0"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,060 | cpp | /*
* Copyright 1999-2002,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: DOM_Attr.cpp,v 1.4 2004/09/08 13:55:42 peiyongz Exp $
*/
#include "DOM_Attr.hpp"
#include "AttrImpl.hpp"
XERCES_CPP_NAMESPACE_BEGIN
DOM_Attr::DOM_Attr()
: DOM_Node(null)
{
};
DOM_Attr::DOM_Attr(const DOM_Attr & other)
: DOM_Node(other)
{
};
DOM_Attr::DOM_Attr(AttrImpl *impl) :
DOM_Node(impl)
{
};
DOM_Attr::~DOM_Attr()
{
};
DOM_Attr & DOM_Attr::operator = (const DOM_Attr & other)
{
return (DOM_Attr &) DOM_Node::operator = (other);
};
DOM_Attr & DOM_Attr::operator = (const DOM_NullPtr *other)
{
return (DOM_Attr &) DOM_Node::operator = (other);
};
DOMString DOM_Attr::getName() const
{
return ((AttrImpl *)fImpl)->getName().clone();
};
bool DOM_Attr::getSpecified() const
{
return ((AttrImpl *)fImpl)->getSpecified();
};
DOMString DOM_Attr::getValue() const
{
// The value of an attribute does not need to be cloned before
// returning, because it is computed dynamically from the
// children of the attribute.
//
return ((AttrImpl *)fImpl)->getValue();
};
void DOM_Attr::setValue(const DOMString &value) {
((AttrImpl *)fImpl)->setValue(value);
};
//Introduced in DOM Level 2
DOM_Element DOM_Attr::getOwnerElement() const
{
return DOM_Element(((AttrImpl *)fImpl)->getOwnerElement());
}
XERCES_CPP_NAMESPACE_END
| [
"[email protected]"
] | [
[
[
1,
99
]
]
] |
b9a5db8a8dd533f5e7e8a9d22a83f09906678114 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Models/BASIC1/PIPE.CPP | 3e2e5dc8ff14c06cc66d62f6021c997babc8f8d7 | [] | 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 | 48,627 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
// SysCAD Copyright Kenwalt (Pty) Ltd 1992
#include "stdafx.h"
#include <string.h>
#include <math.h>
#include <stdio.h>
#include "sc_defs.h"
#include "scdver.h"
#define __PIPE_CPP
#include "pipe.h"
#include "models.h"
#define dbgSetZs 0
#define WITHPLUGFLOW 1
//==========================================================================
//
//
//
//==========================================================================
/*
#i<Qualities> : These are variables which are distinquished
by their prefix #i<_Qual>. These qualities, have two states
either "Present", in which case the quality is included in the
simulation of the unit or "-" in which case the quality is ignored.
*/
//==========================================================================
/*#D:#T:Pipe_GP
#X:#h<General Description>#nThe general purpose pipe connects any two process
units together. It is always connected from an outlet point on one unit to an
inlet point of another. It is commonly used to transport liquids, slurries and
gases. The pipe only has one inlet and one outlet point.
#n#n
#n#h<Variables to be supplied by the user>#n
#i<LnkMode> : Select the link mode. This determines how material is transfered
between units. #u<Pipe> mode allows by-directional flow with pressure drops etc.
#u<Transfer> mode only allows material transfer in the forward direction, it
'instantaneously' delivers all material from one unit to the next.#n
#i<Direction> : Select the direction materials are allowed to flow in the pipe.
This is meaningless if the pipe is in transfer link mode. #u<Default> allows
material to flow in any direction depending on external considerations.
#u<Forward> allows material to only flow in the positive (forward) direction
from link source to link destination. #u<Reverse> allows material to only flow
in the negative (reverse) direction from link destination to link source.#n
#i<Qm_Reqd> : The mass flow #b<required> in the pipe. Usually enter * to indicate
a required value is not being set.#n
#i<VLEquilibrium> : This can be used to switch #x<Vapour Liquid Equilibrium Logic>
on. If it is on then the associated variables (VLE) must be configured.#n
#i<Reactions> : This can be used to switch reactions on. If it is on then the associated
#x<reaction block> variables (m_RB) must be configured.#n
#i<dZ_Rqd> : The required difference in elevation between the inlet and
outlet of the pipe.#n
#i<SrcHFrc> : The height as a fraction at which the base of the pipe physically
connects to the source unit. This may be meaningless when the pipe is connected
to a unit that as no volume or surge capacity.#n
#i<DstHFrc> : The height as a fraction at which the base of the pipe physically
connects to the destination unit. This may be meaningless when the pipe is connected
to a unit that as no volume or surge capacity.#n
#i<Flow.On> : This behaves as a simple valve. If #u<On> then material can flow
in the pipe, if #u<Off> then the pipe is effectively blocked and material will not
be allowed to flow.#n
#i<Eqn.Name> : This allows you to select the model from the #x<pipe flow equations>
which calculates the pressure drop, due to the flow of materials, across the pipe. Each
equation has its own specific parameters which need to be configured.#n
#i<Qi.Model> : This allows the selection of the model that is to be used to calculate
how the species are combined, this is normally done using a mass weighted mean.#n
#i<Qi.View> : This allows the selection of how the list of species is being displayed.
Options such as MassFlow, MoleFlow, VolFlow, MassFrac, ElemntFlow, CompntConc etc can
be selected.#n
#i<Qi.Phase> : This allows the selection of which phase(s) for the list of species is
being displayed. Options such as All, Solids, Liquids and Vapours can be selected.#n
#i<Specie Lockup> : This causes a percentage of the species, to be retained within the
unit. The amount of retention is dependent upon the type of unit.#n
#i<Size Distribution> : This associates a particle size distribution curve with each specie.#n
#n#n
#h<Associated variables>#n
#i<QmEst> : The estimated mass flow within the pipe. This will only differ from "Qm" if the
upstream unit cannot supply sufficient material.#n
#i<Qm> : The mass flow of the material through the pipe.#n
#i<Qv> : The volumetric flowrate of the material within the pipe.#n
#i<NQv> : The normalized volumetric flowrate, ie the flowrate measured at STP, of the material
within the pipe. This will only differ from "Qv" when pressurized gases are being conveyed,
since the volume of a gas is proportional to its pressure.#n
#i<Vel> : The velocity of the flow through the pipe. This will only be calculated if the flow
equation chosen by the user requires a pipe diameter to be specified.#n
#i<T> : The temperature of the material within the pipe.#n
#i<Rho> : The density of the material within the pipe.#n
#i<dPb> : The extra pressure required to deliver the specified flowrate if there is insufficient
pressure at the source of the pipe.#n
#i<dPq> : The pressure drop in the pipe caused by the flow of material within the pipe.#n
#i<dPz> : The static head ie the pressure associated with the difference in elevation between
the inlet and outlet of the pipe.#n
#i<Bst> : The extra pressure (boost) required to deliver the specified flowrate if there is
insufficient pressure at the source of the pipe.#n
#i<PiR> : The remote pressure at the inlet of the pipe ie the pressure measured at the flange.#n
#i<Pi> : The pressure at the inlet of the pipe ie the pressure measured after the flange.#n
#i<dP> : The total pressure drop across the pipe.#n
#i<Po> : The pressure at the outlet of the pipe, ie the pressure measured before the flange.#n
#i<PoR> : The remote pressure at the outlet of the pipe, ie the pressure measured at the flange.#n
#i<dZ> : The difference in elevation between the inlet and outlet of the pipe.#n
#i<L> : The length of the pipe.#n
#i<SrcHgt> : The actual height of the base of the inlet of the pipe, in relation to the common datum.#n
#i<DstHgt> : The actual height of the base of the outlet of the pipe, in relation to the common datum.#n
#i<SrcIO> : The tag identifying the source (upstream) unit, followed by "." and then the
name of the output point of the unit, to which the input of the pipe is connected.#n
#i<DstIO> : The tag identifying the destination (downstream) unit, followed by "." and then
the name of the inlet point of the unit, to which the output of the pipe is connected.#n
#i<QMt> : The total mass flow of all the species within the pipe.#n
#i<QVt> : The total volumetric flow of all the species within the pipe.#n
#i<MoleWt> : The molecular weight of the material within the pipe.#n
#i<CpCv> : ???#n
#i<Sf> : The percentage of solids within the pipe.#n
#i<Lf> : The percentage of liquids within the pipe.#n
#i<Vf> : The percentage of vapours within the pipe.#n
#i<SatT@P> : The temperature at which the liquids within the pipe will boil at atmospheric pressure.
This is mainly of interest for elevated boiling point calculations.#n
#i<SatP@T> : The saturated pressure of the liquids within the pipe.#n
#i<BPE> : The Boiling Point Elevation of the liquids within the pipe.#n
#i<Cp> : The specific heat of the material within the pipe.#n
#i<totH> : The total enthalpy of the amterial within the pipe.#n
#n#n
#n#h<Other>#n
Default model prefix:P#n
Short name:Pipe#n
Model type:Link
#G:Links
*/
//==========================================================================
//==========================================================================
IMPLEMENT_MODELLINK(Pipe, "Pipe", "1", "P", TOC_ALL|TOC_DYNAMICFLOW|TOC_GRP_GENERAL|TOC_STD_KENWALT,
"Process:Piping:Pipe_GP",
"General purpose pipe")
Pipe::Pipe(pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach) :
MN_Lnk(pClass_, TagIn, pAttach, eAttach)
{
m_FEP.AssignFlwEqnGroup(PipeGroup, PipeGroup.Default(), this);
m_FEP.SetOptions(0, 1.0);
AttachIOAreas(TwoIOAreaListWithMBS, &PipeGroup, &PipeGroup);
// EHX.Open(&CEnvironHXClass);
RegisterMacroMdlNode(CMMFlashTrain::MMIOs, &typeid(Pipe), 0, mmio_CONNECT, NULL);
RegisterMacroMdlNode(CMMFlashTrain::MMIOs, &typeid(Pipe), 1, mmio_CONNECT, NULL);
};
//--------------------------------------------------------------------------
Pipe::~Pipe()
{
};
//--------------------------------------------------------------------------
void Pipe::BuildDataDefn(DataDefnBlk &DDB)
{
//const flag IsXfer=((Joins.GetSize()>0) && Joins[0].InXferNet()) || XferFlwMode();
DDB.BeginStruct(this, NULL, NULL, DDB_NoPage);
if (!NetProbalMethod() && PrjFileVerNo()<73)
{
DDB.Visibility(NM_Dynamic|SM_All|HM_All);
DDB.Text ("");
static DDBValueLst DDB0a[]={
{LFM_Xfer, "Transfer"},
{LFM_Full, "Pipe"},
//{LFM_SrcSnk, "SrcSnk", MDD_Hidden},
{0}};
static DDBValueLst DDB0b[]={
{LFM_Xfer, "Transfer"},
{LFM_Full, "Pipe", MDD_Hidden},
//{LFM_SrcSnk, "SrcSnk", MDD_Hidden},
{0}};
if (SolveInlineMethod())
DDB.Long ("LnkMode", "", DC_, "", xidLnkMode, this, 0/*isParmStopped|SetOnChange*/, DDB0b);
else
DDB.Long ("LnkMode", "", DC_, "", xidLnkMode, this, isParmStopped|SetOnChange, DDB0a);
}
const flag IsXfer=(!NetProbalMethod() && (((Joins.GetSize()>0) && Joins[0].InXferNet()) || XferFlowMode()));
const flag IsPipe=!IsXfer;
const flag IsSrcSnk=!IsXfer && GetActiveHold();
DDB.Visibility();
DDB.Text ("");
DDB.Text ("Results: Flow Conditions");
DDB.Double("", "QmPrvPB", DC_Qm, "kg/s", xidFEQmPrvPB, this, isResult|noView|NAN_OK);
DDB.Visibility(NM_Dynamic|SM_All|HM_All);
DDB.String("", "QmEst.Type",DC_, "", xidQmEstType, this, isResult|InitHidden);
DDB.String("", "QmEst.Src", DC_, "", xidQmEstSrc, this, isResult|isTag|InitHidden);
DDB.Double("EstMassFlow", "QmEst", DC_Qm, "kg/s", xidQmEst, this, NetDynamicMethod() ? isResult : isResult|InitHidden);
DDB.Visibility();
DDB.Double ("Mass_Flow", "Qm", DC_Qm, "kg/s", xidQm, this, isResult|isParmConstruct);
DDB.Double ("Vol_Flow", "Qv", DC_Qv, "L/s", xidQv, this, isResult|noFile|noSnap);
DDB.Double ("NVol_Flow", "NQv", DC_NQv, "NL/s", xidNQv, this, isResult|noFile|noSnap);
DDB.Double ("TemperatureIn","Ti", DC_T, "C", xidTempIn, this, isResult|noFile|noSnap);
DDB.Double ("TemperatureOut","To", DC_T, "C", xidTempOut, this, isResult|noFile|noSnap);
DDB.Double ("Temperature", "T", DC_T, "C", xidTemp, this, isResult|/*noView|*/noFile|noSnap|InitHidden);
DDB.Double ("Density", "Rho", DC_Rho, "kg/m^3", xidRho, this, isResult|noFile|noSnap);
DDB.Double ("NDensity", "NRho", DC_Rho, "kg/m^3", xidNRho, this, isResult|noFile|noSnap);
DDB.Visibility(NM_Dynamic|SM_All|HM_All, !IsXfer);
if (NetDynamicMethod())
DDB.Double("Velocity", "Vel", DC_Ldt, "m/s", xidVelocity, this, isResult|noFile|noSnap);
//if (1 && (NoFlwIOs() > 1) && IOFlange(1))
// {
// DDB.Double ("ChkVel", "", DC_Ldt, "m/s", xidChokeVelocity, this, isResult|InitHidden|noFile|noSnap);
// }
if (NetProbalMethod())
{
DDB.Double ("Press_Input", "Pi", DC_P, "kPag", xidPIn, this, isResult);
DDB.Double ("Press_Output", "Po", DC_P, "kPag", xidPOut, this, isResult);
}
else
{
DDB.Visibility(NM_Dynamic|SM_All|HM_All, !IsXfer || dbgfile());
DDB.Text (" ");
if (NoFlwIOs()>0 && Nd_Rmt(0) && (IOPipeEntry_Rmt(0) || IOPipeJoin_Rmt(0)))
DDB.Double ("Flange_Press_In", "PiR", DC_P, "kPag", xidPInRmt, this, isResult|noFile|noSnap);
DDB.Double ("Press_InEst" , "PiEst", DC_P, "kPag", xidPInEst ,this, isResult|isParmConstruct|InitHidden);
DDB.Double ("Press_Input", "Pi", DC_P, "kPag", xidPIn, this, isResult);
DDB.Double ("Boost_Head", "dPb", DC_DP, "kPa", xidFEDPb, this, isResult|InitHidden|isParmConstruct);
DDB.TagComment("+");
DDB.Double ("", "dPbX", DC_DP, "kPa", xidFEDPbX, this, isResult|InitHidden|isParmConstruct);
DDB.TagComment("+");
DDB.Double ("Dynamic_Head", "dPq", DC_DP, "kPa", xidFEDPq, this, isResult|InitHidden|isParmConstruct);
DDB.TagComment("+");
DDB.Double ("Static_Head", "dPz", DC_DP, "kPa", xidFEDPz, this, isResult|InitHidden|isParmConstruct);
DDB.TagComment("+");
DDB.Double ("Press_Output", "Po", DC_P, "kPag", xidPOut, this, isResult);
DDB.TagComment("=");
DDB.Double ("Press_OutEst", "PoEst", DC_P, "kPag", xidPOutEst ,this, isResult|isParmConstruct|InitHidden);
if (NoFlwIOs()>1 && Nd_Rmt(1) && (IOPipeEntry_Rmt(1) || IOPipeJoin_Rmt(1)))
DDB.Double ("Flange_Press_Out","PoR", DC_P, "kPag", xidPOutRmt, this, isResult|noFile|noSnap);
DDB.Text (" ");
if (NoFlwIOs()>0 && Nd_Rmt(0) && (IOPipeEntry_Rmt(0) || IOPipeJoin_Rmt(0)))
DDB.Double ("Flange_DP_In", "DPiR", DC_DP, "kPa", xidDPInRmt, this, isResult|noFile|noSnap);
DDB.Double ("Press_Change", "dP", DC_DP, "kPa", xidDPRmt, this, isResult|noFile|noSnap);
if (NoFlwIOs()>1 && Nd_Rmt(1) && (IOPipeEntry_Rmt(1) || IOPipeJoin_Rmt(1)))
DDB.Double ("Flange_DP_Out","DPoR", DC_DP, "kPa", xidDPOutRmt, this, isResult|noFile|noSnap);
DDB.Visibility(NM_Dynamic|SM_All|HM_All);
DDB.Double ("Ave_Mass_Flow","QmAv", DC_Qm, "kg/s", xidIO_QmAvail, this, isResult|0|InitHidden);
DDB.Double ("", "QmSp", DC_Qm, "kg/s", xidIO_QmSpace, this, isResult|0|InitHidden);
//DDB.Text (" ");
//if (NoFlwIOs()>0 && Nd_Rmt(0) && IOPipeEntry_Rmt(0))
// DDB.Double ("Flange_DP_In", "DPiR", DC_DP, "kPa", xidDPInRmt, this, isResult|noFile|noSnap);
//DDB.Double ("Press_Change", "dP", DC_DP, "kPa", xidDPRmt, this, isResult|noFile|noSnap);
//if (NoFlwIOs()>1 && IOPipeEntry_Rmt(1))
// DDB.Double ("Flange_DP_Out","DPoR", DC_DP, "kPa", xidDPOutRmt, this, isResult|noFile|noSnap);
}
if (!NetProbalMethod() && !HeatSkipMethod())
{
DDB.Visibility(NM_Dynamic|SM_All|HM_All);
DDB.Text (" ");
if (NoFlwIOs()>0 && Nd_Rmt(0) && (IOPipeEntry_Rmt(0) || IOPipeJoin_Rmt(0)))
DDB.Double ("", "Hz@TiR", DC_HMs, "kJ/kg", xidHzInRmt, this, isResult|noFile|noSnap);
DDB.Double ("", "Hz@Ti", DC_HMs, "kJ/kg", xidHzIn, this, isResult|noFile|noSnap);
DDB.Double ("", "Hz@To", DC_HMs, "kJ/kg", xidHzOut, this, isResult|noFile|noSnap);
if (NoFlwIOs()>1 && Nd_Rmt(1) && (IOPipeEntry_Rmt(1) || IOPipeJoin_Rmt(1)))
DDB.Double ("", "Hz@ToR", DC_HMs, "kJ/kg", xidHzOutRmt, this, isResult|noFile|noSnap);
DDB.Text (" ");
if (NoFlwIOs()>0 && Nd_Rmt(0) && (IOPipeEntry_Rmt(0) || IOPipeJoin_Rmt(0)))
DDB.Double ("", "totHz@TiR", DC_Pwr, "kJ/s", xidtotHzInRmt, this, isResult|noFile|noSnap);
DDB.Double ("", "totHz@Ti", DC_Pwr, "kJ/s", xidtotHzIn, this, isResult|noFile|noSnap);
DDB.Double ("", "totHz@To", DC_Pwr, "kJ/s", xidtotHzOut, this, isResult|noFile|noSnap);
if (NoFlwIOs()>1 && Nd_Rmt(1) && (IOPipeEntry_Rmt(1) || IOPipeJoin_Rmt(1)))
DDB.Double ("", "totHz@ToR", DC_Pwr, "kJ/s", xidtotHzOutRmt, this, isResult|noFile|noSnap);
}
DDB.Visibility();
DDB.Text ("Connections", Marker);
DDB.String ("Link_Source", "SrcIO", DC_, "", xidSrcIOTag, this, isTag|noFile|noSnap);
DDB.String ("Link_Destination", "DstIO", DC_, "", xidDstIOTag, this, isTag|noFile|noSnap);
DDB.String ("", "SrcFlange", DC_, "", xidSrcFlangeTag, this, isTag|noFile|noSnap|InitHidden);
DDB.String ("", "DstFlange", DC_, "", xidDstFlangeTag, this, isTag|noFile|noSnap|InitHidden);
DDB.Visibility(NSHM_All);
//Strng Page;
//Page.Set("%s..", Tag());
//DDB.Page(Page(), NetProbalMethod() ? DDB_OptPage : DDB_RqdPage);
if (NetProbalMethod())
{
//DDB.Page("..", DDB_OptPage);
DDB.Text (StdSepUnderbar);
}
else
{
DDB.Page("..", DDB_RqdPage);
}
DDB.Text ("Requirements:");
//DDB.Text ("");
//DDB.Text ("Results: Flow Conditions");
DDB.CheckBoxBtn("Simplify", "", DC_, "", &m_bSimplify, this, isParmStopped|AffectsStruct);
if (DDB.ForView() && m_bSimplify)// && NoIOs()>0)
{
if (m_pSimplifyNote)
DDB.TagComment((LPSTR)m_pSimplifyNote);
//if (!m_bSimplified)
// DDB.TagComment("Inactive-Config");
else if (!IOFlange(0)->RedirectOK())
DDB.TagComment("Tear-Exists");
}
cioOn.BuildDataDefn(this, "Flow", DDB);
DDB.CheckBoxBtn ("Show.Qi", "", DC_, "", &m_bShowQi, this, isParm|SetOnChange);
DDB.Text ("");
if (!NetProbalMethod())
{
//DDB.Text ("");
if (IsXfer || !DDB.ForFileSnpScn() || PrjFileVerNo()<40)
{
DDB.Visibility(NM_Dynamic|SM_All|HM_All, !IsSrcSnk && IsXfer);
m_FEP.BuildDataDefn(FBDDOpt_WithQmSpec, DDB, this, "Flw", 3, DDB_NoPage);
}
static DDBValueLst DDBXfCapOpt[]={
{XCO_Spill, "Spill" },
{XCO_Accept, "Accept" },
{0}};
DDB.Byte ("OverCapacity", "", DC_, "", &m_iXferCapOption, this, isParm|SetOnChange, DDBXfCapOpt);
}
DDB.Visibility(NM_Dynamic|SM_All|HM_All);
if (FullFlowMode())//SolveBufferedMethod())// PipeFlowMode())
{
DDB.Text("Flow Options");
DDB.Visibility(NM_Dynamic|SM_All|HM_All, !IsSrcSnk && (!IsXfer/* || dbgfile()*/));
static DDBValueLst DDBPhasesR[]=
{
{FPh_Liquid, "Liquids" },
{FPh_Gasses, "Gasses" },
{FPh_Both, "Both" },
{0}
};
static DDBValueLst DDBPhasesA[]=
{
{FPh_Liquid, "Liquids" },
{FPh_Gasses, "Gasses" },
{FPh_Both, "Both" },
{FPh_UnKnown, "Unknown" },
{FPh_None, "None" },
{0}
};
DDB.Byte ("NetFlow.Allow", "", DC_, "", xidFlwPhaseRqd, this, isParm|SetOnChange, DDBPhasesR);
DDB.Byte ("NetFlow.Actual", "", DC_, "", xidFlwPhaseAct, this, 0, DDBPhasesA);
Strng S;
if (CFlwBlkData::sm_iFlwPh_Force)
S="Frc";
if (CFlwBlkData::sm_iFlwPh_Block)
S+=S.GetLength()>0?".Blk":"Blk";
if (S.GetLength())
DDB.TagComment(S());
static DDBValueLst DDB1[]={
{FBPS_Default, "Default"},
{FBPS_FwdOnly, "Forward"},
{FBPS_RevOnly, "Reverse"},
{FBPS_FwdOnly|FBPS_Inherit, "(Forward)"},
{FBPS_RevOnly|FBPS_Inherit, "(Reverse)"},
{FBPS_Default|FBPS_Inherit, "(Default)"},
{0}};
DDB.Byte("PropSelect", "", DC_, "", xidPropertySelect, this, isParm, DDB1);
// DDBValueLst DDBFill[]={
// {LFM_None, "None"},
// {LFM_Simple, "Simple"},
// {0}};
// DDB.Byte ("FillMode", "", DC_, "", &iFillMode, this, isParm, DDBFill);
#if WITHMULTIFLWBLK
DDB.CheckBoxBtn("MultiFlwBlk", "", DC_, "", xidMFBOn, this, isParm);
#endif
#if WITHTWOPHASE
DDB.CheckBoxBtn("TwoPhaseFlw", "", DC_, "", &fTwoPhase, this, isParm);
#endif
#if 0 /*JHGJ*/
DDB.CheckBox ("IsDegFreedom", "", DC_, "", &fIsDegFree, this, isParm|SetOnChange|InitHidden);
#endif
DDB.CheckBox ("ApplyRhoH", "", DC_, "", &fAppRhoH, this, isParm|SetOnChange);
DDB.CheckBox ("FindEquilRhoH", "", DC_, "", &fFindRhoH, this, isParm|SetOnChange);
DDB.CheckBoxBtn("OrificePlate", "", DC_, "", xidWithOP, this, isParmStopped|SetOnChange);
}
#if WITHPLUGFLOW
static DDBValueLst DDBVFX[]={
{VFFX_Off, "Off"},
{VFFX_PreMix, "PreMix"},
{VFFX_PostMix, "PostMix"},
{VFFX_Plugflow, "PlugFlow"},
{0}};
static DDBValueLst DDBPFT[]={
{PFT_Incompressible, "Incompressible" },
{PFT_Compressible, "Compressible" },
//{PFT_Mixed, "Mixed" },
{0}};
if (PrjFileVerNo()>=59)
{
DDB.Byte ("VolFlwFX", "", DC_, "", xidVolFlwFX, this, isParmStopped|SetOnChange, DDBVFX);
if (m_PFI.Method == VFFX_Plugflow)
{
DDB.Byte ("PlugFlowType", "", DC_, "", xidPlugFlowType, this, isParmStopped|SetOnChange, DDBPFT);
if (m_PFI.Type != PFT_Incompressible)
{
DDB.Long ("NoSections", "", DC_, "", xidPlugFlowSects, this, isParmStopped);
}
}
}
else
DDB.CheckBoxBtn("Vol_FlwFX", "", DC_, "", xidVolFlwFX, this, isParm, DDBVFX);
DDB.CheckBoxBtn("Vol_PresFX", "", DC_, "", xidVolPrsFX, this, isParm|InitHidden);
DDB.CheckBoxBtn("VolIsSmall", "", DC_, "", &fVolIsSmall, this, isParm|InitHidden);
DDB.CheckBoxBtn("VapLocked", "", DC_, "", &fVapLocked, this, isParm|InitHidden);
#endif
DDB.Visibility();
if (!DDB.ForView() || !m_bSimplified)
m_BlkEval.Add_OnOff(DDB);
if (!NetProbalMethod())
{
DDB.Visibility(NM_Dynamic|SM_All|HM_All);
DDB.CheckBoxBtn("CollectStats", "", DC_, "", xidSI_On, this, isParmStopped);//|SetOnChange);
//TODO: Check: is iLF_Direction only used in dynamic!?!
DDB.Visibility(NM_Dynamic|SM_All|HM_All);//SM_Direct|HM_All);
DDB.Text("Flow Configuration");
static DDBValueLst DDB1[]={
{LFD_Default, "Default"},
{LFD_Forward, "Forward"},
{LFD_Reverse, "Reverse"},
{0}};
DDB.Byte ("Direction", "", DC_, "", &m_iLF_Direction, this, isParm, DDB1);
}
if (NetProbalMethod())
{
DDB.Visibility(NM_Probal|SM_All|HM_All);
DDB.Text ("MakeUp");
//DDB.Double ("Qm_MakeUp.Dst", "", DC_Qm, "kg/s", xidIO_MkUpAvail1, this, isResult|InitHidden|NAN_OK);
DDB.Double ("Qm_MakeUp.Dst", "", DC_Qm, "kg/s", xidIO_MkUpReqd1, this, isResult|NAN_OK);
DDB.Double ("Qm_MakeUp", "", DC_Qm, "kg/s", &m_dMkUpRqd, this, isParm|NAN_OK);
DDB.Double ("Qm_MakeUp.Src", "", DC_Qm, "kg/s", xidIO_MkUpReqd0, this, isResult|NAN_OK);
DDB.Double ("Qm_Avail.Src", "", DC_Qm, "kg/s", xidIO_MkUpAvail0, this, isResult|InitHidden|NAN_OK);
DDB.Text ("");
}
DDB.Visibility();
if (DDB.BeginStruct(this, "Tear", NULL, DDB_NoPage, -1, 0/*MarkerClosed*/))
{
static DDBValueLst DDBTearPri[]=
{
{TP_First, "First"},
{TP_Normal, "Normal"},
{TP_Last, "Last"},
{0}
};
static DDBValueLst DDBTearTypeRqd[]=
{
{TT_NoTear, "NoTear"},
//{TT_SystemTear, "SystemTear"}, // Cannot Select this
{TT_ManualTear, "ManualTear"},
{TT_Break, "Break"},
{0}
};
static DDBValueLst DDBTearState[]=
{
{TT_NoTear, "NoTear"},
{TT_SystemTear, "SystemTear"},
{TT_ManualTear, "ManualTear"},
{TT_Break, "Break"},
{0}
};
//static DDBValueLst DDBHow[]=
// {
// {TIH_ZeroNIters, "Zero" },
// {TIH_HoldNIters, "Hold" },
// {TIH_RampNIters, "Ramp" },
// {0}
// };
//static DDBValueLst DDBWhen[]=
// {
// {TIW_OnInit, "OnInitialise", MDD_Default },
// {TIW_OnStart, "OnStart" },
// //{TIW_Always, "Always" },
// {TIW_Manual, "OnDemand" },
// {0}
// };
//static DDBValueLst DDBInitQmMode[] =
// {
// //{ SPI_QModeNone, "None" },
// { SPI_QModeQm, "Mass" },
// { SPI_QModeQv, "Volume" },
// { SPI_QModeNQv, "NVolume" },
// };
//static DDBValueLst DDBInitEstUsage[]=
// {
// //{TIEU_None, "None"},
// {TIEU_FullEst, "Full"},
// {TIEU_PartEst, "Partial"},
// {0},
// };
//static DDBValueLst DDBInitState[]=
// {
// {TIH_Off, "Off" },
// {TIH_ZeroNIters, "Zeroing" },
// {TIH_HoldNIters, "Holding" },
// {TIH_RampNIters, "Ramping" },
// //{TIH_ZeroNIters, "WillZero" },
// //{TIH_HoldNIters, "WillHold" },
// //{TIH_RampNIters, "WillRamp" },
// //{TIH_Zeroing, "Zeroing" },
// //{TIH_Holding, "Holding" },
// //{TIH_Ramping, "Ramping" },
// {0},
// };
DDEF_Flags B4TearVis=DDB.GetVisibility();
DDB.Byte ("Priority", "", DC_, "", xidTearPriority, this, isParm|SetOnChange, DDBTearPri);
DDB.Byte ("RqdType", "", DC_, "", xidTearType, this, isParm|SetOnChange, DDBTearTypeRqd);
DDB.Byte ("State", "", DC_, "", xidTearState, this, 0, DDBTearState);
DDB.String ("Flange", "", DC_, "", xidTearFlangeTag, this, 0|isTag);
if (NoFlwIOs()>1 && IOFlange(0)->IsTear())
DDB.String ("TearBlock", "", DC_, "", xidTearBlockTag, this, 0|isTag);
//bool TearVis=(NoFlwIOs()>1 && IOFlange(0)->RqdTearType()>=TT_ManualTear);
//DDB.Visibility(NSHM_All, TearVis);
//if (PrjFileVerNo()>=78)
// {
// if (DDB.BeginStruct(this, "Init", NULL, DDB_NoPage))
// {
// DDB.Byte ("How", "", DC_, "", xidTearInitHow, this, isParmStopped|SetOnChange, DDBHow);
// DDB.Byte ("When", "", DC_, "", xidTearInitWhen, this, isParmStopped|SetOnChange, DDBWhen);
// static DDBValueLst DDBStart[] = {{0, "Start"}, {1, "Busy"}, {0}};
// DDB.Button ("Start", "", DC_, "", xidTearInitActivate, this, isParm|SetOnChange);//, DDBStart);
// bool HoldCntVis=true;
// DDB.Visibility(NSHM_All, TearVis && HoldCntVis);
// DDB.Byte ("Count", "", DC_, "", xidTearCntRqd, this, isParmStopped);
// DDB.Byte ("Iters", "", DC_, "", xidTearCntAct, this, InitHidden);
// DDB.Visibility(NSHM_All, TearVis);
// DDB.Byte ("State", "", DC_, "", xidTearInitActive, this, 0, DDBInitState);
// SpImgMode Md=SPI_QModeNone;
// DDBValueLstMem DDBInitQmModeX;
// //DDBInitQmModeX.Add(SPI_QModeNone, "None");
// DDBInitQmModeX.Add(SPI_QModeQm, "Mass");
// if (NoProcessIOs()>0 && IOFlange(0) && IOFlange(0)->TearImage())
// {
// Md=IOFlange(0)->TearImage()->QMode();
// SpImage &Img=*IOFlange(0)->TearImage();
// if (Img.SpVarsAvail() & VAMsk_SpVol)
// DDBInitQmModeX.Add(SPI_QModeQv, "Volume");
// if (Img.SpVarsAvail() & VAMsk_SpNVol)
// DDBInitQmModeX.Add(SPI_QModeNQv, "NVolume");
// }
// DDB.Visibility(NSHM_All, TearVis);
// DDB.Double ("T_Rqd", "", DC_T, "C", xidTearTRqd, this, isParm |NAN_OK, DDBNAN_NotSpecd);
// DDB.Double ("P_Rqd", "", DC_P, "kPag", xidTearPRqd, this, isParm |NAN_OK, DDBNAN_NotSpecd);
// DDB.Byte ("Estimate.Usage","", DC_, "", xidTearInitEstUsage, this, isParmStopped|SetOnChange, DDBInitEstUsage);
// DDB.Byte ("Flow.Mode", "", DC_, "", xidTearQmMode, this, isParmStopped|SetOnChange, DDBInitQmModeX());
// DDB.Visibility(NSHM_All, TearVis && (Md!=SPI_QModeNone));
// DDB.Double ("Qm_Rqd", "", DC_Qm, "kg/s", xidTearQmRqd, this, (Md==SPI_QModeQm?isParm:isResult)|NAN_OK, DDBNAN_NotSpecd);
// DDB.Double ("Qv_Rqd", "", DC_Qv, "L/s", xidTearQvRqd, this, (Md==SPI_QModeQv?isParm:isResult)|NAN_OK, DDBNAN_NotSpecd);
// DDB.Double ("NQv_Rqd", "", DC_NQv, "NL/s", xidTearNQvRqd, this, (Md==SPI_QModeNQv?isParm:isResult)|NAN_OK, DDBNAN_NotSpecd);
// }
// DDB.EndStruct();
// }
//else
// {
// DDB.Byte ("Init.QmMode", "", DC_, "", xidTearQmMode, this, isParm|SetOnChange, DDBInitQmMode);
// DDB.Byte ("Init.How", "", DC_, "", xidTearInitHow, this, isParm|SetOnChange, DDBHow);
// DDB.Byte ("Init.When", "", DC_, "", xidTearInitWhen, this, isParm|SetOnChange, DDBWhen);
// DDB.Byte ("Init.Count", "", DC_, "", xidTearCntRqd, this, isParm);
// DDB.Byte ("Init.Iters", "", DC_, "", xidTearCntAct, this, InitHidden);
// DDB.CheckBoxBtn ("Init.Active", "", DC_, "", xidTearInitActive, this, isParm|SetOnChange);
// DDB.Double ("Qm_Rqd", "", DC_Qm, "kg/s", xidTearQmRqd, this, isParm|NAN_OK);
// DDB.Double ("Qv_Rqd", "", DC_Qv, "L/s", xidTearQvRqd, this, isParm|NAN_OK);
// DDB.Double ("NQv_Rqd", "", DC_NQv, "NL/s", xidTearNQvRqd, this, isParm|NAN_OK);
// DDB.Double ("P_Rqd", "", DC_P, "kPag", xidTearPRqd, this, isParm|NAN_OK);
// DDB.Double ("T_Rqd", "", DC_T, "C", xidTearTRqd, this, isParm|NAN_OK);
// }
DDB.Visibility(NM_Dynamic|SM_All|HM_All);
DDB.CheckBoxBtn ("AdjQmToEstQm", "", DC_, "", &m_bAdjustToEstFlow, this, isParm|SetOnChange);
DDB.SetVisibility(B4TearVis);
}
DDB.EndStruct();
if (IsPipe)//NetDynamicMethod() && IsSrcSnk)
{
DDB.Visibility(NM_Dynamic|SM_All|HM_All, NetDynamicMethod() && IsSrcSnk);
if (DDB.BeginStruct(this, "SrcSnk", NULL, DDB_NoPage, -1, 0))
{
DDB.Double("P_Rqd", "", DC_P, "kPag", &SrcSnk.dPress, this, isParm);
DDB.Double("T_Rqd", "", DC_T, "C", &SrcSnk.dTemp, this, isParm);
#if WITHSRCSNKDIFFS
DDB.Double("QmDiff", "", DC_Frac, "%", &SrcSnk.dQmDiff, this, 0);
DDB.Double("TempDiff", "", DC_Frac, "%", &SrcSnk.dTempDiff, this, 0);
#endif
DDB.CheckBoxBtn("KeepImage", "", DC_, "", xidKeepSrcSnk, this, isParm|InitHidden);
DDB.Button("CopyCurrent", "", DC_, "", xidCopyCurrent, this, isParm);
}
DDB.EndStruct();
}
#if WITHPBDPSTUFF
if (NetProbalMethod())
{
//DDB.Text("");
static DDBValueLst DDB2[]={
{LDP_Fixed_Drop, "Fixed_Drop"},
{LDP_Fixed_Boost, "Fixed_Boost"},
{LDP_Darcy_DP, "Darcy_DP"},
//{LDP_Linear_DP, "Linear_DP"},
//{LDP_SquareLaw_DP, "SquareLaw_DP"},
{LDP_Const_P, "Const_Src_P"},
//{LDP_BRC_DP, "BRC_DP"}, ////Bernoulli Rouse Corrected
{0}};
DDB.Visibility(NM_Probal|SM_All|HM_All);
DDB.Text("Pressure Drop Requirements");
DDB.Byte ("Press_Mode", "", DC_, "", &iDP_Mode, this, isParm|AffectsStruct|SetOnChange, DDB2);
DDB.Visibility(NM_Probal|SM_All|HM_All, iDP_Mode==LDP_Const_P);
DDB.Double("Lnk_P_Src", "", DC_P, "kPag", &LnkP_S, this, isParm);
DDB.Visibility(NM_Probal|SM_All|HM_All, iDP_Mode==LDP_Fixed_Drop || iDP_Mode==LDP_Fixed_Boost);
DDB.Double("Fxd_dP", "", DC_DP, "kPa", &FxddP, this, isParm);
DDB.Visibility(NM_Probal|SM_All|HM_All, iDP_Mode==LDP_Darcy_DP || iDP_Mode==LDP_BRC_DP);
DDB.Double("Diam", "", DC_L, "mm", &PipeD, this, isParm);
DDB.Double("ScaleBuildup", "", DC_L, "mm", &PipeScale, this, isParm);
DDB.Double("PipeDeltaZ", "", DC_L, "m", &PipeDeltaZ, this, isParm);
DDB.Visibility(NM_Probal|SM_All|HM_All, iDP_Mode==LDP_Darcy_DP);
static DDBValueLst DDB1P[]={
{(int)True, "Calc_K"},
{(int)False, "Define_K" },
{0}};
DDB.Bool ("K_Method", "", DC_, "", &iCalc_K, this, isParm|SetOnChange, DDB1P);
DDB.Visibility(NM_Probal|SM_All|HM_All, (iDP_Mode==LDP_Darcy_DP && iCalc_K) || iDP_Mode==LDP_BRC_DP);
if (SolveDirectMethod())
DDB.Double("Length", "L", DC_L, "m", &PipeL, this, isParm);
DDB.Double("FittingsLength", "FitL", DC_L, "m", &FitPipeL, this, isParm);
DDB.Visibility(NM_Probal|SM_All|HM_All, (iDP_Mode==LDP_Darcy_DP && iCalc_K));
static DDBValueLst DDB2P[]={
{(int)True, "Calc_f"},
{(int)False, "Define_f" },
{0}};
DDB.Bool ("f_Method", "", DC_, "", &iCalc_FFac, this, isParm, DDB2P);
DDB.Visibility(NM_Probal|SM_All|HM_All, iDP_Mode==LDP_Darcy_DP && iCalc_K && iCalc_FFac);
DDB.Double("Viscosity", "", DC_Visc,"cP", &Visc, this, isParm);
DDB.Double("Pipe_Rough","", DC_L, "mm", &Rough, this, isParm);
DDB.Double("ReynoldsNo", "Re", DC_, "", &Re, this, isResult);
DDB.Visibility(NM_Probal|SM_All|HM_All, (iDP_Mode==LDP_Darcy_DP && iCalc_K) || iDP_Mode==LDP_BRC_DP);
DDB.Double("FricFac", "", DC_, "", &FricFac, this, (iCalc_FFac && iDP_Mode!=LDP_BRC_DP) ? isResult : isParm);
DDB.Visibility(NM_Probal|SM_All|HM_All, iDP_Mode==LDP_Darcy_DP);
DDB.Double("K_Value", "", DC_, "", &K, this, iCalc_K ? isResult : isParm);
DDB.Double("K_MinorLosses", "", DC_, "", &KMinorLoss, this, isParm);
DDB.Visibility(NM_Probal|SM_All|HM_All, iDP_Mode==LDP_Darcy_DP || iDP_Mode==LDP_BRC_DP);
DDB.Double("Velocity", "Vel", DC_Ldt, "m/s", &Vel, this, isResult);
//DDB.Visibility(NM_Probal|SM_All|HM_All, iDP_Mode==LDP_Linear_DP || iDP_Mode==LDP_SquareLaw_DP);
//DDB.Double("S_MassFlw", "", DC_Qm, "kg/s", &SQmCap, this, isParm);
//DDB.Double("S_dP", "", DC_DP, "kPa", &SQmdP, this, isParm);
//DDB.Double("V_MassFlw", "", DC_Qm, "kg/s", &VQmCap, this, isParm);
//DDB.Double("V_dP", "", DC_DP, "kPa", &VQmdP, this, isParm);
DDB.Visibility(NM_Probal|SM_All|HM_All);
DDB.Double("Pdrop", "", DC_DP, "kPa", &PB_dp, this, isResult);
}
#endif
if (IsXfer)
{
DDB.Visibility(NM_Dynamic|SM_All|HM_All, !IsSrcSnk && (IsXfer || dbgfile()));
}
#ifdef OldCode
DDB.Visibility(NM_Dynamic|SM_All|HM_All, /*HasFullFlow() &&*/ !IsXfer);// || dbgfile());
DDB.Text ("Rise/Length", Marker);
if (NetDynamicMethod())
DDB.Double ("PipeLength", "", DC_L, "m", xidFELength, this, isResult|0|isParmConstruct);
DDB.Double ("SrcH", "SrcHgt", DC_L, "m", xidSrcHgt, this, isResult|noFile|noSnap);
DDB.Double ("DstH", "DstHgt", DC_L, "m", xidDstHgt, this, isResult|noFile|noSnap);
if (PrjFileVerNo()>=100)
DDB.Double ("Rise", "", DC_L, "m", xidFEDZ, this, isResult|0|isParmConstruct);
else
DDB.Double ("Rise", "dZ", DC_L, "m", xidFEDZ, this, isResult|0|isParmConstruct);
if (PrjFileVerNo()<100 && DDB.ForFileSnpScn())
DDB.Double ("", "dZ_Rqd", DC_L, "m", &m_RiseRqd, this, isParmStopped|NAN_OK);
else
{
DDB.Double ("RiseRqd", "", DC_L, "m", &m_RiseRqd, this, isParmStopped|NAN_OK);
DDB.Double ("DatumDiff", "", DC_L, "m", &m_DatumChg, this, isParmStopped|NAN_OK);
}
xx
#else
if (NetDynamicMethod())
{
DWORD LSOpts=PrjFileVerNo()<38 ? 0 : noFile|noSnap;
dword Flgs0=NoFlwIOs()>=1 ? IODesc_Rmt(0)->m_dwFlags : 0;
dword Flgs1=NoFlwIOs()>=2 ? IODesc_Rmt(1)->m_dwFlags : 0;
DDB.Visibility(NM_Dynamic|SM_All|HM_All);// || dbgfile());
DDB.Text ("End Points", Marker);
DDB.Double ("SrcHF", "SrcHFrc", DC_Frac, "%", xidSrcHFrc, this, ((Flgs0&IOChgFracHgt)?isParmStopped:0)|LSOpts);
DDB.Double ("DstHF", "DstHFrc", DC_Frac, "%", xidDstHFrc, this, ((Flgs1&IOChgFracHgt)?isParmStopped:0)|LSOpts);
DDB.Double ("SrcAperture", "", DC_Frac, "%", xidSrcAperture, this, (Flgs0&IOChgFracHgt&&SolveInlineMethod_Rmt(0)?0:noView)|LSOpts);
DDB.Double ("DstAperture", "", DC_Frac, "%", xidDstAperture, this, (Flgs1&IOChgFracHgt&&SolveInlineMethod_Rmt(1)?0:noView)|LSOpts);
DDB.Visibility(NM_Dynamic|SM_All|HM_All, HasModeNear(-1, LFM_Full) && !IsXfer);// || dbgfile());
DDB.Text ("Rise/Length", Marker);
DDB.Double ("SrcH", "SrcHgt", DC_L, "m", xidSrcHgt, this, isResult|noFile|noSnap);
DDB.Double ("DstH", "DstHgt", DC_L, "m", xidDstHgt, this, isResult|noFile|noSnap);
DDB.Double ("PipeLength", "", DC_L, "m", xidFELength, this, isResult|0|isParmConstruct);
//DDB.Double ("SrcHF", "SrcHFrc", DC_Frac, "%", xidSrcHFrc, this, ((Flgs0&IOChgFracHgt)?isParmStopped:0)|LSOpts);
//DDB.Double ("DstHF", "DstHFrc", DC_Frac, "%", xidDstHFrc, this, ((Flgs1&IOChgFracHgt)?isParmStopped:0)|LSOpts);
//DDB.Double ("SrcAperture", "", DC_Frac, "%", xidSrcAperture, this, (Flgs0&IOChgFracHgt&&SolveInlineMethod_Rmt(0)?0:noView)|LSOpts);
//DDB.Double ("DstAperture", "", DC_Frac, "%", xidDstAperture, this, (Flgs1&IOChgFracHgt&&SolveInlineMethod_Rmt(1)?0:noView)|LSOpts);
if (PrjFileVerNo()>=100)
DDB.Double ("Rise", "", DC_L, "m", xidFEDZ, this, isResult|0|isParmConstruct);
else
DDB.Double ("Rise", "dZ", DC_L, "m", xidFEDZ, this, isResult|0|isParmConstruct);
if (PrjFileVerNo()<100 && DDB.ForFileSnpScn())
DDB.Double ("", "dZ_Rqd", DC_L, "m", &m_RiseRqd, this, isParmStopped|NAN_OK);
else
{
DDB.Double ("RiseRqd", "", DC_L, "m", &m_RiseRqd, this, isParmStopped|NAN_OK);
DDB.Double ("DatumDiff", "", DC_L, "m", &m_DatumChg, this, isParmStopped|NAN_OK);
}
}
#endif
DDB.Visibility();
if (!NetProbalMethod())
{
//DDB.Visibility(NM_Dynamic|SM_All|HM_All);
DDB.Text("");
DDB.CheckBox ("FwdOnly","", DC_, "", &m_fFwdOnly, this, isParm|SetOnChange);
}
if (IsPipe)
{
DDB.Text("");
DDB.Visibility(NM_Dynamic|SM_All|HM_All, m_fFwdOnly);
DDB.Double ("UDFOpenP", "", DC_P, "kPa", xidUDFOpenP ,this, isParm);
DDB.Long ("UDFActionCount", "", DC_, "", xidUDFActCnt ,this, 0|InitHidden);
static DDBValueLst DDBUDF[]={
{0, ""},
{1, "Closed"},
{0}};
DDB.Bool ("UDFState", "", DC_, "", xidUDFState ,this, 0, DDBUDF);
DDB.Visibility(NSHM_All);
}
if (pStats && NetDynamicMethod())
{
pStats->BuildDataDefn(DDB, this);
}
DDB.Visibility(NSHM_All);
// DDB.CheckBox("MultiFlwBlk", "", DC_, "", &MFB.fOn, this, isParm|SetOnChange);
// ------------
//if (IsPipe)
if (IsPipe && !NetProbalMethod()) //kga 23/11/04 do we need all these tags in ProBal???
{
if (m_MFB.On())
{
DDB.Object(&m_MFB, this, "MFB", NULL, DDB_OptPage);
}
else
{
DDB.Visibility(NM_Dynamic|SM_All|HM_All, !IsXfer || dbgfile());
DDB.Page("Eqns", DDB_OptPage);
//DDB.Visibility(NM_Dynamic|SM_All|HM_All, !IsXfer || dbgfile()); //kga//hss 14/2/98
DDB.Visibility(NM_Dynamic|SM_All|HM_All, !IsXfer || dbgfile()); //kga//hss 14/2/98
int Do0=(NoFlwIOs()>0) && Nd_Rmt(0);
int Do1=(NoFlwIOs()>1) && Nd_Rmt(1);
DDBPages Pg=NetProbalMethod() ? DDB_OptPage : DDB_RqdPage;
if (!DDB.ForFileSnpScn())
{
//if (Do0 && IOPipeEntry_Rmt(0))
if (Do0 && (IOPipeEntry_Rmt(0) || IOPipeJoin_Rmt(0)))
{
IOFB_Rmt(0,0)->BuildDataDefn(FBDDOpt_WithEqn/*All*/, DDB, this, "Src", 1, Pg);
Pg=DDB_NoPage;
}
}
//if (!DDB.ForFileSnpScn() || PrjFileVerNo()<40)
//m_FEP.BuildDataDefn(FBDDOpt_WithEqn|FBDDOpt_WithDPSpec|(!IsXfer ? FBDDOpt_WithQmSpec:0), DDB, this, "Eqn", 3, Pg);
m_FEP.BuildDataDefn(FBDDOpt_WithEqn|FBDDOpt_WithDPSpec|FBDDOpt_WithQmSpec, DDB, this, "Eqn", 3, Pg);
if (m_bWithOP && NIOFBs(0)==2)
IOFB(0,1)->BuildDataDefn(FBDDOpt_WithEqn, DDB, this, "OP", 4, DDB_NoPage);
if (!DDB.ForFileSnpScn())
{
if (Do1 && (IOPipeEntry_Rmt(1) || IOPipeJoin_Rmt(1)))
IOFB_Rmt(1,0)->BuildDataDefn(FBDDOpt_WithEqn, DDB, this, "Dst", 2, DDB_NoPage);
}
}
}
DDB.Visibility();
if (!DDB.ForView() || !m_bSimplified)
m_BlkEval.BuildDataDefn(DDB);
DDB.Visibility(NM_Dynamic|SM_All|HM_All, (NetDynamicMethod() && IsSrcSnk) || DDB.ForFileSnpScn());
if (IsPipe)
{
if (SrcSnk.pImage)
DDB.Object(SrcSnk.pImage, this, "FlowsRqd", NULL, DDB_RqdPage);
#if WITHSRCSNKDIFFS
if (SrcSnk.pSpDiff)
DDB.Object(SrcSnk.pSpDiff, this, "FlowsDiff", NULL, DDB_RqdPage);
#endif
}
DDB.Visibility();
if (m_PFI.Method==VFFX_Plugflow)
{
DDB.Page("PlugFlow", DDB_RqdPage);
DDB.Long("SamplePtCount", "", DC_, "", xidSamplePtCount, this, isParmStopped|SetOnChange, "The Number of points at which Conditions or composition can be measured");
if (DDB.BeginArray(this, "SamplePos", "PFSamplePos", GetSamplePtCount()))
{
for (int i=0; i<GetSamplePtCount(); i++)
{
DDB.BeginElement(this, i, NULL);
DDB.Double("Position", "RPos", DC_Frac, "%", &m_SamplePt[i].m_dFracPos, this, isParmStopped, NULL, "The Position Relative to the 'Start' of the Pipe");
DDB.Double("Distance", "APos", DC_L, "m", &m_SamplePt[i].m_dAbsPos, this, 0, NULL, "The Distance from the 'Start' of the Pipe");
DDB.Double("Velocity", "Vel", DC_Ldt, "m/s", &m_SamplePt[i].m_dVel, this, 0, NULL, "The Velocity at this Position");
}
}
DDB.EndArray();
}
if (IsPipe && (NoFlwIOs()>=1) && IOFlange(0) &&
((IOFlange(0)->RqdTearType()>=TT_ManualTear) || (IOFlange(0)->TearImageExists())))
{
SpImage &Img=*IOFlange(0)->TearImage();
DDB.Visibility(NSHM_All, IOFlange(0)->RqdTearType()>=TT_ManualTear &&
IOFlange(0)->TearInitEstUsage()>TIEU_None);
static const BDDSpecies_Blk sbImageM[]= { {SVV_AsMassFlow, SVV_AsMassFrac, true, false, VAMsk_SpMass },
{SVV_AsMassFrac, SVV_AsMassFrac, true, true, VAMsk_SpMass }, };
static const BDDSpecies_Blk sbImageV[]= { {SVV_AsVolFlow, SVV_AsMassFrac, true, false, VAMsk_SpVol },
{SVV_AsMassFrac, SVV_AsMassFrac, true, true, VAMsk_SpMass }, };
static const BDDSpecies_Blk sbImageN[]= { {SVV_AsNVolFlow, SVV_AsMassFrac, true, false, VAMsk_SpNVol },
{SVV_AsMassFrac, SVV_AsMassFrac, true, true, VAMsk_SpMass }, };
//{SVV_AsRawMassFlow, SVV_AsRawMassFlow, true, false, true}
SpImgMode Md=SPI_QModeNone;
if (IOFlange(0)->TearImage())
Md=Img.QMode();
const BDDSpecies_Blk *pBlk=Img.pViewBlk;
int BlkSize=Img.iViewBlkSize;
switch (Md)
{
case SPI_QModeQv :
Img.pViewBlk=sbImageV;
Img.iViewBlkSize=sizeof(sbImageV);
break;
case SPI_QModeNQv :
Img.pViewBlk=sbImageN;
Img.iViewBlkSize=sizeof(sbImageN);
break;
default:
Img.pViewBlk=sbImageM;
Img.iViewBlkSize=sizeof(sbImageM);
break;
}
Img.SetTag("QEst");
DDB.Object(IOFlange(0)->TearImage(), this, "QEst", Nd_Rmt(0)->FullObjTag(), DDB_RqdPage);
Img.pViewBlk=pBlk;
Img.iViewBlkSize=BlkSize;
DDB.Visibility();
}
if ((NoFlwIOs() > 1) && IOFlange(0) && !IOFlange(0)->RedirectOK())
{
//if (IOConduitIn(0))
// {
// DDB.Visibility(NSHM_All);
// IOConduitIn(0)->SetTag("QiI");
// DDB.Object(IOConduitIn(0), this, "QiI", Nd_Rmt(1)->FullObjTag(), DDB_RqdPage);
// DDB.Visibility(NSHM_All);
// }
if (m_bShowQi || !DDB.ForView())
{
IOConduit(0)->SetTag("Qi");
DDB.Object(IOConduit(0), this, "Qi", Nd_Rmt(0)->FullObjTag(), DDB_RqdPage);
}
}
if (m_PFI.CnExists)
DDB.Object(&m_PFI.Cn, this, NULL/*PrjFileVerNo()<47?"Content":"Cn"*/, NULL, DDB_RqdPage, 100);
//if (m_PFI.PfExists)
// DDB.Object(&m_PFI.Pf, this, NULL/*PrjFileVerNo()<47?"Content":"Cn"*/, NULL, DDB_RqdPage, 200);
if (m_PFI.Method==VFFX_Plugflow)
{
if (DDB.BeginArray(this, "SamplePt", "PFSamplePt", GetSamplePtCount()))
{
for (int i=0; i<GetSamplePtCount(); i++)
{
DDB.BeginElement(this, i, NULL);//, lPlugFlowCdUI+i);
//m_SamplePt[i].m_dCnd->Tag("QoI");
DDB.Object(m_SamplePt[i].m_pCnd, this, "Sp", NULL, DDB_RqdPage);
}
}
DDB.EndArray();
}
if (NoFlwIOs() >= 2)
{
IOConduit(1)->SetTag("Qo");
DDB.Object(IOConduit(1), this, "Qo", Nd_Rmt(1)->FullObjTag(), DDB_RqdPage);
//if (IOConduitIn(1))
// {
// DDB.Visibility(NSHM_All);
// IOConduitIn(1)->SetTag("QoI");
// DDB.Object(IOConduitIn(1), this, "QoI", Nd_Rmt(1)->FullObjTag(), DDB_RqdPage);
// DDB.Visibility(NSHM_All);
// }
}
DDB.Visibility();
DDB.Text("");
m_FTB.BuildDataDefn(DDB, "Thermal", NULL, DDB_RqdPage, /*FEOF_WithAutoComp|*/FEOF_WithPVConst);
//BuildDataDefnAreaIOs(DDB);
if (DDB.ForFileSnpScn() && NetDynamicMethod())
{
if (!m_pLastFlw)
m_pLastFlw=new SpConduit("LastFlw", this, TOA_Embedded);
DDB.Object(m_pLastFlw, this, "LastFlw", NULL, DDB_OptPage, 250);
}
DDB.EndStruct();
}
// --------------------------------------------------------------------------
flag Pipe::DataXchg(DataChangeBlk & DCB)
{
if (DCB.dwUserInfo==3 && m_FEP.DataXchg(DCB))
return true;
if (NoFlwIOs()>=2 && DCB.dwUserInfo==4 && IOFB(0,1)->DataXchg(DCB))
return true;
if (NoFlwIOs()>=1 && DCB.dwUserInfo==1 && IOFB_Rmt(0,0)->DataXchg(DCB))
return 1;
if (NoFlwIOs()>=2 && DCB.dwUserInfo==2 && IOFB_Rmt(1,0)->DataXchg(DCB))
return 1;
if (MN_Lnk::DataXchg(DCB))
return 1;
if (m_BlkEval.DataXchg(DCB))
return 1;
if (m_RB.DataXchg(DCB))
return 1;
return 0;
}
// --------------------------------------------------------------------------
flag Pipe::ValidateData(ValidateDataBlk & VDB)
{
//if (m_PFI.Method==VFFX_Plugflow)
// {
// LogNote(FullObjTag(), 0, "Discrete Effects not implemented");
// m_PFI.Method=VFFX_PostMix;
// }
flag OK=MN_Lnk::ValidateData(VDB);
if (!m_RB.ValidateData(VDB))
OK=False;
return OK;
}
//--------------------------------------------------------------------------
void Pipe::PostConnect(int IONo)
{
MN_Lnk::PostConnect(IONo);
}
//---------------------------------------------------------------------------
void Pipe::PreDisConnect(int IONo)
{
MN_Lnk::PreDisConnect(IONo);
}
//==========================================================================
| [
"[email protected]",
"[email protected]",
"[email protected]"
] | [
[
[
1,
11
],
[
13,
18
],
[
21,
146
],
[
148,
152
],
[
154,
168
],
[
171,
171
],
[
173,
176
],
[
178,
181
],
[
183,
183
],
[
185,
189
],
[
194,
195
],
[
197,
198
],
[
203,
213
],
[
216,
222
],
[
229,
229
],
[
231,
231
],
[
233,
234
],
[
246,
246
],
[
248,
250
],
[
252,
253
],
[
255,
256
],
[
258,
268
],
[
288,
288
],
[
309,
309
],
[
325,
325
],
[
347,
348
],
[
350,
390
],
[
394,
394
],
[
396,
397
],
[
407,
436
],
[
438,
439
],
[
445,
445
],
[
447,
448
],
[
450,
458
],
[
472,
472
],
[
474,
474
],
[
485,
485
],
[
613,
613
],
[
618,
619
],
[
621,
621
],
[
627,
627
],
[
630,
630
],
[
634,
637
],
[
690,
691
],
[
697,
697
],
[
701,
704
],
[
706,
707
],
[
710,
710
],
[
764,
764
],
[
771,
773
],
[
776,
782
],
[
784,
784
],
[
786,
788
],
[
791,
794
],
[
796,
802
],
[
804,
805
],
[
815,
815
],
[
818,
819
],
[
826,
826
],
[
829,
833
],
[
837,
837
],
[
839,
870
],
[
872,
872
],
[
880,
900
],
[
902,
907
],
[
909,
909
],
[
922,
944
],
[
946,
946
],
[
954,
957
],
[
959,
959
],
[
961,
961
],
[
963,
984
],
[
988,
1022
]
],
[
[
12,
12
],
[
19,
20
],
[
147,
147
],
[
153,
153
],
[
169,
170
],
[
172,
172
],
[
177,
177
],
[
182,
182
],
[
184,
184
],
[
190,
193
],
[
196,
196
],
[
199,
199
],
[
214,
215
],
[
230,
230
],
[
232,
232
],
[
235,
245
],
[
247,
247
],
[
251,
251
],
[
254,
254
],
[
257,
257
],
[
273,
273
],
[
277,
277
],
[
281,
281
],
[
285,
285
],
[
289,
308
],
[
310,
324
],
[
326,
346
],
[
349,
349
],
[
391,
393
],
[
395,
395
],
[
398,
406
],
[
437,
437
],
[
440,
444
],
[
446,
446
],
[
449,
449
],
[
459,
471
],
[
473,
473
],
[
475,
484
],
[
486,
612
],
[
614,
617
],
[
620,
620
],
[
622,
626
],
[
628,
629
],
[
631,
633
],
[
651,
651
],
[
705,
705
],
[
709,
709
],
[
711,
725
],
[
730,
743
],
[
745,
749
],
[
763,
763
],
[
767,
768
],
[
774,
775
],
[
783,
783
],
[
785,
785
],
[
790,
790
],
[
795,
795
],
[
803,
803
],
[
806,
814
],
[
816,
817
],
[
820,
825
],
[
827,
828
],
[
834,
836
],
[
838,
838
],
[
871,
871
],
[
873,
879
],
[
901,
901
],
[
908,
908
],
[
910,
921
],
[
945,
945
],
[
947,
953
],
[
958,
958
],
[
960,
960
],
[
962,
962
],
[
985,
987
]
],
[
[
200,
202
],
[
223,
228
],
[
269,
272
],
[
274,
276
],
[
278,
280
],
[
282,
284
],
[
286,
287
],
[
638,
650
],
[
652,
689
],
[
692,
696
],
[
698,
700
],
[
708,
708
],
[
726,
729
],
[
744,
744
],
[
750,
762
],
[
765,
766
],
[
769,
770
],
[
789,
789
]
]
] |
f78cc7b4ebd8fba046b2a67acb3535c45feaa1ce | 82b701b31535e1d75bbf955a2f610a268921b20e | /New/Na3D/Na3D/SqPlus/sqplus/sqplus.h | 54eb813d28769cd0693e60f9289a631d6ab78de7 | [] | no_license | huytd/nagine3d | f62000f355b3d70c3a4b0a0a5245cfcb248d990d | fb662fed184e409b10c7e572c34224b6ca9cf557 | refs/heads/master | 2021-01-23T19:38:39.286927 | 2009-10-28T04:00:29 | 2009-10-28T04:00:29 | 38,933,923 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 82,513 | h | // SqPlus.h
// Created by John Schultz 9/05/05, major update 10/05/05.
// Template function call design from LuaPlusCD by Joshua C. Jensen,
// inspired by luabind which was inspired by boost::python.
// Const argument, const member functions, and Mac OS-X changes by Simon Michelmore.
// DECLARE_INSTANCE_TYPE_NAME changes by Ben (Project5) from http://www.squirrel-lang.org/forums/.
// Added Kamaitati's changes 5/28/06.
// Free for any use.
#ifndef _SQ_PLUS_H_
#define _SQ_PLUS_H_
#include <stdlib.h>
#ifdef __APPLE__
#include <malloc/malloc.h>
#else
#include <malloc.h>
#endif
#include <memory.h>
#if defined(_MSC_VER) || defined(__BORLANDC__)
#include <tchar.h>
#ifndef UNICODE
#define SCSNPRINTF _snprintf
#define SCPUTS puts
#else
#define SCSNPRINTF _snwprintf
#define SCPUTS _putws
#endif
#else
#define _T(n) n
#define SCSNPRINTF snprintf
#include <stdio.h> // for snprintf
#define SCPUTS puts
#endif
#ifndef _WINDEF_
typedef int BOOL;
typedef int INT;
typedef float FLOAT;
#define TRUE 1
#define FALSE 0
#endif
#if 1
#define SQ_CALL_RAISE_ERROR SQTrue
#else
#define SQ_CALL_RAISE_ERROR SQFalse
#endif
#include "squirrel.h"
#include "SquirrelObject.h"
#include "SquirrelVM.h"
#include "SquirrelBindingsUtils.h"
namespace SqPlus {
// === Class Inheritance Support ===
// Inheritance in Squirrel allows one class to inherit a base class's functions and variables.
// Variables are merged: if Derived has a var name 'val' and Base has a var of the same name,
// the resulting var 'val' will take Derived's initialization value.
// Functions are not merged, and can be called via Squirrel scoping rules.
// Define SQ_USE_CLASS_INHERITANCE to enable class inheritance support
// (requires slightly more memory and adds some CPU overhead).
// Can also be useful for debugging, as class type information is checked before
// dispatching instance function calls and before accessing instance member variables.
#define SQ_USE_CLASS_INHERITANCE
// Comment out to turn off instance type info support (to save a small amount of memory).
#define SQ_SUPPORT_INSTANCE_TYPE_INFO
// === Constant argument and constant member function support ===
// Define SQPLUS_CONST_OPT before including SqPlus.h for constant argument + constant member function support.
//#define SQPLUS_CONST_OPT
// === Uncomment to support std::string ===
//#define SQPLUS_SUPPORT_STD_STRING
// === Uncomment to support typedef std::basic_string<SQChar> sq_std_string ===
//#define SQPLUS_SUPPORT_SQ_STD_STRING
// === Uncomment to support NULL INSTANCE arguments ===
//#define SQPLUS_SUPPORT_NULL_INSTANCES
// === Uncomment to support C++ style inheritance
#define CPP_STYLE_INHERITANCE
// === Uncomment to skip sq_argassert() ===
//#define SQ_SKIP_ARG_ASSERT
template<class T> struct TypeWrapper {};
struct SquirrelNull {};
struct SQAnything { void * anything; }; // Needed for binding pointers to variables (cannot dereference void *).
typedef SQAnything * SQAnythingPtr;
typedef SQChar * SQCharPtr;
// === Do not use directly: use one of the predefined sizes below ===
struct ScriptStringVarBase {
const unsigned char MaxLength; // Real length is MaxLength+1.
SQChar s[1];
ScriptStringVarBase(int _MaxLength) : MaxLength(_MaxLength) {}
operator SQChar * () { return &s[0]; }
operator void * () { return (void *)&s[0]; }
const SQChar * operator = (const SQChar * _s) {
return safeStringCopy(s,_s,MaxLength);
}
// Special safe string copy where MaxLength is 1 less than true buffer length.
// strncpy() pads out nulls for the full length of the buffer specified by MaxLength.
static inline SQChar * safeStringCopy(SQChar * d,const SQChar * s,int MaxLength) {
int i=0;
while (s[i]) {
d[i] = s[i];
i++;
if (i == MaxLength) break;
} // while
d[i] = 0; // Null terminate.
return d;
} // safeStringCopy
};
// === Do not use directly: use one of the predefined sizes below ===
template<int MAXLENGTH> // MAXLENGTH is max printable characters (trailing NULL is accounted for in ScriptStringVarBase::s[1]).
struct ScriptStringVar : ScriptStringVarBase {
SQChar ps[MAXLENGTH];
ScriptStringVar() : ScriptStringVarBase(MAXLENGTH) {
s[0] = 0;
}
ScriptStringVar(const SQChar * _s) : ScriptStringVarBase(MAXLENGTH) {
*this = _s;
}
const SQChar * operator = (const SQChar * _s) {
return safeStringCopy(s,_s,MaxLength);
}
const SQChar * operator = (const ScriptStringVar & _s) {
return safeStringCopy(s,_s.s,MaxLength);
}
bool operator == (const ScriptStringVar & _s) {
return _strcmp(s,_s.s) == 0;
}
bool compareCaseInsensitive(const ScriptStringVar & _s) {
return _stricmp(s,_s.s) == 0;
}
};
// === Fixed size strings for scripting ===
typedef ScriptStringVar<8> ScriptStringVar8;
typedef ScriptStringVar<16> ScriptStringVar16;
typedef ScriptStringVar<32> ScriptStringVar32;
typedef ScriptStringVar<64> ScriptStringVar64;
typedef ScriptStringVar<128> ScriptStringVar128;
typedef ScriptStringVar<256> ScriptStringVar256;
// === Script Variable Types ===
enum ScriptVarType {VAR_TYPE_NONE=-1,VAR_TYPE_INT=0,VAR_TYPE_FLOAT,VAR_TYPE_BOOL,VAR_TYPE_CONST_STRING,VAR_TYPE_STRING,VAR_TYPE_USER_POINTER,VAR_TYPE_INSTANCE};
template <typename T>
struct TypeInfo {
const SQChar * typeName;
enum {TypeID=VAR_TYPE_NONE,Size=0};
};
// === Common Variable Types ===
template<>
struct TypeInfo<INT> {
const SQChar * typeName;
TypeInfo() : typeName(_T("int")) {}
enum {TypeID=VAR_TYPE_INT,Size=sizeof(INT)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<FLOAT> {
const SQChar * typeName;
TypeInfo() : typeName(_T("float")) {}
enum {TypeID=VAR_TYPE_FLOAT,Size=sizeof(FLOAT)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<bool> {
const SQChar * typeName;
TypeInfo() : typeName(_T("bool")) {}
enum {TypeID=VAR_TYPE_BOOL,Size=sizeof(bool)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<SQUserPointer> {
const SQChar * typeName;
TypeInfo() : typeName(_T("SQUserPointer")) {}
enum {TypeID=VAR_TYPE_USER_POINTER,Size=sizeof(SQUserPointer)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<SQAnything> {
const SQChar * typeName;
TypeInfo() : typeName(_T("SQUserPointer")) {}
enum {TypeID=VAR_TYPE_USER_POINTER,Size=sizeof(SQUserPointer)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<const SQChar *> {
const SQChar * typeName;
TypeInfo() : typeName(_T("const SQChar *")) {}
enum {TypeID=VAR_TYPE_CONST_STRING,Size=sizeof(const SQChar *)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<ScriptStringVarBase> {
const SQChar * typeName;
TypeInfo() : typeName(_T("ScriptStringVarBase")) {}
enum {TypeID=VAR_TYPE_STRING,Size=sizeof(ScriptStringVarBase)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
// === Fixed String Variants ===
template<>
struct TypeInfo<ScriptStringVar8> {
const SQChar * typeName;
TypeInfo() : typeName(_T("ScriptStringVar8")) {}
enum {TypeID=VAR_TYPE_STRING,Size=sizeof(ScriptStringVar8)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<ScriptStringVar16> {
const SQChar * typeName;
TypeInfo() : typeName(_T("ScriptStringVar16")) {}
enum {TypeID=VAR_TYPE_STRING,Size=sizeof(ScriptStringVar16)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<ScriptStringVar32> {
const SQChar * typeName;
TypeInfo() : typeName(_T("ScriptStringVar32")) {}
enum {TypeID=VAR_TYPE_STRING,Size=sizeof(ScriptStringVar32)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<ScriptStringVar64> {
const SQChar * typeName;
TypeInfo() : typeName(_T("ScriptStringVar64")) {}
enum {TypeID=VAR_TYPE_STRING,Size=sizeof(ScriptStringVar64)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<ScriptStringVar128> {
const SQChar * typeName;
TypeInfo() : typeName(_T("ScriptStringVar128")) {}
enum {TypeID=VAR_TYPE_STRING,Size=sizeof(ScriptStringVar128)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
template<>
struct TypeInfo<ScriptStringVar256> {
const SQChar * typeName;
TypeInfo() : typeName(_T("ScriptStringVar256")) {}
enum {TypeID=VAR_TYPE_STRING,Size=sizeof(ScriptStringVar256)};
operator ScriptVarType() { return ScriptVarType(TypeID); }
};
enum VarAccessType {VAR_ACCESS_READ_WRITE=0,VAR_ACCESS_READ_ONLY=1<<0,VAR_ACCESS_CONSTANT=1<<1,VAR_ACCESS_STATIC=1<<2};
// See VarRef and ClassType<> below: for instance assignment.
typedef void (*CopyVarFunc)(void * dst,void * src);
// === Variable references for script access ===
#define SQ_PLUS_TYPE_TABLE _T("__SqTypes")
struct VarRef {
// In this case 'offsetOrAddrOrConst' is simpler than using an anonymous union.
void * offsetOrAddrOrConst; // Instance member variable offset from 'this' pointer base (as size_t), or address if static variable (void *), or constant value.
ScriptVarType type; // Variable type (from enum above).
SQUserPointer instanceType; // Unique ID for the containing class instance (for instance vars only). When the var is an instance, its type is encoded in copyFunc.
CopyVarFunc copyFunc; // Function pointer to copy variables (for instance variables only).
short size; // Currently for debugging only (size of item when pointer to item is dereferenced). Could be used for variable max string buffer length.
short access; // VarAccessType.
const SQChar * typeName; // Type name string (to create instances by name).
VarRef() : offsetOrAddrOrConst(0), type(VAR_TYPE_NONE), instanceType((SQUserPointer)-1), copyFunc(0), size(0), access(VAR_ACCESS_READ_WRITE) {}
VarRef(void * _offsetOrAddrOrConst, ScriptVarType _type, SQUserPointer _instanceType, CopyVarFunc _copyFunc, int _size,VarAccessType _access,const SQChar * _typeName) :
offsetOrAddrOrConst(_offsetOrAddrOrConst), type(_type), instanceType(_instanceType), copyFunc(_copyFunc), size(_size), access(_access), typeName(_typeName) {
#ifdef SQ_SUPPORT_INSTANCE_TYPE_INFO
SquirrelObject typeTable = SquirrelVM::GetRootTable().GetValue(SQ_PLUS_TYPE_TABLE);
if (typeTable.IsNull()) {
typeTable = SquirrelVM::CreateTable();
SquirrelObject root = SquirrelVM::GetRootTable();
root.SetValue(SQ_PLUS_TYPE_TABLE,typeTable);
} // if
typeTable.SetValue(INT((size_t)copyFunc),typeName);
#endif
}
};
typedef VarRef * VarRefPtr;
// Internal use only.
inline void getVarNameTag(SQChar * buff,INT maxSize,const SQChar * scriptName) {
// assert(maxSize > 3);
#if 1
SQChar * d = buff;
d[0] = '_';
d[1] = 'v';
d = &d[2];
maxSize -= (2+1); // +1 = space for null.
int pos=0;
while (scriptName[pos] && pos < maxSize) {
d[pos] = scriptName[pos];
pos++;
} // while
d[pos] = 0; // null terminate.
#else
SCSNPRINTF(buff,maxSize,_T("_v%s"),scriptName);
#endif
} // getVarNameTag
// Internal use only.
int setVarFunc(HSQUIRRELVM v);
int getVarFunc(HSQUIRRELVM v);
int setInstanceVarFunc(HSQUIRRELVM v);
int getInstanceVarFunc(HSQUIRRELVM v);
// === BEGIN Helpers ===
inline void createTableSetGetHandlers(SquirrelObject & so) {
SquirrelObject delegate = so.GetDelegate();
if (!delegate.Exists(_T("_set"))) {
delegate = SquirrelVM::CreateTable();
SquirrelVM::CreateFunction(delegate,setVarFunc,_T("_set"),_T("sn|b|s")); // String var name = number(int or float) or bool or string.
SquirrelVM::CreateFunction(delegate,getVarFunc,_T("_get"),_T("s")); // String var name.
so.SetDelegate(delegate);
} // if
} // createTableSetGetHandlers
inline VarRefPtr createVarRef(SquirrelObject & so,const SQChar * scriptVarName) {
VarRefPtr pvr=0;
ScriptStringVar256 scriptVarTagName; getVarNameTag(scriptVarTagName,sizeof(scriptVarTagName),scriptVarName);
if (!so.GetUserData(scriptVarTagName,(SQUserPointer *)&pvr)) {
so.NewUserData(scriptVarTagName,sizeof(*pvr));
if (!so.GetUserData(scriptVarTagName,(SQUserPointer *)&pvr)) throw SquirrelError(_T("Could not create UserData."));
} // if
return pvr;
} // createVarRef
template<typename T>
void validateConstantType(T constant) {
switch(TypeInfo<T>()) {
case VAR_TYPE_INT:
case VAR_TYPE_FLOAT:
case VAR_TYPE_BOOL:
case VAR_TYPE_CONST_STRING:
break;
default:
throw SquirrelError(_T("validateConstantType(): type must be INT, FLOAT, BOOL, or CONST CHAR *."));
} // case
} // validateConstantType
inline void createInstanceSetGetHandlers(SquirrelObject & so) {
if (!so.Exists(_T("_set"))) {
SquirrelVM::CreateFunction(so,setInstanceVarFunc,_T("_set"),_T("sn|b|s|x")); // String var name = number(int or float) or bool or string or instance.
SquirrelVM::CreateFunction(so,getInstanceVarFunc,_T("_get"),_T("s")); // String var name.
} // if
} // createInstanceSetGetHandlers
// === END Helpers ===
// === Class Type Helper class: returns a unique number for each class type ===
template<typename T>
struct ClassType {
static SQUserPointer type(void) { return (SQUserPointer)© }
static CopyVarFunc getCopyFunc(void) { return (CopyVarFunc)© }
static void copy(T * dst,T * src) {
*dst = *src;
} // copy
};
// === Bind a global or pre-allocated (not instance) class member variable or constant (for tables only (not classes)) ===
template<typename T>
void BindVariable(SquirrelObject & so,T * var,const SQChar * scriptVarName,VarAccessType access=VAR_ACCESS_READ_WRITE) {
VarRefPtr pvr = createVarRef(so,scriptVarName);
*pvr = VarRef(var,TypeInfo<T>(),0,ClassType<T>::getCopyFunc(),sizeof(*var),access,TypeInfo<T>().typeName);
createTableSetGetHandlers(so);
} // BindVariable
// === Bind a constant by value: INT, FLOAT, BOOL, or CONST CHAR * (for tables only (not classes)) ===
template<typename T>
void BindConstant(SquirrelObject & so,T constant,const SQChar * scriptVarName) {
validateConstantType(constant);
VarRefPtr pvr = createVarRef(so,scriptVarName);
struct CV {
T var;
} cv; // Cast Variable helper.
cv.var = constant;
*pvr = VarRef(*(void **)&cv,TypeInfo<T>(),0,0,sizeof(constant),VAR_ACCESS_CONSTANT,TypeInfo<T>().typeName);
createTableSetGetHandlers(so);
} // BindConstant
template<typename T>
void BindVariable(T * var,const SQChar * scriptVarName,VarAccessType access=VAR_ACCESS_READ_WRITE) {
SquirrelObject so = SquirrelVM::GetRootTable();
BindVariable(so,var,scriptVarName,access);
} // BindVariable
template<typename T>
void BindConstant(T constant,const SQChar * scriptVarName) {
SquirrelObject so = SquirrelVM::GetRootTable();
BindConstant(so,constant,scriptVarName);
} // BindConstant
// === Register a class instance member variable or constant. var argument provides type and offset ( effectively &((ClassType *)0)->var ) ===
// classType is the type of the member variable's containing class.
template<typename T>
void RegisterInstanceVariable(SquirrelObject & so,SQUserPointer classType,T * var,const SQChar * scriptVarName,VarAccessType access=VAR_ACCESS_READ_WRITE) {
VarRef * pvr = createVarRef(so,scriptVarName);
void * offsetOrAddrOrConst = (void *)var; // var must be passed in as &obj->var, where obj = 0 (the address is the offset), or as static/global address.
*pvr = VarRef(offsetOrAddrOrConst,TypeInfo<T>(),classType,ClassType<T>::getCopyFunc(),sizeof(*var),access,TypeInfo<T>().typeName);
createInstanceSetGetHandlers(so);
} // RegisterInstanceVariable
template<typename T>
void RegisterInstanceConstant(SquirrelObject & so,SQUserPointer classType,T constant,const SQChar * scriptVarName) {
validateConstantType(constant);
VarRef * pvr = createVarRef(so,scriptVarName);
struct CV {
T var;
size_t pad;
} cv; // Cast Variable helper.
cv.var = constant;
*pvr = VarRef(*(void **)&cv,TypeInfo<T>(),classType,0,sizeof(constant),VAR_ACCESS_CONSTANT,TypeInfo<T>().typeName);
createInstanceSetGetHandlers(so);
} // RegisterInstanceConstant
//////////////////////////////////////////////////////////////////////////
/////////// BEGIN Generalized Class/Struct Instance Support //////////////
//////////////////////////////////////////////////////////////////////////
//BOOL CreateNativeClassInstance(HSQUIRRELVM v,const SQChar * classname,SQUserPointer ud,SQRELEASEHOOK hook); // In SquirrelBindingUtils.cpp.
// Create native class instance and leave on stack.
inline BOOL CreateConstructNativeClassInstance(HSQUIRRELVM v,const SQChar * className) {
int oldtop = sq_gettop(v);
sq_pushroottable(v);
sq_pushstring(v,className,-1);
if (SQ_FAILED(sq_rawget(v,-2))) { // Get the class (created with sq_newclass()).
sq_settop(v,oldtop);
return FALSE;
} // if
#if 0
sq_remove(v,-3); // Remove the root table.
sq_push(v,1); // Push the 'this'.
#else // Kamaitati's change. 5/28/06 jcs.
sq_remove(v,-2); // Remove the root table.
sq_pushroottable(v); // Push the 'this'.
#endif
if (SQ_FAILED(sq_call(v,1,SQTrue,SQ_CALL_RAISE_ERROR))) { // Call ClassName(): creates new instance and calls constructor (instead of sq_createinstance() where constructor is not called).
sq_settop(v,oldtop);
return FALSE;
} // if
sq_remove(v,-2); // Remove the class.
// int newtop = sq_gettop(v);
return TRUE;
} // CreateConstructNativeClassInstance
// Create new instance, copy 'classToCopy', and store result on stack.
template<typename T>
inline BOOL CreateCopyInstance(const SQChar * className,const T & classToCopy) {
HSQUIRRELVM v = SquirrelVM::GetVMPtr();
if (!CreateConstructNativeClassInstance(v,className)) {
return FALSE;
} // if
SQUserPointer up=0;
sq_getinstanceup(v,-1,&up,ClassType<T>::type());
if (!up) return FALSE;
T * newClass = (T *)up;
*newClass = classToCopy; // <TODO> Optimized version that uses the copy constructor.
return TRUE;
} // CreateCopyInstance
// Create a new copy of type 'className' and copy 'classToCopy', return result via SquirrelObject.
template<typename T>
inline SquirrelObject NewClassCopy(const SQChar * className,const T & classToCopy) {
SquirrelObject ret;
if (CreateCopyInstance(className,classToCopy)) {
ret.AttachToStackObject(-1);
sq_poptop(SquirrelVM::GetVMPtr());
} else {
throw SquirrelError(_T("NewClassCopy(): could not create class"));
} // if
return ret;
} // NewClassCopy
// Return a new class copy on the stack from a varArgs function call.
template<typename T>
inline int ReturnCopy(HSQUIRRELVM v,const T & classToCopy) {
SquirrelObject so(NewClassCopy(GetTypeName(classToCopy),classToCopy));
return StackHandler(v).Return(so);
} // ReturnCopy
// Katsuaki Kawachi's GetInstance<> exception change. 6/27/06 jcs
// Get an instance of type T from the stack at idx (for function calls).
template<typename T,bool ExceptionOnError>
T * GetInstance(HSQUIRRELVM v,SQInteger idx) {
SQUserPointer up=0;
sq_getinstanceup(v,idx,&up,ClassType<T>::type());
if (ExceptionOnError) { // This code block should be compiled out when ExceptionOnError is false. In any case, the compiler should not generate a test condition (include or exclude the enclosed code block).
if (!up) throw SquirrelError(_T("GetInstance: Invalid argument type"));
} // if
return (T *)up;
} // GetInstance
// NAME and macro changes from Ben's (Project5) forum post. 2/26/06 jcs
// Kamaitati's NULL_INSTANCE support. 5/28/06 jcs
#ifdef SQPLUS_SUPPORT_NULL_INSTANCES
#define DECLARE_INSTANCE_TYPE_NAME_(TYPE,NAME) namespace SqPlus { \
inline const SQChar * GetTypeName(const TYPE & n) { return _T(#NAME); } \
inline void Push(HSQUIRRELVM v,TYPE * value) { \
if (!value) sq_pushnull(v); \
else if (!CreateNativeClassInstance(v,GetTypeName(*value),value,0)) \
throw SquirrelError(_T("Push(): could not create INSTANCE (check registration name)")); } \
inline void Push(HSQUIRRELVM v,TYPE & value) { if (!CreateCopyInstance(GetTypeName(value),value)) throw SquirrelError(_T("Push(): could not create INSTANCE copy (check registration name)")); } \
inline bool Match(TypeWrapper<TYPE &>,HSQUIRRELVM v,int idx) { return GetInstance<TYPE,false>(v,idx) != NULL; } \
inline bool Match(TypeWrapper<TYPE *>,HSQUIRRELVM v,int idx) { \
return (sq_gettype(v,idx)==OT_NULL) || (GetInstance<TYPE,false>(v,idx) != NULL); } \
inline TYPE & Get(TypeWrapper<TYPE &>,HSQUIRRELVM v,int idx) { return *GetInstance<TYPE,true>(v,idx); } \
inline TYPE * Get(TypeWrapper<TYPE *>,HSQUIRRELVM v,int idx) { \
if (sq_gettype(v,idx)==OT_NULL) return NULL; \
return GetInstance<TYPE,true>(v,idx); } \
template<> \
struct TypeInfo<TYPE> { \
const SQChar * typeName; \
TypeInfo() : typeName(_T(#NAME)) {} \
enum {TypeID=VAR_TYPE_INSTANCE,Size=sizeof(TYPE)}; \
operator ScriptVarType() { return ScriptVarType(TypeID); } \
}; \
} // nameSpace SqPlus
#else
#define DECLARE_INSTANCE_TYPE_NAME_(TYPE,NAME) namespace SqPlus { \
inline const SQChar * GetTypeName(const TYPE & n) { return _T(#NAME); } \
inline void Push(HSQUIRRELVM v,TYPE * value) { if (!CreateNativeClassInstance(v,GetTypeName(*value),value,0)) throw SquirrelError(_T("Push(): could not create INSTANCE (check registration name)")); } \
inline void Push(HSQUIRRELVM v,TYPE & value) { if (!CreateCopyInstance(GetTypeName(value),value)) throw SquirrelError(_T("Push(): could not create INSTANCE copy (check registration name)")); } \
inline bool Match(TypeWrapper<TYPE &>,HSQUIRRELVM v,int idx) { return GetInstance<TYPE,false>(v,idx) != NULL; } \
inline bool Match(TypeWrapper<TYPE *>,HSQUIRRELVM v,int idx) { return GetInstance<TYPE,false>(v,idx) != NULL; } \
inline TYPE & Get(TypeWrapper<TYPE &>,HSQUIRRELVM v,int idx) { return *GetInstance<TYPE,true>(v,idx); } \
inline TYPE * Get(TypeWrapper<TYPE *>,HSQUIRRELVM v,int idx) { return GetInstance<TYPE,true>(v,idx); } \
template<> \
struct TypeInfo<TYPE> { \
const SQChar * typeName; \
TypeInfo() : typeName(_T(#NAME)) {} \
enum {TypeID=VAR_TYPE_INSTANCE,Size=sizeof(TYPE)}; \
operator ScriptVarType() { return ScriptVarType(TypeID); } \
}; \
} // nameSpace SqPlus
#endif
// TYPE or NAME below must match the string name used in SQClassDef<>, otherwise name lookup won't match and Squirrel will throw a "can't create instance" error.
#ifndef SQPLUS_CONST_OPT
#define DECLARE_INSTANCE_TYPE(TYPE) DECLARE_INSTANCE_TYPE_NAME_(TYPE,TYPE)
#define DECLARE_INSTANCE_TYPE_NAME(TYPE,NAME) DECLARE_INSTANCE_TYPE_NAME_(TYPE,NAME)
#else
#define SQPLUS_DECLARE_INSTANCE_TYPE_CONST
#include "SqPlusConst.h"
#endif
//////////////////////////////////////////////////////////////////////////
//////////// END Generalized Class/Struct Instance Support ///////////////
//////////////////////////////////////////////////////////////////////////
#ifndef SQ_SKIP_ARG_ASSERT
#define sq_argassert(arg,_index_) if (!Match(TypeWrapper<P##arg>(),v,_index_)) return sq_throwerror(v,_T("Incorrect function argument"))
#else
#define sq_argassert(arg,_index_)
#endif
// === Return value variants ===
template<class RT>
struct ReturnSpecialization {
// === Standard Function calls ===
static int Call(RT (*func)(),HSQUIRRELVM v,int /*index*/) {
RT ret = func();
Push(v,ret);
return 1;
}
template<typename P1>
static int Call(RT (*func)(P1),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
RT ret = func(
Get(TypeWrapper<P1>(),v,index + 0)
);
Push(v,ret);
return 1;
}
template<typename P1,typename P2>
static int Call(RT (*func)(P1,P2),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
RT ret = func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1)
);
Push(v,ret);
return 1;
}
template<typename P1,typename P2,typename P3>
static int Call(RT (*func)(P1,P2,P3),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
RT ret = func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2)
);
Push(v,ret);
return 1;
}
template<typename P1,typename P2,typename P3,typename P4>
static int Call(RT (*func)(P1,P2,P3,P4),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
RT ret = func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3)
);
Push(v,ret);
return 1;
}
template<typename P1,typename P2,typename P3,typename P4,typename P5>
static int Call(RT (*func)(P1,P2,P3,P4,P5),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
RT ret = func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4)
);
Push(v,ret);
return 1;
}
template<typename P1,typename P2,typename P3,typename P4,typename P5,typename P6>
static int Call(RT (*func)(P1,P2,P3,P4,P5,P6),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
sq_argassert(6,index + 5);
RT ret = func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4),
Get(TypeWrapper<P6>(),v,index + 5)
);
Push(v,ret);
return 1;
}
template<typename P1,typename P2,typename P3,typename P4,typename P5,typename P6,typename P7>
static int Call(RT (*func)(P1,P2,P3,P4,P5,P6,P7),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
sq_argassert(6,index + 5);
sq_argassert(7,index + 6);
RT ret = func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4),
Get(TypeWrapper<P6>(),v,index + 5),
Get(TypeWrapper<P7>(),v,index + 6)
);
Push(v,ret);
return 1;
}
// === Member Function calls ===
template <typename Callee>
static int Call(Callee & callee,RT (Callee::*func)(),HSQUIRRELVM v,int /*index*/) {
RT ret = (callee.*func)();
Push(v,ret);
return 1;
}
template <typename Callee,typename P1>
static int Call(Callee & callee,RT (Callee::*func)(P1),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
RT ret = (callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0)
);
Push(v,ret);
return 1;
}
template<typename Callee,typename P1,typename P2>
static int Call(Callee & callee,RT (Callee::*func)(P1,P2),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
RT ret = (callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1)
);
Push(v,ret);
return 1;
}
template<typename Callee,typename P1,typename P2,typename P3>
static int Call(Callee & callee,RT (Callee::*func)(P1,P2,P3),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
RT ret = (callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2)
);
Push(v,ret);
return 1;
}
template<typename Callee,typename P1,typename P2,typename P3,typename P4>
static int Call(Callee & callee,RT (Callee::*func)(P1,P2,P3,P4),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
RT ret = (callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3)
);
Push(v,ret);
return 1;
}
template<typename Callee,typename P1,typename P2,typename P3,typename P4,typename P5>
static int Call(Callee & callee,RT (Callee::*func)(P1,P2,P3,P4,P5),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
RT ret = (callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4)
);
Push(v,ret);
return 1;
}
template<typename Callee,typename P1,typename P2,typename P3,typename P4,typename P5,typename P6>
static int Call(Callee & callee,RT (Callee::*func)(P1,P2,P3,P4,P5,P6),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
sq_argassert(6,index + 5);
RT ret = (callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4),
Get(TypeWrapper<P6>(),v,index + 5)
);
Push(v,ret);
return 1;
}
template<typename Callee,typename P1,typename P2,typename P3,typename P4,typename P5,typename P6,typename P7>
static int Call(Callee & callee,RT (Callee::*func)(P1,P2,P3,P4,P5,P6,P7),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
sq_argassert(6,index + 5);
sq_argassert(7,index + 6);
RT ret = (callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4),
Get(TypeWrapper<P6>(),v,index + 5),
Get(TypeWrapper<P7>(),v,index + 6)
);
Push(v,ret);
return 1;
}
#ifdef SQPLUS_CONST_OPT
#define SQPLUS_CALL_CONST_MFUNC_RET0
#include "SqPlusConst.h"
#endif
};
// === No return value variants ===
template<>
struct ReturnSpecialization<void> {
// === Standard function calls ===
static int Call(void (*func)(),HSQUIRRELVM v,int /*index*/) {
(void)v;
func();
return 0;
}
template<typename P1>
static int Call(void (*func)(P1),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
func(
Get(TypeWrapper<P1>(),v,index + 0)
);
return 0;
}
template<typename P1,typename P2>
static int Call(void (*func)(P1,P2),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1)
);
return 0;
}
template<typename P1,typename P2,typename P3>
static int Call(void (*func)(P1,P2,P3),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2)
);
return 0;
}
template<typename P1,typename P2,typename P3,typename P4>
static int Call(void (*func)(P1,P2,P3,P4),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3)
);
return 0;
}
template<typename P1,typename P2,typename P3,typename P4,typename P5>
static int Call(void (*func)(P1,P2,P3,P4,P5),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4)
);
return 0;
}
template<typename P1,typename P2,typename P3,typename P4,typename P5,typename P6>
static int Call(void (*func)(P1,P2,P3,P4,P5,P6),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
sq_argassert(6,index + 5);
func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4),
Get(TypeWrapper<P6>(),v,index + 5)
);
return 0;
}
template<typename P1,typename P2,typename P3,typename P4,typename P5,typename P6,typename P7>
static int Call(void (*func)(P1,P2,P3,P4,P5,P6,P7),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
sq_argassert(6,index + 5);
sq_argassert(7,index + 6);
func(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4),
Get(TypeWrapper<P6>(),v,index + 5),
Get(TypeWrapper<P7>(),v,index + 6)
);
return 0;
}
// === Member function calls ===
template<typename Callee>
static int Call(Callee & callee,void (Callee::*func)(),HSQUIRRELVM,int /*index*/) {
(callee.*func)();
return 0;
}
template<typename Callee,typename P1>
static int Call(Callee & callee,void (Callee::*func)(P1),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
(callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0)
);
return 0;
}
template<typename Callee,typename P1,typename P2>
static int Call(Callee & callee,void (Callee::*func)(P1,P2),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
(callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1)
);
return 0;
}
template<typename Callee,typename P1,typename P2,typename P3>
static int Call(Callee & callee,void (Callee::*func)(P1,P2,P3),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
(callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2)
);
return 0;
}
template<typename Callee,typename P1,typename P2,typename P3,typename P4>
static int Call(Callee & callee,void (Callee::*func)(P1,P2,P3,P4),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
(callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3)
);
return 0;
}
template<typename Callee,typename P1,typename P2,typename P3,typename P4,typename P5>
static int Call(Callee & callee,void (Callee::*func)(P1,P2,P3,P4,P5),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
(callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4)
);
return 0;
}
template<typename Callee,typename P1,typename P2,typename P3,typename P4,typename P5,typename P6>
static int Call(Callee & callee,void (Callee::*func)(P1,P2,P3,P4,P5,P6),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
sq_argassert(6,index + 5);
(callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4),
Get(TypeWrapper<P6>(),v,index + 5)
);
return 0;
}
template<typename Callee,typename P1,typename P2,typename P3,typename P4,typename P5,typename P6,typename P7>
static int Call(Callee & callee,void (Callee::*func)(P1,P2,P3,P4,P5,P6,P7),HSQUIRRELVM v,int index) {
sq_argassert(1,index + 0);
sq_argassert(2,index + 1);
sq_argassert(3,index + 2);
sq_argassert(4,index + 3);
sq_argassert(5,index + 4);
sq_argassert(6,index + 5);
sq_argassert(7,index + 6);
(callee.*func)(
Get(TypeWrapper<P1>(),v,index + 0),
Get(TypeWrapper<P2>(),v,index + 1),
Get(TypeWrapper<P3>(),v,index + 2),
Get(TypeWrapper<P4>(),v,index + 3),
Get(TypeWrapper<P5>(),v,index + 4),
Get(TypeWrapper<P6>(),v,index + 5),
Get(TypeWrapper<P7>(),v,index + 6)
);
return 0;
}
#ifdef SQPLUS_CONST_OPT
#define SQPLUS_CALL_CONST_MFUNC_NORET
#include "SqPlusConst.h"
#endif
};
// === STANDARD Function return value specialized call handlers ===
template<typename RT>
int Call(RT (*func)(),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(func,v,index);
}
template<typename RT,typename P1>
int Call(RT (*func)(P1),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(func,v,index);
}
template<typename RT,typename P1,typename P2>
int Call(RT (*func)(P1,P2),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(func,v,index);
}
template<typename RT,typename P1,typename P2,typename P3>
int Call(RT (*func)(P1,P2,P3),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(func,v,index);
}
template<typename RT,typename P1,typename P2,typename P3,typename P4>
int Call(RT (*func)(P1,P2,P3,P4),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(func,v,index);
}
template<typename RT,typename P1,typename P2,typename P3,typename P4,typename P5>
int Call(RT (*func)(P1,P2,P3,P4,P5),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(func,v,index);
}
template<typename RT,typename P1,typename P2,typename P3,typename P4,typename P5,typename P6>
int Call(RT (*func)(P1,P2,P3,P4,P5,P6),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(func,v,index);
}
template<typename RT,typename P1,typename P2,typename P3,typename P4,typename P5,typename P6,typename P7>
int Call(RT (*func)(P1,P2,P3,P4,P5,P6,P7),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(func,v,index);
}
// === MEMBER Function return value specialized call handlers ===
template<typename Callee,typename RT>
int Call(Callee & callee, RT (Callee::*func)(),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(callee,func,v,index);
}
template<typename Callee,typename RT,typename P1>
int Call(Callee & callee,RT (Callee::*func)(P1),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(callee,func,v,index);
}
template<typename Callee,typename RT,typename P1,typename P2>
int Call(Callee & callee,RT (Callee::*func)(P1,P2),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(callee,func,v,index);
}
template<typename Callee,typename RT,typename P1,typename P2,typename P3>
int Call(Callee & callee,RT (Callee::*func)(P1,P2,P3),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(callee,func,v,index);
}
template<typename Callee,typename RT,typename P1,typename P2,typename P3,typename P4>
int Call(Callee & callee,RT (Callee::*func)(P1,P2,P3,P4),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(callee,func,v,index);
}
template<typename Callee,typename RT,typename P1,typename P2,typename P3,typename P4,typename P5>
int Call(Callee & callee,RT (Callee::*func)(P1,P2,P3,P4,P5),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(callee,func,v,index);
}
template<typename Callee,typename RT,typename P1,typename P2,typename P3,typename P4,typename P5,typename P6>
int Call(Callee & callee,RT (Callee::*func)(P1,P2,P3,P4,P5,P6),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(callee,func,v,index);
}
template<typename Callee,typename RT,typename P1,typename P2,typename P3,typename P4,typename P5,typename P6,typename P7>
int Call(Callee & callee,RT (Callee::*func)(P1,P2,P3,P4,P5,P6,P7),HSQUIRRELVM v,int index) {
return ReturnSpecialization<RT>::Call(callee,func,v,index);
}
#ifdef SQPLUS_CONST_OPT
#define SQPLUS_CALL_CONST_MFUNC_RET1
#include "SqPlusConst.h"
#endif
// === Direct Call Standard Function handler ===
template<typename Func>
struct DirectCallFunction {
static inline int Dispatch(HSQUIRRELVM v) {
StackHandler sa(v);
int paramCount = sa.GetParamCount();
Func * func = (Func *)sa.GetUserData(paramCount);
return Call(*func,v,2);
} // Dispatch
};
// === Direct Call Member Function handler ===
template<typename Callee,typename Func>
class DirectCallMemberFunction {
public:
static inline int Dispatch(HSQUIRRELVM v) {
StackHandler sa(v);
int paramCount = sa.GetParamCount();
unsigned char * ud = (unsigned char *)sa.GetUserData(paramCount);
return Call(**(Callee**)ud,*(Func*)(ud + sizeof(Callee*)),v,2);
} // Dispatch
};
// === Direct Call Instance Member Function handler ===
#define SQ_CLASS_OBJECT_TABLE_NAME _T("__ot")
#define SQ_CLASS_HIER_ARRAY _T("__ca")
template<typename Callee,typename Func>
class DirectCallInstanceMemberFunction {
public:
static inline int Dispatch(HSQUIRRELVM v) {
StackHandler sa(v);
Callee * instance = (Callee *)sa.GetInstanceUp(1,0);
int paramCount = sa.GetParamCount();
Func * func = (Func *)sa.GetUserData(paramCount);
#ifdef SQ_USE_CLASS_INHERITANCE
SquirrelObject so(sa.GetObjectHandle(1)); // 'this'
SQUserPointer typetag; so.GetTypeTag(&typetag);
SQUserPointer calleeType = ClassType<Callee>::type();
if (typetag != calleeType) {
SquirrelObject typeTable = so.GetValue(SQ_CLASS_OBJECT_TABLE_NAME);
instance = (Callee *)typeTable.GetUserPointer(INT((size_t)ClassType<Callee>::type())); // <TODO> 64-bit compatible version.
if (!instance) {
return sq_throwerror(v,_T("Invalid Instance Type"));
} // if
} // if
#endif
return Call(*instance,*func,v,2);
} // Dispatch
};
// === Direct Call Instance Member Function Variable Argument handler ===
template<typename Callee>
class DirectCallInstanceMemberFunctionVarArgs {
public:
typedef int (Callee::*FuncType)(HSQUIRRELVM);
static inline int Dispatch(HSQUIRRELVM v) {
StackHandler sa(v);
Callee * instance = (Callee *)sa.GetInstanceUp(1,0);
int paramCount = sa.GetParamCount();
FuncType func = *(FuncType *)sa.GetUserData(paramCount);
#ifdef SQ_USE_CLASS_INHERITANCE
SquirrelObject so(sa.GetObjectHandle(1)); // 'this'
SQUserPointer typetag; so.GetTypeTag(&typetag);
SQUserPointer calleeType = ClassType<Callee>::type();
if (typetag != calleeType) {
SquirrelObject typeTable = so.GetValue(SQ_CLASS_OBJECT_TABLE_NAME);
instance = (Callee *)typeTable.GetUserPointer(INT((size_t)ClassType<Callee>::type())); // <TODO> 64-bit compatible version.
if (!instance) {
return sq_throwerror(v,_T("Invalid Instance Type"));
} // if
} // if
#endif
sq_poptop(v); // Remove UserData from stack: so sa.GetParamCount() returns actual param count.
return (instance->*func)(v);
} // Dispatch
};
// Code fragment useful for debugging new implementations.
#if 0
HSQOBJECT ho = sa.GetObjectHandle(paramCount);
SquirrelObject so(ho);
SQObjectType sot = so.GetType();
#endif
// === Standard function call ===
template<typename Func>
inline void sq_pushdirectclosure(HSQUIRRELVM v,Func func,SQUnsignedInteger nupvalues) {
SQUserPointer up = sq_newuserdata(v,sizeof(func)); // Also pushed on stack.
memcpy(up,&func,sizeof(func));
sq_newclosure(v,DirectCallFunction<Func>::Dispatch,nupvalues+1);
} // sq_pushdirectclosure
// === Fixed Class pointer call (always calls with object pointer that was registered) ===
template<typename Callee,typename Func>
inline void sq_pushdirectclosure(HSQUIRRELVM v,const Callee & callee,Func func,SQUnsignedInteger nupvalues) {
unsigned char * up = (unsigned char *)sq_newuserdata(v,sizeof(Callee*)+sizeof(func)); // Also pushed on stack.
const SQUserPointer pCallee = (SQUserPointer)&callee;
memcpy(up,&pCallee,sizeof(Callee*));
memcpy(up + sizeof(Callee*),&func,sizeof(func));
sq_newclosure(v,DirectCallMemberFunction<Callee,Func>::Dispatch,nupvalues+1);
} // sq_pushdirectclosure
// === Class Instance call: class pointer retrieved from script class instance ===
template<typename Callee,typename Func>
inline void sq_pushdirectinstanceclosure(HSQUIRRELVM v,const Callee & callee,Func func,SQUnsignedInteger nupvalues) {
unsigned char * up = (unsigned char *)sq_newuserdata(v,sizeof(func)); // Also pushed on stack.
memcpy(up,&func,sizeof(func));
sq_newclosure(v,DirectCallInstanceMemberFunction<Callee,Func>::Dispatch,nupvalues+1);
} // sq_pushdirectinstanceclosure
// === Class Instance call: class pointer retrieved from script class instance (variable arguments) ===
template<typename Callee>
inline void sq_pushdirectinstanceclosurevarargs(HSQUIRRELVM v,const Callee & callee,int (Callee::*func)(HSQUIRRELVM),SQUnsignedInteger nupvalues) {
unsigned char * up = (unsigned char *)sq_newuserdata(v,sizeof(func)); // Also pushed on stack.
memcpy(up,&func,sizeof(func));
sq_newclosure(v,DirectCallInstanceMemberFunctionVarArgs<Callee>::Dispatch,nupvalues+1);
} // sq_pushdirectinstanceclosurevarargs
// === Register a STANDARD function (table or class on stack) ===
template<typename Func>
inline void Register(HSQUIRRELVM v,Func func,const SQChar * name) {
sq_pushstring(v,name,-1);
sq_pushdirectclosure(v,func,0);
sq_createslot(v,-3); // Stack is restored after this call (same state as before Register() call).
} // Register
// === Register a MEMBER function (table or class on stack) ===
template<typename Callee,typename Func>
inline void Register(HSQUIRRELVM v,Callee & callee,Func func,const SQChar * name) {
sq_pushstring(v,name,-1);
sq_pushdirectclosure(v,callee,func,0);
sq_createslot(v,-3); // Stack is restored after this call (same state as before Register() call).
} // Register
// === Register a STANDARD global function (root table) ===
template<typename Func>
inline void RegisterGlobal(HSQUIRRELVM v,Func func,const SQChar * name) {
sq_pushroottable(v);
Register(v,func,name);
sq_poptop(v); // Remove root table.
} // RegisterGlobal
template<typename Func>
inline void RegisterGlobal(Func func,const SQChar * name) {
RegisterGlobal(SquirrelVM::GetVMPtr(),func,name);
} // RegisterGlobal
// === Register a MEMBER global function (root table) ===
template<typename Callee,typename Func>
inline void RegisterGlobal(HSQUIRRELVM v,Callee & callee,Func func,const SQChar * name) {
sq_pushroottable(v);
Register(v,callee,func,name);
sq_poptop(v); // Remove root table.
} // RegisterGlobal
template<typename Callee,typename Func>
inline void RegisterGlobal(Callee & callee,Func func,const SQChar * name) {
RegisterGlobal(SquirrelVM::GetVMPtr(),callee,func,name);
} // RegisterGlobal
// === Register a STANDARD function (hso is table or class) ===
template<typename Func>
inline void Register(HSQUIRRELVM v,HSQOBJECT hso,Func func,const SQChar * name) {
sq_pushobject(v,hso);
Register(v,func,name);
sq_poptop(v); // Remove hso.
} // Register
// === Register a MEMBER function (hso is table or class) ===
// === Fixed Class pointer call (always calls with object pointer that was registered) ===
template<typename Callee,typename Func>
inline void Register(HSQUIRRELVM v,HSQOBJECT hso,Callee & callee,Func func,const SQChar * name) {
sq_pushobject(v,hso);
Register(v,callee,func,name);
sq_poptop(v); // Remove hso.
} // Register
// === Register an INSTANCE MEMBER function ===
// === Class Instance call: class pointer retrieved from script class instance ===
template<typename Callee,typename Func>
inline void RegisterInstance(HSQUIRRELVM v,HSQOBJECT hclass,Callee & callee,Func func,const SQChar * name) {
sq_pushobject(v,hclass);
sq_pushstring(v,name,-1);
sq_pushdirectinstanceclosure(v,callee,func,0);
sq_createslot(v,-3);
sq_poptop(v); // Remove hclass.
} // RegisterInstance
#ifdef _MSC_VER
#pragma warning(disable : 4995) // Deprecated _snprintf
#endif
// === Register an INSTANCE MEMBER function Variable Arguments ===
// typeMask: "*" means don't check parameters, typeMask=0 means function takes no arguments (and is type checked for that case).
// All the other Squirrel type-masks are passed normally.
template<typename Callee>
inline void RegisterInstanceVarArgs(HSQUIRRELVM v,HSQOBJECT hclass,Callee & callee,int (Callee::*func)(HSQUIRRELVM),const SQChar * name,const SQChar * typeMask=_T("*")) {
sq_pushobject(v,hclass);
sq_pushstring(v,name,-1);
sq_pushdirectinstanceclosurevarargs(v,callee,func,0);
SQChar tm[64];
SQChar * ptm = tm;
int numParams = SQ_MATCHTYPEMASKSTRING;
if (typeMask) {
if (typeMask[0] == '*') {
ptm = 0; // Variable args: don't check parameters.
// numParams = 0; // Clear SQ_MATCHTYPEMASKSTRING (does not mean match 0 params. See sq_setparamscheck()).
} else {
if (SCSNPRINTF(tm,sizeof(tm),_T("x%s"),typeMask) < 0) { // Must be an instance.
throw SquirrelError(_T("RegisterInstanceVarArgs: typeMask string too long."));
} // if
} // if
} else { // <TODO> Need to check object type on stack: table, class, instance, etc.
// _snprintf(tm,sizeof(tm),"x"); // instance.
tm[0] = 'x';
tm[1] = 0;
} // if
if (ptm) { // If ptm == 0, don't check type.
sq_setparamscheck(v,numParams,ptm); // Determine arg count from type string.
} // if
#ifdef _DEBUG
sq_setnativeclosurename(v,-1,name); // For debugging only.
#endif
sq_createslot(v,-3);
sq_poptop(v); // Remove hclass.
} // RegisterInstanceVarArgs
#ifdef _MSC_VER
#pragma warning(default : 4995)
#endif
// === Call Squirrel Functions from C/C++ ===
// No type checking is performed for Squirrel functions as Squirrel types are dynamic:
// Incoming types are passed unchanged to Squirrel functions. The parameter count is checked: an exception is thrown if mismatched.
// Return values must match the RT template argument type, else an exception can be thrown on return.
template<typename RT>
struct SquirrelFunction {
HSQUIRRELVM v;
SquirrelObject object; // Table or class.
SquirrelObject func;
SquirrelFunction() : v(0) {}
SquirrelFunction(HSQUIRRELVM _v,const SquirrelObject & _object,const SquirrelObject & _func) : v(_v), object(_object), func(_func) {}
SquirrelFunction(const SquirrelObject & _object,const SquirrelObject & _func) : v(SquirrelVM::GetVMPtr()), object(_object), func(_func) {}
SquirrelFunction(const SquirrelObject & _object,const SQChar * name) {
v = SquirrelVM::GetVMPtr();
object = _object;
func = object.GetValue(name);
}
SquirrelFunction(const SQChar * name) {
v = SquirrelVM::GetVMPtr();
object = SquirrelVM::GetRootTable();
func = object.GetValue(name);
}
// Release references and reset internal objects to null.
void reset(void) {
func.Reset();
object.Reset();
} // Reset
#define SQPLUS_CHECK_FNCALL(res) if (!SQ_SUCCEEDED(res)) throw SquirrelError(_T("SquirrelFunction<> call failed"))
RT operator()(void) {
sq_pushobject(v,func.GetObjectHandle());
sq_pushobject(v,object.GetObjectHandle());
SQPLUS_CHECK_FNCALL(sq_call(v,1,SQTrue,SQ_CALL_RAISE_ERROR));
return GetRet(TypeWrapper<RT>(),v,-1);
}
template<typename P1>
RT operator()(P1 p1) {
sq_pushobject(v,func.GetObjectHandle());
sq_pushobject(v,object.GetObjectHandle());
Push(v,p1);
SQPLUS_CHECK_FNCALL(sq_call(v,2,SQTrue,SQ_CALL_RAISE_ERROR));
return GetRet(TypeWrapper<RT>(),v,-1);
}
template<typename P1,typename P2>
RT operator()(P1 p1,P2 p2) {
sq_pushobject(v,func.GetObjectHandle());
sq_pushobject(v,object.GetObjectHandle());
Push(v,p1);
Push(v,p2);
SQPLUS_CHECK_FNCALL(sq_call(v,3,SQTrue,SQ_CALL_RAISE_ERROR));
return GetRet(TypeWrapper<RT>(),v,-1);
}
template<typename P1,typename P2,typename P3>
RT operator()(P1 p1,P2 p2,P3 p3) {
sq_pushobject(v,func.GetObjectHandle());
sq_pushobject(v,object.GetObjectHandle());
Push(v,p1);
Push(v,p2);
Push(v,p3);
SQPLUS_CHECK_FNCALL(sq_call(v,4,SQTrue,SQ_CALL_RAISE_ERROR));
return GetRet(TypeWrapper<RT>(),v,-1);
}
template<typename P1,typename P2,typename P3,typename P4>
RT operator()(P1 p1,P2 p2,P3 p3,P4 p4) {
sq_pushobject(v,func.GetObjectHandle());
sq_pushobject(v,object.GetObjectHandle());
Push(v,p1);
Push(v,p2);
Push(v,p3);
Push(v,p4);
SQPLUS_CHECK_FNCALL(sq_call(v,5,SQTrue,SQ_CALL_RAISE_ERROR));
return GetRet(TypeWrapper<RT>(),v,-1);
}
template<typename P1,typename P2,typename P3,typename P4,typename P5>
RT operator()(P1 p1,P2 p2,P3 p3,P4 p4,P5 p5) {
sq_pushobject(v,func.GetObjectHandle());
sq_pushobject(v,object.GetObjectHandle());
Push(v,p1);
Push(v,p2);
Push(v,p3);
Push(v,p4);
Push(v,p5);
SQPLUS_CHECK_FNCALL(sq_call(v,6,SQTrue,SQ_CALL_RAISE_ERROR));
return GetRet(TypeWrapper<RT>(),v,-1);
}
template<typename P1,typename P2,typename P3,typename P4,typename P5,typename P6>
RT operator()(P1 p1,P2 p2,P3 p3,P4 p4,P5 p5,P6 p6) {
sq_pushobject(v,func.GetObjectHandle());
sq_pushobject(v,object.GetObjectHandle());
Push(v,p1);
Push(v,p2);
Push(v,p3);
Push(v,p4);
Push(v,p5);
Push(v,p6);
SQPLUS_CHECK_FNCALL(sq_call(v,7,SQTrue,SQ_CALL_RAISE_ERROR));
return GetRet(TypeWrapper<RT>(),v,-1);
}
template<typename P1,typename P2,typename P3,typename P4,typename P5,typename P6,typename P7>
RT operator()(P1 p1,P2 p2,P3 p3,P4 p4,P5 p5,P6 p6,P7 p7) {
sq_pushobject(v,func.GetObjectHandle());
sq_pushobject(v,object.GetObjectHandle());
Push(v,p1);
Push(v,p2);
Push(v,p3);
Push(v,p4);
Push(v,p5);
Push(v,p6);
Push(v,p7);
SQPLUS_CHECK_FNCALL(sq_call(v,8,SQTrue,SQ_CALL_RAISE_ERROR));
return GetRet(TypeWrapper<RT>(),v,-1);
}
};
// === Class/Struct registration ===
#define SQ_DELETE_CLASS(CLASSTYPE) if (up) { CLASSTYPE * self = (CLASSTYPE *)up; delete self;} return 0
#define SQ_DECLARE_RELEASE(CLASSTYPE) \
static int release(SQUserPointer up,SQInteger size) { \
SQ_DELETE_CLASS(CLASSTYPE); \
}
template<typename T>
struct ReleaseClassPtrPtr {
static int release(SQUserPointer up,SQInteger size) {
if (up) {
T ** self = (T **)up;
delete *self;
} // if
return 0;
} // release
};
template<typename T>
struct ReleaseClassPtr {
static int release(SQUserPointer up,SQInteger size) {
if (up) {
T * self = (T *)up;
delete self;
} // if
return 0;
} // release
};
BOOL CreateClass(HSQUIRRELVM v,SquirrelObject & newClass,SQUserPointer classType,const SQChar * name,const SQChar * baseName=0);
#define SQ_ANCESTOR_CLASS_INDEX _T("__ci")
// Call PostConstruct() at the end of custom constructors.
template<typename T>
inline int PostConstruct(HSQUIRRELVM v,T * newClass,SQRELEASEHOOK hook) {
#ifdef SQ_USE_CLASS_INHERITANCE
StackHandler sa(v);
HSQOBJECT ho = sa.GetObjectHandle(1); // OT_INSTANCE
SquirrelObject instance(ho);
INT classIndex = instance.GetValue(SQ_ANCESTOR_CLASS_INDEX).ToInteger();
if (classIndex == -1) { // Is this the most-derived C/C++ class? If so, create all ancestors (if present).
SquirrelObject newObjectTable = SquirrelVM::CreateTable(); // 11/2/05: Create a new table for this instance.
newObjectTable.SetUserPointer(INT((size_t)ClassType<T>::type()),newClass); // <TODO> 64-bit compatible version.
instance.SetValue(SQ_CLASS_OBJECT_TABLE_NAME,newObjectTable);
SquirrelObject classHierArray = instance.GetValue(SQ_CLASS_HIER_ARRAY);
INT count = classHierArray.Len();
if (count > 1) { // This will be true when more than one C/C++ class is in the hierarchy.
--count; // Skip the most-derived class.
for (INT i=0; i < count; i++) {
#ifdef CPP_STYLE_INHERITANCE // Kamaitati's changes for C++ inheritance support. jcs 5/28/06
SquirrelObject so = classHierArray.GetValue(i);
sq_pushobject(v,so.GetObjectHandle());
SQUserPointer typeTag;
sq_gettypetag(v,-1,&typeTag);
newObjectTable.SetUserPointer(INT(size_t(typeTag)),newClass);
sq_poptop(v);
#else
instance.SetValue(SQ_ANCESTOR_CLASS_INDEX,i); // Store ancestor class index for recursive constructor calls to come.
INT top = sq_gettop(v);
SquirrelObject so = classHierArray.GetValue(i); // Need to create UserData struct: store pointer to class, set release hook.
SquirrelObject func = so.GetValue(_T("constructor"));
sq_pushobject(v,func.GetObjectHandle());
sq_pushobject(v,instance.GetObjectHandle()); // The 'instance' is the real Squirrel 'this' for all ancestors (as opposed to an instance created from the defining class, which does not happen).
sq_call(v,1,SQFalse,SQ_CALL_RAISE_ERROR); // Call constructor: no arguments are passed other than the 'instance'.
sq_settop(v,top);
#endif
} // for
instance.SetValue(SQ_ANCESTOR_CLASS_INDEX,SquirrelObject()); // Store an OT_NULL object to free SQ_ANCESTOR_CLASS_INDEX var.
} // if
} else { // Ancestor: Construct class and set release hook.
SquirrelObject objectTable = instance.GetValue(SQ_CLASS_OBJECT_TABLE_NAME); // 11/2/05: Get the existing object table.
objectTable.SetUserPointer(INT((size_t)ClassType<T>::type()),newClass); // <TODO> 64-bit compatible version.
INT top = sq_gettop(v);
T ** ud = (T **)sq_newuserdata(v,sizeof(T *)); // Create UserData and push onto stack.
*ud = newClass;
sq_setreleasehook(v,-1,ReleaseClassPtrPtr<T>::release); // Set release hook for UserData on stack.
SquirrelObject userData;
userData.AttachToStackObject(-1);
SquirrelObject classHierArray = instance.GetValue(SQ_CLASS_HIER_ARRAY);
classHierArray.SetValue(classIndex,userData); // Replace the class entry with UserData: will be freed during most-derived class destruction.
sq_settop(v,top);
return TRUE;
} // if
#endif
sq_setinstanceup(v,1,newClass);
sq_setreleasehook(v,1,hook);
return 1;
} // PostConstruct
template<typename T>
struct ConstructReleaseClass {
static int construct(HSQUIRRELVM v) {
return PostConstruct<T>(v,new T(),release);
} // construct
SQ_DECLARE_RELEASE(T)
};
// === Helper for RegisterClassType*() ===
inline void setupClassHierarchy(SquirrelObject newClass) {
// <NOTE> New member vars cannot be added to instances (OT_INSTANCE): additions must occur on the defining class (OT_CLASS), before any instances are instantiated.
if (!newClass.Exists(SQ_CLASS_OBJECT_TABLE_NAME)) { // Will always get table from most-derived registered class.
SquirrelObject objectTable = SquirrelVM::CreateTable();
newClass.SetValue(SQ_CLASS_OBJECT_TABLE_NAME,objectTable); // Constructors must add their 'this' pointer indexed by type to this table. See PostConstruct() above.
// 11/2/05: This table will behave as a static global for each instance unless overwritten during construction (see PostConstruct() above).
} // if
SquirrelObject classHierArray;
if (!newClass.Exists(SQ_CLASS_HIER_ARRAY)) { // Will always get table from most-derived registered class.
classHierArray = SquirrelVM::CreateArray(0); // The only constructor called will be the most-derived class: this array contains all classes in the hierarchy to be constructed.
newClass.SetValue(SQ_CLASS_HIER_ARRAY,classHierArray);
} else {
classHierArray = newClass.GetValue(SQ_CLASS_HIER_ARRAY);
} // if
classHierArray.ArrayAppend(newClass); // Add the class to the hierarchy array. The array values will be released and replaced with UserData to free created ancestor classes.
newClass.SetValue(SQ_ANCESTOR_CLASS_INDEX,-1); // When the class hierarchy is created, this var will be used to help in recursively creating ancestor classes.
} // setupClassHierarchy
template<typename T>
inline SquirrelObject RegisterClassType(HSQUIRRELVM v,const SQChar * scriptClassName,const SQChar * baseScriptClassName=0) {
int top = sq_gettop(v);
SquirrelObject newClass;
if (CreateClass(v,newClass,(SQUserPointer)ClassType<T>::type(),scriptClassName,baseScriptClassName)) {
SquirrelVM::CreateFunction(newClass,&ConstructReleaseClass<T>::construct,_T("constructor"));
#ifdef SQ_USE_CLASS_INHERITANCE
setupClassHierarchy(newClass);
#endif
} // if
sq_settop(v,top);
return newClass;
} // RegisterClassType
template<typename T>
inline SquirrelObject RegisterClassTypeNoConstructor(HSQUIRRELVM v,const SQChar * scriptClassName,const SQChar * baseScriptClassName=0) {
int top = sq_gettop(v);
SquirrelObject newClass;
if (CreateClass(v,newClass,(SQUserPointer)ClassType<T>::type(),scriptClassName,baseScriptClassName)) {
#ifdef SQ_USE_CLASS_INHERITANCE
setupClassHierarchy(newClass);
#endif
} // if
sq_settop(v,top);
return newClass;
} // RegisterClassTypeNoConstructor
// === Define and register a C++ class and its members for use with Squirrel ===
// Constructors+destructors are automatically created. Custom constructors must use the
// standard SQFUNCTION signature if variable argument types are required (overloads).
// See testSqPlus2.cpp for examples.
// <NOTE> Do not use SQClassDefBase<> directly, use SQClassDef<> or SQClassDefNoConstructor<>, below.
template<typename TClassType>
struct SQClassDefBase {
HSQUIRRELVM v;
const SQChar * name;
SquirrelObject newClass;
#ifdef SQ_USE_CLASS_INHERITANCE
const SQChar * base;
// Optional base arg is the name of a base class to inherit from (must already be defined in the Squirrel VM).
SQClassDefBase(HSQUIRRELVM _v,const SQChar * _name,const SQChar * _base=0) : v(_v), name(_name), base(_base) {}
// Optional base arg is the name of a base class to inherit from (must already be defined in the Squirrel VM).
SQClassDefBase(const SQChar * _name,const SQChar * _base=0) : v(SquirrelVM::GetVMPtr()), name(_name), base(_base) {}
#else
SQClassDefBase(HSQUIRRELVM _v,const SQChar * _name) : v(_v), name(_name) {}
SQClassDefBase(const SQChar * _name) : v(SquirrelVM::GetVMPtr()), name(_name) {}
#endif
// Register a member function.
template<typename Func>
SQClassDefBase & func(Func pfunc,const SQChar * name) {
RegisterInstance(v,newClass.GetObjectHandle(),*(TClassType *)0,pfunc,name);
return *this;
} // func
// Register a variable-argument member function (supports variable+multiple return values).
// typeMask: "*" means don't check parameters, typeMask=0 means function takes no arguments (and is type checked for that case).
// All the other Squirrel type-masks are passed normally.
template<typename Func>
SQClassDefBase & funcVarArgs(Func pfunc,const SQChar * name,const SQChar * typeMask=_T("*")) {
RegisterInstanceVarArgs(v,newClass.GetObjectHandle(),*(TClassType *)0,pfunc,name,typeMask);
return *this;
} // funcVarArgs
// === BEGIN static-member+global function registration ===
// === This version is for static member functions only, such as custom constructors where 'this' is not yet valid ===
// typeMask: "*" means don't check parameters, typeMask=0 means function takes no arguments (and is type checked for that case).
// All the other Squirrel type-masks are passed normally.
template<typename Func>
SQClassDefBase & staticFuncVarArgs(Func pfunc,const SQChar * name,const SQChar * typeMask=_T("*")) {
SquirrelVM::PushObject(newClass);
SquirrelVM::CreateFunction(pfunc,name,typeMask);
SquirrelVM::Pop(1);
return *this;
} // staticFuncVarArgs
// Register a standard global function (effectively embedding a global function in TClassType's script namespace: does not need or use a 'this' pointer).
template<typename Func>
SQClassDefBase & staticFunc(Func pfunc,const SQChar * name) {
Register(v,newClass.GetObjectHandle(),pfunc,name);
return *this;
} // staticFunc
// Register a function to a pre-allocated class/struct member function: will use callee's 'this' (effectively embedding a global function in TClassType's script namespace).
template<typename Callee,typename Func>
SQClassDefBase & staticFunc(Callee & callee,Func pfunc,const SQChar * name) {
Register(v,newClass.GetObjectHandle(),callee,pfunc,name);
return *this;
} // staticFunc
// === END static+global function registration ===
// Register a member variable.
template<typename VarType>
SQClassDefBase & var(VarType TClassType::* pvar,const SQChar * name,VarAccessType access=VAR_ACCESS_READ_WRITE) {
struct CV {
VarType TClassType::* var;
} cv; // Cast Variable helper.
cv.var = pvar;
RegisterInstanceVariable(newClass,ClassType<TClassType>::type(),*(VarType **)&cv,name,access);
return *this;
} // var
// Register a member variable as a UserPointer (read only).
template<typename VarType>
SQClassDefBase & varAsUserPointer(VarType TClassType::* pvar,const SQChar * name) {
struct CV {
VarType TClassType::* var;
} cv; // Cast Variable helper.
cv.var = pvar;
RegisterInstanceVariable(newClass,ClassType<TClassType>::type(),*(SQAnything **)&cv,name,VAR_ACCESS_READ_ONLY);
return *this;
} // varAsUserPointer
template<typename VarType>
SQClassDefBase & staticVar(VarType * pvar,const SQChar * name,VarAccessType access=VAR_ACCESS_READ_WRITE) {
struct CV {
VarType * var;
} cv; // Cast Variable helper.
cv.var = pvar;
RegisterInstanceVariable(newClass,ClassType<TClassType>::type(),*(VarType **)&cv,name,VarAccessType(access|VAR_ACCESS_STATIC));
return *this;
} // staticVar
#ifdef SQPLUS_CONST_OPT
#define SQ_REG_CONST_STATIC_VAR
#include "SqPlusConst.h"
#endif
// Register a constant (read-only in script, passed by value (only INT, FLOAT, or BOOL types)).
template<typename ConstantType>
SQClassDefBase & constant(ConstantType constant,const SQChar * name) {
RegisterInstanceConstant(newClass,ClassType<TClassType>::type(),constant,name);
return *this;
} // constant
// Register an enum as an integer (read-only in script).
SQClassDefBase & enumInt(int constant,const SQChar * name) {
RegisterInstanceConstant(newClass,ClassType<TClassType>::type(),constant,name);
return *this;
} // enumInt
};
template<typename TClassType>
struct SQClassDef : public SQClassDefBase<TClassType> {
#ifdef SQ_USE_CLASS_INHERITANCE
// Optional base arg is the name of a base class to inherit from (must already be defined in the Squirrel VM).
SQClassDef(HSQUIRRELVM _v,const SQChar * _name,const SQChar * _base=0) : SQClassDefBase<TClassType>(_v,_name,_base) {
newClass = RegisterClassType<TClassType>(v,name,base);
}
// Optional base arg is the name of a base class to inherit from (must already be defined in the Squirrel VM).
SQClassDef(const SQChar * _name,const SQChar * _base=0) : SQClassDefBase<TClassType>(_name,_base) {
newClass = RegisterClassType<TClassType>(v,name,base);
}
#else
SQClassDef(HSQUIRRELVM _v,const SQChar * _name) : SQClassDefBase<TClassType>(_v,_name) {
newClass = RegisterClassType<TClassType>(v,name);
}
SQClassDef(const SQChar * _name) : SQClassDefBase<TClassType>(_name) {
newClass = RegisterClassType<TClassType>(v,name);
}
#endif
};
template<typename TClassType>
struct SQClassDefNoConstructor : public SQClassDefBase<TClassType> {
#ifdef SQ_USE_CLASS_INHERITANCE
// Optional base arg is the name of a base class to inherit from (must already be defined in the Squirrel VM).
SQClassDefNoConstructor(HSQUIRRELVM _v,const SQChar * _name,const SQChar * _base=0) : SQClassDefBase<TClassType>(_v,_name,_base) {
newClass = RegisterClassTypeNoConstructor<TClassType>(v,name,base);
}
// Optional base arg is the name of a base class to inherit from (must already be defined in the Squirrel VM).
SQClassDefNoConstructor(const SQChar * _name,const SQChar * _base=0) : SQClassDefBase<TClassType>(_name,_base) {
newClass = RegisterClassTypeNoConstructor<TClassType>(v,name,base);
}
#else
SQClassDefNoConstructor(HSQUIRRELVM _v,const SQChar * _name) : SQClassDefBase<TClassType>(_v,_name) {
newClass = RegisterClassTypeNoConstructor<TClassType>(v,name);
}
SQClassDefNoConstructor(const SQChar * _name) : SQClassDefBase<TClassType>(_name) {
newClass = RegisterClassTypeNoConstructor<TClassType>(v,name);
}
#endif
};
// === BEGIN Function Call Handlers ===
inline void Push(HSQUIRRELVM v,char value) { sq_pushinteger(v,value); }
inline void Push(HSQUIRRELVM v,unsigned char value) { sq_pushinteger(v,value); }
inline void Push(HSQUIRRELVM v,short value) { sq_pushinteger(v,value); }
inline void Push(HSQUIRRELVM v,unsigned short value) { sq_pushinteger(v,value); }
inline void Push(HSQUIRRELVM v,int value) { sq_pushinteger(v,value); }
inline void Push(HSQUIRRELVM v,unsigned int value) { sq_pushinteger(v,value); }
inline void Push(HSQUIRRELVM v,long value) { sq_pushinteger(v,value); }
inline void Push(HSQUIRRELVM v,unsigned long value) { sq_pushinteger(v,value); }
inline void Push(HSQUIRRELVM v,double value) { sq_pushfloat(v,(FLOAT)value); }
inline void Push(HSQUIRRELVM v,float value) { sq_pushfloat(v,(FLOAT)value); }
inline void Push(HSQUIRRELVM v,const SQChar * value) { sq_pushstring(v,value,-1); }
inline void Push(HSQUIRRELVM v,const SquirrelNull &) { sq_pushnull(v); }
inline void Push(HSQUIRRELVM v,SQFUNCTION value) { sq_pushuserpointer(v,(void*)value); }
inline void Push(HSQUIRRELVM v,SQAnythingPtr value) { sq_pushuserpointer(v,(void*)value); } // Cast to SQAnythingPtr instead of void * if USE_ARGUMENT_DEPENDANT_OVERLOADS can't be used by your compiler.
inline void Push(HSQUIRRELVM v,SquirrelObject & so) { sq_pushobject(v,so.GetObjectHandle()); }
#define USE_ARGUMENT_DEPENDANT_OVERLOADS
#ifdef USE_ARGUMENT_DEPENDANT_OVERLOADS
#ifdef _MSC_VER
#pragma warning (disable:4675) // Disable warning: "resolved overload was found by argument-dependent lookup" when class/struct pointers are used as function arguments.
#endif
// === BEGIN Argument Dependent Overloads ===
inline void Push(HSQUIRRELVM v,bool value) { sq_pushbool(v,value); } // Pass bool as int if USE_ARGUMENT_DEPENDANT_OVERLOADS can't be used by your compiler.
inline void Push(HSQUIRRELVM v,const void * value) { sq_pushuserpointer(v,(void*)value); } // Pass SQAnythingPtr instead of void * " "
inline void Push(HSQUIRRELVM v,const SQUserPointer & value) { sq_pushuserpointer(v,(void*)value); }
// === END Argument Dependent Overloads ===
#endif
#define SQPLUS_CHECK_GET(res) if (!SQ_SUCCEEDED(res)) throw SquirrelError(_T("sq_get*() failed (type error)"))
inline bool Match(TypeWrapper<bool>,HSQUIRRELVM v,int idx) { return sq_gettype(v,idx) == OT_BOOL; }
inline bool Match(TypeWrapper<char>,HSQUIRRELVM v,int idx) { return sq_gettype(v,idx) == OT_INTEGER; }
inline bool Match(TypeWrapper<unsigned char>,HSQUIRRELVM v, int idx) { return sq_gettype(v,idx) == OT_INTEGER; }
inline bool Match(TypeWrapper<short>,HSQUIRRELVM v,int idx) { return sq_gettype(v,idx) == OT_INTEGER; }
inline bool Match(TypeWrapper<unsigned short>,HSQUIRRELVM v,int idx) { return sq_gettype(v,idx) == OT_INTEGER; }
inline bool Match(TypeWrapper<int>,HSQUIRRELVM v,int idx) { return sq_gettype(v,idx) == OT_INTEGER; }
inline bool Match(TypeWrapper<unsigned int>,HSQUIRRELVM v,int idx) { return sq_gettype(v,idx) == OT_INTEGER; }
inline bool Match(TypeWrapper<long>,HSQUIRRELVM v,int idx) { return sq_gettype(v,idx) == OT_INTEGER; }
inline bool Match(TypeWrapper<unsigned long>,HSQUIRRELVM v,int idx) { return sq_gettype(v,idx) == OT_INTEGER; }
inline bool Match(TypeWrapper<float>,HSQUIRRELVM v,int idx) { int type = sq_gettype(v,idx); return type == OT_FLOAT; }
inline bool Match(TypeWrapper<double>,HSQUIRRELVM v,int idx) { int type = sq_gettype(v,idx); return type == OT_FLOAT; }
inline bool Match(TypeWrapper<const SQChar *>,HSQUIRRELVM v,int idx) { return sq_gettype(v,idx) == OT_STRING; }
inline bool Match(TypeWrapper<HSQUIRRELVM>,HSQUIRRELVM v,int idx) { return true; } // See Get() for HSQUIRRELVM below (v is always present).
inline bool Match(TypeWrapper<void*>,HSQUIRRELVM v,int idx) { return sq_gettype(v,idx) == OT_USERPOINTER; }
inline bool Match(TypeWrapper<SquirrelObject>,HSQUIRRELVM v,int idx) { return true; } // See sq_getstackobj(): always returns true.
inline void Get(TypeWrapper<void>,HSQUIRRELVM v,int) {}
inline bool Get(TypeWrapper<bool>,HSQUIRRELVM v,int idx) { SQBool b; SQPLUS_CHECK_GET(sq_getbool(v,idx,&b)); return b != 0; }
inline char Get(TypeWrapper<char>,HSQUIRRELVM v,int idx) { INT i; SQPLUS_CHECK_GET(sq_getinteger(v,idx,&i)); return static_cast<char>(i); }
inline unsigned char Get(TypeWrapper<unsigned char>,HSQUIRRELVM v,int idx) { INT i; SQPLUS_CHECK_GET(sq_getinteger(v,idx,&i)); return static_cast<unsigned char>(i); }
inline short Get(TypeWrapper<short>,HSQUIRRELVM v,int idx) { INT i; SQPLUS_CHECK_GET(sq_getinteger(v,idx,&i)); return static_cast<short>(i); }
inline unsigned short Get(TypeWrapper<unsigned short>,HSQUIRRELVM v,int idx) { INT i; SQPLUS_CHECK_GET(sq_getinteger(v,idx,&i)); return static_cast<unsigned short>(i); }
inline int Get(TypeWrapper<int>,HSQUIRRELVM v,int idx) { INT i; SQPLUS_CHECK_GET(sq_getinteger(v,idx,&i)); return i; }
inline unsigned int Get(TypeWrapper<unsigned int>,HSQUIRRELVM v,int idx) { INT i; SQPLUS_CHECK_GET(sq_getinteger(v,idx,&i)); return static_cast<unsigned int>(i); }
inline long Get(TypeWrapper<long>,HSQUIRRELVM v,int idx) { INT i; SQPLUS_CHECK_GET(sq_getinteger(v,idx,&i)); return static_cast<long>(i); }
inline unsigned long Get(TypeWrapper<unsigned long>,HSQUIRRELVM v,int idx) { INT i; SQPLUS_CHECK_GET(sq_getinteger(v,idx,&i)); return static_cast<unsigned long>(i); }
inline float Get(TypeWrapper<float>,HSQUIRRELVM v,int idx) { FLOAT f; SQPLUS_CHECK_GET(sq_getfloat(v,idx,&f)); return f; }
inline double Get(TypeWrapper<double>,HSQUIRRELVM v,int idx) { FLOAT f; SQPLUS_CHECK_GET(sq_getfloat(v,idx,&f)); return static_cast<double>(f); }
inline const SQChar * Get(TypeWrapper<const SQChar *>,HSQUIRRELVM v,int idx) { const SQChar * s; SQPLUS_CHECK_GET(sq_getstring(v,idx,&s)); return s; }
inline SquirrelNull Get(TypeWrapper<SquirrelNull>,HSQUIRRELVM v,int idx) { (void)v, (void)idx; return SquirrelNull(); }
inline void * Get(TypeWrapper<void *>,HSQUIRRELVM v,int idx) { SQUserPointer p; SQPLUS_CHECK_GET(sq_getuserpointer(v,idx,&p)); return p; }
inline HSQUIRRELVM Get(TypeWrapper<HSQUIRRELVM>,HSQUIRRELVM v,int /*idx*/) { sq_poptop(v); return v; } // sq_poptop(v): remove UserData from stack so GetParamCount() matches normal behavior.
inline SquirrelObject Get(TypeWrapper<SquirrelObject>,HSQUIRRELVM v,int idx) { HSQOBJECT o; SQPLUS_CHECK_GET(sq_getstackobj(v,idx,&o)); return SquirrelObject(o); }
#ifdef SQPLUS_SUPPORT_STD_STRING
inline void Push(HSQUIRRELVM v,const std::string& value) { sq_pushstring(v,value.c_str(),-1); }
inline bool Match(TypeWrapper<const std::string&>, HSQUIRRELVM v, int idx) { return sq_gettype(v,idx) == OT_STRING; }
inline std::string Get(TypeWrapper<const std::string&>,HSQUIRRELVM v,int idx) { const SQChar * s; SQPLUS_CHECK_GET(sq_getstring(v,idx,&s)); return std::string(s); }
#endif
// Added jflanglois suggestion, 8/20/06. jcs
#ifdef SQPLUS_SUPPORT_SQ_STD_STRING
typedef std::basic_string<SQChar> sq_std_string;
inline void Push(HSQUIRRELVM v,const sq_std_string & value) { sq_pushstring(v,value.c_str(),-1); }
inline bool Match(TypeWrapper<const sq_std_string &>, HSQUIRRELVM v, int idx) { return sq_gettype(v,idx) == OT_STRING; }
inline sq_std_string Get(TypeWrapper<const sq_std_string &>,HSQUIRRELVM v,int idx) { const SQChar * s; SQPLUS_CHECK_GET(sq_getstring(v,idx,&s)); return sq_std_string(s); }
#endif
// GetRet() restores the stack for SquirrelFunction<>() calls.
template<typename RT>
inline RT GetRet(TypeWrapper<RT>,HSQUIRRELVM v,int idx) { RT ret = Get(TypeWrapper<RT>(),v,idx); sq_pop(v,2); return ret; } // sq_pop(v,2): restore stack after function call.
// Specialization to support void return type.
inline void GetRet(TypeWrapper<void>,HSQUIRRELVM v,int idx) { sq_pop(v,2); }
// === END Function Call Handlers ===
// === Example SQClassDef usage (see testSqPlus2.cpp): ===
#if 0
SQClassDef<NewTestObj> sqClass(_T("NewTestObj");
sqClass.func(NewTestObj::newtestR1,_T("newtestR1"));
sqClass.var(&NewTestObj::val,_T("val"));
sqClass.var(&NewTestObj::s1,_T("s1"));
sqClass.var(&NewTestObj::s2,_T("s2"));
sqClass.funcVarArgs(&NewTestObj::multiArgs,_T("multiArgs"));
// Shorthand form:
SQClassDef<NewTestObj>(_T("NewTestObj").
func(NewTestObj::newtestR1,_T("newtestR1")).
var(&NewTestObj::val,_T("val")).
var(&NewTestObj::s1,_T("s1")).
var(&NewTestObj::s2,_T("s2")).
funcVarArgs(NewTestObj::multiArgs,_T("multiArgs"));
#endif
// === Macros for old style registration. SQClassDef registration is now easier to use (SQ_DECLARE_CLASS() is not needed) ===
#define SQ_DECLARE_CLASS(CLASSNAME) \
static int _##CLASSNAME##_release(SQUserPointer up,SQInteger size) { \
if (up) { \
CLASSNAME * self = (CLASSNAME *)up; \
delete self; \
} \
return 0; \
} \
static int _##CLASSNAME##_constructor(HSQUIRRELVM v) { \
CLASSNAME * pc = new CLASSNAME(); \
sq_setinstanceup(v,1,pc); \
sq_setreleasehook(v,1,_##CLASSNAME##_release); \
return 1; \
}
#define SQ_REGISTER_CLASS(CLASSNAME) \
RegisterClassType(SquirrelVM::GetVMPtr(),_T(#CLASSNAME),_##CLASSNAME##_constructor)
#define SQ_REGISTER_INSTANCE(NEWSQCLASS,CCLASS,FUNCNAME) \
RegisterInstance(SquirrelVM::GetVMPtr(),NEWSQCLASS.GetObjectHandle(),*(CCLASS *)0,&CCLASS::FUNCNAME,_T(#FUNCNAME));
#define SQ_REGISTER_INSTANCE_VARARGS(NEWSQCLASS,CCLASS,FUNCNAME) \
RegisterInstanceVarArgs(SquirrelVM::GetVMPtr(),NEWSQCLASS.GetObjectHandle(),*(CCLASS *)0,&CCLASS::FUNCNAME,_T(#FUNCNAME));
#define SQ_REGISTER_INSTANCE_VARIABLE(NEWSQCLASS,CCLASS,VARNAME) \
RegisterInstanceVariable(NEWSQCLASS,&((CCLASS *)0)->VARNAME,_T(#VARNAME));
#if defined(USE_ARGUMENT_DEPENDANT_OVERLOADS) && defined(_MSC_VER)
#pragma warning (default:4675)
#endif
}; // namespace SqPlus
#endif //_SQ_PLUS_H_
| [
"kingbazoka@dd2cdab4-e961-11dd-9059-71fac19e68c6"
] | [
[
[
1,
2008
]
]
] |
8d63b57e02600c43a18a8279affd65c47d8ea1dd | 729f72df96cd6f816d3a100b8b1346c98ba72457 | /source/FlourOpenGL.cpp | 737c4157d1656e1901ee3698276894eed558b33a | [] | no_license | yhzhu/flour | e2459c10a05bbb8e03fa2b18b61116825f91f36b | 10424d1ec6490cf8a07705beb6507201c36dcfbc | refs/heads/master | 2021-01-18T03:13:40.892264 | 2010-04-11T17:11:17 | 2010-04-11T17:11:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,068 | cpp | /** File: FlourOpenGL.cpp
Created on: 11-Sept-09
Author: Robin Southern "betajaen"
Copyright (c) 2009 Robin Southern
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "FlourOpenGL.h"
#include "Flour.h"
#include "FlourFlowerFile.h"
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <windows.h>
#include <GL/glut.h>
#include <NxOgre.h>
#include <AntTweakBar.h>
namespace N = NxOgre;
namespace E = NxOgre::Enums;
OpenGL* gOpenGL_WorkingTool = 0;
unsigned int gOpenGL_LastMousePositionX = 0;
unsigned int gOpenGL_LastMousePositionY = 0;
unsigned int gOpenGL_LastMouseButton = 0;
bool gOpenGL_MouseButtonDown = false;
bool gOpenGL_MouseButtonJustDown = false;
void TW_CALL callQuitTW(void*)
{
TwTerminate();
delete Flour::getInstance();
}
void OpenGL_RenderCallback()
{
gOpenGL_WorkingTool->renderOnce();
}
void OpenGL_IdleCallback()
{
glutPostRedisplay();
}
void OpenGL_ExitCallback()
{
callQuitTW(0);
}
void OpenGL_KeyboardCallback(unsigned char key, int x, int y)
{
if (TwEventKeyboardGLUT(key, x, y))
return;
gOpenGL_WorkingTool->onKeyCallback(key);
gOpenGL_WorkingTool->onKeyEvent(key);
}
void OpenGL_MouseCallback(int button, int state, int x, int y)
{
if (TwEventMouseButtonGLUT(button, state, x, y))
return;
gOpenGL_MouseButtonDown = (state == GLUT_DOWN);
if (state == GLUT_DOWN)
{
gOpenGL_LastMouseButton = button;
gOpenGL_LastMousePositionX = x;
gOpenGL_LastMousePositionY = y;
gOpenGL_MouseButtonJustDown = true;
gOpenGL_WorkingTool->onMouseButtonEvent(gOpenGL_LastMouseButton = button, x, y);
}
}
void OpenGL_MotionCallback(int x, int y)
{
if (TwEventMouseMotionGLUT(x,y))
return;
if (gOpenGL_MouseButtonDown && gOpenGL_MouseButtonJustDown)
{
gOpenGL_MouseButtonJustDown = false;
gOpenGL_LastMousePositionX = x;
gOpenGL_LastMousePositionY = y;
}
if (gOpenGL_MouseButtonDown)
{
int deltaX = gOpenGL_LastMousePositionX - x;
int deltaY = gOpenGL_LastMousePositionY - y;
gOpenGL_WorkingTool->onMouseDragEvent(gOpenGL_LastMouseButton, deltaX, deltaY);
gOpenGL_LastMousePositionX = x;
gOpenGL_LastMousePositionY = y;
}
}
void OpenGL_PassiveMotionCallback(int x, int y)
{
if (TwEventMouseMotionGLUT(x,y))
return;
if (gOpenGL_MouseButtonDown && gOpenGL_MouseButtonJustDown)
{
gOpenGL_MouseButtonJustDown = false;
gOpenGL_LastMousePositionX = x;
gOpenGL_LastMousePositionY = y;
}
if (gOpenGL_MouseButtonDown)
{
int deltaX = gOpenGL_LastMousePositionX - x;
int deltaY = gOpenGL_LastMousePositionY - y;
gOpenGL_WorkingTool->onMouseDragEvent(gOpenGL_LastMouseButton, deltaX, deltaY);
gOpenGL_LastMousePositionX = x;
gOpenGL_LastMousePositionY = y;
}
}
void getColour(unsigned col, float &r, float &g, float &b)
{
b = float( col & 0xFF) / 255.0f;
g = float((col >> 8) & 0xFF) / 255.0f;
r = float((col >> 16) & 0xFF) / 255.0f;
}
OpenGL::OpenGL()
: mWorld(0),
mScene(0),
mNextColour(0),
mNextBodiesID(0)
{
mColours.push_back(0xffefd5);
mColours.push_back(0xd2691e);
mColours.push_back(0xfff0f5);
mColours.push_back(0xffdab9);
mColours.push_back(0xff7f50);
mColours.push_back(0x7cfc00);
mColours.push_back(0xf0f8ff);
mColours.push_back(0xdcdcdc);
mColours.push_back(0xfffaf0);
mColours.push_back(0xc71585);
mColours.push_back(0xf5f5f5);
mColours.push_back(0x228b22);
mColours.push_back(0xffe4b5);
mColours.push_back(0x00ffff);
mColours.push_back(0xffd700);
mColours.push_back(0xffdead);
mColours.push_back(0x7fffd4);
mColours.push_back(0xdaa520);
mColours.push_back(0x191970);
mColours.push_back(0xffff00);
mColours.push_back(0xff00ff);
mColours.push_back(0xf5fffa);
mColours.push_back(0xfaebd7);
mColours.push_back(0xf8f8ff);
mColours.push_back(0x000080);
mColours.push_back(0xf0ffff);
mColours.push_back(0x808080);
mColours.push_back(0xfdf5e6);
mColours.push_back(0xf5f5dc);
mColours.push_back(0x008000);
mColours.push_back(0x808000);
mColours.push_back(0xffe4e1);
mColours.push_back(0xee82ee);
mColours.push_back(0x1e90ff);
mColours.push_back(0x00fa9a);
mColours.push_back(0xf5deb3);
mColours.push_back(0xb22222);
mColours.push_back(0x48d1cc);
mColours.push_back(0xffffff);
mColours.push_back(0xffe4c4);
mColours.push_back(0xadff2f);
mColours.push_back(0x6b8e23);
mColours.push_back(0x000000);
mColours.push_back(0xff4500);
mColours.push_back(0x0000ff);
mColours.push_back(0xff69b4);
mColours.push_back(0xda70d6);
mColours.push_back(0x8a2be2);
mColours.push_back(0xcd5c5c);
mColours.push_back(0xeee8aa);
mColours.push_back(0xa52a2a);
mColours.push_back(0x4b0082);
mColours.push_back(0x98fb98);
mColours.push_back(0xa0522d);
mColours.push_back(0xff8c00);
mColours.push_back(0x778899);
mColours.push_back(0xc0c0c0);
mColours.push_back(0x9932cc);
mColours.push_back(0xb0c4de);
mColours.push_back(0x87ceeb);
mColours.push_back(0x8b0000);
mColours.push_back(0xffffe0);
mColours.push_back(0x808080);
mColours.push_back(0x5f9ea0);
mColours.push_back(0xf0e68c);
mColours.push_back(0xdb7093);
mColours.push_back(0x7fff00);
mColours.push_back(0xdeb887);
mColours.push_back(0xfffff0);
mColours.push_back(0xafeeee);
mColours.push_back(0xfff8dc);
mColours.push_back(0xadd8e6);
mColours.push_back(0x778899);
mColours.push_back(0xe6e6fa);
mColours.push_back(0xcd853f);
mColours.push_back(0x6495ed);
mColours.push_back(0xfffacd);
mColours.push_back(0xffc0cb);
mColours.push_back(0xffa500);
mColours.push_back(0xffebcd);
mColours.push_back(0xf0fff0);
mColours.push_back(0x6a5acd);
mColours.push_back(0xe9967a);
mColours.push_back(0x00ff00);
mColours.push_back(0x708090);
mColours.push_back(0x8fbc8f);
mColours.push_back(0x32cd32);
mColours.push_back(0xdda0dd);
mColours.push_back(0xdc143c);
mColours.push_back(0xf08080);
mColours.push_back(0xb0e0e6);
mColours.push_back(0x00ffff);
mColours.push_back(0xe0ffff);
mColours.push_back(0x800080);
mColours.push_back(0x00008b);
mColours.push_back(0xfafad2);
mColours.push_back(0xff0000);
mColours.push_back(0x008b8b);
mColours.push_back(0xd3d3d3);
mColours.push_back(0x006400);
mColours.push_back(0xffb6c1);
mColours.push_back(0xfa8072);
mColours.push_back(0xbc8f8f);
mColours.push_back(0xb8860b);
mColours.push_back(0xfffafa);
mColours.push_back(0x2f4f4f);
mColours.push_back(0xff00ff);
mColours.push_back(0x00ff7f);
mColours.push_back(0x2f4f4f);
mColours.push_back(0x800000);
mColours.push_back(0x4682b4);
mColours.push_back(0x00ced1);
mColours.push_back(0x66cdaa);
mColours.push_back(0xd2b48c);
mColours.push_back(0x9400d3);
mColours.push_back(0x90ee90);
mColours.push_back(0x4169e1);
mColours.push_back(0xa9a9a9);
mColours.push_back(0xd3d3d3);
mColours.push_back(0x8b4513);
mColours.push_back(0xa9a9a9);
mColours.push_back(0xffa07a);
mColours.push_back(0xf4a460);
mColours.push_back(0xbdb76b);
mColours.push_back(0x20b2aa);
mColours.push_back(0x2e8b57);
mColours.push_back(0x8b008b);
mColours.push_back(0x87cefa);
mColours.push_back(0xfff5ee);
mColours.push_back(0x556b2f);
mColours.push_back(0x708090);
mColours.push_back(0x483d8b);
mColours.push_back(0xfaf0e6);
mColours.push_back(0x0000cd);
mColours.push_back(0x008080);
mColours.push_back(0xff1493);
mColours.push_back(0xba55d3);
mColours.push_back(0xd8bfd8);
mColours.push_back(0x00bfff);
mColours.push_back(0x9370db);
mColours.push_back(0xff6347);
mColours.push_back(0x696969);
mColours.push_back(0x3cb371);
mColours.push_back(0x40e0d0);
mColours.push_back(0x696969);
mColours.push_back(0x7b68ee);
mColours.push_back(0x9acd32);
Flour::getInstance()->initNxOgre();
mWorld = N::World::getWorld();
}
OpenGL::~OpenGL()
{
if (mScene)
mWorld->destroyScene(mScene);
// Delete Bodies and Scene here.
if (mBodies.size())
{
for (unsigned int i=0;i < mBodies.size();i++)
delete mBodies[i];
}
}
void OpenGL::createWindow(const std::string& window_caption, unsigned int width, unsigned int height, WindowIcon icon)
{
glutInitWindowSize(width, height);
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH);
mWindowHandle = glutCreateWindow(window_caption.c_str());
glutSetWindow(mWindowHandle);
glutDisplayFunc(OpenGL_RenderCallback);
glutIdleFunc(OpenGL_IdleCallback);
glutKeyboardFunc(OpenGL_KeyboardCallback);
glutMouseFunc(OpenGL_MouseCallback);
glutMotionFunc(OpenGL_MotionCallback);
glutPassiveMotionFunc(OpenGL_PassiveMotionCallback);
atexit(OpenGL_ExitCallback);
glClearColor(0.1337f, 0.1337f, 0.1337f, 0.1337f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glShadeModel(GL_SMOOTH);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
// Enable light and set up 2 light sources (GL_LIGHT0 and GL_LIGHT1)
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_LIGHT1);
// We're setting up two light sources. One of them is located
// on the left side of the model (x = -1.5f) and emits white light. The
// second light source is located on the right side of the model (x = 1.5f)
// emitting red light.
// GL_LIGHT0: the white light emitting light source
// Create light components for GL_LIGHT0
float ambientLight0[] = { 0.2f, 0.2f, 0.2f, 1.0f };
float diffuseLight0[] = { 0.8f, 0.8f, 0.8f, 1.0f };
float specularLight0[] = { 0.5f, 0.5f, 0.5f, 1.0f };
float position0[] = { -25, 15, -25, 1.0f };
// Assign created components to GL_LIGHT0
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight0);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight0);
glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight0);
glLightfv(GL_LIGHT0, GL_POSITION, position0);
mCamera = NxOgre::Vec3::ZERO;
mCameraTarget = NxOgre::Vec3::ZERO;
#ifdef _WIN32
HWND wnd = WindowFromDC(wglGetCurrentDC());
HINSTANCE hInst = (HINSTANCE)GetModuleHandle(NULL);
SetClassLong ( wnd , GCL_HICON, (LONG)LoadIcon (hInst, MAKEINTRESOURCE (icon)));
#else
// ...
#endif
TwInit(TW_OPENGL, NULL);
TwWindowSize(width, height);
mBar = TwNewBar("Flour");
TwDefine(" Flour color='32 32 32' alpha=64 text=light ");
TwDefine(" GLOBAL fontsize=2 ");
TwDefine(" Flour refresh=0.016 ");
TwDefine(" Flour iconifiable=false ");
TwDefine(" GLOBAL fontresizable=false ");
}
void OpenGL::createScene(const N::Vec3& gravity, bool useHardware, bool groundPlane)
{
N::SceneDescription scene_d;
scene_d.mUseHardware = useHardware;
scene_d.mGravity = gravity;
mScene = mWorld->createScene(scene_d);
mScene->getMaterial(0)->setStaticFriction(0.5);
mScene->getMaterial(0)->setDynamicFriction(0.5);
if (groundPlane)
mScene->createSceneGeometry(new N::PlaneGeometry(0, N::Vec3(0, 1, 0)));
}
N::Mesh* OpenGL::createMesh(const std::string &path)
{
boost::filesystem::path mesh_path(path);
if (mesh_path.extension() == ".flower") // Cook the file internally.
return Flour::getInstance()->getFile(".flower")->get(path);
else if (mesh_path.extension() == ".nxs")
return Flour::getInstance()->getFile(".nxs")->get(path);
else
return 0;
}
Body* OpenGL::createBody(const std::string& mesh_path, float mass, const N::Matrix44& pose)
{
N::Mesh* mesh = createMesh(mesh_path);
if (mesh == 0)
return 0;
Body* body = new Body();
body->mActor = 0;
body->mSceneGeometry = 0;
body->mPose = pose;
body->mMesh = mesh;
N::RigidBodyDescription rbody_d;
rbody_d.mMass = mass;
N::Shape* shape = 0;
if (mesh->getType() == E::MeshType_Convex)
{
shape = new N::Convex(mesh);
}
else if (mesh->getType() == E::MeshType_Triangle)
{
shape = new N::TriangleGeometry(mesh);
rbody_d.mMass = 0;
}
if (shape == 0)
return 0;
if (rbody_d.mMass)
body->mActor = mScene->createActor(shape, pose, rbody_d);
else
body->mSceneGeometry = mScene->createSceneGeometry(shape, pose, rbody_d);
N::MeshData* mesh_data = body->mMesh->getMeshData();
body->parse(mesh_data);
delete mesh_data;
int colour = mColours[mNextColour++];
if (mNextColour == mColours.size())
mNextColour = 0;
body->mID = mNextBodiesID++;
getColour(colour, body->mRed, body->mGreen, body->mBlue);
mBodies.push_back(body);
return body;
}
void OpenGL::startRendering()
{
gOpenGL_WorkingTool = this;
mWorkingBodyIndex = 0;
glutMainLoop();
}
void OpenGL::renderOnce()
{
onPreFrame();
//////////////////////////////////////////////////////////////
N::TimeController::getSingleton()->advance();
//////////////////////////////////////////////////////////////
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f, (float)glutGet(GLUT_WINDOW_WIDTH)/(float)glutGet(GLUT_WINDOW_HEIGHT), 0.1f, 1000.0f);
N::Vec3 origin;
if (mWorkingBodyIndex > mBodies.size())
mWorkingBodyIndex = 0;
if (mBodies.size())
{
Body* body = mBodies[mWorkingBodyIndex];
if (body->mActor)
origin = body->mActor->getGlobalPosition();
else if (body->mSceneGeometry)
origin = body->mSceneGeometry->getGlobalPosition();
}
else
origin = N::Vec3::ZERO;
gluLookAt(origin.x + mCamera.x, origin.y + mCamera.y, origin.z + mCamera.z, origin.x + mCameraTarget.x, origin.y + mCameraTarget.y, origin.z + mCameraTarget.z, 0.0f, 1.0f, 0.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//////////////////////////////////////////////////////////////
glDisable(GL_LIGHTING);
drawGrid();
glEnable(GL_LIGHTING);
//////////////////////////////////////////////////////////////
for (unsigned int i=0;i < mBodies.size();i++)
{
mBodies[i]->draw();
}
//////////////////////////////////////////////////////////////
onPostFrame();
//////////////////////////////////////////////////////////////
TwDraw();
//////////////////////////////////////////////////////////////
glutSwapBuffers();
}
void OpenGL::onPreFrame()
{
// virtual
}
void OpenGL::onPostFrame()
{
// virtual
}
void OpenGL::resetBodies()
{
for (unsigned int i=0;i < mBodies.size();i++)
{
if (mBodies[i]->mActor)
{
mBodies[i]->mActor->setLinearMomentum(N::Vec3(0,0,0));
mBodies[i]->mActor->setAngularMomentum(N::Vec3(0,0,0));
mBodies[i]->mActor->setGlobalPose(mBodies[i]->mPose);
}
}
}
N::Actor* OpenGL::getSelectedActor()
{
if (mBodies.size() == 0)
return 0;
if (mWorkingBodyIndex > mBodies.size())
return 0;
Body* body = mBodies[mWorkingBodyIndex];
if (body->mSceneGeometry)
return 0;
return body->mActor;
}
void OpenGL::orbitCamera(float& yaw, float& pitch, float& distance)
{
if (yaw < -bml::Pi)
yaw = bml::Pi;
else if (yaw > bml::Pi)
yaw = -bml::Pi;
if (pitch < 0)
pitch = 0;
else if (pitch > 1.2f)
pitch = 1.2f;
mCamera.x = sin(yaw) * distance;
mCamera.y = tan(pitch) * distance;
mCamera.z = cos(yaw) * distance;
}
void OpenGL::drawGrid()
{
glPushMatrix();
glBegin(GL_LINES);
for(int i=0;i<=50;i++)
{
if (i==25)
glColor3f(.3,.3,.6);
else
glColor3f(.2,.2,.2);
glVertex3f(-25 + i,0,-25);
glVertex3f(-25 + i,0,25);
if (i==25)
glColor3f(.6,.3,.3);
else
glColor3f(.2,.2,.2);
glVertex3f(-25,0,-25 + i);
glVertex3f(25,0,-25 + i);
}
glColor3f(.3,.6,.3);
glVertex3f(0,0,0);
glColor3f(.3,.6,.3);
glVertex3f(0,1,0);
glEnd();
glPopMatrix();
}
void OpenGL::onKeyEvent(char key)
{
// virtual
}
void OpenGL::onMouseDragEvent(int ButtonID, int deltaX, int deltaY)
{
// virtual
}
void OpenGL::onMouseButtonEvent(int ButtonID, int x, int y)
{
// virtual
}
void OpenGL::onKeyCallback(char key)
{
if (key == 27)
{
exit(0);
return;
}
if (key == '[' || key == ']')
{
if (mBodies.size() == 0 || mWorkingBodyIndex > mBodies.size() - 1)
{
mWorkingBodyIndex = 0;
return;
}
if (key == '[')
{
if (mWorkingBodyIndex == 0)
mWorkingBodyIndex = mBodies.size() - 1;
else
mWorkingBodyIndex--;
}
else
{
if (mWorkingBodyIndex == mBodies.size() - 1)
mWorkingBodyIndex = 0;
else
mWorkingBodyIndex++;
}
}
}
void OpenGL_Triangle::calculateNormal()
{
N::Vec3 n, m;
n.x = a.x - b.x;
n.y = a.y - b.y;
n.z = a.z - b.z;
m.x = b.x - c.x;
m.y = b.y - c.y;
m.z = b.z - c.z;
normal.x = (n.y * m.z) - (n.z * m.y);
normal.y = (n.z * m.x) - (n.x * m.z);
normal.z = (n.x * m.y) - (n.y * m.x);
normal.normalise();
}
void Body::parse(N::MeshData* mesh_data)
{
unsigned int index_a = 0, index_b = 0, index_c = 0;
N::Vec3 vertex_a, vertex_b, vertex_c;
for (unsigned int i=0; i < mesh_data->mIndexes.size();i+=3)
{
index_a = mesh_data->mIndexes[i];
index_b = mesh_data->mIndexes[i+1];
index_c = mesh_data->mIndexes[i+2];
OpenGL_Triangle triangle;
triangle.a.x = mesh_data->mVertices[(index_a * 3)];
triangle.a.y = mesh_data->mVertices[(index_a * 3) + 1];
triangle.a.z = mesh_data->mVertices[(index_a * 3) + 2];
triangle.b.x = mesh_data->mVertices[(index_b * 3)];
triangle.b.y = mesh_data->mVertices[(index_b * 3) + 1];
triangle.b.z = mesh_data->mVertices[(index_b * 3) + 2];
triangle.c.x = mesh_data->mVertices[(index_c * 3)];
triangle.c.y = mesh_data->mVertices[(index_c * 3) + 1];
triangle.c.z = mesh_data->mVertices[(index_c * 3) + 2];
triangle.calculateNormal();
mTriangles.push_back(triangle);
}
}
void Body::draw()
{
glLoadIdentity();
glPushMatrix();
float glMat[16];
if (mActor)
mActor->getGlobalPose().columnMajor(glMat);
else if (mSceneGeometry)
mSceneGeometry->getGlobalPose().columnMajor(glMat);
glMultMatrixf(glMat);
glBegin(GL_TRIANGLES);
float no_mat[] = {0.0f, 0.0f, 0.0f, 1.0f};
float mat_ambient[] = {0.7f, 0.7f, 0.7f, 1.0f};
float mat_ambient_color[] = {mRed, mGreen, mBlue, 1.0f};
float mat_diffuse[] = {0.5f, 0.5f, 0.5f, 1.0f};
float mat_specular[] = {1.0f, 1.0f, 1.0f, 1.0f};
float no_shininess = 0.0f;
float low_shininess = 5.0f;
float high_shininess = 100.0f;
float mat_emission[] = {0.3f, 0.2f, 0.2f, 0.0f};
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient_color);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialf(GL_FRONT, GL_SHININESS, high_shininess);
glMaterialfv(GL_FRONT, GL_EMISSION, no_mat);
for (std::vector<OpenGL_Triangle>::iterator it = mTriangles.begin(); it != mTriangles.end(); it++)
{
glNormal3f((*it).normal.x, (*it).normal.y, (*it).normal.z);
glVertex3f((*it).a.x, (*it).a.y, (*it).a.z);
glVertex3f((*it).b.x, (*it).b.y, (*it).b.z);
glVertex3f((*it).c.x, (*it).c.y, (*it).c.z);
}
glEnd();
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
glLineWidth(2.0f);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LINE_SMOOTH);
for (std::vector<OpenGL_Triangle>::iterator it = mTriangles.begin(); it != mTriangles.end(); it++)
{
glColor3f(0,0,0);
glVertex3f((*it).a.x * 1.01f, (*it).a.y * 1.01f, (*it).a.z * 1.01f);
glVertex3f((*it).b.x * 1.01f, (*it).b.y * 1.01f, (*it).b.z * 1.01f);
glVertex3f((*it).c.x * 1.01f, (*it).c.y * 1.01f, (*it).c.z * 1.01f);
glVertex3f((*it).a.x * 1.01f, (*it).a.y * 1.01f, (*it).a.z * 1.01f);
//glVertex3f((*it).a.x+(*it).normal.x, (*it).a.y+(*it).normal.y, (*it).a.z+(*it).normal.z);
}
glDisable(GL_LINE_SMOOTH);
glDisable(GL_COLOR_MATERIAL);
glEnd();
glEnable(GL_LIGHTING);
glPopMatrix();
}
| [
"[email protected]"
] | [
[
[
1,
820
]
]
] |
a1936d0615ee33c205de9abceb9f5cdf44cfbbe9 | d6eba554d0c3db3b2252ad34ffce74669fa49c58 | /Source/States/gameState.h | 67beb742540b5005450b785437d3a5342011312d | [] | no_license | nbucciarelli/Polarity-Shift | e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10 | 8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017 | refs/heads/master | 2016-09-11T00:24:32.906933 | 2008-09-26T18:01:01 | 2008-09-26T18:01:01 | 3,408,115 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,147 | h | #pragma once
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File: “gameState.h”
// Author: Scott Smallback (SS)
// Purpose: The interface for game states
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class gameState
{
protected:
volatile bool entered, rendering;
gameState() : entered(false), rendering(false) {}
public:
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “Deconstructor”
// Last modified: August 27, 2008
// Purpose: The deconstructor for the various game states
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual ~gameState(void) = 0 {}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “enter”
// Last modified: August 27, 2008
// Purpose: Enters the various game states
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void enter(void) = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “exit”
// Last modified: August 27, 2008
// Purpose: Exits the various game states
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void exit(void) = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “input”
// Last modified: August 27, 2008
// Purpose: Input used for the various game states
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual bool input(float dt) = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “update”
// Last modified: August 27, 2008
// Purpose: Updates the various game states
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void update(float dt) = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Function: “render”
// Last modified: August 27, 2008
// Purpose: Renders the various game states
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
virtual void render(void) const = 0;
virtual void Rendering(bool set) { rendering = set; }
virtual void Entered(bool set) { entered = set; }
virtual bool Entered() const { return entered; }
}; | [
"[email protected]",
"[email protected]"
] | [
[
[
1,
1
],
[
7,
14
],
[
20,
21
],
[
27,
27
],
[
34,
35
],
[
41,
41
],
[
48,
48
],
[
55,
60
]
],
[
[
2,
6
],
[
15,
19
],
[
22,
26
],
[
28,
33
],
[
36,
40
],
[
42,
47
],
[
49,
54
]
]
] |
2f6434ba20e1cd7fcd05d1d0c058f1fc33a41a2a | 5a05acb4caae7d8eb6ab4731dcda528e2696b093 | /GameEngine/Gfx/GUI/GuiText.cpp | de0a68f6793c9ab3669a5fd99c99ebfcdc7ee4a5 | [] | no_license | andreparker/spiralengine | aea8b22491aaae4c14f1cdb20f5407a4fb725922 | 36a4942045f49a7255004ec968b188f8088758f4 | refs/heads/master | 2021-01-22T12:12:39.066832 | 2010-05-07T00:02:31 | 2010-05-07T00:02:31 | 33,547,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,304 | cpp | #include <boost/make_shared.hpp>
#include "GuiText.hpp"
#include "../SurfaceUP.hpp"
#include "../Texture.hpp"
#include "../GfxImpl.hpp"
#include "../GfxDriver.hpp"
#include "../Font.hpp"
#include "../Color.hpp"
#include "../../Resource/Resource.hpp"
#include "../../Resource/ResLockImpl.hpp"
#include "GuiWindowEvents.hpp"
using namespace Spiral;
using namespace Spiral::GUI;
using namespace boost;
const boost::uint32_t kPadHeight = 0;
GuiText::GuiText( const Math::Vector2f& position, const boost::shared_ptr<GfxDriver>& gfxDriver, const Rgba& textColor,
boost::uint32_t maxCharLen, const boost::shared_ptr<Font>& font, const wString& text, bool multiline ):
GuiWindow( position, Rect<SpReal>(), shared_ptr<Texture>(), true ), m_text( text ), m_charPos( 0 ),
m_font( font ),m_editSurface(),m_maxCharLen( maxCharLen ),m_fontColor( textColor ),m_multiline(multiline),
m_gfxDriver( gfxDriver.get() )
{
SetFont( font, gfxDriver.get() );
}
GuiText::GuiText():
GuiWindow( Math::make_vector<SpReal>(0,0) , Rect<SpReal>(), shared_ptr<Texture>(), true ),
m_text(),m_charPos(0),m_font(),m_editSurface(),m_maxCharLen(16),m_fontColor(),m_multiline(false),
m_gfxDriver(NULL)
{
}
void GuiText::DrawString( const wString& str )
{
shared_ptr< Resource > res = GetTexture()->GetResource();
ResLockRtInfo_t info;
if( res->Lock( info, false ) )
{
SurfaceUP* surf = static_cast<SurfaceUP*>( m_editSurface.get() );
surf->SetDataPtr( info.data );
m_font->RenderAlpha( m_editSurface, m_charPos, str, m_fontColor );
res->Unlock();
// report that data has changed
CallHandler( data_changed, this, boost::any() );
}
}
void GuiText::DrawChar( wChar c )
{
if( m_maxCharLen > m_text.length() )
{
m_text += c;
m_charPos = 0;
DrawString( m_text );
}
}
void GuiText::SetText( const wString& text )
{
if( m_multiline || m_maxCharLen > m_text.length() )
{
m_text = text;
UpdateBox();
}
}
void GuiText::EraseEnd()
{
if( m_text.length() )
{
m_charPos = 0;
m_text.erase( m_text.length()-1, 1 );
ClearBox();
}
DrawString( m_text );
}
void GuiText::ClearBox()
{
shared_ptr< Texture > texture = GetTexture();
if( texture )
{
shared_ptr< Resource > res = GetTexture()->GetResource();
ResLockRtInfo_t info;
if( res->Lock( info, false ) )
{
SurfaceUP* surf = static_cast<SurfaceUP*>( m_editSurface.get() );
surf->SetDataPtr( info.data );
surf->Fill( Rgba( 0.0f, 0.0f, 0.0f, 0.0f ) );
res->Unlock();
}
}
}
void GuiText::SetFont( const boost::shared_ptr< Font >& font, GfxDriver* gfxDriver )
{
m_font = font;
m_gfxDriver = gfxDriver;
UpdateBox();
}
void GuiText::SetMaxCharLen( boost::uint32_t maxCharLen )
{
if( !m_multiline && m_maxCharLen != maxCharLen && m_gfxDriver )
{
m_maxCharLen = maxCharLen;
int32_t width = m_font->GetCharWidth() * m_maxCharLen;
int32_t height = m_font->GetCharHeight() + kPadHeight;
ResizeBox(width, height);
}
}
void GuiText::ResizeBox( int32_t width, int32_t height )
{
shared_ptr<Texture> textTexture;
TextureInfo_t info;
info.bitDepth = 32;
info.bManaged = false;
info.width = width;
info.height = height;
m_gfxDriver->CreateTexture( info, textTexture );
m_editSurface = make_surfaceUP( textTexture->GetWidth(), textTexture->GetHeight(), 4, NULL );
Rect<SpReal> texCoords( 0, static_cast<SpReal>(width)/textTexture->GetWidth(),
static_cast<SpReal>(height)/textTexture->GetHeight(), 0 );
Rect<SpReal> rect( 0, static_cast<SpReal>(width), static_cast<SpReal>(height), 0 );
SetRect( rect );
SetTexCoords( texCoords );
SetTexture( textTexture );
Refresh();
}
void GuiText::SetFontColor( const Rgba& color )
{
m_fontColor = color;
Refresh();
}
void GuiText::Refresh()
{
if( m_font )
{
m_charPos = 0;
ClearBox();
DrawString( m_text );
}
}
void GuiText::UpdateBox()
{
if( m_font )
{
boost::int32_t width = 16;
boost::int32_t height = 16;
if( m_multiline && !m_text.empty() )
{
m_font->CalcSurfaceSize( m_text, width, height );
}else
{
width = m_font->GetCharWidth() * m_maxCharLen;
height = m_font->GetCharHeight() + kPadHeight;
}
ResizeBox( width, height );
}
} | [
"DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e"
] | [
[
[
1,
182
]
]
] |
eefb5478d64b7d77365222560c60d3fad6b313de | 1536bdbfb912d9bec8cea8c85d144033570bcb62 | /agent/browser/ie/urlBlast/URLBlaster.cpp | ab71b8777ed8df1152d81a9764f6ffe1adf92f17 | [] | no_license | sdo-ops/WebPageTest-mirror- | ad6efec365471072ce62b6ecaa4c1eb4f2808794 | 16bcff6e67a49bc84611cedd3f2d7224893ef021 | refs/heads/master | 2020-12-24T13:28:49.940398 | 2011-02-20T16:37:45 | 2011-02-20T16:37:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,002 | cpp | #include "StdAfx.h"
#include "URLBlaster.h"
#include <process.h>
#include <shlwapi.h>
#include <Userenv.h>
#include <Aclapi.h>
#include <Lm.h>
#include <WtsApi32.h>
#include "TraceRoute.h"
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
CURLBlaster::CURLBlaster(HWND hWnd, CLog &logRef)
: userName(_T(""))
, hLogonToken(NULL)
, hProfile(NULL)
, password(_T("2dialit"))
, accountBase(_T("user"))
, hThread(NULL)
, index(0)
, count(0)
, hDlg(hWnd)
, urlManager(NULL)
, testType(0)
, labID(0)
, dialerID(0)
, connectionType(0)
, timeout(60)
, experimental(0)
, sequentialErrors(0)
, screenShotErrors(0)
, browserPID(0)
, userSID(NULL)
, log(logRef)
, pipeIn(0)
, pipeOut(0)
, hDynaTrace(NULL)
, useBitBlt(0)
, winpcap(logRef)
{
InitializeCriticalSection(&cs);
hMustExit = CreateEvent(0, TRUE, FALSE, NULL );
hClearedCache = CreateEvent(0, TRUE, FALSE, NULL );
hRun = CreateEvent(0, TRUE, FALSE, NULL );
srand(GetTickCount());
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
CURLBlaster::~CURLBlaster(void)
{
SetEvent(hMustExit);
// wait for the thread to exit (up to double the timeout value)
if( hThread )
{
if( WaitForSingleObject(hThread, timeout * 2 * 1000) == WAIT_TIMEOUT )
TerminateThread(hThread, 0);
CloseHandle(hThread);
}
if( hLogonToken )
{
if( hProfile )
UnloadUserProfile( hLogonToken, hProfile );
CloseHandle( hLogonToken );
}
CloseHandle( hMustExit );
CloseHandle( hClearedCache );
CloseHandle( hRun );
EnterCriticalSection(&cs);
if( userSID )
{
HeapFree(GetProcessHeap(), 0, (LPVOID)userSID);
userSID = 0;
}
LeaveCriticalSection(&cs);
DeleteCriticalSection(&cs);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
static unsigned __stdcall ThreadProc( void* arg )
{
CURLBlaster * blaster = (CURLBlaster *)arg;
if( blaster )
blaster->ThreadProc();
return 0;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
bool CURLBlaster::Start(int userIndex)
{
bool ret = false;
// store off which user this worker belongs to
index = userIndex;
userName.Format(_T("%s%d"), (LPCTSTR)accountBase, index);
info.userName = userName;
// default directories
TCHAR path[MAX_PATH];
DWORD len = _countof(path);
CString profiles = _T("C:\\Documents and Settings");
if( GetProfilesDirectory(path, &len) )
profiles = path;
profiles += _T("\\");
profile = profiles + userName;
cookies = profile + _T("\\Cookies");
history = profile + _T("\\Local Settings\\History");
tempFiles = profile + _T("\\Local Settings\\Temporary Internet Files");
silverlight = profile + _T("\\Local Settings\\Application Data\\Microsoft\\Silverlight");
flash = profile + _T("\\Application Data\\Macromedia\\Flash Player\\#SharedObjects");
// Get WinPCap ready (install it if necessary)
winpcap.Initialize();
// spawn the worker thread
ResetEvent(hMustExit);
hThread = (HANDLE)_beginthreadex(0, 0, ::ThreadProc, this, 0, 0);
if( hThread )
ret = true;
return ret;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CURLBlaster::Stop(void)
{
SetEvent(hMustExit);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void CURLBlaster::ThreadProc(void)
{
if( DoUserLogon() )
{
sequentialErrors = 0;
log.Trace(_T("Waiting for startup synchronization"));
// synchronize all of the threads and don't start testing until they have all cleared out the caches (heavy disk activity)
SetEvent(hClearedCache);
WaitForSingleObject(hRun, INFINITE);
log.Trace(_T("Running..."));
// start off with IPFW in a clean state
ResetIpfw();
while( WaitForSingleObject(hMustExit,0) == WAIT_TIMEOUT )
{
// get the url to test
if( GetUrl() )
{
if( info.testType.GetLength() )
{
// running a custom test
do
{
if( !info.testType.CompareNoCase(_T("traceroute")) )
{
CTraceRoute tracert(info);
tracert.Run();
}
urlManager->UrlFinished(info);
}while( !info.done );
}
else if( !info.zipFileDir.IsEmpty() )
{
EncodeVideo();
urlManager->UrlFinished(info);
}
else
{
// loop for as many runs as are needed for the current request
do
{
ClearCache();
if( Launch(preLaunch) )
{
LaunchBrowser();
// record the cleared cache view
if( urlManager->RunRepeatView(info) )
LaunchBrowser();
Launch(postLaunch);
}
urlManager->UrlFinished(info);
}while( !info.done );
}
}
else
Sleep(500 + (rand() % 500));
}
}
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
bool CURLBlaster::DoUserLogon(void)
{
bool ret = false;
log.Trace(_T("Logging on user:%s, password:%s"), (LPCTSTR)userName, (LPCTSTR)password);
// create the account if it doesn't exist
USER_INFO_0 * userInfo = NULL;
if( !NetUserGetInfo( NULL, userName, 0, (LPBYTE *)&userInfo ) )
NetApiBufferFree(userInfo);
else
{
USER_INFO_1 info;
memset(&info, 0, sizeof(info));
wchar_t name[1000];
wchar_t pw[PWLEN];
lstrcpyW(name, CT2W(userName));
lstrcpyW(pw, CT2W(password));
info.usri1_name = name;
info.usri1_password = pw;
info.usri1_priv = USER_PRIV_USER;
info.usri1_comment = L"UrlBlast testing user account";
info.usri1_flags = UF_SCRIPT | UF_DONT_EXPIRE_PASSWD;
if( !NetUserAdd(NULL, 1, (LPBYTE)&info, NULL) )
{
CString msg;
msg.Format(_T("Created user account '%s'"), (LPCTSTR)userName);
log.LogEvent(event_Info, 0, msg);
// hide the account from the welcome screen
HKEY hKey;
if( RegCreateKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon\\SpecialAccounts\\UserList"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
DWORD val = 0;
RegSetValueEx(hKey, userName, 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegCloseKey(hKey);
}
}
else
{
CString msg;
msg.Format(_T("Failed to create user account '%s'"), (LPCTSTR)userName);
log.LogEvent(event_Error, 0, msg);
}
}
// log the user on
if( LogonUser(userName, NULL, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &hLogonToken) )
{
TCHAR szUserName[100];
lstrcpy( szUserName, (LPCTSTR)userName);
// get the SID for the account
EnterCriticalSection(&cs);
TOKEN_USER * user = NULL;
DWORD userLen = 0;
DWORD len = 0;
GetTokenInformation(hLogonToken, TokenUser, &user, userLen, &len);
if( len )
{
user = (TOKEN_USER *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len);
userLen = len;
if( user )
{
if( GetTokenInformation(hLogonToken, TokenUser, user, userLen, &len) )
{
if( user->User.Sid && IsValidSid(user->User.Sid) )
{
len = GetLengthSid(user->User.Sid);
userSID = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len);
if( userSID )
CopySid(len, userSID, user->User.Sid);
}
}
HeapFree(GetProcessHeap(), 0, (LPVOID)user);
}
}
LeaveCriticalSection(&cs);
log.Trace(_T("Logon ok, loading user profile"));
// load their profile
PROFILEINFO userProfile;
memset( &userProfile, 0, sizeof(userProfile) );
userProfile.dwSize = sizeof(userProfile);
userProfile.lpUserName = szUserName;
if( LoadUserProfile( hLogonToken, &userProfile ) )
{
hProfile = userProfile.hProfile;
log.Trace(_T("Profile loaded, locating profile directory"));
// close the IE settings from the main OS user to the URLBlast user
CloneIESettings();
// figure out where their directories are
TCHAR path[MAX_PATH];
DWORD len = _countof(path);
if( GetUserProfileDirectory(hLogonToken, path, &len) )
{
profile = path;
HKEY hKey;
if( SUCCEEDED(RegOpenKeyEx((HKEY)hProfile, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders"), 0, KEY_READ, &hKey)) )
{
len = _countof(path);
if( SUCCEEDED(RegQueryValueEx(hKey, _T("Cookies"), 0, 0, (LPBYTE)path, &len)) )
cookies = path;
len = _countof(path);
if( SUCCEEDED(RegQueryValueEx(hKey, _T("History"), 0, 0, (LPBYTE)path, &len)) )
history = path;
len = _countof(path);
if( SUCCEEDED(RegQueryValueEx(hKey, _T("Cache"), 0, 0, (LPBYTE)path, &len)) )
tempFiles = path;
len = _countof(path);
if( SUCCEEDED(RegQueryValueEx(hKey, _T("Local AppData"), 0, 0, (LPBYTE)path, &len)) )
{
silverlight = path;
silverlight += _T("\\Microsoft\\Silverlight");
}
len = _countof(path);
if( SUCCEEDED(RegQueryValueEx(hKey, _T("AppData"), 0, 0, (LPBYTE)path, &len)) )
{
flash = path;
flash += _T("\\Macromedia\\Flash Player\\#SharedObjects");
}
cookies.Replace(_T("%USERPROFILE%"), profile);
history.Replace(_T("%USERPROFILE%"), profile);
tempFiles.Replace(_T("%USERPROFILE%"), profile);
silverlight.Replace(_T("%USERPROFILE%"), profile);
flash.Replace(_T("%USERPROFILE%"), profile);
RegCloseKey(hKey);
}
}
ret = true;
}
}
else
{
log.Trace(_T("Logon failed: %d"), GetLastError());
CString msg;
msg.Format(_T("Logon failed for '%s'"), (LPCTSTR)userName);
log.LogEvent(event_Error, 0, msg);
}
if( ret )
log.Trace(_T("DoUserLogon successful for %s"), (LPCTSTR)userName);
else
log.Trace(_T("DoUserLogon failed for %s"), (LPCTSTR)userName);
return ret;
}
int cacheCount;
/*-----------------------------------------------------------------------------
Launch a process in the given user space that will delete the appropriate folders
-----------------------------------------------------------------------------*/
void CURLBlaster::ClearCache(void)
{
// delete the cookies, history and temporary internet files for this user
DeleteDirectory( cookies );
DeleteDirectory( history );
cacheCount = 0;
DeleteDirectory( tempFiles );
CString buff;
buff.Format(_T("%d files found in cache\n"), cacheCount);
OutputDebugString(buff);
DeleteDirectory( silverlight );
DeleteDirectory( flash, false );
cached = false;
}
/*-----------------------------------------------------------------------------
recursively delete the given directory
-----------------------------------------------------------------------------*/
void DeleteDirectory( LPCTSTR inPath, bool remove )
{
if( lstrlen(inPath) )
{
TCHAR * path = new TCHAR[MAX_PATH]; // allocate off of the heap so we don't blow the stack
lstrcpy( path, inPath );
PathAppend( path, _T("*.*") );
WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile(path, &fd);
if( hFind != INVALID_HANDLE_VALUE )
{
do
{
if( lstrcmp(fd.cFileName, _T(".")) && lstrcmp(fd.cFileName, _T("..")) )
{
lstrcpy( path, inPath );
PathAppend( path, fd.cFileName );
if( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
DeleteDirectory(path);
else
{
cacheCount++;
if( !DeleteFile(path) )
{
CString buff;
buff.Format(_T("Failed to delete '%s'\n"), (LPCTSTR)path);
OutputDebugString(buff);
}
}
}
}while(FindNextFile(hFind, &fd));
FindClose(hFind);
}
delete [] path;
// remove the actual directory
if( remove )
RemoveDirectory(inPath);
}
}
/*-----------------------------------------------------------------------------
Launch the browser and wait for it to exit
-----------------------------------------------------------------------------*/
bool CURLBlaster::LaunchBrowser(void)
{
bool ret = false;
info.testResult = -1;
// flush the DNS cache
FlushDNS();
if( !info.url.IsEmpty() )
{
STARTUPINFOW si;
memset(&si, 0, sizeof(si));
si.cb = sizeof(si);
if( ConfigureIpfw() )
{
if( ConfigureIE() )
{
ConfigurePagetest();
CString browser;
if( info.browser.GetLength() )
{
// check to see if the browser is in the same directory - otherwise let the path find it
browser = info.browser;
TCHAR buff[MAX_PATH];
if( GetModuleFileName(NULL, buff, _countof(buff)) )
{
lstrcpy( PathFindFileName(buff), PathFindFileName(browser) );
if( GetFileAttributes(buff) != INVALID_FILE_ATTRIBUTES )
browser = buff;
}
}
// build the launch command for IE
TCHAR exe[MAX_PATH];
TCHAR commandLine[MAX_PATH + 1024];
if( !info.url.Left(6).CompareNoCase(_T("run://")) )
{
// we're launching a custom exe
CString cmd = info.url.Mid(6);
CString options;
int index = cmd.Find(' ');
if( index > 0 )
{
options = cmd.Mid(index + 1);
cmd = cmd.Left(index);
}
cmd.Trim();
options.Trim();
// get the full path for the exe
lstrcpy(exe, cmd);
// build the command line
lstrcpy( commandLine, _T("\"") );
lstrcat( commandLine, exe );
lstrcat( commandLine, _T("\"") );
if( options.GetLength() )
lstrcat( commandLine, CString(" ") + options );
}
else if( browser.GetLength() )
{
// custom browser
lstrcpy( exe, browser );
// build the command line
lstrcpy( commandLine, _T("\"") );
lstrcat( commandLine, exe );
lstrcat( commandLine, _T("\"") );
}
else
{
// we're launching IE
SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, 0, SHGFP_TYPE_CURRENT, exe);
PathAppend(exe, _T("Internet Explorer\\iexplore.exe"));
// give it an about:blank command line for launch
lstrcpy( commandLine, _T("\"") );
lstrcat( commandLine, exe );
lstrcat( commandLine, _T("\" about:blank") );
// see if we need to launch dynaTrace
LaunchDynaTrace();
}
// start a packet capture if we need to
if( !info.tcpdumpFile.IsEmpty() )
winpcap.StartCapture(info.tcpdumpFile);
PROCESS_INFORMATION pi;
log.Trace(_T("Launching... user='%s', path='%s', command line='%s'"), (LPCTSTR)userName, (LPCTSTR)exe, (LPCTSTR)commandLine);
// launch internet explorer as our user
EnterCriticalSection(&cs);
if( CreateProcessWithLogonW(CT2W((LPCTSTR)userName), NULL, CT2W((LPCTSTR)password), 0, CT2W(exe), CT2W(commandLine), 0, NULL, NULL, &si, &pi) )
{
// keep track of the process ID for the browser we care about
browserPID = pi.dwProcessId;
LeaveCriticalSection(&cs);
// boost the browser priority
SetPriorityClass(pi.hProcess, ABOVE_NORMAL_PRIORITY_CLASS);
log.LogEvent(event_BrowserLaunch, 0, (LPCTSTR)eventName.Left(1000));
// wait for it to exit - give it up to double the timeout value
// TODO: have urlManager specify the timeout
int multiple = 2;
if( info.runningScript || info.aft )
multiple = 10;
if( WaitForSingleObject(pi.hProcess, timeout * multiple * 1000) == WAIT_OBJECT_0 )
{
count++;
cached = true;
ret = true;
if( hDlg )
PostMessage(hDlg, MSG_UPDATE_UI, 0, 0);
}
else
{
log.LogEvent(event_TerminatedBrowser, 0, (LPCTSTR)eventName.Left(1000));
TerminateProcess(pi.hProcess, 0); // kill the browser if it didn't exit on it's own
}
EnterCriticalSection(&cs);
browserPID = 0;
LeaveCriticalSection(&cs);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
// get the result
HKEY hKey;
if( RegCreateKeyEx((HKEY)hProfile, _T("SOFTWARE\\AOL\\ieWatch"), 0, 0, 0, KEY_READ | KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
DWORD len = sizeof(info.testResult);
if( RegQueryValueEx(hKey, _T("Result"), 0, 0, (LPBYTE)&info.testResult, &len) == ERROR_SUCCESS )
{
// only track sequential errors when not running a script
if( !info.runningScript )
{
if( info.testResult & 0x80000000 )
sequentialErrors++;
else
sequentialErrors = 0;
}
}
RegDeleteValue(hKey, _T("Result"));
// delete a few other keys we don't want to persist
RegDeleteValue(hKey, _T("Use Address"));
RegDeleteValue(hKey, _T("DNS Latency"));
RegCloseKey(hKey);
}
// clean up any processes that may have been spawned
KillProcs();
// see if we are running in crawler mode and collected links
if( info.harvestLinks )
urlManager->HarvestedLinks(info);
}
else
{
LeaveCriticalSection(&cs);
LPVOID lpvMessageBuffer;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpvMessageBuffer, 0, NULL);
LPCTSTR szMsg = (LPCTSTR)lpvMessageBuffer;
LocalFree(lpvMessageBuffer);
CString msg;
msg.Format(_T("Failed to launch browser '%s' - %s"), (LPCTSTR)szMsg, (LPCTSTR)exe);
log.LogEvent(event_Error, 0, msg);
SetEvent(hMustExit); // something went horribly wrong, this should never happen but don't get stuck in a loop
}
// stop the tcpdump if we started one
if( !info.tcpdumpFile.IsEmpty() )
winpcap.StopCapture();
CloseDynaTrace();
}
ResetIpfw();
}
}
return ret;
}
/*-----------------------------------------------------------------------------
Get the next url to test
-----------------------------------------------------------------------------*/
bool CURLBlaster::GetUrl(void)
{
bool ret = false;
info.Reset();
// get a new url from the central url manager
if( urlManager->GetNextUrl(info) )
{
info.eventText += customEventText;
ret = true;
}
return ret;
}
/*-----------------------------------------------------------------------------
Store the stuff pagetest needs in the registry
-----------------------------------------------------------------------------*/
void CURLBlaster::ConfigurePagetest(void)
{
if( hProfile )
{
// tell it what url to test
HKEY hKey;
if( RegCreateKeyEx((HKEY)hProfile, _T("SOFTWARE\\AOL\\ieWatch"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
RegSetValueEx(hKey, _T("url"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.url, (info.url.GetLength() + 1) * sizeof(TCHAR));
DWORD block = 1;
RegSetValueEx(hKey, _T("Block All Popups"), 0, REG_DWORD, (const LPBYTE)&block, sizeof(block));
RegSetValueEx(hKey, _T("Timeout"), 0, REG_DWORD, (const LPBYTE)&timeout, sizeof(timeout));
// tell ieWatch where to place the browser window
DWORD val = 0;
RegSetValueEx(hKey, _T("Window Left"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("Window Top"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
val = pos.right;
RegSetValueEx(hKey, _T("Window Width"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
val = pos.bottom;
RegSetValueEx(hKey, _T("Window Height"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
// pass it the IP address to use
RegDeleteValue(hKey, _T("Use Address"));
if( !ipAddress.IsEmpty() )
RegSetValueEx(hKey, _T("Use Address"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)ipAddress, (ipAddress.GetLength() + 1) * sizeof(TCHAR));
// delete any old results from the reg key
RegDeleteValue(hKey, _T("Result"));
RegCloseKey(hKey);
}
// create the event name
DWORD isCached = 0;
CString cachedString;
if( cached )
{
cachedString = _T("Cached-");
isCached = 1;
}
else
{
cachedString = _T("Cleared Cache-");
}
eventName = cachedString + info.eventText + _T("^");
if( info.runningScript )
{
TCHAR script[MAX_PATH];
lstrcpy(script, info.url.Right(info.url.GetLength() - 9));
eventName += PathFindFileName(script);
}
else
eventName += info.url;
// give it the event name and log file location
if( RegCreateKeyEx((HKEY)hProfile, _T("SOFTWARE\\America Online\\SOM"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
RegDeleteValue(hKey, _T("IEWatchLog"));
if( !info.logFile.IsEmpty() )
RegSetValueEx(hKey, _T("IEWatchLog"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.logFile, (info.logFile.GetLength() + 1) * sizeof(TCHAR));
RegDeleteValue(hKey, _T("Links File"));
if( info.harvestLinks && !info.linksFile.IsEmpty() )
{
DeleteFile(info.linksFile);
RegSetValueEx(hKey, _T("Links File"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.linksFile, (info.linksFile.GetLength() + 1) * sizeof(TCHAR));
}
RegDeleteValue(hKey, _T("404 File"));
if( !info.s404File.IsEmpty() )
RegSetValueEx(hKey, _T("404 File"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.s404File, (info.s404File.GetLength() + 1) * sizeof(TCHAR));
RegDeleteValue(hKey, _T("HTML File"));
if( !info.htmlFile.IsEmpty() )
RegSetValueEx(hKey, _T("HTML File"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.htmlFile, (info.htmlFile.GetLength() + 1) * sizeof(TCHAR));
RegDeleteValue(hKey, _T("Cookies File"));
if( !info.cookiesFile.IsEmpty() )
RegSetValueEx(hKey, _T("Cookies File"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.cookiesFile, (info.cookiesFile.GetLength() + 1) * sizeof(TCHAR));
RegSetValueEx(hKey, _T("EventName"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)eventName, (eventName.GetLength() + 1) * sizeof(TCHAR));
RegSetValueEx(hKey, _T("LabID"), 0, REG_DWORD, (const LPBYTE)&labID, sizeof(labID));
RegSetValueEx(hKey, _T("DialerID"), 0, REG_DWORD, (const LPBYTE)&dialerID, sizeof(dialerID));
RegSetValueEx(hKey, _T("ConnectionType"), 0, REG_DWORD, (const LPBYTE)&connectionType, sizeof(connectionType));
RegSetValueEx(hKey, _T("Cached"), 0, REG_DWORD, (const LPBYTE)&isCached, sizeof(isCached));
RegSetValueEx(hKey, _T("URL"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.url, (info.url.GetLength() + 1) * sizeof(TCHAR));
RegSetValueEx(hKey, _T("DOM Element ID"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.domElement, (info.domElement.GetLength() + 1) * sizeof(TCHAR));
RegSetValueEx(hKey, _T("Experimental"), 0, REG_DWORD, (const LPBYTE)&experimental, sizeof(experimental));
RegSetValueEx(hKey, _T("Screen Shot Errors"), 0, REG_DWORD, (const LPBYTE)&screenShotErrors, sizeof(screenShotErrors));
RegSetValueEx(hKey, _T("Check Optimizations"), 0, REG_DWORD, (const LPBYTE)&info.checkOpt, sizeof(info.checkOpt));
RegSetValueEx(hKey, _T("Include Object Data"), 0, REG_DWORD, (const LPBYTE)&info.includeObjectData, sizeof(info.includeObjectData));
RegSetValueEx(hKey, _T("ignoreSSL"), 0, REG_DWORD, (const LPBYTE)&info.ignoreSSL, sizeof(info.ignoreSSL));
RegSetValueEx(hKey, _T("useBitBlt"), 0, REG_DWORD, (const LPBYTE)&useBitBlt, sizeof(useBitBlt));
CString descriptor = _T("Launch");
RegSetValueEx(hKey, _T("Descriptor"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)descriptor, (descriptor.GetLength() + 1) * sizeof(TCHAR));
DWORD abm = 2;
if( info.urlType == 1 )
abm = 0;
else if( info.urlType == 2 )
abm = 1;
RegSetValueEx(hKey, _T("ABM"), 0, REG_DWORD, (const LPBYTE)&abm, sizeof(abm));
DWORD val = 0;
if( info.saveEverything )
val = 1;
RegSetValueEx(hKey, _T("Save Everything"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
val = 0;
if( info.captureVideo )
val = 1;
RegSetValueEx(hKey, _T("Capture Video"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("AFT"), 0, REG_DWORD, (const LPBYTE)&info.aft, sizeof(info.aft));
RegDeleteValue(hKey, _T("Block"));
if( !info.block.IsEmpty() )
RegSetValueEx(hKey, _T("Block"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.block, (info.block.GetLength() + 1) * sizeof(TCHAR));
RegDeleteValue(hKey, _T("Basic Auth"));
if( !info.basicAuth.IsEmpty() )
RegSetValueEx(hKey, _T("Basic Auth"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.basicAuth, (info.basicAuth.GetLength() + 1) * sizeof(TCHAR));
RegDeleteValue(hKey, _T("Host"));
if( !info.host.IsEmpty() )
RegSetValueEx(hKey, _T("Host"), 0, REG_SZ, (const LPBYTE)(LPCTSTR)info.host, (info.host.GetLength() + 1) * sizeof(TCHAR));
RegCloseKey(hKey);
}
}
}
/*-----------------------------------------------------------------------------
Setup the IE settings so we don't get a bunch of dialogs
-----------------------------------------------------------------------------*/
bool CURLBlaster::ConfigureIE(void)
{
bool ret = false;
if( hProfile )
{
ret = true;
// Set some basic IE options
HKEY hKey;
if( RegCreateKeyEx((HKEY)hProfile, _T("Software\\Microsoft\\Internet Explorer\\Main"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
LPCTSTR szVal = _T("yes");
RegSetValueEx(hKey, _T("DisableScriptDebuggerIE"), 0, REG_SZ, (const LPBYTE)szVal, (lstrlen(szVal) + 1) * sizeof(TCHAR));
szVal = _T("no");
RegSetValueEx(hKey, _T("FormSuggest PW Ask"), 0, REG_SZ, (const LPBYTE)szVal, (lstrlen(szVal) + 1) * sizeof(TCHAR));
RegSetValueEx(hKey, _T("Friendly http errors"), 0, REG_SZ, (const LPBYTE)szVal, (lstrlen(szVal) + 1) * sizeof(TCHAR));
RegSetValueEx(hKey, _T("Use FormSuggest"), 0, REG_SZ, (const LPBYTE)szVal, (lstrlen(szVal) + 1) * sizeof(TCHAR));
DWORD val = 1;
RegSetValueEx(hKey, _T("NoUpdateCheck"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("NoJITSetup"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("NoWebJITSetup"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegCloseKey(hKey);
}
if( RegCreateKeyEx((HKEY)hProfile, _T("Software\\Microsoft\\Internet Explorer\\InformationBar"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
DWORD val = 0;
RegSetValueEx(hKey, _T("FirstTime"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegCloseKey(hKey);
}
if( RegCreateKeyEx((HKEY)hProfile, _T("Software\\Microsoft\\Internet Explorer\\IntelliForms"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
DWORD val = 0;
RegSetValueEx(hKey, _T("AskUser"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegCloseKey(hKey);
}
if( RegCreateKeyEx((HKEY)hProfile, _T("Software\\Microsoft\\Internet Explorer\\Security"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
LPCTSTR szVal = _T("Query");
RegSetValueEx(hKey, _T("Safety Warning Level"), 0, REG_SZ, (const LPBYTE)szVal, (lstrlen(szVal) + 1) * sizeof(TCHAR));
szVal = _T("Medium");
RegSetValueEx(hKey, _T("Sending_Security"), 0, REG_SZ, (const LPBYTE)szVal, (lstrlen(szVal) + 1) * sizeof(TCHAR));
szVal = _T("Low");
RegSetValueEx(hKey, _T("Viewing_Security"), 0, REG_SZ, (const LPBYTE)szVal, (lstrlen(szVal) + 1) * sizeof(TCHAR));
RegCloseKey(hKey);
}
if( RegCreateKeyEx((HKEY)hProfile, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
DWORD val = 1;
RegSetValueEx(hKey, _T("AllowCookies"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("EnableHttp1_1"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("ProxyHttp1.1"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("EnableNegotiate"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
val = 0;
RegSetValueEx(hKey, _T("WarnAlwaysOnPost"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("WarnonBadCertRecving"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("WarnOnPost"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("WarnOnPostRedirect"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegSetValueEx(hKey, _T("WarnOnZoneCrossing"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
//RegSetValueEx(hKey, _T("ProxyEnable"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegCloseKey(hKey);
}
if( RegCreateKeyEx((HKEY)hProfile, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\5.0\\Cache\\Content"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
DWORD val = 131072;
RegSetValueEx(hKey, _T("CacheLimit"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegCloseKey(hKey);
}
if( RegCreateKeyEx((HKEY)hProfile, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Cache\\Content"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
DWORD val = 131072;
RegSetValueEx(hKey, _T("CacheLimit"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegCloseKey(hKey);
}
// reset the toolbar layout (to make sure the sidebar isn't open)
if( RegCreateKeyEx((HKEY)hProfile, _T("Software\\Microsoft\\Internet Explorer\\Toolbar\\WebBrowser"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
RegDeleteValue(hKey, _T("ITBarLayout"));
RegCloseKey(hKey);
}
// Tweak the security zone to eliminate some warnings
if( RegCreateKeyEx((HKEY)hProfile, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\\Zones\\3"), 0, 0, 0, KEY_WRITE, 0, &hKey, 0) == ERROR_SUCCESS )
{
DWORD val = 0;
// don't warn about posting data
RegSetValueEx(hKey, _T("1601"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
// don't warn about mixed content
RegSetValueEx(hKey, _T("1609"), 0, REG_DWORD, (const LPBYTE)&val, sizeof(val));
RegCloseKey(hKey);
}
}
return ret;
}
/*-----------------------------------------------------------------------------
Recusrively copy the IE settings
-----------------------------------------------------------------------------*/
void CURLBlaster::CloneIESettings(void)
{
CloneRegKey( HKEY_CURRENT_USER, (HKEY)hProfile, _T("Software\\Microsoft\\Internet Explorer") );
CloneRegKey( HKEY_CURRENT_USER, (HKEY)hProfile, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings") );
}
/*-----------------------------------------------------------------------------
Recusrively copy a registry key
-----------------------------------------------------------------------------*/
void CURLBlaster::CloneRegKey(HKEY hSrc, HKEY hDest, LPCTSTR subKey)
{
HKEY src;
if( RegOpenKeyEx(hSrc, subKey, 0, KEY_READ, &src) == ERROR_SUCCESS )
{
HKEY dest;
if( RegCreateKeyEx(hDest, subKey, 0, 0, 0, KEY_WRITE, 0, &dest, 0) == ERROR_SUCCESS )
{
// copy all of the values over
DWORD nameSize = 16384;
DWORD valSize = 32767;
TCHAR * name = new TCHAR[nameSize];
LPBYTE data = new BYTE[valSize];
DWORD nameLen = nameSize;
DWORD dataLen = valSize;
DWORD type;
DWORD index = 0;
while( RegEnumValue(src, index, name, &nameLen, 0, &type, data, &dataLen) == ERROR_SUCCESS )
{
RegSetValueEx(dest, name, 0, type, data, dataLen);
index++;
nameLen = nameSize;
dataLen = valSize;
}
// copy all of the sub-keys over
index = 0;
nameLen = nameSize;
while( RegEnumKeyEx(src, index, name, &nameLen, 0, 0, 0, 0) == ERROR_SUCCESS )
{
// don't copy the search providers key, this can triggere IE messages
if( _tcsicmp(name, _T("SearchScopes")) )
CloneRegKey(src, dest, name);
index++;
nameLen = nameSize;
}
delete [] name;
delete [] data;
RegCloseKey(dest);
}
RegCloseKey(src);
}
}
/*-----------------------------------------------------------------------------
Encode a video job
-----------------------------------------------------------------------------*/
void CURLBlaster::EncodeVideo(void)
{
TCHAR path[MAX_PATH];
if( GetModuleFileName(NULL, path, _countof(path)) )
{
lstrcpy(PathFindFileName(path), _T("x264.exe"));
CString exe(path);
CString cmd = CString(_T("\"")) + exe + _T("\" --crf 24 --threads 1 --keyint 10 --min-keyint 1 -o video.mp4 video.avs");
PROCESS_INFORMATION pi;
STARTUPINFO si;
memset( &si, 0, sizeof(si) );
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
log.Trace(_T("Executing '%s' in '%s'"), (LPCTSTR)cmd, (LPCTSTR)info.zipFileDir);
if( CreateProcess((LPCTSTR)exe, (LPTSTR)(LPCTSTR)cmd, 0, 0, FALSE, IDLE_PRIORITY_CLASS , 0, (LPCTSTR)info.zipFileDir, &si, &pi) )
{
WaitForSingleObject(pi.hProcess, 60 * 60 * 1000);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
log.Trace(_T("Successfully ran '%s'"), (LPCTSTR)cmd);
}
else
log.Trace(_T("Execution failed '%s'"), (LPCTSTR)cmd);
}
}
/*-----------------------------------------------------------------------------
Launch the given exe and ensure that we get a clean return code
-----------------------------------------------------------------------------*/
bool CURLBlaster::Launch(CString cmd, HANDLE * phProc)
{
bool ret = false;
if( cmd.GetLength() )
{
PROCESS_INFORMATION pi;
STARTUPINFO si;
memset( &si, 0, sizeof(si) );
si.cb = sizeof(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
log.Trace(_T("Executing '%s'"), (LPCTSTR)cmd);
if( CreateProcess(NULL, (LPTSTR)(LPCTSTR)cmd, 0, 0, FALSE, NORMAL_PRIORITY_CLASS , 0, NULL, &si, &pi) )
{
if( phProc )
{
*phProc = pi.hProcess;
CloseHandle(pi.hThread);
}
else
{
WaitForSingleObject(pi.hProcess, 60 * 60 * 1000);
DWORD code;
if( GetExitCodeProcess(pi.hProcess, &code) && code == 0 )
ret = true;
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
log.Trace(_T("Successfully ran '%s'"), (LPCTSTR)cmd);
}
}
else
log.Trace(_T("Execution failed '%s'"), (LPCTSTR)cmd);
}
else
ret = true;
return ret;
}
/*-----------------------------------------------------------------------------
Set up bandwidth throttling
-----------------------------------------------------------------------------*/
bool CURLBlaster::ConfigureIpfw(void)
{
bool ret = false;
if( pipeIn && pipeOut && info.ipfw && info.bwIn && info.bwOut )
{
// split the latency across directions
DWORD latency = info.latency / 2;
CString buff;
buff.Format(_T("[urlblast] - Throttling: %d Kbps in, %d Kbps out, %d ms latency, %0.2f plr"), info.bwIn, info.bwOut, info.latency, info.plr );
OutputDebugString(buff);
// create the inbound pipe
if( ipfw.CreatePipe(pipeIn, info.bwIn * 1000, latency, info.plr / 100.0) )
{
// make up for odd values
if( info.latency % 2 )
latency++;
// create the outbound pipe
if( ipfw.CreatePipe(pipeOut, info.bwOut * 1000, latency, info.plr / 100.0) )
ret = true;
else
ipfw.CreatePipe(pipeIn, 0, 0, 0);
}
}
else
ret = true;
return ret;
}
/*-----------------------------------------------------------------------------
Remove the bandwidth throttling
-----------------------------------------------------------------------------*/
void CURLBlaster::ResetIpfw(void)
{
if( pipeIn )
ipfw.CreatePipe(pipeIn, 0, 0, 0);
if( pipeOut )
ipfw.CreatePipe(pipeOut, 0, 0, 0);
}
/*-----------------------------------------------------------------------------
Terminate any procs that are running under our test user account
in case something got spawned while testing
-----------------------------------------------------------------------------*/
void CURLBlaster::KillProcs()
{
#ifndef _DEBUG
WTS_PROCESS_INFO * proc = NULL;
DWORD count = 0;
if( WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &proc, &count) )
{
for( DWORD i = 0; i < count; i++ )
{
// see if the SID matches
if( userSID && proc[i].pUserSid && IsValidSid(userSID) && IsValidSid(proc[i].pUserSid) )
{
if( EqualSid(proc[i].pUserSid, userSID ) )
{
HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, proc[i].ProcessId);
if( hProc )
{
TerminateProcess(hProc, 0);
CloseHandle(hProc);
}
}
}
}
WTSFreeMemory(proc);
}
#endif
}
typedef int (CALLBACK* DNSFLUSHPROC)();
/*-----------------------------------------------------------------------------
Flush the OS DNS cache
-----------------------------------------------------------------------------*/
void CURLBlaster::FlushDNS()
{
bool flushed = false;
HINSTANCE hDnsDll;
log.Trace(_T("Flushing DNS cache"));
hDnsDll = LoadLibrary(_T("dnsapi.dll"));
if( hDnsDll )
{
DNSFLUSHPROC pDnsFlushProc = (DNSFLUSHPROC)GetProcAddress(hDnsDll, "DnsFlushResolverCache");
if( pDnsFlushProc )
{
int ret = pDnsFlushProc();
if( ret == ERROR_SUCCESS)
{
flushed = true;
log.Trace(_T("Successfully flushed the DNS resolved cache"));
}
else
log.Trace(_T("DnsFlushResolverCache returned %d"), ret);
}
else
log.Trace(_T("Failed to load dnsapi.dll"));
FreeLibrary(hDnsDll);
}
else
log.Trace(_T("Failed to load dnsapi.dll"));
if( !flushed )
Launch(_T("ipconfig.exe /flushdns"));
}
/*-----------------------------------------------------------------------------
Launch Dynatrace (if necessary)
-----------------------------------------------------------------------------*/
void CURLBlaster::LaunchDynaTrace()
{
if( !dynaTrace.IsEmpty() )
{
Launch(dynaTrace, &hDynaTrace);
WaitForInputIdle(hDynaTrace, 30000);
}
}
/*-----------------------------------------------------------------------------
Close Dynatrace (if necessary)
-----------------------------------------------------------------------------*/
void CURLBlaster::CloseDynaTrace()
{
if( hDynaTrace )
{
HWND hWnd = FindWindow(NULL, _T("dynaTrace AJAX Edition"));
PostMessage(hWnd, WM_CLOSE, 0, 0);
if( WaitForSingleObject(hDynaTrace, 60000) == WAIT_TIMEOUT )
TerminateProcess(hDynaTrace,0);
CloseHandle(hDynaTrace);
// zip up the profile data to our test results folder
TCHAR path[MAX_PATH];
DWORD len = _countof(path);
lstrcpy(path, _T("C:\\Documents and Settings"));
GetProfilesDirectory(path, &len);
TCHAR name[MAX_PATH];
len = _countof(name);
if( GetUserName(name, &len) )
{
lstrcat(path, _T("\\"));
lstrcat(path, name);
lstrcat(path, _T("\\.dynaTrace\\ajax\\browser\\iesessions"));
ZipDir(path, info.logFile + _T("_dynaTrace.dtas"), _T(""), NULL);
}
}
}
/*-----------------------------------------------------------------------------
Archive (and delete) the given directory
-----------------------------------------------------------------------------*/
void CURLBlaster::ZipDir(CString dir, CString dest, CString depth, zipFile file)
{
bool top = false;
// start by creating an empty zip file
if( !file )
{
file = zipOpen(CT2A(dest), APPEND_STATUS_CREATE);
top = true;
}
if( file )
{
WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile( dir + _T("\\*.*"), &fd );
if( hFind != INVALID_HANDLE_VALUE )
{
do
{
// skip over . and ..
if( lstrcmp(fd.cFileName, _T(".")) && lstrcmp(fd.cFileName, _T("..")) )
{
if( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
CString d = fd.cFileName;
if( depth.GetLength() )
d = depth + CString(_T("\\")) + fd.cFileName;
ZipDir( dir + CString(_T("\\")) + fd.cFileName, dest, d, file);
RemoveDirectory(dir + CString(_T("\\")) + fd.cFileName);
}
else
{
CString archiveFile;
if( depth.GetLength() )
archiveFile = depth + CString(_T("/"));
archiveFile += fd.cFileName;
CString filePath = dir + CString(_T("\\")) + fd.cFileName;
// add the file to the zip archive
HANDLE hFile = CreateFile( filePath, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
if( hFile != INVALID_HANDLE_VALUE )
{
DWORD size = GetFileSize(hFile, 0);
if( size )
{
BYTE * mem = (BYTE *)malloc(size);
if( mem )
{
DWORD bytes;
if( ReadFile(hFile, mem, size, &bytes, 0) && size == bytes )
{
// add the file to the archive
if( !zipOpenNewFileInZip( file, CT2A(archiveFile), 0, 0, 0, 0, 0, 0, Z_DEFLATED, Z_BEST_COMPRESSION ) )
{
// write the file to the archive
zipWriteInFileInZip( file, mem, size );
zipCloseFileInZip( file );
}
}
free(mem);
}
}
CloseHandle( hFile );
}
DeleteFile(filePath);
}
}
}while( FindNextFile(hFind, &fd) );
FindClose(hFind);
}
}
// if we're done with the root, delete everything
if( top && file )
zipClose(file, 0);
}
| [
"[email protected]@aac4e670-4c05-fb8f-3594-08f7db841d5f"
] | [
[
[
1,
1308
]
]
] |
d3cec963c29c334cf88e59023d7ac627f4c2f67f | 85b3c5d2c89d05f4ad9cd90c9becc2ba8912eb0f | /problem14/14.cpp | 5e05a2d014066663662c5f74d0d194364a61db86 | [] | no_license | stevenc49/project_euler | 89ce29403f363363a477a776aaf523712b98185a | 7b3463af4bc37bcd25335431e7854f47b2c021cc | refs/heads/master | 2021-03-12T21:41:45.978945 | 2011-12-16T04:44:35 | 2011-12-16T04:44:35 | 968,635 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,151 | cpp | #include <iostream>
#include <ext/hash_map>
using namespace std;
using namespace __gnu_cxx;
int main()
{
int longest_num = 0;
int longest_seq_length = 0;
hash_map<int, int> map;
for(int i=1; i<1000000; i++)
{
unsigned long long current_num = i; //unsigned long long or else current_num will overflow
int current_num_seq_length = 1;
while(current_num != 1)
{
if( map[current_num] != 0 )
{
current_num_seq_length += map[current_num]-1;
break;
}
else if(current_num%2==0)
current_num >>= 1;
else
current_num = 3*current_num + 1;
current_num_seq_length++;
}
map[i] = current_num_seq_length;
if(current_num_seq_length > longest_seq_length)
{
longest_seq_length = current_num_seq_length;
longest_num = i;
}
}
cout << "longest number: " << longest_num << endl;
cout << "longest sequence: " << longest_seq_length << endl;
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
47
]
]
] |
91d90bb771c858bb65ef83cd791f7a6fbdda6712 | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/POJ/google code jam 1B-B the next num/b.cpp | 706da98213367b6e2b6b7fd15698a626aaebf5bf | [] | 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 | 959 | cpp | #include "stdio.h"
#include "iostream"
#include "string.h"
#include "math.h"
#include "string"
#include "vector"
#include "set"
#include "map"
#include "queue"
#include "list"
#include "stack"
using namespace std;
int main()
{
int cs;
scanf("%d",&cs);
// freopen("out.txt","w",stdout);
for(int ii=1;ii<=cs;ii++){
printf("Case #%d: ",ii);
char a[1000],b[1000];
scanf("%s",a);
int n=strlen(a);
int i,j;
n--;
int m=n;
while(m>0 && a[m]<=a[m-1]) m--;
if(m==0){
m=n;
while(a[m]=='0') m--;
b[0]=a[m];
b[1]='0';
for(i=2,j=n;j>=0;i++,j--){
if(j==m) j--;
if(j>=0) b[i]=a[j];
else i--;
}
b[i]=0;
printf("%s\n",b);
continue;
}
int l=n;
m--;
while(a[l]<=a[m]) l--;
for(i=0;i<m;i++)
b[i]=a[i];
b[i]=a[l];
for(i++,j=n;j>l;j--,i++)
b[i]=a[j];
b[i]=a[m];
for(i++,j--;j>m;j--,i++)
b[i]=a[j];
b[i]=0;
printf("%s\n",b);
}
}
| [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
] | [
[
[
1,
58
]
]
] |
2e9194c1087d7961245354210238db0ecb05c49d | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/GameDLL/AVMine.cpp | 0bcba14ec1a1dc5db46984bfba6bcdf6f836c42c | [] | no_license | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05T14:32:01.782047 | 2008-01-01T13:13:39 | 2008-01-01T13:13:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,161 | cpp | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2007.
-------------------------------------------------------------------------
$Id:$
$DateTime$
Description: Anti-Vehicle mine implementation
-------------------------------------------------------------------------
History:
- 22:1:2007 14:39 : Created by Steve Humphreys
*************************************************************************/
#include "StdAfx.h"
#include "AVMine.h"
#include "Game.h"
#include "GameRules.h"
#include "HUD/HUD.h"
#include "Player.h"
#include "IEntityProxy.h"
//------------------------------------------------------------------------
CAVMine::CAVMine()
: m_currentWeight(0)
, m_triggerWeight(100)
, m_teamId(0)
, m_frozen(false)
{
}
//------------------------------------------------------------------------
CAVMine::~CAVMine()
{
if(gEnv->bMultiplayer && gEnv->bServer)
{
IActor* pOwner = g_pGame->GetIGameFramework()->GetIActorSystem()->GetActor(m_ownerId);
if(pOwner && pOwner->IsPlayer())
{
((CPlayer*)pOwner)->RecordExplosiveDestroyed(GetEntityId(), 1);
}
}
if(g_pGame->GetHUD())
g_pGame->GetHUD()->RecordExplosiveDestroyed(GetEntityId());
}
//------------------------------------------------------------------------
bool CAVMine::Init(IGameObject *pGameObject)
{
bool ok = CProjectile::Init(pGameObject);
if(g_pGame->GetHUD())
g_pGame->GetHUD()->RecordExplosivePlaced(GetEntityId());
// if not already a hit listener, register us.
// (removed in ~CProjectile )
if(!m_hitListener)
{
g_pGame->GetGameRules()->AddHitListener(this);
m_hitListener = true;
}
return ok;
}
//------------------------------------------------------------------------
void CAVMine::Launch(const Vec3 &pos, const Vec3 &dir, const Vec3 &velocity, float speedScale)
{
// sit flat on the ground.
Vec3 newDir = dir;
newDir.z = 0.0f;
CProjectile::Launch(pos, newDir, velocity, speedScale);
if(gEnv->bMultiplayer && gEnv->bServer)
{
CActor* pOwner = GetWeapon()->GetOwnerActor();
if(pOwner && pOwner->IsPlayer())
{
((CPlayer*)pOwner)->RecordExplosivePlaced(GetEntityId(), 1);
}
}
float boxDimension = 3;
m_triggerWeight = GetParam("triggerweight", m_triggerWeight);
boxDimension = GetParam("box_dimension", boxDimension);
if(gEnv->bServer)
{
IEntityTriggerProxy *pTriggerProxy = (IEntityTriggerProxy*)(GetEntity()->GetProxy(ENTITY_PROXY_TRIGGER));
if (!pTriggerProxy)
{
GetEntity()->CreateProxy(ENTITY_PROXY_TRIGGER);
pTriggerProxy = (IEntityTriggerProxy*)GetEntity()->GetProxy(ENTITY_PROXY_TRIGGER);
}
if(pTriggerProxy)
{
// increase box in the z direction to cope with big vehicles passing over the top (eg NK truck)
AABB boundingBox = AABB(Vec3(-boxDimension,-boxDimension,-(boxDimension+1)), Vec3(boxDimension,boxDimension,(boxDimension+1)));
pTriggerProxy->SetTriggerBounds(boundingBox);
}
}
}
void CAVMine::HandleEvent(const SGameObjectEvent &event)
{
CProjectile::HandleEvent(event);
if (event.event==eCGE_PostFreeze)
m_frozen=event.param!=0;
}
void CAVMine::ProcessEvent(SEntityEvent &event)
{
if (m_frozen)
return;
switch(event.event)
{
case ENTITY_EVENT_ENTERAREA:
{
IEntity * pEntity = gEnv->pEntitySystem->GetEntity(event.nParam[0]);
CGameRules* pGR = g_pGame->GetGameRules();
if(pEntity && pGR)
{
// if this is a team game, mines aren't set off by their own team
if(pGR->GetTeamCount() > 0 && (m_teamId != 0 && pGR->GetTeam(pEntity->GetId()) == m_teamId))
break;
IPhysicalEntity *pPhysics = pEntity->GetPhysics();
if(pPhysics)
{
pe_status_dynamics physStatus;
if(0 != pPhysics->GetStatus(&physStatus))
{
// only count moving objects
if(physStatus.v.GetLengthSquared() > 0.1f)
m_currentWeight += physStatus.mass;
if (m_currentWeight > m_triggerWeight)
Explode(true);
}
}
}
break;
}
case ENTITY_EVENT_LEAVEAREA:
{
IEntity * pEntity = gEnv->pEntitySystem->GetEntity(event.nParam[0]);
if(pEntity)
{
IPhysicalEntity *pPhysics = pEntity->GetPhysics();
if(pPhysics)
{
pe_status_dynamics physStatus;
if(0 != pPhysics->GetStatus(&physStatus))
{
m_currentWeight -= physStatus.mass;
if(m_currentWeight < 0)
m_currentWeight = 0;
}
}
}
break;
}
default:
break;
}
return CProjectile::ProcessEvent(event);
}
void CAVMine::SetParams(EntityId ownerId, EntityId hostId, EntityId weaponId, int damage, int hitTypeId, float damageDrop, float damageDropMinR)
{
// if this is a team game, record which team placed this mine...
if(gEnv->bServer)
{
if(CGameRules* pGameRules = g_pGame->GetGameRules())
{
m_teamId = pGameRules->GetTeam(ownerId);
pGameRules->SetTeam(m_teamId, GetEntityId());
}
}
CProjectile::SetParams(ownerId, hostId, weaponId, damage, hitTypeId, damageDrop, damageDropMinR);
} | [
"[email protected]",
"kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31"
] | [
[
[
1,
16
],
[
22,
28
],
[
31,
36
],
[
67,
73
],
[
88,
92
],
[
94,
94
],
[
102,
102
],
[
109,
111
],
[
122,
123
],
[
127,
131
],
[
134,
134
],
[
139,
148
],
[
150,
181
],
[
184,
184
]
],
[
[
17,
21
],
[
29,
30
],
[
37,
66
],
[
74,
87
],
[
93,
93
],
[
95,
101
],
[
103,
108
],
[
112,
121
],
[
124,
126
],
[
132,
133
],
[
135,
138
],
[
149,
149
],
[
182,
183
],
[
185,
199
]
]
] |
e78d9304ceaeebe7a7da001b347fac33ea55a949 | accd6e4daa3fc1103c86d245c784182e31681ea4 | /Chess/Chess/ChessEveluation.cpp | 301ba610246b16465d7c02841cb94a0df242eb1d | [] | no_license | linfuqing/zero3d | d87ad6cf97069aea7861332a9ab8fc02b016d286 | cebb12c37fe0c9047fb5b8fd3c50157638764c24 | refs/heads/master | 2016-09-05T19:37:56.213992 | 2011-08-04T01:37:36 | 2011-08-04T01:37:36 | 34,048,942 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,977 | cpp | #include "StdAfx.h"
#include "ChessEveluation.h"
const INT RED_PAWN_ADDITIONAL_VALUE[CHESS_HEIGHT][CHESS_WIDTH] =
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},
{90, 90, 110, 120, 120, 120, 110, 90, 90},
{90, 90, 110, 120, 120, 120, 110, 90, 90},
{70, 90, 110, 110, 110, 110, 110, 90, 70},
{70, 70, 70, 70, 70, 70, 70, 70, 70},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
const INT BLACK_PAWN_ADDITIONAL_VALUE[CHESS_HEIGHT][CHESS_WIDTH] =
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0},
{70, 70, 70, 70, 70, 70, 70, 70, 70},
{70, 90, 110, 110, 110, 110, 110, 90, 70},
{90, 90, 110, 120, 120, 120, 110, 90, 90},
{90, 90, 110, 120, 120, 120, 110, 90, 90},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
//Class:
CChessEveluation::CChessEveluation(void):CEveluation(MAX_DEPTH_VALUE)
{
m_BaseValue[CHESS_TYPE_SUBSCRIPT[RED_KING ]] = BASEVALUE_KING;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[RED_CAR ]] = BASEVALUE_CAR;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[RED_HORSE ]] = BASEVALUE_HORSE;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[RED_CANON ]] = BASEVALUE_CANON;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[RED_BISHOP ]] = BASEVALUE_BISHOP;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[RED_ELEPHANT ]] = BASEVALUE_ELEPHANT;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[RED_PAWN ]] = BASEVALUE_PAWN;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[BLACK_KING ]] = BASEVALUE_KING;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[BLACK_CAR ]] = BASEVALUE_CAR;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[BLACK_HORSE ]] = BASEVALUE_HORSE;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[BLACK_CANON ]] = BASEVALUE_CANON;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[BLACK_BISHOP ]] = BASEVALUE_BISHOP;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[BLACK_ELEPHANT]] = BASEVALUE_ELEPHANT;
m_BaseValue[CHESS_TYPE_SUBSCRIPT[BLACK_PAWN ]] = BASEVALUE_PAWN;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[RED_KING ]] = FLEXIBILITY_KING;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[RED_CAR ]] = FLEXIBILITY_CAR;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[RED_HORSE ]] = FLEXIBILITY_HORSE;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[RED_CANON ]] = FLEXIBILITY_CANON;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[RED_BISHOP ]] = FLEXIBILITY_BISHOP;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[RED_ELEPHANT ]] = FLEXIBILITY_ELEPHANT;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[RED_PAWN ]] = FLEXIBILITY_PAWN;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[BLACK_KING ]] = FLEXIBILITY_KING;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[BLACK_CAR ]] = FLEXIBILITY_CAR;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[BLACK_HORSE ]] = FLEXIBILITY_HORSE;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[BLACK_CANON ]] = FLEXIBILITY_CANON;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[BLACK_BISHOP ]] = FLEXIBILITY_BISHOP;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[BLACK_ELEPHANT]] = FLEXIBILITY_ELEPHANT;
m_FlexValue[CHESS_TYPE_SUBSCRIPT[BLACK_PAWN ]] = FLEXIBILITY_PAWN;
}
CChessEveluation::~CChessEveluation(void)
{
}
INT g_nCount = 0;
///Fuck This:
INT CChessEveluation::Eveluate(BOARD CHESS& ChessBoard, CHESSSIDE Side)
{
g_nCount++;
memset( &m_Attract, 0, sizeof(CHESSBOARD<SHORT>) );
memset( &m_Guard, 0, sizeof(CHESSBOARD<BYTE>) );
memset( &m_Flexibility, 0, sizeof(CHESSBOARD<BYTE>) );
memset( &m_ChessValue, 0, sizeof(CHESSBOARD<INT>) );
INT i, j, k;
CHESSMANTYPE ChessType, TargetType;
for(i = 0; i < CHESS_WIDTH; i++)
{
for(j = 0; j < CHESS_HEIGHT; j++)
{
if(ChessBoard.gPosition[j][i] != NO_CHESS)
{
ChessType = ChessBoard.gPosition[j][i];
//GetRelatePiece(ChessBoard, i, j);
m_nPositionCount = 0;
CChessRules::GetMoves(ChessBoard, i, j, FALSE);
for(k = 0; k < m_nPositionCount; k++)
{
TargetType = ChessBoard.gPosition[gRelatePosition[k].y][gRelatePosition[k].x];
if(TargetType == NO_CHESS)
m_Flexibility.gPosition[j][i]++;
else
{
if( ChessType >> SIDE_SHIFT == TargetType >> SIDE_SHIFT )
m_Guard.gPosition[gRelatePosition[k].y][gRelatePosition[k].x]++;
else
{
m_Attract.gPosition[gRelatePosition[k].y][gRelatePosition[k].x]++;
m_Flexibility.gPosition[j][i] ++;
if( (TargetType == RED_KING && Side == BLACK_SIDE) || (TargetType == BLACK_KING && Side == RED_SIDE) )
return FAIL_VALUE;
else
{
///Fuck This:
m_Attract.gPosition[gRelatePosition[k].y][gRelatePosition[k].x] +=
(30 + (m_BaseValue[CHESS_TYPE_SUBSCRIPT[TargetType]] - m_BaseValue[CHESS_TYPE_SUBSCRIPT[ChessType]]) / 10) / 10;
}
}
}
}
}
}
}
INT nHalfValue;
CHESSSIDE ChessSide;
CHESSMANTYPE King;
SHORT nSubscript;
INT nRedValue = 0, nBlackValue = 0;
for(i = 0; i < CHESS_WIDTH; i++)
{
for(j = 0; j < CHESS_HEIGHT; j++)
{
if(ChessBoard.gPosition[j][i] != NO_CHESS)
{
ChessType = ChessBoard.gPosition[j][i];
nSubscript = CHESS_TYPE_SUBSCRIPT[ChessType];
///PartI
m_ChessValue.gPosition[j][i] ++;
m_ChessValue.gPosition[j][i] += m_FlexValue[nSubscript] * m_Flexibility.gPosition[j][i];
if(ChessType == RED_PAWN)
m_ChessValue.gPosition[j][i] += RED_PAWN_ADDITIONAL_VALUE[j][i];
if(ChessType == BLACK_PAWN)
m_ChessValue.gPosition[j][i] += BLACK_PAWN_ADDITIONAL_VALUE[j][i];
///PartII
nHalfValue = m_BaseValue[nSubscript];
m_ChessValue.gPosition[j][i] += nHalfValue;
///Fuck This:
nHalfValue /= 16;
ChessSide = SEARCHSIDE(ChessType >> SIDE_SHIFT);
if(m_Attract.gPosition[j][i])
{
King = CHESSMANTYPE( KING + (ChessSide << SIDE_SHIFT) );
if(Side == ChessSide)
{
///Fuck This:
m_ChessValue.gPosition[j][i] += ChessType == King ? -20 : -(nHalfValue * 2);
if(m_Guard.gPosition[j][i])
m_ChessValue.gPosition[j][i] += nHalfValue;
}
else
{
if(ChessType == King)
return FAIL_VALUE;
///Fuck This:
m_ChessValue.gPosition[j][i] -= m_Guard.gPosition[j][i] ? nHalfValue : nHalfValue * 10;
}
m_ChessValue.gPosition[j][i] -= m_Attract.gPosition[j][i];
}
else if(m_Guard.gPosition[j][i])
//And Fuck This:
m_ChessValue.gPosition[j][i] += 5;
///PartIII:
if(ChessSide == RED_SIDE)
nRedValue += m_ChessValue.gPosition[j][i];
else
nBlackValue += m_ChessValue.gPosition[j][i];
}
}
}
return Side == RED_SIDE ? (nRedValue - nBlackValue) : (nBlackValue - nRedValue);
}
INT CChessEveluation::IsGameOver(BOARD CHESS &ChessBoard, const UINT uDepth, const CHESSSIDE Side, const BOOL bIsCurrentSide)
{
INT i, j;
BOOL RedLive = FALSE, BlackLive = FALSE;
for(i = 3; i < 6; i++)
{
for(j = 7; j < 10; j++)
{
if(ChessBoard.gPosition[j][i] == RED_KING)
RedLive = TRUE;
if(ChessBoard.gPosition[j][i] == BLACK_KING)
BlackLive = TRUE;
}
for(j = 0; j < 3 ; j++)
{
if(ChessBoard.gPosition[j][i] == RED_KING)
RedLive = TRUE;
if(ChessBoard.gPosition[j][i] == BLACK_KING)
BlackLive = TRUE;
}
}
//i = (m_nMaxDepth - uDepth + 1) % 2;
if(Side == RED_SIDE)
{
if(!RedLive)
return bIsCurrentSide ? ( MAX_VALUE + uDepth) : (-MAX_VALUE - uDepth);
if(!BlackLive)
return bIsCurrentSide ? (-MAX_VALUE - uDepth) : ( MAX_VALUE + uDepth);
}
else if(Side == BLACK_SIDE)
{
if(!RedLive)
return bIsCurrentSide ? (-MAX_VALUE - uDepth) : ( MAX_VALUE + uDepth);
if(!BlackLive)
return bIsCurrentSide ? ( MAX_VALUE + uDepth) : (-MAX_VALUE - uDepth);
}
return 0;
} | [
"[email protected]"
] | [
[
[
1,
243
]
]
] |
81a7509ee36bd7b2ad959db0ef92a0a682a5cf81 | dba70d101eb0e52373a825372e4413ed7600d84d | /Demo/Demo_CubeMapAndNormalMap/Shader.h | 5a9798f33fdb4a125734a234f6807dbb77b99776 | [] | no_license | nustxujun/simplerenderer | 2aa269199f3bab5dc56069caa8162258e71f0f96 | 466a43a1e4f6e36e7d03722d0d5355395872ad86 | refs/heads/master | 2021-03-12T22:38:06.759909 | 2010-10-02T03:30:26 | 2010-10-02T03:30:26 | 32,198,944 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,687 | h | #pragma once;
#include "..\..\RendererComplement\include\PipelinePlus.h"
using namespace RCP;
class VS:public VertexShader
{
void execute(Vertex& vert)
{
//world space
vert.color[2] = convert(matrix4X4[0] * vert.pos);
vert.pos = matrix4X4[1] * (matrix4X4[0] * vert.pos);
vert.texCrood[0] = vert.texCrood[0];
Vector4 norm = matrix4X4[1] * matrix4X4[0] * Vector4(vert.norm,0);
//norm.normalise();
Vector3 eyeR(-vert.pos.x,-vert.pos.y,-vert.pos.z);
eyeR.normalise();
Vector3 vRef(norm.x,norm.y,norm.z);
vRef = vRef * 2 * eyeR.dotProduct(vRef) - eyeR;
//vRef.normalise();
//reflect
vert.color[0] = convert(vRef);
vert.pos = matrix4X4[2] * vert.pos;
//worldspace normal
vert.color[1] = convert(matrix4X4[0] * Vector4(vert.norm,0));
//light dir
Vector4 lightDir = vector4[1] - vert.pos;
Vector4 cameraDir = vector4[0] - vert.pos;
lightDir.w = 0;
cameraDir.w = 0;
//转换到模型空间
lightDir = matrix4X4[3] * lightDir;
cameraDir = matrix4X4[3] * cameraDir;
Matrix4X4 tangentSpace;
tangentSpace.m[0][0] = vert.tan.x;
tangentSpace.m[0][1] = vert.tan.y;
tangentSpace.m[0][2] = vert.tan.z;
tangentSpace.m[1][0] = vert.bino.x;
tangentSpace.m[1][1] = vert.bino.y;
tangentSpace.m[1][2] = vert.bino.z;
tangentSpace.m[2][0] = vert.norm.x;
tangentSpace.m[2][1] = vert.norm.y;
tangentSpace.m[2][2] = vert.norm.z;
//tangentSpace
lightDir = tangentSpace * lightDir;
cameraDir = tangentSpace* cameraDir;
//方向,在这里做完变换后直接和采出的normal进行运算
Vector3 temp(lightDir.x,lightDir.y,lightDir.z);
temp.normalise();
//tangent space lightdir
vert.color[3] = convert(temp);
temp = Vector3(cameraDir.x,cameraDir.y,cameraDir.z);
temp.normalise();
//tangent space cameradir
vert.color[4] = convert(temp);
}
};
class PS:public PixelShader
{
Colour shade(const Pixel& p)
{
//Vector4 realPos(convert(p.color[2]));
//Vector4 temp = vector4[1] - realPos;
Vector3 L(p.color[3].r,p.color[3].g,p.color[3].b);
//L.normalise();
//temp = vector4[0] - realPos;
Vector3 V(p.color[4].r,p.color[4].g,p.color[4].b);
//V.normalise();
Vector3 H = L + V;
H.normalise();
Colour temp = tex2D(1,p.u[0] ,p.v[0] );
temp = temp * 2.0f - 1.0f;
Vector3 norm(temp.r,temp.g,temp.b);
Colour specular = pow(std::max<float>(0,H.dotProduct(norm) * 1.1f ),10) ;
Colour diffuse = std::max<float>(0,norm.dotProduct(L));
//return diffuse;
return ((texCube(0,p.color[0].r,p.color[0].g,p.color[0].b)*diffuse + specular) * Colour(0.5f,0.375f,0.25f,1.0f) ) .saturate();
}
};
| [
"[email protected]@c2606ca0-2ebb-fda8-717c-293879e69bc3"
] | [
[
[
1,
96
]
]
] |
dd71096452ef1c9b2c385a2aa6cb65c097b75b94 | ef8e875dbd9e81d84edb53b502b495e25163725c | /litewiz/src/session/aet_session.cpp | 1694db1d74b869c0ddb2c9ceb828dd036602c2c3 | [] | no_license | panone/litewiz | 22b9d549097727754c9a1e6286c50c5ad8e94f2d | e80ed9f9d845b08c55b687117acb1ed9b6e9a444 | refs/heads/master | 2021-01-10T19:54:31.146153 | 2010-10-01T13:29:38 | 2010-10-01T13:29:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,020 | cpp | /*******************************************************************************
*******************************************************************************/
#include <QDir>
#include <QDomDocument>
#include <QDomElement>
#include <QFile>
#include <QString>
#include <QStringList>
#include <QTextStream>
#include "file.h"
#include "file_collection.h"
#include "item.h"
#include "item_collection.h"
#include "variant.h"
#include "variant_collection.h"
#include "session.h"
#include "aet_session.h"
/*******************************************************************************
*******************************************************************************/
AetSession::AetSession
(
Session * const session
) :
session( session )
{
document = new QDomDocument();
title = "Session";
rangeSelection = false;
}
/*******************************************************************************
*******************************************************************************/
AetSession::~AetSession
(
void
)
{
delete document;
}
/*******************************************************************************
*******************************************************************************/
void AetSession::setTitle
(
QString const & title
)
{
if ( !title.isEmpty() )
{
this->title = title;
}
}
/*******************************************************************************
*******************************************************************************/
void AetSession::setAudioDevice
(
QString const & deviceName
)
{
if ( !deviceName.isEmpty() )
{
audioDevice = deviceName;
}
}
/*******************************************************************************
*******************************************************************************/
void AetSession::setRangeSelection
(
bool const selection
)
{
rangeSelection = selection;
}
/*******************************************************************************
*******************************************************************************/
bool AetSession::save
(
QString const & fileName
)
{
QFile file( fileName );
bool result = file.open( QIODevice::WriteOnly | QIODevice::Text );
if ( result )
{
document->clear();
document->appendChild( document->createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"utf-8\" " ) );
document->appendChild( document->createElement( "Session" ) );
QFileInfo fileInfo( file.fileName() );
formatSession( document->lastChildElement(), fileInfo.canonicalPath() );
QTextStream output( &file );
output << document->toString();
file.close();
}
return result;
}
/*******************************************************************************
*******************************************************************************/
void AetSession::formatSession
(
QDomElement parent,
QString const & sessionPath
)
{
parent.appendChild( createStringElement( "Title", title ) );
if ( !audioDevice.isEmpty() )
{
parent.appendChild( createStringElement( "AudioDevice", audioDevice ) );
}
if ( rangeSelection )
{
parent.appendChild( createIntegerElement( "RangeSelection", 1 ) );
}
formatVariants( parent );
formatItems( parent, sessionPath );
}
/*******************************************************************************
*******************************************************************************/
void AetSession::formatVariants
(
QDomElement parent
)
{
VariantCollection const * variants = session->getVariants();
int reference = 0;
QStringList names;
for ( int i = 0; i < variants->getCount(); i++ )
{
if ( variants->getVariant( i )->isReference() )
{
reference = i;
break;
}
}
Variant const * variant = variants->getVariant( reference );
if ( !variant->isExcluded() )
{
names.append( variant->getName() );
}
for ( int i = 0; i < variants->getCount(); i++ )
{
variant = variants->getVariant( i );
if ( ( i != reference ) && !variant->isExcluded() )
{
names.append( variants->getVariant( i )->getName() );
}
}
parent.appendChild( createStringListElement( "Variants", names ) );
}
/*******************************************************************************
*******************************************************************************/
void AetSession::formatItems
(
QDomElement parent,
QString const & sessionPath
)
{
ItemCollection const * items = session->getItems();
QDomElement tracks = document->createElement( "Tracks" );
tracks.setAttribute( "type", "list" );
tracks.setAttribute( "depth", "1" );
tracks.setAttribute( "itemtype", "section" );
for ( int i = 0; i < items->getCount(); i++ )
{
if ( !items->getItem( i )->isExcluded() )
{
QDomElement item = document->createElement( "Item" );
formatItem( item, items->getItem( i ), sessionPath );
tracks.appendChild( item );
}
}
parent.appendChild( tracks );
}
/*******************************************************************************
*******************************************************************************/
void AetSession::formatItem
(
QDomElement parent,
Item const * const item,
QString const & sessionPath
)
{
FileList files = session->getFiles()->getItemFiles( item, true, true );
QDir sessionDirectory( sessionPath );
QStringList names;
foreach ( File const * file, files )
{
names.append( sessionDirectory.relativeFilePath( file->getPathName() ) );
}
parent.appendChild( createStringElement( "Title", item->getName() ) );
parent.appendChild( createStringListElement( "Files", names ) );
}
/*******************************************************************************
*******************************************************************************/
QDomElement AetSession::createIntegerElement
(
QString const & name,
int const value
)
{
QDomElement result = document->createElement( name );
result.setAttribute( "type", "integer" );
result.setAttribute( "value", value );
return result;
}
/*******************************************************************************
*******************************************************************************/
QDomElement AetSession::createStringElement
(
QString const & name,
QString const & value
)
{
QDomElement result = document->createElement( name );
result.setAttribute( "type", "string" );
result.setAttribute( "value", value );
return result;
}
/*******************************************************************************
*******************************************************************************/
QDomElement AetSession::createStringListElement
(
QString const & name,
QStringList const & values
)
{
QDomElement result = document->createElement( name );
result.setAttribute( "type", "list" );
result.setAttribute( "depth", "1" );
result.setAttribute( "itemtype", "string" );
foreach ( QString const & value, values )
{
QDomElement item = document->createElement( "Item" );
item.setAttribute( "value", value );
result.appendChild( item );
}
return result;
}
/******************************************************************************/
| [
"[email protected]"
] | [
[
[
1,
285
]
]
] |
b67e91e0da5c11915d0e73173df968548aee64e9 | bf7d05c055c5686e4ded30f9705a28a396520d48 | /Meta/MetaBase.cpp | 90d6dcc5cfa319c073a00c0f6de16f88a1e09420 | [] | no_license | ghemingway/mgalib | f32438d5abdbeb5739c298e401a0513f91c8d6d0 | c8cf8507a7fe73efe1da19abcdb77b52e75e2de0 | refs/heads/master | 2020-12-24T15:40:33.538434 | 2011-02-04T16:38:09 | 2011-02-04T16:38:09 | 32,185,568 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,545 | cpp | /*** Included Header Files ***/
#include "MetaBase.h"
#include "MetaProject.h"
#include "MetaGeneric.h"
#include "MetaConstraint.h"
// --------------------------- Public MetaBase Methods --------------------------- //
MetaBase::MetaBase(CoreObject &coreObject, MetaProject* const &metaProject) :
_coreObject(coreObject), _metaProject(metaProject)
{
ASSERT(coreObject != NULL);
ASSERT(metaProject != NULL);
}
MetaBase::~MetaBase()
{
ASSERT( this->_coreObject != NULL );
// Delete the coreObject
this->_coreObject = NULL;
}
const Result_t MetaBase::GetName(std::string &name) const throw()
{
Result_t txResult = this->_metaProject->BeginTransaction();
ASSERT( txResult == S_OK );
Result_t result = this->_coreObject->GetAttributeValue(ATTRID_NAME, name);
txResult = this->_metaProject->CommitTransaction();
ASSERT( txResult == S_OK );
return result;
}
const Result_t MetaBase::SetName(const std::string &name) throw()
{
Result_t txResult = this->_metaProject->BeginTransaction();
ASSERT( txResult == S_OK );
Result_t result = this->_coreObject->SetAttributeValue(ATTRID_NAME, name);
txResult = this->_metaProject->CommitTransaction();
ASSERT( txResult == S_OK );
return result;
}
const Result_t MetaBase::GetDisplayedName(std::string &name) const throw()
{
Result_t txResult = this->_metaProject->BeginTransaction();
ASSERT( txResult == S_OK );
Result_t result = this->_coreObject->GetAttributeValue(ATTRID_DISPNAME, name);
txResult = this->_metaProject->CommitTransaction();
ASSERT( txResult == S_OK );
return result;
}
const Result_t MetaBase::SetDisplayedName(const std::string &name) throw()
{
Result_t txResult = this->_metaProject->BeginTransaction();
ASSERT( txResult == S_OK );
Result_t result = this->_coreObject->SetAttributeValue(ATTRID_DISPNAME, name);
txResult = this->_metaProject->CommitTransaction();
ASSERT( txResult == S_OK );
return result;
}
const Result_t MetaBase::GetRegistryValue(const std::string &key, std::string &value) const throw()
{
Result_t txResult = this->_metaProject->BeginTransaction();
ASSERT( txResult == S_OK );
std::pair<std::string,std::string> pair(key, "");
Result_t result = this->_coreObject->GetAttributeValue(ATTRID_REGISTRY, pair);
txResult = this->_metaProject->CommitTransaction();
value = pair.second;
ASSERT( txResult == S_OK );
return result;
}
const Result_t MetaBase::SetRegistryValue(const std::string &key, const std::string &value) throw()
{
Result_t txResult = this->_metaProject->BeginTransaction();
ASSERT( txResult == S_OK );
std::pair<std::string,std::string> pair(key, value);
Result_t result = this->_coreObject->SetAttributeValue(ATTRID_REGISTRY, pair);
txResult = this->_metaProject->CommitTransaction();
ASSERT( txResult == S_OK );
return result;
}
const Result_t MetaBase::GetObjType(ObjType_t &objType) const throw()
{
MetaID_t metaID = METAID_NONE;
Result_t result = this->_coreObject->GetMetaID(metaID);
ASSERT( result == S_OK );
ASSERT( metaID != METAID_NONE );
if( metaID == METAID_METAPROJECT ) objType = (ObjType_t)OBJTYPE_FOLDER;
else objType = (ObjType_t)(metaID - METAID_METABASE);
return S_OK;
}
const Result_t MetaBase::GetConstraints(std::list<MetaConstraint*> &constraintList) throw()
{
// Get the associated coreProject
CoreProject* coreProject = NULL;
Result_t result = this->_coreObject->Project(coreProject);
ASSERT( result == S_OK );
ASSERT( coreProject != NULL );
// Get the collection from the attributes
std::list<Uuid> idList;
result = this->_coreObject->GetAttributeValue(ATTRID_CONSTRAINT_PTR + ATTRID_COLLECTION, idList);
ASSERT( result == S_OK );
std::list<Uuid>::iterator idIter = idList.begin();
// Iterate over the list to gather the objects
constraintList.clear();
while (idIter != idList.end())
{
// Get the coreObject from this uuid
CoreObject object;
result = coreProject->Object(*idIter, object);
ASSERT( result == S_OK );
ASSERT( object != NULL );
// Create the MetaConstraint with the coreObject and metaProject
MetaConstraint* metaConstraint = new MetaConstraint(object, this->_metaProject);
ASSERT( metaConstraint != NULL );
constraintList.push_back(metaConstraint);
// Move on to the next uuid
++idIter;
}
return S_OK;
}
const Result_t MetaBase::CreateConstraint(MetaConstraint* &constraint) throw()
{
// Get the associated coreProject
CoreProject* coreProject = NULL;
Result_t result = this->_coreObject->Project(coreProject);
ASSERT( result == S_OK );
ASSERT( coreProject != NULL );
// Start a transaction
result = coreProject->BeginTransaction(false);
ASSERT( result == S_OK );
// Create a METAID_METACONSTRAINT core object
CoreObject coreObject;
result = coreProject->CreateObject(METAID_METACONSTRAINT, coreObject);
ASSERT( result == S_OK );
ASSERT( coreObject != NULL );
// Link the new child to this object as parent
Uuid uuid = Uuid::Null();
result = this->_coreObject->GetUuid(uuid);
ASSERT( result == S_OK );
ASSERT( uuid != Uuid::Null() );
result = coreObject->SetAttributeValue(ATTRID_CONSTRAINT_PTR, uuid);
ASSERT( result == S_OK );
// Commit transaction at the CoreProject level
result = coreProject->CommitTransaction();
ASSERT( result == S_OK );
// Now use the core object to create a MetaConstraint
constraint = new MetaConstraint(coreObject, this->_metaProject);
ASSERT( constraint != NULL );
return S_OK;
}
| [
"graham.hemingway@8932de9b-a0df-7518-fb39-9aee4a96b462"
] | [
[
[
1,
170
]
]
] |
ddf37fbea240a53b04aeb3d6aaea2d1012f89d62 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/source/aosl/unit_time.cpp | f08e34276a72a776bf0518f32a294ff021871a6d | [] | no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,387 | cpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
// Begin prologue.
//
#define AOSLCPP_SOURCE
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "aosl/unit_time.hpp"
#include <xsd/cxx/xml/dom/wildcard-source.hxx>
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
#include <xsd/cxx/tree/comparison-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
static
const ::xsd::cxx::tree::comparison_plate< 0, char >
comparison_plate_init;
}
namespace aosl
{
// Unit_time
//
Unit_time::
Unit_time (const ::xml_schema::Double& _xsd_Double_base)
: ::xsd::cxx::tree::fundamental_base< ::xml_schema::Double, char, ::xml_schema::SimpleType, ::xsd::cxx::tree::schema_type::double_ > (_xsd_Double_base)
{
}
Unit_time::
Unit_time (const Unit_time& x,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xsd::cxx::tree::fundamental_base< ::xml_schema::Double, char, ::xml_schema::SimpleType, ::xsd::cxx::tree::schema_type::double_ > (x, f, c)
{
}
Unit_time::
Unit_time (const ::xercesc::DOMElement& e,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xsd::cxx::tree::fundamental_base< ::xml_schema::Double, char, ::xml_schema::SimpleType, ::xsd::cxx::tree::schema_type::double_ > (e, f, c)
{
}
Unit_time::
Unit_time (const ::xercesc::DOMAttr& a,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xsd::cxx::tree::fundamental_base< ::xml_schema::Double, char, ::xml_schema::SimpleType, ::xsd::cxx::tree::schema_type::double_ > (a, f, c)
{
}
Unit_time::
Unit_time (const ::std::string& s,
const ::xercesc::DOMElement* e,
::xml_schema::Flags f,
::xml_schema::Container* c)
: ::xsd::cxx::tree::fundamental_base< ::xml_schema::Double, char, ::xml_schema::SimpleType, ::xsd::cxx::tree::schema_type::double_ > (s, e, f, c)
{
}
Unit_time* Unit_time::
_clone (::xml_schema::Flags f,
::xml_schema::Container* c) const
{
return new class Unit_time (*this, f, c);
}
Unit_time::
~Unit_time ()
{
}
}
#include <ostream>
#include <xsd/cxx/tree/std-ostream-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::std_ostream_plate< 0, char >
std_ostream_plate_init;
}
namespace aosl
{
::std::ostream&
operator<< (::std::ostream& o, const Unit_time& i)
{
o << static_cast< const ::xsd::cxx::tree::fundamental_base< ::xml_schema::Double, char, ::xml_schema::SimpleType, ::xsd::cxx::tree::schema_type::double_ >& > (i);
return o;
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace aosl
{
}
#include <ostream>
#include <xsd/cxx/tree/error-handler.hxx>
#include <xsd/cxx/xml/dom/serialization-source.hxx>
#include <xsd/cxx/tree/type-serializer-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_serializer_plate< 0, char >
type_serializer_plate_init;
}
namespace aosl
{
void
operator<< (::xercesc::DOMElement& e, const Unit_time& i)
{
e << static_cast< const ::xsd::cxx::tree::fundamental_base< ::xml_schema::Double, char, ::xml_schema::SimpleType, ::xsd::cxx::tree::schema_type::double_ >& > (i);
}
void
operator<< (::xercesc::DOMAttr& a, const Unit_time& i)
{
a << static_cast< const ::xsd::cxx::tree::fundamental_base< ::xml_schema::Double, char, ::xml_schema::SimpleType, ::xsd::cxx::tree::schema_type::double_ >& > (i);
}
void
operator<< (::xml_schema::ListStream& l,
const Unit_time& i)
{
l << static_cast< const ::xsd::cxx::tree::fundamental_base< ::xml_schema::Double, char, ::xml_schema::SimpleType, ::xsd::cxx::tree::schema_type::double_ >& > (i);
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| [
"klaim@localhost"
] | [
[
[
1,
169
]
]
] |
b15d1e162fa32b05dcdaa418b55acfb2a1381e5a | 6c8c4728e608a4badd88de181910a294be56953a | /RexLogicModule/Avatar/AvatarExporter.h | 5ab92f3c51426d7189617231c1958fb53b0568d0 | [
"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 | 2,517 | h | // For conditions of distribution and use, see copyright notice in license.txt
#ifndef incl_RexLogic_AvatarExporter_h
#define incl_RexLogic_AvatarExporter_h
#include "ThreadTask.h"
namespace RexLogic
{
//! An asset to export.
/*! Note: hash has to be calculated before submitting for export, and many assets
with duplicate same hash should not exist!
*/
class ExportAsset
{
public:
//! Asset data
std::vector<u8> data_;
//! Base64-encoded SHA1 hash of data
std::string hash_;
void CalculateHash();
};
//! Asset map for export, keyed by filename
typedef std::map<std::string, ExportAsset> ExportAssetMap;
//! Request for avatar export
class AvatarExporterRequest : public Foundation::ThreadTaskRequest
{
public:
//! User account
std::string account_;
//! Authentication server to use (note: auth.server tells the storage address to use)
std::string authserver_;
//! Password
std::string password_;
//! Avatar description
std::string avatar_xml_;
//! Assets to be exported
ExportAssetMap assets_;
};
//! Result for avatar export
class AvatarExporterResult : public Foundation::ThreadTaskResult
{
public:
//! Success flag
bool success_;
//! Message to be displayed (if any)
std::string message_;
};
typedef boost::shared_ptr<AvatarExporterRequest> AvatarExporterRequestPtr;
typedef boost::shared_ptr<AvatarExporterResult> AvatarExporterResultPtr;
//! Threadtask that handles avatar export to legacy avatar storage.
/*! Also handles periodically refreshing the authentication session hash, so that export stays legal.
*/
class AvatarExporter : public Foundation::ThreadTask
{
public:
AvatarExporter();
virtual void Work();
private:
//! Perform the export
void ProcessRequest(AvatarExporterRequestPtr request, AvatarExporterResultPtr result);
//! Login to authentication & get new sessionhash
bool LoginToAuthentication(const std::string& account, const std::string& authserver, const std::string& password, std::string& sessionhash, std::string& avatarurl, std::string& error);
};
typedef boost::shared_ptr<AvatarExporter> AvatarExporterPtr;
}
#endif
| [
"cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3"
] | [
[
[
1,
78
]
]
] |
68697766f499a803ae3ee856af7c1e239d39a2cc | d0ae9c74f91979b9a99c122e8a40de4a5d955bae | /AstroVis2/CVector.cpp | 08376a99be494eb5f4f98ff382eb8cf1cf7303a9 | [] | no_license | RyanDuToit/AstroVis | fe36bedb4f6fa628578de26c2173f9fe155483b0 | a8864f20553e0a824bbf0c309cb9d76617ba5aad | refs/heads/master | 2021-01-17T08:08:58.780711 | 2011-07-06T19:01:24 | 2011-07-06T19:01:24 | 2,008,297 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,473 | cpp | #include <stdio.h>
#include <math.h>
#include "CVector.h"
#define _EPSILON (0.0001)
CVector::CVector(
)
{
value_[0] = 0.0;
value_[1] = 0.0;
value_[2] = 0.0;
value_[3] = 0.0;
texcoord_[0] = 0.0;
texcoord_[1] = 0.0;
texcoord_[2] = 0.0;
color_[0] = 1.0;
color_[1] = 1.0;
color_[2] = 1.0;
color_[3] = 1.0;
}
CVector::CVector(
const CVector& vector_in
)
{
value_[0] = vector_in.value_[0];
value_[1] = vector_in.value_[1];
value_[2] = vector_in.value_[2];
value_[3] = vector_in.value_[3];
texcoord_[0] = vector_in.texcoord_[0];
texcoord_[1] = vector_in.texcoord_[1];
texcoord_[2] = vector_in.texcoord_[2];
color_[0] = vector_in.color_[0];
color_[1] = vector_in.color_[1];
color_[2] = vector_in.color_[2];
color_[3] = vector_in.color_[3];
}
CVector::CVector(
const double& a_in,
const double& b_in,
const double& c_in,
const double& d_in
)
{
value_[0] = a_in;
value_[1] = b_in;
value_[2] = c_in;
value_[3] = d_in;
}
CVector::CVector(
const double& a_in,
const double& b_in,
const double& c_in,
const double& d_in,
const double& s_in,
const double& t_in,
const double& r_in,
const double& R_in,
const double& G_in,
const double& B_in,
const double& A_in
)
{
value_[0] = a_in;
value_[1] = b_in;
value_[2] = c_in;
value_[3] = d_in;
texcoord_[0] = s_in;
texcoord_[1] = t_in;
texcoord_[2] = r_in;
color_[0] = R_in;
color_[1] = G_in;
color_[2] = B_in;
color_[3] = A_in;
}
CVector::CVector(
const double& a_in,
const double& b_in,
const double& c_in,
const double& d_in,
const double& s_in,
const double& t_in,
const double& r_in
)
{
value_[0] = a_in;
value_[1] = b_in;
value_[2] = c_in;
value_[3] = d_in;
texcoord_[0] = s_in;
texcoord_[1] = t_in;
texcoord_[2] = r_in;
color_[0] = 1.0;
color_[1] = 1.0;
color_[2] = 1.0;
color_[3] = 1.0;
}
CVector::CVector(
const double& a_in,
const double& b_in,
const double& c_in,
const double& d_in,
const double& R_in,
const double& G_in,
const double& B_in,
const double& A_in
)
{
value_[0] = a_in;
value_[1] = b_in;
value_[2] = c_in;
value_[3] = d_in;
texcoord_[0] = 0.0;
texcoord_[1] = 0.0;
texcoord_[2] = 0.0;
color_[0] = R_in;
color_[1] = G_in;
color_[2] = B_in;
color_[3] = A_in;
}
CVector&
CVector::operator=(
const CVector& vector_in
)
{
if(&vector_in != this)
{
value_[0] = vector_in.value_[0];
value_[1] = vector_in.value_[1];
value_[2] = vector_in.value_[2];
value_[3] = vector_in.value_[3];
texcoord_[0] = vector_in.texcoord_[0];
texcoord_[1] = vector_in.texcoord_[1];
texcoord_[2] = vector_in.texcoord_[2];
color_[0] = vector_in.color_[0];
color_[1] = vector_in.color_[1];
color_[2] = vector_in.color_[2];
color_[3] = vector_in.color_[3];
}
return *this;
}
double&
CVector::operator[](
const unsigned short index_in
)
{
if(index_in > 3)
throw;
return value_[index_in];
}
double
CVector::operator[](
const unsigned short index_in
) const
{
if(index_in > 3)
throw;
return value_[index_in];
}
double&
CVector::operator()(
const unsigned short index_in
)
{
if(index_in > 3)
throw;
return value_[index_in];
}
double
CVector::operator()(
const unsigned short index_in
) const
{
if(index_in > 3)
throw;
return value_[index_in];
}
void
CVector::set(
const double& a_in,
const double& b_in,
const double& c_in,
const double& d_in
)
{
value_[0] = a_in;
value_[1] = b_in;
value_[2] = c_in;
value_[3] = d_in;
}
void
CVector::get(
double& a_out,
double& b_out,
double& c_out,
double& d_out
) const
{
a_out = value_[0];
b_out = value_[1];
c_out = value_[2];
d_out = value_[3];
}
bool
CVector::operator==(
const CVector& vector_in
) const
{
if( (fabs(value_[0] - vector_in.value_[0]) > _EPSILON)
|| (fabs(value_[1] - vector_in.value_[1]) > _EPSILON)
|| (fabs(value_[2] - vector_in.value_[2]) > _EPSILON)
|| (fabs(value_[3] - vector_in.value_[3]) > _EPSILON) )
return false;
return true;
}
bool
CVector::operator!=(
const CVector& vector_in
) const
{
return( !(*this == vector_in) );
}
CVector
CVector::operator-(
) const
{
return CVector(
-value_[0],
-value_[1],
-value_[2],
-value_[3],
-texcoord_[0],
-texcoord_[1],
-texcoord_[2]
);
}
CVector
operator-(
const CVector& vector0_in,
const CVector& vector1_in
)
{
return CVector(
vector0_in.value_[0] - vector1_in.value_[0],
vector0_in.value_[1] - vector1_in.value_[1],
vector0_in.value_[2] - vector1_in.value_[2],
vector0_in.value_[3] - vector1_in.value_[3],
vector0_in.texcoord_[0] - vector1_in.texcoord_[0],
vector0_in.texcoord_[1] - vector1_in.texcoord_[1],
vector0_in.texcoord_[2] - vector1_in.texcoord_[2],
vector0_in.color_[0] - vector1_in.color_[0],
vector0_in.color_[1] - vector1_in.color_[1],
vector0_in.color_[2] - vector1_in.color_[2],
vector0_in.color_[3] - vector1_in.color_[3]
);
}
CVector
operator+(
const CVector& vector0_in,
const CVector& vector1_in
)
{
return CVector(
vector0_in.value_[0] + vector1_in.value_[0],
vector0_in.value_[1] + vector1_in.value_[1],
vector0_in.value_[2] + vector1_in.value_[2],
vector0_in.value_[3] + vector1_in.value_[3],
vector0_in.texcoord_[0] + vector1_in.texcoord_[0],
vector0_in.texcoord_[1] + vector1_in.texcoord_[1],
vector0_in.texcoord_[2] + vector1_in.texcoord_[2],
vector0_in.color_[0] + vector1_in.color_[0],
vector0_in.color_[1] + vector1_in.color_[1],
vector0_in.color_[2] + vector1_in.color_[2],
vector0_in.color_[3] + vector1_in.color_[3]
);
}
double
operator*(
const CVector& vector0_in,
const CVector& vector1_in
)
{
return(
vector0_in.value_[0] * vector1_in.value_[0]
+ vector0_in.value_[1] * vector1_in.value_[1]
+ vector0_in.value_[2] * vector1_in.value_[2]
+ vector0_in.value_[3] * vector1_in.value_[3]
);
}
double
CVector::getInnerProduct(
const CVector& vector_in
) const
{
return(
value_[0] * vector_in.value_[0]
+ value_[1] * vector_in.value_[1]
+ value_[2] * vector_in.value_[2]
+ value_[3] * vector_in.value_[3]
);
}
CVector
operator*(
const double& scalar_in,
const CVector& vector_in
)
{
return CVector(
scalar_in * vector_in.value_[0],
scalar_in * vector_in.value_[1],
scalar_in * vector_in.value_[2],
scalar_in * vector_in.value_[3],
scalar_in * vector_in.texcoord_[0],
scalar_in * vector_in.texcoord_[1],
scalar_in * vector_in.texcoord_[2],
scalar_in * vector_in.color_[0],
scalar_in * vector_in.color_[1],
scalar_in * vector_in.color_[2],
scalar_in * vector_in.color_[3]
);
}
CVector
operator*(
const CVector& vector_in,
const double& scalar_in
)
{
return CVector(
vector_in.value_[0] * scalar_in,
vector_in.value_[1] * scalar_in,
vector_in.value_[2] * scalar_in,
vector_in.value_[3] * scalar_in,
vector_in.texcoord_[0] * scalar_in,
vector_in.texcoord_[1] * scalar_in,
vector_in.texcoord_[2] * scalar_in,
vector_in.color_[0] * scalar_in,
vector_in.color_[1] * scalar_in,
vector_in.color_[2] * scalar_in,
vector_in.color_[3] * scalar_in
);
}
CVector
operator/(
const CVector& vector_in,
const double& scalar_in
)
{
return CVector(
vector_in.value_[0] / scalar_in,
vector_in.value_[1] / scalar_in,
vector_in.value_[2] / scalar_in,
vector_in.value_[3] / scalar_in,
vector_in.texcoord_[0] / scalar_in,
vector_in.texcoord_[1] / scalar_in,
vector_in.texcoord_[2] / scalar_in,
vector_in.color_[0] / scalar_in,
vector_in.color_[1] / scalar_in,
vector_in.color_[2] / scalar_in,
vector_in.color_[3] / scalar_in
);
}
CVector&
CVector::operator+=(
const CVector& vector_in
)
{
value_[0] += vector_in.value_[0];
value_[1] += vector_in.value_[1];
value_[2] += vector_in.value_[2];
value_[3] += vector_in.value_[3];
texcoord_[0] += vector_in.texcoord_[0];
texcoord_[1] += vector_in.texcoord_[1];
texcoord_[2] += vector_in.texcoord_[2];
color_[0] += vector_in.color_[0] ;
color_[1] += vector_in.color_[1] ;
color_[2] += vector_in.color_[2] ;
color_[3] += vector_in.color_[3] ;
return *this;
}
CVector&
CVector::operator-=(
const CVector& vector_in
)
{
value_[0] -= vector_in.value_[0];
value_[1] -= vector_in.value_[1];
value_[2] -= vector_in.value_[2];
value_[3] -= vector_in.value_[3];
texcoord_[0] -= vector_in.texcoord_[0];
texcoord_[1] -= vector_in.texcoord_[1];
texcoord_[2] -= vector_in.texcoord_[2];
color_[0] -= vector_in.color_[0] ;
color_[1] -= vector_in.color_[1] ;
color_[2] -= vector_in.color_[2] ;
color_[3] -= vector_in.color_[3] ;
return *this;
}
CVector&
CVector::operator*=(
const double& scalar_in
)
{
value_[0] *= scalar_in;
value_[1] *= scalar_in;
value_[2] *= scalar_in;
value_[3] *= scalar_in;
texcoord_[0] *= scalar_in;
texcoord_[1] *= scalar_in;
texcoord_[2] *= scalar_in;
color_[0] *= scalar_in;
color_[1] *= scalar_in;
color_[2] *= scalar_in;
color_[3] *= scalar_in;
return *this;
}
CVector&
CVector::operator/=(
const double& scalar_in
)
{
value_[0] /= scalar_in;
value_[1] /= scalar_in;
value_[2] /= scalar_in;
value_[3] /= scalar_in;
texcoord_[0] /= scalar_in;
texcoord_[1] /= scalar_in;
texcoord_[2] /= scalar_in;
color_[0] /= scalar_in;
color_[1] /= scalar_in;
color_[2] /= scalar_in;
color_[3] /= scalar_in;
return *this;
}
double
CVector::getLength(
) const
{
return sqrt(
value_[0] * value_[0]
+ value_[1] * value_[1]
+ value_[2] * value_[2]
+ value_[3] * value_[3]
);
}
void
CVector::normalize(
)
{
double length;
length = getLength();
if( fabs( length ) < _EPSILON )
return;
value_[0] /= length;
value_[1] /= length;
value_[2] /= length;
value_[3] /= length;
}
bool
CVector::isNormalized(
) const
{
double length;
length = getLength();
if(fabs(length - 1.0) > _EPSILON)
return false;
return true;
}
bool
CVector::isNil(
) const
{
double length;
length = getLength();
if(fabs(length) > _EPSILON)
return false;
return true;
}
| [
"[email protected]"
] | [
[
[
1,
534
]
]
] |
ea35bc54a90d191f798eb05b51e1f0798b0013fd | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/nGENE Toolset/ParticleSystemWrapper.h | 0d9706c1c26a5201f7a9d300a9ce21fe8aea0eea | [] | no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,035 | h | /*
---------------------------------------------------------------------------
This source file is part of nGENE Tech.
Copyright (c) 2006- Wojciech Toman
This program is free software.
File: ParticleSystemWrapper.h
Version: 0.02
---------------------------------------------------------------------------
*/
#ifndef __INC_PARTICLESYSTEMWRAPPER_H_
#define __INC_PARTICLESYSTEMWRAPPER_H_
#include "nGENE.h"
#include "NodeWrapper.h"
#include "frmRenderTarget.h"
#include <sstream>
namespace nGENEToolset
{
using namespace System;
using namespace System::Drawing;
using nGENE::PARTICLE_COLOUR;
using nGENE::SParticleForce;
using nGENE::SParticleDeflector;
using nGENE::NodeParticleSystem;
using nGENE::ParticleEmitter;
using nGENE::SceneManager;
using nGENE::Engine;
using nGENE::Real;
ref class ParticleEmitterWrapper;
/// Wrapper for particle deflector structure.
ref class ParticleDeflectorWrapper: public SceneNode
{
protected:
SParticleDeflector* m_pDeflector;
bool m_bOnHeap;
nGENEToolset::Vector3^ m_Position;
nGENEToolset::Vector3^ m_Normal;
static int s_nDeflectorsCount;
public:
ParticleDeflectorWrapper()
{
m_pDeflector = new SParticleDeflector();
m_bOnHeap = true;
m_Position = gcnew nGENEToolset::Vector3(NULL);
m_Normal = gcnew nGENEToolset::Vector3(NULL);
m_Position->x = m_pDeflector->plane.getPlanePoint().x;
m_Position->y = m_pDeflector->plane.getPlanePoint().y;
m_Position->z = m_pDeflector->plane.getPlanePoint().z;
m_Normal->x = m_pDeflector->plane.getPlaneNormal().x;
m_Normal->y = m_pDeflector->plane.getPlaneNormal().y;
m_Normal->z = m_pDeflector->plane.getPlaneNormal().z;
this->Name = "ParticleDeflector" + (s_nDeflectorsCount);
this->Key = "ParticleDeflector" + (s_nDeflectorsCount++);
}
ParticleDeflectorWrapper(SParticleDeflector* _deflector)
{
m_pDeflector = _deflector;
m_bOnHeap = false;
m_Position = gcnew nGENEToolset::Vector3(NULL);
m_Normal = gcnew nGENEToolset::Vector3(NULL);
m_Position->x = m_pDeflector->plane.getPlanePoint().x;
m_Position->y = m_pDeflector->plane.getPlanePoint().y;
m_Position->z = m_pDeflector->plane.getPlanePoint().z;
m_Normal->x = m_pDeflector->plane.getPlaneNormal().x;
m_Normal->y = m_pDeflector->plane.getPlaneNormal().y;
m_Normal->z = m_pDeflector->plane.getPlaneNormal().z;
this->Name = "ParticleDeflector" + (s_nDeflectorsCount);
this->Key = "ParticleDeflector" + (s_nDeflectorsCount++);
}
virtual ~ParticleDeflectorWrapper()
{
if(m_bOnHeap)
NGENE_DELETE(m_pDeflector);
}
[Browsable(true), CategoryAttribute("Deflector"),
DescriptionAttribute("Deflector bounciness")]
property Real Bounciness
{
Real get()
{
return m_pDeflector->restitution;
}
void set(Real value)
{
m_pDeflector->restitution = value;
}
}
[Browsable(true), CategoryAttribute("Deflector"),
DescriptionAttribute("Position of the deflector")]
property nGENEToolset::Vector3^ Position
{
nGENEToolset::Vector3^ get()
{
m_pDeflector->plane.setPlane(m_pDeflector->plane.getPlaneNormal(),
nGENE::Point(m_Position->x,
m_Position->y,
m_Position->z));
return m_Position;
}
void set(nGENEToolset::Vector3^ value)
{
m_Position->x = value->x;
m_Position->y = value->y;
m_Position->z = value->z;
}
}
[Browsable(true), CategoryAttribute("Deflector"),
DescriptionAttribute("Normal vector of the deflector plane")]
property nGENEToolset::Vector3^ Normal
{
nGENEToolset::Vector3^ get()
{
m_pDeflector->plane.setPlane(m_Normal->getVector(),
m_pDeflector->plane.getPlanePoint());
return m_Normal;
}
void set(nGENEToolset::Vector3^ value)
{
m_Normal->x = value->x;
m_Normal->y = value->y;
m_Normal->z = value->z;
}
}
SParticleDeflector* getDeflector()
{
return m_pDeflector;
}
void setDeflector(SParticleDeflector* _deflector)
{
if(m_bOnHeap)
{
NGENE_DELETE(m_pDeflector);
m_bOnHeap = false;
}
m_pDeflector = _deflector;
}
};
/// Wrapper for particle force structure.
ref class ParticleForceWrapper: public SceneNode
{
protected:
SParticleForce* m_pForce;
nGENEToolset::Vector3^ m_Position;
bool m_bOnHeap;
static int s_nForcesCount;
public:
ParticleForceWrapper()
{
m_pForce = new SParticleForce();
m_bOnHeap = true;
m_Position = gcnew nGENEToolset::Vector3(&m_pForce->vecPosition);
this->Name = "ParticleForce" + (s_nForcesCount);
this->Key = "ParticleForce" + (s_nForcesCount++);
}
ParticleForceWrapper(SParticleForce* _force)
{
m_pForce = _force;
m_bOnHeap = false;
m_Position = gcnew nGENEToolset::Vector3(&m_pForce->vecPosition);
this->Name = "ParticleForce" + (s_nForcesCount);
this->Key = "ParticleForce" + (s_nForcesCount++);
}
virtual ~ParticleForceWrapper()
{
if(m_bOnHeap)
NGENE_DELETE(m_pForce);
}
[Browsable(true), CategoryAttribute("Force"),
DescriptionAttribute("Position of the force")]
property nGENEToolset::Vector3^ Position
{
nGENEToolset::Vector3^ get()
{
m_pForce->vecPosition = nGENE::Vector3(m_Position->x,
m_Position->y,
m_Position->z);
return m_Position;
}
void set(nGENEToolset::Vector3^ value)
{
m_Position->x = value->x;
m_Position->y = value->y;
m_Position->z = value->z;
}
}
[Browsable(true), CategoryAttribute("Force"),
DescriptionAttribute("Strength of the force")]
property Real Strength
{
Real get()
{
return m_pForce->fStrength;
}
void set(Real value)
{
m_pForce->fStrength = value;
}
}
[Browsable(true), CategoryAttribute("Force"),
DescriptionAttribute("Linear attenuation with distance")]
property Real LinearAttenuation
{
Real get()
{
return m_pForce->fLinearAtt;
}
void set(Real value)
{
m_pForce->fLinearAtt = value;
}
}
[Browsable(true), CategoryAttribute("Force"),
DescriptionAttribute("Quadratic attenuation with distance")]
property Real QuadraticAttenuation
{
Real get()
{
return m_pForce->fQuadraticAtt;
}
void set(Real value)
{
m_pForce->fQuadraticAtt = value;
}
}
SParticleForce* getForce()
{
return m_pForce;
}
void setForce(SParticleForce* _force)
{
if(m_bOnHeap)
{
NGENE_DELETE(m_pForce);
m_bOnHeap = false;
}
m_pForce = _force;
m_Position->setPointer(&m_pForce->vecPosition);
}
};
/// Wrapper for particle colour structure.
ref class ParticleColourWrapper: public SceneNode
{
protected:
PARTICLE_COLOUR* m_pColour;
ParticleEmitter* m_pEmitter;
ParticleEmitterWrapper^ m_Emitter;
Color m_Colour;
bool m_bOnHeap;
static int s_nColoursCount;
public:
ParticleColourWrapper()
{
m_pColour = new PARTICLE_COLOUR();
m_bOnHeap = true;
this->Name = "ParticleColour" + (s_nColoursCount);
this->Key = "ParticleColour" + (s_nColoursCount++);
m_pEmitter = NULL;
}
ParticleColourWrapper(PARTICLE_COLOUR* _colour)
{
m_pColour = _colour;
m_bOnHeap = false;
this->Name = "ParticleColour" + (s_nColoursCount);
this->Key = "ParticleColour" + (s_nColoursCount++);
m_pEmitter = NULL;
}
virtual ~ParticleColourWrapper()
{
if(m_bOnHeap)
NGENE_DELETE(m_pColour);
}
[Browsable(true), CategoryAttribute("Colour"),
DescriptionAttribute("Colour of the particle")]
property System::Drawing::Color Colour
{
Color get()
{
return m_Colour;
}
void set(Color value)
{
m_Colour = value;
m_pColour->colour.setRed(value.R);
m_pColour->colour.setGreen(value.G);
m_pColour->colour.setBlue(value.B);
}
}
[Browsable(true), CategoryAttribute("Animation"),
DescriptionAttribute("Time when colour should reach this value")]
property Real Stage
{
Real get()
{
return m_pColour->fLifeTimeLevel;
}
void set(Real value)
{
if(value >= 0.0f && value <= 1.0f)
{
refreshEmitter(value);
}
else
{
System::Windows::Forms::MessageBox::Show("Invalid value. Values are limited to 0 to 1 range.",
"Invalid value",
System::Windows::Forms::MessageBoxButtons::OK,
System::Windows::Forms::MessageBoxIcon::Warning);
}
}
}
[Browsable(true), CategoryAttribute("Colour"),
DescriptionAttribute("Transparency level")]
property nGENE::byte Transparency
{
nGENE::byte get()
{
return m_pColour->colour.getAlpha();
}
void set(nGENE::byte value)
{
m_pColour->colour.setAlpha(value);
}
}
PARTICLE_COLOUR* getColour()
{
return m_pColour;
}
void setColour(PARTICLE_COLOUR* _colour)
{
if(m_bOnHeap)
{
NGENE_DELETE(m_pColour);
m_bOnHeap = false;
}
m_pColour = _colour;
}
void setEmitter(ParticleEmitterWrapper^ _emitter)
{
m_Emitter = _emitter;
}
private: void refreshEmitter(float value);
};
/// Wrapper for a ParticleEmitter class
ref class ParticleEmitterWrapper: public SceneNode
{
protected:
ParticleEmitter* m_pEmitter;
bool m_bOnHeap;
static int s_nEmittersCount;
nGENEToolset::Vector3^ m_Position;
nGENEToolset::Vector3^ m_Velocity;
nGENEToolset::Vector3^ m_VelocitySpread;
nGENEToolset::Vector3^ m_Accel;
nGENEToolset::Vector3^ m_AccelSpread;
System::Collections::ArrayList^ m_ColoursList;
public:
ParticleEmitterWrapper();
ParticleEmitterWrapper(ParticleEmitter* _emitter);
virtual ~ParticleEmitterWrapper()
{
if(m_bOnHeap)
NGENE_DELETE(m_pEmitter);
}
ParticleEmitter* getEmitter()
{
return m_pEmitter;
}
[Browsable(true), CategoryAttribute("Emission"),
DescriptionAttribute("Maximum number of particles emitted")]
property uint MaxParticlesCount
{
uint get()
{
return m_pEmitter->getParticlesMaxCount();
}
void set(uint value)
{
if(!frmRenderTarget::engine->tryLock())
return;
m_pEmitter->setParticlesMaxCount(value);
frmRenderTarget::engine->releaseLock();
}
}
[Browsable(true), CategoryAttribute("Emission"),
DescriptionAttribute("Number of particles spawned per second")]
property uint SpawnRate
{
uint get()
{
return m_pEmitter->getSpawnRate();
}
void set(uint value)
{
m_pEmitter->setSpawnRate(value);
}
}
[Browsable(true), CategoryAttribute("Emission"),
DescriptionAttribute("Time in milliseconds without emitting particles (warm-up time)")]
property uint WarmUpTime
{
uint get()
{
return m_pEmitter->getWarmUpTime();
}
void set(uint value)
{
m_pEmitter->setWarmUpTime(value);
}
}
[Browsable(true), CategoryAttribute("Particles"),
DescriptionAttribute("Average size of a particle")]
property float Size
{
float get()
{
return m_pEmitter->getSize();
}
void set(float value)
{
m_pEmitter->setSize(value);
}
}
[Browsable(true), CategoryAttribute("Particles"),
DescriptionAttribute("Deviation of size of a particle")]
property float SizeSpread
{
float get()
{
return m_pEmitter->getSizeSpread();
}
void set(float value)
{
m_pEmitter->setSizeSpread(value);
}
}
[Browsable(true), CategoryAttribute("Particles"),
DescriptionAttribute("Average particle growth per second")]
property float Growth
{
float get()
{
return m_pEmitter->getGrowth();
}
void set(float value)
{
m_pEmitter->setGrowth(value);
}
}
[Browsable(true), CategoryAttribute("Particles"),
DescriptionAttribute("Deviation of growth of a particle")]
property float GrowthSpread
{
float get()
{
return m_pEmitter->getGrowthSpread();
}
void set(float value)
{
m_pEmitter->setGrowthSpread(value);
}
}
[Browsable(true), CategoryAttribute("Particles"),
DescriptionAttribute("Average particle life time")]
property float LifeTime
{
float get()
{
return m_pEmitter->getLifeTime();
}
void set(float value)
{
m_pEmitter->setLifeTime(value);
}
}
[Browsable(true), CategoryAttribute("Particles"),
DescriptionAttribute("Deviation of life time of a particle")]
property float LifeTimeSpread
{
float get()
{
return m_pEmitter->getLifeTimeSpread();
}
void set(float value)
{
m_pEmitter->setLifeTimeSpread(value);
}
}
[Browsable(true), CategoryAttribute("Particles"),
DescriptionAttribute("Modifies fading factor of a particle")]
property float FadeSpeed
{
float get()
{
return m_pEmitter->getFadeSpeed();
}
void set(float value)
{
m_pEmitter->setFadeSpeed(value);
}
}
[Browsable(true), CategoryAttribute("Movement"),
DescriptionAttribute("Average angular velocity of a particle")]
property float AngularVelocity
{
float get()
{
return m_pEmitter->getAngularVelocity();
}
void set(float value)
{
m_pEmitter->setAngularVelocity(value);
}
}
[Browsable(true), CategoryAttribute("Movement"),
DescriptionAttribute("Deviation of angular velocity of a particle")]
property float AngularVelocitySpread
{
float get()
{
return m_pEmitter->getAngularVelocitySpread();
}
void set(float value)
{
m_pEmitter->setAngularVelocitySpread(value);
}
}
[Browsable(true), CategoryAttribute("Movement"),
DescriptionAttribute("Starting position of a particle in regard to particle system position")]
property nGENEToolset::Vector3^ ParticlePosition
{
nGENEToolset::Vector3^ get()
{
m_pEmitter->setPosition(m_Position->x,
m_Position->y,
m_Position->z);
return m_Position;
}
void set(nGENEToolset::Vector3^ value)
{
m_Position->x = value->x;
m_Position->y = value->y;
m_Position->z = value->z;
}
}
[Browsable(true), CategoryAttribute("Movement"),
DescriptionAttribute("Starting average velocity of a particle")]
property nGENEToolset::Vector3^ Velocity
{
nGENEToolset::Vector3^ get()
{
m_pEmitter->setVelocity(m_Velocity->x,
m_Velocity->y,
m_Velocity->z);
return m_Velocity;
}
void set(nGENEToolset::Vector3^ value)
{
m_Velocity->x = value->x;
m_Velocity->y = value->y;
m_Velocity->z = value->z;
}
}
[Browsable(true), CategoryAttribute("Movement"),
DescriptionAttribute("Deviation of velocity of a particle")]
property nGENEToolset::Vector3^ VelocitySpread
{
nGENEToolset::Vector3^ get()
{
m_pEmitter->setVelocitySpread(m_VelocitySpread->x,
m_VelocitySpread->y,
m_VelocitySpread->z);
return m_VelocitySpread;
}
void set(nGENEToolset::Vector3^ value)
{
m_VelocitySpread->x = value->x;
m_VelocitySpread->y = value->y;
m_VelocitySpread->z = value->z;
}
}
[Browsable(true), CategoryAttribute("Movement"),
DescriptionAttribute("Starting average acceleration of a particle")]
property nGENEToolset::Vector3^ Acceleration
{
nGENEToolset::Vector3^ get()
{
m_pEmitter->setAcceleration(m_Accel->x,
m_Accel->y,
m_Accel->z);
return m_Accel;
}
void set(nGENEToolset::Vector3^ value)
{
m_Accel->x = value->x;
m_Accel->y = value->y;
m_Accel->z = value->z;
}
}
[Browsable(true), CategoryAttribute("Movement"),
DescriptionAttribute("Deviation of acceleration of a particle")]
property nGENEToolset::Vector3^ AccelerationSpread
{
nGENEToolset::Vector3^ get()
{
m_pEmitter->setAccelerationSpread(m_AccelSpread->x,
m_AccelSpread->y,
m_AccelSpread->z);
return m_AccelSpread;
}
void set(nGENEToolset::Vector3^ value)
{
m_AccelSpread->x = value->x;
m_AccelSpread->y = value->y;
m_AccelSpread->z = value->z;
}
}
/// Adds particle colour wrapper to this particle emitter (also to a wrapper ;) )
System::Void addColour(ParticleColourWrapper^ colour);
System::Void addForce(ParticleForceWrapper^ force);
System::Void addDeflector(ParticleDeflectorWrapper^ deflector);
System::Void sortColours()
{
if(!frmRenderTarget::engine->tryLock())
return;
m_pEmitter->sortColours();
for(unsigned int i = 0; i < m_pEmitter->getParticleColoursNum(); ++i)
{
((ParticleColourWrapper^)m_ColoursList[i])->setColour(m_pEmitter->getParticleColour(i));
((ParticleColourWrapper^)m_ColoursList[i])->Colour = Color::FromArgb(255,
m_pEmitter->getParticleColour(i)->colour.getRed(),
m_pEmitter->getParticleColour(i)->colour.getGreen(),
m_pEmitter->getParticleColour(i)->colour.getBlue());
}
frmRenderTarget::engine->releaseLock();
}
public:
void parseColours();
void parseForces();
void parseDeflectors();
};
/// Wrapper for a NodeParticleSystem class.
ref class ParticleSystemWrapper: public NodeVisibleWrapper
{
protected:
NodeParticleSystem* m_pPS;
static int s_nPSCount;
public:
ParticleSystemWrapper();
ParticleSystemWrapper(NodeParticleSystem* _ps, String^ _name);
virtual ~ParticleSystemWrapper()
{
}
/// Adds particle emitter wrapper to this particle system (also to a wrapper ;) )
System::Void addEmitter(ParticleEmitterWrapper^ emitter);
};
}
#endif | [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | [
[
[
1,
804
]
]
] |
c038239c898ecf36c4f0c32c343e7dd4aa08c397 | 4d8a6d75e1b61f38417232cf3a448eb5d368d1af | /SamArchiveManager/SamException.cpp | 818fc05da221f4e4730993cbb86199e1b7b04b3f | [] | no_license | kux/sam-archiver | 5894337c29be74fa3018943343d3d09ee1380183 | c4184e3f142dbc52d973798a08ebd52da8fb7e93 | refs/heads/master | 2021-01-10T21:42:27.687854 | 2009-12-06T23:43:26 | 2009-12-06T23:43:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | #include "SamException.h"
bool SamException::isInitialized_ = false;
std::map<int , std::string> SamException::SamExceptionMap_;
const int SamException::FILE_NO_EXIST = 0 ;
const int SamException::INVALID_PATH = 1;
const int SamException::METHOD_NOT_SUPPORTED = 2;
const int SamException::UNABLE_TO_OPEN_FILE = 3;
const int SamException::FILE_TO_BIG = 4;
const int SamException::UNABLE_TO_READ_FILE = 5; | [
"kux@080cfd25-d5d9-4c59-82ea-70d02a200d8b"
] | [
[
[
1,
11
]
]
] |
7b854de4edd2e4ce00592da512df952ba61a813e | b4d726a0321649f907923cc57323942a1e45915b | /CODE/ImpED/WaypointPathDlg.h | 4d5259d3acecf8266e4ef99ea48dec4a0d2cff96 | [] | no_license | chief1983/Imperial-Alliance | f1aa664d91f32c9e244867aaac43fffdf42199dc | 6db0102a8897deac845a8bd2a7aa2e1b25086448 | refs/heads/master | 2016-09-06T02:40:39.069630 | 2010-10-06T22:06:24 | 2010-10-06T22:06:24 | 967,775 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,582 | h | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on the
* source.
*
*/
/*
* $Logfile: /Freespace2/code/FRED2/WaypointPathDlg.h $
* $Revision: 1.1.1.1 $
* $Date: 2002/07/15 03:11:03 $
* $Author: inquisitor $
*
* Waypoint editor
*
* $Log: WaypointPathDlg.h,v $
* Revision 1.1.1.1 2002/07/15 03:11:03 inquisitor
* Initial FRED2 Checking
*
*
* 2 10/07/98 6:28p Dave
* Initial checkin. Renamed all relevant stuff to be Fred2 instead of
* Fred. Globalized mission and campaign file extensions. Removed Silent
* Threat specific code.
*
* 1 10/07/98 3:02p Dave
*
* 1 10/07/98 3:00p Dave
*
* 4 5/23/97 1:53p Hoffoss
* Fixed problems with modeless dialog updating. It won't get caught in
* an infinate loop anymore, but still gives an error warning 3 times when
* using cancel and trying to switch window focus to main window. Don't
* know if I can fix that, but it's not too critical right now.
*
* 3 3/13/97 12:09p Hoffoss
* Waypoint path editor finished (apparently I didn't get around to
* completing it before).
*
* 2 2/12/97 12:26p Hoffoss
* Expanded on global error checker, added initial orders conflict
* checking and warning, added waypoint editor dialog and code.
*
* $NoKeywords: $
*/
#ifndef _WAYPOINTPATHDLG_H
#define _WAYPOINTPATHDLG_H
/////////////////////////////////////////////////////////////////////////////
// waypoint_path_dlg dialog
class waypoint_path_dlg : public CDialog
{
// Construction
public:
int bypass_errors;
int update_data(int redraw = 1);
void initialize_data(int full_update);
void OnOK();
BOOL Create();
waypoint_path_dlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(waypoint_path_dlg)
enum { IDD = IDD_WAYPOINT_PATH_EDITOR };
CString m_name;
int m_iff;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(waypoint_path_dlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
virtual void OnSelChangeIff();
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(waypoint_path_dlg)
afx_msg void OnInitMenu(CMenu* pMenu);
afx_msg void OnClose();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#endif | [
"[email protected]"
] | [
[
[
1,
93
]
]
] |
1e7567d6a1fd7646b70e5a0cf534ec7785bd334f | bfcc0f6ef5b3ec68365971fd2e7d32f4abd054ed | /vheap.cpp | 0c9670be3eed0370af2833f52834a5d8dec0df8c | [] | no_license | cnsuhao/kgui-1 | d0a7d1e11cc5c15d098114051fabf6218f26fb96 | ea304953c7f5579487769258b55f34a1c680e3ed | refs/heads/master | 2021-05-28T22:52:18.733717 | 2011-03-10T03:10:47 | 2011-03-10T03:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,473 | cpp | /**********************************************************************************/
/* kGUI - vheap.cpp */
/* */
/* Programmed by Kevin Pickell */
/* */
/* http://code.google.com/p/kgui/ */
/* */
/* kGUI 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; version 2. */
/* */
/* kGUI 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. */
/* */
/* http://www.gnu.org/licenses/lgpl.txt */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with kGUI; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* */
/**********************************************************************************/
/*! @file heap.cpp
@brief VHeap is .... */
/* used for array template */
#include "kgui.h"
#include "vheap.h"
VHeap::VHeap()
{
m_blocksizepow2=0;
m_blocksizebytes=0;
m_blocksizemask=0;
m_maxblocksinmem=0;
m_numblocks=0;
m_used=0;
m_file=0;
/* init active linked list to no entries */
m_head.m_next=&m_tail;
m_tail.m_prev=&m_head;
}
VHeap::~VHeap()
{
VHEAP_BLOCK *vr;
/* purge all allocated blocks */
vr=m_head.m_next;
while(vr!=&m_tail)
{
delete []vr->m_addr;
vr=vr->m_next;
}
if(m_file)
fclose(m_file);
}
void VHeap::Init(unsigned int blocksizepow2,unsigned int maxblocksinmem,const char *filename)
{
m_blocksizepow2=blocksizepow2;
m_blocksizebytes=1<<blocksizepow2;
m_blocksizemask=m_blocksizebytes-1;
m_maxblocksinmem=maxblocksinmem;
m_file=fopen(filename,"wb+");
assert(m_file!=0,"Error opening VHeap file for write");
m_used=0;
m_numblocks=0;
m_blocks.Init(maxblocksinmem,-1); /* double in size if too small */
/* init active linked list to no entries */
m_head.m_next=&m_tail;
m_tail.m_prev=&m_head;
}
vheap_offset VHeap::Alloc(unsigned int numbytes)
{
vheap_offset off=m_used;
unsigned int endblock;
m_used+=numbytes;
/* do we need to allocate another block?? */
endblock=(unsigned int)(m_used>>m_blocksizepow2);
while(m_numblocks<=endblock)
{
/* add a new end block */
VHEAP_BLOCK *vb;
vb=m_blocks.GetEntryPtr(m_numblocks);
vb->m_offset=(vheap_offset)m_numblocks<<m_blocksizepow2;
vb->m_dirty=0;
if(m_numblocks<m_maxblocksinmem)
{
VHEAP_BLOCK *next;
/* allocate ram for this block and add to in mem linked list */
vb->m_addr=new unsigned char[m_blocksizebytes];
vb->m_new=false;
/* add to head of active linked list */
next=m_head.m_next;
vb->m_prev=&m_head;
vb->m_next=next;
m_head.m_next=vb;
next->m_prev=vb;
}
else
{
/* not active yet */
vb->m_addr=0;
vb->m_new=true;
vb->m_prev=0;
vb->m_next=0;
}
++m_numblocks;
}
return(off);
}
void VHeap::Write(const void *data,vheap_offset offset,unsigned int numbytes)
{
unsigned int startblock;
unsigned int endblock;
VHEAP_BLOCK *vb;
unsigned int boffset;
const unsigned char *cdata=(const unsigned char *)data;
startblock=(unsigned int)(offset>>m_blocksizepow2);
boffset=(unsigned int)(offset&m_blocksizemask);
endblock=(unsigned int)((offset+numbytes)>>m_blocksizepow2);
vb=Activate(startblock);
if(startblock==endblock)
{
memcpy(vb->m_addr+boffset,cdata,numbytes);
vb->m_dirty=true;
}
else
{
unsigned int chunk;
/* write to remainer at the end of the start block */
chunk=(unsigned int)(m_blocksizebytes-boffset);
memcpy(vb->m_addr+boffset,cdata,chunk);
vb->m_dirty=true;
cdata+=chunk;
numbytes-=chunk;
/* copy full blocks */
while(numbytes>=m_blocksizebytes)
{
vb=Activate(++startblock);
memcpy(vb->m_addr,cdata,m_blocksizebytes);
vb->m_dirty=true;
cdata+=m_blocksizebytes;
numbytes-=m_blocksizebytes;
}
if(numbytes)
{
vb=Activate(++startblock);
memcpy(vb->m_addr,cdata,numbytes);
vb->m_dirty=true;
}
}
}
void VHeap::Read(void *data,vheap_offset offset,unsigned int numbytes)
{
unsigned int startblock;
unsigned int endblock;
unsigned int boffset;
VHEAP_BLOCK *vb;
unsigned char *cdata=(unsigned char *)data;
startblock=(unsigned int)(offset>>m_blocksizepow2);
boffset=(unsigned int)(offset&m_blocksizemask);
endblock=(unsigned int)((offset+numbytes)>>m_blocksizepow2);
vb=Activate(startblock);
if(startblock==endblock)
memcpy(cdata,vb->m_addr+boffset,numbytes);
else
{
unsigned int chunk;
/* read to remainer at the end of the start block */
chunk=(unsigned int)(m_blocksizebytes-boffset);
memcpy(cdata,vb->m_addr+boffset,chunk);
cdata+=chunk;
numbytes-=chunk;
/* copy full blocks */
while(numbytes>=m_blocksizebytes)
{
vb=Activate(++startblock);
memcpy(cdata,vb->m_addr,m_blocksizebytes);
cdata+=m_blocksizebytes;
numbytes-=m_blocksizebytes;
}
if(numbytes)
{
vb=Activate(++startblock);
memcpy(cdata,vb->m_addr,numbytes);
}
}
}
VHEAP_BLOCK *VHeap::Activate(unsigned int blocknum)
{
VHEAP_BLOCK *vr=m_blocks.GetEntryPtr(blocknum);
VHEAP_BLOCK *prev;
VHEAP_BLOCK *next;
VHEAP_BLOCK *old;
#if defined(WIN32) || defined(MINGW)
fpos_t pos;
#endif
int sok;
assert(blocknum<m_numblocks,"Error: referencing unallocated block");
/* if we are already the first in the linked list of active blocks then return */
if(m_head.m_next==vr)
return(vr);
/* are we in memory already? */
if(vr->m_addr)
{
/* remove from old spot */
prev=vr->m_prev;
next=vr->m_next;
prev->m_next=next;
next->m_prev=prev;
/* add to the top */
next=m_head.m_next;
vr->m_prev=&m_head;
vr->m_next=next;
m_head.m_next=vr;
next->m_prev=vr;
return(vr);
}
/* we are not in memory at this point, so we will */
/* write out the last referenced block to the cache file */
old=m_tail.m_prev;
if(old->m_dirty)
{
old->m_dirty=false;
#if defined(WIN32) || defined(MINGW)
pos=old->m_offset;
sok=fsetpos(m_file,&pos);
#else
sok=fseek(m_file,old->m_offset,SEEK_SET);
#endif
assert(sok==0,"Seek error!");
if(fwrite(old->m_addr,1,m_blocksizebytes,m_file)!=m_blocksizebytes)
{
assert(false,"Write Error!");
}
}
/* remove it from the active list */
prev=old->m_prev;
next=old->m_next;
prev->m_next=next;
next->m_prev=prev;
/* move the memory pointer to new block, clear it in old block */
vr->m_addr=old->m_addr;
old->m_addr=0;
/* if this is a new block then we don't load it */
if(vr->m_new)
{
vr->m_new=false;
/* clear the buffer, probably not really necessary */
memset(vr->m_addr,0,m_blocksizebytes);
vr->m_dirty=true;
}
else
{
/* load our data back from the cache file */
#if defined(WIN32) || defined(MINGW)
pos=vr->m_offset;
sok=fsetpos(m_file,&pos);
#else
sok=fseek(m_file,vr->m_offset,SEEK_SET);
#endif
assert(sok==0,"Seek error!");
if(fread(vr->m_addr,1,m_blocksizebytes,m_file)!=m_blocksizebytes)
{
assert(false,"Read Error!");
}
vr->m_dirty=false;
}
/* add us to the head of the active list */
next=m_head.m_next;
vr->m_prev=&m_head;
vr->m_next=next;
m_head.m_next=vr;
next->m_prev=vr;
return(vr);
}
| [
"[email protected]@4b35e2fd-144d-0410-91a6-811dcd9ab31d"
] | [
[
[
1,
310
]
]
] |
f113acdee09dfb9f86dbf5f3104cb6d8875ea04f | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/TextImpl.cpp | 9cba8fb5d59ae1d5d809b808ab12b33b112e6f08 | [
"Apache-2.0"
] | permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,554 | cpp | /*
* Copyright 1999-2002,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: TextImpl.cpp,v 1.5 2004/09/08 13:55:44 peiyongz Exp $
*/
#include "DocumentImpl.hpp"
#include "DOM_DOMException.hpp"
#include "DOM_Node.hpp"
#include "TextImpl.hpp"
#include "CharacterDataImpl.hpp"
#include "DStringPool.hpp"
#include "RangeImpl.hpp"
XERCES_CPP_NAMESPACE_BEGIN
static DOMString *gText = 0; // will be lazily initialized to point to "#text"
static XMLRegisterCleanup gTextCleanup;
TextImpl::TextImpl(DocumentImpl *ownerDoc, const DOMString &dat)
: CharacterDataImpl(ownerDoc, dat)
{
};
TextImpl::TextImpl(const TextImpl &other, bool deep)
: CharacterDataImpl(other, deep)
{
};
TextImpl::~TextImpl()
{
};
bool TextImpl::isTextImpl()
{
return true;
};
NodeImpl *TextImpl::cloneNode(bool deep)
{
return new (getOwnerDocument()->getMemoryManager()) TextImpl(*this, deep);
};
DOMString TextImpl::getNodeName() {
return DStringPool::getStaticString("#text"
, &gText
, reinitTextImpl
, gTextCleanup
);
}
short TextImpl::getNodeType() {
return DOM_Node::TEXT_NODE;
};
TextImpl *TextImpl::splitText(unsigned int offset)
{
if (isReadOnly())
{
throw DOM_DOMException(
DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);
}
unsigned int len = data.length();
if (offset > len || offset < 0)
throw DOM_DOMException(DOM_DOMException::INDEX_SIZE_ERR, null);
TextImpl *newText =
(TextImpl *) getOwnerDocument()->createTextNode(
data.substringData(offset, data.length() - offset));
NodeImpl *parent = getParentNode();
if (parent != null)
parent->insertBefore(newText, getNextSibling());
data = data.substringData(0, offset);
if (this->getOwnerDocument() != null) {
typedef RefVectorOf<RangeImpl> RangeImpls;
RangeImpls* ranges = this->getOwnerDocument()->getRanges();
if (ranges != null) {
unsigned int sz = ranges->size();
if (sz != 0) {
for (unsigned int i =0; i<sz; i++) {
ranges->elementAt(i)->updateSplitInfo( this, newText, offset);
}
}
}
}
return newText;
};
bool TextImpl::isIgnorableWhitespace()
{
return ignorableWhitespace();
}
void TextImpl::setIgnorableWhitespace(bool ignorable)
{
ignorableWhitespace(ignorable);
}
// -----------------------------------------------------------------------
// Notification that lazy data has been deleted
// -----------------------------------------------------------------------
void TextImpl::reinitTextImpl() {
delete gText;
gText = 0;
}
XERCES_CPP_NAMESPACE_END
| [
"[email protected]"
] | [
[
[
1,
135
]
]
] |
05c8ad7e99a47045600f66ccac1bfe7e6dcbdc14 | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/Qt/q3canvas.h | 84496806e3802b5889dc7c647ea1899a353b9d6d | [
"BSD-2-Clause"
] | permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,806 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the Qt3Support module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef Q3CANVAS_H
#define Q3CANVAS_H
#include <Qt3Support/q3scrollview.h>
#include <QtGui/qpixmap.h>
#include <Qt3Support/q3ptrlist.h>
#include <QtGui/qbrush.h>
#include <QtGui/qpen.h>
#include <Qt3Support/q3valuelist.h>
#include <Qt3Support/q3pointarray.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Qt3Support)
class Q3CanvasSprite;
class Q3CanvasPolygonalItem;
class Q3CanvasRectangle;
class Q3CanvasPolygon;
class Q3CanvasEllipse;
class Q3CanvasText;
class Q3CanvasLine;
class Q3CanvasChunk;
class Q3Canvas;
class Q3CanvasItem;
class Q3CanvasView;
class Q3CanvasPixmap;
class Q_COMPAT_EXPORT Q3CanvasItemList : public Q3ValueList<Q3CanvasItem*> {
public:
void sort();
void drawUnique(QPainter& painter);
Q3CanvasItemList operator+(const Q3CanvasItemList &l) const;
};
class Q3CanvasItemExtra;
class Q_COMPAT_EXPORT Q3CanvasItem
{
public:
Q3CanvasItem(Q3Canvas* canvas);
virtual ~Q3CanvasItem();
double x() const
{ return myx; }
double y() const
{ return myy; }
double z() const
{ return myz; } // (depth)
virtual void moveBy(double dx, double dy);
void move(double x, double y);
void setX(double a) { move(a,y()); }
void setY(double a) { move(x(),a); }
void setZ(double a) { myz=a; changeChunks(); }
bool animated() const;
virtual void setAnimated(bool y);
virtual void setVelocity(double vx, double vy);
void setXVelocity(double vx) { setVelocity(vx,yVelocity()); }
void setYVelocity(double vy) { setVelocity(xVelocity(),vy); }
double xVelocity() const;
double yVelocity() const;
virtual void advance(int stage);
virtual bool collidesWith(const Q3CanvasItem*) const=0;
Q3CanvasItemList collisions(bool exact /* NO DEFAULT */) const;
virtual void setCanvas(Q3Canvas*);
virtual void draw(QPainter&)=0;
void show();
void hide();
virtual void setVisible(bool yes);
bool isVisible() const
{ return (bool)vis; }
virtual void setSelected(bool yes);
bool isSelected() const
{ return (bool)sel; }
virtual void setEnabled(bool yes);
bool isEnabled() const
{ return (bool)ena; }
virtual void setActive(bool yes);
bool isActive() const
{ return (bool)act; }
bool visible() const
{ return (bool)vis; }
bool selected() const
{ return (bool)sel; }
bool enabled() const
{ return (bool)ena; }
bool active() const
{ return (bool)act; }
enum RttiValues {
Rtti_Item = 0,
Rtti_Sprite = 1,
Rtti_PolygonalItem = 2,
Rtti_Text = 3,
Rtti_Polygon = 4,
Rtti_Rectangle = 5,
Rtti_Ellipse = 6,
Rtti_Line = 7,
Rtti_Spline = 8
};
virtual int rtti() const;
static int RTTI;
virtual QRect boundingRect() const=0;
virtual QRect boundingRectAdvanced() const;
Q3Canvas* canvas() const
{ return cnv; }
protected:
void update() { changeChunks(); }
private:
// For friendly subclasses...
friend class Q3CanvasPolygonalItem;
friend class Q3CanvasSprite;
friend class Q3CanvasRectangle;
friend class Q3CanvasPolygon;
friend class Q3CanvasEllipse;
friend class Q3CanvasText;
friend class Q3CanvasLine;
virtual Q3PointArray chunks() const;
virtual void addToChunks();
virtual void removeFromChunks();
virtual void changeChunks();
virtual bool collidesWith(const Q3CanvasSprite*,
const Q3CanvasPolygonalItem*,
const Q3CanvasRectangle*,
const Q3CanvasEllipse*,
const Q3CanvasText*) const = 0;
// End of friend stuff
Q3Canvas* cnv;
static Q3Canvas* current_canvas;
double myx,myy,myz;
Q3CanvasItemExtra *ext;
Q3CanvasItemExtra& extra();
uint ani:1;
uint vis:1;
uint val:1;
uint sel:1;
uint ena:1;
uint act:1;
};
class Q3CanvasData;
class Q_COMPAT_EXPORT Q3Canvas : public QObject
{
Q_OBJECT
public:
Q3Canvas(QObject* parent = 0, const char* name = 0);
Q3Canvas(int w, int h);
Q3Canvas(QPixmap p, int h, int v, int tilewidth, int tileheight);
virtual ~Q3Canvas();
virtual void setTiles(QPixmap tiles, int h, int v,
int tilewidth, int tileheight);
virtual void setBackgroundPixmap(const QPixmap& p);
QPixmap backgroundPixmap() const;
virtual void setBackgroundColor(const QColor& c);
QColor backgroundColor() const;
virtual void setTile(int x, int y, int tilenum);
int tile(int x, int y) const
{ return grid[x+y*htiles]; }
int tilesHorizontally() const
{ return htiles; }
int tilesVertically() const
{ return vtiles; }
int tileWidth() const
{ return tilew; }
int tileHeight() const
{ return tileh; }
virtual void resize(int width, int height);
int width() const
{ return awidth; }
int height() const
{ return aheight; }
QSize size() const
{ return QSize(awidth,aheight); }
QRect rect() const
{ return QRect(0, 0, awidth, aheight); }
bool onCanvas(int x, int y) const
{ return x>=0 && y>=0 && x<awidth && y<aheight; }
bool onCanvas(const QPoint& p) const
{ return onCanvas(p.x(),p.y()); }
bool validChunk(int x, int y) const
{ return x>=0 && y>=0 && x<chwidth && y<chheight; }
bool validChunk(const QPoint& p) const
{ return validChunk(p.x(),p.y()); }
int chunkSize() const
{ return chunksize; }
virtual void retune(int chunksize, int maxclusters=100);
bool sameChunk(int x1, int y1, int x2, int y2) const
{ return x1/chunksize==x2/chunksize && y1/chunksize==y2/chunksize; }
virtual void setChangedChunk(int i, int j);
virtual void setChangedChunkContaining(int x, int y);
virtual void setAllChanged();
virtual void setChanged(const QRect& area);
virtual void setUnchanged(const QRect& area);
// These call setChangedChunk.
void addItemToChunk(Q3CanvasItem*, int i, int j);
void removeItemFromChunk(Q3CanvasItem*, int i, int j);
void addItemToChunkContaining(Q3CanvasItem*, int x, int y);
void removeItemFromChunkContaining(Q3CanvasItem*, int x, int y);
Q3CanvasItemList allItems();
Q3CanvasItemList collisions(const QPoint&) const;
Q3CanvasItemList collisions(const QRect&) const;
Q3CanvasItemList collisions(const Q3PointArray& pa, const Q3CanvasItem* item,
bool exact) const;
void drawArea(const QRect&, QPainter* p, bool double_buffer=false);
// These are for Q3CanvasView to call
virtual void addView(Q3CanvasView*);
virtual void removeView(Q3CanvasView*);
void drawCanvasArea(const QRect&, QPainter* p=0, bool double_buffer=true);
void drawViewArea(Q3CanvasView* view, QPainter* p, const QRect& r, bool dbuf);
// These are for Q3CanvasItem to call
virtual void addItem(Q3CanvasItem*);
virtual void addAnimation(Q3CanvasItem*);
virtual void removeItem(Q3CanvasItem*);
virtual void removeAnimation(Q3CanvasItem*);
virtual void setAdvancePeriod(int ms);
virtual void setUpdatePeriod(int ms);
virtual void setDoubleBuffering(bool y);
Q_SIGNALS:
void resized();
public Q_SLOTS:
virtual void advance();
virtual void update();
protected:
virtual void drawBackground(QPainter&, const QRect& area);
virtual void drawForeground(QPainter&, const QRect& area);
private:
void init(int w, int h, int chunksze=16, int maxclust=100);
Q3CanvasChunk& chunk(int i, int j) const;
Q3CanvasChunk& chunkContaining(int x, int y) const;
QRect changeBounds(const QRect& inarea);
void ensureOffScrSize(int osw, int osh);
QPixmap offscr;
int awidth,aheight;
int chunksize;
int maxclusters;
int chwidth,chheight;
Q3CanvasChunk* chunks;
Q3CanvasData* d;
void initTiles(QPixmap p, int h, int v, int tilewidth, int tileheight);
ushort *grid;
ushort htiles;
ushort vtiles;
ushort tilew;
ushort tileh;
bool oneone;
QPixmap pm;
QTimer* update_timer;
QColor bgcolor;
bool debug_redraw_areas;
bool dblbuf;
friend void qt_unview(Q3Canvas* c);
Q_DISABLE_COPY(Q3Canvas)
};
class Q3CanvasViewData;
class Q_COMPAT_EXPORT Q3CanvasView : public Q3ScrollView
{
Q_OBJECT
public:
Q3CanvasView(QWidget* parent=0, const char* name=0, Qt::WindowFlags f=0);
Q3CanvasView(Q3Canvas* viewing, QWidget* parent=0, const char* name=0, Qt::WindowFlags f=0);
~Q3CanvasView();
Q3Canvas* canvas() const
{ return viewing; }
void setCanvas(Q3Canvas* v);
const QMatrix &worldMatrix() const;
const QMatrix &inverseWorldMatrix() const;
bool setWorldMatrix(const QMatrix &);
protected:
void drawContents(QPainter *p, int cx, int cy, int cw, int ch);
QSize sizeHint() const;
private:
friend class Q3Canvas;
void drawContents(QPainter*);
Q3Canvas* viewing;
Q3CanvasViewData* d;
friend void qt_unview(Q3Canvas* c);
private Q_SLOTS:
void updateContentsSize();
private:
Q_DISABLE_COPY(Q3CanvasView)
};
class Q_COMPAT_EXPORT Q3CanvasPixmap : public QPixmap
{
public:
#ifndef QT_NO_IMAGEIO
Q3CanvasPixmap(const QString& datafilename);
#endif
Q3CanvasPixmap(const QImage& image);
Q3CanvasPixmap(const QPixmap&, const QPoint& hotspot);
~Q3CanvasPixmap();
int offsetX() const
{ return hotx; }
int offsetY() const
{ return hoty; }
void setOffset(int x, int y) { hotx = x; hoty = y; }
private:
Q_DISABLE_COPY(Q3CanvasPixmap)
void init(const QImage&);
void init(const QPixmap& pixmap, int hx, int hy);
friend class Q3CanvasSprite;
friend class Q3CanvasPixmapArray;
friend bool qt_testCollision(const Q3CanvasSprite* s1, const Q3CanvasSprite* s2);
int hotx,hoty;
QImage* collision_mask;
};
class Q_COMPAT_EXPORT Q3CanvasPixmapArray
{
public:
Q3CanvasPixmapArray();
#ifndef QT_NO_IMAGEIO
Q3CanvasPixmapArray(const QString& datafilenamepattern, int framecount=0);
#endif
// this form is deprecated
Q3CanvasPixmapArray(Q3PtrList<QPixmap>, Q3PtrList<QPoint> hotspots);
Q3CanvasPixmapArray(Q3ValueList<QPixmap>, Q3PointArray hotspots = Q3PointArray());
~Q3CanvasPixmapArray();
#ifndef QT_NO_IMAGEIO
bool readPixmaps(const QString& datafilenamepattern, int framecount=0);
bool readCollisionMasks(const QString& filenamepattern);
#endif
// deprecated
bool operator!(); // Failure check.
bool isValid() const;
Q3CanvasPixmap* image(int i) const
{ return img ? img[i] : 0; }
void setImage(int i, Q3CanvasPixmap* p);
uint count() const
{ return (uint)framecount; }
private:
Q_DISABLE_COPY(Q3CanvasPixmapArray)
#ifndef QT_NO_IMAGEIO
bool readPixmaps(const QString& datafilenamepattern, int framecount, bool maskonly);
#endif
void reset();
int framecount;
Q3CanvasPixmap** img;
};
class Q_COMPAT_EXPORT Q3CanvasSprite : public Q3CanvasItem
{
public:
Q3CanvasSprite(Q3CanvasPixmapArray* array, Q3Canvas* canvas);
void setSequence(Q3CanvasPixmapArray* seq);
virtual ~Q3CanvasSprite();
void move(double x, double y);
virtual void move(double x, double y, int frame);
void setFrame(int);
enum FrameAnimationType { Cycle, Oscillate };
virtual void setFrameAnimation(FrameAnimationType=Cycle, int step=1, int state=0);
int frame() const
{ return frm; }
int frameCount() const
{ return images->count(); }
int rtti() const;
static int RTTI;
bool collidesWith(const Q3CanvasItem*) const;
QRect boundingRect() const;
// is there a reason for these to be protected? Lars
//protected:
int width() const;
int height() const;
int leftEdge() const;
int topEdge() const;
int rightEdge() const;
int bottomEdge() const;
int leftEdge(int nx) const;
int topEdge(int ny) const;
int rightEdge(int nx) const;
int bottomEdge(int ny) const;
Q3CanvasPixmap* image() const
{ return images->image(frm); }
virtual Q3CanvasPixmap* imageAdvanced() const;
Q3CanvasPixmap* image(int f) const
{ return images->image(f); }
virtual void advance(int stage);
public:
void draw(QPainter& painter);
private:
Q_DISABLE_COPY(Q3CanvasSprite)
void addToChunks();
void removeFromChunks();
void changeChunks();
int frm;
ushort anim_val;
uint anim_state:2;
uint anim_type:14;
bool collidesWith(const Q3CanvasSprite*,
const Q3CanvasPolygonalItem*,
const Q3CanvasRectangle*,
const Q3CanvasEllipse*,
const Q3CanvasText*) const;
friend bool qt_testCollision(const Q3CanvasSprite* s1,
const Q3CanvasSprite* s2);
Q3CanvasPixmapArray* images;
};
class QPolygonalProcessor;
class Q_COMPAT_EXPORT Q3CanvasPolygonalItem : public Q3CanvasItem
{
public:
Q3CanvasPolygonalItem(Q3Canvas* canvas);
virtual ~Q3CanvasPolygonalItem();
bool collidesWith(const Q3CanvasItem*) const;
virtual void setPen(QPen p);
virtual void setBrush(QBrush b);
QPen pen() const
{ return pn; }
QBrush brush() const
{ return br; }
virtual Q3PointArray areaPoints() const=0;
virtual Q3PointArray areaPointsAdvanced() const;
QRect boundingRect() const;
int rtti() const;
static int RTTI;
protected:
void draw(QPainter &);
virtual void drawShape(QPainter &) = 0;
bool winding() const;
void setWinding(bool);
void invalidate();
bool isValid() const
{ return (bool)val; }
private:
void scanPolygon(const Q3PointArray& pa, int winding,
QPolygonalProcessor& process) const;
Q3PointArray chunks() const;
bool collidesWith(const Q3CanvasSprite*,
const Q3CanvasPolygonalItem*,
const Q3CanvasRectangle*,
const Q3CanvasEllipse*,
const Q3CanvasText*) const;
QBrush br;
QPen pn;
uint wind:1;
};
class Q_COMPAT_EXPORT Q3CanvasRectangle : public Q3CanvasPolygonalItem
{
public:
Q3CanvasRectangle(Q3Canvas* canvas);
Q3CanvasRectangle(const QRect&, Q3Canvas* canvas);
Q3CanvasRectangle(int x, int y, int width, int height, Q3Canvas* canvas);
~Q3CanvasRectangle();
int width() const;
int height() const;
void setSize(int w, int h);
QSize size() const
{ return QSize(w,h); }
Q3PointArray areaPoints() const;
QRect rect() const
{ return QRect(int(x()),int(y()),w,h); }
bool collidesWith(const Q3CanvasItem*) const;
int rtti() const;
static int RTTI;
protected:
void drawShape(QPainter &);
Q3PointArray chunks() const;
private:
bool collidesWith( const Q3CanvasSprite*,
const Q3CanvasPolygonalItem*,
const Q3CanvasRectangle*,
const Q3CanvasEllipse*,
const Q3CanvasText*) const;
int w, h;
};
class Q_COMPAT_EXPORT Q3CanvasPolygon : public Q3CanvasPolygonalItem
{
public:
Q3CanvasPolygon(Q3Canvas* canvas);
~Q3CanvasPolygon();
void setPoints(Q3PointArray);
Q3PointArray points() const;
void moveBy(double dx, double dy);
Q3PointArray areaPoints() const;
int rtti() const;
static int RTTI;
protected:
void drawShape(QPainter &);
Q3PointArray poly;
};
class Q_COMPAT_EXPORT Q3CanvasSpline : public Q3CanvasPolygon
{
public:
Q3CanvasSpline(Q3Canvas* canvas);
~Q3CanvasSpline();
void setControlPoints(Q3PointArray, bool closed=true);
Q3PointArray controlPoints() const;
bool closed() const;
int rtti() const;
static int RTTI;
private:
void recalcPoly();
Q3PointArray bez;
bool cl;
};
class Q_COMPAT_EXPORT Q3CanvasLine : public Q3CanvasPolygonalItem
{
public:
Q3CanvasLine(Q3Canvas* canvas);
~Q3CanvasLine();
void setPoints(int x1, int y1, int x2, int y2);
QPoint startPoint() const
{ return QPoint(x1,y1); }
QPoint endPoint() const
{ return QPoint(x2,y2); }
int rtti() const;
static int RTTI;
void setPen(QPen p);
void moveBy(double dx, double dy);
protected:
void drawShape(QPainter &);
Q3PointArray areaPoints() const;
private:
int x1,y1,x2,y2;
};
class Q_COMPAT_EXPORT Q3CanvasEllipse : public Q3CanvasPolygonalItem
{
public:
Q3CanvasEllipse(Q3Canvas* canvas);
Q3CanvasEllipse(int width, int height, Q3Canvas* canvas);
Q3CanvasEllipse(int width, int height, int startangle, int angle,
Q3Canvas* canvas);
~Q3CanvasEllipse();
int width() const;
int height() const;
void setSize(int w, int h);
void setAngles(int start, int length);
int angleStart() const
{ return a1; }
int angleLength() const
{ return a2; }
Q3PointArray areaPoints() const;
bool collidesWith(const Q3CanvasItem*) const;
int rtti() const;
static int RTTI;
protected:
void drawShape(QPainter &);
private:
bool collidesWith(const Q3CanvasSprite*,
const Q3CanvasPolygonalItem*,
const Q3CanvasRectangle*,
const Q3CanvasEllipse*,
const Q3CanvasText*) const;
int w, h;
int a1, a2;
};
class Q3CanvasTextExtra;
class Q_COMPAT_EXPORT Q3CanvasText : public Q3CanvasItem
{
public:
Q3CanvasText(Q3Canvas* canvas);
Q3CanvasText(const QString&, Q3Canvas* canvas);
Q3CanvasText(const QString&, QFont, Q3Canvas* canvas);
virtual ~Q3CanvasText();
void setText(const QString&);
void setFont(const QFont&);
void setColor(const QColor&);
QString text() const;
QFont font() const;
QColor color() const;
void moveBy(double dx, double dy);
int textFlags() const
{ return flags; }
void setTextFlags(int);
QRect boundingRect() const;
bool collidesWith(const Q3CanvasItem*) const;
int rtti() const;
static int RTTI;
protected:
virtual void draw(QPainter&);
private:
Q_DISABLE_COPY(Q3CanvasText)
void addToChunks();
void removeFromChunks();
void changeChunks();
void setRect();
QRect brect;
QString txt;
int flags;
QFont fnt;
QColor col;
Q3CanvasTextExtra* extra;
bool collidesWith(const Q3CanvasSprite*,
const Q3CanvasPolygonalItem*,
const Q3CanvasRectangle*,
const Q3CanvasEllipse*,
const Q3CanvasText*) const;
};
QT_END_NAMESPACE
QT_END_HEADER
#endif // Q3CANVAS_H
| [
"alon@rogue.(none)"
] | [
[
[
1,
787
]
]
] |
0292e7cbb9251ff7e8dcc4a9f5ec34d9837e4cb9 | d8f64a24453c6f077426ea58aaa7313aafafc75c | /DKER/TestDLL/src/hddraw.cpp | 7ad2afedfce5961a116b96574214c5dbb0eed4b5 | [] | no_license | dotted/wfto | 5b98591645f3ddd72cad33736da5def09484a339 | 6eebb66384e6eb519401bdd649ae986d94bcaf27 | refs/heads/master | 2021-01-20T06:25:20.468978 | 2010-11-04T21:01:51 | 2010-11-04T21:01:51 | 32,183,921 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,147 | cpp | #include <windows.h>
#include <ddraw.h>
#include "dxwnd.h"
typedef HRESULT (WINAPI *DirectDrawCreate_Type)(GUID *, LPDIRECTDRAW *, IUnknown *);
typedef HRESULT (WINAPI *DirectDrawCreateEx_Type)(GUID *, LPDIRECTDRAW *, REFIID, IUnknown *);
typedef HRESULT (WINAPI *QueryInterface_Type)(void *, REFIID, LPVOID *);
typedef HRESULT (WINAPI *CreateSurface_Type)(LPDIRECTDRAW, DDSURFACEDESC2 *, LPDIRECTDRAWSURFACE *, void *);
typedef HRESULT (WINAPI *SetCooperativeLevel_Type)(void *, HWND, DWORD);
typedef HRESULT (WINAPI *GetAttachedSurface_Type)(void *, DDSCAPS *, LPDIRECTDRAWSURFACE *);
typedef HRESULT (WINAPI *SetDisplayMode_Type)(LPDIRECTDRAW, DWORD, DWORD, DWORD, DWORD, DWORD);
typedef HRESULT (WINAPI *SetDisplayMode1_Type)(LPDIRECTDRAW, DWORD, DWORD, DWORD);
typedef HRESULT (WINAPI *CreatePalette_Type)(LPDIRECTDRAW, DWORD, LPPALETTEENTRY, LPDIRECTDRAWPALETTE *, IUnknown *);
typedef HRESULT (WINAPI *Blt_Type)(LPDIRECTDRAWSURFACE, LPRECT, LPDIRECTDRAWSURFACE, LPRECT, DWORD, LPDDBLTFX);
typedef HRESULT (WINAPI *SetPalette_Type)(LPDIRECTDRAWSURFACE, LPDIRECTDRAWPALETTE);
typedef HRESULT (WINAPI *GetPalette_Type)(LPDIRECTDRAWSURFACE, LPDIRECTDRAWPALETTE *);
typedef HRESULT (WINAPI *SetEntries_Type)(LPDIRECTDRAWPALETTE, DWORD, DWORD, DWORD, LPPALETTEENTRY);
typedef HRESULT (WINAPI *GetDisplayMode_Type)(LPDIRECTDRAW, LPDDSURFACEDESC);
typedef HRESULT (WINAPI *WaitForVerticalBlank_Type)(LPDIRECTDRAW, DWORD, HANDLE);
typedef HRESULT (WINAPI *SetClipper_Type)(LPDIRECTDRAWSURFACE, LPDIRECTDRAWCLIPPER);
HRESULT WINAPI extDirectDrawCreate(GUID FAR *, LPDIRECTDRAW FAR *, IUnknown FAR *);
HRESULT WINAPI extDirectDrawCreateEx(GUID FAR *, LPDIRECTDRAW FAR *, REFIID, IUnknown FAR *);
HRESULT WINAPI extQueryInterfaceD(void *, REFIID, LPVOID *);
HRESULT WINAPI extQueryInterfaceS(void *, REFIID, LPVOID *);
HRESULT WINAPI extSetDisplayMode(LPDIRECTDRAW, DWORD, DWORD, DWORD, DWORD, DWORD);
HRESULT WINAPI extSetDisplayMode1(LPDIRECTDRAW, DWORD, DWORD, DWORD);
HRESULT WINAPI extCreateSurface(LPDIRECTDRAW, DDSURFACEDESC2 *, LPDIRECTDRAWSURFACE *, void *);
HRESULT WINAPI extSetCooperativeLevel(void *, HWND, DWORD);
HRESULT WINAPI extGetAttachedSurface(void *, DDSCAPS *, LPDIRECTDRAWSURFACE *);
HRESULT WINAPI extFlip(LPDIRECTDRAWSURFACE, LPDIRECTDRAWSURFACE, DWORD);
HRESULT WINAPI extBltFast(LPDIRECTDRAWSURFACE, DWORD, DWORD, LPDIRECTDRAWSURFACE, LPRECT, DWORD);
HRESULT WINAPI extCreatePalette(LPDIRECTDRAW, DWORD, LPPALETTEENTRY, LPDIRECTDRAWPALETTE *, IUnknown *);
HRESULT WINAPI extSetEntries(LPDIRECTDRAWPALETTE, DWORD, DWORD, DWORD, LPPALETTEENTRY);
HRESULT WINAPI extBlt(LPDIRECTDRAWSURFACE, LPRECT, LPDIRECTDRAWSURFACE, LPRECT, DWORD, LPDDBLTFX);
HRESULT WINAPI extGetPalette(LPDIRECTDRAWSURFACE, LPDIRECTDRAWPALETTE *);
HRESULT WINAPI extSetPalette(LPDIRECTDRAWSURFACE, LPDIRECTDRAWPALETTE);
HRESULT WINAPI extGetDisplayMode(LPDIRECTDRAW, LPDDSURFACEDESC);
HRESULT WINAPI extWaitForVerticalBlank(LPDIRECTDRAW, DWORD, HANDLE);
HRESULT WINAPI extSetClipper(LPDIRECTDRAWSURFACE, LPDIRECTDRAWCLIPPER);
extern HWND hWnd;
extern DWORD dwWidth;
extern DWORD dwHeight;
DWORD dwDDVersion;
extern DWORD dwFlags;
extern BOOL bActive;
DirectDrawCreate_Type pDirectDrawCreate = 0;
DirectDrawCreateEx_Type pDirectDrawCreateEx = 0;
QueryInterface_Type pQueryInterfaceD;
QueryInterface_Type pQueryInterfaceS;
CreateSurface_Type pCreateSurface;
CreateSurface_Type pCreateSurfaceOld;
SetCooperativeLevel_Type pSetCooperativeLevel;
GetAttachedSurface_Type pGetAttachedSurface;
SetDisplayMode_Type pSetDisplayMode;
SetDisplayMode1_Type pSetDisplayMode1;
CreatePalette_Type pCreatePalette;
Blt_Type pBlt;
GetPalette_Type pGetPalette;
SetPalette_Type pSetPalette;
SetEntries_Type pSetEntries;
GetDisplayMode_Type pGetDisplayMode;
WaitForVerticalBlank_Type pWaitForVerticalBlank;
SetClipper_Type pSetClipper;
LPDIRECTDRAWSURFACE lpDDSBack, lpDDSPrim, lpDDSEmu_Prim, lpDDSEmu_Back;
LPDIRECTDRAWCLIPPER lpDDC;
LPDIRECTDRAWPALETTE lpDDP = 0;
LPDIRECTDRAW lpDD;
DWORD PaletteEntries[256];
int HookDirectDraw(int version)
{
HINSTANCE hinst;
void *tmp;
const GUID dd7 = {0x15e65ec0,0x3b9c,0x11d2,0xb9,0x2f,0x00,0x60,0x97,0x97,0xea,0x5b};
LPDIRECTDRAW lpdd;
switch(version){
case 0:
tmp = HookAPI("ddraw.dll", "DirectDrawCreate", extDirectDrawCreate);
if(tmp) pDirectDrawCreate = (DirectDrawCreate_Type)tmp;
tmp = HookAPI("ddraw.dll", "DirectDrawCreateEx", extDirectDrawCreateEx);
if(tmp) pDirectDrawCreateEx = (DirectDrawCreateEx_Type)tmp;
break;
case 1:
case 2:
case 3:
case 5:
case 6:
hinst = LoadLibrary("ddraw.dll");
pDirectDrawCreate =
(DirectDrawCreate_Type)GetProcAddress(hinst, "DirectDrawCreate");
if(pDirectDrawCreate)
if(!extDirectDrawCreate(0, &lpdd, 0)) lpdd->Release();
break;
case 7:
hinst = LoadLibrary("ddraw.dll");
pDirectDrawCreateEx =
(DirectDrawCreateEx_Type)GetProcAddress(hinst, "DirectDrawCreateEx");
if(pDirectDrawCreateEx)
if(!extDirectDrawCreateEx(0, &lpdd, dd7, 0)) lpdd->Release();
break;
}
if(pDirectDrawCreate || pDirectDrawCreateEx) return 1;
return 0;
}
HRESULT WINAPI extDirectDrawCreate(GUID FAR *lpguid,
LPDIRECTDRAW FAR *lplpdd, IUnknown FAR *pu)
{
HRESULT res;
void *tmp;
dwDDVersion = 1;
res = (*pDirectDrawCreate)(lpguid, lplpdd, pu);
if(res) return res;
tmp = SetHook((void *)(**(DWORD **)lplpdd), extQueryInterfaceD);
if(tmp) pQueryInterfaceD = (QueryInterface_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 84), extSetDisplayMode1);
if(tmp) pSetDisplayMode1 = (SetDisplayMode1_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 24), extCreateSurface);
if(tmp) pCreateSurface = (CreateSurface_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 80), extSetCooperativeLevel);
if(tmp) pSetCooperativeLevel = (SetCooperativeLevel_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 20), extCreatePalette);
if(tmp) pCreatePalette = (CreatePalette_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 88), extWaitForVerticalBlank);
if(tmp) pWaitForVerticalBlank = (WaitForVerticalBlank_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 48), extGetDisplayMode);
if(tmp) pGetDisplayMode = (GetDisplayMode_Type)tmp;
OutTrace("DirectDrawCreate: pCreateSurface = %x\n",
pCreateSurface);
return 0;
}
HRESULT WINAPI extDirectDrawCreateEx(GUID FAR *lpguid,
LPDIRECTDRAW FAR *lplpdd, REFIID iid, IUnknown FAR *pu)
{
HRESULT res;
void *tmp;
dwDDVersion = 7;
res = (*pDirectDrawCreateEx)(lpguid, lplpdd, iid, pu);
if(res) return res;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 84), extSetDisplayMode);
if(tmp) pSetDisplayMode = (SetDisplayMode_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 24), extCreateSurface);
if(tmp) pCreateSurface = (CreateSurface_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 80), extSetCooperativeLevel);
if(tmp) pSetCooperativeLevel = (SetCooperativeLevel_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 20), extCreatePalette);
if(tmp) pCreatePalette = (CreatePalette_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 48), extGetDisplayMode);
if(tmp) pGetDisplayMode = (GetDisplayMode_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)lplpdd + 88), extWaitForVerticalBlank);
if(tmp) pWaitForVerticalBlank = (WaitForVerticalBlank_Type)tmp;
OutTrace("DirectDrawCreateEx: REFIID = %x pCreateSurface = %x\n",
iid.Data1, pCreateSurface);
return 0;
}
HRESULT WINAPI extQueryInterfaceD(void *lpdd, REFIID riid, LPVOID *obp)
{
HRESULT res;
void *tmp;
res = (*pQueryInterfaceD)(lpdd, riid, obp);
if(res) return res;
switch(riid.Data1){
case 0x9c59509a: //DirectDraw4
dwDDVersion = 4;
case 0xB3A6F3E0: //DirectDraw2
if(dwDDVersion != 4) dwDDVersion = 2;
tmp = SetHook((void *)(**(DWORD **)obp + 84), extSetDisplayMode);
if(tmp) pSetDisplayMode = (SetDisplayMode_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)obp + 24), extCreateSurface);
if(tmp){
pCreateSurfaceOld = pCreateSurface;
pCreateSurface = (CreateSurface_Type)tmp;
}
tmp = SetHook((void *)(**(DWORD **)obp + 80), extSetCooperativeLevel);
if(tmp) pSetCooperativeLevel = (SetCooperativeLevel_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)obp + 20), extCreatePalette);
if(tmp) pCreatePalette = (CreatePalette_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)obp + 48), extGetDisplayMode);
if(tmp) pGetDisplayMode = (GetDisplayMode_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)obp + 88), extWaitForVerticalBlank);
if(tmp) pWaitForVerticalBlank = (WaitForVerticalBlank_Type)tmp;
break;
}
OutTrace("lpDD->QueryInterface: lpDD = %x REFIID = %x pCreateSurface = %x\n",
lpdd, riid.Data1, pCreateSurface);
return 0;
}
HRESULT WINAPI extQueryInterfaceS(void *lpdds, REFIID riid, LPVOID *obp)
{
HRESULT res;
void *tmp;
res = (*pQueryInterfaceS)(lpdds, riid, obp);
if(res) return res;
switch(riid.Data1){
case 0xDA044E00: //DDSurface3
dwDDVersion = 3;
if(lpdds == lpDDSPrim){
lpDDSPrim = (LPDIRECTDRAWSURFACE)*obp;
}
tmp = SetHook((void *)(**(DWORD **)obp + 48), extGetAttachedSurface);
if(tmp) pGetAttachedSurface = (GetAttachedSurface_Type)tmp;
SetHook((void *)(**(DWORD **)obp + 44), extFlip);
tmp = SetHook((void *)(**(DWORD **)obp + 20), extBlt);
if(tmp) pBlt = (Blt_Type)tmp;
SetHook((void *)(**(DWORD **)obp + 28), extBltFast);
tmp = SetHook((void *)(**(DWORD **)obp + 80), extGetPalette);
if(tmp) pGetPalette = (GetPalette_Type)tmp;
tmp = SetHook((void *)(**(DWORD **)obp + 124), extSetPalette);
if(tmp) pSetPalette = (SetPalette_Type)tmp;
tmp = SetHook((void *)(*(DWORD **)obp + 112), extSetClipper);
if(tmp) pSetClipper = (SetClipper_Type)tmp;
break;
}
OutTrace("lpDDS->QueryInterface: lpdds = %x REFIID = %x\n",
lpdds, riid.Data1);
return 0;
}
HRESULT WINAPI extSetDisplayMode(LPDIRECTDRAW lpdd,
DWORD dwwidth, DWORD dwheight, DWORD dwbpp, DWORD dwrefreshrate, DWORD dwflags)
{
DDSURFACEDESC2 ddsd;
HRESULT res = 0;
OutTrace("SetDisplayMode: dwWidth = %i dwHeight = %i dwBPP = %i dwRefresh = %i dwFlags = %x\n",
dwwidth, dwheight, dwbpp, dwrefreshrate, dwflags);
dwWidth = dwwidth;
dwHeight = dwheight;
if(hWnd) AdjustWindowFrame(hWnd, dwwidth, dwheight);
if(dwFlags & EMULATEPAL) dwbpp = 32;
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = (dwDDVersion < 4) ? sizeof(DDSURFACEDESC) : sizeof(DDSURFACEDESC2);
ddsd.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT | DDSD_REFRESHRATE;
ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
ddsd.ddpfPixelFormat.dwFlags = DDPF_RGB;
(*pGetDisplayMode)(lpdd, (LPDDSURFACEDESC)&ddsd);
if(ddsd.ddpfPixelFormat.dwRGBBitCount != dwbpp)
res = (*pSetDisplayMode)(lpdd, ddsd.dwWidth, ddsd.dwHeight, dwbpp, ddsd.dwRefreshRate, 0);
return 0;
}
HRESULT WINAPI extSetDisplayMode1(LPDIRECTDRAW lpdd,
DWORD dwwidth, DWORD dwheight, DWORD dwbpp)
{
DDSURFACEDESC2 ddsd;
HRESULT res = 0;
OutTrace("SetDisplayMode1: dwWidth = %i dwHeight = %i dwBPP = %i\n",
dwwidth, dwheight, dwbpp);
dwWidth = dwwidth;
dwHeight = dwheight;
if(hWnd) AdjustWindowFrame(hWnd, dwwidth, dwheight);
if(dwFlags & EMULATEPAL) dwbpp = 32;
ZeroMemory(&ddsd, sizeof(ddsd));
ddsd.dwSize = (dwDDVersion < 4) ? sizeof(DDSURFACEDESC) : sizeof(DDSURFACEDESC2);
ddsd.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT;
ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
ddsd.ddpfPixelFormat.dwFlags = DDPF_RGB;
(*pGetDisplayMode)(lpdd, (LPDDSURFACEDESC)&ddsd);
if(ddsd.ddpfPixelFormat.dwRGBBitCount != dwbpp)
res = (*pSetDisplayMode1)(lpdd, ddsd.dwWidth, ddsd.dwHeight, dwbpp);
return res;
}
HRESULT WINAPI extGetDisplayMode(LPDIRECTDRAW lpdd, LPDDSURFACEDESC lpddsd)
{
OutTrace("GetDisplayMode\n");
(*pGetDisplayMode)(lpdd, lpddsd);
lpddsd->dwWidth = dwWidth;
lpddsd->dwHeight = dwHeight;
if(dwFlags & EMULATEPAL){
lpddsd->ddpfPixelFormat.dwFlags |= DDPF_PALETTEINDEXED8;
lpddsd->ddpfPixelFormat.dwRGBBitCount = 8;
lpddsd->ddsCaps.dwCaps |= DDSCAPS_PALETTE;
}
return 0;
}
HRESULT WINAPI extSetCooperativeLevel(void *lpdd, HWND hwnd, DWORD dwflags)
{
hWnd = hwnd;
OutTrace("SetCooperativeLevel: dwFlags = %x\n",
dwflags);
if(dwWidth) AdjustWindowFrame(hwnd, dwWidth, dwHeight);
return (*pSetCooperativeLevel)(lpdd, hwnd, DDSCL_NORMAL);
}
HRESULT WINAPI extCreateSurface(LPDIRECTDRAW lpdd, DDSURFACEDESC2 *lpddsd,
LPDIRECTDRAWSURFACE *lplpdds, void *pu)
{
void *tmp;
HRESULT res;
DDSURFACEDESC2 ddsd;
lpDD = lpdd;
OutTrace("CreateSurface: lpDD = %x Flags = %x Width = %i Height = %i Caps = %x",
lpdd, lpddsd->dwFlags, lpddsd->dwWidth, lpddsd->dwHeight, lpddsd->ddsCaps.dwCaps);
memcpy(&ddsd, lpddsd, lpddsd->dwSize);
if(ddsd.dwFlags & DDSD_CAPS && ddsd.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE){
if(dwFlags & EMULATEPAL){
ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | DDSD_PIXELFORMAT;
ddsd.ddsCaps.dwCaps = DDSCAPS_SYSTEMMEMORY | DDSCAPS_OFFSCREENPLAIN;
ddsd.dwWidth = dwWidth;
ddsd.dwHeight = dwHeight;
ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
ddsd.ddpfPixelFormat.dwFlags = DDPF_RGB | DDPF_PALETTEINDEXED8;
ddsd.ddpfPixelFormat.dwRGBBitCount = 8;
(*pCreateSurface)(lpdd, &ddsd, lplpdds, 0);
lpDDSPrim = *lplpdds;
(*pCreateSurface)(lpdd, &ddsd, &lpDDSBack, 0);
ddsd.dwFlags = DDSD_CAPS;
ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
(*pCreateSurface)(lpdd, &ddsd, &lpDDSEmu_Prim, 0);
lpdd->CreateClipper(0, &lpDDC, NULL);
lpDDC->SetHWnd(0, hWnd);
tmp = SetHook((void *)(*(DWORD *)lpDDSPrim + 112), extSetClipper);
if(tmp) pSetClipper = (SetClipper_Type)tmp;
(*pSetClipper)(lpDDSEmu_Prim, lpDDC);
ddsd.dwFlags = DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT;
ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
ddsd.dwWidth = dwWidth;
ddsd.dwHeight = dwHeight;
(*pCreateSurface)(lpdd, &ddsd, &lpDDSEmu_Back, 0);
}
else{
ddsd.dwFlags &= ~(DDSD_WIDTH | DDSD_HEIGHT | DDSD_BACKBUFFERCOUNT |
DDSD_REFRESHRATE | DDSD_PIXELFORMAT);
ddsd.ddsCaps.dwCaps &= ~(DDSCAPS_FLIP | DDSCAPS_COMPLEX);
res = (*pCreateSurface)(lpdd, &ddsd, lplpdds, pu);
if(res) return res;
lpDDSPrim = *lplpdds;
lpdd->CreateClipper(0, &lpDDC, NULL);
lpDDC->SetHWnd(0, hWnd);
tmp = SetHook((void *)(*(DWORD *)lpDDSPrim + 112), extSetClipper);
if(tmp) pSetClipper = (SetClipper_Type)tmp;
(*pSetClipper)(lpDDSPrim, lpDDC);
ddsd.dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_CAPS;
ddsd.dwWidth = dwWidth;
ddsd.dwHeight = dwHeight;
ddsd.ddsCaps.dwCaps &= ~DDSCAPS_PRIMARYSURFACE;
ddsd.ddsCaps.dwCaps |= DDSCAPS_OFFSCREENPLAIN;
(*pCreateSurface)(lpdd, &ddsd, &lpDDSBack, 0);
}
tmp = SetHook((void *)(*(DWORD *)lpDDSPrim), extQueryInterfaceS);
if(tmp) pQueryInterfaceS = (QueryInterface_Type)tmp;
tmp = SetHook((void *)(*(DWORD *)lpDDSPrim + 48), extGetAttachedSurface);
if(tmp) pGetAttachedSurface = (GetAttachedSurface_Type)tmp;
SetHook((void *)(*(DWORD *)lpDDSPrim + 44), extFlip);
tmp = SetHook((void *)(*(DWORD *)lpDDSPrim + 20), extBlt);
if(tmp) pBlt = (Blt_Type)tmp;
SetHook((void *)(*(DWORD *)lpDDSPrim + 28), extBltFast);
tmp = SetHook((void *)(*(DWORD *)lpDDSPrim + 80), extGetPalette);
if(tmp) pGetPalette = (GetPalette_Type)tmp;
tmp = SetHook((void *)(*(DWORD *)lpDDSPrim + 124), extSetPalette);
if(tmp) pSetPalette = (SetPalette_Type)tmp;
return 0;
}
if(dwFlags & EMULATEPAL && !(ddsd.dwFlags & DDSD_PIXELFORMAT)){
ddsd.ddsCaps.dwCaps &= ~DDSCAPS_VIDEOMEMORY;
ddsd.ddsCaps.dwCaps |= DDSCAPS_SYSTEMMEMORY;
ddsd.dwFlags |= DDSD_PIXELFORMAT;
ddsd.ddpfPixelFormat.dwSize = sizeof(DDPIXELFORMAT);
ddsd.ddpfPixelFormat.dwFlags = DDPF_RGB | DDPF_PALETTEINDEXED8;
ddsd.ddpfPixelFormat.dwRGBBitCount = 8;
res = (*pCreateSurface)(lpdd, &ddsd, lplpdds, pu);
OutTrace(" 256EmuSub Return %x\n", res);
return res;
}
res = (*pCreateSurface)(lpdd, lpddsd, lplpdds, 0);
if(res) res = (*pCreateSurfaceOld)(lpdd, lpddsd, lplpdds, 0);
OutTrace(" Default Return %x\n", res);
return res;
}
HRESULT WINAPI extGetAttachedSurface(void *lpdds, LPDDSCAPS lpddsc,
LPDIRECTDRAWSURFACE *lplpddas)
{
if(lpdds == lpDDSPrim){
*lplpddas = lpDDSBack;
OutTrace("GetAttachedSurface: BackBuffer\n");
return 0;
}
else{
OutTrace("GetAttachedSurface: Other\n");
return (*pGetAttachedSurface)(lpdds, lpddsc, lplpddas);
}
}
HRESULT WINAPI extFlip(LPDIRECTDRAWSURFACE lpdds, LPDIRECTDRAWSURFACE lpddst, DWORD dwflags)
{
OutTrace("Flip: target = %x src = %x\n", lpdds, lpddst);
if((dwflags & DDFLIP_WAIT) || (dwFlags & SAVELOAD)) lpDD->WaitForVerticalBlank(DDWAITVB_BLOCKEND , 0);
if(lpddst)
return lpdds->Blt(0, lpddst, 0, DDBLT_WAIT, 0);
else
return lpdds->Blt(0, lpDDSBack, 0, DDBLT_WAIT, 0);
}
HRESULT WINAPI extBlt(LPDIRECTDRAWSURFACE lpdds, LPRECT lpdestrect,
LPDIRECTDRAWSURFACE lpddssrc, LPRECT lpsrcrect, DWORD dwflags, LPDDBLTFX lpddbltfx)
{
DDSURFACEDESC2 ddsd;
BYTE *src;
DWORD *dest;
long srcpitch, destpitch;
DWORD x, y, w, h;
RECT rect, screen;
POINT p = {0, 0};
OutTrace("Blt: dest = %x src = %x dwFlags = %x\n",
lpdds, lpddssrc, dwflags);
if(lpdds == lpDDSPrim){
if(lpdestrect) screen = *lpdestrect;
if(!lpdestrect || (screen.right == dwWidth && screen.bottom == dwHeight)){
GetClientRect(hWnd, &screen);
}
ClientToScreen(hWnd, &p);
OffsetRect(&screen ,p.x, p.y);
if(dwFlags & EMULATEPAL){
if(!lpddssrc) return 0;
(*pBlt)(lpdds, lpdestrect, lpddssrc, lpsrcrect, dwflags, lpddbltfx);
if(lpdestrect){
rect = *lpdestrect;
}
else{
rect.left = 0;
rect.top = 0;
rect.right = dwWidth;
rect.bottom = dwHeight;
}
w = rect.right - rect.left;
h = rect.bottom - rect.top;
ddsd.dwSize = (dwDDVersion < 4) ? sizeof(DDSURFACEDESC) : sizeof(DDSURFACEDESC2);
ddsd.dwFlags = DDSD_LPSURFACE | DDSD_PITCH;
if(lpDDSEmu_Back->Lock(0, (DDSURFACEDESC *)&ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_WRITEONLY, 0))
return 0;
ddsd.lPitch >>= 2;
dest = (DWORD *)ddsd.lpSurface;
dest += rect.top*ddsd.lPitch;
dest += rect.left;
destpitch = ddsd.lPitch - w;
if(lpdds->Lock(0, (DDSURFACEDESC *)&ddsd, DDLOCK_SURFACEMEMORYPTR | DDLOCK_READONLY, 0)){
lpDDSEmu_Back->Unlock(0);
return 0;
}
src = (BYTE *)ddsd.lpSurface;
src += rect.top*ddsd.lPitch;
src += rect.left;
srcpitch = ddsd.lPitch - w;
for(y = 0; y < h; y ++){
for(x = 0; x < w; x ++){
*(dest ++) = PaletteEntries[*(src ++)];
}
dest += destpitch;
src += srcpitch;
}
lpdds->Unlock(0);
lpDDSEmu_Back->Unlock(0);
p.x = 0; p.y = 0;
ClientToScreen(hWnd, &p);
OffsetRect(&rect, p.x, p.y);
(*pBlt)(lpDDSEmu_Prim, &screen, lpDDSEmu_Back, lpdestrect, DDBLT_WAIT, 0);
return 0;
}
else{
return (*pBlt)(lpDDSPrim, &screen, lpddssrc, lpsrcrect, dwflags, lpddbltfx);
}
}
else{
return (*pBlt)(lpdds, lpdestrect, lpddssrc, lpsrcrect, dwflags, lpddbltfx);
}
return 0;
}
HRESULT WINAPI extBltFast(LPDIRECTDRAWSURFACE lpdds, DWORD dwx, DWORD dwy,
LPDIRECTDRAWSURFACE lpddssrc, LPRECT lpsrcrect, DWORD dwtrans)
{
RECT r;
POINT p = {0, 0};
DWORD flags = 0;
DDSURFACEDESC2 ddsd;
OutTrace("BltFast: dest = %x src = %x dwTrans = %x\n",
lpdds, lpddssrc, dwtrans);
if(dwtrans & DDBLTFAST_WAIT) flags |= DDBLT_WAIT;
if(dwtrans & DDBLTFAST_DESTCOLORKEY) flags |= DDBLT_KEYDEST;
if(dwtrans & DDBLTFAST_SRCCOLORKEY) flags |= DDBLT_KEYSRC;
r.left = dwx;
r.top = dwy;
if(lpsrcrect){
r.right = r.left + lpsrcrect->right - lpsrcrect->left;
r.bottom = r.top + lpsrcrect->bottom - lpsrcrect->top;
}
else{
ddsd.dwSize = (dwDDVersion < 4) ? sizeof(DDSURFACEDESC) : sizeof(DDSURFACEDESC2);
ddsd.dwFlags = DDSD_WIDTH | DDSD_HEIGHT;
lpddssrc->GetSurfaceDesc((LPDDSURFACEDESC)&ddsd);
r.right = r.left + ddsd.dwWidth;
r.bottom = r.top + ddsd.dwHeight;
}
return lpdds->Blt(&r, lpddssrc, lpsrcrect, flags, 0);
}
HRESULT WINAPI extCreatePalette(LPDIRECTDRAW lpdd, DWORD dwflags, LPPALETTEENTRY lpddpa,
LPDIRECTDRAWPALETTE *lplpddp, IUnknown *pu)
{
HRESULT res;
void *tmp;
int i;
OutTrace("CreatePalette: dwFlags = %x\n", dwflags);
if(!(dwFlags & EMULATEPAL)){
res = (*pCreatePalette)(lpdd, dwflags, lpddpa, lplpddp, pu);
OutTrace("res:%x\n", res);
return res;
}
res = (*pCreatePalette)(lpdd, dwflags & ~DDPCAPS_PRIMARYSURFACE, lpddpa, lplpddp, pu);
if(res) return res;
tmp = SetHook((void *)(**(DWORD **)lplpddp + 24), extSetEntries);
if(tmp) pSetEntries = (SetEntries_Type)tmp;
if(dwflags & DDPCAPS_PRIMARYSURFACE){
for(i = 0; i < 256; i ++){
PaletteEntries[i] =
(((DWORD)lpddpa[i].peRed) << 16) + (((DWORD)lpddpa[i].peGreen) << 8) + ((DWORD)lpddpa[i].peBlue);
}
lpDDP = *lplpddp;
}
return 0;
}
HRESULT WINAPI extWaitForVerticalBlank(LPDIRECTDRAW lpdd, DWORD dwflags, HANDLE hevent)
{
static DWORD time = 0;
static BOOL step = 0;
DWORD tmp;
if(!(dwFlags & SAVELOAD)) return (*pWaitForVerticalBlank)(lpdd, dwflags, hevent);
tmp = GetTickCount();
if((time - tmp) > 32) time = tmp;
Sleep(time - tmp);
if(step) time += 16;
else time += 17;
step ^= 1;
return 0;
}
HRESULT WINAPI extGetPalette(LPDIRECTDRAWSURFACE lpdds, LPDIRECTDRAWPALETTE *lplpddp)
{
OutTrace("GetPalette\n");
if(!(dwFlags & EMULATEPAL) || lpdds != lpDDSPrim) return (*pGetPalette)(lpdds, lplpddp);
if(!lpDDP) return DDERR_NOPALETTEATTACHED;
*lplpddp = lpDDP;
return 0;
}
HRESULT WINAPI extSetPalette(LPDIRECTDRAWSURFACE lpdds, LPDIRECTDRAWPALETTE lpddp)
{
int i;
HRESULT res;
PALETTEENTRY *tmp;
OutTrace("SetPalette\n");
if(!(dwFlags & EMULATEPAL) || lpdds != lpDDSPrim)
return (*pSetPalette)(lpdds, lpddp);
lpDDP = lpddp;
(*pSetPalette)(lpDDSBack, lpddp);
if(lpddp){
tmp = (LPPALETTEENTRY)PaletteEntries;
lpddp->GetEntries(0,0, 256, tmp);
for(i = 0; i < 256; i ++){
PaletteEntries[i] =
(((DWORD)tmp[i].peRed) << 16) + (((DWORD)tmp[i].peGreen) << 8) + ((DWORD)tmp[i].peBlue);
}
}
return 0;
}
HRESULT WINAPI extSetEntries(LPDIRECTDRAWPALETTE lpddp, DWORD dwflags, DWORD dwstart, DWORD dwcount, LPPALETTEENTRY lpentries)
{
int i;
HRESULT res;
OutTrace("SetEntries\n");
res = (*pSetEntries)(lpddp, dwflags, dwstart, dwcount, lpentries);
if(!(dwFlags & EMULATEPAL) || lpDDP != lpddp) return res;
for(i = 0; i < dwcount; i ++){
PaletteEntries[i + dwstart] =
(((DWORD)lpentries[i].peRed) << 16) + (((DWORD)lpentries[i].peGreen) << 8) + ((DWORD)lpentries[i].peBlue);
}
return 0;
}
HRESULT WINAPI extSetClipper(LPDIRECTDRAWSURFACE lpdds, LPDIRECTDRAWCLIPPER lpddc)
{
OutTrace("SetClipper\n");
if(lpdds == lpDDSPrim && (dwFlags & EMULATEPAL))
return (*pSetClipper)(lpDDSEmu_Prim, lpddc);
return (*pSetClipper)(lpdds, lpddc);
}
| [
"[email protected]"
] | [
[
[
1,
650
]
]
] |
59317d662c8bb7c8ea9d17437b9f5863bd354c03 | 631072cb1b59533d921616b968e06590f0da64dc | /prevent/WMP.cpp | 5b22525ce2f4d0d8125e1a093d3a9bc5fdce33f9 | [] | no_license | lloydpick/preVentrilo | 4065d8e4bc819a94716ff4b49b88b9e238437f5a | f212ba1cff67faa1f7c41b1a05fce36682f59b7c | refs/heads/master | 2021-01-15T12:25:57.822184 | 2010-09-06T17:03:20 | 2010-09-06T17:03:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 963 | cpp | #include "StdAfx.h"
#include "WMP.h"
#include "defs.h"
/**** WINDOWS MEDIA PLAYER ****/
#define WMP_PAUSE 0x00004978
CWMP::CWMP(void)
{
m_nType = MEDIA_PLAYER_WMP;
}
CWMP::~CWMP(void)
{
}
bool CWMP::IsPlaying()
{
return true;
}
bool CWMP::IsPaused()
{
return true;
}
int CWMP::CurrentVolume()
{
return 0;
}
void CWMP::SetVolume(int nVolume)
{
}
void CWMP::Pause()
{
if(m_hwndMediaPlayer)
PostMessage(m_hwndMediaPlayer, WM_APPCOMMAND, NULL, APPCOMMAND_MEDIA_PLAY_PAUSE * 65536);
}
void CWMP::UnPause()
{
if(m_hwndMediaPlayer)
PostMessage(m_hwndMediaPlayer, WM_APPCOMMAND, NULL, APPCOMMAND_MEDIA_PLAY_PAUSE * 65536);
}
void CWMP::Play()
{
if(m_hwndMediaPlayer)
PostMessage(m_hwndMediaPlayer, WM_APPCOMMAND, NULL, APPCOMMAND_MEDIA_PLAY * 65536);
}
void CWMP::FindHandle()
{
m_hwndMediaPlayer = FindWindow(TEXT("WMPlayerApp"), TEXT("Windows Media Player"));
} | [
"[email protected]"
] | [
[
[
1,
57
]
]
] |
daa1728b473bda3ab06060c469bc44b4beb22c1f | ffa46b6c97ef6e0c03e034d542fa94ba02d519e5 | /neteasebook/qneteasebookdownload.cpp | d0fa10b21de8deaa846d7b69068cfa2c5a9c2a3c | [] | no_license | jason-cpc/chmcreator | 50467a2bc31833aef931e24be1ac68f5c06efd97 | 5da66666a9df47c5cf67b71bfb115b403f41b72b | refs/heads/master | 2021-12-04T11:22:23.616758 | 2010-07-20T23:50:15 | 2010-07-20T23:50:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,813 | cpp | #include "qneteasebookdownload.h"
QNeteaseBookDownload::QNeteaseBookDownload(QString bookIndexURL,QString bookRoot)
{
this->bookRoot = bookRoot;
this->bookIndexURL = bookIndexURL;
QString temp = bookIndexURL.right(26);
bookCatalog = temp.left(12);
qDebug()<<"Catalog is:"<<bookCatalog;
bookID = temp.right(13).left(8);
qDebug()<<"Book ID is:"<<bookID;
http = new QHttp(this);
http->setHost("data.book.163.com");
connect(http,SIGNAL(done(bool)),this,SLOT(saveFile(bool)));
QDir dir(bookRoot);
dir.setCurrent(bookRoot);
if(!dir.exists(bookID)){
dir.mkdir(bookID);
}
block = 0;
status = 0;
}
void QNeteaseBookDownload::setProxy(QString hostname,int port){
http->setProxy(hostname,port,"","");
qDebug()<<"setProxy:"<<hostname<<":"<<port;
}
void QNeteaseBookDownload::saveFile(bool isError){
qDebug()<<"Requesting:Finished!"<<http->lastResponse().statusCode();
if(isError||http->lastResponse().statusCode()==404){
qDebug()<<"ERROR!"<<http->errorString();
emit finished();
return;
}
downloadChapter();
block++;
}
void QNeteaseBookDownload::download()
{
QString indexURL = QString(INDEX_URL_TEMPLATE).arg(bookCatalog).arg(bookID);
qDebug()<<"Start downloading:"<<indexURL;
http->get(QUrl::toPercentEncoding(indexURL),new QFile(bookRoot+"/"+bookID+"/index.html",this));
}
void QNeteaseBookDownload::downloadChapter(){
QString chapterTemplate = QString(CONTENT_URL_TEMPLATE).arg(bookID).arg(bookID).arg(block);
http->get(QUrl::toPercentEncoding(chapterTemplate),new QFile(bookRoot+"/"+bookID+"/"+QString(CHAPTER_LOCAL_FILE_TEMPLATE).arg(bookID).arg(block),this));
qDebug()<<"Requesting:"<<chapterTemplate;
}
| [
"zhurx4g@35deca34-8bc2-11de-b999-7dfecaa767bb"
] | [
[
[
1,
56
]
]
] |
ba7fb5af6c03cd265eea73253747fc7a36691169 | 9df4b47eb2d37fd7f08b8e723e17f733fd21c92b | /plugintemplate/libs/lib_download.h | 460c571c59fee6688eeb0e9dc43bc680d77463ee | [] | no_license | sn4k3/sourcesdk-plugintemplate | d5a806f8793ad328b21cf8e7af81903c98b07143 | d89166b79a92b710d275c817be2fb723f6be64b5 | refs/heads/master | 2020-04-09T07:11:55.754168 | 2011-01-23T22:58:09 | 2011-01-23T22:58:09 | 32,112,282 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,948 | h | #ifndef LIB_DOWNLOAD_H
#define LIB_DOWNLOAD_H
//========= Copyright © 2010-2011, Tiago Conceição, All rights reserved. ============
// Plugin Template
//
// Please Read (LICENSE.txt) and (README.txt)
// Dont Forget Visit:
// (http://www.sourceplugins.com) -> VPS Plugins
// (http://www.sourcemm.net) (http://forums.alliedmods.net/forumdisplay.php?f=52) - MMS Plugins
//
//===================================================================================
//=================================================================================
// Defines
//=================================================================================
#define LIB_DOWNLOAD_VERSION "1.0"
#define LIB_DOWNLOAD_CLASS CDownloadLib
//=================================================================================
// Class
//=================================================================================
class LIB_DOWNLOAD_CLASS
{
public:
enum DownloadType { DOWNLOAD_FILE, DOWNLOAD_FROMFILE, DOWNLOAD_FOLDER };
public:
// Constructor
LIB_DOWNLOAD_CLASS();
// Destructor
~LIB_DOWNLOAD_CLASS();
// Add a file to downloads list
// This files got registed as download to clients when 'DispatchDownloads' was called.
bool Add(const char *file, bool checkExist = true);
// Add a file to downloads list
// This files got registed as download to clients when 'DispatchDownloads' was called.
bool Add(const char *path, DownloadType type, char *filesFilter /*= "*.*"*/, bool subFolders /*= false*/);
// Remove a file to downloads list
bool Remove(const char *file);
// Clear downloads list
void Clear();
// Add a file to be downloaded
static bool AddDownload(const char *file);
// Add a file to be downloaded
static bool AddDownload(const char *path, DownloadType type, char *filesFilter = "*.*", bool subFolders = false);
// Find and Assign downloadables table, without this client download is not possible
// Call once (Automatic).
static bool RegisterDownloadables();
// Register all files from list as client download.
// Call once (Automatic).
int DispatchDownloads() const;
// Gets if download engine is ready to use
static bool CanDownload();
// Prints all strings on downloadables table
static void PrintDownloadablesTable();
// Store all files to be downloaded
// Use to loop only
CUtlVector<const char *> files;
public:
// All downloads got Dispatch at Level Init
// If true and if your plugin loads in a middle of a map all downloads in list will be Dispatch and avalible to download for new clients.
bool DispatchDownloadsOnLoad;
};
//=================================================================================
// Extern global variable
//=================================================================================
extern LIB_DOWNLOAD_CLASS *VAR_LIB_DOWNLOAD;
#endif | [
"[email protected]@2dd402b7-31f5-573d-f87e-a7bc63fa017b"
] | [
[
[
1,
85
]
]
] |
c475a020fab1341e1f31be1f46290a84be69ff01 | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /dingus/dingus/animator/AnimDataType.h | 28a3849635d96d7c7716a808d81b3270455f0562 | [
"MIT"
] | permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 875 | h | // --------------------------------------------------------------------------
// Dingus project - a collection of subsystems for game/graphics applications
// --------------------------------------------------------------------------
#ifndef __ANIM_DATA_TYPE_H
#define __ANIM_DATA_TYPE_H
namespace dingus {
// NOTE: don't change the constants! exported files might have them!
/** Animation type in a data file (and nowhere else). */
enum eAnimDataFileType {
ANIMTYPE_CUSTOM = 0,
ANIMTYPE_FLT = 1, // 1 float
ANIMTYPE_INT = 2, // 1 int
ANIMTYPE_VEC3 = 3, // 3 floats
ANIMTYPE_QUAT = 4, // 4 floats, to be treated as quaternion
ANIMTYPE_COLOR = 5, // 1 int (d3dcolor), to be treated as vector4
ANIMTYPE_FLT_H = 6, // 1 16bit float
ANIMTYPE_VEC3_H = 7, // 3 16bit floats
ANIMTYPE_QUAT_H = 8, // 4 16bit floats - quaternion
};
};
#endif
| [
"[email protected]"
] | [
[
[
1,
27
]
]
] |
13db2a28cf1cb290007e9c14f9bc3bb06e4684a5 | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /Learning OpenCV/Chapter 7 - Histograms and Matching/Ex_7_3.cpp | 6a2fcd5e45212af4719ad93c87a564e72a6e6b13 | [] | no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,322 | cpp | /////////////////////////////////////////////////////////////////////////////
// Date: 2009-10-06
// Coder: Yishi Guo
// Copy From: Example 7-3. Creating signatures form histograms for EMD
// Chapter: 6
// Page: 208
// Content: Earth Mover's Distance | Some More Complicated Stuff
/////////////////////////////////////////////////////////////////////////////
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
#include <stdio.h>
void help() {
printf("\nCall is:\n"
"Ex_7_1 modelImage0 testImage1 testImage2 dadImage3\n\n");
printf(
" Note that the model image is split in half. Top half(0) makes model. It's then tested\n"
" against its lower half(0), testImages 1 and 2 in different lighting and diferent object 3\n\n");
}
int main( int argc, char** argv ) {
IplImage* src[5], *tmp;
int i;
if ( argc == 5 ) {
if (( tmp = cvLoadImage( argv[1], 1 )) == 0 ) {
printf( "Error on reading iamge 1, %s", argv[1]);
help();
return (-1);
}
printf("Getting size [[%d] [%d]]\n", tmp->width, tmp->height);
CvSize size = cvGetSize( tmp );
printf("Get size %d %d\n", size.width, size.height);
int width = size.width;
int height = size.height;
int halfheight = height >> 1;
src[0] = cvCreateImage( cvSize(width, halfheight), 8, 3 );
src[1] = cvCreateImage( cvSize(width, halfheight), 8, 3 );
if (src[0]->widthStep != tmp->widthStep) {
printf("Error. Widthstep of alloated src doesn't equal widthStep of loaded image [%d vs %d]",
src[0]->widthStep, tmp->widthStep);
help();
return (-2);
}
int widthStep = tmp->widthStep;
unsigned char *p = (unsigned char*) (tmp->imageData);
unsigned char *sp = (unsigned char*) (src[0]->imageData);
for(i = 0; i < widthStep*halfheight; ++i ) {
*sp++ = *p++;
}
sp = (unsigned char*)(src[1]->imageData);
for( i = 0; i < widthStep*halfheight; ++i ) { // Bottom half
*sp++ = *p++;
}
// LOAD THE OTHER THERE IMAGES
for( i = 2; i < 5; ++i ) {
if (( src[i] = cvLoadImage( argv[i], 1 )) == 0 ) {
printf("Error on reading image %d: %s\n", i, argv[i] );
help();
return (-1);
}
}
// Compute the HSV image, and decompose it into separate planes
//
IplImage *hsv[5], *h_plane[5], *s_plane[5], *v_plane[5], *planes[5][2];
IplImage* hist_img[5];
CvHistogram* hist[5];
int h_bins = 8, s_bins = 8;
int hist_size[] = { h_bins, s_bins };
float h_ranges[] = { 0, 180 }; // hue is [0, 180]
float s_ranges[] = { 0, 255 };
float* ranges[] = { h_ranges, s_ranges };
int scale = 10;
for (i = 0; i < 5; ++i) {
hsv[i] = cvCreateImage( cvGetSize(src[i]), 8, 3 );
cvCvtColor( src[i], hsv[i], CV_BGR2HSV );
h_plane[i] = cvCreateImage( cvGetSize( src[i] ), 8, 1 );
s_plane[i] = cvCreateImage( cvGetSize( src[i] ), 8, 1 );
v_plane[i] = cvCreateImage( cvGetSize( src[i] ), 8, 1 );
planes[i][0] = h_plane[i];
planes[i][1] = s_plane[i];
cvCvtPixToPlane( hsv[i], h_plane[i], s_plane[i], v_plane[i], 0 );
// Build the histogram and compute ites contents.
//
{
hist[i] = cvCreateHist(
2,
hist_size,
CV_HIST_ARRAY,
ranges,
1
);
}
cvCalcHist( planes[i], hist[i], 0, 0 );
cvNormalizeHist( hist[i], 1.0 );
// Create an image to use to visualize our histogram
//
hist_img[i] = cvCreateImage(
cvSize( h_bins * scale, s_bins * scale ),
8,
3
);
cvZero( hist_img[i] );
// Populate our visualization with little gray squares.
//
float max_value = 0;
float *fp, fval;
cvGetMinMaxHistValue( hist[i], 0, &max_value, 0, 0 );
for( int h = 0; h < h_bins; h++ ) {
for ( int s = 0; s < s_bins; s++ ) {
float bin_val = cvQueryHistValue_2D( hist[i], h, s );
int intensity =cvRound( bin_val * 255 / max_value );
cvRectangle(
hist_img[i],
cvPoint( h*scale, s*scale ),
cvPoint( (h+1)*scale - 1, (s+1)*scale - 1 ),
CV_RGB(intensity, intensity, intensity),
CV_FILLED
);
}
}
} // For 5 images
//DISPLAY
cvNamedWindow( "Source0", 1 );
cvShowImage( "Source0", src[0] );
cvNamedWindow( "H-S Histogram0", 1 );
cvShowImage( "H-S Histogram0", hist_img[0] );
cvNamedWindow( "Source1", 1 );
cvShowImage( "Source1", src[1] );
cvNamedWindow( "H-S Histogram1", 1 );
cvShowImage( "H-S Histogram1", hist_img[1] );
cvNamedWindow( "Source2", 1 );
cvShowImage( "Source2", src[2] );
cvNamedWindow( "H-S Histogram2", 1 );
cvShowImage( "H-S Histogram2", hist_img[2] );
cvNamedWindow( "Source3", 1 );
cvShowImage( "Source3", src[3] );
cvNamedWindow( "H-S Histogram3", 1 );
cvShowImage( "H-S Histogram3", hist_img[3] );
cvNamedWindow( "Source4", 1 );
cvShowImage( "Source4", src[4] );
cvNamedWindow( "H-S Histogram4", 1 );
cvShowImage( "H-S Histogram4", hist_img[4] );
// Compare the histogram src0 vs 1, vs2, vs3, vs4
printf(" Comparision Corr Chi Intersect Bhat\n");
for (i=1; i<5; ++i) { // For histogram
printf("Hist[0] vs: Hist[%d]: ", i);
for(int j = 0; j < 4; ++j ) { // For comparision type
printf("CmpMethod[%d]: %lf: ", j, cvCompareHist(hist[0], hist[j], j ));
}
printf("\n");
}
// Oi Vey, parse histogram to earth movers signatures
// CvRNG rgn_state = cvRNG(0xffffffff); // Testd random bins
CvMat* sig[5];
int numrows = h_bins*s_bins;
int numcols = 3; // value,i,j
for(i = 0; i < 5; ++i ) {
sig[i] = cvCreateMat( numrows, 3, CV_32FC1 );
// fill it
float sum = 0.0;
for ( int h = 0; h < h_bins; h++ ) {
for ( int s = 0; s < s_bins; s++ ) {
float bin_val = cvQueryHistValue_2D( hist[i], h, s );
cvSet2D(sig[i], h*s_bins + s, 0, cvScalar(bin_val, bin_val, bin_val)); // Point weight
cvSet2D(sig[i], h*s_bins + s, 1, cvScalar(h)); // Coord 1
cvSet2D(sig[i], h*s_bins + s, 2, cvScalar(s)); // Coord 2
}
}
}
// DO EMD AND REPORT
printf("EMD: \n");
for( i = 1; i < 5; ++i ) {
float emd = cvCalcEMD2( sig[0], sig[i], CV_DIST_L2 );
printf("%f: \n", emd);
}
printf("\n");
cvWaitKey(0);
}
else {
printf("Error: Wront number of arguments\n");
help();
}
} | [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
] | [
[
[
1,
202
]
]
] |
c0c914b8681edd0e3457a142d710eb5d8b328698 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/Neuz/ScreenEffect.h | 3b67165a921006b7772cfeec9769a2cdb299a826 | [] | 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 | UTF-8 | C++ | false | false | 271 | h | #ifndef __SCREENEFFECT_H
#define __SCREENEFFECT_H
class CScreenEffect
{
int m_nFrame;
FLOAT m_fFrame;
public:
CScreenEffect();
~CScreenEffect();
void Render( C2DRender* p2DRender );
void Process();
int nCount;
};
#endif // __SCREENEFFECT_H | [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
20
]
]
] |
ce3810ebd3fc3a75abbb4e3cbf17669897f4a5d9 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aosdesigner/core/Library.cpp | 53bffc4010509d144f6fad86b926a3666d168cdb | [] | no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,072 | cpp | #include "Library.hpp"
#include "core/Context.hpp"
#include "core/resources/Resource.hpp"
#include "aosl/library.hpp"
#include "utilcpp/Assert.hpp"
namespace aosd
{
namespace core
{
Library::Library()
{
}
Library::Library( const aosl::Library& library_info )
{
update( library_info );
}
Library::Library( const bfs::path& file_path )
{
UTILCPP_NOT_IMPLEMENTED_YET;
}
Library::~Library()
{
}
void Library::update( const aosl::Library& library_info )
{
clear();
const auto& resource_list = library_info.resources().resource();
std::for_each( begin(resource_list), end(resource_list), [&]( const aosl::Resource& resource )
{
auto resource_object = Context::instance().resource_provider().get( resource );
UTILCPP_ASSERT_NOT_NULL( resource_object ); // TODO : replace by exception?
add( resource.id() , resource_object );
});
if( library_info.import() )
{
const auto& import_list = library_info.import()->include();
std::for_each( begin(import_list), end(import_list), [&]( const aosl::Library_include& import_info )
{
// build the library
try
{
auto import_path = bfs::path( import_info.data() );
auto library_to_import = std::unique_ptr<Library>( new Library( import_path ) );
import( *library_to_import );
}
catch( const std::exception& e )
{
UTILCPP_LOG_ERROR << "Failed to load library at \"" << import_info.data() << "\" : " << e.what();
}
});
}
}
void Library::import( const Library& library )
{
// TODO : replace by std::copy? does it work with maps?
std::for_each( begin(library.m_resource_registry), end(library.m_resource_registry), [&]( std::pair< aosl::Resource_id, ResourcePtr > resource_it )
{
add( resource_it.first, resource_it.second );
});
}
void Library::clear()
{
m_resource_registry.clear();
m_resources.clear();
}
void Library::add( aosl::Resource_id resource_id, ResourcePtr resource )
{
if( resource && !resource_id.empty() )
{
auto success = m_resource_registry.insert( std::make_pair( resource_id, resource ) );
if( success.second ) // inserted with success
{
m_resources.emplace_back( ResourceRef( resource_id, resource ) );
}
else
{
throw std::exception( "Failed to add resource!" );
}
}
else
{
throw std::exception( "Tried to add invalid resource!" );
}
}
ResourcePtr Library::find( const aosl::Resource_id& resource_id ) const
{
auto resource_it = m_resource_registry.find( resource_id );
if( resource_it != end(m_resource_registry) )
{
UTILCPP_ASSERT_NOT_NULL( resource_it->second );
return resource_it->second;
}
return ResourcePtr();
}
void Library::for_each_resource( ResourceFunc func ) const
{
std::for_each( begin(m_resources), end(m_resources), [&]( const ResourceRef& resource_ref )
{
UTILCPP_ASSERT_NOT_NULL( resource_ref.resource() );
func( resource_ref );
});
}
}
} | [
"klaim@localhost"
] | [
[
[
1,
129
]
]
] |
581a01ac2e4ff9cddd1e1a671bf1b96efc98e257 | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /Win32/2011-01-28/02ProcessList_main.cpp | 659d680a933d5c7504be0f2842014cfa6a41674a | [] | no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,274 | cpp | // ** 2011-01-28 Win32 2.4.1 02ProcessList
// ** Yishi Guo
#include <windows.h>
#include <tlhelp32.h> // Defination of CreateToolhelp32Snapshot Function
#include <stdio.h>
int main( int argc, char** argv ) {
PROCESSENTRY32 pe32; // declare pe32
pe32.dwSize = sizeof( pe32 ); // set the size of pe32
// Snapshot:
HANDLE hProcessSnap =
::CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
// valid values:
// TH32CS_INHERIT 0x80000000
// TH32CS_SNAPALL
// TH32CS_SNAPHEAPLIST 0x00000001
// TH32CS_SNAPMODULE 0x00000008
// TH32CS_SNAPMOUDLE32 0x00000010
// TH32CS_SNAPPROCESS 0x00000002
// TH32CS_SNAPTHREAD 0x00000004
if ( hProcessSnap == INVALID_HANDLE_VALUE ) { // error occur
printf( " CreateToolhelp32Snapshot 调用失败!\n" );
return -1;
}
BOOL bMore = ::Process32First( hProcessSnap, &pe32 ); // Get the first one
while( bMore ) {
printf( " 进程名称:%s\n", pe32.szExeFile ); // Print process name
printf( " 进程ID号:%u\n\n", pe32.th32ProcessID ); // Print process ID Number
bMore = ::Process32Next( hProcessSnap, &pe32 ); // Get the next one
}
// Close the handle
::CloseHandle( hProcessSnap );
getchar();
return 0;
} | [
"[email protected]@70501136-4834-11de-8855-c187e5f49513"
] | [
[
[
1,
39
]
]
] |
c174b026ed0812d2eca2564e010b74dc5799a4d1 | 5c3ae0d061432533efe7b777c8205cf00db72be6 | / spacerenegade/inc/menu.h | 80b0459fbacf316b94458980ba383b664575e24c | [] | no_license | jamoozy/spacerenegade | 6da0abbcdc86a9edb3a1a9c4e7224d5a1121423c | 4240a4b6418cb7b03d22a42de65e800277cfc889 | refs/heads/master | 2016-09-06T17:24:11.028035 | 2007-08-12T07:19:14 | 2007-08-12T07:19:14 | 41,124,730 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,678 | h | #ifndef MENU_H
#define MENU_H
#include <iostream>
#include <string>
#include "mission.h"
using std::string;
class Button
{
private:
string title;
GLfloat border; // how much space around button (.1 looks pretty good)
GLfloat xPos;
GLfloat yPos;
GLfloat RGB[3];
GLuint id; // The ID number (for picking purposes).
void (*pressFunc)(); // Function to call when button is pressed.
public:
Button();
Button(string title, GLfloat border,
GLfloat xPos, GLfloat yPos,
GLfloat red, GLfloat green, GLfloat blue,
GLuint id, void (*pressFunc)());
virtual ~Button() {};
void Place(GLenum mode);
void drawText(GLint x, GLint y, string s, GLfloat r, GLfloat g, GLfloat b);
GLfloat getBuffer(){return border;}
string getTitle(){return title;}
GLfloat getXPos(){return xPos;}
GLfloat getYPos(){return yPos;}
GLuint getID() { return id; }
void buttonPressed();
void setBuffer(GLfloat border){border = border;}
void setTitle(string title){title = title;}
void setXPos(GLfloat xPos){xPos = xPos;}
void setYPos(GLfloat yPos){yPos = yPos;}
void setRGB(GLfloat red, GLfloat green, GLfloat blue){RGB[0] = red;RGB[1] = green;RGB[2] = blue;}
};
class Menu
{
private:
Button *buttons;
int numButtons;
Mission *selectedMission; // for clicking on missions, reading briefing, and accepting
bool remake;
public:
Menu();
Menu(int type);
virtual ~Menu();
void setProjection();
void draw(GLenum mode);
void cleanProjection();
//int getNumButtons() {return numButtons;}
void processHits(GLint hits, GLuint buffer[]);
bool needsRefresh() { return remake; };
};
#endif
| [
"GumOtaku@d98d4265-742f-0410-abd1-c3b8cf015911",
"jamoozy@d98d4265-742f-0410-abd1-c3b8cf015911",
"gumotaku@d98d4265-742f-0410-abd1-c3b8cf015911"
] | [
[
[
1,
6
],
[
44,
44
],
[
46,
50
],
[
52,
54
],
[
56,
56
],
[
58,
58
],
[
63,
64
]
],
[
[
7,
28
],
[
30,
43
],
[
45,
45
],
[
51,
51
],
[
57,
57
],
[
59,
59
],
[
62,
62
],
[
65,
66
]
],
[
[
29,
29
],
[
55,
55
],
[
60,
61
]
]
] |
5e076587ad6106d8667df5d676efc717766a1ef0 | a8f57238ec20d8b0c4d7b4442a287aaf3caa200f | /Tools/XP_UDB_HILSIM/HILSIM.cpp | 4ed4d8589db995338922c850067ad3989da0fd09 | [] | no_license | shengangsiaopo/propilot | b6f39a9ea5e291fcbd16b6548ff4f1711bfba230 | f8c5422f261985973af9a615455a94a697a5224b | refs/heads/master | 2020-04-24T23:28:56.910130 | 2011-04-24T06:26:07 | 2011-04-24T06:26:07 | 34,727,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,196 | cpp | #include "stdafx.h"
#include "SerialIO.h"
#define MAX_ITEMS 30;
bool CommsEnabled;
float fTextColour[3];
char szString[100];
XPLMHotKeyID gHotKey = NULL;
void MyHotKeyCallback(void * inRefcon);
int MyOrbitPlaneFunc(
XPLMCameraPosition_t * outCameraPosition,
int inIsLosingControl,
void * inRefcon);
int MyDrawCallback(
XPLMDrawingPhase inPhase,
int inIsBefore,
void * inRefcon);
// Here are the variables for implementing the file based control of the setup
Channels ControlSurfaces; // The list of control surfaces
string CommPortString = "\\\\.\\COM4"; // Pnace to put the port string to open, defaults to COM4
string OverString = "sim/operation/override/override_flightcontrol";
// Defaults to standard joystick control
float ThrottleSettings[8] = {0,0,0,0,0,0,0,0}; // The throttle settings with default values
float GetBodyRates(float elapsedMe, float elapsedSim, int counter, void * refcon);
void SerialPortAccessCallback(XPLMWindowID inWindowID, void *inRefcon);
int DrawStrings(XPLMDrawingPhase inPhase, int inIsBefore, void *inRefcon);
void CalculateChecksum(unsigned char msg[]);
void Store4LE(unsigned char *store, union longbbbb data);
void Store2LE(unsigned char *store, union intbb data);
void msgDefault(unsigned char rxChar);
void msgSync1(unsigned char rxChar);
void msgServos(unsigned char rxChar);
void msgCheckSum(unsigned char rxChar);
unsigned char ck_in_a, ck_in_b, ck_calc_a, ck_calc_b;
void SetupDefaultServoZeros(void);
void ServosToControls();
int store_index = 0;
void (* msg_parse) (unsigned char rxChar) = &msgDefault;
#define SERVO_MSG_LENGTH 16
// Servo offsets are a variable so that they can be actively zeroed from the real received offsets
// This offset zero will need to be a menu add on to the plugin.
intbb ServoOffsets[SERVO_CHANNELS];
unsigned char SERVO_IN[SERVO_CHANNELS*2];
unsigned char SERVO_IN_[SERVO_CHANNELS*2];
int rxCount = 0;
// At 40hz, this message will be ~6500bps
// 20 bytes
unsigned char NAV_BODYRATES[] = {
0xB5, 0x62, // Header
0x01, 0xAB, // ID
0x0C, 0x00, // Payload Length
0x00, 0x00, // P
0x00, 0x00, // Q
0x00, 0x00, // R
0x00, 0x00, // U_dot
0x00, 0x00, // V_dot
0x00, 0x00, // W_dot
0x00, 0x00 // Checksum
};
// At 4hz the normal messages are ~6000 bps
// 60 bytes
unsigned char NAV_SOL[] = {
0xB5, 0x62, // Header - DONE
0x01, 0x06, // ID - DONE
0x34, 0x00, // Payload Length - DONE
0x00, 0x00, 0x00, 0x00, // iTOW - DONE
0x00, 0x00, 0x00, 0x00, // fTOW - DONE
0x00, 0x00, // week - DONE
0x03, // gpsFix - DONE
0x0D, // flags - DONE
0x00, 0x00, 0x00, 0x00, // ecefX - DONE
0x00, 0x00, 0x00, 0x00, // ecefY - DONE
0x00, 0x00, 0x00, 0x00, // ecefZ - DONE
0x64, 0x00, 0x00, 0x00, // pAcc - DONE
0x00, 0x00, 0x00, 0x00, // ecefVX - DONE
0x00, 0x00, 0x00, 0x00, // ecefVY - DONE
0x00, 0x00, 0x00, 0x00, // ecefVZ - DONE
0x64, 0x00, 0x00, 0x00, // sACC - DONE
0x64, 0x00, // pDOP - DONE
0x00, // res1 - DONE
0x04, // numSV - DONE
0x00, 0x00, 0x00, 0x00, // res2 - DONE
0x00, 0x00 // Checksum - DONE
};
// 26 bytes
unsigned char NAV_DOP[] = {
0xB5, 0x62, // Header - DONE
0x01, 0x04, // ID - DONE
0x12, 0x00, // Payload Length - DONE
0x00, 0x00, 0x00, 0x00, // iTOW - DONE
0x64, 0x00, // gDOP - DONE
0x64, 0x00, // pDOP - DONE
0x64, 0x00, // tDOP - DONE
0x64, 0x00, // vDOP - DONE
0x64, 0x00, // hDOP - DONE
0x64, 0x00, // nDOP - DONE
0x64, 0x00, // eDOP - DONE
0x00, 0x00 // Checksum - DONE
};
// 36 bytes
unsigned char NAV_POSLLH[] = {
0xB5, 0x62, // Header - DONE
0x01, 0x02, // ID - DONE
0x1C, 0x00, // Payload Length - DONE
0x00, 0x00, 0x00, 0x00, // iTOW - DONE
0x00, 0x00, 0x00, 0x00, // lon - DONE
0x00, 0x00, 0x00, 0x00, // lat - DONE
0x00, 0x00, 0x00, 0x00, // height - DONE
0x00, 0x00, 0x00, 0x00, // hMSL - DONE
0xE8, 0x03, 0x00, 0x00, // hAcc - DONE
0xE8, 0x03, 0x00, 0x00, // vAcc - DONE
0x00, 0x00 // Checksum - DONE
};
// 44 bytes
unsigned char NAV_VELNED[] = {
0xB5, 0x62, // Header - DONE
0x01, 0x12, // ID - DONE
0x24, 0x00, // Payload Length - DONE
0x00, 0x00, 0x00, 0x00, // iTOW - DONE
0x00, 0x00, 0x00, 0x00, // velN - DONE
0x00, 0x00, 0x00, 0x00, // velE - DONE
0x00, 0x00, 0x00, 0x00, // velD - DONE
0x00, 0x00, 0x00, 0x00, // speed - DONE
0x00, 0x00, 0x00, 0x00, // gSpeed - DONE
0x00, 0x00, 0x00, 0x00, // heading - DONE
0x64, 0x00, 0x00, 0x00, // sAcc - DONE
0xA0, 0x86, 0x01, 0x00, // cAcc - DONE
0x00, 0x00 // Checksum - DONE
};
XPLMDataRef drP, drQ, drR,
drLat, drLon, drElev,
drLocal_ax, drLocal_ay, drLocal_az,
drLocal_vx, drLocal_vy, drLocal_vz,
drLocal_x, drLocal_y, drLocal_z,
drGroundSpeed, drAirSpeedTrue, drHeading,
drLocalDays, drLocalSecs,
drPhi, drTheta, drPsi,
drAlpha, drBeta,
drOverRide, drThrOverRide,
drPitchAxis, drRollAxis, drYawAxis, drThro;
float CamYaw, CamPitch, CamRoll;
float CamX, CamY, CamZ;
float P_plane, Q_plane, R_plane;
float ax_NED, ay_NED, az_NED, mag_NED;
float ax_plane, ay_plane, az_plane;
#define CamPathLength 50000
float CamPath[CamPathLength][3];
int CamPathIterator = 0;
int CamPathCount = 0;
void GetGPSData(void);
PLUGIN_API int XPluginStart(
char * outName,
char * outSig,
char * outDesc)
{
strcpy(outName, "UDB HILSIM");
strcpy(outSig, "UDB.HardwareInLoop");
strcpy(outDesc, "UDB Hardware-In-Loop Simulator");
drP = XPLMFindDataRef("sim/flightmodel/position/P");
drQ = XPLMFindDataRef("sim/flightmodel/position/Q");
drR = XPLMFindDataRef("sim/flightmodel/position/R");
drLat = XPLMFindDataRef("sim/flightmodel/position/latitude");
drLon = XPLMFindDataRef("sim/flightmodel/position/longitude");
drElev = XPLMFindDataRef("sim/flightmodel/position/elevation");
drLocal_ax = XPLMFindDataRef("sim/flightmodel/position/local_ax");
drLocal_ay = XPLMFindDataRef("sim/flightmodel/position/local_ay");
drLocal_az = XPLMFindDataRef("sim/flightmodel/position/local_az");
drLocal_vx = XPLMFindDataRef("sim/flightmodel/position/local_vx");
drLocal_vy = XPLMFindDataRef("sim/flightmodel/position/local_vy");
drLocal_vz = XPLMFindDataRef("sim/flightmodel/position/local_vz");
drLocalDays = XPLMFindDataRef("sim/time/local_date_days");
drLocalSecs = XPLMFindDataRef("sim/time/local_time_sec");
drGroundSpeed = XPLMFindDataRef("sim/flightmodel/position/groundspeed");
drAirSpeedTrue = XPLMFindDataRef("sim/flightmodel/position/true_airspeed");
drHeading = XPLMFindDataRef("sim/flightmodel/position/psi");
drLocal_x = XPLMFindDataRef("sim/flightmodel/position/local_x");
drLocal_y = XPLMFindDataRef("sim/flightmodel/position/local_y");
drLocal_z = XPLMFindDataRef("sim/flightmodel/position/local_z");
drPhi = XPLMFindDataRef("sim/flightmodel/position/phi");
drTheta = XPLMFindDataRef("sim/flightmodel/position/theta");
drPsi = XPLMFindDataRef("sim/flightmodel/position/psi");
drAlpha = XPLMFindDataRef("sim/flightmodel/position/alpha");
drBeta = XPLMFindDataRef("sim/flightmodel/position/beta");
drThrOverRide = XPLMFindDataRef("sim/operation/override/override_throttles");
drPitchAxis = XPLMFindDataRef("sim/joystick/FC_ptch");
drRollAxis = XPLMFindDataRef("sim/joystick/FC_roll");
drYawAxis = XPLMFindDataRef("sim/joystick/FC_hdng");
drThro = XPLMFindDataRef("sim/flightmodel/engine/ENGN_thro_use");
fTextColour[0] = 1.0;
fTextColour[1] = 1.0;
fTextColour[2] = 1.0;
XPLMRegisterFlightLoopCallback(GetBodyRates, 1.0, NULL);
XPLMRegisterDrawCallback(
DrawStrings,
xplm_Phase_Window, /* Draw when sim is doing objects */
0, /* After objects */
NULL); /* No refcon needed */
// XPLMSetDatai(drOverRide, 1); // Now overide surfaces, not yaw,roll,pitch
/* Register our hot key for the new view. */
gHotKey = XPLMRegisterHotKey(XPLM_VK_F8, xplm_DownFlag,
"Circling External View",
MyHotKeyCallback,
NULL);
XPLMRegisterDrawCallback(
MyDrawCallback,
xplm_Phase_Objects, /* Draw when sim is doing objects */
0, /* After objects */
NULL); /* No refcon needed */
memset(&CamPath, 0, sizeof(float) * 3 * CamPathLength);
return 1;
}
int DrawStrings(XPLMDrawingPhase inPhase, int inIsBefore, void *inRefcon)
{
XPLMDrawString(fTextColour,300,740,szString,NULL,xplmFont_Basic);
return 1;
}
PLUGIN_API void XPluginStop(void)
{
XPLMUnregisterHotKey(gHotKey);
XPLMUnregisterDrawCallback(
MyDrawCallback,
xplm_Phase_LastCockpit,
0,
NULL);
}
PLUGIN_API void XPluginDisable(void)
{
CloseComms();
XPLMSetDatai(drOverRide, 0); // Clear the overides
XPLMSetDatai(drThrOverRide, 0);
}
PLUGIN_API int XPluginEnable(void)
{
// Load the setup file on enable. This allows the user to modify the file without exit of XPlane
SetupFile Setup;
Setup.LoadSetupFile(ControlSurfaces, CommPortString, OverString); // Open the setup file and parse it into the control surface list
OpenComms();
SetupDefaultServoZeros(); // Setup the servo defaults.
drOverRide = XPLMFindDataRef(OverString.data()); // Get the latest overide reference
XPLMSetDatai(drOverRide, 1); // Overide from the setup file
XPLMSetDatai(drThrOverRide, 1);
memset(&CamPath, 0, sizeof(float) * 3 * CamPathLength);
return 1;
}
PLUGIN_API void XPluginReceiveMessage(
XPLMPluginID inFromWho,
long inMessage,
void * inParam)
{
}
float GetBodyRates(float elapsedMe, float elapsedSim, int counter, void * refcon)
{
union intbb Temp2;
float phi, theta, psi;
float alpha, beta;
float P_flight, Q_flight, R_flight;
float ax, ay, az;
// Angular rates in X-Plane are specified relative to the flight path, not to the aircraft,
// for reasons unknown. So that means we need to rotate by alpha and beta to get angular rates
// in the aircraft body frame, which is what the UDB measures.
// Retrieve rates and slip angles, and convert to radians
P_flight = XPLMGetDataf(drP) / 180 * PI ;
Q_flight = XPLMGetDataf(drQ) / 180 * PI ;
R_flight = XPLMGetDataf(drR) / 180 * PI ;
alpha = XPLMGetDataf(drAlpha) / 180 * PI;
beta = XPLMGetDataf(drBeta) / 180 * PI;
FLIGHTtoBCBF(P_flight, Q_flight, R_flight, alpha, beta);
P_plane = P_flight;
Q_plane = Q_flight;
R_plane = R_flight;
// Angular rate
// multiply by 5632 (constant from UDB code)
// Divide by SCALEGYRO(3.0 for red board)
// 1 * 5632 / 3.0 = 1877.33
Temp2.BB = (int)(P_plane * 1877.33);
Store2LE(&NAV_BODYRATES[6], Temp2);
Temp2.BB = (int)(Q_plane * 1877.33);
Store2LE(&NAV_BODYRATES[8], Temp2);
Temp2.BB = (int)(R_plane * 1877.33);
Store2LE(&NAV_BODYRATES[10], Temp2);
// Our euler angles:
// X-Plane angles are in degrees.
// Phi is roll, roll to right is positive
// Theta is pitch, pitch up is positive
// Psi is yaw, relative to north. North is 0/360.
// Convert these angles to radians first.
phi =(XPLMGetDataf(drPhi)) / 180 * PI * -1.0;
theta = (XPLMGetDataf(drTheta)) / 180 * PI;
psi = (XPLMGetDataf(drPsi)) / 180 * PI * -1.0;
// Get accelerations in OpenGL coordinate frame
//ax = XPLMGetDataf(drLocal_ax);
//ay = XPLMGetDataf(drLocal_ay);
//az = XPLMGetDataf(drLocal_ay);
ax = 0;
ay = 0;
az = 0;
// Gravity is not included in ay, we need to add it. OGL y axis is +ve up,
// so g is -9.8.
ay -= (float)9.8;
// Convert from OGL frame to Aircraft body fixed frame
OGLtoBCBF(ax, ay, az, phi, theta, psi);
ax_plane = ax;
ay_plane = ay;
az_plane = az;
// Lastly we need to convert from X-Plane units (m/s^2) to the arbitrary units used by the UDB
// Accelerations are in m/s^2
// Divide by 9.8 to get g's
// Multiply by 5280 (constant from UDB code)
// Divide by SCALEACCEL (2.64 for red board)
// 1 / 9.8 * 5280 / 2.64 = 204.8
Temp2.BB = (int)(ax * 204.8);
Store2LE(&NAV_BODYRATES[12], Temp2);
Temp2.BB = (int)(ay * 204.8);
Store2LE(&NAV_BODYRATES[14], Temp2);
Temp2.BB = (int)(az * 204.8);
Store2LE(&NAV_BODYRATES[16], Temp2);
CalculateChecksum(NAV_BODYRATES);
SendToComPort(sizeof(NAV_BODYRATES),NAV_BODYRATES);
ReceiveFromComPort();
ServosToControls();
// float ThrottleSetting = 0; //SurfaceDeflections[CHANNEL_THROTTLE];
// float throttle[8] = {ThrottleSetting, ThrottleSetting, ThrottleSetting, ThrottleSetting,
// ThrottleSetting, ThrottleSetting, ThrottleSetting, ThrottleSetting};
XPLMSetDatavf(drThro, ThrottleSettings,0,8);
return -1;
}
void GetGPSData(void)
{
union longbbbb Temp4;
union intbb Temp2;
int LocalDays = XPLMGetDatai(drLocalDays);
float LocalSecsFloat = XPLMGetDataf(drLocalSecs) * 1000;
LocalDays += 5;
int Week = (int)(LocalDays / 7) + 1564;
LocalDays = (LocalDays % 7);
Week = (Week * 10) + LocalDays;
int LocalSecsInt = (int)LocalSecsFloat + (LocalDays * 86400000);
LocalSecsFloat = (LocalSecsFloat - (int)LocalSecsFloat) * 1000000;
Temp2.BB = Week;
Store2LE(&NAV_SOL[14], Temp2);
Temp4.WW = LocalSecsInt;
Store4LE(&NAV_SOL[6], Temp4);
Store4LE(&NAV_DOP[6], Temp4);
Store4LE(&NAV_POSLLH[6], Temp4);
Store4LE(&NAV_VELNED[6], Temp4);
Temp4.WW = (int)LocalSecsFloat;
Store4LE(&NAV_SOL[10], Temp4);
double latitude = XPLMGetDataf(drLat);
double longitude = XPLMGetDataf(drLon);
double elevation = XPLMGetDataf(drElev);
double local_x = XPLMGetDataf(drLocal_x);
double local_y = XPLMGetDataf(drLocal_y);
double local_z = XPLMGetDataf(drLocal_z);
double local_vx = XPLMGetDataf(drLocal_vx);
double local_vy = XPLMGetDataf(drLocal_vy);
double local_vz = XPLMGetDataf(drLocal_vz);
Temp4.WW = (int)(local_vx * 100);
Store4LE(&NAV_VELNED[14], Temp4);
Temp4.WW = (int)(local_vy * -100);
Store4LE(&NAV_VELNED[18], Temp4);
Temp4.WW = (int)(local_vz * -100);
Store4LE(&NAV_VELNED[10], Temp4);
Temp4.WW = (int)(XPLMGetDataf(drAirSpeedTrue) * 100);
Store4LE(&NAV_VELNED[22], Temp4);
Temp4.WW = (int)(XPLMGetDataf(drGroundSpeed) * 100);
Store4LE(&NAV_VELNED[26], Temp4);
Temp4.WW = (int)(XPLMGetDataf(drHeading) * 100000);
Store4LE(&NAV_VELNED[30], Temp4);
Temp4.WW = (int)(latitude * 10000000);
Store4LE(&NAV_POSLLH[14], Temp4);
Temp4.WW = (int)(longitude * 10000000);
Store4LE(&NAV_POSLLH[10], Temp4);
Temp4.WW = (int)(elevation * 1000);
Store4LE(&NAV_POSLLH[18], Temp4);
Store4LE(&NAV_POSLLH[22], Temp4);
double ac_pos_lat, ac_pos_lon, ac_pos_elev;
double ac_vel_lat, ac_vel_lon, ac_vel_elev;
// Get AC pos in LLA
XPLMLocalToWorld( local_x,
local_y,
local_z,
&ac_pos_lat,
&ac_pos_lon,
&ac_pos_elev );
// Get AC pos + velocity vector in LLA
XPLMLocalToWorld( local_x + local_vx,
local_y + local_vy,
local_z + local_vz,
&ac_vel_lat,
&ac_vel_lon,
&ac_vel_elev );
// convert to ECEF
LLAtoECEF(ac_pos_lat, ac_pos_lon, ac_pos_elev, local_x, local_y, local_z);
LLAtoECEF(ac_vel_lat, ac_vel_lon, ac_vel_elev, local_vx, local_vy, local_vz);
// AC pos stays as is
// subtract to get velocity vector in ECEF
local_vy -= local_y;
local_vx -= local_x;
local_vz -= local_z;
Temp4.WW = (int)(local_x * 100);
Store4LE(&NAV_SOL[18], Temp4);
Temp4.WW = (int)(local_y * 100);
Store4LE(&NAV_SOL[22], Temp4);
Temp4.WW = (int)(local_z * 100);
Store4LE(&NAV_SOL[26], Temp4);
Temp4.WW = (int)(local_vx * 100);
Store4LE(&NAV_SOL[34], Temp4);
Temp4.WW = (int)(local_vy * 100);
Store4LE(&NAV_SOL[38], Temp4);
Temp4.WW = (int)(local_vz * 100);
Store4LE(&NAV_SOL[42], Temp4);
CalculateChecksum(NAV_SOL);
SendToComPort(sizeof(NAV_SOL),NAV_SOL);
CalculateChecksum(NAV_DOP);
SendToComPort(sizeof(NAV_DOP),NAV_DOP);
CalculateChecksum(NAV_POSLLH);
SendToComPort(sizeof(NAV_POSLLH),NAV_POSLLH);
CalculateChecksum(NAV_VELNED);
SendToComPort(sizeof(NAV_VELNED),NAV_VELNED);
}
void CalculateChecksum(unsigned char *msg)
{
// length is technically 2 bytes (in little endian order) but we're
// not using any messages over 256 bytes long, so we can get away
// with just looking at the first byte.
int length = msg[4];
int i;
int CK_A = 0;
int CK_B = 0;
for(i = 2 ; i < length + 6 ; i++)
{
CK_A += msg[i];
CK_B += CK_A;
}
msg[length + 6] = CK_A;
msg[length + 7] = CK_B;
return;
}
void HandleMsgByte(char b)
{
(* msg_parse) ( b ) ;
}
void Store4LE(unsigned char *store, union longbbbb data)
{
store[0] = data.__.B0;
store[1] = data.__.B1;
store[2] = data.__.B2;
store[3] = data.__.B3;
}
void Store2LE(unsigned char *store, union intbb data)
{
store[0] = data._.B0;
store[1] = data._.B1;
}
void msgDefault ( unsigned char rxChar )
{
if ( rxChar == 0xFF )
{
msg_parse = &msgSync1 ;
}
else
{
// error condition
}
return ;
}
void msgSync1 ( unsigned char rxChar )
{
if ( rxChar == 0xEE )
{
store_index = 0 ;
ck_calc_a = ck_calc_b = 0;
msg_parse = &msgServos ;
}
else if ( rxChar == 0xFF )
{
// do nothing
}
else
{
msg_parse = &msgDefault; // error condition
}
return ;
}
void msgServos(unsigned char rxChar)
{
if(store_index < SERVO_MSG_LENGTH)
{
SERVO_IN_[store_index++] = rxChar;
ck_calc_a += rxChar;
ck_calc_b += ck_calc_a;
}
else
{
ck_in_a = rxChar;
msg_parse = &msgCheckSum;
}
}
static int GPSCount = 0;
void msgCheckSum(unsigned char rxChar)
{
ck_in_b = rxChar;
if((ck_in_a == ck_calc_a) && (ck_in_b == ck_calc_b))
{
memcpy(SERVO_IN,SERVO_IN_,sizeof(SERVO_IN_));
GPSCount++;
if (GPSCount % 10 == 0)
{
GetGPSData();
GPSCount = 0;
}
}
msg_parse = &msgDefault;
}
/****************************************************************************************/
// Step through list of controls reading the servo channel, calculating new position
// and setting either a surface or engine(s) to the value
void ServosToControls()
{
int iIndex = 0;
int iSize = ControlSurfaces.size();
int iServoChannel;
intbb ServoValue;
int Value;
float ControlSetting;
ChannelSetup* pScanSetup;
for(iIndex = 0; iIndex < iSize; iIndex++)
{
pScanSetup = &ControlSurfaces[iIndex];
iServoChannel = pScanSetup->mServoChannel;
ServoValue._.B1 = SERVO_IN[2*iServoChannel];
ServoValue._.B0 = SERVO_IN[(2*iServoChannel)+1];
ControlSetting = pScanSetup->GetControlDeflection(ServoValue.BB);
if(pScanSetup->mControlType == CONTROL_TYPE_SURFACE)
{
XPLMSetDataf(pScanSetup->mControlSurfaceRef, ControlSetting);
}
else if(pScanSetup->mControlType == CONTROL_TYPE_ENGINE)
{
unsigned int Mask = pScanSetup->mEngineMask;
for (int Engine = 0; Engine < 8; Engine++)
{
if( (Mask & 0x01) != 0 )
{
ThrottleSettings[Engine] = ControlSetting;
}
Mask >>= 1;
}
}
}
}
// Set all control channels in the list to the default servo position
// Note, if there is more than one control surface per channel, it will reset it
// to the last surface defined in the list
void SetupDefaultServoZeros(void)
{
int iIndex = 0;
int iSize = ControlSurfaces.size();
int iServoChannel;
intbb ServoValue;
ChannelSetup* pScanSetup;
for(iIndex = 0; iIndex < iSize; iIndex++)
{
pScanSetup = &ControlSurfaces[iIndex];
ServoValue.BB = pScanSetup->mChannelOffset;
iServoChannel = pScanSetup->mServoChannel;
SERVO_IN[2*iServoChannel] = ServoValue._.B1;
SERVO_IN[(2*iServoChannel)+1] = ServoValue._.B0;
};
}
void MyHotKeyCallback(void * inRefcon)
{
/* This is the hotkey callback. First we simulate a joystick press and
* release to put us in 'free view 1'. This guarantees that no panels
* are showing and we are an external view. */
XPLMCommandButtonPress(xplm_joy_v_fr1);
XPLMCommandButtonRelease(xplm_joy_v_fr1);
/* Now we control the camera until the view changes. */
XPLMControlCamera(xplm_ControlCameraUntilViewChanges, MyOrbitPlaneFunc, NULL);
}
/*
* MyOrbitPlaneFunc
*
* This is the actual camera control function, the real worker of the plugin. It is
* called each time X-Plane needs to draw a frame.
*
*/
int MyOrbitPlaneFunc(
XPLMCameraPosition_t * outCameraPosition,
int inIsLosingControl,
void * inRefcon)
{
if (outCameraPosition && !inIsLosingControl)
{
int w, h, x, y;
float dx, dz, dy, heading, pitch;
/* First get the screen size and mouse location. We will use this to decide
* what part of the orbit we are in. The mouse will move us up-down and around. */
XPLMGetScreenSize(&w, &h);
XPLMGetMouseLocation(&x, &y);
heading = 2 * PI * (((float) x / (float) w)-0.5);
pitch = PI * (((float) y / (float) h) - 0.5);
double local_x = XPLMGetDataf(drLocal_x);
double local_y = XPLMGetDataf(drLocal_y);
double local_z = XPLMGetDataf(drLocal_z);
float phi = XPLMGetDataf(drPhi);
float theta = XPLMGetDataf(drTheta);
float psi = XPLMGetDataf(drPsi);
// Convert this vector back into angles.
float CamPitchOGL = (atan2( CamY , sqrt( (CamX * CamX) + (CamZ * CamZ) ))) / PI * 180;
float CamYawOGL = (atan2( CamX , CamZ * (float)-1.0 )) / PI * 180;
//sprintf(szString,"CamPitch: %f,\tCamYaw: %f,\tCamX: %f,\tCamY: %f,\tCamZ: %f,\0", (CamPitch), (CamYaw), CamX, CamY, CamZ);
// Camera Position On Aircraft
dx = -1.0;
dy = 0.0;
dz = 1.0;
BCBFtoOGL(dx,dy,dz,phi,theta,psi);
/* Fill out the camera position info. */
outCameraPosition->x = local_x + dx;
outCameraPosition->y = local_y + dy;
outCameraPosition->z = local_z + dz;
outCameraPosition->pitch = CamPitchOGL;
outCameraPosition->heading = CamYawOGL;
outCameraPosition->roll = 0;
}
/* Return 1 to indicate we want to keep controlling the camera. */
return 1;
}
int MyDrawCallback(
XPLMDrawingPhase inPhase,
int inIsBefore,
void * inRefcon)
{
/* If any data refs are missing, do not draw. */
if (!drLocal_x || !drLocal_y || !drLocal_z)
return 1;
/* Fetch the plane's location at this instant in OGL coordinates. */
float planeX = XPLMGetDataf(drLocal_x);
float planeY = XPLMGetDataf(drLocal_y);
float planeZ = XPLMGetDataf(drLocal_z);
float phi = XPLMGetDataf(drPhi) / 180 * PI;
float theta = XPLMGetDataf(drTheta) / 180 * PI;
float psi = XPLMGetDataf(drPsi) / 180 * PI;
float alpha = XPLMGetDataf(drAlpha) / 180 * PI;
float beta = XPLMGetDataf(drBeta) / 180 * PI;
/* Reset the graphics state. This turns off fog, texturing, lighting,
* alpha blending or testing and depth reading and writing, which
* guarantees that our axes will be seen no matter what. */
XPLMSetGraphicsState(0, 0, 0, 0, 0, 0, 0);
/* Do the actual drawing. use GL_LINES to draw sets of discrete lines.
* Each one will go 100 meters in any direction from the plane. */
float pointX1 = 0;
float pointY1 = 0;
float pointZ1 = 0;
float pointX2 = 10 * ax_plane;
float pointY2 = 0;
float pointZ2 = 0;
BCBFtoOGL(pointX1, pointY1, pointZ1, phi, theta, psi);
BCBFtoOGL(pointX2, pointY2, pointZ2, phi, theta, psi);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3f(pointX1 + planeX, pointY1 + planeY, pointZ1 + planeZ);
glVertex3f(pointX2 + planeX, pointY2 + planeY, pointZ2 + planeZ);
glEnd();
pointX1 = 0;
pointY1 = 0;
pointZ1 = 0;
pointX2 = 0;
pointY2 = 10 * ay_plane;
pointZ2 = 0;
BCBFtoOGL(pointX1, pointY1, pointZ1, phi, theta, psi);
BCBFtoOGL(pointX2, pointY2, pointZ2, phi, theta, psi);
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_LINES);
glVertex3f(pointX1 + planeX, pointY1 + planeY, pointZ1 + planeZ);
glVertex3f(pointX2 + planeX, pointY2 + planeY, pointZ2 + planeZ);
glEnd();
pointX1 = 0;
pointY1 = 0;
pointZ1 = 0;
pointX2 = 0;
pointY2 = 0;
pointZ2 = 10 * az_plane;
BCBFtoOGL(pointX1, pointY1, pointZ1, phi, theta, psi);
BCBFtoOGL(pointX2, pointY2, pointZ2, phi, theta, psi);
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINES);
glVertex3f(pointX1 + planeX, pointY1 + planeY, pointZ1 + planeZ);
glVertex3f(pointX2 + planeX, pointY2 + planeY, pointZ2 + planeZ);
glEnd();
// Calculate a direction vector for the camera in the aircraft reference frame.
CamX = cos(CamPitch) * cos(CamYaw);
CamY = cos(CamPitch) * sin(CamYaw);
CamZ = sin(CamPitch);
// Convert this vector to the OGL frame
BCBFtoOGL(CamX, CamY, CamZ, phi, theta, psi);
float scalar = 1;
if( CamY != 0 ) scalar = (planeY - 624) / CamY * -1.0;
// If the camera view intersects the ground, add that point to the
// camera ground path.
if(CamY < 0)
{
CamPath[CamPathIterator][0] = (CamX * scalar) + planeX;
CamPath[CamPathIterator][1] = (CamY * scalar) + planeY;
CamPath[CamPathIterator][2] = (CamZ * scalar) + planeZ;
}
// A vector pointing in the direction of the camera
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_LINES);
glVertex3f(planeX, planeY, planeZ);
glVertex3f((CamX * scalar) + planeX,(CamY * scalar) + planeY,(CamZ * scalar) + planeZ);
glEnd();
// Display the OpenGL axis'
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINES);
glVertex3f(planeX, planeY, planeZ);
glVertex3f(planeX+100, planeY, planeZ);
glVertex3f(planeX, planeY, planeZ);
glVertex3f(planeX, planeY+100, planeZ);
glVertex3f(planeX, planeY, planeZ);
glVertex3f(planeX, planeY, planeZ+100);
glEnd();
// Display the camera ground track
int i = 0;
int j = CamPathIterator;
/*glColor3f(0.0, 1.0, 0.0);
glBegin(GL_LINE_STRIP);
for(i = 0; i < CamPathCount; i++)
{
glVertex3f(CamPath[j][0],CamPath[j][1],CamPath[j][2]);
j--;
if(j < 0) j = (CamPathLength - 1);
}
glEnd();*/
if(CamPathCount < CamPathLength) CamPathCount++;
if(CamY < 0) CamPathIterator++;
if(CamPathIterator >= CamPathLength) CamPathIterator = 0;
// Display a vector in the flight frame
pointX1 = 100;
pointY1 = 0;
pointZ1 = 0;
FLIGHTtoBCBF(pointX1, pointY1, pointZ1, alpha, beta);
BCBFtoOGL(pointX1, pointY1, pointZ1, phi, theta, psi);
glColor3f(1.0, 0.0, 1.0);
glBegin(GL_LINES);
glVertex3f(pointX1 + planeX, pointY1 + planeY, pointZ1 + planeZ);
glVertex3f(planeX, planeY, planeZ);
glEnd();
// Test our rotation from OGL to BCBF frame
/*pointX1 = 0;
pointY1 = 0;
pointZ1 = 20;
OGLtoBCBF(pointX1, pointY1, pointZ1, phi, theta, psi);
BCBFtoOGL(pointX1, pointY1, pointZ1, phi, theta, psi);
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3f(pointX1 + planeX, pointY1 + planeY, pointZ1 + planeZ);
glVertex3f(planeX, planeY, planeZ);
glEnd();*/
return 1;
} | [
"[email protected]@d12ab692-325c-acc3-3055-b791ab0241ae"
] | [
[
[
1,
937
]
]
] |
6f4aaeda8a4a424c18a6350d4c3fd42d68b0c262 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/sidearms.h | 87dfb67a1c62307a4ff70dcb306ce33d6d68cfee | [] | no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 925 | h | class sidearms_state : public driver_device
{
public:
sidearms_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
int m_gameid;
UINT8 *m_videoram;
UINT8 *m_colorram;
UINT8 *m_bg_scrollx;
UINT8 *m_bg_scrolly;
UINT8 *m_tilerom;
tilemap_t *m_bg_tilemap;
tilemap_t *m_fg_tilemap;
int m_bgon;
int m_objon;
int m_staron;
int m_charon;
int m_flipon;
UINT32 m_hflop_74a_n;
UINT32 m_hcount_191;
UINT32 m_vcount_191;
UINT32 m_latch_374;
};
/*----------- defined in video/sidearms.c -----------*/
WRITE8_HANDLER( sidearms_videoram_w );
WRITE8_HANDLER( sidearms_colorram_w );
WRITE8_HANDLER( sidearms_star_scrollx_w );
WRITE8_HANDLER( sidearms_star_scrolly_w );
WRITE8_HANDLER( sidearms_c804_w );
WRITE8_HANDLER( sidearms_gfxctrl_w );
VIDEO_START( sidearms );
SCREEN_UPDATE( sidearms );
SCREEN_EOF( sidearms );
| [
"Mike@localhost"
] | [
[
[
1,
40
]
]
] |
6eb851d31e95cdeaee0840b283302bf00925e920 | dd007771e947dbed60fe6a80d4f325c4ed006f8c | /ofPoint.h | 6c79b564625b1817a7c82f088a8124351717ac8a | [] | no_license | chenzhi/CameraGame | fccea24426ea5dacbe140b11adc949e043e84ef7 | 914e1a2b8bb45b729e8d55b4baebc9ba18989b55 | refs/heads/master | 2016-09-05T20:06:11.694787 | 2011-09-09T09:09:39 | 2011-09-09T09:09:39 | 2,005,632 | 0 | 0 | null | null | null | null | TIS-620 | C++ | false | false | 8,637 | h | /*
* ofPoint.h
* Accelerometer
*
* Created by chen zhi on 11-6-18.
* Copyright 2011 sx. All rights reserved.
*
*/
#ifndef ofPoint_h_h_h_h_
#define ofPoint_h_h_h_h_
#include <math.h>
#include <string.h>
#define RAD_TO_DEG (180.0f/3.1415926f)
class ofPoint
{
public:
virtual ~ofPoint()
{}
ofPoint( float _x=0.0f, float _y=0.0f, float _z=0.0f ) {
x = _x;
y = _y;
z = _z;
}
ofPoint( const ofPoint & pnt){
x = pnt.x;
y = pnt.y;
z = pnt.z;
}
void set(float _x, float _y, float _z = 0){
x = _x;
y = _y;
z = _z;
}
//------ Operators:
//Negative
ofPoint operator-() const {
return ofPoint( -x, -y, -z );
}
//equality
bool operator==( const ofPoint& pnt ) {
return (x == pnt.x) && (y == pnt.y) && (z == pnt.z);
}
//inequality
bool operator!=( const ofPoint& pnt ) {
return (x != pnt.x) || (y != pnt.y) || (z != pnt.z);
}
//Set
ofPoint & operator=( const ofPoint& pnt ){
x = pnt.x;
y = pnt.y;
z = pnt.z;
return *this;
}
ofPoint & operator=( const float& val ){
x = val;
y = val;
z = val;
return *this;
}
// Add
ofPoint operator+( const ofPoint& pnt ) const {
return ofPoint( x+pnt.x, y+pnt.y, z+pnt.z );
}
ofPoint operator+( const float& val ) const {
return ofPoint( x+val, y+val, z+val );
}
ofPoint & operator+=( const ofPoint& pnt ) {
x+=pnt.x;
y+=pnt.y;
z+=pnt.z;
return *this;
}
ofPoint & operator+=( const float & val ) {
x+=val;
y+=val;
z+=val;
return *this;
}
// Subtract
ofPoint operator-(const ofPoint& pnt) const {
return ofPoint( x-pnt.x, y-pnt.y, z-pnt.z );
}
ofPoint operator-(const float& val) const {
return ofPoint( x-val, y-val, z-val);
}
ofPoint & operator-=( const ofPoint& pnt ) {
x -= pnt.x;
y -= pnt.y;
z -= pnt.z;
return *this;
}
ofPoint & operator-=( const float & val ) {
x -= val;
y -= val;
z -= val;
return *this;
}
// Multiply
ofPoint operator*( const ofPoint& pnt ) const {
return ofPoint( x*pnt.x, y*pnt.y, z*pnt.z );
}
ofPoint operator*(const float& val) const {
return ofPoint( x*val, y*val, z*val);
}
ofPoint & operator*=( const ofPoint& pnt ) {
x*=pnt.x;
y*=pnt.y;
z*=pnt.z;
return *this;
}
ofPoint & operator*=( const float & val ) {
x*=val;
y*=val;
z*=val;
return *this;
}
// Divide
ofPoint operator/( const ofPoint& pnt ) const {
return ofPoint( pnt.x!=0 ? x/pnt.x : x , pnt.y!=0 ? y/pnt.y : y, pnt.z!=0 ? z/pnt.z : z );
}
ofPoint operator/( const float &val ) const {
if( val != 0){
return ofPoint( x/val, y/val, z/val );
}
return ofPoint(x, y, z );
}
ofPoint& operator/=( const ofPoint& pnt ) {
pnt.x!=0 ? x/=pnt.x : x;
pnt.y!=0 ? y/=pnt.y : y;
pnt.z!=0 ? z/=pnt.z : z;
return *this;
}
ofPoint& operator/=( const float &val ) {
if( val != 0 ){
x /= val;
y /= val;
z /= val;
}
return *this;
}
// union allows us to access the coordinates through
// both an array 'v' and 'x', 'y', 'z' member varibles
union {
struct {
float x;
float y;
float z;
};
float v[3];
};
float& operator[]( int n )
{
return v[n];
}
};
typedef void (*ofxAccelCB)(ofPoint& point); // typedef for accelerometer callback
class ofxAccelerometerHandler
{
public:
ofxAccelerometerHandler()
{
callback = 0;
setForceSmoothing(0.0f); // little bit of smoothing for force
setOrientationSmoothing(0.9f); // lots of smoothing for orientation / matrix
}
// call this to set it all up
//void setup();กา
// call this when you no longer need the accelerometer
//void exit();
// returns current smoothed accelerometer data (value in number of g's (1g = gravity, 9.8m/s^2)
ofPoint &getForce()
{
return accelForce;
}
// returns current real accelerometer data (value in number of g's (1g = gravity, 9.8m/s^2)
ofPoint &getRawAcceleration()
{
return accelReal;
}
// returns current orientation in degrees (x: pitch, y: roll, z: not used)
ofPoint &getOrientation()
{
updateOrientation();
return orientation;
}
const ofPoint& getSmoothOrientation()
{
return accelOrientation;
}
float* getMatrix()
{
updateMatrix();
return (float*)matrix;
}
// set amount of smoothing on data (0: no smooth, 1:very smooth)
void setForceSmoothing(float forceSmoothing)
{
this->forceSmoothing = forceSmoothing;
}
void setOrientationSmoothing(float orientationSmoothing)
{
this->orientationSmoothing = orientationSmoothing;
}
// if you have a callback which conforms to ofxAccelCB, pass it to this to have it called when motion is detected
void setCallback(ofxAccelCB new_callback)
{
callback = new_callback;
}
// platform specific accelerometer engine should call this when motion is detected
void update(float x, float y, float z)
{
orientDirty = matrixDirty = true;
accelReal.set(x, y, z);
if(forceSmoothing) {
float lerpFactor = 1 - forceSmoothing;
if(lerpFactor>1) lerpFactor = 1;
else if(lerpFactor < 0.01f) lerpFactor = 0.01f;
accelForce += (accelReal - accelForce) * lerpFactor;
} else {
accelForce.set(x, y, z);
}
if(orientationSmoothing) {
float lerpFactor = 1 - orientationSmoothing;
if(lerpFactor>1) lerpFactor = 1;
else if(lerpFactor < 0.01f) lerpFactor = 0.01f;
accelOrientation += (accelReal - accelOrientation) * lerpFactor;
} else {
accelOrientation.set(x, y, z);
}
if(callback) callback(accelReal);
}
protected:
ofxAccelCB callback;
float forceSmoothing; // amount to smooth incoming data by
float orientationSmoothing; // amount to smooth orientation by
// ofPoint restAccel; // rest acceleration (for calibration)
ofPoint accelReal; // current acceleration
ofPoint accelForce; // smoothed for force
ofPoint accelOrientation; // smoothed for acceleration
ofPoint orientation; // current orientation
bool orientDirty;
float matrix[4][4]; // contains orientation matrix
bool matrixDirty;
void updateOrientation()
{
if(!orientDirty) return;
orientDirty = false;
orientation.x = atan2(accelOrientation.y, -accelOrientation.z) * RAD_TO_DEG;
orientation.y = atan2(accelOrientation.x, -accelOrientation.z) * RAD_TO_DEG;
orientation.z = 0;
}
void updateMatrix()
{
if(!matrixDirty)
return;
matrixDirty = false;
float length;
//Make sure we have a big enough acceleration vector
length = sqrtf(accelOrientation.x * accelOrientation.x + accelOrientation.y * accelOrientation.y + accelOrientation.z * accelOrientation.z);
if(length < 0.1) return;
//Clear matrix to be used to rotate from the current referential to one based on the gravity vector
//memset(matrix, sizeof(matrix),0);
memset(matrix, 0, sizeof(matrix));
matrix[3][3] = 1.0;
//Setup first matrix column as gravity vector
matrix[0][0] = accelOrientation.x / length;
matrix[0][1] = accelOrientation.y / length;
matrix[0][2] = accelOrientation.z / length;
//Setup second matrix column as an arbitrary vector in the plane perpendicular to the gravity vector {Gx, Gy, Gz} defined by by the equation "Gx * x + Gy * y + Gz * z = 0" in which we arbitrarily set x=0 and y=1
matrix[1][0] = 0.0;
matrix[1][1] = 1.0;
matrix[1][2] = -accelOrientation.y / accelOrientation.z;
length = sqrtf(matrix[1][0] * matrix[1][0] + matrix[1][1] * matrix[1][1] + matrix[1][2] * matrix[1][2]);
matrix[1][0] /= length;
matrix[1][1] /= length;
matrix[1][2] /= length;
//Setup third matrix column as the cross product of the first two
matrix[2][0] = matrix[0][1] * matrix[1][2] - matrix[0][2] * matrix[1][1];
matrix[2][1] = matrix[1][0] * matrix[0][2] - matrix[1][2] * matrix[0][0];
matrix[2][2] = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
}
};
#endif | [
"chenzhi@aee8fb6d-90e1-2f42-9ce8-abdac5710353"
] | [
[
[
1,
361
]
]
] |
29e8aebf47bdb859bb3385d20ed8e39b57a2d487 | e95784c83b6cec527f3292d2af4f2ee9b257a0b7 | /UAV/Drivers/Camera.h | a29ecc86e82af459cfbe31a1eb4b635e2b0623d7 | [] | no_license | ehaskins/scoe-robotics-onboard-controller | 5e6818cb469c512a4429aa6ccb96478b89c9ce6f | f44887f79cf89c9ff85963e515381199c9b2b2d7 | refs/heads/master | 2020-06-06T12:53:54.350781 | 2011-05-01T00:26:17 | 2011-05-01T00:26:17 | 32,115,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,703 | h | /*
* Camera.h
*
* Created on: Apr 11, 2011
* Author: Nick
*/
#ifndef CAMERA_H_
#define CAMERA_H_
#include "Drivers.h"
#include "ICamera.h"
#include "BaseSensor.h"
typedef enum {
CMU_BM, // Buffer Mode
CMU_CR, // Camera Register
CMU_CP, // Camera Power
CMU_CT, // Camera Type
CMU_DC, // Differencing Channel
CMU_DM, // Delay Mode
CMU_DS, // Down Sampling
CMU_FD, // Frame Differencing
CMU_FS, // Frame Streaming
CMU_GB, // Get Button
CMU_GH, // Get Histogram
CMU_GI, // Get Input
CMU_GM, // Get Mean
CMU_GS, // Get Servo
CMU_GT, // Get Track
CMU_GV, // Get Version
CMU_GW, // Get Window
CMU_HC, // Histogram Config
CMU_HD, // Hi-res Differencing
CMU_HR, // Hi-Res mode
CMU_HT, // Histogram Tracking
CMU_L0, // LED 0
CMU_L1, // LED 1
CMU_LF, // Load Frame
CMU_LM, // Line Mode
CMU_MD, // Masked Differencing
CMU_NF, // Noise Filter
CMU_OM, // Output Mask
CMU_PD, // Pixel Differencing
CMU_PF, // Packet Filtering
CMU_PM, // Poll Mode
CMU_PS, // Packet Skip
CMU_RF, // Read Frame
CMU_RM, // Raw Mode
CMU_RS, // Reset
CMU_SD, // Sleep Deeply
CMU_SF, // Send Frame
CMU_SL, // Sleep
CMU_SM, // Servo Mask
CMU_SO, // Servo Output
CMU_SP, // Servo Parameters
CMU_ST, // Set Tracking
CMU_SV, // Servo Value (position)
CMU_TC, // Track Color
CMU_TI, // Track Inverted
CMU_TW, // Track Windowed
CMU_UD, // Upload Difference
CMU_VW // Virtual Window
} CMUCAM_CMDS;
class Camera : public BaseSensor, public ICamera {
public:
Camera();
virtual ~Camera();
};
#endif /* CAMERA_H_ */
| [
"[email protected]"
] | [
[
[
1,
73
]
]
] |
fa4093e618820ed41bfa7ba6a1b4f23891ec65e1 | f8b364974573f652d7916c3a830e1d8773751277 | /emulator/log.h | ddef47055caaae6ae18ba4469915465fdc38875a | [] | no_license | lemmore22/pspe4all | 7a234aece25340c99f49eac280780e08e4f8ef49 | 77ad0acf0fcb7eda137fdfcb1e93a36428badfd0 | refs/heads/master | 2021-01-10T08:39:45.222505 | 2009-08-02T11:58:07 | 2009-08-02T11:58:07 | 55,047,469 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 2,808 | h | /*
* log.h
*
* Created on: 13 déc. 2008
* Author: hli
*/
#ifndef LOG_H_
#define LOG_H_
#include <string>
#include <cstdarg>
class LogFile
{
public:
enum LevelEnum
{
E_OFF, E_FATAL, E_ERROR, E_WARN, E_INFO, E_DEBUG, E_TRACE
};
LogFile(std::string const &name);
~LogFile();
void reset();
void flush();
static void useConsole(bool use);
LevelEnum getLevel() const;
void setLevel(LevelEnum level);
bool checkLevel(LevelEnum level) const;
void log(LevelEnum level, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(level, fmt, args);
va_end(args);
}
void fatal(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(E_FATAL, fmt, args);
va_end(args);
}
void error(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(E_ERROR, fmt, args);
va_end(args);
}
void warn(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(E_WARN, fmt, args);
va_end(args);
}
void info(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(E_INFO, fmt, args);
va_end(args);
}
void debug(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(E_DEBUG, fmt, args);
va_end(args);
}
void trace(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
printf(E_TRACE, fmt, args);
va_end(args);
}
private:
void printf(LevelEnum level, const char *fmt, va_list args);
LogFile(LogFile const &);
void operator =(LogFile const &);
LevelEnum level;
FILE *file;
std::string name;
};
#ifdef NO_LOGGING
#define lprintf(name, level, fmt, ...)
#define fatalf(name, fmt, ...)
#define errorf(name, fmt, ...)
#define warnf(name, fmt, ...)
#define infof(name, fmt, ...)
#define debugf(name, fmt, ...)
#define tracef(name, fmt, ...)
#else
#define lprintf(name, level, fmt, ...) Log::name.log(level, fmt, ## __VA_ARGS__)
#define fatalf(name, fmt, ...) Log::name.fatal(fmt, ## __VA_ARGS__)
#define errorf(name, fmt, ...) Log::name.error(fmt, ## __VA_ARGS__)
#define warnf(name, fmt, ...) Log::name.warn(fmt, ## __VA_ARGS__)
#define infof(name, fmt, ...) Log::name.info(fmt, ## __VA_ARGS__)
#define debugf(name, fmt, ...) Log::name.debug(fmt, ## __VA_ARGS__)
#define tracef(name, fmt, ...) Log::name.trace(fmt, ## __VA_ARGS__)
#endif
namespace Log
{
void show(const char *s);
void reset();
extern LogFile misc;
extern LogFile memory;
extern LogFile interpreter;
}
#endif /* LOG_H_ */
| [
"[email protected]"
] | [
[
[
1,
127
]
]
] |
63d6f23e2acc254957181bd362b4d6ffe06c8d37 | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/CryEngine/CryCommon/IInput.h | 513925bdd5df0cd786ee35150a347ca7e9189ebd | [] | no_license | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05T14:32:01.782047 | 2008-01-01T13:13:39 | 2008-01-01T13:13:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,450 | h | #ifndef __IINPUT_H__
#define __IINPUT_H__
#ifdef CRYINPUT_EXPORTS
#define CRYINPUT_API DLL_EXPORT
#else
#define CRYINPUT_API DLL_IMPORT
#endif
#include <platform.h>
#include <CryName.h>
#include <vector>
#include <map>
enum EModifierMask
{
eMM_None = 0,
eMM_LCtrl = (1 << 0),
eMM_LShift = (1 << 1),
eMM_LAlt = (1 << 2),
eMM_LWin = (1 << 3),
eMM_RCtrl = (1 << 4),
eMM_RShift = (1 << 5),
eMM_RAlt = (1 << 6),
eMM_RWin = (1 << 7),
eMM_NumLock = (1 << 8),
eMM_CapsLock = (1 << 9),
eMM_ScrollLock = (1 << 10),
eMM_Ctrl = (eMM_LCtrl | eMM_RCtrl),
eMM_Shift = (eMM_LShift | eMM_RShift),
eMM_Alt = (eMM_LAlt | eMM_RAlt),
eMM_Win = (eMM_LWin | eMM_RWin),
eMM_Modifiers = (eMM_Ctrl | eMM_Shift | eMM_Alt | eMM_Win),
eMM_LockKeys = (eMM_CapsLock | eMM_NumLock | eMM_ScrollLock)
};
enum EDeviceId
{
eDI_Keyboard = 0,
eDI_Mouse = 1,
eDI_XI = 2,
eDI_Unknown = 0xff,
};
enum EFFEffectId
{
eFF_Rumble_Basic = 0
};
//! Input Event types.
enum EInputState
{
eIS_Unknown = 0,
eIS_Pressed = (1 << 0),
eIS_Released = (1 << 1),
eIS_Down = (1 << 2),
eIS_Changed = (1 << 3),
eIS_UI = (1 << 4),
};
enum EInputDeviceType
{
eIDT_Keyboard,
eIDT_Mouse,
eIDT_Joystick,
eIDT_Gamepad,
};
struct TKeyName
{
const char *key;
TKeyName() { key = ""; }
TKeyName( const char *_key ) { key = _key; };
operator const char*() const { return key; };
bool operator<( const TKeyName &n ) const { return stricmp(key,n.key) < 0; }
bool operator>( const TKeyName &n ) const { return stricmp(key,n.key) > 0; }
bool operator==( const TKeyName &n ) const { return stricmp(key,n.key) == 0; }
bool operator!=( const TKeyName &n ) const { return stricmp(key,n.key) != 0; }
bool operator<( const char *str ) const { return stricmp(key,str) < 0; }
bool operator>( const char *str ) const { return stricmp(key,str) > 0; }
bool operator==( const char *str ) const { return stricmp(key,str) == 0; }
bool operator!=( const char *str ) const { return stricmp(key,str) != 0; }
const char *c_str() const { return key; }
};
inline bool operator==( const char *str,TKeyName &n ) { return n == str; }
inline bool operator!=( const char *str,TKeyName &n ) { return n != str; }
inline bool operator<( const char *str,TKeyName &n ) { return n < str; }
inline bool operator>( const char *str,TKeyName &n ) { return n > str; }
#define KI_KEYBOARD_BASE 0
#define KI_MOUSE_BASE 256
#define KI_XINPUT_BASE 512
#define KI_PS3_BASE 1024
#define KI_SYS_BASE 2048
enum EKeyId
{
eKI_Escape = KI_KEYBOARD_BASE,
eKI_1,
eKI_2,
eKI_3,
eKI_4,
eKI_5,
eKI_6,
eKI_7,
eKI_8,
eKI_9,
eKI_0,
eKI_Minus,
eKI_Equals,
eKI_Backspace,
eKI_Tab,
eKI_Q,
eKI_W,
eKI_E,
eKI_R,
eKI_T,
eKI_Y,
eKI_U,
eKI_I,
eKI_O,
eKI_P,
eKI_LBracket,
eKI_RBracket,
eKI_Enter,
eKI_LCtrl,
eKI_A,
eKI_S,
eKI_D,
eKI_F,
eKI_G,
eKI_H,
eKI_J,
eKI_K,
eKI_L,
eKI_Semicolon,
eKI_Apostrophe,
eKI_Tilde,
eKI_LShift,
eKI_Backslash,
eKI_Z,
eKI_X,
eKI_C,
eKI_V,
eKI_B,
eKI_N,
eKI_M,
eKI_Comma,
eKI_Period,
eKI_Slash,
eKI_RShift,
eKI_NP_Multiply,
eKI_LAlt,
eKI_Space,
eKI_CapsLock,
eKI_F1,
eKI_F2,
eKI_F3,
eKI_F4,
eKI_F5,
eKI_F6,
eKI_F7,
eKI_F8,
eKI_F9,
eKI_F10,
eKI_NumLock,
eKI_ScrollLock,
eKI_NP_7,
eKI_NP_8,
eKI_NP_9,
eKI_NP_Substract,
eKI_NP_4,
eKI_NP_5,
eKI_NP_6,
eKI_NP_Add,
eKI_NP_1,
eKI_NP_2,
eKI_NP_3,
eKI_NP_0,
eKI_F11,
eKI_F12,
eKI_F13,
eKI_F14,
eKI_F15,
eKI_Colon,
eKI_Underline,
eKI_NP_Enter,
eKI_RCtrl,
eKI_NP_Period,
eKI_NP_Divide,
eKI_Print,
eKI_RAlt,
eKI_Pause,
eKI_Home,
eKI_Up,
eKI_PgUp,
eKI_Left,
eKI_Right,
eKI_End,
eKI_Down,
eKI_PgDn,
eKI_Insert,
eKI_Delete,
eKI_LWin,
eKI_RWin,
eKI_Apps,
eKI_OEM_102,
// mouse
eKI_Mouse1 = KI_MOUSE_BASE,
eKI_Mouse2,
eKI_Mouse3,
eKI_Mouse4,
eKI_Mouse5,
eKI_Mouse6,
eKI_Mouse7,
eKI_Mouse8,
eKI_MouseWheelUp,
eKI_MouseWheelDown,
eKI_MouseX,
eKI_MouseY,
eKI_MouseZ,
eKI_MouseLast,
// X360 controller
eKI_XI_DPadUp = KI_XINPUT_BASE,
eKI_XI_DPadDown,
eKI_XI_DPadLeft,
eKI_XI_DPadRight,
eKI_XI_Start,
eKI_XI_Back,
eKI_XI_ThumbL,
eKI_XI_ThumbR,
eKI_XI_ShoulderL,
eKI_XI_ShoulderR,
eKI_XI_A,
eKI_XI_B,
eKI_XI_X,
eKI_XI_Y,
eKI_XI_TriggerL,
eKI_XI_TriggerR,
eKI_XI_ThumbLX,
eKI_XI_ThumbLY,
eKI_XI_ThumbRX,
eKI_XI_ThumbRY,
eKI_XI_TriggerLBtn,
eKI_XI_TriggerRBtn,
eKI_XI_Connect,
eKI_XI_Disconnect,
// PS3 controller
eKI_PS3_Select = KI_PS3_BASE,
eKI_PS3_L3,
eKI_PS3_R3,
eKI_PS3_Start,
eKI_PS3_Up,
eKI_PS3_Right,
eKI_PS3_Down,
eKI_PS3_Left,
eKI_PS3_L2,
eKI_PS3_R2,
eKI_PS3_L1,
eKI_PS3_R1,
eKI_PS3_Triangle,
eKI_PS3_Circle,
eKI_PS3_Cross,
eKI_PS3_Square,
eKI_PS3_StickLX,
eKI_PS3_StickLY,
eKI_PS3_StickRX,
eKI_PS3_StickRY,
eKI_PS3_RotX,
eKI_PS3_RotY,
eKI_PS3_RotZ,
eKI_PS3_ROTX_KeyL,
eKI_PS3_ROTX_KeyR,
eKI_PS3_ROTZ_KeyD,
eKI_PS3_ROTZ_KeyU,
eKI_SYS_Commit = KI_SYS_BASE,
// terminator
eKI_Unknown = 0xffffffff,
};
/*! InputEvents are generated by input system and dispatched to all event listeners.
*/
struct SInputSymbol;
struct SInputEvent
{
EDeviceId deviceId; // which device did the event originate from
EInputState state; // type of input event
TKeyName keyName; // human readable name of the event
EKeyId keyId; // device-specific id corresponding to the event
uint32 timestamp; // timestamp of the event, (GetTickCount compatible)
int modifiers; // key modifiers enabled at the time of this event
float value; // value associated with the event
SInputSymbol* pSymbol; // input symbol the event originated from
SInputEvent()
{
deviceId = eDI_Unknown;
state = eIS_Unknown;
keyId = eKI_Unknown;
modifiers = eMM_None;
timestamp = 0;
value = 0;
keyName = "";
pSymbol = 0;
}
};
/*! SFFOutputEvents are force feedback signals send to an input controller
*/
struct SFFOutputEvent
{
EDeviceId deviceId; // which device will receive the event
EFFEffectId eventId;
float amplifierS, amplifierA;
float timeInSeconds;
SFFOutputEvent()
{
deviceId = eDI_Unknown;
eventId = eFF_Rumble_Basic;
amplifierS = 1.0f;
amplifierA = 1.0f;
timeInSeconds = 0.3f;
}
SFFOutputEvent(EDeviceId id, EFFEffectId event, float time = 1.0f, float ampA = 1.0f, float ampB = 1.0f) :
deviceId(id), eventId(event), timeInSeconds(time), amplifierS(ampA), amplifierA(ampB)
{}
};
struct SInputSymbol
{
//! input symbol type
enum EType
{
Button, // state == press/hold/release -- value = 0, 1
Toggle, // transition state with a press
RawAxis, // state == change -- value = movement of axis
Axis, // state == change -- value = -1.0 to 1.0
Trigger, // state == change -- value = 0.0 to 1.0
};
SInputSymbol(uint32 devSpecId_, EKeyId keyId_, const TKeyName& name_, EType type_, uint32 user_ = 0)
: devSpecId(devSpecId_)
, keyId(keyId_), name(name_)
, state(eIS_Unknown)
, type(type_)
, value(0.0f)
, user(user_)
{
}
void PressEvent(bool pressed)
{
if (pressed)
{
state = eIS_Pressed;
value = 1.0f;
}
else
{
state = eIS_Released;
value = 0.0f;
}
}
void ChangeEvent(float v)
{
state = eIS_Changed;
value = v;
}
void AssignTo(SInputEvent& event, int modifiers=0)
{
event.pSymbol = this;
event.deviceId= deviceId;
event.modifiers= modifiers;
event.state = state;
event.value = value;
event.keyName = name;
event.keyId = keyId;
}
const EKeyId keyId; // external id for fast comparison
const TKeyName name; // human readable name of the event
const uint32 devSpecId; // device internal id of this symbol (we will use it to look it up)
EInputState state; // current state
const EType type; // type of this symbol
float value; // current value
uint32 user; // type dependent value (toggle-mask for toggles)
EDeviceId deviceId; // which device does the symbol belong to
};
//////////////////////////////////////////////////////////////////////////
/* Input event listeners registered to input system and receive input events when they are generated.
*/
struct IInputEventListener
{
//! Called every time input event is generated.
//! @return if return True then broadcasting of this event should be aborted and the rest of input
//! listeners should not receive this event.
virtual bool OnInputEvent( const SInputEvent &event ) = 0;
virtual bool OnInputEventUI( const SInputEvent &event ) { return false; }
};
/*! Interface to the Input system.
The input system give access and initialize Keyboard,Mouse and Joystick SubSystems.
*/
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
/*! Main Input system interface.
*/
struct IInput
{
//////////////////////////////////////////////////////////////////////////
//! Register new input events listener.
virtual void AddEventListener( IInputEventListener *pListener ) = 0;
virtual void RemoveEventListener( IInputEventListener *pListener ) = 0;
//! Register new console input event listeners. console input listeners receive all events, no matter what.
virtual void AddConsoleEventListener( IInputEventListener *pListener ) = 0;
virtual void RemoveConsoleEventListener( IInputEventListener *pListener ) = 0;
//! Register an exclusive listener which has the ability to filter out events before they arrive at the normal
//! listeners
virtual void SetExclusiveListener( IInputEventListener *pListener ) = 0;
virtual IInputEventListener *GetExclusiveListener() = 0;
//! Register an exclusive listener which has the ability to filter out events before they arrive at the normal
//! listeners
virtual void EnableEventPosting ( bool bEnable ) = 0;
virtual void PostInputEvent( const SInputEvent &event ) = 0;
//! post a force feedback / rumble output event
virtual void ForceFeedbackEvent( const SFFOutputEvent &event ) = 0;
//////////////////////////////////////////////////////////////////////////
//! init input system (required params should be passed through constructor)
virtual bool Init() = 0;
//! update Keyboard, Mouse and Joystick. Set bFocus to true if window has focus and input is enabled.
virtual void Update(bool bFocus) = 0;
//! clear all subsystems
virtual void ShutDown() = 0;
//! @see IInputDevice::SetExclusive
virtual void SetExclusiveMode(EDeviceId deviceId, bool exclusive,void *hwnd=0) = 0;
//! @see IInputDevice::InputState
virtual bool InputState(const TKeyName& key, EInputState state) = 0;
//! Convert an input event to the key name. Should internally dispatch to all managed input devices and
//! return the first recognized event.
//! @param event input event to translate into a name
virtual const char *GetKeyName(const SInputEvent& event, bool bGUI = 0) = 0;
// Lookup a symbol for a given symbol and key ids.
virtual SInputSymbol* LookupSymbol( EDeviceId deviceId, EKeyId keyId ) = 0;
//! Get OS Keyname
//! @param event input event to translate into a name
virtual const wchar_t* GetOSKeyName(const SInputEvent& event) = 0;
//! clear key states of all devices
virtual void ClearKeyState() = 0;
//! retriggers pressed keys (used for transitioning action maps)
virtual void RetriggerKeyState() = 0;
//! are we currently retriggering (needed to filter out actions)
virtual bool Retriggering() = 0;
// query to see if this machine has some kind of input device connected
virtual bool HasInputDeviceOfType( EInputDeviceType type ) = 0;
// get the currently pressed modifiers
virtual int GetModifiers() const = 0;
//! tell devices whether to report input or not
virtual void EnableDevice( EDeviceId deviceId, bool enable) = 0;
};
#ifdef __cplusplus
extern "C" {
#endif
typedef IInput (* CRY_PTRCREATEINPUTFNC(ISystem *pSystem, void* hwnd));
CRYINPUT_API IInput *CreateInput(ISystem *pSystem, void* hwnd);
#ifdef __cplusplus
};
#endif
#endif //__IINPUT_H__
| [
"[email protected]",
"kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31"
] | [
[
[
1,
59
],
[
61,
274
],
[
282,
407
],
[
409,
434
],
[
437,
439
],
[
441,
464
],
[
468,
471
],
[
478,
482
],
[
486,
503
]
],
[
[
60,
60
],
[
275,
281
],
[
408,
408
],
[
435,
436
],
[
440,
440
],
[
465,
467
],
[
472,
477
],
[
483,
485
]
]
] |
684431afcdfa8811d79b9d29a9f0eed6070cc6e7 | 6c8c4728e608a4badd88de181910a294be56953a | /ProtocolModuleTaiga/TaigaWorldSession.h | 76274a4101b6ef9c6141a6113172a45c25085708 | [
"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 | 2,175 | h | // For conditions of distribution and use, see copyright notice in license.txt
#ifndef incl_ProtocolUtilities_TaigaWorldSession_h
#define incl_ProtocolUtilities_TaigaWorldSession_h
#include "Login/LoginCredentials.h"
#include "ProtocolModuleTaigaApi.h"
#include "Interfaces/WorldSessionInterface.h"
#include <QUrl>
namespace TaigaProtocol
{
class TAIGAPROTO_MODULE_API TaigaWorldSession : public ProtocolUtilities::WorldSessionInterface
{
public:
//! RealXtendWorldSession constructor
TaigaWorldSession(Foundation::Framework *framework);
//! RealXtendWorldSession deconstructor
virtual ~TaigaWorldSession(void);
/* INHERITED FUNCTIONS FROM WorldSessionInterface */
//! Login function
bool StartSession(ProtocolUtilities::LoginCredentialsInterface *credentials, QUrl *serverEntryPointUrl);
//! Cable Beach style login, setting authentication done unlike normal LoginToServer
bool LoginToServer(const QString& address,
const QString& port,
const QString& identityUrl,
ProtocolUtilities::ConnectionThreadState *thread_state);
//! Make Url validation according to type
QUrl ValidateUrl(const QString urlString, const UrlType urlType);
//! Get login credentials
ProtocolUtilities::LoginCredentialsInterface* GetCredentials() const;
//! Get server entry point url. Used for xmlrpc login_to_simulator and authentication internally.
QUrl GetServerEntryPointUrl() const;
//! Get created WorldStream: void -> WorldStreamInterface when implemented
void GetWorldStream() const;
//! Set login credentials
void SetCredentials(ProtocolUtilities::LoginCredentialsInterface *newCredentials);
//! Set server entry point url
void SetServerEntryPointUrl(const QUrl &newUrl);
private:
ProtocolUtilities::TaigaCredentials *credentials_;
QUrl serverEntryPointUrl_;
//! Pointer to framework
Foundation::Framework *framework_;
//! Pointer to the opensim network interface.
boost::weak_ptr<TaigaProtocol::ProtocolModuleTaiga> networkTaiga_;
};
}
#endif // incl_ProtocolUtilities_TaigaWorldSession_h | [
"jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3"
] | [
[
[
1,
66
]
]
] |
4b8357dd1fa48ed04a8ec7350bdbc0b407ecd53f | 3201bc35622102fe99b50e5f7d1351ad0d89b2f2 | /design/repository/models/gip/c_execution_model_class.h | 060c377d6d62ba7471d64d69c3c4e782fe3d3178 | [] | no_license | embisi-github/embisi_gip | 1f7e8ce334ae9611f52a2cd6e536ef71fb00cec4 | dd6dfe8667b28f03dba2ac605d67916cb4483005 | refs/heads/master | 2021-01-10T12:33:55.917299 | 2006-11-27T09:43:39 | 2006-11-27T09:43:39 | 48,285,426 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,236 | h | /*a Copyright Gavin J Stark and John Croft, 2003
*/
/*a Wrapper
*/
#ifndef C_EXECUTION_MODEL_CLASS
#define C_EXECUTION_MODEL_CLASS
/*a Includes
*/
/*a Defines
*/
#define MAX_TRACING (8)
/*a Types
*/
/*t gip_flag_mask_*
*/
enum
{
gip_flag_mask_z = 1,
gip_flag_mask_n = 2,
gip_flag_mask_c = 4,
gip_flag_mask_v = 8,
gip_flag_mask_cp= 16,
};
/*t t_log_data
*/
typedef struct t_log_data
{
unsigned int address;
unsigned int opcode;
int conditional;
int condition_passed;
int sequential;
int branch;
int rfr;
int rfw;
int sign;
} t_log_data;
/*t c_execution_model_class
*/
class c_execution_model_class
{
public:
/*b Constructors/destructors methods
*/
c_execution_model_class::c_execution_model_class( class c_memory_model *memory_model );
virtual c_execution_model_class::~c_execution_model_class() = 0;
/*b Execution methods
*/
virtual int c_execution_model_class::step( int *reason, int requested_count ) = 0;
/*b Code loading methods
*/
virtual void c_execution_model_class::load_code( FILE *f, unsigned int base_address ) = 0;
virtual void c_execution_model_class::load_code_binary( FILE *f, unsigned int base_address ) = 0;
virtual void c_execution_model_class::load_symbol_table( char *filename ) = 0;
/*b Debug methods
*/
virtual void c_execution_model_class::set_register( int r, unsigned int value ) = 0;
virtual unsigned int c_execution_model_class::get_register( int r ) = 0;
virtual void c_execution_model_class::set_flags( int value, int mask ) = 0;
virtual int c_execution_model_class::get_flags( void ) = 0;
virtual int c_execution_model_class::set_breakpoint( unsigned int address ) = 0;
virtual int c_execution_model_class::unset_breakpoint( unsigned int address ) = 0;
virtual void c_execution_model_class::halt_cpu( void ) = 0;
virtual void c_execution_model_class::debug( int mask ) = 0;
/*a Trace methods
*/
void c_execution_model_class::trace_output( char *format, ... );
int c_execution_model_class::trace_set_file( char *filename );
int c_execution_model_class::trace_region( int region, unsigned int start_address, unsigned int end_address );
int c_execution_model_class::trace_region_stop( int region );
int c_execution_model_class::trace_all_stop( void );
int c_execution_model_class::trace_restart( void );
/*b Log methods
*/
void c_execution_model_class::log( char *reason, unsigned int arg );
void c_execution_model_class::log_display( FILE *f );
void c_execution_model_class::log_reset( void );
struct t_private_data *pd;
private:
int tracing_enabled; // If 0, no tracing, else tracing is performed
FILE *trace_file;
unsigned int trace_region_starts[ MAX_TRACING ]; // inclusive start address of area to trace - up to MAX_TRACING areas
unsigned int trace_region_ends[ MAX_TRACING ]; // exclusive end address of area to trace - up to MAX_TRACING areas
t_log_data log_data;
/*b Private data
*/
};
/*a External functions
*/
/*a Wrapper
*/
#endif
| [
""
] | [
[
[
1,
107
]
]
] |
7342de6ff744e660446ce8e6d1b855e76802c012 | 3533c9f37def95dcc9d6b530c59138f7570ca239 | /guCORE/include/guCORE_CDownloadsMenuForm.h | bc932b7808f714756fee5f3dcca4419436347039 | [] | 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 | 5,356 | h | /*
* 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
*/
#ifndef GU_CORE_CDOWNLOADSMENUFORM_H
#define GU_CORE_CDOWNLOADSMENUFORM_H
/*-------------------------------------------------------------------------//
// //
// INCLUDES //
// //
//-------------------------------------------------------------------------*/
#ifndef GUCEF_GUI_CFORMEX_H
#include "gucefGUI_CFormEx.h"
#define GUCEF_GUI_CFORMEX_H
#endif /* GUCEF_GUI_CFORMEX_H ? */
#ifndef GUCEF_GUI_CBUTTON_H
#include "gucefGUI_CButton.h"
#define GUCEF_GUI_CBUTTON_H
#endif /* GUCEF_GUI_CBUTTON_H ? */
#ifndef GUCEF_GUI_CTABCONTROL_H
#include "gucefGUI_CTabControl.h"
#define GUCEF_GUI_CTABCONTROL_H
#endif /* GUCEF_GUI_CTABCONTROL_H ? */
#ifndef GU_CORE_MACROS_H
#include "guCORE_macros.h"
#define GU_CORE_MACROS_H
#endif /* GU_CORE_MACROS_H ? */
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
namespace GU {
namespace CORE {
/*-------------------------------------------------------------------------//
// //
// CLASSES //
// //
//-------------------------------------------------------------------------*/
class GU_CORE_EXPORT_CPP CDownloadsMenuForm : public GUCEF::GUI::CFormEx
{
public:
typedef enum TDownloadsTab
{
DOWNLOADSTAB_AVAILABLE = 1,
DOWNLOADSTAB_TRANSFERS ,
DOWNLOADSTAB_DOWNLOADED ,
DOWNLOADSTAB_NONE = 0
};
CDownloadsMenuForm( void );
virtual ~CDownloadsMenuForm();
GUCEF::GUI::CButton* GetMenuButton( void );
GUCEF::GUI::CButton* GetSettingsButton( void );
GUCEF::GUI::CButton* GetRefreshButton( void );
GUCEF::GUI::CTabControl* GetDownloadsTabControl( void );
GUCEF::GUI::CTabContentPane* GetAllAvailableDownloadsTabPane( void );
GUCEF::GUI::CTabContentPane* GetTransfersTabPane( void );
GUCEF::GUI::CTabContentPane* GetDownloadedTabPane( void );
TDownloadsTab GetActiveTab( void ) const;
protected:
virtual void OnPreLayoutLoad( void );
virtual void OnPostLayoutLoad( void );
private:
CDownloadsMenuForm( const CDownloadsMenuForm& src );
CDownloadsMenuForm& operator=( const CDownloadsMenuForm& other );
private:
GUCEF::GUI::CButton* m_menuButton;
GUCEF::GUI::CButton* m_settingsButton;
GUCEF::GUI::CButton* m_refreshButton;
GUCEF::GUI::CTabControl* m_downloadsTabControl;
GUCEF::GUI::CTabContentPane* m_allAvailableDownloadsTabPane;
GUCEF::GUI::CTabContentPane* m_transfersTabPane;
GUCEF::GUI::CTabContentPane* m_downloadedTabPane;
};
/*-------------------------------------------------------------------------//
// //
// NAMESPACE //
// //
//-------------------------------------------------------------------------*/
}; /* namespace CORE */
}; /* namespace GU */
/*-------------------------------------------------------------------------*/
#endif /* GU_CORE_CDOWNLOADSMENUFORM_H ? */
/*-------------------------------------------------------------------------//
// //
// Info & Changes //
// //
//-------------------------------------------------------------------------//
- 14-01-2007 :
- Dinand: Initial implementation
---------------------------------------------------------------------------*/
| [
"[email protected]"
] | [
[
[
1,
141
]
]
] |
4fd8c56eb6d4d075c135f3417765c29f2cf7eac8 | 17ebdb307b9e503a9df5c86db264e060695f9cb9 | /include/QjtMouseGesture.h | 0d5aeb67e0f3c4a381de3767b67e3da96dbbb8e0 | [] | no_license | e8johan/mouse-gesture-recognizer | a5224f0353f651489cafb70cdb80f828449d6275 | 983537fc7ddbaf5e04afffc300b104b4805593f2 | refs/heads/master | 2020-03-27T05:04:47.602603 | 2009-05-06T13:08:08 | 2009-05-06T13:08:08 | 32,892,845 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,442 | h | /*
* This file is part of the mouse gesture package.
* Copyright (C) 2006 Johan Thelin <[email protected]>
* 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.
* - The names of its contributors may be used to endorse
* or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef QJTMOUSEGESTURE_H
#define QJTMOUSEGESTURE_H
#include <QObject>
#include <QList>
#include "mousegesturerecognizer.h"
class GestureCallbackToSignal;
/*
* A Direction can be any of the following:
*
* Up
* Down
* Left
* Right
* AnyHorizontal (Left or Right)
* AnyVertical (Up or Down)
* UpLeft (diagnonal)
* UpRight (diagnonal)
* DownLeft (diagnonal)
* DownRight (diagnonal)
*
* In addition to these, the NoMatch enum is
* available. A gesture holding only the NoMatch
* enum is gestured when no other gesture can be
* matched to the mouse gesture performed.
*/
typedef Gesture::Direction Direction;
using Gesture::Up;
using Gesture::Down;
using Gesture::Left;
using Gesture::Right;
using Gesture::AnyHorizontal;
using Gesture::AnyVertical;
using Gesture::UpLeft;
using Gesture::UpRight;
using Gesture::DownLeft;
using Gesture::DownRight;
using Gesture::NoMatch;
/*
* A list of Directions
*/
typedef QList<Direction> DirectionList;
/*
* A mouse gesture is a list of Directions that
* trigger the gestured signal. Create instances
* and add to a QjtMouseGestureFilter object.
*/
class QjtMouseGesture : public QObject
{
Q_OBJECT
public:
QjtMouseGesture( const DirectionList &directions, QObject *parent = 0 );
~QjtMouseGesture();
const DirectionList directions() const;
signals:
void gestured();
private:
friend class GestureCallbackToSignal;
/*
* Emits the gestured signal.
*
* Required to connect this to the toolkit
* independent recognizer in a tidy way.
*/
void emitGestured();
DirectionList m_directions;
};
#endif // QJTMOUSEGESTURE_H
| [
"e8johan@2c227689-8b1f-0410-847e-0d0e51d0f70e"
] | [
[
[
1,
117
]
]
] |
510e61f08abd253b5326cc36537e341e99471262 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/_Common/ObjSerializeOpt.cpp | ad86c50ac1cb1abc1b1124ce16bc8c7c97a4ef0c | [] | 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 | 20,120 | cpp | #include "stdafx.h"
# if defined(__WORLDSERVER) || defined(__CLIENT)
#include "mover.h"
#include "defineItem.h"
# else // __WORLDSERVER, __CLIENT
#include "..\_network\objects\obj.h"
# endif // __WORLDSERVER, __CLIENT
#ifndef GETBLOCK
#define GETBLOCK( ar, lpBuf, nBufSize ) \
int nBufSize; \
LPBYTE lpBuf = ar.GetBuffer( &nBufSize );
#endif // __GETBLOCK
#if __VER >= 13 // __HONORABLE_TITLE
#include "honor.h"
#endif // __HONORABLE_TITLE
void CObj::Serialize( CAr & ar ) // 21
{
if( ar.IsStoring() )
{
ar << (u_char)m_dwType;
// mirchang_100513 type cast fix
ar << (u_short)m_dwIndex;
//ar << m_dwIndex;
// mirchang_100513 type cast fix
ar << (u_short)( m_vScale.x * 100.0f );
ar << m_vPos;
ar << (short)( m_fAngle * 10.0f );
}
else
{
u_short u2;
short i2;
m_dwType = m_dwIndex = 0;
ar >> (u_char&)m_dwType; // m_dwType
// mirchang_100513 type cast fix
ar >> u2; // m_dwIndex
m_dwIndex = (DWORD)u2;
//ar >> m_dwIndex;
// mirchang_100513 type cast fix
ar >> u2; // m_vScale.x * 100.0f
m_vScale.x = m_vScale.y = m_vScale.z = (float)u2 / 100.0f;
ar >> m_vPos; // m_vPos
ar >> i2; // m_fAngle * 10.0f
m_fAngle = (float)i2 / 10.0f;
#if defined(__WORLDSERVER) || defined(__CLIENT)
SetAngle( m_fAngle );
#endif
#ifdef __WORLDSERVER
m_vLink = m_vPos;
#endif // __WORLDSERVER
}
}
#if defined(__WORLDSERVER) || defined(__CLIENT)
// 장어구이, 신속의 두루마리 등의 예외처리
void CMover::OnApplySM()
{
ItemProp* aItemprop;
int nAdjParamVal;
if( m_dwSMTime[SM_MAX_HP] > 0 )
{
aItemprop = prj.GetItemProp( II_CHR_FOO_COO_BULLHAMS );
nAdjParamVal = aItemprop->nAdjParamVal2;
SetDestParam( aItemprop->dwDestParam1, nAdjParamVal, NULL_CHGPARAM, 1 ); // fixed by jeff
}
if( m_dwSMTime[SM_MAX_HP50] > 0 )
{
aItemprop = prj.GetItemProp( II_CHR_FOO_COO_GRILLEDEEL );
nAdjParamVal = m_nPlusMaxHitPoint;
SetDestParam( aItemprop->dwDestParam1, nAdjParamVal, NULL_CHGPARAM, 1 ); // fixed by jeff
}
if( m_dwSMTime[SM_VELOCIJUMP] > 0 )
{
aItemprop = prj.GetItemProp( g_AddSMMode.dwSMItemID[SM_VELOCIJUMP] );
if( aItemprop )
{
if( aItemprop->dwDestParam1 != -1 )
SetDestParam( aItemprop->dwDestParam1, aItemprop->nAdjParamVal1, NULL_CHGPARAM );
if( aItemprop->dwDestParam2 != -1 )
SetDestParam( aItemprop->dwDestParam2, aItemprop->nAdjParamVal2, NULL_CHGPARAM );
}
}
}
#endif // __WORLDSERVER __CLIENT
void CMover::Serialize( CAr & ar )
{
CCtrl::Serialize( ar ); // 25
DWORD dwGold;
if( ar.IsStoring() ) // STORING
{
ar << (u_short)m_dwMotion;
ar << (u_char)m_bPlayer;
ar << m_nHitPoint;
ar << m_pActMover->GetState();
ar << m_pActMover->GetStateFlag();
ar << (u_char)m_dwBelligerence;
#if __VER >= 15 // __PETVIS
ar << m_dwMoverSfxId;
#endif // __PETVIS
if( m_bPlayer ) // PLAYER
{
ar.WriteString( m_szName );
ar << GetSex();
ar << (u_char)m_dwSkinSet;
ar << (u_char)m_dwHairMesh;
ar << m_dwHairColor;
ar << (u_char)m_dwHeadMesh;
ar << m_idPlayer;
ar << (u_char)m_nJob;
ar << (u_short)m_nStr;
ar << (u_short)m_nSta;
ar << (u_short)m_nDex;
ar << (u_short)m_nInt;
ar << (u_short)m_nLevel;
ar << m_nFuel;
ar << m_tmAccFuel;
if( m_idGuild > 0 )
{
ar << (u_char)1;
ar << m_idGuild;
ar << m_idWar;
}
else
{
ar << (u_char)0;
}
ar << m_idGuildCloak;
if( m_idparty > 0 )
{
ar << (u_char)1;
ar << m_idparty;
ar << m_idDuelParty;
}
else
{
ar << (u_char)0;
}
ar << (char)m_dwAuthorization;
ar << m_dwMode;
ar << m_dwStateMode;
#ifdef __WORLDSERVER
CItemElem* pItemElem = m_Inventory.GetAtId( m_dwUseItemId );
if( pItemElem )
ar << pItemElem->GetProp()->dwID;
else
ar << (OBJID)0;
#else // __WORLDSERVER
ar << m_dwUseItemId;
#endif // __WORLDSERVER
#if __VER >= 8 // __S8_PK
if( m_dwPKTime > 0 )
#ifdef __WORLDSERVER
ar << ( m_dwPKTime - GetTickCount() );
#else // __WORLDSERVER
ar << m_dwPKTime;
#endif // __WORLDSERVER
else
ar << m_dwPKTime;
ar << m_nPKValue;
ar << m_dwPKPropensity;
ar << m_dwPKExp;
#else // __VER >= 8 // __S8_PK
ar << (u_short)m_nNumKill;
ar << m_nSlaughter;
#endif // __VER >= 8 // __S8_PK
ar << m_nFame;
ar << (u_char)m_nDuel;
#if __VER >= 13 // __HONORABLE_TITLE // 달인
ar << m_nHonor; // 달인선택
#endif // __HONORABLE_TITLE // 달인
{
int i;
for( i = 0; i < MAX_HUMAN_PARTS; i ++ )
{
ar << m_aEquipInfo[i].nOption;
}
}
ar << m_nGuildCombatState;
int j; for( j = 0 ; j < SM_MAX ; ++j )
ar << m_dwSMTime[j];
if( CObj::GetMethod() == METHOD_NONE )
{
ar << (u_short)m_nManaPoint;
ar << (u_short)m_nFatiguePoint;
#if __VER >= 12 // __MOD_TUTORIAL
ar << m_nTutorialState;
#else // __MOD_TUTORIAL
ar << (u_short)m_nFlightLv;
#endif // __MOD_TUTORIAL
ar << m_nFxp;
dwGold = GetGold();
ar << dwGold;
ar << m_nExp1;
ar << m_nSkillLevel;
ar << m_nSkillPoint;
ar << m_nDeathExp;
ar << m_nDeathLevel;
DWORD dwJobLv[MAX_JOB] = {0, };
ar.Write( (void*)dwJobLv, sizeof(DWORD) * MAX_JOB );
ar << m_idMarkingWorld;
ar << m_vMarkingPos;
ar << m_nQuestSize;
ar.Write( m_aQuest, sizeof(QUEST) * m_nQuestSize );
ar << m_nCompleteQuestSize;
ar.Write( m_aCompleteQuest, sizeof(WORD) * m_nCompleteQuestSize );
#if __VER >= 15 // __IMPROVE_QUEST_INTERFACE
ar << m_nCheckedQuestSize;
ar.Write( m_aCheckedQuest, sizeof(WORD) * m_nCheckedQuestSize );
#endif // __IMPROVE_QUEST_INTERFACE
ar << m_idMurderer;
ar << (short)m_nRemainGP;
ar << (short)0;
{
int i; for( i = 0; i < MAX_HUMAN_PARTS; i++ )
ar << m_aEquipInfo[i].dwId;
}
ar.Write( (void*)m_aJobSkill, sizeof(SKILL) * ( MAX_SKILL_JOB ) );
ar << (BYTE)m_nCheerPoint << m_dwTickCheer - GetTickCount();
ar << m_nSlot;
int k;
for( k = 0 ; k < 3 ; ++k )
ar << m_dwGoldBank[k];
for( k = 0 ; k < 3 ; ++k )
ar << m_idPlayerBank[k];
ar << m_nPlusMaxHitPoint;
ar << m_nAttackResistLeft;
ar << m_nAttackResistRight;
ar << m_nDefenseResist;
#if __VER >= 8 // __CSC_VER8_5
ar << m_nAngelExp;
ar << m_nAngelLevel;
#endif // __CSC_VER8_5
m_Inventory.Serialize( ar );
for( k = 0 ; k < 3 ; ++k )
m_Bank[k].Serialize( ar );
#if __VER >= 9 // __PET_0410
ar << GetPetId(); // 소환 중인 펫 인벤토리 위치
#endif // __PET_0410
#if __VER >= 11 // __SYS_POCKET
m_Pocket.Serialize( ar );
#endif // __SYS_POCKET
#ifdef __JEFF_9_20
ar << m_dwMute;
#endif // __JEFF_9_20
#if __VER >= 13 // __HONORABLE_TITLE // 달인
int i; for( i = 0 ; i < MAX_HONOR_TITLE ; ++i )
{
ar << m_aHonorTitle[i];
}
#endif // __HONORABLE_TITLE // 달인
#if __VER >= 15 // __CAMPUS
ar << m_idCampus;
ar << m_nCampusPoint;
#endif // __CAMPUS
}
else if( CObj::GetMethod() == METHOD_EXCLUDE_ITEM )
{
# if defined (__WORLDSERVER) || defined(__CLIENT)
ar.WriteString( m_vtInfo.GetTitle() );
# endif
u_char uSize = 0;
u_long uOffset = ar.GetOffset();
ar << uSize;
for( u_char uParts = 0; uParts < MAX_HUMAN_PARTS; uParts++ )
{
CItemElem* pItemElem = m_Inventory.GetEquip( uParts );
if( pItemElem )
{
uSize++;
ar << uParts;
ar << (u_short)pItemElem->m_dwItemId;
ar << pItemElem->m_byFlag;
}
}
GETBLOCK( ar, pBlock, nBlockSize );
*(UNALIGNED u_char*)( pBlock + uOffset ) = uSize;
#if __VER >= 9 // __PET_0410
DWORD dwPetId = NULL_ID;
#ifdef __PET_1024
char* pszPetName = "";
#endif // __PET_1024
CItemElem* pItemElem = GetPetItem();
if( pItemElem )
{
dwPetId = MAKELONG( (WORD)pItemElem->m_pPet->GetIndex(), (WORD)pItemElem->m_pPet->GetLevel() );
#ifdef __PET_1024
pszPetName = const_cast<char*>( pItemElem->m_pPet->GetName() );
#endif // __PET_1024
}
ar << dwPetId;
#ifdef __PET_1024
ar.WriteString( pszPetName );
#endif // __PET_1024
#endif // __PET_0410
}
}
else // NPC
{
ar << (u_char)m_dwHairMesh << m_dwHairColor << (u_char)m_dwHeadMesh;
ar.WriteString( m_szCharacterKey );
u_char uSize = 0;
u_long uOffset = ar.GetOffset();
ar << uSize;
if( IsEquipableNPC() )
{
CItemElem* pItemElem;
for( u_char uParts = 0; uParts < MAX_HUMAN_PARTS; uParts++ )
{
pItemElem = m_Inventory.GetEquip( uParts );
if( pItemElem )
{
uSize++;
ar << uParts;
ar << (u_short)pItemElem->m_dwItemId;
}
}
}
GETBLOCK( ar, pBlock, nBlockSize );
*(UNALIGNED u_char*)( pBlock + uOffset ) = uSize;
ar << (u_char)m_bActiveAttack;
ar << (u_char)m_nMovePattern;
ar << (u_char)m_nMoveEvent;
ar << m_nMoveEventCnt;
#if __VER >= 9 //__AI_0509
ar << m_fSpeedFactor;
#endif // __AI_0509
}
#ifdef __BUFF_1107
m_buffs.Serialize( ar );
#else // __BUFF_1107
m_SkillState.Serialize( ar );
#endif // __BUFF_1107
}
else // LOADING
{
m_dwMotion = 0;
u_short nMotion;
ar >> nMotion; // m_dwMotion
#if defined(__WORLDSERVER) || defined(__CLIENT)
m_dwMotion = (DWORD)nMotion; // 성별도 정해지지 않는 상태에서는 SetMotion호출하지 않는다.
#else // defined(__WORLDSERVER) || defined(__CLIENT)
m_dwMotion = (DWORD)nMotion;
#endif
m_bPlayer =
m_dwBelligerence =
m_idGuild =
m_idWar =
m_idparty =
m_idDuelParty =
m_nDuel =
m_dwRideItemIdx = 0;
ClearEquipInfo();
ar >> (u_char&)m_bPlayer;
#ifdef __SKILL_0205
SKILL aJobSkill[MAX_SKILL_JOB];
memcpy( aJobSkill, m_aJobSkill, sizeof(aJobSkill) );
#endif // __SKILL_0205
InitProp();
m_nHitPoint = 0;
ar >> m_nHitPoint;
DWORD dw1, dw2;
ar >> dw1;
ar >> dw2;
m_pActMover->ClearStateFlag();
m_pActMover->AddStateFlag( dw2 );
m_pActMover->__ForceSetState( dw1 );
ar >> (u_char&)m_dwBelligerence;
#if __VER >= 15 // __PETVIS
ar >> m_dwMoverSfxId;
#endif // __PETVIS
if( m_bPlayer ) // PLAYER
{
m_dwSkinSet =
m_dwHairMesh =
m_dwHeadMesh =
m_idPlayer =
m_nJob =
m_nStr =
m_nSta =
m_nDex =
m_nInt =
m_nLevel =
m_dwAuthorization =
#if __VER < 8 // __S8_PK
m_nNumKill =
#endif // __VER < 8 // __S8_PK
0;
BYTE bySex;
ar.ReadString( m_szName, 32 );
ar >> bySex;
SetSex( bySex );
ar >> (u_char&)m_dwSkinSet;
ar >> (u_char&)m_dwHairMesh;
ar >> m_dwHairColor;
ar >> (u_char&)m_dwHeadMesh;
# if defined (__WORLDSERVER) || defined(__CLIENT)
SetHairColor( m_dwHairColor );
# endif // __WORLDSERVER //__CLIENT
ar >> m_idPlayer;
ar >> (u_char&)m_nJob;
ar >> (u_short&)m_nStr;
ar >> (u_short&)m_nSta;
ar >> (u_short&)m_nDex;
ar >> (u_short&)m_nInt;
ar >> (u_short&)m_nLevel;
ar >> m_nFuel;
ar >> m_tmAccFuel;
u_char u1;
ar >> u1;
if( u1 == 1 )
{
ar >> m_idGuild;
ar >> m_idWar;
}
ar >> m_idGuildCloak;
ar >> u1;
if( u1 == 1 )
{
ar >> m_idparty;
ar >> m_idDuelParty;
}
ar >> (char&)m_dwAuthorization;
ar >> m_dwMode;
ar >> m_dwStateMode;
#ifdef __WORLDSERVER
OBJID dwItemTem;
ar >> dwItemTem;
#else // __WORLDSERVER
ar >> m_dwUseItemId;
#endif // __WORLDSERVER
#if __VER >= 8 // __S8_PK
ar >> m_dwPKTime;
#ifdef __WORLDSERVER
if( m_dwPKTime > 0 )
m_dwPKTime = GetTickCount() + m_dwPKTime;
#endif // __WORLDSERVER
ar >> m_nPKValue;
ar >> m_dwPKPropensity;
ar >> m_dwPKExp;
#else // __VER >= 8 // __S8_PK
ar >> (u_short&)m_nNumKill;
ar >> m_nSlaughter;
#endif // __VER >= 8 // __S8_PK
ar >> m_nFame;
ar >> (u_char&)m_nDuel;
#if __VER >= 13 // __HONORABLE_TITLE // 달인
int nTemp = -1;
ar >> nTemp;
#ifdef __CLIENT
if(m_nHonor != nTemp)// 달인선택
{
m_nHonor = nTemp;
SetTitle(CTitleManager::Instance()->GetTitle(m_nHonor));
}
#else // __CLIENT
m_nHonor = nTemp;
#endif // __CLIENT
#endif // __HONORABLE_TITLE // 달인
{
int i; for( i = 0; i < MAX_HUMAN_PARTS; i ++ )
{
ar >> m_aEquipInfo[i].nOption;
}
}
ar >> m_nGuildCombatState;
int j; for( j = 0 ; j < SM_MAX ; ++j )
ar >> m_dwSMTime[j];
// 장어구이, 신속의 두루마리 등의 예외처리는 m_nPlusMaxHitPoint등이 세트되고 OnApplySM() 실행한다.
if( CObj::GetMethod() == METHOD_NONE )
{
m_nManaPoint = 0;
m_nFatiguePoint = 0;
#if __VER < 12 // __MOD_TUTORIAL
m_nFlightLv = 0;
#endif // __MOD_TUTORIAL
m_nRemainGP = 0;
ar >> (u_short&)m_nManaPoint;
ar >> (u_short&)m_nFatiguePoint;
#if __VER >= 12 // __MOD_TUTORIAL
ar >> m_nTutorialState;
#ifdef __CLIENT
g_Option.m_nTutorialLv = m_nTutorialState;
#endif // __CLIENT
#else // __MOD_TUTORIAL
ar >> (u_short&)m_nFlightLv;
#endif // __MOD_TUTORIAL
ar >> m_nFxp;
ar >> dwGold;
SetGold( dwGold );
ar >> m_nExp1;
ar >> m_nSkillLevel;
ar >> m_nSkillPoint;
ar >> m_nDeathExp;
ar >> m_nDeathLevel;
DWORD dwJobLv[MAX_JOB]; // 사용하지 않음
ar.Read( (void*)dwJobLv, sizeof(DWORD) * MAX_JOB );
ar >> m_idMarkingWorld;
ar >> m_vMarkingPos;
ar >> m_nQuestSize;
ar.Read( m_aQuest, sizeof(QUEST) * m_nQuestSize );
ar >> m_nCompleteQuestSize;
ar.Read( m_aCompleteQuest, sizeof(WORD) * m_nCompleteQuestSize );
#if __VER >= 15 // __IMPROVE_QUEST_INTERFACE
ar >> m_nCheckedQuestSize;
ar.Read( m_aCheckedQuest, sizeof(WORD) * m_nCheckedQuestSize );
#endif // __IMPROVE_QUEST_INTERFACE
ar >> m_idMurderer;
short n1, n2; // n2는 사용하지 않는다.
ar >> n1 >> n2;
m_nRemainGP = n1;
{
int i; for( i = 0; i < MAX_HUMAN_PARTS; i++ )
ar >> m_aEquipInfo[i].dwId;
}
#ifdef __SKILL_0205
ar.Read( (void*)m_aJobSkill, sizeof(SKILL) * ( MAX_SKILL_JOB ) );
int i; for( i = 0 ; i < MAX_SKILL_JOB; i++)
m_abUpdateSkill[i] = (BOOL)( memcmp( &m_aJobSkill[i], &aJobSkill[i], sizeof(SKILL) ) != 0 );
#else // __SKILL_0205
ar.Read( (void*)m_aJobSkill, sizeof(SKILL) * ( MAX_SKILL_JOB ) );
#endif // __SKILL_0205
m_nCheerPoint = 0;
ar >> (BYTE&)m_nCheerPoint >> m_dwTickCheer;
m_dwTickCheer += GetTickCount();
ar >> m_nSlot;
int k;
for( k = 0 ; k < 3 ; ++k )
ar >> m_dwGoldBank[k];
for( k = 0 ; k < 3 ; ++k )
ar >> m_idPlayerBank[k];
ar >> m_nPlusMaxHitPoint;
ar >> m_nAttackResistLeft;
ar >> m_nAttackResistRight;
ar >> m_nDefenseResist;
#if __VER >= 8 //__CSC_VER8_5
ar >> m_nAngelExp;
ar >> m_nAngelLevel;
#endif // __CSC_VER8_5
m_Inventory.Serialize( ar );
for( k = 0 ; k < 3 ; ++k )
m_Bank[k].Serialize( ar );
CItemElem* pItemElem = m_Inventory.GetEquip( PARTS_RIDE );
if( pItemElem )
m_dwRideItemIdx = pItemElem->m_dwItemId;
#if __VER >= 9 // __PET_0410
DWORD dwPetId;
ar >> dwPetId;
SetPetId( dwPetId );
#ifdef __PET_1024
#ifdef __CLIENT
CPet* pPet = GetPet();
if( pPet )
m_pet.SetName( const_cast<char*>( pPet->GetName() ) );
#endif // __CLIENT
#endif // __PET_1024
#endif // __PET_0410
#if __VER >= 11 // __SYS_POCKET
m_Pocket.Serialize( ar );
#endif // __SYS_POCKET
#ifdef __JEFF_9_20
ar >> m_dwMute;
#endif // __JEFF_9_20
#if __VER >= 13 // __HONORABLE_TITLE // 달인
#ifdef __CLIENT
CTitleManager::Instance()->InitEarned();
#endif // __CLIENT
for( int l = 0 ; l < MAX_HONOR_TITLE ; ++l )
{
ar >> m_aHonorTitle[l];
#ifdef __CLIENT
int nNeed = CTitleManager::Instance()->GetNeedCount(l, -1);
if(m_aHonorTitle[l] >= nNeed && nNeed > 0)
{
CTitleManager::Instance()->AddEarned(l);
}
else
{
// 획득된 타이틀이지만 요구사항을 충족못하게 될때
if(CTitleManager::Instance()->IsEarned(l))
{
CTitleManager::Instance()->RemoveEarned(l);
}
}
#endif // __CLIENT
}
#endif // __HONORABLE_TITLE // 달인
#if __VER >= 15 // __CAMPUS
ar >> m_idCampus;
ar >> m_nCampusPoint;
#endif // __CAMPUS
}
else if( CObj::GetMethod() == METHOD_EXCLUDE_ITEM )
{
#if defined (__WORLDSERVER) || defined(__CLIENT)
char szPVendor[MAX_VENDORNAME] = {0, };
ar.ReadString( szPVendor, MAX_VENDORNAME );
m_vtInfo.SetTitle( szPVendor );
#endif
int i; for( i = 0; i < MAX_HUMAN_PARTS; i++ )
m_aEquipInfo[i].dwId = NULL_ID;
u_char uSize;
ar >> uSize;
u_char uParts;
u_short u2;
for( u_char uCount = 0; uCount < uSize; uCount++ )
{
ar >> uParts;
ar >> u2;
m_aEquipInfo[uParts].dwId = (DWORD)u2;
ar >> m_aEquipInfo[uParts].byFlag;
}
if( m_aEquipInfo[PARTS_RIDE].dwId != NULL_ID )
m_dwRideItemIdx = m_aEquipInfo[PARTS_RIDE].dwId;
#if __VER >= 9 // __PET_0410
DWORD dwPetId;
ar >> dwPetId;
SetPetId( dwPetId );
#ifdef __PET_1024
char szPetName[MAX_PET_NAME] = { 0,};
ar.ReadString( szPetName, MAX_PET_NAME );
#ifdef __CLIENT
m_pet.SetName( szPetName );
#endif // __CLIENT
#endif // __PET_1024
#endif // __PET_0410
}
#if defined(__WORLDSERVER) || defined(__CLIENT)
if( m_dwRideItemIdx )
{
ItemProp *pItemProp = prj.GetItemProp( m_dwRideItemIdx );
if( pItemProp && m_nFuel == -1 )
m_nFuel = (int)( pItemProp->dwFFuelReMax * 0.2f );
}
OnApplySM();
#endif // __WORLDSERVER // __CLIENT
}
else // NPC
{
ar >> (u_char&)m_dwHairMesh >> m_dwHairColor >> (u_char&)m_dwHeadMesh;
ar.ReadString( m_szCharacterKey, 32 );
#if defined (__WORLDSERVER) || defined(__CLIENT)
SetHairColor( m_dwHairColor );
#endif // __WORLDSERVER //__CLIENT
{
int i; for( i = 0; i < MAX_HUMAN_PARTS; i++ )
m_aEquipInfo[i].dwId = NULL_ID;
}
u_char uSize;
ar >> uSize;
if( IsEquipableNPC() )
{
u_char uParts;
u_short u2;
for( u_char uCount = 0; uCount < uSize; uCount++ )
{
ar >> uParts;
ar >> u2;
m_aEquipInfo[uParts].dwId = (DWORD)u2;
/*
#ifdef __PERF_0229
if( GetIndex() == 11 || GetIndex() == 12 )
{
int nAttr = 0; //xRandom( 0, 5 );
int nAttrLevel = 0;
//if( nAttr > 0 )
// nAttrLevel= xRandom( 8, 10 );
int nLevel = 0;
//if( nAttr < 3 )
nLevel = xRandom( 9, 10 );
int nOption = nLevel;
nOption |= ( nAttrLevel << 24 );
nOption |= (nAttr << 16 );
m_aEquipInfo[uParts].nOption = nOption;
}
#endif // __PERF_0229
*/
}
}
m_bActiveAttack =
m_nMovePattern =
m_nMoveEvent =
0;
ar >> (u_char&)m_bActiveAttack;
ar >> (u_char&)m_nMovePattern;
ar >> (u_char&)m_nMoveEvent;
ar >> m_nMoveEventCnt;
#ifdef __CLIENT
if( *m_szCharacterKey )
{
LPCHARACTER pCharacter = prj.GetCharacter( m_szCharacterKey );
if( pCharacter )
{
_tcscpy( m_szName, pCharacter->m_strName );
AllocShopInventory( pCharacter );
}
}
#endif // __CLIENT
#if __VER >= 9 //__AI_0509
ar >> m_fSpeedFactor;
#endif // __AI_0509
}
#ifdef __BUFF_1107
m_buffs.Serialize( ar );
#else // __BUFF_1107
m_SkillState.Serialize( ar );
#endif // __BUFF_1107
#ifdef __CLIENT
InitInterpolation();
#endif // __CLIENT
} // LOADING
#ifdef __CLIENT
m_fDestScale = GetScale().x;
if( m_fDestScale > 10.0f )
{
LPCTSTR szErr = Error( "SerializeOpt:%f %s", m_fDestScale, GetName() );
ADDERRORMSG( szErr );
}
#endif
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
779
]
]
] |
af12f1e49dd3777c8c5ec2d0087ac8009fd1ec21 | d6b0c51999cecf65d5be208fab74bb8a199eb0ac | /MagicCube/StateArchive.cpp | 6880981e6cd158ef1ff5c8d058df14ecceef2b06 | [] | no_license | k-l-lambda/klsmagiccube | 5076e6be0a729ff8741d960e44e5fb061c473b08 | 1cfb166f537573b7e64d902085075ff0e99b9166 | refs/heads/master | 2016-09-05T22:12:35.513552 | 2011-02-10T16:17:38 | 2011-02-10T16:17:38 | 32,123,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,278 | cpp | /*
** This source file is part of K.L.'s MagicCube.
**
** Copyright (c) 2008 K.L.<[email protected]>
** This program is free software without any warranty.
*/
#include <stdexcept>
#include <iostream>
#include <assert.h>
#include <Integer.h>
#pragma comment(lib, "Integer.lib")
#include "StateArchive.h"
namespace MagicCube
{
void appendToInteger(size_t code, size_t max, integer::Integer& i)
{
i = i * max + code;
}
size_t fetchFromInteger(size_t max, integer::Integer& i)
{
size_t code = size_t((i % max).toInt());
i /= max;
return code;
}
StateArchive::StateArchive(const MagicCube& mc)
{
for(size_t i = 0; i < 8; ++ i)
{
m_CornerState[i].PositionIndex = mc.getUnitPositionStateIndex(i);
m_CornerState[i].OrientationIndex = mc.getUnitOrientationStateIndex(i);
}
for(size_t i = 0; i < 12; ++ i)
{
m_EdgeState[i].PositionIndex = mc.getUnitPositionStateIndex(8 + i);
m_EdgeState[i].OrientationIndex = mc.getUnitOrientationStateIndex(8 + i);
}
m_SerializationCode = generateSerializationCode(*this);
}
StateArchive::StateArchive(const std::string& code)
: m_SerializationCode(code)
{
integer::Integer ii(code, 16);
for(size_t i = 0; i < 12; ++ i)
{
m_EdgeState[11 - i].OrientationIndex = fetchFromInteger(2, ii);
m_EdgeState[11 - i].PositionIndex = fetchFromInteger(12, ii);
}
for(size_t i = 0; i < 8; ++ i)
{
m_CornerState[7 - i].OrientationIndex = fetchFromInteger(3, ii);
m_CornerState[7 - i].PositionIndex = fetchFromInteger(8, ii);
}
assert(integer::Integer(generateSerializationCode(*this), 16) == integer::Integer(code, 16));
}
bool StateArchive::valid() const
{
return MagicCube(*this).physicalValid();
}
std::string StateArchive::generateSerializationCode(const StateArchive& sa)
{
integer::Integer ii;
for(size_t i = 0; i < 8; ++ i)
{
appendToInteger(sa.m_CornerState[i].PositionIndex, 8, ii);
appendToInteger(sa.m_CornerState[i].OrientationIndex, 3, ii);
}
for(size_t i = 0; i < 12; ++ i)
{
appendToInteger(sa.m_EdgeState[i].PositionIndex, 12, ii);
appendToInteger(sa.m_EdgeState[i].OrientationIndex, 2, ii);
}
return ii.print16();
}
}
| [
"[email protected]"
] | [
[
[
1,
96
]
]
] |
9ed3cde57b31bc1781851fe4476eca4508c35f8b | 668dc83d4bc041d522e35b0c783c3e073fcc0bd2 | /fbide-vs/Sdk/Registry.h | adcda320b22457308b71d4e991f16d5a99019a90 | [] | no_license | albeva/fbide-old-svn | 4add934982ce1ce95960c9b3859aeaf22477f10b | bde1e72e7e182fabc89452738f7655e3307296f4 | refs/heads/master | 2021-01-13T10:22:25.921182 | 2009-11-19T16:50:48 | 2009-11-19T16:50:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,020 | h | /*
* This file is part of FBIde project
*
* FBIde 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.
*
* FBIde 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 FBIde. If not, see <http://www.gnu.org/licenses/>.
*
* Author: Albert Varaksin <[email protected]>
* Copyright (C) The FBIde development team
*/
#pragma once
namespace fbi
{
/**
* For Registry use unordered_map
* for a simple key - value pairs
* use wxString and Variant
*/
class Registry : public VariantHashMap, public NonCopyable {};
}
| [
"vongodric@957c6b5c-1c3a-0410-895f-c76cfc11fbc7"
] | [
[
[
1,
32
]
]
] |
1779d3c2e15bee0f7fbdd5ebfd43bf66948a18bb | 3643bb671f78a0669c8e08935476551a297ce996 | /W_Thing_Load.cpp | eb87d21479000343ac6f841896de249519b4403d | [] | no_license | mattfischer/3dportal | 44b3b9fb2331650fc406596b941f6228f37ff14b | e00f7d601138f5cf72aac35f4d15bdf230c518d9 | refs/heads/master | 2020-12-25T10:36:51.991814 | 2010-08-29T22:53:06 | 2010-08-29T22:53:06 | 65,869,788 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,377 | cpp | #include "W_Thing.h"
#include "JK_Template.h"
#include "JK_Level.h"
#include "S_SoundClass.h"
#include "R_Model.h"
#include "C_Script.h"
namespace World
{
void Thing::ProcessTemplate()
{
string s;
int i;
float height;
model = NULL;
if( thingTemplate->GetString( "model3d", s ) )
model = currentLevel.models[s];
orient = Math::Vector( 0, 0, 0 );
thingTemplate->GetVector( "orient", orient );
maxVelocity = 0;
thingTemplate->GetFloat( "maxvel", maxVelocity );
maxThrust = 0;
thingTemplate->GetFloat( "maxthrust", maxThrust );
maxRotVelocity = 0;
thingTemplate->GetFloat( "maxrotvel", maxRotVelocity );
maxRotThrust = 0;
thingTemplate->GetFloat( "maxrotthrust", maxRotThrust );
mass = 0;
thingTemplate->GetFloat( "mass", mass );
surfaceDrag = 0;
thingTemplate->GetFloat( "surfdrag", surfaceDrag );
staticDrag = 0;
thingTemplate->GetFloat( "staticdrag", staticDrag );
airDrag = 0;
thingTemplate->GetFloat( "airdrag", airDrag );
eyeOffset = Math::Vector( 0, 0, 0 );
thingTemplate->GetVector( "eyeoffset", eyeOffset );
moveSize = 0;
thingTemplate->GetFloat( "movesize", moveSize );
size = 0;
thingTemplate->GetFloat( "size", size );
move = MOVE_NONE;
thingTemplate->GetString( "move", s );
if( s == "none" ) move = MOVE_NONE;
if( s == "path" ) move = MOVE_PATH;
if( s == "physics" ) move = MOVE_PHYSICS;
thingFlags = 0;
thingTemplate->GetHex( "thingflags", thingFlags );
physicsFlags = 0;
thingTemplate->GetHex( "physflags", physicsFlags );
typeFlags = 0;
thingTemplate->GetHex( "typeflags", typeFlags );
rotVelocity = Math::Vector( 0, 0, 0 );
thingTemplate->GetVector( "angvel", rotVelocity );
height = 0;
if( thingTemplate->GetFloat( "height", height ) )
insertOffset = Math::Vector( 0, 0, height / 2 );
else if( model != NULL )
insertOffset = model->GetInsertOffset();
else
insertOffset = Math::Vector( 0, 0, 0 );
collide = 0;
thingTemplate->GetInt( "collide", collide );
jumpVelocity = 0;
thingTemplate->GetFloat( "jumpspeed", jumpVelocity );
thingTemplate->GetFrames( frames );
if( thingTemplate->GetString( "cog", s ) )
AddCogLink( currentLevel.cogScripts[s] );
if( thingTemplate->GetString( "soundclass", s ) )
soundClass = currentLevel.soundClasses[s];
else soundClass = NULL;
if( thingTemplate->GetString( "type", s ) )
{
if( s == "actor" ) type = ACTOR;
if( s == "weapon" ) type = WEAPON;
if( s == "item" ) type = ITEM;
if( s == "explosion" ) type = EXPLOSION;
if( s == "cog" ) type = COG;
if( s == "ghost" ) type = GHOST;
if( s == "corpse" ) type = CORPSE;
if( s == "player" ) type = PLAYER;
}
else type = GHOST;
velocity = Math::Vector( 0, 0, 0 );
thingTemplate->GetVector( "vel", velocity );
animClass = NULL;
if( thingTemplate->GetString( "puppet", s ) )
{
animClass = currentLevel.animClasses[s];
if(animClass->modes.size() > 0)
{
std::string filename = animClass->modes[0].submodes["stand"].key;
if(filename != "")
{
keyTrack = Jk::Key::Track( currentLevel.keyframes[filename], 0, 0 );
}
}
}
aiClass = NULL;
if( thingTemplate->GetString( "aiclass", s ) )
{
aiClass = currentLevel.aiClasses[s];
InitAi();
}
explodeTemplate = NULL;
if( thingTemplate->GetString( "explode", s ) )
{
explodeTemplate = currentLevel.templates[s];
}
sprite = NULL;
if( thingTemplate->GetString( "sprite", s ) )
{
sprite = currentLevel.sprites[s];
}
killTime = -1;
float timer;
if( thingTemplate->GetFloat( "timer", timer ) )
{
killTime = GetTickCount() + timer * 1000;
}
}
void Thing::Explode()
{
if( explodeTemplate )
{
Thing::Create( explodeTemplate, position, rotation, sector );
}
Destroy();
}
} | [
"devnull@localhost"
] | [
[
[
1,
168
]
]
] |
5736e8f0d5ba21d475561eef464b032d4ac7ec6a | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/test/src/results_reporter.cpp | 001870b6e18842febed7ab02a2f40a926b410c9c | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | 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,033 | cpp | // (C) Copyright Gennadiy Rozental 2005.
// 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/test for the library home page.
//
// File : $RCSfile: results_reporter.cpp,v $
//
// Version : $Revision: 1.2 $
//
// Description : forwarding source
// ***************************************************************************
#define BOOST_TEST_SOURCE
#include <boost/test/impl/results_reporter.ipp>
// ***************************************************************************
// Revision History :
//
// $Log: results_reporter.cpp,v $
// Revision 1.2 2005/03/22 07:18:50 rogeeff
// no message
//
// Revision 1.1 2005/02/20 08:28:34 rogeeff
// This a major update for Boost.Test framework. See release docs for complete list of fixes/updates
//
// ***************************************************************************
// EOF
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
30
]
]
] |
f4e18af42921f228f87b2c637f30ad7e04e00884 | 208475bcab65438eed5d8380f26eacd25eb58f70 | /ComuExe/ComuExeMain.cpp | 8986fe34c9c51bc033dacc9c1cd0d1708796c34a | [] | no_license | awzhang/MyWork | 83b3f0b9df5ff37330c0e976310d75593f806ec4 | 075ad5d0726c793a0c08f9158080a144e0bb5ea5 | refs/heads/master | 2021-01-18T07:57:03.219372 | 2011-07-05T02:41:55 | 2011-07-05T02:46:30 | 15,523,223 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 27,215 | cpp | #include "ComuStdAfx.h"
#if SMALL_VER == 1
#define _REENTRANT
#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <stdarg.h>
#include <assert.h>
#include <unistd.h>
#include <dirent.h>
#include <getopt.h>
#include <termios.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <asm/page.h>
#include <sys/uio.h>
#include <sys/vfs.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/poll.h>
#include <sys/time.h>
#include <sys/wait.h>
//#include <sys/mount.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <linux/fs.h>
#include <linux/fb.h>
#include <linux/rtc.h>
#include <linux/ioctl.h>
#include <linux/types.h>
#endif
#undef MSG_HEAD
#define MSG_HEAD ("ComuExe-Main ")
int _InitAll()
{
#if VEHICLE_TYPE == VEHICLE_M
g_objLightCtrl.Init();
#endif
#if VEHICLE_TYPE == VEHICLE_V8 || VEHICLE_TYPE == VEHICLE_M2
g_objLightCtrl2.Init();
#endif
#if SMALL_VER == 0
g_objGpsSrc.InitGpsAll();
#endif
g_objComAdjust.Init();
g_hst.Init();
g_hstapp.Init();
g_objDiaodu.Init();
sleep(1);
system("insmod /dvs/extdrv/hi3511_usb.ko");
if( NETWORK_TYPE==NETWORK_GSM )
{
g_objComVir.Init();
g_objPhoneGsm.InitPhone();
}
else if( NETWORK_TYPE==NETWORK_TD )
{
g_objPhoneTd.InitPhone();
}
else if( NETWORK_TYPE==NETWORK_EVDO )
{
g_objPhoneEvdo.InitPhone();
}
else if( NETWORK_TYPE==NETWORK_WCDMA )
{
g_objPhoneWcdma.InitPhone();
}
return 0;
}
int _ReleaseAll()
{
if( NETWORK_TYPE==NETWORK_GSM )
{
g_objPhoneGsm.ReleasePhone();
g_objComVir.Release();
}
else if( NETWORK_TYPE==NETWORK_TD )
{
g_objPhoneTd.ReleasePhone();
}
else if( NETWORK_TYPE==NETWORK_EVDO )
{
g_objPhoneEvdo.ReleasePhone();
}
else if( NETWORK_TYPE==NETWORK_WCDMA )
{
g_objPhoneWcdma.ReleasePhone();
}
#if SMALL_VER == 0
g_objGpsSrc.ReleaseGpsAll();
#endif
g_objDiaodu.Release();
g_hstapp.Release();
g_hst.Release();
g_objComAdjust.Release();
#if VEHICLE_TYPE == VEHICLE_M
g_objLightCtrl.Release();
#endif
#if VEHICLE_TYPE == VEHICLE_V8 || VEHICLE_TYPE == VEHICLE_M2
g_objLightCtrl2.Release();
#endif
return 0;
}
void *G_RecvDiaoduData(void *arg)
{
//读取通信组件diaodu数据
char szbuf[MAX_DEAL_BUF_SIZE] = {0};
DWORD dwLen;
BYTE bytLvl;
DWORD dwPktNum;
DWORD dwSrcSymb;
int iResult = DataWaitPop(DEV_DIAODU);
while( !iResult )
{
if( g_bProgExit )
{
break;
}
//pop进程组件发送到调度的数据
while( !DataPop(szbuf, MAX_DEAL_BUF_SIZE, &dwLen, &dwSrcSymb, DEV_DIAODU, &bytLvl) )
{
if( dwLen < 1 ) continue; //保险处理
if(DEV_IO == dwSrcSymb )
{
continue;
}
switch( szbuf[0] )
{
case 0x00: // 使用串口扩展盒,从调度屏/手柄接收到的数据
{
g_objComAdjust.AnalyseComFrame(szbuf+1, dwLen-1);
}
break;
case 0x01: // 要发往调度屏/手柄的数据
{
g_objDiaoduOrHandWorkMng.PushData((BYTE)LV1, dwLen-1, (char*)szbuf+1, dwPktNum, 0);
}
break;
case 0x02: // 指示灯控制
{
#if VEHICLE_TYPE == VEHICLE_M
g_objLightCtrl.SetLightSta(szbuf[1]);
#endif
#if VEHICLE_TYPE == VEHICLE_V8 || VEHICLE_TYPE == VEHICLE_M2
if(dwLen > 2)
g_objLightCtrl2.m_objMemInfoMng.PushData(LV1, dwLen-1, (char*)szbuf+1, dwPktNum);
else
g_objLightCtrl2.SetLightSta(szbuf[1]);
#endif
}
break;
case 0x03: //油耗AD指示
{
memcpy((void*)&g_usOilAD, szbuf+1, 2);
}
break;
case 0x04: // 请求恢复GPS
{
g_objGpsSrc.m_bNeedGpsOn = true;
}
break;
case 0x05: //GPS开关
{
g_objGpsSrc.GpsSwitch = szbuf[1] ? false : true;
}
break;
default:
break;
}
}
iResult = DataWaitPop(DEV_DIAODU);
}
// DataWaitPop返回出错,可能以后需要添加一些清除操作
if(ERR_MSGSKIPBLOCK == iResult)
{
}
// 若接收线程退出,则整个程序退出
g_bProgExit = true;
PRTMSG(MSG_NOR,"G_RecvDiaoduData线程退出\n");
}
void *G_RecvPhoneData(void *arg)
{
//读取通信组件phone数据
char szbuf[MAX_DEAL_BUF_SIZE] = {0};
DWORD dwLen;
BYTE bytLvl;
DWORD dwPktNum;
DWORD dwSrcSymb;
int iResult = DataWaitPop(DEV_PHONE);
while( !iResult )
{
if( g_bProgExit )
{
break;
}
//pop进程组件发送到手机模块的数据
while( !DataPop(szbuf, MAX_DEAL_BUF_SIZE, &dwLen, &dwSrcSymb, DEV_PHONE, &bytLvl) )
{
if( dwLen < 1 ) continue; //保险处理
if(DEV_IO == dwSrcSymb )
{
g_objIoStaRcvMng.PushData((BYTE)LV1, dwLen, (char*)szbuf, dwPktNum);
continue;
}
//推到手机模块数据接收队列
if( dwSrcSymb != DEV_IO )
g_objPhoneRecvDataMng.PushData((BYTE)LV1, dwLen, (char*)szbuf, dwPktNum, 0);
}
iResult = DataWaitPop(DEV_PHONE);
}
// DataWaitPop返回出错,可能以后需要添加一些清除操作
if(ERR_MSGSKIPBLOCK == iResult)
{
}
// 若接收线程退出,则整个程序退出
g_bProgExit = true;
PRTMSG(MSG_NOR,"G_RecvPhoneData线程退出\n");
}
void *G_DealIOThread(void* arg)
{
char szbuf[100];
DWORD dwLen;
BYTE bytLvl;
BYTE bytSrcSymb;
DWORD dwPushTm;
while( !g_bProgExit )
{
usleep(100000);
while( !g_objIoStaRcvMng.PopData(bytLvl, (DWORD)sizeof(szbuf), dwLen, (char*)szbuf, dwPushTm, &bytSrcSymb) )
{
if( dwLen != 1 )
continue;
g_objIoSta.DealIOMsg(szbuf, dwLen, bytSrcSymb);
}
}
}
void (* G_Signal(int signo, void(* func)(int v_signo)))(int)
{
struct sigaction act;//新的信号关联信息
struct sigaction oact;//老的信号关联信息
act.sa_handler = func;//新的信号处理函数
sigemptyset(&act.sa_mask);//初始化屏蔽字
act.sa_flags = 0;//初始化flags
if (signo == SIGALRM)
{//不会重启动
// act.sa_flags |= SA_INERRUPT;
}
else
{ //重启动
act.sa_flags |= SA_RESTART;
}
if (sigaction(signo, &act, &oact) < 0)//新老交换
return(SIG_ERR);
return NULL;
}
#if SMALL_VER == 1
#if VEHICLE_TYPE == VEHICLE_M
#define BUS_SDISK ("/sys/bus/usb/drivers/usb-storage/1-2.1:1.0")
#define BUS_HDISK ("/sys/bus/usb/drivers/usb-storage/1-1:1.0")
#define BUS_UDISK ("/sys/bus/usb/drivers/usb-storage/1-2.2:1.0")
#define DEV_SDISK ("/sys/devices/platform/hisilicon-ohci.0/usb1/1-2/1-2.1/1-2.1:1.0")
#define DEV_HDISK ("/sys/devices/platform/hisilicon-ohci.0/usb1/1-1/1-1:1.0")
#define DEV_UDISK ("/sys/devices/platform/hisilicon-ohci.0/usb1/1-2/1-2.2/1-2.2:1.0")
#endif
#if VEHICLE_TYPE == VEHICLE_M2
#define BUS_SDISK ("/sys/bus/usb/drivers/usb-storage/1-1.1:1.0")
#define BUS_HDISK ("/sys/bus/usb/drivers/usb-storage/1-1.3:1.0")
#define BUS_UDISK ("/sys/bus/usb/drivers/usb-storage/2-1:1.0")
#define DEV_SDISK ("/sys/devices/platform/hisilicon-ohci.0/usb1/1-1/1-1.1/1-1.1:1.0")
#define DEV_HDISK ("/sys/devices/platform/hisilicon-ohci.0/usb1/1-1/1-1.3/1-1.3:1.0")
#define DEV_UDISK ("/sys/devices/platform/hiusb-hcd.0/usb2/2-1/2-1:1.0")
#endif
#if VEHICLE_TYPE == VEHICLE_V8
#define BUS_UDISK ("/sys/bus/usb/drivers/usb-storage/2-1:1.0")
#define DEV_UDISK ("/sys/devices/platform/hiusb-hcd.0/usb2/2-1/2-1:1.0")
#endif
//磁盘使用率上下限
#define MAX_INODE_USAGE_SDISK 0.90
#define MIN_INODE_USAGE_SDISK 0.80
#define MAX_INODE_USAGE_HDISK 0.90
#define MIN_INODE_USAGE_HDISK 0.80
#define MAX_INODE_USAGE_UDISK 0.90
#define MIN_INODE_USAGE_UDISK 0.80
#define MAX_SPACE_USAGE_SDISK 0.90
#define MIN_SPACE_USAGE_SDISK 0.80
#define MAX_SPACE_USAGE_HDISK 0.90
#define MIN_SPACE_USAGE_HDISK 0.80
#define MAX_SPACE_USAGE_UDISK 0.90
#define MIN_SPACE_USAGE_UDISK 0.80
//磁盘检测间隔(秒)
#define VALID_DECCNT_SDISK 6
#define VALID_DECCNT_HDISK 6
#define VALID_DECCNT_UDISK 6
#define SPACE_DECCNT_SDISK 60
#define SPACE_DECCNT_HDISK 60
#define SPACE_DECCNT_UDISK 60
#define INODE_DECCNT_SDISK 60*60
#define INODE_DECCNT_HDISK 60*60
#define INODE_DECCNT_UDISK 60*60
//磁盘分区数
#define PART_NUM_SDISK 2
#define PART_NUM_HDISK 2
#define PART_NUM_UDISK 1
//磁盘未挂载复位时间(秒)
#define UMOUNT_REBOOT_SDISK 1200
#define UMOUNT_REBOOT_HDISK 1200
#define UMOUNT_REBOOT_UDISK 1200
//磁盘未识别复位时间(秒)
#define UCONNECT_INIT_SDISK 60
#define UCONNECT_INIT_HDISK 60
#define UCONNECT_INIT_UDISK 60
/*存储器状态*/
enum
{
UCON_UMOU_UVAL,//未连接、未挂载、无可用空间
CON_UMOU_UVAL,//已连接、未挂载、无可用空间
CON_MOU_UVAL,//已连接、已挂载、无可用空间
CON_MOU_VAL//已连接、已挂载、有可用空间
};
/*USB设备状态*/
typedef struct yx_USB_STATE
{
BYTE SDisk[2];
BYTE HDisk[2];
BYTE UDisk[2];
}USB_STATE;
/*USB设备卸载*/
typedef struct yx_USB_UMOUNT
{
BOOL SDisk[2];
BOOL HDisk[2];
BOOL UDisk[2];
}USB_UMOUNT;
USB_STATE g_objUsbSta = {UCON_UMOU_UVAL};
USB_UMOUNT g_objUsbUmount = {FALSE};
enum{ SDISK, HDISK, UDISK };
enum{ PART1=0, PART2, PART3 };
bool UCONNECT(void *Event)
{
if( *((BYTE*)Event)==UCON_UMOU_UVAL )
return true;
else
return false;
}
bool UMOUNT(void *Event)
{
if( *((BYTE*)Event)==CON_UMOU_UVAL )
return true;
else
return false;
}
bool MOUNT(void *Event)
{
if( *((BYTE*)Event)==CON_MOU_UVAL || *((BYTE*)Event)==CON_MOU_VAL )
return true;
else
return false;
}
//单屏显示
void ShowDiaodu(char *fmt, ...)
{
char str[1024] = {0x01, 0x72, 0x01};
va_list ap;
va_start(ap, fmt);
vsprintf(str+3, fmt, ap);
va_end(ap);
DataPush(str, strlen(str), DEV_DIAODU, DEV_DIAODU, LV2);
}
int GetFileNum(char *v_szPath, char *v_szName, bool v_bRecur)
{
int i;
int iAllFileNum = 0;
int iFileNum = 0;
char szPath[1024] = {0};
struct dirent **objList;
struct stat objStat;
iAllFileNum = scandir(v_szPath, &objList, 0, alphasort);
for(i=0; i<iAllFileNum; i++)
{
// ClearThreadDog(1);//防止文件太多时计算时间过长而来不及清看门狗
STRCPY(szPath, 2, v_szPath, objList[i]->d_name);
if( 0!=stat(szPath, &objStat) )
{
PRTMSG(MSG_ERR, "stat err\n");
perror("");
continue;
}
if(S_ISREG(objStat.st_mode) || S_ISCHR(objStat.st_mode) || S_ISBLK(objStat.st_mode))//找到一个文件
{
if( STRCMP(v_szName, objList[i]->d_name)==0 )// 满足条件
iFileNum += 1;
strcpy(szPath, v_szPath);
}
else if(S_ISDIR(objStat.st_mode))//找到一个目录
{
if(strcmp(objList[i]->d_name, ".") && strcmp(objList[i]->d_name, ".."))//忽略这两个目录
{
if(v_bRecur)//递归查找
{
strcat(szPath, "/");
iFileNum += GetFileNum(szPath, v_szName, v_bRecur);//子目录下查找目标
}
else if( STRCMP(v_szName, objList[i]->d_name)==0 )// 满足条件
iFileNum += 1;
}
strcpy(szPath, v_szPath);
}
}
return iFileNum;
}
//磁盘分区未挂载时获取到的是Flash的容量
void GetDiskSpace( int v_iDiskStyle, int v_iDiskPart, long long *v_lTotalSpace, long long *v_lFreeSpace, long long *v_lAvailSpace )
{
char szDiskPart[128] = {0};
struct statfs buf = {0};
// ClearThreadDog(1);//防止文件太多时计算时间过长而来不及清看门狗
switch( v_iDiskStyle )
{
case SDISK:
{
if( MOUNT(&g_objUsbSta.SDisk[v_iDiskPart]) )
{
statfs(SPRINTF(szDiskPart, "/mnt/SDisk/part%d", v_iDiskPart+1), &buf);
goto DISK_SIZE;
}
}
break;
case HDISK:
{
if( MOUNT(&g_objUsbSta.HDisk[v_iDiskPart]) )
{
statfs(SPRINTF(szDiskPart, "/mnt/HDisk/part%d", v_iDiskPart+1), &buf);
goto DISK_SIZE;
}
}
break;
case UDISK:
{
if( MOUNT(&g_objUsbSta.UDisk[v_iDiskPart]) )
{
statfs(SPRINTF(szDiskPart, "/mnt/UDisk/part%d", v_iDiskPart+1), &buf);
goto DISK_SIZE;
}
}
break;
default:
break;
}
if(v_lTotalSpace)
*v_lTotalSpace = -1;
if(v_lFreeSpace)
*v_lFreeSpace = -1;
if(v_lAvailSpace)
*v_lAvailSpace = -1;
return;
DISK_SIZE:
if(v_lTotalSpace)
*v_lTotalSpace = (long long)buf.f_bsize * buf.f_blocks;
if(v_lFreeSpace)
*v_lFreeSpace = (long long)buf.f_bsize * buf.f_bfree;
if(v_lAvailSpace)
*v_lAvailSpace = (long long)buf.f_bsize * buf.f_bavail;
}
double GetDiskUsage( int v_iDiskStyle, int v_iDiskPart, char v_cUsageType )
{
double dDiskUsage;
int iTotalInode, iUseInode;
long long lTotalSpace, lAvailSpace;
GetDiskSpace(v_iDiskStyle, v_iDiskPart, &lTotalSpace, NULL, &lAvailSpace);
//计算磁盘节点使用率
if( v_cUsageType=='I' )
{
switch( v_iDiskStyle )
{
case SDISK:
{
if( v_iDiskPart==PART1 )
{
iTotalInode = lTotalSpace/1048576;
iUseInode = GetFileNum("/mnt/SDisk/part1/data/", "*", true);
}
else if( v_iDiskPart==PART2 )
{
iTotalInode = lTotalSpace/4096;
iUseInode = GetFileNum("/mnt/SDisk/part2/data/", "*", true);
}
}
break;
case HDISK:
{
if( v_iDiskPart==PART1 )
{
iTotalInode = lTotalSpace/1048576;
iUseInode = GetFileNum("/mnt/HDisk/part1/data/", "*", true);
}
else if( v_iDiskPart==PART2 )
{
iTotalInode = lTotalSpace/4096;
iUseInode = GetFileNum("/mnt/HDisk/part2/data/", "*", true);
}
}
break;
case UDISK:
{
if( v_iDiskPart==PART1 )
{
iTotalInode = lTotalSpace/4096;
iUseInode = GetFileNum("/mnt/UDisk/part1/data/", "*", true);
}
else if( v_iDiskPart==PART2 )
{
iTotalInode = lTotalSpace/4096;
iUseInode = GetFileNum("/mnt/UDisk/part2/data/", "*", true);
}
}
break;
default:
break;
}
dDiskUsage = iUseInode/(double)iTotalInode;
}
//计算磁盘容量使用率
else if( v_cUsageType=='S' )
{
dDiskUsage = 1 - lAvailSpace/(double)lTotalSpace;
}
return dDiskUsage;
}
void* G_ChkUDisk(void* arg)
{
char szTempBuf[1024];
int iRet;
int i,j;
DWORD dwSDiskUconnectCnt[PART_NUM_SDISK] = {0}, dwHDiskUconnectCnt[PART_NUM_HDISK] = {0}, dwUDiskUconnectCnt[PART_NUM_UDISK] = {0};
DWORD dwSDiskUmountCnt[PART_NUM_SDISK] = {0}, dwHDiskUmountCnt[PART_NUM_HDISK] = {0}, dwUDiskUmountCnt[PART_NUM_UDISK] = {0};
DWORD dwSDiskMountCnt[PART_NUM_SDISK] = {0}, dwHDiskMountCnt[PART_NUM_HDISK] = {0}, dwUDiskMountCnt[PART_NUM_UDISK] = {0};
DWORD dwSDiskDetectCnt[PART_NUM_SDISK] = {0}, dwHDiskDetectCnt[PART_NUM_HDISK] = {0}, dwUDiskDetectCnt[PART_NUM_UDISK] = {0};
BOOL bSDiskExist[PART_NUM_SDISK] = {FALSE}, bHDiskExist[PART_NUM_HDISK] = {FALSE}, bUDiskExist[PART_NUM_UDISK] = {FALSE};
BOOL bSDiskSpaceValid[PART_NUM_SDISK] = {FALSE}, bHDiskSpaceValid[PART_NUM_HDISK] = {FALSE}, bUDiskSpaceValid[PART_NUM_UDISK] = {FALSE};
BOOL bSDiskInodeValid[PART_NUM_SDISK] = {FALSE}, bHDiskInodeValid[PART_NUM_HDISK] = {FALSE}, bUDiskInodeValid[PART_NUM_UDISK] = {FALSE};
BOOL bSDiskMount[PART_NUM_SDISK] = {TRUE}, bHDiskMount[PART_NUM_HDISK] = {TRUE}, bUDiskMount[PART_NUM_UDISK] = {TRUE};
FILE *pSDiskFile[PART_NUM_SDISK] = {NULL}, *pHDiskFile[PART_NUM_HDISK] = {NULL}, *pUDiskFile[PART_NUM_UDISK] = {NULL};
struct dirent **ppSDiskList, **ppHDiskList, **ppUDiskList;
struct statfs objSDiskBuf, objHDiskBuf, objUDiskBuf;
double dSDiskUsage[PART_NUM_SDISK] = {0}, dHDiskUsage[PART_NUM_HDISK] = {0}, dUDiskUsage[PART_NUM_UDISK] = {0};
double dSDiskInodeUsage[PART_NUM_SDISK] = {0}, dSDiskSpaceUsage[PART_NUM_SDISK] = {0};
double dHDiskInodeUsage[PART_NUM_HDISK] = {0}, dHDiskSpaceUsage[PART_NUM_HDISK] = {0};
double dUDiskInodeUsage[PART_NUM_UDISK] = {0}, dUDiskSpaceUsage[PART_NUM_UDISK] = {0};
#if VEHICLE_TYPE == VEHICLE_V8
IOSet(IOS_USBPOW, IO_USBPOW_ON, NULL, 0);
#endif
while(1)
{
///----------U盘状态检测----------
for(i=0; i<PART_NUM_UDISK; i++)
{
switch(g_objUsbSta.UDisk[i])
{
case UCON_UMOU_UVAL:
{
// ResetUsb();//如果usb otg出错则复位之
if(access(BUS_UDISK, F_OK) == 0)
{
int n = scandir(DEV_UDISK, &ppUDiskList, 0, alphasort);
if(access(SPRINTF(szTempBuf, "/dev/scsi/%s/bus0/target0/lun0/disc", ppUDiskList[10]->d_name), F_OK) == 0)
{
bUDiskMount[i] = TRUE;
g_objUsbSta.UDisk[i] = CON_UMOU_UVAL;
}
}
}
break;
case CON_UMOU_UVAL:
{
if( g_objUsbUmount.UDisk[i] )
break;
if(access(SPRINTF(szTempBuf, "/dev/scsi/%s/bus0/target0/lun0/part%d", ppUDiskList[10]->d_name, i+1), F_OK) == 0)
{
if( bUDiskMount[i] )
{
if(SYSTEM("mount -t vfat -o rw /dev/scsi/%s/bus0/target0/lun0/part%d /mnt/UDisk/part%d", ppUDiskList[10]->d_name, i+1, i+1) == 0
&&access(SPRINTF(szTempBuf, "/mnt/UDisk/part%d/flash", i+1), F_OK) != 0)
{
if(access(SPRINTF(szTempBuf, "/mnt/UDisk/part%d/data", i+1), F_OK) == 0)
{
chmod(SPRINTF(szTempBuf, "/mnt/UDisk/part%d/data", i+1), S_IRWXU|S_IRWXG|S_IRWXO);// 将目录的访问权限设置为所有人可读、可写、可执行
}
else
{
if(mkdir(SPRINTF(szTempBuf, "/mnt/UDisk/part%d/data", i+1), 0777) == 0)
{
chmod(SPRINTF(szTempBuf, "/mnt/UDisk/part%d/data", i+1), S_IRWXU|S_IRWXG|S_IRWXO);
}
}
if((pUDiskFile[i] = fopen(SPRINTF(szTempBuf, "/mnt/UDisk/part%d/data/disk", i+1), "w+b")) == NULL)
{
switch(++dwUDiskDetectCnt[i])
{
case 1:
case 2:
case 3:
case 4:
{
dwUDiskMountCnt[i] = 0;
g_objUsbSta.UDisk[i] = UCON_UMOU_UVAL;
SYSTEM("umount /mnt/UDisk/part%d", i+1);
}
break;
case 5:
{
bUDiskMount[i] = FALSE;//当U盘连续5次读写失败时,停止挂载
}
break;
default:
break;
}
}
else
{
fclose(pUDiskFile[i]);
pUDiskFile[i] = NULL;
dwUDiskMountCnt[i] = 0;
dwUDiskDetectCnt[i] = 0;
g_objUsbSta.UDisk[i] = CON_MOU_UVAL;
dUDiskInodeUsage[i] = GetDiskUsage(UDISK, i, 'I');
dUDiskSpaceUsage[i] = GetDiskUsage(UDISK, i, 'S');
if( dUDiskInodeUsage[i]>=MAX_INODE_USAGE_UDISK )
{
bUDiskInodeValid[i] = FALSE;
}
else
{
bUDiskInodeValid[i] = TRUE;
}
if( dUDiskSpaceUsage[i]>=MAX_SPACE_USAGE_UDISK )
{
bUDiskSpaceValid[i] = FALSE;
}
else
{
bUDiskSpaceValid[i] = TRUE;
}
if( bUDiskInodeValid[i] && bUDiskSpaceValid[i] )
{
g_objUsbSta.UDisk[i] = CON_MOU_VAL;
}
PRTMSG(MSG_NOR, "UDisk part%d mount succ, inode usage %.3f%%, space usage %.3f%%\n", i+1, 100*dUDiskInodeUsage[i], 100*dUDiskSpaceUsage[i]);
bool bMount = true;
for(int c=0; c<PART_NUM_UDISK; c++)
{
if( MOUNT(&g_objUsbSta.UDisk[c])==false )
{
bMount = false;
break;
}
}
if( bMount )
ShowDiaodu("检测到U盘插入");
}
}
else
{
switch( ++dwUDiskMountCnt[i] )
{
case 2:
case 4:
// SYSTEM("umount /mnt/UDisk/part%d", i+1);
// g_objUsbSta.UDisk[i] = UCON_UMOU_UVAL;
break;
case 5:
bUDiskMount[i] = FALSE;//当U盘连续5次挂载失败时,停止挂载
PRTMSG(MSG_NOR, "UDisk part%d can not dectect\n", i+1);
break;
default:
break;
}
}
}
}
else
{
dwUDiskMountCnt[i] = 0;
dwUDiskDetectCnt[i] = 0;
g_objUsbSta.UDisk[i] = UCON_UMOU_UVAL;
}
}
break;
case CON_MOU_UVAL:
{
if( g_objUsbUmount.UDisk[i] )
{
if(SYSTEM("umount /mnt/UDisk/part%d", i+1) == 0)
{
PRTMSG(MSG_NOR, "UDisk part%d umount succ\n", i+1);
}
dwUDiskMountCnt[i] = 0;
dwUDiskDetectCnt[i] = 0;
g_objUsbSta.UDisk[i] = CON_UMOU_UVAL;
break;
}
++dwUDiskDetectCnt[i];
if((pUDiskFile[i] = fopen(SPRINTF(szTempBuf, "/mnt/UDisk/part%d/data/disk", i+1), "r+b")) != NULL)
{
fclose(pUDiskFile[i]);
pUDiskFile[i] = NULL;
//ClearDisk("UDisk", SPRINTF(szTempBuf, "part%d", i+1));
if( !bUDiskInodeValid[i] )
{
dUDiskInodeUsage[i] = GetDiskUsage(UDISK, i, 'I');
if( dUDiskInodeUsage[i]<=MIN_INODE_USAGE_UDISK )
{
bUDiskInodeValid[i] = TRUE;
}
}
if( !bUDiskSpaceValid[i] )
{
dUDiskSpaceUsage[i] = GetDiskUsage(UDISK, i, 'S');
if( dUDiskSpaceUsage[i]<=MIN_SPACE_USAGE_UDISK )
{
bUDiskSpaceValid[i] = TRUE;
}
}
if( bUDiskInodeValid[i] && bUDiskSpaceValid[i] )
{
// dUDiskInodeUsage[i] = GetDiskUsage(UDISK, i, 'I');
// dUDiskSpaceUsage[i] = GetDiskUsage(UDISK, i, 'S');
PRTMSG(MSG_NOR, "UDisk part%d: inode usage %.3f%%, space usage %.3f%%\n", i+1, 100*dUDiskInodeUsage[i], 100*dUDiskSpaceUsage[i]);
g_objUsbSta.UDisk[i] = CON_MOU_VAL;
}
}
else
{
dwUDiskMountCnt[i] = 0;
dwUDiskDetectCnt[i] = 0;
g_objUsbSta.UDisk[i] = UCON_UMOU_UVAL;
if(SYSTEM("umount /mnt/UDisk/part%d", i+1) == 0)
{
PRTMSG(MSG_NOR, "UDisk part%d umount succ\n", i+1);
}
bool bUconnect = true;
for(int c=0; c<PART_NUM_UDISK; c++)
{
if( UCONNECT(&g_objUsbSta.UDisk[c])==false )
{
bUconnect = false;
break;
}
}
if( bUconnect )
ShowDiaodu("检测到U盘拔出");
}
}
break;
case CON_MOU_VAL:
{
if( g_objUsbUmount.UDisk[i] )
{
if(SYSTEM("umount /mnt/UDisk/part%d", i+1) == 0)
{
PRTMSG(MSG_NOR, "UDisk part%d umount succ\n", i+1);
}
dwUDiskMountCnt[i] = 0;
dwUDiskDetectCnt[i] = 0;
g_objUsbSta.UDisk[i] = CON_UMOU_UVAL;
break;
}
if(++dwUDiskDetectCnt[i]%VALID_DECCNT_UDISK == 0)
{
if((pUDiskFile[i] = fopen(SPRINTF(szTempBuf, "/mnt/UDisk/part%d/data/disk", i+1), "r+b")) != NULL)
{
fclose(pUDiskFile[i]);
pUDiskFile[i] = NULL;
if(dwUDiskDetectCnt[i]%INODE_DECCNT_UDISK == 0)
{
dUDiskInodeUsage[i] = GetDiskUsage(UDISK, i, 'I');
if( dUDiskInodeUsage[i]>=MAX_INODE_USAGE_UDISK )
{
bUDiskInodeValid[i] = FALSE;
}
}
if(dwUDiskDetectCnt[i]%SPACE_DECCNT_UDISK == 0)
{
dUDiskSpaceUsage[i] = GetDiskUsage(UDISK, i, 'S');
if( dUDiskSpaceUsage[i]>=MAX_SPACE_USAGE_UDISK )
{
bUDiskSpaceValid[i] = FALSE;
}
}
if( !bUDiskInodeValid[i] || !bUDiskSpaceValid[i] )
{
// dUDiskInodeUsage[i] = GetDiskUsage(UDISK, i, 'I');
// dUDiskSpaceUsage[i] = GetDiskUsage(UDISK, i, 'S');
PRTMSG(MSG_NOR, "UDisk part%d: inode usage %.3f%%, space usage %.3f%%\n", i+1, 100*dUDiskInodeUsage[i], 100*dUDiskSpaceUsage[i]);
g_objUsbSta.UDisk[i] = CON_MOU_UVAL;
}
}
else
{
if(SYSTEM("umount /mnt/UDisk/part%d", i+1) == 0)
{
PRTMSG(MSG_NOR, "UDisk part%d umount succ\n", i+1);
}
dwUDiskMountCnt[i] = 0;
dwUDiskDetectCnt[i] = 0;
g_objUsbSta.UDisk[i] = UCON_UMOU_UVAL;
bool bUconnect = true;
for(int c=0; c<PART_NUM_UDISK; c++)
{
if( UCONNECT(&g_objUsbSta.UDisk[c])==false )
{
bUconnect = false;
break;
}
}
if( bUconnect )
ShowDiaodu("检测到U盘拔出");
}
}
}
break;
default:
break;
}
}
sleep(1);
}
}
#endif
int main()
{
ListPhoneInfo();
pthread_t pRecvDiaoduData, pRecvPhoneData, pRecvIoData;
#if SMALL_VER == 1
pthread_t pChkUDisk;
#endif
bool bNeedReset = false;
DWORD dwBeginTm = 0, dwCurTm = 0;
int iRand = 0;
byte bytAccSta;
struct tm pCurrentTime;
dwBeginTm = dwCurTm = GetTickCount();
srand( (int)time(0) );
iRand = rand() % 60 ; // 产生一个随机数,用于复位控制
_InitAll();
if( pthread_create(&pRecvDiaoduData, NULL, G_RecvDiaoduData, NULL) != 0
||
pthread_create(&pRecvPhoneData, NULL, G_RecvPhoneData, NULL) != 0
||
pthread_create(&pRecvIoData, NULL, G_DealIOThread, NULL) != 0
#if SMALL_VER == 1
||
pthread_create(&pChkUDisk, NULL, G_ChkUDisk, NULL) != 0
#endif
)
{
PRTMSG(MSG_ERR, "create deal thread failed: ");
perror(" ");
_ReleaseAll();
return ERR_THREAD;
}
PRTMSG(MSG_NOR, "The ComuExe begin to run!\n");
int i = 0;
while(!g_bProgExit)
{
sleep(1);
// 清看门狗
if( i++ % 5 == 0 )
{
DogClr( DOG_COMU );
}
//////////////////////////////////////////////////////////////////////////
// 定时复位
dwCurTm = GetTickCount();
if( dwCurTm - dwBeginTm > 48*3600*1000 ) // 若运行时间已超过48小时,则强制复位
goto _RESET_SYSTEM;
if( dwCurTm - dwBeginTm > 24*3600*1000 ) // 若运行时间已超过24小时,根据ACC状态、时间段来判断是否复位
{
IOGet(IOS_ACC, &bytAccSta);
// 若ACC有效,则不复位
if( bytAccSta == IO_ACC_ON )
continue;
G_GetTime(&pCurrentTime);
// 若不在复位时间段内,则不复位(复位时间段定为每天 09:00 ~ 11:00, 随机选取一个时刻复位)
if( pCurrentTime.tm_hour == 12 && pCurrentTime.tm_min == iRand )
goto _RESET_SYSTEM;
else
continue;
}
else
continue;
_RESET_SYSTEM:
PRTMSG(MSG_NOR, "Reset Time!!!!!!!!!!!!!!!!!!!!!!!!!\n");
G_ResetSystem();
break;
}
g_bProgExit = true;
_ReleaseAll();
// 等待子线程、以及其他进程退出
sleep(15);
PRTMSG(MSG_NOR, "ComuExe is now to quit\n");
// system("reboot");
return 0;
}
| [
"[email protected]"
] | [
[
[
1,
1071
]
]
] |
40ed61282e00497f7ab771e818c288e3dd2f03c8 | d57f646dc96686ef496054d073d4d495b6036b9b | /NetPipe/Kicker.cpp | 011bca4776bf9ee864ca64f4bf9b1f5605ecba77 | [
"BSD-2-Clause"
] | permissive | limura/netpipe | 00d65fd542d3bab833acf24a1a27ac7fd767503a | 1e363a21e299bc2bab4f902c8e70c66786ea8e5b | refs/heads/master | 2021-01-19T13:50:41.041736 | 2007-10-02T10:25:13 | 2007-10-02T10:25:13 | 32,438,427 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,971 | cpp | /*
* Copyright (c) 2007 IIMURA Takuji. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
*
* $Id: Kicker.cpp 66 2007-07-04 07:01:15Z $
*/
#include "config.h"
#include "MainLoop.h"
#include "Kicker.h"
#include "ServiceDB.h"
#include "net.h"
#include "StreamBuffer.h"
#include "tools.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <map>
#include <string>
namespace NetPipe {
Kicker::Kicker(){
}
Kicker::~Kicker(){
}
void Kicker::kick(char *NetPipePathString){
ServiceDB *db = ServiceDB::getInstance();
char *buf;
if(NetPipePathString == NULL)
return;
int NetPipePathStringLen = (int)strlen(NetPipePathString);
if(NetPipePathString[NetPipePathStringLen - 1] != '\n'){
buf = (char *)malloc(NetPipePathStringLen + 2);
if(buf == NULL)
throw "no more memory";
memcpy(buf, NetPipePathString, NetPipePathStringLen);
buf[NetPipePathStringLen] = '\n';
buf[NetPipePathStringLen+1] = '\0';
}else{
buf = strdup(NetPipePathString);
if(buf == NULL)
throw "no more memory";
}
stringExistsMap inServiceMap;
stringExistsMap outServiceMap;
inServiceMap.clear();
outServiceMap.clear();
char *LineStart = buf;
char *NextLine;
char *outPortService = NULL;
char *inPort = NULL;
char *inService = NULL;
while((NextLine = strchr(LineStart, '\n')) != NULL){
*NextLine = '\0';
NextLine++;
inService = LineStart;
char *p = strchr(LineStart, ';');
if(p == NULL)
goto CONTINUE;
*p = '\0';
p++;
inPort = p;
p = strchr(p, ';');
if(p == NULL)
goto CONTINUE;
*p = '\0';
p++;
outPortService = p;
p = strchr(p, ';');
if(p == NULL)
goto CONTINUE;
p++;
inServiceMap[inService] = inPort;
outServiceMap[p] = p;
CONTINUE:
LineStart = NextLine;
}
stringExistsMap firstServiceMap;
firstServiceMap.clear();
for(stringExistsMap::iterator i = inServiceMap.begin(); i != inServiceMap.end(); i++){
if(outServiceMap[i->first] == NULL)
firstServiceMap[i->first] = i->second;
}
for(stringExistsMap::iterator i = firstServiceMap.begin(); i != firstServiceMap.end(); i++){
char *targetService = (char *)i->first.c_str();
char *targetPort = i->second;
char *IPaddr = db->QueryIPHostName((char *)i->first.c_str());
char *port = db->QueryTCPPortName((char *)i->first.c_str());
if(targetService == NULL || IPaddr == NULL || port == NULL){
DPRINTF(10, ("can not find service name(%s) or IPaddr:port (%s:%s)\n", targetService, IPaddr, port));
continue;
}
if(targetPort == NULL)
targetPort = "";
DPRINTF(10, (" %s:%s <- %s;%s\n", IPaddr, port, targetPort, targetService));
int sock = connect_stream(IPaddr, port);
if(sock < 0)
continue;
int size = NetPipePathStringLen + (int)sizeof(uint32_t) * 2 + (int)strlen(targetService) + 3 + (int)strlen(targetPort);
StreamBuffer *sm = new StreamBuffer(size + sizeof(uint32_t));
if(sm == NULL)
throw "no more memory";
sm->WriteBinary(NETPIPE_HELLO_STRING, strlen(NETPIPE_HELLO_STRING));
sm->WriteInt32(size);
sm->WriteUint32(0);
sm->WriteUint32(size - sizeof(uint32_t) * 2);
sm->WriteBinary(targetPort, strlen(targetPort));
sm->WriteUint8(';');
sm->WriteBinary(targetService, strlen(targetService));
sm->WriteUint8('\n');
sm->WriteBinary(NetPipePathString, NetPipePathStringLen);
sm->WriteUint8('\n');
while(sm->socketWrite(sock))
;
closeSocket(sock);
}
free(buf);
}
}; /* namespace NetPipe */
| [
"uirou.j@b085bb30-bf34-0410-99c5-0750ab6b8f60"
] | [
[
[
1,
153
]
]
] |
2e6b07420297c494d1742ac361eea0cb9008a68c | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/QtGui/qdial.h | 75b2e7c552742b4b87f717f58bda5700f2923487 | [
"BSD-2-Clause"
] | permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,863 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QDIAL_H
#define QDIAL_H
#include <QtGui/qabstractslider.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
#ifndef QT_NO_DIAL
class QDialPrivate;
class QStyleOptionSlider;
class Q_GUI_EXPORT QDial: public QAbstractSlider
{
Q_OBJECT
Q_PROPERTY(bool wrapping READ wrapping WRITE setWrapping)
Q_PROPERTY(int notchSize READ notchSize)
Q_PROPERTY(qreal notchTarget READ notchTarget WRITE setNotchTarget)
Q_PROPERTY(bool notchesVisible READ notchesVisible WRITE setNotchesVisible)
public:
explicit QDial(QWidget *parent = 0);
~QDial();
bool wrapping() const;
int notchSize() const;
void setNotchTarget(double target);
qreal notchTarget() const;
bool notchesVisible() const;
QSize sizeHint() const;
QSize minimumSizeHint() const;
public Q_SLOTS:
void setNotchesVisible(bool visible);
void setWrapping(bool on);
protected:
bool event(QEvent *e);
void resizeEvent(QResizeEvent *re);
void paintEvent(QPaintEvent *pe);
void mousePressEvent(QMouseEvent *me);
void mouseReleaseEvent(QMouseEvent *me);
void mouseMoveEvent(QMouseEvent *me);
void sliderChange(SliderChange change);
void initStyleOption(QStyleOptionSlider *option) const;
#ifdef QT3_SUPPORT
public:
QT3_SUPPORT_CONSTRUCTOR QDial(int minValue, int maxValue, int pageStep, int value,
QWidget* parent = 0, const char* name = 0);
QT3_SUPPORT_CONSTRUCTOR QDial(QWidget *parent, const char *name);
Q_SIGNALS:
QT_MOC_COMPAT void dialPressed();
QT_MOC_COMPAT void dialMoved(int value);
QT_MOC_COMPAT void dialReleased();
#endif
private:
Q_DECLARE_PRIVATE(QDial)
Q_DISABLE_COPY(QDial)
};
#endif // QT_NO_DIAL
QT_END_NAMESPACE
QT_END_HEADER
#endif // QDIAL_H
| [
"alon@rogue.(none)"
] | [
[
[
1,
122
]
]
] |
16293c2e3a18c840176e053c3b1eebf68990e169 | b308f1edaab2be56eb66b7c03b0bf4673621b62f | /Code/CryEngine/CryCommon/ILog.h | b908f77cab730d16b0e5f6b1b5a835e97bf58a76 | [] | 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 | 4,593 | h | #include DEVIRTUALIZE_HEADER_FIX(ILog.h)
#ifndef _ILOG_H_
#define _ILOG_H_
#include "ProjectDefines.h"
#include <platform.h>
#include "IMiniLog.h"
// forward declarations
class ICrySizer;
// Summary:
// Callback interface to the ILog.
struct ILogCallback
{
virtual ~ILogCallback(){}
virtual void OnWriteToConsole( const char *sText,bool bNewLine ) = 0;
virtual void OnWriteToFile( const char *sText,bool bNewLine ) = 0;
};
// Summary:
// Interface for logging operations based on IMiniLog.
// Notes:
// Logging in CryEngine should be done using the following global functions:
// CryLog (eMessage)
// CryLogAlways (eAlways)
// CryError (eError)
// CryWarning (eWarning)
// CryComment (eComment)
// ILog gives you more control on logging operations.
// See also:
// IMiniLog, CryLog, CryLogAlways, CryError, CryWarning
UNIQUE_IFACE struct ILog: public IMiniLog
{
virtual void Release() = 0;
// Summary:
// Sets the file used to log to disk.
virtual bool SetFileName(const char *command = NULL) = 0;
// Summary:
// Gets the filename used to log to disk.
virtual const char* GetFileName() = 0;
// Summary:
// Gets the filename where the current log backup was copied to on disk
virtual const char* GetBackupFileName() = 0;
//all the following functions will be removed are here just to be able to compile the project ---------------------------
// Summary:
// Logs the text both to file and console.
virtual void Log(const char *szCommand,...) PRINTF_PARAMS(2, 3) = 0;
virtual void LogAlways(const char *szCommand,...) PRINTF_PARAMS(2, 3) = 0;
virtual void LogWarning(const char *szCommand,...) PRINTF_PARAMS(2, 3) = 0;
virtual void LogError(const char *szCommand,...) PRINTF_PARAMS(2, 3) = 0;
// Summary:
// Logs the text both to the end of file and console.
virtual void LogPlus(const char *command,...) PRINTF_PARAMS(2, 3) = 0;
// Summary:
// Logs to the file specified in SetFileName.
// See also:
// SetFileName
virtual void LogToFile(const char *command,...) PRINTF_PARAMS(2, 3) = 0;
//
virtual void LogToFilePlus(const char *command,...) PRINTF_PARAMS(2, 3) = 0;
// Summary:
// Logs to console only.
virtual void LogToConsole(const char *command,...) PRINTF_PARAMS(2, 3) = 0;
//
virtual void LogToConsolePlus(const char *command,...) PRINTF_PARAMS(2, 3) = 0;
//
virtual void UpdateLoadingScreen(const char *command,...) PRINTF_PARAMS(2, 3) = 0;
//
virtual void RegisterConsoleVariables() {}
//
virtual void UnregisterConsoleVariables() {}
// Notes:
// Full logging (to console and file) can be enabled with verbosity 4.
// In the console 'log_Verbosity 4' command can be used.
virtual void SetVerbosity( int verbosity ) = 0;
virtual int GetVerbosityLevel()=0;
virtual void AddCallback( ILogCallback *pCallback ) = 0;
virtual void RemoveCallback( ILogCallback *pCallback ) = 0;
// Notes:
// The function called every frame by system.
virtual void Update() = 0;
virtual const char* GetModuleFilter() = 0;
// Notes:
// Collect memory statistics in CrySizer
virtual void GetMemoryUsage( ICrySizer *pSizer ) const = 0;
#if !defined(_RELEASE) && !defined(RESOURCE_COMPILER)
virtual void Indent(class CLogIndenter * indenter) = 0;
virtual void Unindent(class CLogIndenter * indenter) = 0;
#endif
DEVIRTUALIZATION_VTABLE_FIX
};
#if defined(_RELEASE) || defined(RESOURCE_COMPILER)
#define INDENT_LOG_DURING_SCOPE(...) (void)(0)
#else
class CLogIndenter
{
public:
CLogIndenter(ILog * log) : m_log(log), m_enabled(false), m_nextIndenter(NULL)
{
}
void Enable(bool enable = true)
{
enable &= (m_log != NULL);
if (enable != m_enabled && m_log)
{
if (enable)
{
m_log->Indent(this);
}
else
{
m_log->Unindent(this);
}
m_enabled = enable;
}
}
CLogIndenter * GetNextIndenter()
{
return m_nextIndenter;
}
void SetNextIndenter(CLogIndenter * indenter)
{
m_nextIndenter = indenter;
}
~CLogIndenter()
{
Enable(false);
}
private:
bool m_enabled;
ILog * m_log;
CLogIndenter * m_nextIndenter;
};
#define ILOG_CONCAT_IMPL( x, y ) x##y
#define ILOG_CONCAT_MACRO( x, y ) ILOG_CONCAT_IMPL( x, y )
#define INDENT_LOG_DURING_SCOPE(...) CLogIndenter ILOG_CONCAT_MACRO(indentMe, __LINE__) ((CryGetCurrentThreadId() == gEnv->mMainThreadId) ? gEnv->pLog : NULL); ILOG_CONCAT_MACRO(indentMe, __LINE__).Enable(__VA_ARGS__)
#endif
#endif //_ILOG_H_
| [
"[email protected]"
] | [
[
[
1,
181
]
]
] |
1a7dc05af1d6e57a13dace7fb942900dd297ade5 | ec41b76a607f9e8dd29288997df56b6837e286c6 | /OgreMath/OgreVector3.h | 43c4869af831b19a6a3946e09e22fd745cd3f99e | [] | no_license | tkaleas/screen-space-fluid-rendering | 2309d5de0886ad961708d1c2203bba6976dd8c2f | 28f0968cb044a40d561747bba9574cc59d3d2fcb | refs/heads/master | 2020-06-04T07:26:25.578575 | 2011-04-26T21:29:49 | 2011-04-26T21:29:49 | 32,113,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,847 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2006 Torus Knot Software Ltd
Also see acknowledgements in Readme.html
This program 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 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser 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, or go to
http://www.gnu.org/copyleft/lesser.txt.
You may alternatively use this source under the terms of a specific version of
the OGRE Unrestricted License provided you have obtained such a license from
Torus Knot Software Ltd.
-----------------------------------------------------------------------------
*/
#ifndef __Vector3_H__
#define __Vector3_H__
#include "OgreCommon.h"
#include "OgreQuaternion.h"
namespace Ogre
{
/** Standard 3-dimensional vector.
@remarks
A direction in 3D space represented as distances along the 3
orthoganal axes (x, y, z). Note that positions, directions and
scaling factors can be represented by a vector, depending on how
you interpret the values.
*/
class _OgreExport Vector3
{
public:
float x, y, z;
public:
inline Vector3()
{
}
inline Vector3( const float fX, const float fY, const float fZ )
: x( fX ), y( fY ), z( fZ )
{
}
inline explicit Vector3( const float afCoordinate[3] )
: x( afCoordinate[0] ),
y( afCoordinate[1] ),
z( afCoordinate[2] )
{
}
inline explicit Vector3( const int afCoordinate[3] )
{
x = (float)afCoordinate[0];
y = (float)afCoordinate[1];
z = (float)afCoordinate[2];
}
inline explicit Vector3( float* const r )
: x( r[0] ), y( r[1] ), z( r[2] )
{
}
inline explicit Vector3( const float scaler )
: x( scaler )
, y( scaler )
, z( scaler )
{
}
inline Vector3( const Vector3& rkVector )
: x( rkVector.x ), y( rkVector.y ), z( rkVector.z )
{
}
inline float operator [] ( const size_t i ) const
{
assert( i < 3 );
return *(&x+i);
}
inline float& operator [] ( const size_t i )
{
assert( i < 3 );
return *(&x+i);
}
/// Pointer accessor for direct copying
inline float* ptr()
{
return &x;
}
/// Pointer accessor for direct copying
inline const float* ptr() const
{
return &x;
}
/** Assigns the value of the other vector.
@param
rkVector The other vector
*/
inline Vector3& operator = ( const Vector3& rkVector )
{
x = rkVector.x;
y = rkVector.y;
z = rkVector.z;
return *this;
}
inline Vector3& operator = ( const float fScaler )
{
x = fScaler;
y = fScaler;
z = fScaler;
return *this;
}
inline bool operator == ( const Vector3& rkVector ) const
{
return ( x == rkVector.x && y == rkVector.y && z == rkVector.z );
}
inline bool operator != ( const Vector3& rkVector ) const
{
return ( x != rkVector.x || y != rkVector.y || z != rkVector.z );
}
// arithmetic operations
inline Vector3 operator + ( const Vector3& rkVector ) const
{
return Vector3(
x + rkVector.x,
y + rkVector.y,
z + rkVector.z);
}
inline Vector3 operator - ( const Vector3& rkVector ) const
{
return Vector3(
x - rkVector.x,
y - rkVector.y,
z - rkVector.z);
}
inline Vector3 operator * ( const float fScalar ) const
{
return Vector3(
x * fScalar,
y * fScalar,
z * fScalar);
}
inline Vector3 operator * ( const Vector3& rhs) const
{
return Vector3(
x * rhs.x,
y * rhs.y,
z * rhs.z);
}
inline Vector3 operator / ( const float fScalar ) const
{
assert( fScalar != 0.0f );
float fInv = 1.0f / fScalar;
return Vector3(
x * fInv,
y * fInv,
z * fInv);
}
inline Vector3 operator / ( const Vector3& rhs) const
{
return Vector3(
x / rhs.x,
y / rhs.y,
z / rhs.z);
}
inline const Vector3& operator + () const
{
return *this;
}
inline Vector3 operator - () const
{
return Vector3(-x, -y, -z);
}
// overloaded operators to help Vector3
inline friend Vector3 operator * ( const float fScalar, const Vector3& rkVector )
{
return Vector3(
fScalar * rkVector.x,
fScalar * rkVector.y,
fScalar * rkVector.z);
}
inline friend Vector3 operator / ( const float fScalar, const Vector3& rkVector )
{
return Vector3(
fScalar / rkVector.x,
fScalar / rkVector.y,
fScalar / rkVector.z);
}
inline friend Vector3 operator + (const Vector3& lhs, const float rhs)
{
return Vector3(
lhs.x + rhs,
lhs.y + rhs,
lhs.z + rhs);
}
inline friend Vector3 operator + (const float lhs, const Vector3& rhs)
{
return Vector3(
lhs + rhs.x,
lhs + rhs.y,
lhs + rhs.z);
}
inline friend Vector3 operator - (const Vector3& lhs, const float rhs)
{
return Vector3(
lhs.x - rhs,
lhs.y - rhs,
lhs.z - rhs);
}
inline friend Vector3 operator - (const float lhs, const Vector3& rhs)
{
return Vector3(
lhs - rhs.x,
lhs - rhs.y,
lhs - rhs.z);
}
// arithmetic updates
inline Vector3& operator += ( const Vector3& rkVector )
{
x += rkVector.x;
y += rkVector.y;
z += rkVector.z;
return *this;
}
inline Vector3& operator += ( const float fScalar )
{
x += fScalar;
y += fScalar;
z += fScalar;
return *this;
}
inline Vector3& operator -= ( const Vector3& rkVector )
{
x -= rkVector.x;
y -= rkVector.y;
z -= rkVector.z;
return *this;
}
inline Vector3& operator -= ( const float fScalar )
{
x -= fScalar;
y -= fScalar;
z -= fScalar;
return *this;
}
inline Vector3& operator *= ( const float fScalar )
{
x *= fScalar;
y *= fScalar;
z *= fScalar;
return *this;
}
inline Vector3& operator *= ( const Vector3& rkVector )
{
x *= rkVector.x;
y *= rkVector.y;
z *= rkVector.z;
return *this;
}
inline Vector3& operator /= ( const float fScalar )
{
assert( fScalar != 0.0f );
float fInv = 1.0f / fScalar;
x *= fInv;
y *= fInv;
z *= fInv;
return *this;
}
inline Vector3& operator /= ( const Vector3& rkVector )
{
x /= rkVector.x;
y /= rkVector.y;
z /= rkVector.z;
return *this;
}
/** Returns the length (magnitude) of the vector.
@warning
This operation requires a square root and is expensive in
terms of CPU operations. If you don't need to know the exact
length (e.g. for just comparing lengths) use squaredLength()
instead.
*/
inline float length () const
{
return sqrtf( x * x + y * y + z * z );
}
/** Returns the square of the length(magnitude) of the vector.
@remarks
This method is for efficiency - calculating the actual
length of a vector requires a square root, which is expensive
in terms of the operations required. This method returns the
square of the length of the vector, i.e. the same as the
length but before the square root is taken. Use this if you
want to find the longest / shortest vector without incurring
the square root.
*/
inline float squaredLength () const
{
return x * x + y * y + z * z;
}
/** Returns the distance to another vector.
@warning
This operation requires a square root and is expensive in
terms of CPU operations. If you don't need to know the exact
distance (e.g. for just comparing distances) use squaredDistance()
instead.
*/
inline float distance(const Vector3& rhs) const
{
return (*this - rhs).length();
}
/** Returns the square of the distance to another vector.
@remarks
This method is for efficiency - calculating the actual
distance to another vector requires a square root, which is
expensive in terms of the operations required. This method
returns the square of the distance to another vector, i.e.
the same as the distance but before the square root is taken.
Use this if you want to find the longest / shortest distance
without incurring the square root.
*/
inline float squaredDistance(const Vector3& rhs) const
{
return (*this - rhs).squaredLength();
}
/** Calculates the dot (scalar) product of this vector with another.
@remarks
The dot product can be used to calculate the angle between 2
vectors. If both are unit vectors, the dot product is the
cosine of the angle; otherwise the dot product must be
divided by the product of the lengths of both vectors to get
the cosine of the angle. This result can further be used to
calculate the distance of a point from a plane.
@param
vec Vector with which to calculate the dot product (together
with this one).
@returns
A float representing the dot product value.
*/
inline float dotProduct(const Vector3& vec) const
{
return x * vec.x + y * vec.y + z * vec.z;
}
/** Calculates the absolute dot (scalar) product of this vector with another.
@remarks
This function work similar dotProduct, except it use absolute value
of each component of the vector to computing.
@param
vec Vector with which to calculate the absolute dot product (together
with this one).
@returns
A float representing the absolute dot product value.
*/
inline float absDotProduct(const Vector3& vec) const
{
return fabs(x * vec.x) + fabs(y * vec.y) + fabs(z * vec.z);
}
/** Normalises the vector.
@remarks
This method normalises the vector such that it's
length / magnitude is 1. The result is called a unit vector.
@note
This function will not crash for zero-sized vectors, but there
will be no changes made to their components.
@returns The previous length of the vector.
*/
inline float normalise()
{
float fLength = sqrtf( x * x + y * y + z * z );
// Will also work for zero-sized vectors, but will change nothing
if ( fLength > 1e-08 )
{
float fInvLength = 1.0f / fLength;
x *= fInvLength;
y *= fInvLength;
z *= fInvLength;
}
return fLength;
}
/** Calculates the cross-product of 2 vectors, i.e. the vector that
lies perpendicular to them both.
@remarks
The cross-product is normally used to calculate the normal
vector of a plane, by calculating the cross-product of 2
non-equivalent vectors which lie on the plane (e.g. 2 edges
of a triangle).
@param
vec Vector which, together with this one, will be used to
calculate the cross-product.
@returns
A vector which is the result of the cross-product. This
vector will <b>NOT</b> be normalised, to maximise efficiency
- call Vector3::normalise on the result if you wish this to
be done. As for which side the resultant vector will be on, the
returned vector will be on the side from which the arc from 'this'
to rkVector is anticlockwise, e.g. UNIT_Y.crossProduct(UNIT_Z)
= UNIT_X, whilst UNIT_Z.crossProduct(UNIT_Y) = -UNIT_X.
This is because OGRE uses a right-handed coordinate system.
@par
For a clearer explanation, look a the left and the bottom edges
of your monitor's screen. Assume that the first vector is the
left edge and the second vector is the bottom edge, both of
them starting from the lower-left corner of the screen. The
resulting vector is going to be perpendicular to both of them
and will go <i>inside</i> the screen, towards the cathode tube
(assuming you're using a CRT monitor, of course).
*/
inline Vector3 crossProduct( const Vector3& rkVector ) const
{
return Vector3(
y * rkVector.z - z * rkVector.y,
z * rkVector.x - x * rkVector.z,
x * rkVector.y - y * rkVector.x);
}
/** Returns a vector at a point half way between this and the passed
in vector.
*/
inline Vector3 midPoint( const Vector3& vec ) const
{
return Vector3(
( x + vec.x ) * 0.5f,
( y + vec.y ) * 0.5f,
( z + vec.z ) * 0.5f );
}
/** Returns true if the vector's scalar components are all greater
that the ones of the vector it is compared against.
*/
inline bool operator < ( const Vector3& rhs ) const
{
if( x < rhs.x && y < rhs.y && z < rhs.z )
return true;
return false;
}
/** Returns true if the vector's scalar components are all smaller
that the ones of the vector it is compared against.
*/
inline bool operator > ( const Vector3& rhs ) const
{
if( x > rhs.x && y > rhs.y && z > rhs.z )
return true;
return false;
}
/** Sets this vector's components to the minimum of its own and the
ones of the passed in vector.
@remarks
'Minimum' in this case means the combination of the lowest
value of x, y and z from both vectors. Lowest is taken just
numerically, not magnitude, so -1 < 0.
*/
inline void makeFloor( const Vector3& cmp )
{
if( cmp.x < x ) x = cmp.x;
if( cmp.y < y ) y = cmp.y;
if( cmp.z < z ) z = cmp.z;
}
/** Sets this vector's components to the maximum of its own and the
ones of the passed in vector.
@remarks
'Maximum' in this case means the combination of the highest
value of x, y and z from both vectors. Highest is taken just
numerically, not magnitude, so 1 > -3.
*/
inline void makeCeil( const Vector3& cmp )
{
if( cmp.x > x ) x = cmp.x;
if( cmp.y > y ) y = cmp.y;
if( cmp.z > z ) z = cmp.z;
}
/** Generates a vector perpendicular to this vector (eg an 'up' vector).
@remarks
This method will return a vector which is perpendicular to this
vector. There are an infinite number of possibilities but this
method will guarantee to generate one of them. If you need more
control you should use the Quaternion class.
*/
inline Vector3 perpendicular(void) const
{
static const float fSquareZero = float(1e-06 * 1e-06);
Vector3 perp = this->crossProduct( Vector3::UNIT_X );
// Check length
if( perp.squaredLength() < fSquareZero )
{
/* This vector is the Y axis multiplied by a scalar, so we have
to use another axis.
*/
perp = this->crossProduct( Vector3::UNIT_Y );
}
perp.normalise();
return perp;
}
/** Gets the shortest arc quaternion to rotate this vector to the destination
vector.
@remarks
If you call this with a dest vector that is close to the inverse
of this vector, we will rotate 180 degrees around the 'fallbackAxis'
(if specified, or a generated axis if not) since in this case
ANY axis of rotation is valid.
*/
Quaternion getRotationTo(const Vector3& dest,
const Vector3& fallbackAxis = Vector3::ZERO) const
{
// Based on Stan Melax's article in Game Programming Gems
Quaternion q;
// Copy, since cannot modify local
Vector3 v0 = *this;
Vector3 v1 = dest;
v0.normalise();
v1.normalise();
float d = v0.dotProduct(v1);
// If dot == 1, vectors are the same
if (d >= 1.0f)
{
return Quaternion::IDENTITY;
}
if (d < (1e-6f - 1.0f))
{
if (fallbackAxis != Vector3::ZERO)
{
// rotate 180 degrees about the fallback axis
q.FromAngleAxis(float(M_PI), fallbackAxis);
}
else
{
// Generate an axis
Vector3 axis = Vector3::UNIT_X.crossProduct(*this);
if (axis.isZeroLength()) // pick another if colinear
axis = Vector3::UNIT_Y.crossProduct(*this);
axis.normalise();
q.FromAngleAxis(float(M_PI), axis);
}
}
else
{
float s = sqrtf( (1+d)*2 );
float invs = 1 / s;
Vector3 c = v0.crossProduct(v1);
q.x = c.x * invs;
q.y = c.y * invs;
q.z = c.z * invs;
q.w = s * 0.5f;
q.normalise();
}
return q;
}
/** Returns true if this vector is zero length. */
inline bool isZeroLength(void) const
{
float sqlen = (x * x) + (y * y) + (z * z);
return (sqlen < (1e-06 * 1e-06));
}
/** As normalise, except that this vector is unaffected and the
normalised vector is returned as a copy. */
inline Vector3 normalisedCopy(void) const
{
Vector3 ret = *this;
ret.normalise();
return ret;
}
/** Calculates a reflection vector to the plane with the given normal .
@remarks NB assumes 'this' is pointing AWAY FROM the plane, invert if it is not.
*/
inline Vector3 reflect(const Vector3& normal) const
{
return Vector3( *this - ( 2 * this->dotProduct(normal) * normal ) );
}
/** Returns whether this vector is within a positional tolerance
of another vector.
@param rhs The vector to compare with
@param tolerance The amount that each element of the vector may vary by
and still be considered equal
*/
inline bool positionEquals(const Vector3& rhs, float tolerance = 1e-03) const
{
return fabs(x-rhs.x) < tolerance &&
fabs(y-rhs.y) < tolerance &&
fabs(z-rhs.z) < tolerance;
}
/** Returns whether this vector is within a positional tolerance
of another vector, also take scale of the vectors into account.
@param rhs The vector to compare with
@param tolerance The amount (related to the scale of vectors) that distance
of the vector may vary by and still be considered close
*/
inline bool positionCloses(const Vector3& rhs, float tolerance = 1e-03f) const
{
return squaredDistance(rhs) <=
(squaredLength() + rhs.squaredLength()) * tolerance;
}
/** Returns whether this vector is within a directional tolerance
of another vector.
@param rhs The vector to compare with
@param tolerance The maximum angle by which the vectors may vary and
still be considered equal
@note Both vectors should be normalised.
*/
inline bool directionEquals(const Vector3& rhs,
const float& tolerance) const
{
float dot = dotProduct(rhs);
float angle = acosf(dot);
return fabs(angle) <= tolerance;
}
// special points
static const Vector3 ZERO;
static const Vector3 UNIT_X;
static const Vector3 UNIT_Y;
static const Vector3 UNIT_Z;
static const Vector3 NEGATIVE_UNIT_X;
static const Vector3 NEGATIVE_UNIT_Y;
static const Vector3 NEGATIVE_UNIT_Z;
static const Vector3 UNIT_SCALE;
/** Function for writing to a stream.
*/
inline _OgreExport friend std::ostream& operator <<
( std::ostream& o, const Vector3& v )
{
o << "Vector3(" << v.x << ", " << v.y << ", " << v.z << ")";
return o;
}
};
}
#endif
| [
"[email protected]@58403bee-ede4-9baf-e632-59ccd62f6f02"
] | [
[
[
1,
715
]
]
] |
5400645aeeaacd8657e740cb1b1f33480c9ebbeb | 9bc85a2a7213db0725beb6ac7bbace0d1f239784 | /src/main.cpp | 17342aed8ba0c4017c1d7775b477071139a041b1 | [] | no_license | doodoonovitch/fastxml | ac17d6679a0cb6c3044a43160f490a4df9c3441f | f3d55399d09899ce48d5a8b496d8c9ea4117ff86 | refs/heads/master | 2021-01-10T12:16:26.743154 | 2010-07-15T22:31:14 | 2010-07-15T22:31:14 | 44,275,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,989 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "PxAssert.h"
/*!
**
** Copyright (c) 2010 by John W. Ratcliff mailto:[email protected]
**
** Skype ID: jratcliff63367
** Yahoo: jratcliff63367
** AOL: jratcliff1961
** email: [email protected]
**
**
** The MIT license:
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is furnished
** to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
** WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "FastXml.h"
#include "PxFileBuffer.h"
#pragma warning(disable:4996)
class TestFastXML : public FAST_XML::FastXml::Callback
{
public:
TestFastXML(physx::PxFileBuf &stream)
{
mDepth = 0;
FAST_XML::FastXml *xml = FAST_XML::createFastXml(this);
PX_ASSERT(xml);
if ( xml )
{
printf("Processing XML file once\r\n");
xml->processXml(stream,true);
xml->release();
}
}
virtual bool processComment(const char *comment)
{
indent();
printf("XML Comment: \"%s\"\r\n", comment );
return true;
}
virtual bool processClose(const char *element,physx::PxU32 depth,bool &isError)
{
isError = false;
#if 1
indent();
printf("CLOSE TAG: %s\r\n", element );
mDepth--;
PX_ASSERT(mDepth>=0);
#endif
return depth == 0 ? false : true;
}
// return true to continue processing the XML document, false to skip.
virtual bool processElement(
const char *elementName, // name of the element
physx::PxI32 argc, // number of attributes
const char **argv, // list of attributes.
const char *elementData, // element data, null if none
physx::PxI32 lineno) // line number in the source XML file
{
#if 1
mDepth++;
indent();
printf("Element: %s with %d attributes.\r\n", elementName, argc );
for (physx::PxI32 i=0; i<(argc/2); i++)
{
indent();
printf("Attribute[%d] %s=%s\r\n", i+1, argv[i*2], argv[i*2+1] );
}
if ( elementData )
{
indent();
char scratch[96];
strncpy(scratch,elementData,95);
scratch[95] = 0;
printf("ElementData: %s\r\n", scratch );
}
#endif
return true;
}
void indent(void)
{
for (physx::PxI32 i=0; i<mDepth; i++)
{
printf(" ");
}
}
virtual bool processXmlDeclaration(
physx::PxI32 argc,
const char **argv,
const char *elementData,
physx::PxI32 lineno)
{
return true;
}
virtual void * fastxml_malloc(physx::PxU32 size)
{
return ::malloc(size);
}
virtual void fastxml_free(void *mem)
{
::free(mem);
}
physx::PxI32 mDepth;
};
void main(int argc,const char **argv)
{
if ( argc == 2 )
{
physx::PxFileBuffer fb(argv[1],physx::PxFileBuf::OPEN_READ_ONLY);
if ( fb.getOpenMode() != physx::PxFileBuf::OPEN_FILE_NOT_FOUND )
{
TestFastXML t(fb);
}
else
{
printf("Input file '%s' not found.\r\n", argv[1] );
}
}
else
{
printf("This is a demonstration application which shows how to use the FastXML parser.\r\n");
printf("Usage: FastXML <filename>\r\n");
}
}
| [
"jratcliffscarab@8511ecbf-a51f-191b-956b-410d5f6f4539"
] | [
[
[
1,
154
]
]
] |
7530fb7d7b3a5c82aed79f0899a433f2702c837d | 9bd0004220edc6cde7927d06f4d06d05a57d6d7d | /xq/move_helper.cpp | eb885b6a88c55584437ef3b79f44785e4b5cef49 | [] | no_license | lwm3751/folium | 32b8c1450d8a1dc1c899ac959493fd4ae5166264 | e32237b6bb5dabbce64ea08e2cf8f4fe60b514d5 | refs/heads/master | 2021-01-22T03:12:58.594929 | 2011-01-09T15:36:02 | 2011-01-09T15:36:02 | 26,789,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,120 | cpp | #include <map>
#include "move_helper.h"
#include "xq_data.h"
namespace folium
{
using std::map;
uint32 ucci2move(const string& ucci)
{
int sx, sy, dx, dy;
sx = ucci[0] - 'a';
sy = ucci[1] - '0';
dx = ucci[2] - 'a';
dy = ucci[3] - '0';
if (sx < 0 || sx > 8 || sy < 0 || sy > 9 ||
dx < 0 || dx > 8 || dy < 0 || dy > 9)
{
return 0;
}
return create_move(xy_coordinate(sx, sy), xy_coordinate(dx, dy));
}
string move2ucci(uint32 move)
{
string ucci;
uint src = move_src(move);
uint dst = move_dst(move);
ucci.push_back(static_cast<char>(coordinate_x(src)+'a'));
ucci.push_back(static_cast<char>(coordinate_y(src)+'0'));
ucci.push_back(static_cast<char>(coordinate_x(dst)+'a'));
ucci.push_back(static_cast<char>(coordinate_y(dst)+'0'));
return ucci;
}
static const char _origin_1[] = "abcdefghi0123456789";
static const char _target_1[] = "ihgfedcba0123456789";
static const char _origin_2[] = "abcdefghi0123456789";
static const char _target_2[] = "ihgfedcba9876543210";
static map<char, char> _m1_map;
static map<char, char> _m2_map;
string mirror4uccimove(const string& ucci, uint mirror)
{
if (_m1_map.empty())
{
for (uint i = 0; i < (sizeof(_origin_1) / sizeof(_origin_1[0])); ++i)
_m1_map[_origin_1[i]] = _target_1[i];
for (uint i = 0; i < (sizeof(_origin_2) / sizeof(_origin_2[0])); ++i)
_m2_map[_origin_2[i]] = _target_2[i];
}
assert(mirror < 4);
string ret = ucci;
if (mirror & 1)
{
for (string::iterator itr = ret.begin(); itr != ret.end(); ++itr)
*itr = _m1_map[*itr];
}
if (mirror & 2)
{
for (string::iterator itr = ret.begin(); itr != ret.end(); ++itr)
*itr = _m2_map[*itr];
}
return ret;
}
}//namespace folium
| [
"lwm3751@cb49bd84-cb2d-0410-93fd-e1760d46b244"
] | [
[
[
1,
66
]
]
] |
4f7413a976c7c8b6230861a55ef87212ba6bf03d | 7b4e708809905ae003d0cb355bf53e4d16c9cbbc | /JuceLibraryCode/modules/juce_audio_utils/gui/juce_MidiKeyboardComponent.cpp | e08b20bffd80d2ef93e9ca72893920f8dfe77276 | [] | no_license | sonic59/JulesText | ce6507014e4cba7fb0b67597600d1cee48a973a5 | 986cbea68447ace080bf34ac2b94ac3ab46faca4 | refs/heads/master | 2016-09-06T06:10:01.815928 | 2011-11-18T01:19:26 | 2011-11-18T01:19:26 | 2,796,827 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,949 | cpp | /*
==============================================================================
This file is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-11 by Raw Material Software Ltd.
------------------------------------------------------------------------------
JUCE can be redistributed and/or modified under the terms of the GNU General
Public License (Version 2), as published by the Free Software Foundation.
A copy of the license is included in the JUCE distribution, or can be found
online at www.gnu.org/licenses.
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.rawmaterialsoftware.com/juce for more information.
==============================================================================
*/
BEGIN_JUCE_NAMESPACE
//==============================================================================
class MidiKeyboardUpDownButton : public Button
{
public:
MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
: Button (String::empty),
owner (owner_),
delta (delta_)
{
setOpaque (true);
}
void clicked()
{
int note = owner.getLowestVisibleKey();
if (delta < 0)
note = (note - 1) / 12;
else
note = note / 12 + 1;
owner.setLowestVisibleKey (note * 12);
}
void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
{
owner.drawUpDownButton (g, getWidth(), getHeight(),
isMouseOverButton, isButtonDown,
delta > 0);
}
private:
MidiKeyboardComponent& owner;
const int delta;
JUCE_DECLARE_NON_COPYABLE (MidiKeyboardUpDownButton);
};
//==============================================================================
MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
const Orientation orientation_)
: state (state_),
xOffset (0),
blackNoteLength (1),
keyWidth (16.0f),
orientation (orientation_),
midiChannel (1),
midiInChannelMask (0xffff),
velocity (1.0f),
noteUnderMouse (-1),
mouseDownNote (-1),
rangeStart (0),
rangeEnd (127),
firstKey (12 * 4),
canScroll (true),
mouseDragging (false),
useMousePositionForVelocity (true),
keyMappingOctave (6),
octaveNumForMiddleC (3)
{
addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
// initialise with a default set of querty key-mappings..
const char* const keymap = "awsedftgyhujkolp;";
for (int i = String (keymap).length(); --i >= 0;)
setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
setOpaque (true);
setWantsKeyboardFocus (true);
state.addListener (this);
}
MidiKeyboardComponent::~MidiKeyboardComponent()
{
state.removeListener (this);
jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
}
//==============================================================================
void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
{
keyWidth = widthInPixels;
resized();
}
void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
{
if (orientation != newOrientation)
{
orientation = newOrientation;
resized();
}
}
void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
const int highestNote)
{
jassert (lowestNote >= 0 && lowestNote <= 127);
jassert (highestNote >= 0 && highestNote <= 127);
jassert (lowestNote <= highestNote);
if (rangeStart != lowestNote || rangeEnd != highestNote)
{
rangeStart = jlimit (0, 127, lowestNote);
rangeEnd = jlimit (0, 127, highestNote);
firstKey = jlimit (rangeStart, rangeEnd, firstKey);
resized();
}
}
void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
{
noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
if (noteNumber != firstKey)
{
firstKey = noteNumber;
sendChangeMessage();
resized();
}
}
void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
{
if (canScroll != canScroll_)
{
canScroll = canScroll_;
resized();
}
}
void MidiKeyboardComponent::colourChanged()
{
repaint();
}
//==============================================================================
void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
{
jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
if (midiChannel != midiChannelNumber)
{
resetAnyKeysInUse();
midiChannel = jlimit (1, 16, midiChannelNumber);
}
}
void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
{
midiInChannelMask = midiChannelMask;
triggerAsyncUpdate();
}
void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
{
velocity = jlimit (0.0f, 1.0f, velocity_);
useMousePositionForVelocity = useMousePositionForVelocity_;
}
//==============================================================================
void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
{
jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
static const float blackNoteWidth = 0.7f;
static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
1.0f, 2 - blackNoteWidth * 0.4f,
2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
4.0f, 5 - blackNoteWidth * 0.5f,
5.0f, 6 - blackNoteWidth * 0.3f,
6.0f };
static const float widths[] = { 1.0f, blackNoteWidth,
1.0f, blackNoteWidth,
1.0f, 1.0f, blackNoteWidth,
1.0f, blackNoteWidth,
1.0f, blackNoteWidth,
1.0f };
const int octave = midiNoteNumber / 12;
const int note = midiNoteNumber % 12;
x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
w = roundToInt (widths [note] * keyWidth_);
}
void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
{
getKeyPosition (midiNoteNumber, keyWidth, x, w);
int rx, rw;
getKeyPosition (rangeStart, keyWidth, rx, rw);
x -= xOffset + rx;
}
int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
{
int x, y;
getKeyPos (midiNoteNumber, x, y);
return x;
}
const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
{
if (! reallyContains (pos, false))
return -1;
Point<int> p (pos);
if (orientation != horizontalKeyboard)
{
p = Point<int> (p.y, p.x);
if (orientation == verticalKeyboardFacingLeft)
p = Point<int> (p.x, getWidth() - p.y);
else
p = Point<int> (getHeight() - p.x, p.y);
}
return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
}
int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
{
if (pos.getY() < blackNoteLength)
{
for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
{
for (int i = 0; i < 5; ++i)
{
const int note = octaveStart + blackNotes [i];
if (note >= rangeStart && note <= rangeEnd)
{
int kx, kw;
getKeyPos (note, kx, kw);
kx += xOffset;
if (pos.x >= kx && pos.x < kx + kw)
{
mousePositionVelocity = pos.y / (float) blackNoteLength;
return note;
}
}
}
}
}
for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
{
for (int i = 0; i < 7; ++i)
{
const int note = octaveStart + whiteNotes [i];
if (note >= rangeStart && note <= rangeEnd)
{
int kx, kw;
getKeyPos (note, kx, kw);
kx += xOffset;
if (pos.x >= kx && pos.x < kx + kw)
{
const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
mousePositionVelocity = pos.y / (float) whiteNoteLength;
return note;
}
}
}
}
mousePositionVelocity = 0;
return -1;
}
//==============================================================================
void MidiKeyboardComponent::repaintNote (const int noteNum)
{
if (noteNum >= rangeStart && noteNum <= rangeEnd)
{
int x, w;
getKeyPos (noteNum, x, w);
if (orientation == horizontalKeyboard)
repaint (x, 0, w, getHeight());
else if (orientation == verticalKeyboardFacingLeft)
repaint (0, x, getWidth(), w);
else if (orientation == verticalKeyboardFacingRight)
repaint (0, getHeight() - x - w, getWidth(), w);
}
}
void MidiKeyboardComponent::paint (Graphics& g)
{
g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
const Colour lineColour (findColour (keySeparatorLineColourId));
const Colour textColour (findColour (textLabelColourId));
int x, w, octave;
for (octave = 0; octave < 128; octave += 12)
{
for (int white = 0; white < 7; ++white)
{
const int noteNum = octave + whiteNotes [white];
if (noteNum >= rangeStart && noteNum <= rangeEnd)
{
getKeyPos (noteNum, x, w);
if (orientation == horizontalKeyboard)
drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
state.isNoteOnForChannels (midiInChannelMask, noteNum),
noteUnderMouse == noteNum,
lineColour, textColour);
else if (orientation == verticalKeyboardFacingLeft)
drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
state.isNoteOnForChannels (midiInChannelMask, noteNum),
noteUnderMouse == noteNum,
lineColour, textColour);
else if (orientation == verticalKeyboardFacingRight)
drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
state.isNoteOnForChannels (midiInChannelMask, noteNum),
noteUnderMouse == noteNum,
lineColour, textColour);
}
}
}
float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
if (orientation == verticalKeyboardFacingLeft)
{
x1 = getWidth() - 1.0f;
x2 = getWidth() - 5.0f;
}
else if (orientation == verticalKeyboardFacingRight)
x2 = 5.0f;
else
y2 = 5.0f;
g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
Colours::transparentBlack, x2, y2, false));
getKeyPos (rangeEnd, x, w);
x += w;
if (orientation == verticalKeyboardFacingLeft)
g.fillRect (getWidth() - 5, 0, 5, x);
else if (orientation == verticalKeyboardFacingRight)
g.fillRect (0, 0, 5, x);
else
g.fillRect (0, 0, x, 5);
g.setColour (lineColour);
if (orientation == verticalKeyboardFacingLeft)
g.fillRect (0, 0, 1, x);
else if (orientation == verticalKeyboardFacingRight)
g.fillRect (getWidth() - 1, 0, 1, x);
else
g.fillRect (0, getHeight() - 1, x, 1);
const Colour blackNoteColour (findColour (blackNoteColourId));
for (octave = 0; octave < 128; octave += 12)
{
for (int black = 0; black < 5; ++black)
{
const int noteNum = octave + blackNotes [black];
if (noteNum >= rangeStart && noteNum <= rangeEnd)
{
getKeyPos (noteNum, x, w);
if (orientation == horizontalKeyboard)
drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
state.isNoteOnForChannels (midiInChannelMask, noteNum),
noteUnderMouse == noteNum,
blackNoteColour);
else if (orientation == verticalKeyboardFacingLeft)
drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
state.isNoteOnForChannels (midiInChannelMask, noteNum),
noteUnderMouse == noteNum,
blackNoteColour);
else if (orientation == verticalKeyboardFacingRight)
drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
state.isNoteOnForChannels (midiInChannelMask, noteNum),
noteUnderMouse == noteNum,
blackNoteColour);
}
}
}
}
void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
Graphics& g, int x, int y, int w, int h,
bool isDown, bool isOver,
const Colour& lineColour,
const Colour& textColour)
{
Colour c (Colours::transparentWhite);
if (isDown)
c = findColour (keyDownOverlayColourId);
if (isOver)
c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
g.setColour (c);
g.fillRect (x, y, w, h);
const String text (getWhiteNoteText (midiNoteNumber));
if (! text.isEmpty())
{
g.setColour (textColour);
Font f (jmin (12.0f, keyWidth * 0.9f));
f.setHorizontalScale (0.8f);
g.setFont (f);
Justification justification (Justification::centredBottom);
if (orientation == verticalKeyboardFacingLeft)
justification = Justification::centredLeft;
else if (orientation == verticalKeyboardFacingRight)
justification = Justification::centredRight;
g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
}
g.setColour (lineColour);
if (orientation == horizontalKeyboard)
g.fillRect (x, y, 1, h);
else if (orientation == verticalKeyboardFacingLeft)
g.fillRect (x, y, w, 1);
else if (orientation == verticalKeyboardFacingRight)
g.fillRect (x, y + h - 1, w, 1);
if (midiNoteNumber == rangeEnd)
{
if (orientation == horizontalKeyboard)
g.fillRect (x + w, y, 1, h);
else if (orientation == verticalKeyboardFacingLeft)
g.fillRect (x, y + h, w, 1);
else if (orientation == verticalKeyboardFacingRight)
g.fillRect (x, y - 1, w, 1);
}
}
void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
Graphics& g, int x, int y, int w, int h,
bool isDown, bool isOver,
const Colour& noteFillColour)
{
Colour c (noteFillColour);
if (isDown)
c = c.overlaidWith (findColour (keyDownOverlayColourId));
if (isOver)
c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
g.setColour (c);
g.fillRect (x, y, w, h);
if (isDown)
{
g.setColour (noteFillColour);
g.drawRect (x, y, w, h);
}
else
{
const int xIndent = jmax (1, jmin (w, h) / 8);
g.setColour (c.brighter());
if (orientation == horizontalKeyboard)
g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
else if (orientation == verticalKeyboardFacingLeft)
g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
else if (orientation == verticalKeyboardFacingRight)
g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
}
}
void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
{
octaveNumForMiddleC = octaveNumForMiddleC_;
repaint();
}
String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
{
if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
return String::empty;
}
void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
const bool isMouseOver_,
const bool isButtonDown,
const bool movesOctavesUp)
{
g.fillAll (findColour (upDownButtonBackgroundColourId));
float angle;
if (orientation == MidiKeyboardComponent::horizontalKeyboard)
angle = movesOctavesUp ? 0.0f : 0.5f;
else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
angle = movesOctavesUp ? 0.25f : 0.75f;
else
angle = movesOctavesUp ? 0.75f : 0.25f;
Path path;
path.lineTo (0.0f, 1.0f);
path.lineTo (1.0f, 0.5f);
path.closeSubPath();
path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
g.setColour (findColour (upDownButtonArrowColourId)
.withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
w - 2.0f,
h - 2.0f,
true));
}
void MidiKeyboardComponent::resized()
{
int w = getWidth();
int h = getHeight();
if (w > 0 && h > 0)
{
if (orientation != horizontalKeyboard)
std::swap (w, h);
blackNoteLength = roundToInt (h * 0.7f);
int kx2, kw2;
getKeyPos (rangeEnd, kx2, kw2);
kx2 += kw2;
if (firstKey != rangeStart)
{
int kx1, kw1;
getKeyPos (rangeStart, kx1, kw1);
if (kx2 - kx1 <= w)
{
firstKey = rangeStart;
sendChangeMessage();
repaint();
}
}
const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
scrollDown->setVisible (showScrollButtons);
scrollUp->setVisible (showScrollButtons);
xOffset = 0;
if (showScrollButtons)
{
const int scrollButtonW = jmin (12, w / 2);
if (orientation == horizontalKeyboard)
{
scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
}
else if (orientation == verticalKeyboardFacingLeft)
{
scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
}
else if (orientation == verticalKeyboardFacingRight)
{
scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
}
int endOfLastKey, kw;
getKeyPos (rangeEnd, endOfLastKey, kw);
endOfLastKey += kw;
float mousePositionVelocity;
const int spaceAvailable = w - scrollButtonW * 2;
const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
if (lastStartKey >= 0 && firstKey > lastStartKey)
{
firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
sendChangeMessage();
}
int newOffset = 0;
getKeyPos (firstKey, newOffset, kw);
xOffset = newOffset - scrollButtonW;
}
else
{
firstKey = rangeStart;
}
timerCallback();
repaint();
}
}
//==============================================================================
void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
{
triggerAsyncUpdate();
}
void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
{
triggerAsyncUpdate();
}
void MidiKeyboardComponent::handleAsyncUpdate()
{
for (int i = rangeStart; i <= rangeEnd; ++i)
{
if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
{
keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
repaintNote (i);
}
}
}
//==============================================================================
void MidiKeyboardComponent::resetAnyKeysInUse()
{
if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
{
state.allNotesOff (midiChannel);
keysPressed.clear();
mouseDownNote = -1;
}
}
void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
{
float mousePositionVelocity = 0.0f;
const int newNote = (mouseDragging || isMouseOver())
? xyToNote (pos, mousePositionVelocity) : -1;
if (noteUnderMouse != newNote)
{
if (mouseDownNote >= 0)
{
state.noteOff (midiChannel, mouseDownNote);
mouseDownNote = -1;
}
if (mouseDragging && newNote >= 0)
{
if (! useMousePositionForVelocity)
mousePositionVelocity = 1.0f;
state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
mouseDownNote = newNote;
}
repaintNote (noteUnderMouse);
noteUnderMouse = newNote;
repaintNote (noteUnderMouse);
}
else if (mouseDownNote >= 0 && ! mouseDragging)
{
state.noteOff (midiChannel, mouseDownNote);
mouseDownNote = -1;
}
}
void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
{
updateNoteUnderMouse (e.getPosition());
stopTimer();
}
void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
{
float mousePositionVelocity;
const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
if (newNote >= 0)
mouseDraggedToKey (newNote, e);
updateNoteUnderMouse (e.getPosition());
}
bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
{
return true;
}
void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
{
}
void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
{
float mousePositionVelocity;
const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
mouseDragging = false;
if (newNote >= 0 && mouseDownOnKey (newNote, e))
{
repaintNote (noteUnderMouse);
noteUnderMouse = -1;
mouseDragging = true;
updateNoteUnderMouse (e.getPosition());
startTimer (500);
}
}
void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
{
mouseDragging = false;
updateNoteUnderMouse (e.getPosition());
stopTimer();
}
void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
{
updateNoteUnderMouse (e.getPosition());
}
void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
{
updateNoteUnderMouse (e.getPosition());
}
void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
{
setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
}
void MidiKeyboardComponent::timerCallback()
{
updateNoteUnderMouse (getMouseXYRelative());
}
//==============================================================================
void MidiKeyboardComponent::clearKeyMappings()
{
resetAnyKeysInUse();
keyPressNotes.clear();
keyPresses.clear();
}
void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
const int midiNoteOffsetFromC)
{
removeKeyPressForNote (midiNoteOffsetFromC);
keyPressNotes.add (midiNoteOffsetFromC);
keyPresses.add (key);
}
void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
{
for (int i = keyPressNotes.size(); --i >= 0;)
{
if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
{
keyPressNotes.remove (i);
keyPresses.remove (i);
}
}
}
void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
{
jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
keyMappingOctave = newOctaveNumber;
}
bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
{
bool keyPressUsed = false;
for (int i = keyPresses.size(); --i >= 0;)
{
const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
if (keyPresses.getReference(i).isCurrentlyDown())
{
if (! keysPressed [note])
{
keysPressed.setBit (note);
state.noteOn (midiChannel, note, velocity);
keyPressUsed = true;
}
}
else
{
if (keysPressed [note])
{
keysPressed.clearBit (note);
state.noteOff (midiChannel, note);
keyPressUsed = true;
}
}
}
return keyPressUsed;
}
void MidiKeyboardComponent::focusLost (FocusChangeType)
{
resetAnyKeysInUse();
}
END_JUCE_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
867
]
]
] |
11858c197d2acf418497b1ee6d893a2da8c6071e | 975d45994f670a7f284b0dc88d3a0ebe44458a82 | /servidor/WarBugsServer/WarBugsServer/CDataBase.cpp | 4a747cffe9f91818f8e3054d4deeca7e4f26c9ea | [] | no_license | phabh/warbugs | 2b616be17a54fbf46c78b576f17e702f6ddda1e6 | bf1def2f8b7d4267fb7af42df104e9cdbe0378f8 | refs/heads/master | 2020-12-25T08:51:02.308060 | 2010-11-15T00:37:38 | 2010-11-15T00:37:38 | 60,636,297 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,545 | cpp | #include "CDataBase.h"
#include "commom.h"
//Metodos
/*
Construtor padrão
*/
CDataBase::CDataBase()
{
_connection = mysql_init(NULL);
}
/*
Construtor Secundário
Ele ja cria a conexão com o BD
@param host - IP da máquina onde estará o BD
@param bd - Nome do BD
@param user - Nome Usuario do BD
@param password - Senha BD
*/
CDataBase::CDataBase(char *host, char *bd, char *user, char *password)
{
_connection = mysql_init(NULL);
_connected = connectNow(host,bd,user,password);
}
/*
Cria a Conexão com o BD
@param host - IP da máquina onde estará o BD
@param bd - Nome do BD
@param user - Nome Usuario do BD
@param password - Senha BD
@return true se a conexão ocorreu
*/
bool CDataBase::connectNow(char *host, char *bd, char *user, char *password)
{
_host = host;
_dataBase = bd;
_user = user;
_password = password;
_connected = mysql_real_connect(_connection,host,user,password,bd,0,NULL,0) != NULL;
System::String ^ temp = gcnew System::String(mysql_error(_connection));
WarBugsLog::_log->Items->Add(L"Erro: "+temp);
return (_connected);
}
/*
Cria uma consulta com o BD
@param query - Instrução SQL;
@param numFields - numero de campos que a linha possui
@param numRegs - numero de registros que foram selecionados
@param - retorna as informações todas as linhas com seus respectivos dados
*/
bool CDataBase::selectNow(char *query, unsigned int &numFields, unsigned int &numRegs, TDadosBD ^dados)
{
bool resultado = false;
numFields = 0;
numRegs = 0;
if(_connected)
{
if(strlen(query) > 0)
{
mysql_query(_connection,query);
}
_resultSet = mysql_store_result(_connection);
if(_resultSet != NULL)
{
numRegs = (unsigned)mysql_num_rows(_resultSet);
numFields = mysql_num_fields(_resultSet);
MYSQL_FIELD * campo;
System::String ^ teste;
while((campo = mysql_fetch_field(_resultSet)))
{
char * tex = campo->name;
teste = gcnew System::String(tex);
dados->Add(teste);
}
while((_row = mysql_fetch_row(_resultSet)))
{
for(unsigned int i = 0; i < numFields; i++)
{
//dado = _row[i];
teste = gcnew System::String(_row[i]);
dados->Add(teste);
}
}
resultado = true;
}
mysql_free_result(_resultSet);
}
return resultado;
}
/*
Insere dados no BD
@param query - Instrução de inserção
@return - se a instrução foi executada com sucesso
*/
bool CDataBase::insertNow(char *query)
{
bool resultado = false;
if(_connected)
{
if(strlen(query) > 0)
{
int res = mysql_query(_connection,query);
resultado = res == 0;
WarBugsLog::_log->Items->Add(gcnew System::String(mysql_error(_connection)));
}
}
return resultado;
}
/*
Deleta dados do BD
@param query - Instrução de inserção
@return - se a instrução foi executada com sucesso
*/
bool CDataBase::deleteNow(char *query)
{
return insertNow(query);
}
/*
Altera dados do BD
@param query - Instrução de inserção
@return - se a instrução foi executada com sucesso
*/
bool CDataBase::updateNow(char *query)
{
return insertNow(query);
}
/*
Fecha a conexão com o banco de dados
*/
void CDataBase::closeNow()
{
mysql_close(_connection);
}
/*
Verifica se está conectado com o bd
*/
bool CDataBase::isConnected()
{
_connected = mysql_ping(_connection) == 0;
return _connected;
} | [
"[email protected]"
] | [
[
[
1,
164
]
]
] |
e5c5116ad4f9c23d1401d5260249b793cc6f82f5 | c497f6d85bdbcbb21e93ae701c5570f16370f0ae | /Sync/Lets_try_all_engine/backup/trrr/SatDb.hpp | c4d0672540517aeceba85a0be7f0a86ab40054ed | [] | no_license | mfkiwl/gpsgyan_fork | 91b380cf3cfedb5d1aac569c6284bbf34c047573 | f7c850216c16b49e01a0653b70c1905b5b6c2587 | refs/heads/master | 2021-10-15T08:32:53.606124 | 2011-01-19T16:24:18 | 2011-01-19T16:24:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,323 | hpp | /* * File name : SatDb.hpp
*
* Abstract : This file contains definitions of structures and Global classes
* Struchers used in the Gpsgyan project.
*
* Compiler : Visual C++ Version 9.0
*
* Compiler options : Default
*
* Pragmas : None used
*
* H/W Platform : IBM PC
*
* Portability : No Operating system call used.
* No machine specific instruction used.
* No compiler specific routines used.
* Hence Portable.
*
* Authors : Priyank Kumar
*
*
* Version history : Base version
* Priyank Kumar November 2009
*
* References : None
*
* Functions called : None
* Library Used : GPStk
* Copyright 2009, The University of Texas at Austin
*
*/
/* GPSTk Library*/
#include "YumaAlmanacStore.hpp"
#include "AlmOrbit.hpp"
#include "DayTime.hpp"
#include "SatID.hpp"
#include "EphReader.hpp"
#include "MSCData.hpp"
#include "MSCStream.hpp"
#include "FFIdentifier.hpp"
#include "Position.hpp"
#include "SatDbMac.hpp"
#include "SatDbtypes.hpp"
/*C++ Systems Include files*/
#include <iostream>
#include <string>
#include <map>
#include <vector>
/*GPSGyan Include files*/
#include "EngineFramework.hpp"
using namespace gpstk;
class SatDb: public EngineFramework
{
public:
NEW_EXCEPTION_CLASS(ExcSatDb , gpstk::Exception);
SatDb(const string& applName) throw()
: EngineFramework(
applName,
"this computes satellite Position , Velocity and time for the specified receiever position and time")
{};
// bool initialize(int argc, char *argv[]) throw();
// virtual void process();
void GetPassiveInput();
void GetActiveInput();
void GetPassiveParam();
void GetActiveParam();
void InputInfToEngine(Kind kind); // think of argv and argc implementation
//virtual void runEngine();
void InputParamToEngine(Kind kind);// throw(InvalidParameter);
//bool runEngine() throw();
//void outputInfFromEngine(std::ostream & s ,const std::string & data);
void outputInfFromEngine(std::ostream & s );
//void OutputDumpOfEngine();
// Public Data memebers
engineHealthMonitor satDb_probe;
std::vector<satDb_ostruct> satDb_oData;
string yumaFileName;
DayTime inp_time ;
double usr_elev;
std::vector<int> error_number;
//std::string op_inf;
protected :
//void EngineControl(Kind kind);
void VerifyIpToEngine() throw(ExcSatDb);
// void prepareIpToEngine() ;
void MethodOfEngine() throw(ExcSatDb);
void getSatParam(SatID sat, DayTime& t ,const YumaAlmanacStore& yums);
void SatDb_ExpHandler(ExcSatDb &e);
// Fromatted File Printing
std::string print_content(satDb_ostruct &ostruct);
std::string print_header();
// void validateOpOfEngine();
// void PrepareOpOfEngine() ;
//virtual void dump(std::ostream &s);
private :
EphReader yumaReader; // Reads all type of possible input file ( YUMA , Sem, RINEX etc , currently implemented for YUMA)
DayTime satTime;
SatID gps_sv;
std::vector<satDb_ostruct> satDb_pData;
Xvt sv_xvt;
// Error Value
double minElev;
};
| [
"priyankguddu@6c0848c6-feae-43ef-b685-015bb26c21a7"
] | [
[
[
1,
138
]
]
] |
5c810dc4faa24cfbdf28c154183dd6aecc4b84a8 | 252e638cde99ab2aa84922a2e230511f8f0c84be | /toollib/src/ErrorMessageDialogForm.h | fcb692d75ea7c94eea02b33fde12ede9875f068e | [] | no_license | openlab-vn-ua/tour | abbd8be4f3f2fe4d787e9054385dea2f926f2287 | d467a300bb31a0e82c54004e26e47f7139bd728d | refs/heads/master | 2022-10-02T20:03:43.778821 | 2011-11-10T12:58:15 | 2011-11-10T12:58:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,258 | h | //---------------------------------------------------------------------------
#ifndef ErrorMessageDialogFormH
#define ErrorMessageDialogFormH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "VStringStorage.h"
//---------------------------------------------------------------------------
class TTourErrorMessageDialogForm : public TForm
{
__published: // IDE-managed Components
TLabel *ErrorMessageLabel;
TButton *DetailsButton;
TMemo *DetailsMemo;
TVStringStorage *VStringStorage;
TButton *CloseButton;
void __fastcall DetailsButtonClick(TObject *Sender);
void __fastcall FormCreate(TObject *Sender);
void __fastcall FormDestroy(TObject *Sender);
private: // User declarations
bool DialogDetailsFlag;
int StoredFormHeight;
void UpdateByDetailsFlags();
public: // User declarations
__fastcall TTourErrorMessageDialogForm(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TTourErrorMessageDialogForm *TourErrorMessageDialogForm;
//---------------------------------------------------------------------------
#endif
| [
"[email protected]"
] | [
[
[
1,
34
]
]
] |
497551ffd1fa34bd2e790379e3cf90d2bdb2b448 | 5236606f2e6fb870fa7c41492327f3f8b0fa38dc | /srpc/include/srpc/detail/RpcEvent.h | 14fba7e3e95684c6edd2b003470743bb8c35cc04 | [] | no_license | jcloudpld/srpc | aa8ecf4ffc5391b7183b19d217f49fb2b1a67c88 | f2483c8177d03834552053e8ecbe788e15b92ac0 | refs/heads/master | 2021-01-10T08:54:57.140800 | 2010-02-08T07:03:00 | 2010-02-08T07:03:00 | 44,454,693 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,066 | h | #ifndef SRPC_RPCEVENT_H
#define SRPC_RPCEVENT_H
#ifdef _MSC_VER
# pragma once
#endif
#include "ReceivingFunctors.h"
#include "RpcId.h"
#include <boost/noncopyable.hpp>
#include <memory>
namespace srpc {
class IStream;
/** @addtogroup RpcReceiving
* @{
*/
/**
* @class RpcEvent
*
* rpc event(response)
*/
class RpcEvent : public boost::noncopyable
{
public:
RpcEvent(const RRpcId& rpcId) :
rpcId_(rpcId) {}
virtual ~RpcEvent() {}
void dispatch(void* rpcClassThisPtr, IStream& istream,
const void* rpcHint = 0) {
ReceivingFunctor& dispatcher = getDispatcher();
dispatcher.unmarshal(istream);
dispatcher.call(rpcClassThisPtr, rpcHint);
}
const RRpcId& getRpcId() const {
return rpcId_;
}
public:
virtual std::auto_ptr<RpcEvent> clone() const = 0;
virtual ReceivingFunctor& getDispatcher() = 0;
private:
const RRpcId& rpcId_;
};
/** @} */ // addtogroup RpcReceiving
} // namespace srpc
#endif // SRPC_RPCEVENT_H
| [
"kcando@6d7ccee0-1a3b-0410-bfa1-83648d9ec9a4"
] | [
[
[
1,
56
]
]
] |
a463787da795c18ba1d2e1bd1c848f286222a565 | 27b8c57bef3eb26b5e7b4b85803a8115e5453dcb | /trunk/lib/include/Control/Utility/EnvironmentWrapper.h | 3687012da64295f9a80ca0a0d973259fd55af1ce | [] | no_license | BackupTheBerlios/walker-svn | 2576609a17eab7a08bb2437119ef162487444f19 | 66ae38b2c1210ac2f036e43b5f0a96013a8e3383 | refs/heads/master | 2020-05-30T11:30:48.193275 | 2011-03-24T17:10:17 | 2011-03-24T17:10:17 | 40,819,670 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,095 | h | #ifndef __WALKER_YARD_CONTROL_UTILITY_RL_ENVIRONMENT_WRAPPER_H___
#define __WALKER_YARD_CONTROL_UTILITY_RL_ENVIRONMENT_WRAPPER_H___
namespace ctrl
{
template<typename Environment>
class environment_wrapper
{
public:
typedef Environment environment_type;
typedef boost::intrusive_ptr<Environment> environment_ptr;
public:
environment_wrapper(environment_ptr env_)
: env(env_)
{}
// Implement Environment
size_t state_size() const { return env->stateSize; }
size_t action_size() const { return env->actionSize; }
template<typename T>
T sgn(T val)
{
if (val > T(0)) return T(1);
if (val < T(0)) return T(-1);
return T(0);
}
template<typename InIterator>
float perform_action(InIterator firstPin, InIterator endPin, bool nowait = false)
{
size_t i = 0;
for (InIterator pin = firstPin; pin != endPin; ++pin, ++i)
{
float force = float(*pin);
if (force > 1.0f) {
force = 1.0f;
}
else if (force < -1.0f) {
force = -1.0f;
}
if ( env->getControlType() == PhysicsEnvironment::CONTROL_VELOCITY ) {
env->targetVelocity[i] = force * env->maxVelocity;
}
else {
env->targetForce[i] = force * env->maxForce;
}
}
// wait for action
if (nowait) {
env->makeAction();
}
else
{
boost::unique_lock<boost::mutex> stateLock(env->stateMutex);
env->state = Environment::WAITING_ACTION;
env->actionReadyCondition.wait( stateLock, boost::bind(boost::bind(&environment_type::state, env) == Environment::READY) );
}
// wait for reward
if (nowait) {
env->makeReward();
}
else
{
boost::unique_lock<boost::mutex> stateLock(env->stateMutex);
env->state = Environment::WAITING_REWARD;
env->rewardReadyCondition.wait( stateLock, boost::bind(boost::bind(&environment_type::state, env) == Environment::READY) );
}
env->state = Environment::READY;
return env->reward;
}
template<typename OutIterator>
bool query_state(OutIterator stateOut, bool nowait = false)
{
using namespace math;
// wait for state
if (nowait) {
env->makeState();
}
else
{
boost::unique_lock<boost::mutex> lock(env->stateMutex);
env->state = Environment::WAITING_STATE;
env->stateReadyCondition.wait( lock, boost::bind(boost::bind(&environment_type::state, env) == Environment::READY) );
}
//// copy base body orientation
//{
// *stateOut++ = rotation.x;
// *stateOut++ = rotation.y;
// *stateOut++ = rotation.z;
// *stateOut++ = angVelocity.x;
// *stateOut++ = angVelocity.y;
// *stateOut++ = angVelocity.z;
//}
// copy state
for (size_t i = 0; i<env->motors.size(); ++i)
{
physics::real hi = env->motors[i]->getHiLimit();
physics::real lo = env->motors[i]->getLoLimit();
if (hi > lo) {
*stateOut++ = physics::real(2.0) * (env->position[i] - lo) / (hi - lo) - physics::real(1.0);
}
else {
*stateOut++ = env->position[i] / math::PI - physics::real(1.0);
}
//*stateOut++ = 2.0f * std::min(std::max(env->constraintVelocities[i].x, -env->maxVelocity), env->maxVelocity) / env->maxVelocity - 1.0f;
//*stateOut++ = 2.0f * std::min(std::max(env->constraintVelocities[i].y, -env->maxVelocity), env->maxVelocity) / env->maxVelocity - 1.0f;
}
return env->terminal;
}
private:
environment_ptr env;
};
} // namespace ctrl
#endif // __WALKER_YARD_CONTROL_UTILITY_RL_ENVIRONMENT_WRAPPER_H___ | [
"dikobraz@9454499b-da03-4d27-8628-e94e5ff957f9"
] | [
[
[
1,
132
]
]
] |
80abc74ca0303d7d173c4d8f4a876d766ac98e87 | dde32744a06bb6697823975956a757bd6c666e87 | /bwapi/SCProjects/BTHAIModule/Source/ZerglingAgent.cpp | 1e8c5b22a51b450f8ef54ee83cc8bde4ac71e6e9 | [] | no_license | zarac/tgspu-bthai | 30070aa8f72585354ab9724298b17eb6df4810af | 1c7e06ca02e8b606e7164e74d010df66162c532f | refs/heads/master | 2021-01-10T21:29:19.519754 | 2011-11-16T16:21:51 | 2011-11-16T16:21:51 | 2,533,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 800 | cpp | #include "ZerglingAgent.h"
#include "PFManager.h"
#include "AgentManager.h"
ZerglingAgent::ZerglingAgent(Unit* mUnit) {
unit = mUnit;
unitID = unit->getID();
//Broodwar->printf("ZealotAgent created (%s)", unit->getType().getName().c_str());
lastFrame = 0;
goal = TilePosition(-1, -1);
}
void ZerglingAgent::computeActions() {
int cFrame = Broodwar->getFrameCount();
if (cFrame - lastFrame < 20) {
return;
}
lastFrame = cFrame;
if (currentState != EXPLORE) {
bool defensive = false;
//TODO: Add unitspecific code here
PFManager::getInstance()->computeAttackingUnitActions(this, goal, defensive);
}
else {
if (goal.x() >= 0) {
unit->rightClick(Position(goal));
}
}
}
string ZerglingAgent::getTypeName() {
return "ZerglingAgent";
} | [
"[email protected]"
] | [
[
[
1,
37
]
]
] |
712ca9ff06f7db67cb1cc5600eb9572ffa66cc5e | 3ea6d378a57e4a62be5b6e14138e2ac3212bdd6c | /unsorted/codejam/alien_numbers/util.h | 927b0b5e9c3056942e5e0b2e0623c6796603a76b | [] | no_license | stevenc49/dotcsc | 8f8bcac83c8bdf2a5a9a3920455444563f0268c3 | 52d40c8a2b167bdeeed5f22f2d48a43e4e6470a7 | refs/heads/master | 2021-01-23T03:05:11.732403 | 2010-04-10T05:27:30 | 2010-04-10T05:27:30 | 39,530,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 248 | h |
#include <string>
#include <strstream>
using namespace std;
template<class Source>
string ToString(const Source& Value)
{
strstream ss;
ss << Value << '\0';
string os = ss.str();
ss.freeze(false);
return os;
}
| [
"stevenc49@bb60cac8-25a5-11de-870d-bbf10152ea7e"
] | [
[
[
1,
15
]
]
] |
bddcd5e971b58f5f2c9ad49ee08354a6343a1c28 | b002ebd2938f8d79c6b09fc652064001a2d92887 | /source/CSave.h | 933096f48bf080cea1ca92161037804d7d51c4d0 | [] | no_license | benbaker76/DetectiveDS | 104a175738970dfd12ea8557685a63245b2a3fbe | ca487610b8088a07fc7fe62e345557ccb9663b20 | refs/heads/master | 2022-11-25T17:22:07.218401 | 2011-07-30T13:13:23 | 2011-07-30T13:13:23 | 241,390,011 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,120 | h | #ifndef __CSAVE_H__
#define __CSAVE_H__
#include <nds.h>
#include "Globals.h"
union IFConvert
{
u32 Int;
float Float;
};
class CCharacter;
class CSprite;
class CRoom;
class CDoor;
class CItem;
class CEvent;
class CTime;
class CSave
{
public:
CSave(int bufferSize, CCharacter** characterArray, CSprite** spriteArray, CRoom** roomArray, CItem** itemArray, CEvent** eventArray);
~CSave();
bool ReadTimeStamp(const char* fileName, CTime* time);
int ReadBuffer(const char* pFileName);
int WriteBuffer(const char* pFileName);
void ClearBuffer();
void ReadUInt64(u64* value);
void ReadUInt32(u32* value);
void ReadUInt16(u16* value);
void ReadByte(byte* value);
void ReadBool(bool* value);
bool ReadBool();
void ReadFloat(float* value);
void ReadString(char* value);
void ReadRect(Rect* pRect);
void ReadPoint(Point* pPoint);
void ReadPointF(PointF* pPointF);
void ReadSize(Size* pSize);
void ReadCharacter(CCharacter** pCharacter);
void ReadRoom(CRoom** pRoom);
void ReadItem(CItem** pItem);
void ReadDoor(CDoor** pDoor);
void ReadPadding(int count);
void WriteUInt64(u64 value);
void WriteUInt32(u32 value);
void WriteUInt16(u16 value);
void WriteByte(byte value);
void WriteBool(bool value);
void WriteFloat(float value);
void WriteString(const char* value);
void WriteRect(Rect* pRect);
void WritePoint(Point* pPoint);
void WritePointF(PointF* pPointF);
void WriteSize(Size* pSize);
void WriteCharacter(CCharacter* pCharacter);
void WriteRoom(CRoom* pRoom);
void WriteItem(CItem* pItem);
void WriteDoor(CDoor* pDoor);
void WritePadding(int count);
void ToString();
void ToString(int start, int size);
int GetBufferPos() const { return m_bufferPos; }
void SetBufferPos(int bufferPos) { m_bufferPos = bufferPos; }
int GetBufferSize() const { return m_bufferSize; }
private:
char *m_pBuffer;
int m_bufferPos;
int m_bufferSize;
CCharacter** m_characterArray;
CSprite** m_spriteArray;
CRoom** m_roomArray;
CItem** m_itemArray;
CEvent** m_eventArray;
};
#endif
| [
"[email protected]"
] | [
[
[
1,
89
]
]
] |
1f94ac42335d30cf8d318aee7b40706479f90d1f | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/test/test/errors_handling_test.cpp | 3d42b836df3e019870396a7e8b10b14fa6262631 | [
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | 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 | 7,071 | cpp | // (C) Copyright Gennadiy Rozental 2001-2006.
// (C) Copyright Beman Dawes 2001.
// 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/test for the library home page.
//
// File : $RCSfile: errors_handling_test.cpp,v $
//
// Version : $Revision: 1.38 $
//
// Description : tests an ability of Unit Test Framework to catch all kinds
// of test errors in a user code and properly report it.
// ***************************************************************************
// Boost.Test
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/output_test_stream.hpp>
#include <boost/test/unit_test_log.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/framework.hpp>
#include <boost/test/detail/unit_test_parameters.hpp>
#include <boost/test/output/compiler_log_formatter.hpp>
#include <boost/test/results_reporter.hpp>
// STL
#include <iostream>
#include <stdexcept>
using namespace boost::unit_test;
using namespace boost::test_tools;
#if defined(__GNUC__) || defined(__SUNPRO_CC) || defined(__DECCXX_VER)
#define LIMITED_TEST
#endif
namespace {
struct this_test_log_formatter : public boost::unit_test::output::compiler_log_formatter
{
void print_prefix( std::ostream& output, boost::unit_test::const_string, std::size_t line )
{
output << line << ": ";
}
void test_unit_finish( std::ostream& output, test_unit const& tu, unsigned long elapsed )
{
output << "Leaving test " << tu.p_type_name << " \"" << tu.p_name << "\"" << std::endl;
}
};
//____________________________________________________________________________//
char const* log_level_name[] = {
"log_successful_tests",
"log_test_suites",
"log_messages",
"log_warnings",
"log_all_errors",
"log_cpp_exception_errors",
"log_system_errors",
"log_fatal_errors",
"log_nothing"
};
enum error_type_enum {
et_begin,
et_none = et_begin,
et_message,
et_warning,
et_user,
et_cpp_exception,
#ifdef LIMITED_TEST
et_fatal_user,
#else
et_system,
et_fatal_user,
et_fatal_system,
#endif
et_end
} error_type;
char const* error_type_name[] = {
"no error", "user message", "user warning",
"user non-fatal error", "cpp exception", " system error",
"user fatal error", "system fatal error"
};
int divide_by_zero = 0;
void error_on_demand()
{
switch( error_type ) {
case et_none:
BOOST_CHECK_MESSAGE( divide_by_zero == 0, "no error" );
break;
case et_message:
BOOST_TEST_MESSAGE( "message" );
break;
case et_warning:
BOOST_WARN_MESSAGE( divide_by_zero != 0, "warning" );
break;
case et_user:
BOOST_ERROR( "non-fatal error" );
break;
case et_fatal_user:
BOOST_FAIL( "fatal error" );
BOOST_ERROR( "Should never reach this code!" );
break;
case et_cpp_exception:
BOOST_TEST_CHECKPOINT( "error_on_demand() throw runtime_error" );
throw std::runtime_error( "test std::runtime error what() message" );
#ifndef LIMITED_TEST
case et_system:
BOOST_TEST_CHECKPOINT( "error_on_demand() divide by zero" );
divide_by_zero = 1 / divide_by_zero;
break;
case et_fatal_system:
BOOST_TEST_CHECKPOINT( "write to an invalid address" );
{
int* p = 0;
*p = 0;
BOOST_ERROR( "Should never reach this code!" );
}
break;
#endif
default:
BOOST_ERROR( "Should never reach this code!" );
}
return;
}
} // local namespace
//____________________________________________________________________________//
BOOST_AUTO_TEST_CASE( test_errors_handling )
{
#define PATTERN_FILE_NAME "errors_handling_test.pattern"
std::string pattern_file_name(
framework::master_test_suite().argc <= 1
? (runtime_config::save_pattern() ? PATTERN_FILE_NAME : "./test_files/" PATTERN_FILE_NAME)
: framework::master_test_suite().argv[1] );
#ifdef LIMITED_TEST
pattern_file_name += "2";
#endif
output_test_stream test_output( pattern_file_name, !runtime_config::save_pattern() );
test_case* test = BOOST_TEST_CASE( &error_on_demand );
// for each log level
for( log_level level = log_successful_tests;
level <= log_nothing;
level = static_cast<log_level>(level+1) )
{
// for each error type
for( error_type = et_begin;
error_type != et_end;
error_type = static_cast<error_type_enum>(error_type+1) )
{
test_output << "\n===========================\n"
<< "log level: " << log_level_name[level] << ';'
<< " error type: " << error_type_name[error_type] << ";\n" << std::endl;
unit_test_log.set_stream( test_output );
unit_test_log.set_formatter( new this_test_log_formatter );
unit_test_log.set_threshold_level( level );
framework::run( test );
unit_test_log.set_stream( std::cout );
unit_test_log.set_format( runtime_config::log_format() );
unit_test_log.set_threshold_level( runtime_config::log_level() != invalid_log_level
? runtime_config::log_level()
: log_all_errors );
BOOST_CHECK( test_output.match_pattern() );
}
}
}
//____________________________________________________________________________//
// ***************************************************************************
// Revision History :
//
// $Log: errors_handling_test.cpp,v $
// Revision 1.38 2006/03/19 11:49:04 rogeeff
// *** empty log message ***
//
// Revision 1.37 2006/02/01 08:00:15 rogeeff
// *** empty log message ***
//
// Revision 1.36 2005/12/14 06:01:02 rogeeff
// *** empty log message ***
//
// Revision 1.35 2005/06/13 11:46:26 schoepflin
// Use limited tests with Tru64/CXX.
//
// Revision 1.34 2005/06/11 19:20:58 rogeeff
// *** empty log message ***
//
// Revision 1.33 2005/05/11 05:07:56 rogeeff
// licence update
//
// Revision 1.32 2005/03/23 21:06:39 rogeeff
// Sunpro CC 5.3 fixes
//
// Revision 1.31 2005/03/22 07:14:44 rogeeff
// no message
//
// Revision 1.30 2005/02/23 06:36:01 vawjr
// Deleted - extraneous \r characters in the file
//
// Revision 1.29 2005/02/20 08:28:34 rogeeff
// This a major update for Boost.Test framework. See release docs for complete list of fixes/updates
//
// ***************************************************************************
// EOF
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
] | [
[
[
1,
234
]
]
] |
923df009def61d563d62c04491a5827b78056f32 | 881321ed22c5c024aa515e0f152b7f9cc7d1decd | /Pathman/WalkingMovableController.h | 49a97d3ea4ae6b96477c04fad4ee2ce2da742cc0 | [] | no_license | titarenko/Pathman | c37f756c08a1473fc0df561f303942cde97e1d90 | 1c998f57b02576574c48943734fcc0e22e9a63c3 | refs/heads/master | 2020-05-19T08:02:44.881983 | 2011-04-01T20:13:39 | 2011-04-01T20:13:39 | 3,443,429 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | h | #pragma once
#include "MovableController.h"
#include "EDirection.h"
/*!
Controller that forces controlled object to behave very straightforward
walking along a predetermined route.
*/
class WalkingMovableController : MovableController
{
public:
/*!
Creates controller.
@param directions A set of directions defining
controlled object's behaviour.
@param movable Controlled object (can be set up later).
*/
WalkingMovableController(
const irr::core::list<E_DIRECTION>& directions,
Movable* movable = NULL);
~WalkingMovableController(void);
/*!
Implementation of IController.
*/
void refresh();
bool OnEvent(const irr::SEvent& event);
private:
irr::core::list<E_DIRECTION> _directions;
irr::core::list<E_DIRECTION>::ConstIterator _iterator;
}; | [
"[email protected]"
] | [
[
[
1,
35
]
]
] |
26993dc05432535ecf7c2fa101e0ec6d8c7a51e0 | 27c6eed99799f8398fe4c30df2088f30ae317aff | /rtt-tool/qdoc3/location.cpp | 0dd396428a1dd5f4959570e849b4e9c9ecfcc65b | [] | no_license | lit-uriy/ysoft | ae67cd174861e610f7e1519236e94ffb4d350249 | 6c3f077ff00c8332b162b4e82229879475fc8f97 | refs/heads/master | 2021-01-10T08:16:45.115964 | 2009-07-16T00:27:01 | 2009-07-16T00:27:01 | 51,699,806 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,285 | cpp | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#include "config.h"
#include "location.h"
#include <qregexp.h>
#include <qtranslator.h>
#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
QT_BEGIN_NAMESPACE
QT_STATIC_CONST_IMPL Location Location::null;
int Location::tabSize;
QString Location::programName;
QRegExp *Location::spuriousRegExp = 0;
/*!
\class Location
\brief The Location class keeps track of where we are in a file.
It maintains a stack of file positions. A file position
consists of the file path, line number, and column number.
*/
/*!
Constructs an empty location.
*/
Location::Location()
: stk(0), stkTop(&stkBottom), stkDepth(0), etcetera(false)
{
// nothing.
}
/*!
Constructs a location with (fileName, 1, 1) on its file
position stack.
*/
Location::Location(const QString& fileName)
: stk(0), stkTop(&stkBottom), stkDepth(0), etcetera(false)
{
push(fileName);
}
/*!
The copy constructor copies the contents of \a other into
this Location using the assignment operator.
*/
Location::Location(const Location& other)
: stk(0), stkTop(&stkBottom), stkDepth(0), etcetera(false)
{
*this = other;
}
/*!
The assignment operator does a deep copy of the entire
state of \a other into this Location.
*/
Location& Location::operator=(const Location& other)
{
QStack<StackEntry> *oldStk = stk;
stkBottom = other.stkBottom;
if (other.stk == 0) {
stk = 0;
stkTop = &stkBottom;
}
else {
stk = new QStack<StackEntry>(*other.stk);
stkTop = &stk->top();
}
stkDepth = other.stkDepth;
etcetera = other.etcetera;
delete oldStk;
return *this;
}
/*!
If the file position on top of the stack has a line number
less than 1, set its line number to 1 and its column number
to 1. Otherwise, do nothing.
*/
void Location::start()
{
if (stkTop->lineNo < 1) {
stkTop->lineNo = 1;
stkTop->columnNo = 1;
}
}
/*!
Advance the current file position, using \a ch to decide how to do
that. If \a ch is a \c{'\\n'}, increment the current line number and
set the column number to 1. If \ch is a \c{'\\t'}, increment to the
next tab column. Otherwise, increment the column number by 1.
The current file position is the one on top of the position stack.
*/
void Location::advance(QChar ch)
{
if (ch == QLatin1Char('\n')) {
stkTop->lineNo++;
stkTop->columnNo = 1;
}
else if (ch == QLatin1Char('\t')) {
stkTop->columnNo =
1 + tabSize * (stkTop->columnNo + tabSize-1) / tabSize;
}
else {
stkTop->columnNo++;
}
}
/*!
Pushes \a filePath onto the file position stack. The current
file position becomes (\a filePath, 1, 1).
\sa pop()
*/
void Location::push(const QString& filePath)
{
if (stkDepth++ >= 1) {
if (stk == 0)
stk = new QStack<StackEntry>;
stk->push(StackEntry());
stkTop = &stk->top();
}
stkTop->filePath = filePath;
stkTop->lineNo = INT_MIN;
stkTop->columnNo = 1;
}
/*!
Pops the top of the internal stack. The current file position
becomes the next one in the new top of stack.
\sa push()
*/
void Location::pop()
{
if (--stkDepth == 0) {
stkBottom = StackEntry();
}
else {
stk->pop();
if (stk->isEmpty()) {
delete stk;
stk = 0;
stkTop = &stkBottom;
}
else {
stkTop = &stk->top();
}
}
}
/*! \fn bool Location::isEmpty() const
Returns true if there is no file name set yet; returns false
otherwise. The functions filePath(), lineNo() and columnNo()
must not be called on an empty Location object.
*/
/*! \fn const QString& Location::filePath() const
Returns the current path and file name.
Must not be called on an empty Location object.
\sa lineNo(), columnNo()
*/
/*!
Returns the file name part of the file path, ie the
current file. Must not be called on an empty Location
object.
*/
QString Location::fileName() const
{
QString fp = filePath();
return fp.mid(fp.lastIndexOf('/') + 1);
}
/*! \fn int Location::lineNo() const
Returns the current line number.
Must not be called on an empty Location object.
\sa filePath(), columnNo()
*/
/*! \fn int Location::columnNo() const
Returns the current column number.
Must not be called on an empty Location object.
\sa filePath(), lineNo()
*/
/*!
Writes \a message and \a detals to stderr as a formatted
warning message.
*/
void Location::warning(const QString& message, const QString& details) const
{
emitMessage(Warning, message, details);
}
/*!
Writes \a message and \a detals to stderr as a formatted
error message.
*/
void Location::error(const QString& message, const QString& details) const
{
emitMessage(Error, message, details);
}
/*!
Writes \a message and \a detals to stderr as a formatted
error message and then exits the program.
*/
void Location::fatal(const QString& message, const QString& details) const
{
emitMessage(Error, message, details);
information("Aborting");
exit(EXIT_FAILURE);
}
/*!
*/
void Location::initialize(const Config& config)
{
tabSize = config.getInt(CONFIG_TABSIZE);
programName = config.programName();
QRegExp regExp = config.getRegExp(CONFIG_SPURIOUS);
if (regExp.isValid()) {
spuriousRegExp = new QRegExp(regExp);
}
else {
config.lastLocation().warning(tr("Invalid regular expression '%1'")
.arg(regExp.pattern()));
}
}
/*!
Apparently, all this does is delete a so-called
\e{spurious regular expression} in the internal
state and set the pointer to it to 0.
*/
void Location::terminate()
{
delete spuriousRegExp;
spuriousRegExp = 0;
}
/*!
Prints \a message to \c stdout followed by a \c{'\n'}.
*/
void Location::information(const QString& message)
{
printf("%s\n", message.toLatin1().data());
fflush(stdout);
}
/*!
Report a program bug, including the \a hint.
*/
void Location::internalError(const QString& hint)
{
Location::null.fatal(tr("Internal error (%1)").arg(hint),
tr("There is a bug in %1. Seek advice from your local"
" %2 guru.")
.arg(programName).arg(programName));
}
/*!
Formats \a message and \a details into a single string
and outputs that string to \c stderr. \a type specifies
whether the \a message is an error or a warning.
*/
void Location::emitMessage(MessageType type,
const QString& message,
const QString& details) const
{
if (type == Warning &&
spuriousRegExp != 0 &&
spuriousRegExp->exactMatch(message))
return;
QString result = message;
if (!details.isEmpty())
result += "\n[" + details + "]";
result.replace("\n", "\n ");
if (type == Error)
result.prepend(tr("error: "));
result.prepend(toString());
fprintf(stderr, "%s\n", result.toLatin1().data());
fflush(stderr);
}
QString Location::toString() const
{
QString str;
if (isEmpty()) {
str = programName;
}
else {
Location loc2 = *this;
loc2.setEtc(false);
loc2.pop();
if (!loc2.isEmpty()) {
QString blah = tr("In file included from ");
for (;;) {
str += blah;
str += loc2.top();
loc2.pop();
if (loc2.isEmpty())
break;
str += tr(",");
str += QLatin1Char('\n');
blah.fill(' ');
}
str += tr(":");
str += QLatin1Char('\n');
}
str += top();
}
str += QLatin1String(": ");
return str;
}
QString Location::top() const
{
QString str = filePath();
if (lineNo() >= 1) {
str += QLatin1Char(':');
str += QString::number(lineNo());
#if 0
if (columnNo() >= 1)
str += ":" + QString::number(columnNo());
#endif
}
if (etc())
str += QLatin1String(" (etc.)");
return str;
}
QT_END_NAMESPACE
| [
"lit-uriy@d7ba3245-3e7b-42d0-9cd4-356c8b94b330"
] | [
[
[
1,
391
]
]
] |
2d8ff5c41cb82dd4afcf15848c1d5694813a9e24 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEFoundation/SEShaders/SEShader.inl | 72e717b0866f2ef29e12081a5a64c9dc702605e6 | [] | no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,747 | inl | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// 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. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
//----------------------------------------------------------------------------
inline const std::string& SEShader::GetShaderName() const
{
return m_ShaderName;
}
//----------------------------------------------------------------------------
inline int SEShader::GetTextureCount() const
{
return (int)m_Textures.size();
}
//----------------------------------------------------------------------------
inline void SEShader::SetInterfaceDescriptor(SEInterfaceDescriptor*
pDescriptor)
{
m_spInterfaces = pDescriptor;
}
//----------------------------------------------------------------------------
inline SEInterfaceDescriptor* SEShader::GetInterfaceDescriptor() const
{
return m_spInterfaces;
}
//---------------------------------------------------------------------------- | [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
] | [
[
[
1,
42
]
]
] |
77d541461ad8e12c61071314b0fcc725e7deffb2 | 3d9e738c19a8796aad3195fd229cdacf00c80f90 | /src/geometries/Geometry.h | 72957a35c0f6bdaa777abec76980caff2d1846f4 | [] | no_license | mrG7/mesecina | 0cd16eb5340c72b3e8db5feda362b6353b5cefda | d34135836d686a60b6f59fa0849015fb99164ab4 | refs/heads/master | 2021-01-17T10:02:04.124541 | 2011-03-05T17:29:40 | 2011-03-05T17:29:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,673 | h | /* This source file is part of Mesecina, a software for visualization and studying of
* the medial axis and related computational geometry structures.
* More info: http://www.agg.ethz.ch/~miklosb/mesecina
* Copyright Balint Miklos, Applied Geometry Group, ETH Zurich
*
* $Id: Geometry.h 737 2009-05-16 15:40:46Z miklosb $
*/
#ifndef MESECINA_GEOMETRY_H
#define MESECINA_GEOMETRY_H
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/Exact_predicates_exact_constructions_kernel_with_sqrt.h>
#include <QtCore/QPointF>
#include <QtCore/QString>
#include <QObject>
#include <list>
#include <vector>
#include <string>
#include <gui/app/Application_variable.h>
#include <gui/app/Point3D.h>
//class Main_window;
class Managable_layer;
//class Evolution;
class Geometry : public QObject {
Q_OBJECT
public:
//virtual functions
Geometry();
virtual ~Geometry() {}
virtual Geometry* clone() { return 0; }
#ifdef MESECINA_3D
virtual void add_points(std::list<Point3D>*) {}
virtual std::list<Point3D>* get_points() { return 0; }
virtual void add_weighted_points(std::list<Point4D>*) {}
virtual std::list<Point4D>* get_weighted_points() { return 0; }
#else
virtual void add_point(double, double) {}
virtual void add_points(std::list<QPointF>*) {}
virtual std::list<QPointF>* get_points() { return 0; }
virtual void add_weighted_point(const Point3D&) {}
virtual void add_weighted_points(const std::list<Point3D>*) {}
virtual std::list<Point3D>* get_weighted_points() { return 0; }
#endif
virtual void load_generic_file(const std::string&) {}
virtual void save_generic_file(const std::string&) {}
virtual std::list<std::string> offer_structures() { return std::list<std::string>(); }
virtual void* give_structure(const std::string&) { return 0; }
virtual void receive_structure_changed(const std::string&) {}
virtual void application_settings_changed(const QString&) {}
virtual void apply_modification(const std::string& ) {}
virtual size_t layers_size() { return l_layers.size(); }
virtual Managable_layer* layers(size_t i) { return l_layers[i]; }
virtual size_t evolutions_size() { return l_evolutions.size(); }
virtual std::string evolutions(size_t i) { return l_evolutions[i]; }
virtual size_t app_variables_size() { return l_app_variables.size(); }
virtual Application_variable app_variables(size_t i) { return l_app_variables[i]; }
signals:
// communicate with gui
void announce_structure_changed(const std::string& name);
void* request_structure(const std::string& name);
void do_widget_repaint();
void do_statistics_repaint();
protected:
//self managing functions
// to be called at the construction time
void add_layer(Managable_layer* l);
void add_evolution(const std::string& name);
// can be called whenever
void add_variable(const char* name, float val);
void add_variable(const char* name, const char* val);
void invalidate_all_layers();
std::vector<Application_variable> l_app_variables;
std::vector<Managable_layer*> l_layers;
std::vector<std::string> l_evolutions;
};
typedef CGAL::Exact_predicates_inexact_constructions_kernel Double_kernel;
//typedef CGAL::Exact_predicates_exact_constructions_kernel Exact_kernel;
//typedef CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt Exact_kernel;
#ifdef _DEBUG
typedef CORE::Expr Lazy_core;
#else
typedef CGAL::Lazy_exact_nt< CORE::Expr > Lazy_core;
#endif
typedef CGAL::Simple_cartesian<Lazy_core > Exact_kernel;
#endif //MESECINA_GEOMETRY_H | [
"balint.miklos@localhost"
] | [
[
[
1,
111
]
]
] |
fc9ecb726d45327dcc00826e9dd440048caebede | b4bff7f61d078e3dddeb760e21174a781ed7f985 | /Source/Contrib/Lua/src/Manager/OSGLuaManager.cpp | fa96dd5e19759f39bff36e48f34bc547671aedfd | [] | no_license | Langkamp/OpenSGToolbox | 8283edb6074dffba477c2c4d632e954c3c73f4e3 | 5a4230441e68f001cdf3e08e9f97f9c0f3c71015 | refs/heads/master | 2021-01-16T18:15:50.951223 | 2010-05-19T20:24:52 | 2010-05-19T20:24:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,519 | cpp | /*---------------------------------------------------------------------------*\
* OpenSG Toolbox Lua *
* *
* *
* *
* *
* www.vrac.iastate.edu *
* *
* Authors: David Kabala *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* 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 *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#define OSG_COMPILELUALIB
#include "OSGConfig.h"
#include "OSGBaseFunctions.h"
#include "OSGBaseInitFunctions.h"
#include "OSGLog.h"
#include "OSGEvent.h"
#include "OSGLuaManager.h"
#include <boost/bind.hpp>
#include <boost/filesystem/operations.hpp>
#include <sstream>
//This is the OSGBase wrapped module in Bindings/OSG_wrap.cpp
extern "C" int luaopen_OSG(lua_State* L); // declare the wrapped module
OSG_BEGIN_NAMESPACE
/***************************************************************************\
* Description *
\***************************************************************************/
/*! \class OSG::LuaManager
A FMod SoundManager Interface.
*/
struct AddLuaInitFuncs
{
AddLuaInitFuncs()
{
addPreFactoryInitFunction(boost::bind(&LuaManager::init));
addPreFactoryExitFunction(boost::bind(&LuaManager::uninit));
}
} AddLuaInitFuncsInstantiation;
/***************************************************************************\
* Class variables *
\***************************************************************************/
LuaManager *LuaManager::_the = NULL;
lua_State *LuaManager::_State = NULL;
//! WindowEventProducer Produced Methods
MethodDescription *LuaManager::_methodDesc[] =
{
new MethodDescription("LuaError",
"Lua Error",
LuaErrorMethodId,
SFUnrecEventPtr::getClassType(),
FunctorAccessMethod())
};
EventProducerType LuaManager::_producerType(
"LuaManagerProducerType",
"EventProducerType",
"",
InitEventProducerFunctor(),
_methodDesc,
sizeof(_methodDesc));
/***************************************************************************\
* Class methods *
\***************************************************************************/
const EventProducerType &LuaManager::getProducerType(void) const
{
return _producerType;
}
LuaManager *LuaManager::the(void)
{
if(_the == NULL)
{
_the = new LuaManager();
}
return _the;
}
void LuaManager::report_errors(lua_State *L, int status)
{
}
bool LuaManager::init(void)
{
SLOG << "LuaManager Initializing." << std::endl;
_State = lua_open();
if(_State == NULL)
{
SWARNING << "Failed to create lua state." << std::endl;
return false;
}
luaL_openlibs(_State);
//Load the OpenSG Bindings
SLOG << "LuaManager Loading OpenSG Bindings." << std::endl;
luaopen_OSG(_State);
SLOG << "LuaManager Successfully Initialized." << std::endl;
return true;
}
bool LuaManager::recreateLuaState(void)
{
//Close the Lua State
if(_State != NULL)
{
SLOG << "LuaManager: closing Lua State." << std::endl;
lua_close(_State);
_State = NULL;
SLOG << "LuaManager: Lua State Closed." << std::endl;
}
SLOG << "LuaManager: Opening Lua State." << std::endl;
_State = lua_open();
if(_State == NULL)
{
SWARNING << "LuaManager: Failed to open lua state." << std::endl;
return false;
}
luaL_openlibs(_State);
//Load the OpenSG Bindings
SLOG << "LuaManager: Loading OpenSG Bindings." << std::endl;
luaopen_OSG(_State);
SLOG << "LuaManager: Successfully opened Lua State." << std::endl;
return true;
}
bool LuaManager::openLuaBindingLib(OpenBoundLuaLibFunctor OpenFunc)
{
if(_State != NULL)
{
SLOG << "LuaManager: Opening Lua bindings lib." << std::endl;
OpenFunc(_State);
SLOG << "LuaManager: Succefully opened Lua bindings lib." << std::endl;
return true;
}
else
{
SWARNING << "LuaManager: Failed to open lua binding, because the Lua State has not been created.." << std::endl;
return false;
}
}
bool LuaManager::uninit(void)
{
if(_State != NULL)
{
SLOG << "LuaManager Uninitializing." << std::endl;
lua_close(_State);
_State = NULL;
SLOG << "LuaManager Successfully Uninitialized." << std::endl;
return true;
}
else
{
return false;
}
}
void LuaManager::FunctionHook(lua_State *l, lua_Debug *ar)
{
//fill up the debug structure with information from the lua stack
lua_getinfo(l, "Snl", ar);
switch (ar->event)
{
case LUA_HOOKCALL:
{
//push function calls to the top of the callstack
std::stringstream ss;
ss << ar->short_src << ":"
<< ar->linedefined << ": "
<< (ar->name == NULL ? "[UNKNOWN]" : ar->name)
<< " (" << ar->namewhat << ")";
the()->_LuaStack.push_front(ss.str());
}
break;
case LUA_HOOKRET:
//pop the returned function from the callstack
if (the()->_LuaStack.size()>0)
{
the()->_LuaStack.pop_front();
}
break;
}
}
/***************************************************************************\
* Instance methods *
\***************************************************************************/
void LuaManager::runScript(const std::string& Script)
{
//If Stack Trace is enabled
if(_EnableStackTrace)
{
_LuaStack.clear();
lua_sethook(_State,&LuaManager::FunctionHook,LUA_MASKCALL | LUA_MASKRET,0);
}
else
{
lua_sethook(_State,NULL,LUA_MASKCALL | LUA_MASKRET,0);
}
//Load the Script
int s = luaL_loadstring(_State, Script.c_str());
checkError(s);
if(s != 0) {return;} //Error loading the string exit
// execute Lua program
s = lua_pcall(_State, 0, LUA_MULTRET, 0);
checkError(s);
}
void LuaManager::runScript(const BoostPath& ScriptPath)
{
if(boost::filesystem::exists(ScriptPath))
{
//If Stack Trace is enabled
if(_EnableStackTrace)
{
_LuaStack.clear();
lua_sethook(_State,&LuaManager::FunctionHook,LUA_MASKCALL | LUA_MASKRET,0);
}
else
{
lua_sethook(_State,NULL,LUA_MASKCALL | LUA_MASKRET,0);
}
//Load the Script
int s = luaL_loadfile(_State, ScriptPath.string().c_str());
checkError(s);
if(s != 0) {return;} //Error loading the string exit
// execute Lua program
s = lua_pcall(_State, 0, LUA_MULTRET, 0);
checkError(s);
}
else
{
SWARNING << "LuaManager::runScript(): File by path: " << ScriptPath.string() << ", does not exist." << std::endl;
}
}
EventConnection LuaManager::addLuaListener(LuaListenerRefPtr Listener)
{
_LuaListeners.insert(Listener);
return EventConnection(
boost::bind(&LuaManager::isLuaListenerAttached, this, Listener),
boost::bind(&LuaManager::removeLuaListener, this, Listener));
}
void LuaManager::removeLuaListener(LuaListenerRefPtr Listener)
{
LuaListenerSetItor EraseIter(_LuaListeners.find(Listener));
if(EraseIter != _LuaListeners.end())
{
_LuaListeners.erase(EraseIter);
}
}
void LuaManager::checkError(int Status)
{
switch(Status)
{
case 0:
//No Error
break;
case LUA_ERRSYNTAX:
//Syntax Error
SWARNING << "Lua Syntax Error: " << lua_tostring(_State, -1) << std::endl;
produceError(Status);
lua_pop(_State, 1); // remove error message
break;
case LUA_ERRFILE:
//File Read Error
SWARNING << "Lua File Load Error: " << lua_tostring(_State, -1) << std::endl;
printStackTrace();
produceError(Status);
lua_pop(_State, 1); // remove error message
break;
case LUA_ERRMEM:
//Memory Allocation Error
SWARNING << "Lua Memory Allocation Error: " << lua_tostring(_State, -1) << std::endl;
printStackTrace();
produceError(Status);
lua_pop(_State, 1); // remove error message
break;
case LUA_ERRRUN:
//Memory Allocation Error
SWARNING << "Lua Runtime Error: " << lua_tostring(_State, -1) << std::endl;
printStackTrace();
produceError(Status);
lua_pop(_State, 1); // remove error message
break;
case LUA_ERRERR:
//Memory Allocation Error
SWARNING << "Lua Error in Error Handler: " << lua_tostring(_State, -1) << std::endl;
printStackTrace();
produceError(Status);
lua_pop(_State, 1); // remove error message
break;
}
if(_EnableStackTrace)
{
_LuaStack.clear();
}
}
void LuaManager::printStackTrace(void) const
{
if(_EnableStackTrace)
{
std::stringstream ss;
ss << "Lua Stack Trace: " << std::endl;
std::list<std::string>::const_iterator ListItor(_LuaStack.begin());
for(; ListItor != _LuaStack.end() ; ++ListItor)
{
ss << " " << (*ListItor) << std::endl;
}
SWARNING << ss.str();
}
}
void LuaManager::produceError(int Status)
{
LuaErrorEventUnrecPtr TheEvent = LuaErrorEvent::create( NULL, getSystemTime(), _State, Status, _LuaStack, _EnableStackTrace);
LuaListenerSet ListenerSet(_LuaListeners);
for(LuaListenerSetConstItor SetItor(ListenerSet.begin()) ; SetItor != ListenerSet.end() ; ++SetItor)
{
(*SetItor)->error(TheEvent);
}
_Producer.produceEvent(LuaErrorMethodId,TheEvent);
}
void LuaManager::setPackagePath(const std::string& Pattern)
{
//Get the package table
lua_getglobal(_State, "package");
if (LUA_TTABLE != lua_type(_State, 1))
{
SWARNING << "LuaManager::getPackagePath(): package is not a table" << std::endl;
return;
}
lua_pushlstring(_State, Pattern.c_str(), Pattern.size());
lua_setfield(_State, 1, "path");
lua_pop(_State, 1);
}
std::string LuaManager::getPackagePath(void) const
{
std::string Result("");
//Get the package table
lua_getglobal(_State, "package");
if (LUA_TTABLE != lua_type(_State, 1))
{
SWARNING << "LuaManager::getPackagePath(): package is not a table" << std::endl;
return Result;
}
lua_getfield(_State, 1, "path");
if (LUA_TSTRING != lua_type(_State, 2))
{
SWARNING << "LuaManager::getPackagePath(): package.path is not a string" << std::endl;
lua_pop(_State, 1);
return Result;
}
Result = lua_tostring(_State, 2);
lua_pop(_State, 1);
return Result;
}
void LuaManager::setPackageCPath(const std::string& Pattern)
{
//Get the package table
lua_getglobal(_State, "package");
if (LUA_TTABLE != lua_type(_State, 1))
{
SWARNING << "LuaManager::getPackageCPath(): package is not a table" << std::endl;
return;
}
lua_pushlstring(_State, Pattern.c_str(), Pattern.size());
lua_setfield(_State, 1, "cpath");
lua_pop(_State, 1);
}
std::string LuaManager::getPackageCPath(void) const
{
std::string Result("");
//Get the package table
lua_getglobal(_State, "package");
if (LUA_TTABLE != lua_type(_State, 1))
{
SWARNING << "LuaManager::getPackageCPath(): package is not a table" << std::endl;
return Result;
}
lua_getfield(_State, 1, "cpath");
if (LUA_TSTRING != lua_type(_State, 2))
{
SWARNING << "LuaManager::getPackageCPath(): package.cpath is not a string" << std::endl;
lua_pop(_State, 1);
return Result;
}
Result = lua_tostring(_State, 2);
lua_pop(_State, 1);
return Result;
}
/*-------------------------------------------------------------------------*\
- private -
\*-------------------------------------------------------------------------*/
/*----------------------- constructors & destructors ----------------------*/
LuaManager::LuaManager(void) :
_EnableStackTrace(true),
_Producer(&_producerType)
{
}
LuaManager::LuaManager(const LuaManager &source) :
_EnableStackTrace(source._EnableStackTrace),
_Producer(&_producerType)
{
assert(false && "Sould NOT CALL LuaManager copy constructor");
}
LuaManager::~LuaManager(void)
{
}
OSG_END_NAMESPACE
| [
"[email protected]"
] | [
[
[
1,
499
]
]
] |
496b1a1598e9240afad5818ea7d3f82826b97edd | b887b5999a912513e7b9be35abe48da50f83650e | /Projekt/src/gfx/Graphics.h | 6aa71fb6f0220b304edea561af965b142b85a634 | [] | no_license | ryba616/Projekt | e39ce225ce725262f50f2b89b44f7a97bed383dc | ddc3c0a078e261e0e1d1278a5d1ff19930cc10b2 | refs/heads/master | 2021-01-22T22:56:50.420462 | 2010-05-16T22:55:53 | 2010-05-16T22:55:53 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 2,116 | h | #ifndef GRAPHICS_H
#define GRAPHICS_H
#include "../logic/Player.h"
#include "../map/Platform.h"
#include "../map/Map.h"
#include "../common/Vec.h"
#include "../gfx/Drawable.h"
#include <vector>
class Graphics
{
public:
void init(); // inicjuje (tworzy) okno gry
void drawWindow(); // rysuje okno gry
void setPlayer(Player *_p); // zapisuje wskaźnik na gracza do pola p
void setMap(Map *_m); // zapisuje wskaznik na instancje mapy
void createElements(); // tworzy elementy do narysowania
Vecf offset; // przesuniecie elementow wzgledem gracza
private:
void loadMapData(); // zapisuje w pola dane potrzebne do rysowania elementów mapy pobrane z instancji klasy Map
void prepareBuffer(); // rysuje wszystkie elementy (Drawable) na bufor
void countOffset(); // oblicza aktualny offset
std::vector<Platform> platforms; // kontener zawierający instancję klasy Platform, ale tylko te które mają zostać wyświetlone na ekranie
// std::vector<BITMAP*> platform_bitmaps; // kontener zawierający przygotowane do wyświetlenia bitmapy platform
std::vector<Drawable> environment; // kontener zawierajacy wszystkie elementy otoczenia
Drawable bg; // tlo
Drawable player; // grafika gracza
BITMAP *buffer;
char *bgPath; // sciezka do tla
Player *p;
Map *map;
static const int RESOLUTION_WIDTH = 800; // tych stalych nalezy uzyc do okreslania rozdzielczosci okna
static const int RESOLUTION_HEIGHT = 600;
};
#endif
// PROBLEMY
/*
1. wsadzenie wszystkich elementow ktore maja zostac narysowane do jednej kolekcji, a nastepnie rysowanie ich po kolei stwarza dosyc powazny problem,
mianowicie nie uwzglednia koniecznosci zachowania priorytetow (pewne grupy elementow musza byc rysowane w odpowiedniej kolejnosci - np tlo musi
zostac narysowane w pierwszej kolejnosci, nastepnie platformy, na koncu postacie)
TODO: albo dodac do klasy Drawable pole priority i przy rysowaniu robic to zgodnie z priorytetami, albo stworzyc z kilka z gory okreslonych grup
elementow (kilka wektorow), sklanialbym sie ku pierwszemu rozwiazaniu
ryba
*/ | [
"ryba@ryb-520fb58ee61.(none)"
] | [
[
[
1,
57
]
]
] |
96ed25ca1229729b1396377302d4e9a35970a3d5 | c70eef5627d8910181878dcfea2eed4ef991a6ad | /MoshBall/MoshBall/highprecisiontime.h | 52080d8158bb2b8f6548d38df66d08d16972c08b | [] | no_license | Phildo/moshball | cb8c26badb7e7b8d7ef2e86c31a5a22ab99a88c9 | b99501e2b49422e1ec3427e361939c9d16ba2b48 | refs/heads/master | 2016-09-05T09:53:27.841416 | 2011-12-07T04:56:54 | 2011-12-07T04:56:54 | 2,676,543 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | h | #ifndef HIGHPRECISIONTIME_H
#define HIGHPRECISIONTIME_H
#ifdef WIN32
#include <Windows.h>
#endif
class HighPrecisionTime
{
public:
HighPrecisionTime();
double TimeSinceLastCall();
double TotalTime();
private:
#ifdef WIN32
LARGE_INTEGER initializationTicks;
LARGE_INTEGER ticksPerSecond;
LARGE_INTEGER previousTicks;
#endif
};
#endif | [
"[email protected]"
] | [
[
[
1,
25
]
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.