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
394a9d7a2d21e7b9afabeaed130694d415dfd699
f0da2c3ab8426f8bcdd8c3625c805a25f04aa89d
/armagic/Tracker.h
48e828fed813f59d02883e90d4c27b9a1fc97476
[]
no_license
sanyaade-augmented-reality/armagic
81e557978936c396333be0261e45d869da680e6d
eb5132d280685e2f8db4ae1f3fbe624b1876bf73
refs/heads/master
2016-09-06T17:12:20.458558
2010-07-06T22:57:18
2010-07-06T22:57:18
34,191,493
0
0
null
null
null
null
UTF-8
C++
false
false
710
h
#ifndef ARMAGIC_TRACKER_H_ #define ARMAGIC_TRACKER_H_ #include <irrlicht.h> #include <AR/video.h> #include <AR/param.h> #include <AR/ar.h> // Tracker is the vision core of ARMagic // This class interfaces with ARTOOLKIT PLUS providing tracking information class Tracker { public: Tracker(); ~Tracker(); void loadImage(ARUint8* image); void setTreshold(const int tresh); bool trackMarker(const int patt, irr::core::CMatrix4<float>& matrix); private: ARUint8* image_; int treshold_; int markerNum_; ARMarkerInfo* markerInfo_; double pattWidth_; double pattCenter_[2]; // Aux functions void convertTransPara(double trans[3][4], float gl_para[16]); }; #endif
[ "leochatain@22892e45-cd4f-0d29-0166-6a0decb81ae3", "pmdusso@22892e45-cd4f-0d29-0166-6a0decb81ae3" ]
[ [ [ 1, 4 ], [ 7, 35 ] ], [ [ 5, 6 ] ] ]
c348706498e1ff95119ef083730d8a2ce062bda7
de8f00c6db2403836a5296384cb129e39b3fd982
/src/controls/Slider.cpp
fe64a0877d16acbf44f44726510760bb569f8ce8
[ "MIT" ]
permissive
underdoeg/datasynth
61caaef790aec6de9e55783789aa948807d62cf7
eb1b03d927d496674d6f928d51775a2d66b1234a
refs/heads/master
2021-01-17T23:23:33.947597
2011-07-25T21:58:20
2011-07-25T21:58:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,762
cpp
#include "Slider.h" //some code stolen from here: https://github.com/openframeworks/openFrameworks/blob/master/apps/devApps/guiExample/src/ofSlider.h using namespace ds; Slider::Slider(float* _x, float* _y, string _name, float* _val, bool* _bIsNodeActive) { ofRegisterMouseEvents(this); bIsNodeActive = _bIsNodeActive; val = _val; name = _name; min = 0; max = 3; x = _x; y = _y; b.x = *x + 2; b.y = *y + 28; b.width = 147; b.height = 10; } Slider::~Slider() { ofUnregisterMouseEvents(this); } void Slider::draw() { if(*val >= max) { max = *val + (*val / 2); } if(*val <= min) { min = *val - (*val / 2); } b.x = *x + 2; b.y = *y + 28; ofNoFill(); ofSetColor(0, 0, 0); ofRect(b); ofFill(); float valAsPct = ofMap(*val, min, max, 0, b.width, true ); ofEnableAlphaBlending(); ofSetColor(0, 0, 0); ofRect(b.x, b.y, valAsPct, b.height); } void Slider::setValue(float _val) { *val = _val; } void Slider::setValue(float mx, float my, bool bCheck) { if(b.inside(mx, my) ) { *val = ofMap(mx, b.x, b.x + b.width, min, max, true); } else { return; } } void Slider::mouseMoved(ofMouseEventArgs & args) { } void Slider::mousePressed(ofMouseEventArgs & args) { if(b.inside(args.x,args.y)) { setValue(args.x, args.y, true); bIsActive = true; *bIsNodeActive = false; } else { bIsActive = false; } } void Slider::mouseDragged(ofMouseEventArgs & args) { if(b.inside(args.x,args.y) && bIsActive) { setValue(args.x, args.y, false); } } void Slider::mouseReleased(ofMouseEventArgs & args) { bIsActive = false; }
[ [ [ 1, 96 ] ] ]
67ca8404802288e52d9c54284cf86c4141be6bf2
880e5a47c23523c8e5ba1602144ea1c48c8c8f9a
/CommonLibSrc/Math/CMathOperations.hpp
02b0e9a4c27ee37521bfe53e446a9feea032c0f8
[]
no_license
kfazi/Engine
050cb76826d5bb55595ecdce39df8ffb2d5547f8
0cedfb3e1a9a80fd49679142be33e17186322290
refs/heads/master
2020-05-20T10:02:29.050190
2010-02-11T17:45:42
2010-02-11T17:45:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,583
hpp
#ifndef COMMON_MATH_OPERATIONS_HPP #define COMMON_MATH_OPERATIONS_HPP #include "../Internal.hpp" #include "CVector3D.hpp" #include "CQuaternion.hpp" #include "cmath" namespace Common { class COMMONDLLIMPORTEXPORT CMathOperations { public: /** * Returns minimum of its two arguments. * This function is here only because of Microsoft's fuckups. * @param[in] x First value. * @param[in] y Second value. * @return Minimum value. */ template<class CType> inline static const CType& Min(const CType& x, const CType& y) { return (x < y) ? x : y; } /** * Returns maximum of its two arguments. * This function is here only because of Microsoft's fuckups. * @param[in] x First value. * @param[in] y Second value. * @return Maximum value. */ template<class CType> inline static const CType& Max(const CType& x, const CType& y) { return (x < y) ? y : x; } /** * Converts degrees to radians. * @param[in] fDegrees Value in degrees. * @return Value in radians. */ inline static double DegToRad(const double fDegrees) { return fDegrees * 0.017453292519943295769236907684888; /* fDegrees * pi / 180 */ } /** * Converts radians to degrees. * @param[in] fRadians Value in radians. * @return Value in degrees. */ inline static double RadToDeg(const double fRadians) { return fRadians * 57.295779513082320876798154814105; /* fRadians * 180 / pi */ } inline static double DotProduct(const CVector3D& cVector1, const CVector3D& cVector2) { return cVector1.X * cVector2.X + cVector1.Y * cVector2.Y + cVector1.Z * cVector2.Z; } inline static double DotProduct(const CQuaternion& cQuaternion1, const CQuaternion& cQuaternion2) { return DotProduct(cQuaternion1.GetVector(), cQuaternion2.GetVector()) + cQuaternion1.W * cQuaternion1.W; } inline static CVector3D CrossProduct(const CVector3D& cVector1, const CVector3D& cVector2) { return CVector3D(cVector1.Y * cVector2.Z - cVector1.Z * cVector2.Y, cVector1.Z * cVector2.X - cVector1.X * cVector2.Z, cVector1.X * cVector2.Y - cVector1.Y * cVector2.X); } inline static CVector3D Rotate(const CVector3D& cVector, const CQuaternion& cQuaternion) { CQuaternion cVectorQuaternion(0, cVector); CQuaternion cConjugate(cQuaternion); cConjugate.Conjugate(); return (cQuaternion * cVectorQuaternion * cConjugate).GetVector(); } //! linear quaternion interpolation static CQuaternion Lerp(const CQuaternion& cQuaternion1, const CQuaternion& cQuaternion2, const double fT) { return (cQuaternion1 * (1.0 - fT) + cQuaternion2 * fT).GetNormalized(); } //! spherical linear interpolation static CQuaternion Slerp(const CQuaternion& cQuaternion1, const CQuaternion& cQuaternion2, const double fT) { CQuaternion cQuaternion3; double fDot = DotProduct(cQuaternion1, cQuaternion2); /* dot = cos(theta) if (dot < 0), q1 and q2 are more than 90 degrees apart, so we can invert one to reduce spinning */ if (fDot < 0) { fDot = -fDot; cQuaternion3 = -cQuaternion2; } else cQuaternion3 = cQuaternion2; if (fDot < 0.95) { double fAngle = acos(fDot); return (cQuaternion1 * sin(fAngle * (1.0 - fT)) + cQuaternion3 * sin(fAngle * fT)) / sin(fAngle); } else // if the angle is small, use linear interpolation return Lerp(cQuaternion1, cQuaternion3, fT); } //! This version of slerp, used by squad, does not check for theta > 90. static CQuaternion SlerpNoInvert(const CQuaternion& cQuaternion1, const CQuaternion& cQuaternion2, const double fT) { double fDot = DotProduct(cQuaternion1, cQuaternion2); if (fDot > -0.95 && fDot < 0.95) { double fAngle = acos(fDot); return (cQuaternion1 * sin(fAngle * (1.0 - fT)) + cQuaternion2 * sin(fAngle * fT)) / sin(fAngle); } else // if the angle is small, use linear interpolation return Lerp(cQuaternion1, cQuaternion2, fT); } //! spherical cubic interpolation static CQuaternion Squad(const CQuaternion& cQuaternion1, const CQuaternion& cQuaternion2, const CQuaternion& cQuaternionA, const CQuaternion& cQuaternionB, const double fT) { CQuaternion cQuaternionC = SlerpNoInvert(cQuaternion1, cQuaternion2, fT); CQuaternion cQuaternionD = SlerpNoInvert(cQuaternionA, cQuaternionB, fT); return SlerpNoInvert(cQuaternionC, cQuaternionD, 2.0 * fT * (1.0 - fT)); } //! Shoemake-Bezier interpolation using De Castlejau algorithm static CQuaternion Bezier(const CQuaternion& cQuaternion1, const CQuaternion& cQuaternion2, const CQuaternion& cQuaternionA, const CQuaternion& cQuaternionB, const double fT) { // level 1 CQuaternion cQuaternion11 = SlerpNoInvert(cQuaternion1, cQuaternionA, fT); CQuaternion cQuaternion12 = SlerpNoInvert(cQuaternionA, cQuaternionB, fT); CQuaternion cQuaternion13 = SlerpNoInvert(cQuaternionB, cQuaternion2, fT); // level 2 and 3 return SlerpNoInvert(SlerpNoInvert(cQuaternion11, cQuaternion12, fT), SlerpNoInvert(cQuaternion12, cQuaternion13, fT), fT); } #if 0 //! Given 3 quaternions, qn-1,qn and qn+1, calculate a control point to be used in spline interpolation static quaternion spline(const quaternion& qnm1,const quaternion& qn,const quaternion& qnp1) { quaternion qni(qn.s, -qn.v); return qn * (( (qni*qnm1).log()+(qni*qnp1).log() )/-4).exp(); } #endif }; } #endif /* COMMON_MATH_OPERATIONS_HPP */ /* EOF */
[ [ [ 1, 161 ] ] ]
25e8d1368bbc50bbf1df170af64aebc43abe3a08
5095bbe94f3af8dc3b14a331519cfee887f4c07e
/apsim/Plant/source/Reproductive/FruitCohortFN.cpp
9342788358de603a1b14d5f75a922540e6fee3a5
[]
no_license
sativa/apsim_development
efc2b584459b43c89e841abf93830db8d523b07a
a90ffef3b4ed8a7d0cce1c169c65364be6e93797
refs/heads/master
2020-12-24T06:53:59.364336
2008-09-17T05:31:07
2008-09-17T05:31:07
64,154,433
0
0
null
null
null
null
UTF-8
C++
false
false
12,514
cpp
#include "StdPlant.h" #include "FruitCohortFN.h" #include "Environment.h" #include "ThingFactory.h" using namespace std; // ############################################################## // DPH: Most of this file can be removed by relying on // composite part to do the looping over parts for dmGreenVeg, // dmSenescedVeg etc. We would need to put in lines in the grain // parts to return 0.0 for the dmGreenVeg, dmSenescedVeg etc. // ############################################################## // initialise data members. FruitCohortFN::FruitCohortFN(ScienceAPI& scienceAPI, plantInterface *p, const string &name) : FruitCohort(scienceAPI, p, name) { string phenologyModel; scienceAPI.readOptional("phenology_model", phenologyModel); fruitPhenology = dynamic_cast<Phenology*> (createThing(scienceAPI, *plant, "Phenology", phenologyModel)); } // destructor FruitCohortFN::~FruitCohortFN() // ==================================================================== { delete fruitPhenology; } float FruitCohortFN::getDltTT(void) //=========================================================================== { return fruitPhenology->TT(); } bool FruitCohortFN::onDayOf(const string &what) //=========================================================================== { return (fruitPhenology->onDayOf(what)); } void FruitCohortFN::onInit1(protocol::Component *system) //=========================================================================== { zeroAllGlobals(); zeroDeltas(); fruitPhenology->onInit1(system); grainPart = new fruitGrainPartFN(scienceAPI, plant, this, "grain"); podPart = new fruitPodPartFN(scienceAPI, plant, this, "pod"); add(podPart); myVegParts.push_back(podPart); supplyPools.push_back(podPart); add(grainPart); myGrainParts.push_back(grainPart); // call into base class. FruitCohort::onInit1(system); // register some other things. system->addGettableVar("dlt_dm_fruit", gDlt_dm, "g/m^2", "Change in dry matter"); setupGetFunction(system, "head_wt", protocol::DTsingle, false,&FruitCohortFN::get_head_wt, "g/m^2", "Weight of heads"); setupGetFunction(system, "head_n", protocol::DTsingle, false,&FruitCohortFN::get_head_n, "g/m^2", "N in heads"); setupGetFunction(system, "head_p", protocol::DTsingle, false, &FruitCohortFN::get_head_p, "g/m^2","P in head"); } void FruitCohortFN::process (void) //======================================================================================= { fruitPhenology->process (); FruitCohort::process(); } void FruitCohortFN::onPlantEvent(const string &event) //======================================================================================= { fruitPhenology->onPlantEvent(event); FruitCohort::onPlantEvent(event); } void FruitCohortFN::zeroAllGlobals(void) //=========================================================================== { fruitPhenology->zeroAllGlobals(); FruitCohort::zeroAllGlobals(); } void FruitCohortFN::zeroDeltas(void) //=========================================================================== { fruitPhenology->zeroDeltas(); FruitCohort::zeroDeltas(); } void FruitCohortFN::readCultivarParameters (protocol::Component *system, const string &cultivar) //=========================================================================== { fruitPhenology->readCultivarParameters(system, cultivar); rel_grainfill.read(scienceAPI, "x_temp_grainfill", "oC", 0.0, 40.0 , "y_rel_grainfill", "-", 0.0, 1.0); scienceAPI.read("potential_fruit_filling_rate", p.potential_fruit_filling_rate, 0.0f, 1.0f); //'(g/fruit/degday)' fracPod.read(scienceAPI, "x_fruit_stage_no_partition", "-", 0.0, 20.0 , "y_fruit_frac_pod", "-", 0.0, 2.0); sdr_min.read(scienceAPI, "x_stage_supply_demand_ratio", "-", 1.0, 100.0 , "y_supply_demand_ratio_min", "-", 0.0, 2.0); scienceAPI.read("dm_fruit_max", p.dm_fruit_max, 0.0f, 100.0f); // Temporarily remove scienceAPI.read("dm_abort_fract", c.dm_abort_fract, 0.0f, 1.0f); // scienceAPI.read("fract_dm_fruit_abort_crit", c.fract_dm_fruit_abort_crit, 0.0f, 1.0f); // scienceAPI.read("fruit_phen_end", c.fruit_phen_end, 0.0f, 1.0f); FruitCohort::readCultivarParameters(system, cultivar); } void FruitCohortFN::readConstants(protocol::Component *system, const string &section) //=========================================================================== { fruitPhenology->readConstants(system, section); FruitCohort::readConstants(system, section); } void FruitCohortFN::readSpeciesParameters(protocol::Component *system, vector<string> &sections) //=========================================================================== { fruitPhenology->readSpeciesParameters(system, sections); FruitCohort::readSpeciesParameters(system, sections); } void FruitCohortFN::doGrainNumber(void) //=========================================================================== { doFruitNumber(); } // Purpose // Get change in plant fruit number void FruitCohortFN::doFruitNumber(void) //=========================================================================== { if (flower_no > 0.0) { if (fruitPhenology->TTInPhase("fruiting") >= c.tt_flower_to_start_pod) dlt_fruit_no = flower_no; // flowers become fruit else dlt_fruit_no = 0.0; } else dlt_fruit_no = 0.0; } float FruitCohortFN::fruitNumber(void) //=========================================================================== { return fruit_no; } float FruitCohortFN::flowerNumber(void) //=========================================================================== { return flower_no; } void FruitCohortFN::giveFlowerNo(float dltFlowerNo) //=========================================================================== { flower_no += dltFlowerNo; } float FruitCohortFN::potentialGrainFillRate(void) //=========================================================================== { return podPart->removePodFraction(p.potential_fruit_filling_rate); } float FruitCohortFN::potentialCohortGrainFillRate(void) //=========================================================================== { return fruit_no * potentialGrainFillRate(); } float FruitCohortFN::dltDmFruitMax(void) //=========================================================================== { float dlt_dm_fruit_max = p.dm_fruit_max - divide (Green.DM(), fruit_no, 0.0); return l_bound (dlt_dm_fruit_max, 0.0); //cohort dm demand - cohort stuff } float FruitCohortFN::dltDmGrainMax(void) //=========================================================================== { return podPart->removePodFraction(dltDmFruitMax()); } //+ Purpose // Perform grain filling calculations void FruitCohortFN::doDmDemand (float /*dlt_dm_supply_by_veg*/) // //=========================================================================== // float *dlt_dm_grain_demand) //(OUTPUT) { // doProcessBioDemand(); // // (OUTPUT) assimilate demand for reproductive part (g/m^2) // // calculate demands of reproductive parts // podPart->doDmDemand(dlt_dm_veg_supply); // cohort = 0; // do { // float dlt_dm_grain_demand = 0.0; // float dlt_dm_fruit_demand = 0.0; if (fruit_no > 0.0) { if (plant->phenology().inPhase("flowering")) //pod dm demand - pod stuff { //pod dm demand - pod stuff // we are in flowering phase //pod dm demand - pod stuff float tt_fruit_age_max = fruitPhenology->TTTargetInPhase("fruiting"); float dlt_fruit_age = divide(plant->phenology().TT() //pod dm demand - pod stuff , tt_fruit_age_max, 0.0); //pod dm demand - pod stuff float dm_max = p.dm_fruit_max //pod dm demand - pod stuff * rel_grainfill.value(plant->environment().meant()) //pod dm demand - pod stuff * fruit_no; //pod dm demand - pod stuff //pod dm demand - pod stuff float dlt_dm_fruit_demand_pot = dm_max * dlt_fruit_age; //pod dm demand - pod stuff podPart->doDmDemand(dlt_dm_fruit_demand_pot); //pod dm demand - pod stuff } else if (plant->phenology().inPhase("grainfilling")) { // we are in grain filling stage // float frac_pod = linear_interp_real(g_current_stage[cohort] // ,c_x_stage_no_partition // ,c_y_frac_pod // ,c_num_stage_no_partition); // float frac_pod = fracPod.value(plant->getStageCode()); //// float potential_grain_filling_rate = divide(p.potential_fruit_filling_rate //// , 1.0 + frac_pod //// , 0.0); // float potential_grain_filling_rate = potentialGrainFillRate(); // float dlt_dm_yield = grainPart->dltDmYieldPotential(); //cohort dm demand - cohort stuff // adjust for grain energy // float dlt_dm_grain_demand = oilPart->addEnergy(dlt_dm_yield); //grain dm demand - grain stuff // dlt_dm_pod_demand = dlt_dm_yield * frac_pod; //pod dm demand - pod stuff podPart->doDmDemand(grainPart->dltDmYieldPotential()); doProcessBioDemand(); // // dlt_dm_fruit_demand = dmGreenDemand(); //cohort dm demand - cohort stuff // // float dlt_dm_fruit_max = dltDmFruitCohortMax(); //cohort dm demand - cohort stuff // - sum_real_array(&g_dm_fruit_green[cohort][pod], max_part-pod); //cohort dm demand - cohort stuff // dlt_dm_fruit_max = l_bound (dlt_dm_fruit_max, 0.0); //cohort dm demand - cohort stuff // // adjust the demands // if (dlt_dm_fruit_demand > dlt_dm_fruit_max) //grain dm demand - grain stuff // { //grain dm demand - grain stuff // dlt_dm_grain_demand = dlt_dm_grain_demand //grain dm demand - grain stuff // * divide (dlt_dm_fruit_max //grain dm demand - grain stuff // , dlt_dm_fruit_demand //grain dm demand - grain stuff // , 0.0); //grain dm demand - grain stuff // dlt_dm_fruit_demand = dlt_dm_fruit_max; // } //cohort dm demand - cohort stuff } else { // no changes // dlt_dm_grain_demand = 0.0; // dlt_dm_fruit_demand = 0.0; } } else { // no fruit // dlt_dm_grain_demand = 0.0; // dlt_dm_fruit_demand = 0.0; } //// cohort++; //// } while (cohort < g_num_fruit_cohorts); //// pop_routine (my_name); }
[ "hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8", "har297@8bb03f63-af10-0410-889a-a89e84ef1bc8" ]
[ [ [ 1, 1 ], [ 4, 5 ], [ 21, 22 ], [ 35, 35 ], [ 38, 38 ], [ 41, 41 ], [ 75, 75 ], [ 153, 153 ], [ 207, 207 ], [ 223, 223 ], [ 227, 227 ], [ 230, 230 ], [ 236, 236 ] ], [ [ 2, 3 ], [ 6, 20 ], [ 23, 34 ], [ 36, 37 ], [ 39, 40 ], [ 42, 74 ], [ 76, 152 ], [ 154, 206 ], [ 208, 222 ], [ 224, 226 ], [ 228, 229 ], [ 231, 235 ], [ 237, 292 ] ] ]
ae44c7f1af723827cdd7a3d030e392c346f80d5e
f38fce44b6b8faa614c5cc8ad112b0f2e74750ec
/Saber Graphic Engine/SaberGE_DirectX.cpp
7f4a744bde0c80f55f4051810bea574232d5fba2
[]
no_license
Eskat0n/Nebula
ac199ae8c7a807d99c6b8837a3bc52b079fbc6ee
8d47e83abc20b3abd98e49c4c4fcc1b74ba18f6d
refs/heads/master
2016-09-05T17:42:47.468149
2011-05-21T17:37:29
2011-05-21T17:37:29
1,779,667
0
0
null
null
null
null
UTF-8
C++
false
false
14,295
cpp
//------------------------------------------------------------- // Saber Graphic Engine main functions desciption file // Written by Eskat0n // Current engine version: 0.0.8 // Modified: 6 nov 2008 //------------------------------------------------------------- #include "SaberGE_DirectX.h" #include <boost/foreach.hpp> //------------------------------------------------------------- SaberEngine* SaberEngine::_self = 0; int SaberEngine::_nRefCount = 0; //------------------------------------------------------------- // SaberEngine class constructor // Func: sets default values to internal vars //------------------------------------------------------------- ISaberGE* SaberEngine::Instance() { if ( !_self ) _self = new SaberEngine(); _nRefCount++; return static_cast<ISaberGE*>(_self); } //------------------------------------------------------------- void __stdcall SaberEngine::Release() { _nRefCount--; if ( !_nRefCount ) { delete _self; _self = 0; } } //------------------------------------------------------------- SaberEngine::SaberEngine() { // Nulifies private class fields _hInst = GetModuleHandle( 0 ); _hwnd = 0; _bRunning = false; _pD3d = 0; _pD3dDevice = 0; //_d3dpp = 0; _pVB = 0; _pVertices = 0; _pOnCloseFunc = 0; _nScreenResX = 800; _nScreenResY = 600; // _nScreenBD = 32; _bVisibleCursor = false; wcscpy( _wstrWinTitle, L"DefaultWindow" ); } //------------------------------------------------------------- // SaberEngine class destructor // Func: releases resources used by D3D Object, D3D Device and Vertex Buffer //------------------------------------------------------------- SaberEngine::~SaberEngine() { _nRefCount = 0; _vTextures.clear(); _vFuncs.clear(); if ( _pD3d ) _pD3d->Release(); if ( _pD3dDevice ) _pD3dDevice->Release(); if ( _pVB ) _pVB->Release(); UnregisterClass( L"SaberEngineWnd", _hInst ); } //------------------------------------------------------------- void SaberEngine::_SetProjMatrix( int width, int height ) { D3DXMATRIX tmp; D3DXMatrixScaling( &_mtProj, 1.0f, -1.0f, 1.0f ); D3DXMatrixTranslation( &tmp, -0.5f, height + 0.5f, 0.0f ); D3DXMatrixMultiply( &_mtProj, &_mtProj, &tmp); D3DXMatrixOrthoOffCenterLH( &tmp, 0, (float)width, 0, (float)height, 0.0f, 1.0f); D3DXMatrixMultiply( &_mtProj, &_mtProj, &tmp); } //------------------------------------------------------------- void SaberEngine::_RenderAll( bool bSceneEnded ) { if ( _pVertices ) { _pVB->Unlock(); if ( _nPrim ) { _pD3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, _nPrim<<2, 0, _nPrim<<1, _nPrim * 2 ); _nPrim = 0; } if ( bSceneEnded ) _pVertices = 0; else _pVB->Lock( 0, 0, (VOID**)&_pVertices, 0 ); } } //------------------------------------------------------------- bool SaberEngine::_Initialize() { D3DADAPTER_IDENTIFIER9 AdID; D3DDISPLAYMODE Mode; D3DFORMAT Format = D3DFMT_UNKNOWN; // Init D3D _pD3d = Direct3DCreate9( D3D_SDK_VERSION ); if ( _pD3d == 0 ) return false; // Get adapter info _pD3d->GetAdapterIdentifier( D3DADAPTER_DEFAULT, 0, &AdID ); // Set up for windowed mode if ( FAILED( _pD3d->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &Mode ) ) || Mode.Format == D3DFMT_UNKNOWN ) { if ( _bWindowed ) return false; } ZeroMemory( &_d3dpp, sizeof(_d3dpp) ); _d3dpp.BackBufferWidth = _nScreenResX; _d3dpp.BackBufferHeight = _nScreenResY; _d3dpp.BackBufferCount = 1; _d3dpp.BackBufferFormat = Mode.Format; _d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; _d3dpp.hDeviceWindow = _hwnd; _d3dpp.Windowed = TRUE; _d3dpp.SwapEffect = D3DSWAPEFFECT_COPY; // ?????? _d3dpp.EnableAutoDepthStencil = TRUE; _d3dpp.AutoDepthStencilFormat = D3DFMT_D16; // Set up for fullscreen mode // skipped // Create D3D Device if ( FAILED( _pD3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, _hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &_d3dpp, &_pD3dDevice ) ) ) return false; // TODO: in next versions //_pScreenSurf=0; //_pScreenDepth=0; //_pD3dDevice->GetRenderTarget( &_pScreenSurf ); //_pD3dDevice->GetDepthStencilSurface( &_pScreenDepth ); // Skipped in performance purposes //_CalibrateWindow(); // Initialize vertex pointer _pVertices = 0; // Create vertex buffer if ( FAILED( _pD3dDevice->CreateVertexBuffer( SBR_VERTEX_BUFFER_SIZE * sizeof(VERTEX), D3DUSAGE_WRITEONLY, SBR_D3DFVF_VERTEX, D3DPOOL_DEFAULT, &_pVB, 0 ) ) ) return false; //_pD3dDevice->SetVertexShader( 0 ); _pD3dDevice->SetFVF( SBR_D3DFVF_VERTEX ); _pD3dDevice->SetStreamSource( 0, _pVB, 0, sizeof(VERTEX) ); // Setting main render states _pD3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE ); _pD3dDevice->SetRenderState( D3DRS_LIGHTING, FALSE ); _pD3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); _pD3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); _pD3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA ); _pD3dDevice->SetRenderState( D3DRS_ALPHATESTENABLE, TRUE ); _pD3dDevice->SetRenderState( D3DRS_ALPHAREF, 0x01 ); _pD3dDevice->SetRenderState( D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL ); _pD3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE ); _pD3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE ); _pD3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE ); _pD3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); _pD3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE ); _pD3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE ); _nPrim = 0; _curTexture = 0; // Other stuff _SetProjMatrix( _nScreenResX, _nScreenResY ); D3DXMatrixIdentity( &_mtView ); _pD3dDevice->SetTransform(D3DTS_VIEW, &_mtView); _pD3dDevice->SetTransform( D3DTS_PROJECTION, &_mtProj ); Clear( 0 ); return true; } //------------------------------------------------------------- void SaberEngine::_CalibrateWindow() { RECT* rect; LONG style; if ( _bWindowed ) { rect = &_rectW; style = _styleW; } else { // FS code goes here } SetWindowLong( _hwnd, GWL_STYLE, style ); style = GetWindowLong( _hwnd, GWL_EXSTYLE ); if ( _bWindowed ) { SetWindowLong( _hwnd, GWL_EXSTYLE, style & (~WS_EX_TOPMOST) ); SetWindowPos( _hwnd, HWND_TOPMOST, rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top, SWP_FRAMECHANGED ); } else { // FS code goes here } } //------------------------------------------------------------- void SaberEngine::_FocusChange( bool active ) { _bActive = active; if ( _bActive ) { if ( _pOnFocusGainFunc ) _pOnFocusGainFunc(); } else { if ( _pOnFocusLostFunc ) _pOnFocusLostFunc(); } } //------------------------------------------------------------- bool __stdcall SaberEngine::SetUp() { WNDCLASS wnd; INT width, height; wnd.style = CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW; wnd.lpfnWndProc = SaberEngine::WindowProc; wnd.cbClsExtra = 0; wnd.cbWndExtra = 0; wnd.hInstance = _hInst; wnd.hCursor = LoadCursor(0, IDC_ARROW); wnd.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wnd.lpszMenuName = 0; wnd.lpszClassName = L"SaberEngineWnd"; wnd.hIcon = LoadIcon( _hInst, IDI_APPLICATION ); if ( !RegisterClass( &wnd ) ) return false; width = _nScreenResX; height = _nScreenResY; _rectW.left = ( GetSystemMetrics( SM_CXSCREEN ) - width ) / 2; _rectW.top = ( GetSystemMetrics( SM_CYSCREEN ) - height ) / 2; _rectW.right = _rectW.left + width; _rectW.bottom = _rectW.top + height; _styleW = WS_POPUP | WS_MINIMIZEBOX | WS_VISIBLE | WS_CAPTION; _hwnd = CreateWindowEx( 0, L"SaberEngineWnd", _wstrWinTitle, _styleW, _rectW.left, _rectW.top, width, height, 0, 0, _hInst, 0 ); if ( !_hwnd ) return false; ShowWindow( _hwnd, SW_SHOW ); UpdateWindow( _hwnd ); if ( !_Initialize() ) return false; _bActive = true; return true; } //------------------------------------------------------------- void __stdcall SaberEngine::Halt() { if ( _hwnd ) DestroyWindow( _hwnd ); } //------------------------------------------------------------- void __stdcall SaberEngine::SetWndTitle( LPCWSTR value ) { wcscpy( _wstrWinTitle, value ); } //------------------------------------------------------------- void __stdcall SaberEngine::SetResX( int value ) { if ( !_pD3dDevice ) if ( value > 0 ) _nScreenResX = value; } void __stdcall SaberEngine::SetResY( int value ) { if ( !_pD3dDevice ) if ( value > 0 ) _nScreenResY = value; } void __stdcall SaberEngine::SetBD( int value ) { if ( !_pD3dDevice ) _nScreenBD = value; } //------------------------------------------------------------- bool __stdcall SaberEngine::BeginScene() { //if ( _pVertices ) // return false; _pD3dDevice->BeginScene(); //if ( FAILED( _pVB->Lock( 0, 0, (VOID**)&_pVertices, 0 ) ) ) // return false; return true; } //------------------------------------------------------------- void __stdcall SaberEngine::EndScene() { //_RenderAll( true ); _pD3dDevice->EndScene(); _pD3dDevice->Present( 0, 0, 0, 0 ); } //------------------------------------------------------------- void __stdcall SaberEngine::Clear( DWORD color ) { _pD3dDevice->Clear( 0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, color, 1.0f, 0 ); } //------------------------------------------------------------- void __stdcall SaberEngine::RenderQuad( const PQUAD quad ) { // TODO: put batching code here //if ( _pVertices ) //{ // if ( _curTexture != quad->tex || _nPrim >= SBR_VERTEX_BUFFER_SIZE / 4 ) // { // _RenderAll(); // if ( _curTexture != quad->tex ) // { // _pD3dDevice->SetTexture( 0, quad->tex ); // _curTexture = quad->tex; // } // } // memcpy( &_pVertices[ _nPrim * 4 ], quad->v, sizeof(SbrVertex) * 4 ); // _nPrim++; //} PVOID pVertices; _pVB->Lock( 0, 0, (void**)&pVertices, 0 ); memcpy( pVertices, quad->v, sizeof(quad->v)); _pVB->Unlock(); _pD3dDevice->SetTexture( 0, (LPDIRECT3DTEXTURE9)(quad->tex) ); _pD3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 2 ); } //------------------------------------------------------------- void __stdcall SaberEngine::SetOnClose( SbrPlugFunc pFunc ) { _pOnCloseFunc = pFunc; } void __stdcall SaberEngine::SetOnFocusGain( SbrPlugFunc pFunc ) { _pOnFocusGainFunc = pFunc; } void __stdcall SaberEngine::SetOnFocusLost( SbrPlugFunc pFunc ) { _pOnFocusLostFunc = pFunc; } //------------------------------------------------------------- void __stdcall SaberEngine::PlugFunc( SbrPlugMsgFunc pFunc ) { _vFuncs.push_back( pFunc ); } //------------------------------------------------------------- void __stdcall SaberEngine::UnplugFunc( SbrPlugMsgFunc pFunc ) { std::vector<SbrPlugMsgFunc>::iterator iTemp; for ( iTemp = _vFuncs.begin(); iTemp != _vFuncs.end(); iTemp++ ) { if ( *iTemp = pFunc ) { _vFuncs.erase( iTemp ); break; } } } //------------------------------------------------------------- SBRFONT SaberEngine::CreateFont( LPCWSTR facename, int size ) { ID3DXFont* pFont; if ( FAILED ( D3DXCreateFont( _pD3dDevice, size, 0, FW_BOLD, 0, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, facename, &pFont ) ) ) return 0; return (SBRFONT)pFont; } //------------------------------------------------------------- SBRTEXTURE __stdcall SaberEngine::LoadTexture( LPCWSTR filename )//, DWORD size, bool bMipmap ) { LPDIRECT3DTEXTURE9 pTex; D3DXIMAGE_INFO info; if ( !_pD3dDevice ) return 0; if ( FAILED( D3DXCreateTextureFromFileEx( _pD3dDevice, filename, 0, 0, 0, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, D3DX_FILTER_NONE, D3DX_FILTER_NONE, SBR_ALPHACH, &info, 0, &pTex ) ) ) return 0; _vTextures.push_back( new TEXTURE( (SBRTEXTURE)pTex, info.Width, info.Height ) ); return (SBRTEXTURE)pTex; } //------------------------------------------------------------- INT __stdcall SaberEngine::GetTextureWidth( SBRTEXTURE tex ) { BOOST_FOREACH( PTEXTURE pTex, _vTextures ) { if ( pTex->tex == tex ) return pTex->width; } return 0; } //------------------------------------------------------------- INT __stdcall SaberEngine::GetTextureHeight( SBRTEXTURE tex ) { BOOST_FOREACH( PTEXTURE pTex, _vTextures ) { if ( pTex->tex == tex ) return pTex->height; } return 0; } //------------------------------------------------------------- void __stdcall SaberEngine::ReleaseTexture( SBRTEXTURE tex ) { if ( !tex ) return; std::vector<PTEXTURE>::iterator iTemp; for ( iTemp = _vTextures.begin(); iTemp != _vTextures.end(); iTemp++ ) { if ( (*iTemp)->tex == tex ) { ((LPDIRECT3DTEXTURE9)((*iTemp)->tex))->Release(); _vTextures.erase( iTemp ); return; } } }; //------------------------------------------------------------- LRESULT __stdcall SaberEngine::WindowProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { if ( _self ) { BOOST_FOREACH( SbrPlugMsgFunc pFunc, _self->_vFuncs ) { pFunc( hWnd, msg, wParam, lParam ); } switch ( msg ) { case WM_SETCURSOR: if ( !_self->_bVisibleCursor ) SetCursor( 0 ); else SetCursor( LoadCursor( 0, IDC_ARROW ) ); return 0; case WM_CLOSE: if ( _self->_pOnCloseFunc ) _self->_pOnCloseFunc(); return 0; case WM_ACTIVATE: { bool bActivating = ( LOWORD(wParam) != WA_INACTIVE ) && ( HIWORD(wParam) == 0 ); if( _self->_pD3d && _self->_bActive != bActivating ) _self->_FocusChange( bActivating ); } } } return DefWindowProc( hWnd, msg, wParam, lParam ); } //-------------------------------------------------------------
[ [ [ 1, 576 ] ] ]
60741975643339ab6f1e0907cad975da4807a7cf
4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61
/CleanProject/ParticleUniverse/include/ParticleRenderers/ParticleUniverseBillboard.h
791b64c83fe34d3c051727712d4b0d8493e71218
[]
no_license
bahao247/apeengine2
56560dbf6d262364fbc0f9f96ba4231e5e4ed301
f2617b2a42bdf2907c6d56e334c0d027fb62062d
refs/heads/master
2021-01-10T14:04:02.319337
2009-08-26T08:23:33
2009-08-26T08:23:33
45,979,392
0
1
null
null
null
null
UTF-8
C++
false
false
1,132
h
/* ----------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2006-2008 Henry van Merode Usage of this program is free for non-commercial use and licensed under the the terms of the GNU Lesser General Public License. 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. ----------------------------------------------------------------------------- */ #ifndef __PU_BILLBOARD_H__ #define __PU_BILLBOARD_H__ #include "ParticleUniversePrerequisites.h" namespace ParticleUniverse { /** This is a child of the Ogre Billboard class, with the exception that it has new friends ;-) */ class _ParticleUniverseExport Billboard : public Ogre::Billboard { friend class BillboardRenderer; public: Billboard(void) : Ogre::Billboard(){}; virtual ~Billboard(void){}; }; } #endif
[ "pablosn@06488772-1f9a-11de-8b5c-13accb87f508" ]
[ [ [ 1, 36 ] ] ]
7337cf48238648d44b58695be3269049f06c283e
fb8ab028c5e7865229f7032052ef6419cce6d843
/patterndemo/src/ImageTable.h
bb7ee7ba7abd7396c4916474da1ae1852c3c1609
[]
no_license
alexunder/autumtao
d3fbca5b87fef96606501de8bfd600825b628e42
296db161b50c96efab48b05b5846e6f1ac90c38a
refs/heads/master
2016-09-05T09:43:36.361738
2011-03-25T16:13:51
2011-03-25T16:13:51
33,286,987
0
0
null
null
null
null
UTF-8
C++
false
false
2,030
h
#if !defined(AFX_IMAGETABLE_H__430D868D_4227_44E4_A419_6822438DE3D9__INCLUDED_) #define AFX_IMAGETABLE_H__430D868D_4227_44E4_A419_6822438DE3D9__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // ImageTable.h : header file // #define NUM_IMAGE 10 class ImageObject { public: ImageObject( HBITMAP m_himg ); ~ImageObject(); void DrawPic( HDC hdc ); void SetRect( RECT rect ); private: RECT m_rect; HBITMAP m_himg; }; ///////////////////////////////////////////////////////////////////////////// // CImageTable window class CImageTable : public CWnd { // Construction public: CImageTable(); // Attributes public: BOOL Create( int width, int heigth, LPCTSTR lpszWindowName, CWnd* pParentWnd ); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CImageTable) //}}AFX_VIRTUAL // Implementation bool SetImage( HBITMAP hbmp ); void CopyImageBuffer( unsigned char * buffer, int width, int hight ); void CopyImageBufferTo8( unsigned char * buffer, int width, int hight ); void algo_AverageFilter(); void algo_AverageFilter1(); void algo_findcontent(); void ClearImage(); void DumpImageData(); public: static HBITMAP CreateGrayBmp( unsigned char * buffer, int width, int hight ); public: virtual ~CImageTable(); private: int m_width; int m_heigth; int m_iflag; int m_inum_imgobject; ImageObject * m_imageobjects[NUM_IMAGE]; unsigned char * m_imagedate; int m_image_width; int m_image_heigth; // Generated message map functions protected: //{{AFX_MSG(CImageTable) afx_msg void OnPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_IMAGETABLE_H__430D868D_4227_44E4_A419_6822438DE3D9__INCLUDED_)
[ "Xalexu@59d19903-2beb-cf48-5e42-6f21bef2d45e" ]
[ [ [ 1, 86 ] ] ]
c241dc2e8510667696911f6d7b06c553e6915740
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/contrib/nxsi/src/nxsi/nxsi_mesh.cc
b7912e95e25586b3b6319a9f62766cb558dfedf8
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
18,345
cc
//----------------------------------------------------------------------------- // Copyright (c) Ville Ruusutie, 2004. All Rights Reserved. //----------------------------------------------------------------------------- // See the file "nxsi_license.txt" for information on usage and redistribution // of this file, and for a DISCLAIMER OF ALL WARRANTIES. //----------------------------------------------------------------------------- // nXSI mesh handling functions //----------------------------------------------------------------------------- #include "nxsi/nxsi.h" #include <scene/nskinanimator.h> #include <scene/nskinshapenode.h> #include <scene/nshapenode.h> #include <mathlib/quaternion.h> #include <kernel/nfileserver2.h> //----------------------------------------------------------------------------- void nXSI::HandleSIMesh(CSLMesh* mesh) { CSLModel* templ = mesh->ParentModel(); nString skinName(templ->Name().GetText()); nString animName(templ->Name().GetText()); bool hasAnimator = false; bool isMultiMesh = false; bool isSkinned = false; int groupCount = 0; int groupId; int i; // get filename nString meshFilename(this->options.GetMeshFilename()); if (!(this->options.GetOutputFlags() & nXSIOptions::OUTPUT_MERGEALL)) { meshFilename = mesh->Name().GetText(); if (this->options.GetOutputFlags() & nXSIOptions::OUTPUT_BINARY) { meshFilename.Append(".nvx2"); } else { meshFilename.Append(".n3d2"); } } // get transform information vector3 position = (vector3&)templ->Transform()->GetTranslation(); vector3 rotation = (vector3&)templ->Transform()->GetEulerRotation(); vector3 scale = (vector3&)templ->Transform()->GetScale(); VECTOR3_DEG2RAD(rotation); // get shape CSLShape* shape = (CSLShape*)mesh->Shape(); nArray<nXSIWeight> weightList; // destroy FTK converted triangle lists if (mesh->GetTriangleStripListCount() > 0) { mesh->ClearTriangleLists(); } // convert triangle_strip_lists to triangle_lists CSLTriangleStripList** stripLists = mesh->TriangleStripLists(); for (i = 0; i < mesh->GetTriangleStripListCount(); i++) { this->ConvertSITriangleStripList(stripLists[i]); } // convert polygon_lists to triangle_lists CSLPolygonList** polygonLists = mesh->PolygonLists(); for (i = 0; i < mesh->GetPolygonListCount(); i++) { this->ConvertSIPolygonList(polygonLists[i]); } // check if multi mesh if (mesh->GetTriangleListCount() > 1) { isMultiMesh = true; nTransformNode* newNode = (nTransformNode*)this->kernelServer.New("ntransformnode", mesh->Name().GetText()); this->kernelServer.PushCwd(newNode); newNode->SetPosition(position); newNode->SetEuler(rotation); newNode->SetScale(scale); // build transform animation if (this->BuildTransformAnimation(templ->Transform(), animName)) { newNode->AddAnimator(animName.Get()); } } // check if skinned mesh if (templ->GetEnvelopeCount() > 0) { isSkinned = true; this->HandleSIMeshSkeleton(mesh, skinName, weightList); } // create mesh parts CSLTriangleList** triangleLists = mesh->TriangleLists(); int triangleListCount = mesh->GetTriangleListCount(); if (triangleListCount > 0) { // read parts for (i = 0, groupId = this->meshGroupId; i < triangleListCount; i++, groupId++, groupCount++) { this->HandleSITriangleList(triangleLists[i], shape, weightList, groupId); } // if skinned, repartition mesh if (isSkinned) { nMeshBuilder newMesh; if (this->skinPartioner.PartitionMesh(this->meshBuilder, newMesh, 32)) { // group_count = m_skin_partioner.GetNumPartitions(); this->meshBuilder = newMesh; } else { n_printf("WARNING: repartitioning failed (%s)\n", mesh->Name().GetText()); } } // create parts for (i = 0, groupId = this->meshGroupId; i < groupCount; i++, groupId++) { // create part name nString meshName(mesh->Name().GetText()); if (isMultiMesh) { meshName += "_"; meshName += groupId; } // create new mesh node nShapeNode* newNode; if (isSkinned) newNode = (nShapeNode*)this->kernelServer.New("nskinshapenode", meshName.Get()); else newNode = (nShapeNode*)this->kernelServer.New("nshapenode", meshName.Get()); newNode->SetLocalBox(this->meshBuilder.GetGroupBBox(groupId)); newNode->SetMesh(meshFilename.Get()); newNode->SetGroupIndex(groupId); if (isMultiMesh) { newNode->SetPosition(vector3(0.0f, 0.0f, 0.0f)); newNode->SetEuler(vector3(0.0f, 0.0f, 0.0f)); newNode->SetScale(vector3(1.0f, 1.0f, 1.0f)); } else { this->kernelServer.PushCwd(newNode); newNode->SetPosition(position); newNode->SetEuler(rotation); newNode->SetScale(scale); // build transform animation if (this->BuildTransformAnimation(templ->Transform(), animName)) { newNode->AddAnimator(animName.Get()); } } { // get material variables CSLBaseMaterial* baseMaterial = triangleLists[i]->GetMaterial(); switch (baseMaterial->Type()) { case CSLTemplate::XSI_MATERIAL: HandleXSIMaterialVariables((CSLXSIMaterial*)baseMaterial, newNode, isSkinned); break; case CSLTemplate::SI_MATERIAL: HandleSIMaterialVariables((CSLMaterial*)baseMaterial, newNode, isSkinned); break; default: n_printf("WARNING: found unknown material type.\n"); break; } } // get bone joint infos if (isSkinned) { nSkinShapeNode* newSkinNode = (nSkinShapeNode*)newNode; int partCount = this->skinPartioner.GetNumPartitions(); newSkinNode->SetSkinAnimator(("../" + skinName).Get()); newSkinNode->BeginFragments(partCount); for (int p = 0; p < partCount; p++) { const nArray<int>& jointList = this->skinPartioner.GetJointPalette(p); newSkinNode->SetFragGroupIndex(p, groupId); newSkinNode->BeginJointPalette(p, jointList.Size()); for (int j = 0; j < jointList.Size(); j++) { newSkinNode->SetJointIndex(p, j, jointList[j]); } newSkinNode->EndJointPalette(p); } newSkinNode->EndFragments(); } } // update group id if merging if (this->options.GetOutputFlags() & nXSIOptions::OUTPUT_MERGEALL) { this->meshGroupId += groupCount; } // save mesh object if ((this->options.GetOutputFlags() & nXSIOptions::OUTPUT_MESH) && !(this->options.GetOutputFlags() & nXSIOptions::OUTPUT_MERGEALL)) { this->meshBuilder.BuildTriangleTangents(); this->meshBuilder.BuildVertexTangents(); this->meshBuilder.Cleanup(0); this->meshBuilder.Optimize(); this->meshBuilder.Save(nFileServer2::Instance(), meshFilename.Get()); this->meshBuilder.Clear(); n_printf("mesh saved: %s\n", meshFilename.Get()); } // handle child models CSLModel* *childList = templ->GetChildrenList(); for (int i = 0; i < templ->GetChildrenCount(); i++) { HandleSIModel(childList[i]); } this->kernelServer.PopCwd(); } } void RemapBones(int boneId, const nArray<int>& boneParentList, int& remapId, nArray<int>& boneRemapList) { int count = boneParentList.Size(); boneRemapList[remapId] = boneId; remapId++; for (int i = 0; i < count; i++) { if (boneParentList[i] == boneId) { RemapBones(i, boneParentList, remapId, boneRemapList); } } } void nXSI::HandleSIMeshSkeleton(CSLMesh* mesh, nString& skinName, nArray<nXSIWeight>& weightList) { CSLShape* shape = (CSLShape*)mesh->Shape(); CSLModel* templ = mesh->ParentModel(); nString animFilename; int vertexCount = shape->GetVertexCount(); int i, j, b, w; // set name skinName.Append("_animator"); animFilename = this->options.GetAnimFilename().Get(); if (!(this->options.GetOutputFlags() & nXSIOptions::OUTPUT_MERGEALL)) { animFilename = mesh->Name().GetText(); if (this->options.GetOutputFlags() & nXSIOptions::OUTPUT_BINARY) { animFilename.Append(".nax2"); } else { animFilename.Append(".nanim2"); } } // get envelope infos CSLEnvelope** envelopeList = templ->GetEnvelopeList(); int envelopeCount = templ->GetEnvelopeCount(); // create envelope remap list nArray<int> envelopeRemapList; envelopeRemapList.SetFixedSize(envelopeCount); // build skeleton { nArray<int> boneParentList; nArray<CSLModel*> boneList; boneParentList.SetFixedSize(envelopeCount); boneList.SetFixedSize(envelopeCount); // fill bone list for (i = 0; i < envelopeCount; i++) { boneList[i] = envelopeList[i]->GetDeformer(); } // fill parent list for (i = 0; i < envelopeCount; i++) { boneParentList[i] = -1; for (j = 0; j < envelopeCount; j++) { if (boneList[i]->ParentModel() == boneList[j]) { boneParentList[i] = j; } } } // create sorted list for (i = 0, b = 0; i < envelopeCount; i++) { if (boneParentList[i] == -1) { RemapBones(i, boneParentList, b, envelopeRemapList); break; } } envelopeCount = b; // remap bone list for (i = 0; i < envelopeCount; i++) { boneList[i] = envelopeList[envelopeRemapList[i]]->GetDeformer(); } // create skin animator nSkinAnimator* newNode = (nSkinAnimator*)this->kernelServer.New("nskinanimator", skinName.Get()); newNode->SetChannel("time"); newNode->SetLoopType(nAnimator::Loop); newNode->SetAnim(animFilename.Get()); // add joints newNode->BeginJoints(envelopeCount); for (i = 0; i < envelopeCount; i++) { int boneId = envelopeRemapList[i]; int parentId = -1; if (boneParentList[boneId] > -1) { parentId = envelopeRemapList[boneParentList[boneId]]; } CSLModel* joint = boneList[i]; // get joint info vector3 translation = (vector3&)(joint->Transform()->GetTranslation()); vector3 eulerRotation = (vector3&)(joint->Transform()->GetEulerRotation()); vector3 scale = (vector3&)(joint->Transform()->GetScale()); VECTOR3_DEG2RAD(eulerRotation); quaternion rotation; rotation.set_rotate_xyz(eulerRotation.x, eulerRotation.y, eulerRotation.z); // set joint newNode->SetJoint(i, parentId, translation, rotation, scale); newNode->AddJointName(i, joint->Name().GetText()); } newNode->EndJoints(); // build joint_animations this->BuildJointAnimations(boneList, envelopeCount); // set states newNode->SetStateChannel("charState"); newNode->BeginStates(1); newNode->SetState(0, this->animGroupId, 0.0f); newNode->BeginClips(0, 1); newNode->SetClip(0, 0, "one"); newNode->EndClips(0); newNode->EndStates(); } // create weight list weightList.SetFixedSize(vertexCount); // clear list for (i = 0; i < vertexCount; i++) { weightList[i].joints[0] = 0; weightList[i].joints[1] = 0; weightList[i].joints[2] = 0; weightList[i].joints[3] = 0; weightList[i].weights[0] = 0; weightList[i].weights[1] = 0; weightList[i].weights[2] = 0; weightList[i].weights[3] = 0; weightList[i].count = 0; } // fill weight list for (i = 0; i < envelopeCount; i++) { CSLEnvelope* envelope = envelopeList[envelopeRemapList[i]]; SLVertexWeight* envelopeWeights = envelope->GetVertexWeightListPtr(); int weightCount = envelope->GetVertexWeightCount(); // get envelope weights for (w = 0; w < weightCount; w++) { nXSIWeight& weight = weightList[(int)(envelopeWeights[w].m_fVertexIndex)]; if (weight.count < 4) { weight.joints[weight.count] = (float)(i); weight.weights[weight.count] = envelopeWeights[w].m_fWeight / 100.f; weight.count++; } else { n_printf("WARNING: too much weights in one vertex\n"); } } } // update group id if merging if (this->options.GetOutputFlags() & nXSIOptions::OUTPUT_MERGEALL) { this->animGroupId++; } // save skin animation if ((this->options.GetOutputFlags() & nXSIOptions::OUTPUT_ANIM) && !(this->options.GetOutputFlags() & nXSIOptions::OUTPUT_MERGEALL)) { this->animBuilder.Optimize(); this->animBuilder.FixKeyOffsets(); this->animBuilder.Save(nFileServer2::Instance(), animFilename.Get()); this->animBuilder.Clear(); n_printf("animation saved: %s\n", animFilename.Get()); } } void nXSI::HandleSITriangleList(CSLTriangleList* templ, CSLShape* shapeOld, const nArray<nXSIWeight>& weightList, uint groupId) { CSLModel* parentTempl = templ->ParentModel(); CSLShape_35* shape = (CSLShape_35*)shapeOld; int shapeType = shape->Type(); int firstVertex = this->meshBuilder.GetNumVertices(); int triangleCount = templ->GetTriangleCount(); int vertexCount = triangleCount * 3; bool isSkinned = false; int i, j; // check if mesh is skinned if (parentTempl->GetEnvelopeCount() > 0) { isSkinned = true; } // get uvset count int uvsetCount = templ->GetUVArrayCount(); if (shapeType == CSLTemplate::SI_SHAPE35) { if (uvsetCount > NXSI_MAX_UVSETS) { n_printf("WARNING: found %i uvsets. clamping into %i sets.\n", uvsetCount, NXSI_MAX_UVSETS); uvsetCount = NXSI_MAX_UVSETS; } } else if (uvsetCount > 1) { uvsetCount = 1; } if (uvsetCount == 0) { n_printf("WARNING: uv coordinates not found (%s). may result strange lighting.\n", parentTempl->Name().GetText()); } // fill vertex list { int* triPositions = templ->GetVertexIndicesPtr(); int* triNormals = templ->GetNormalIndicesPtr(); int* triColors = templ->GetColorIndicesPtr(); int* triUvset[NXSI_MAX_UVSETS]; for (i = 0; i < uvsetCount; i++) { triUvset[i] = templ->GetUVIndicesPtr(i); } vector3* positions = (vector3*)(shape->GetVertexListPtr()); vector3* normals = (vector3*)(shape->GetNormalListPtr()); vector4* colors = (vector4*)shape->GetColorListPtr(); vector2* uvset[NXSI_MAX_UVSETS]; if (shapeType == CSLTemplate::SI_SHAPE35) { for (i = 0; i < uvsetCount; i++) { uvset[i] = (vector2*)(shape->UVCoordArrays()[i]->GetUVCoordListPtr()); } } else { uvset[0] = (vector2*)(shapeOld->GetUVCoordListPtr()); } nMeshBuilder::Vertex vertex; for (i = 0; i < vertexCount; i++) { vertex.SetCoord(positions[*triPositions]); if (isSkinned) { vertex.SetJointIndices(*((vector4*)(&weightList[*triPositions].joints))); vertex.SetWeights(*((vector4*)(&weightList[*triPositions].weights))); } triPositions++; if (normals) { vertex.SetNormal(normals[*triNormals]); triNormals++; } if (colors) { vertex.SetColor(colors[*triColors]); triColors++; } for (j = 0; j < uvsetCount; j++) { vertex.SetUv(j, uvset[j][*triUvset[j]]); triUvset[j]++; } this->meshBuilder.AddVertex(vertex); } } // fill triangle list nMeshBuilder::Triangle triangle; for (i = 0; i < triangleCount; i++) { triangle.SetVertexIndices(firstVertex + i*3, firstVertex + i*3 + 1, firstVertex + i*3 + 2); triangle.SetGroupId(groupId); this->meshBuilder.AddTriangle(triangle); } } //----------------------------------------------------------------------------- // Eof
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 543 ] ] ]
f243f68dd6c9eb5af76ade765b615f256afdf8f0
699746171f662df8923b8894e5178126285beb2d
/Software/C++/vrpn_07_26/vrpn/vrpn_Tracker_Android.h
a704ff2ef2e9feb0c20608c270c94ce5da8095b5
[ "LicenseRef-scancode-public-domain" ]
permissive
iurnah/tesis
4793b539bec676255e0f880dc6524b1e70b78394
652d6096e53a56123408d325921981b0ff6c39fd
refs/heads/master
2021-01-24T19:51:48.438405
2011-06-27T11:44:23
2011-06-27T11:44:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,089
h
#pragma once //#include <windows.h> #include <winsock.h> //#include <ws2tcpip.h> //#include "json/json.h" #include "vrpn_tracker.h" #include "vrpn_button.h" #include "vrpn_analog.h" namespace Json { class Reader; class Value; } class vrpn_Tracker_GTab : public vrpn_Tracker, public vrpn_Button, public vrpn_Analog { public: vrpn_Tracker_GTab( const char* name, vrpn_Connection* c, int udpPort ); ~vrpn_Tracker_GTab(void); void mainloop(); enum { TILT_TRACKER_ID = 0, }; private: // Network stuff bool _network_init(int udp_port); int _network_receive(void *buffer, int maxlen, int tout_us); void _network_release(); SOCKET _socket; enum { _NETWORK_BUFFER_SIZE = 2000, }; char _network_buffer[_NETWORK_BUFFER_SIZE]; // Json stuff bool _parse(const char* buffer, int length); bool _parse_tracker_data(const Json::Value& root); bool _parse_analog(const Json::Value& root); bool _parse_button(const Json::Value& root); bool _parse_data(const Json::Value& root); Json::Reader* _pJsonReader; };
[ [ [ 1, 54 ] ] ]
adce534bf0765035334e54a76a6a05a69c7e6542
ce28ec891a0d502e7461fd121b4d96a308c9dab7
/dbmerge/mergers/MatchMerger.cc
7f5e5132838c20d6449a28dd10810791a846f85b
[]
no_license
aktau/Tangerine
fe84f6578ce918d1fa151138c0cc5780161b3b8f
179ac9901513f90b17c5cd4add35608a7101055b
refs/heads/master
2020-06-08T17:07:53.860642
2011-08-14T09:41:41
2011-08-14T09:41:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,160
cc
#include "MatchMerger.h" #include <limits> #include "MergeItemSubclasses.h" using namespace thera; #define QT_USE_FAST_CONCATENATION #define QT_USE_FAST_OPERATOR_PLUS #define MERGE_DEEP_CHECK template <class T> static inline float frobeniusf(const XForm<T> &xf) { float norm = 0.0f; for (int i = 0; i < 16; ++i) { norm += xf[i]*xf[i]; } return sqrt(norm); } MatchMerger::MatchMerger() { } MatchMerger::~MatchMerger() { qDebug() << "MatchMerger::~MatchMerger: ran"; } void MatchMerger::merge(SQLDatabase *left, SQLDatabase *right) { assert(mMapper != NULL); clear(); // avoid memory leaks QList<SQLFragmentConf> leftMatches = left->getMatches(); QList<SQLFragmentConf> rightMatches = right->getMatches(); QList<MergeItem *> fixedIdList; QList<MergeItem *> newIdList; QElapsedTimer timer; timer.start(); FragmentMap leftMap; leftMap.reserve(leftMatches.size()); // TODO: convert to QSet instead of QMap/QHash, the value is never used anyway IndexMap leftIndices; leftIndices.reserve(leftMatches.size()); foreach (const SQLFragmentConf& leftConf, leftMatches) { leftIndices.insert(leftConf.index(), &leftConf); } qDebug() << "MatchMerger::merge: constructing index map of size" << leftIndices.size() << "took" << timer.restart() << "msec"; foreach (const SQLFragmentConf& leftConf, leftMatches) { int min = qMin(leftConf.mFragments[IFragmentConf::SOURCE], leftConf.mFragments[IFragmentConf::TARGET]); int max = qMax(leftConf.mFragments[IFragmentConf::SOURCE], leftConf.mFragments[IFragmentConf::TARGET]); IntPair pair(min, max); FragmentMap::iterator i = leftMap.find(pair); if (i != leftMap.end()) { i.value() << &leftConf; //qDebug() << "List existed already, current list size for pair" << pair << "=" << i.value().size(); } else { leftMap.insert(pair, FragConfList() << &leftConf); } } qDebug() << "MatchMerger::merge: constructing fragment map of size" << leftMap.size() << "took" << timer.restart() << "msec"; FragmentMap::const_iterator end = leftMap.constEnd(); foreach (const SQLFragmentConf& rightConf, rightMatches) { int min = qMin(rightConf.mFragments[IFragmentConf::SOURCE], rightConf.mFragments[IFragmentConf::TARGET]); int max = qMax(rightConf.mFragments[IFragmentConf::SOURCE], rightConf.mFragments[IFragmentConf::TARGET]); IntPair pair(min, max); FragmentMap::const_iterator i = leftMap.constFind(pair); // if the current match in the right database has the same fragments as a match // on the left database, look into it to see if it either is the same match (ID merging) if (i != end) { //const FragConfList& list = i.value(); int id = idOfIdenticalMatch(rightConf, i.value()); if (id != -1 && rightConf.index() != id) { // this means that the current item on the right matches one on the right // but doesn't have the same ID, we'll just map the right ID to the left ID // so that future mergers can recognize that both match id's refer to // the same object qDebug("MatchMerger::merge: right id (%d) is from now on equal to left id (%d)", rightConf.index(), id); mMapper->addMapping(MergeMapper::MATCH_ID, rightConf.index(), id); continue; } else { // this means the current item on the left matches on on the right // and has the same ID, nothing needs to happen continue; } } // this means the current item from right doesn't match any in left // if the ID assigned to it is occupied, we have to pick a new one if (leftIndices.contains(rightConf.index())) { // it's occupied, we have to pick a new one qDebug() << "MatchMerger::merge: ID conflict, reassigning" << rightConf.index() << "to another ID. right (source <-> conf) = " << rightConf.getSourceId() << "<->" << rightConf.getTargetId(); newIdList << new MatchMergeItem(rightConf.index(), rightConf.getSourceId(), rightConf.getTargetId(), rightConf.mXF); } // in this case the match didn't conflict with any id, we can merge it in // under the same id // these should be inserted under their original id and also shouldn't receive a mapping/ // we already assign an action else { qDebug() << "MatchMerger::merge: merging in but keeping id:" << rightConf.index(); MatchMergeItem *item = new MatchMergeItem(rightConf.index(), rightConf.getSourceId(), rightConf.getTargetId(), rightConf.mXF); AssignIdAction action(rightConf.index()); action.visit(item); fixedIdList << item; } } // fixed ID's first! mItems << fixedIdList; mItems << newIdList; } void MatchMerger::execute(SQLDatabase *left, MergeMapper *mapper) { assert(left != NULL && mapper != NULL); // order transactions correctly (those without ID reassignment first!) left->transaction(); foreach (MergeItem *item, mItems) { if (!item->isDone()) { if (!item->execute(left, mapper)) { qDebug() << "MatchMerger::execute: item" << item->message() << "did not execute properly"; } } } left->commit(); } inline int MatchMerger::idOfIdenticalMatch(const thera::SQLFragmentConf& conf , const FragConfList& list, float threshold) const { // compare based on XF, the fragments are already the same // TODO: detect the case in which fragments are reversed and then complain about it (might be slow and shouldn't happen though) // TODO: remove "norms", it's just for debugging purposes const XF baseXF = conf.mXF; QList<float> norms; norms.reserve(list.size()); float smallestNorm = std::numeric_limits<float>::max(); int id = -1; foreach (const SQLFragmentConf *possibleConf, list) { norms << frobeniusf(baseXF - possibleConf->mXF); if (norms.last() < smallestNorm) { smallestNorm = norms.last(); id = possibleConf->index(); } } QStringList ids; ids << QString("<%1>").arg(conf.index()); foreach (const SQLFragmentConf *possibleConf, list) ids << QString::number(possibleConf->index()); qDebug() << "norms =" << norms << ids.join(" - "); return (smallestNorm < threshold) ? id : -1; }
[ [ [ 1, 183 ] ] ]
34f8cf8bcd7ba10c673bcb0a4739b39f5b3581a0
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/include/ParticleAffectors/ParticleUniverseJetAffectorFactory.h
46159e24a55f304eeef8ac57e0b5150c389465ea
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,036
h
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #ifndef __PU_JET_AFFECTOR_FACTORY_H__ #define __PU_JET_AFFECTOR_FACTORY_H__ #include "ParticleUniversePrerequisites.h" #include "ParticleUniverseJetAffectorTokens.h" #include "ParticleUniverseJetAffector.h" #include "ParticleUniverseAffectorFactory.h" namespace ParticleUniverse { /** Factory class responsible for creating the JetAffector. */ class _ParticleUniverseExport JetAffectorFactory : public ParticleAffectorFactory { public: JetAffectorFactory(void) {}; virtual ~JetAffectorFactory(void) {}; /** See ParticleAffectorFactory */ Ogre::String getAffectorType(void) const { return "Jet"; } /** See ParticleAffectorFactory */ ParticleAffector* createAffector(void) { return _createAffector<JetAffector>(); } /** See ScriptReader */ virtual bool translateChildProperty(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { return mJetAffectorTranslator.translateChildProperty(compiler, node); }; /** See ScriptReader */ virtual bool translateChildObject(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { return mJetAffectorTranslator.translateChildObject(compiler, node); }; /* */ virtual void write(ParticleScriptSerializer* serializer , const IElement* element) { // Delegate mJetAffectorWriter.write(serializer, element); } protected: JetAffectorWriter mJetAffectorWriter; JetAffectorTranslator mJetAffectorTranslator; }; } #endif
[ [ [ 1, 67 ] ] ]
696037d647b3b8c7cb5a0264710bc57449151b67
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/tutorials/src/esample/nesample.cc
34025b8e40aacadafd31bcd9e051140a3cfa5a09
[]
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
97
cc
#include "esample/nesample.h" nNebulaEntityObject(neSample,"nentityobject","nesampleclass");
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 3 ] ] ]
f950f502b9f4e6d14a59bcf13968b51432f9fc96
2112057af069a78e75adfd244a3f5b224fbab321
/branches/refactor/src_root/include/common/OgreOde/OgreOdeBody.h
be4db44726c3f35c5e62fdea9b707bd683988a01
[]
no_license
blockspacer/ireon
120bde79e39fb107c961697985a1fe4cb309bd81
a89fa30b369a0b21661c992da2c4ec1087aac312
refs/heads/master
2023-04-15T00:22:02.905112
2010-01-07T20:31:07
2010-01-07T20:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,900
h
#ifndef _OGREODEBODY_H_ #define _OGREODEBODY_H_ #include "OgreOdePreReqs.h" namespace OgreOde { class _OgreOdeExport Body: public MaintainedItem ,public MovableObject { friend class Joint; friend class World; friend class Geometry; public: Body(const String& name = StringUtil::BLANK); virtual ~Body(); static const String MovableType; void setPosition(const Vector3& position); void setOrientation(const Quaternion& orientation); void setLinearVelocity(const Vector3& linear_velocity); void setAngularVelocity(const Vector3& angular_velocity); void setTorque(const Vector3& torque); const Vector3& getPosition(); const Quaternion& getOrientation(); const Vector3& getLinearVelocity(); const Vector3& getAngularVelocity(); virtual const String& getMovableType() const; virtual const String& getName(void) const; virtual const AxisAlignedBox& getBoundingBox(void) const; virtual Real getBoundingRadius(void) const; virtual void _updateRenderQueue(RenderQueue* queue); virtual void _notifyAttached(Node* parent,bool isTagPoint = false); virtual void _notifyCurrentCamera(Camera* camera); void updateParentNode(); void deriveLocation(); void setMass(const Mass& mass); const Mass& getMass(); void addForce(const Vector3& force); void addTorque(const Vector3& torque); void addRelativeForce(const Vector3& force); void addRelativeTorque(const Vector3& torque); void addForceAt(const Vector3& force,const Vector3& position); void addForceAtRelative(const Vector3& force,const Vector3& position); void addRelativeForceAt(const Vector3& force,const Vector3& position); void addRelativeForceAtRelative(const Vector3& force,const Vector3& position); const Vector3& getForce(); const Vector3& getTorque(); Vector3 getPointWorldPosition(const Vector3& position); Vector3 getPointWorldVelocity(const Vector3& position); Vector3 getPointVelocity(const Vector3& position); Vector3 getPointBodyPosition(const Vector3& position); Vector3 getVectorToWorld(const Vector3& vector); Vector3 getVectorFromWorld(const Vector3& vector); void wake(); void sleep(); bool isAwake(); void setAutoSleep(bool auto_sleep); bool getAutoSleep(); void setAutoSleepLinearThreshold(Real linear_threshold); Real getAutoSleepLinearThreshold(); void setAutoSleepAngularThreshold(Real angular_threshold); Real getAutoSleepAngularThreshold(); void setAutoSleepSteps(int steps); int getAutoSleepSteps(); void setAutoSleepTime(Real time); Real getAutoSleepTime(); void setAutoSleepDefaults(); void setFiniteRotationMode(bool on); bool getFiniteRotationMode(); void setFiniteRotationAxis(const Vector3& axis); const Vector3& getFiniteRotationAxis(); int getJointCount(); Joint* getJoint(int index); int getGeometryCount(); Geometry* getGeometry(int index); void setAffectedByGravity(bool on); bool getAffectedByGravity(); void setDamping(Real linear_damping,Real angular_damping); Real getLinearDamping(); Real getAngularDamping(); void setUserData(unsigned long user_data); unsigned long getUserData(); virtual unsigned long getID(); virtual void sync(); virtual void setDebug(bool debug); protected: dBodyID getBodyID() const; void destroyDebugNode(); void addDebugNode(Node* node); void recursiveSetMode(SceneNode* node); void applyDamping(); protected: dBodyID _body; String _name; Node* _debug_node; static int _body_count; Vector3 _position,_linear_vel,_angular_vel,_finite_axis,_force,_torque; Quaternion _orientation; AxisAlignedBox _bounding_box; Mass* _mass; dReal _linear_damping,_angular_damping; unsigned long _user_data; }; } #endif
[ [ [ 1, 131 ] ] ]
70079638359bc4d0df7c650c8ca8a6d7be6c09a7
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/aux_/config/has_apply.hpp
594e813e0742d14b92929dbbc4ef080e92746fb9
[]
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
1,061
hpp
#ifndef BOOST_MPL_AUX_CONFIG_HAS_APPLY_HPP_INCLUDED #define BOOST_MPL_AUX_CONFIG_HAS_APPLY_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2004 // // 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/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/aux_/config/has_apply.hpp,v $ // $Date: 2006/04/17 23:47:07 $ // $Revision: 1.1 $ #include <boost/mpl/aux_/config/has_xxx.hpp> #include <boost/mpl/aux_/config/msvc.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #if !defined(BOOST_MPL_CFG_NO_HAS_APPLY) \ && ( defined(BOOST_MPL_CFG_NO_HAS_XXX) \ || BOOST_WORKAROUND(__EDG_VERSION__, < 300) \ || BOOST_WORKAROUND(BOOST_MSVC, <= 1300) \ || BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3202)) \ ) # define BOOST_MPL_CFG_NO_HAS_APPLY #endif #endif // BOOST_MPL_AUX_CONFIG_HAS_APPLY_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 32 ] ] ]
c38dd3a17675b951f0571eec11f88ad7690cc316
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/SRC/DRIVERS/HSMMC/HSMMCCh2/s3c6410_hsmmc_drv/s3c6410_hsmmc.cpp
d2cc77f4ba476dd985e6542fb6d13d98ed095bfe
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
10,542
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this source code is subject to the terms of the Microsoft end-user // license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. // If you did not accept the terms of the EULA, you are not authorized to use // this source code. For a copy of the EULA, please see the LICENSE.RTF on your // install media. // #include <windows.h> #include <nkintr.h> #include <ceddk.h> #include <s3c6410.h> #include <cebuscfg.h> #include "s3c6410_hsmmc.h" #define _SRCCLK_48MHZ_ // from USB PHY (Keep sync with "sdhcslot.cpp") // Global Variables LPCTSTR HostControllerName = TEXT("HSMMCCh2"); static volatile S3C6410_GPIO_REG *pIOPreg = NULL; #ifdef _SMDK6410_CH2_EXTCD_ // New Constructor for card detect of HSMMC ch2 on SMDK6410. CSDHControllerCh2::CSDHControllerCh2() : CSDHCBase() { m_htCardDetectThread = NULL; m_hevCardDetectEvent = NULL; m_dwSDDetectSysIntr = SYSINTR_UNDEFINED; } #endif BOOL CSDHControllerCh2::Init(LPCTSTR pszActiveKey) { RETAILMSG(TRUE,(TEXT("[HSMMC2] Initializing the HSMMC Host Controller\n"))); // HSMMC Ch2 initialization if (!InitCh()) return FALSE; return CSDHCBase::Init(pszActiveKey); } VOID CSDHControllerCh2::PowerUp() { RETAILMSG(FALSE,(TEXT("[HSMMC2] Power Up the HSMMC Host Controller\n"))); // HSMMC Ch2 initialization for "WakeUp" if (!InitCh()) return; CSDHCBase::PowerUp(); } extern "C" PCSDHCBase CreateHSMMCHCCh2Object() { return new CSDHControllerCh2; } VOID CSDHControllerCh2::DestroyHSMMCHCCh2Object(PCSDHCBase pSDHC) { DEBUGCHK(pSDHC); delete pSDHC; } // The function that initilize SYSCON for a clock gating. BOOL CSDHControllerCh2::InitClkPwr() { volatile S3C6410_SYSCON_REG *pCLKPWR = NULL; PHYSICAL_ADDRESS ioPhysicalBase = {0,0}; ioPhysicalBase.LowPart = S3C6410_BASE_REG_PA_SYSCON; pCLKPWR = (volatile S3C6410_SYSCON_REG *)MmMapIoSpace(ioPhysicalBase, sizeof(S3C6410_SYSCON_REG), FALSE); if (pCLKPWR == NULL) { RETAILMSG(TRUE, (TEXT("[HSMMC2] Clock & Power Management Special Register is *NOT* mapped.\n"))); return FALSE; } #ifdef _SRCCLK_48MHZ_ RETAILMSG(FALSE, (TEXT("[HSMMC2] Setting registers for the USB48MHz (EXTCLK for SDCLK) : SYSCon.\n"))); // SCLK_HSMMC#_48 : CLK48M_PHY(OTH PHY 48MHz Clock Source from SYSCON block) // To use the USB clock, must be set the "USB_SIG_MASK" bit in the syscon register. pCLKPWR->OTHERS |= (0x1<<16); // set USB_SIG_MASK pCLKPWR->HCLK_GATE |= (0x1<<19); // Gating HCLK for HSMMC2 pCLKPWR->SCLK_GATE |= (0x1<<29); // Gating special clock for HSMMC2 (SCLK_MMC2_48) #else RETAILMSG(TRUE, (TEXT("[HSMMC2] Setting registers for the EPLL (for SDCLK) : SYSCon.\n"))); // SCLK_HSMMC# : EPLLout, MPLLout, PLL_source_clk or CLK27 clock // (from SYSCON block, can be selected by MMC#_SEL[1:0] fields of the CLK_SRC register in SYSCON block) // Set the clock source to EPLL out for CLKMMC2 pCLKPWR->CLK_SRC = (pCLKPWR->CLK_SRC & ~(0x3<<22) & ~(0x1<<2)) | // Control MUX(MMC2:MOUT EPLL) (0x1<<2); // Control MUX(EPLL:FOUT EPLL) pCLKPWR->HCLK_GATE |= (0x1<<19); // Gating HCLK for HSMMC2 pCLKPWR->SCLK_GATE = (pCLKPWR->SCLK_GATE) | (0x1<<26); // Gating special clock for HSMMC2 (SCLK_MMC2) #endif MmUnmapIoSpace((PVOID)pCLKPWR, sizeof(S3C6410_SYSCON_REG)); return TRUE; } // The function that initilize GPIO for DAT, CD and WP lines. BOOL CSDHControllerCh2::InitGPIO() { PHYSICAL_ADDRESS ioPhysicalBase = {0,0}; if (NULL == pIOPreg) { ioPhysicalBase.LowPart = S3C6410_BASE_REG_PA_GPIO; pIOPreg = (volatile S3C6410_GPIO_REG *)MmMapIoSpace(ioPhysicalBase, sizeof(S3C6410_GPIO_REG), FALSE); if (pIOPreg == NULL) { RETAILMSG(TRUE, (TEXT("[HSMMC2] GPIO registers is *NOT* mapped.\n"))); return FALSE; } } RETAILMSG(FALSE, (TEXT("[HSMMC2] Setting registers for the GPIO.\n"))); pIOPreg->GPCCON = (pIOPreg->GPCCON & ~(0xFF<<16)) | (0x33<<16); // CLK2[GPC5], CMD2[GPC4] for the MMC 2 pIOPreg->GPCPUD &= ~(0xF<<8); // Pull-up/down disabled pIOPreg->GPHCON0 = (pIOPreg->GPHCON0 & ~(0xFF<<24)) | (0x33<<24); // 4'b0010 for the MMC 2 pIOPreg->GPHCON1 = (pIOPreg->GPHCON1 & ~(0xFF<<0)) | (0x33<<0); // 4'b0010 for the MMC 2 pIOPreg->GPHPUD &= ~(0xFF<<12); // Pull-up/down disabled #ifdef _SMDK6410_CH2_WP_ pIOPreg->GPNCON &= ~(0x3<<28); // WP_SD2 pIOPreg->GPNPUD &= ~(0x3<<28); // Pull-up/down disabled #endif #ifndef _SMDK6410_CH2_EXTCD_ #endif #ifdef _SMDK6410_CH2_EXTCD_ // Setting for card detect pin of HSMMC Ch2 on SMDK6410. pIOPreg->GPNCON = ( pIOPreg->GPNCON & ~(0x3<<30) ) | (0x2<<30); // SD_CD2 by EINT15 pIOPreg->GPNPUD = ( pIOPreg->GPNPUD & ~(0x3<<30) ) | (0x0<<30); // pull-up/down disabled pIOPreg->EINT0CON0 = ( pIOPreg->EINT0CON0 & ~(0x7<<28)) | (0x7<<28); // Both edge triggered pIOPreg->EINT0PEND = ( pIOPreg->EINT0PEND | (0x1<<15) ); //clear EINT15 pending bit pIOPreg->EINT0MASK = ( pIOPreg->EINT0MASK & ~(0x1<<15)); //enable EINT15 #endif //MmUnmapIoSpace((PVOID)pIOPreg, sizeof(S3C6410_GPIO_REG)); return TRUE; } // The function that initilize the register for HSMMC Control. BOOL CSDHControllerCh2::InitHSMMC() { volatile S3C6410_HSMMC_REG *pHSMMC = NULL; PHYSICAL_ADDRESS ioPhysicalBase = {0,0}; ioPhysicalBase.LowPart = S3C6410_BASE_REG_PA_HSMMC2; pHSMMC = (volatile S3C6410_HSMMC_REG *)MmMapIoSpace(ioPhysicalBase, sizeof(S3C6410_HSMMC_REG), FALSE); if (pHSMMC == NULL) { RETAILMSG(TRUE, (TEXT("[HSMMC2] HSMMC Special Register is *NOT* mapped.\n"))); return FALSE; } #ifdef _SRCCLK_48MHZ_ RETAILMSG(FALSE, (TEXT("[HSMMC2] Setting registers for the USB48MHz (EXTCLK) : HSMMCCon.\n"))); // Set the clock source to USB_PHY for CLKMMC0 pHSMMC->CONTROL2 = (pHSMMC->CONTROL2 & ~(0xffffffff)) | (0x3<<9) | // Debounce Filter Count 0x3=64 iSDCLK (0x1<<8) | // SDCLK Hold Enable (0x3<<4); // Base Clock Source = External Clock #else RETAILMSG(TRUE, (TEXT("[HSMMC2] Setting registers for the EPLL : HSMMCCon.\n"))); // Set the clock source to EPLL out for CLKMMC0 pHSMMC->CONTROL2 = (pHSMMC->CONTROL2 & ~(0xffffffff)) | (0x3<<9) | // Debounce Filter Count 0x3=64 iSDCLK (0x1<<8) | // SDCLK Hold Enable (0x2<<4); // Base Clock Source = EPLL out #endif MmUnmapIoSpace((PVOID)pHSMMC, sizeof(S3C6410_HSMMC_REG)); return TRUE; } BOOL CSDHControllerCh2::InitCh() { if (!InitClkPwr()) return FALSE; if (!InitGPIO()) return FALSE; if (!InitHSMMC()) return FALSE; return TRUE; } #ifdef _SMDK6410_CH2_EXTCD_ // New function to Card detect thread of HSMMC Ch2 on SMDK6410. DWORD CSDHControllerCh2::CardDetectThread() { BOOL bSlotStateChanged = FALSE; DWORD dwWaitResult = WAIT_TIMEOUT; PCSDHCSlotBase pSlotZero = GetSlot(0); CeSetThreadPriority(GetCurrentThread(), 100); while(1) { // Wait for the next insertion/removal interrupt dwWaitResult = WaitForSingleObject(m_hevCardDetectEvent, INFINITE); Lock(); pSlotZero->HandleInterrupt(SDSLOT_INT_CARD_DETECTED); Unlock(); InterruptDone(m_dwSDDetectSysIntr); EnableCardDetectInterrupt(); } return TRUE; } // New function to request a SYSINTR for Card detect interrupt of HSMMC Ch2 on SMDK6410. BOOL CSDHControllerCh2::InitializeHardware() { m_dwSDDetectIrq = SD_CD2_IRQ; // convert the SDI hardware IRQ into a logical SYSINTR value if (!KernelIoControl(IOCTL_HAL_REQUEST_SYSINTR, &m_dwSDDetectIrq, sizeof(DWORD), &m_dwSDDetectSysIntr, sizeof(DWORD), NULL)) { // invalid SDDetect SYSINTR value! RETAILMSG(TRUE, (TEXT("[HSMMC2] invalid SD detect SYSINTR value!\n"))); m_dwSDDetectSysIntr = SYSINTR_UNDEFINED; return FALSE; } return CSDHCBase::InitializeHardware(); } // New Start function for Card detect of HSMMC ch2 on SMDK6410. SD_API_STATUS CSDHControllerCh2::Start() { SD_API_STATUS status = SD_API_STATUS_INSUFFICIENT_RESOURCES; m_fDriverShutdown = FALSE; // allocate the interrupt event m_hevInterrupt = CreateEvent(NULL, FALSE, FALSE,NULL); if (NULL == m_hevInterrupt) { goto EXIT; } // initialize the interrupt event if (!InterruptInitialize (m_dwSysIntr, m_hevInterrupt, NULL, 0)) { goto EXIT; } m_fInterruptInitialized = TRUE; // create the interrupt thread for controller interrupts m_htIST = CreateThread(NULL, 0, ISTStub, this, 0, NULL); if (NULL == m_htIST) { goto EXIT; } // allocate the card detect event #ifdef OMNIBOOK_VER m_hevCardDetectEvent = CreateEvent(NULL, FALSE, FALSE, _T("OMNIBOOK_EVENT_SDMMCCH2CD")); #else //!OMNIBOOK_VER m_hevCardDetectEvent = CreateEvent(NULL, FALSE, FALSE,NULL); #endif OMNIBOOK_VER if (NULL == m_hevCardDetectEvent) { goto EXIT; } // initialize the interrupt event if (!InterruptInitialize (m_dwSDDetectSysIntr, m_hevCardDetectEvent, NULL, 0)) { goto EXIT; } // create the card detect interrupt thread m_htCardDetectThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)SD_CardDetectThread, this, 0, NULL); if (NULL == m_htCardDetectThread) { goto EXIT; } for (DWORD dwSlot = 0; dwSlot < m_cSlots; ++dwSlot) { PCSDHCSlotBase pSlot = GetSlot(dwSlot); status = pSlot->Start(); if (!SD_API_SUCCESS(status)) { goto EXIT; } } // wake up the interrupt thread to check the slot ::SetInterruptEvent(m_dwSDDetectSysIntr); status = SD_API_STATUS_SUCCESS; EXIT: if (!SD_API_SUCCESS(status)) { // Clean up Stop(); } return status; } // New function for enabling the Card detect interrupt of HSMMC ch2 on SMDK6410. BOOL CSDHControllerCh2::EnableCardDetectInterrupt() { pIOPreg->EINT0PEND = ( pIOPreg->EINT0PEND | (0x1<<15)); //clear EINT15 pending bit pIOPreg->EINT0MASK = ( pIOPreg->EINT0MASK & ~(0x1<<15)); //enable EINT15 return TRUE; } #endif // The end of BSP_SMDK6410
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
[ [ [ 1, 290 ] ] ]
cf985ae46f29898d80642f804db70866a6d5ad4a
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Mathematics/Wm4Line3.h
123543159b7d9cdeef1e6b2e087ea568ca54a0d0
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
1,052
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4LINE3_H #define WM4LINE3_H #include "Wm4FoundationLIB.h" #include "Wm4Vector3.h" namespace Wm4 { template <class Real> class Line3 { public: // The line is represented as P+t*D where P is the line origin and D is // a unit-length direction vector. The user must ensure that the // direction vector satisfies this condition. // construction Line3 (); // uninitialized Line3 (const Vector3<Real>& rkOrigin, const Vector3<Real>& rkDirection); Vector3<Real> Origin, Direction; }; #include "Wm4Line3.inl" typedef Line3<float> Line3f; typedef Line3<double> Line3d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 42 ] ] ]
79375ec56d2db6436b622af3c7f29f0848c96fdc
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/com/XMLDOMComment.h
1c88f467aef188e2d8f11bd8cc9e6319fb71381d
[ "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,310
h
/* * Copyright 1999-2001,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. */ /* * $Log: XMLDOMComment.h,v $ * Revision 1.7 2004/09/08 13:55:35 peiyongz * Apache License Version 2.0 * * Revision 1.6 2004/02/25 18:38:33 amassari * The COM wrapper doesn't use the deprecated DOM anymore * * Revision 1.5 2003/11/21 12:05:48 amassari * Updated version to 2.4 * * Revision 1.4 2003/10/21 21:21:32 amassari * When the COM object is loaded by a late-binding engine (like WSH, or * Visual Basic when the type library is not preloaded in the editor), the type * library version stored in the resource must match the version specified in the * IDispatchImpl template (defaulted to 1.0), or trying to invoke a method will fail * * Revision 1.3 2003/03/14 12:44:49 tng * [Bug 17147] C++ namespace breaks build of XercesCOM DLL * * Revision 1.2 2002/05/21 19:53:53 tng * DOM Reorganization: update include path for the old DOM interface in COM files * * Revision 1.1.1.1 2002/02/01 22:21:40 peiyongz * sane_include * * Revision 1.5 2001/05/11 13:25:02 tng * Copyright update. * * Revision 1.4 2001/01/19 15:18:05 tng * COM Updates by Curt Arnold: changed 1.3 to 1.4, updated the GUID's so * both can coexist and fixed a new minor bugs. Most of the changes involved * error reporting, now a DOM defined error will return an HRESULT of * 0x80040600 + code and will set an error description to the error name. * * Revision 1.3 2000/06/03 00:28:57 andyh * COM Wrapper changes from Curt Arnold * * Revision 1.2 2000/03/30 02:00:11 abagchi * Initial checkin of working code with Copyright Notice * */ #ifndef ___xmldomcomment_h___ #define ___xmldomcomment_h___ #include <xercesc/dom/DOMComment.hpp> #include "IXMLDOMCharacterDataImpl.h" XERCES_CPP_NAMESPACE_USE class ATL_NO_VTABLE CXMLDOMComment : public CComObjectRootEx<CComSingleThreadModel>, public IXMLDOMCharacterDataImpl<IXMLDOMComment, &IID_IXMLDOMComment> { public: CXMLDOMComment() {} void FinalRelease() { ReleaseOwnerDoc(); } virtual DOMCharacterData* get_DOMCharacterData() { return comment;} virtual DOMNodeType get_DOMNodeType() const { return NODE_COMMENT; } DECLARE_NOT_AGGREGATABLE(CXMLDOMComment) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CXMLDOMComment) COM_INTERFACE_ENTRY(IXMLDOMComment) COM_INTERFACE_ENTRY(IXMLDOMCharacterData) COM_INTERFACE_ENTRY(IXMLDOMNode) COM_INTERFACE_ENTRY(IIBMXMLDOMNodeIdentity) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY(IDispatch) END_COM_MAP() DOMComment* comment; }; typedef CComObject<CXMLDOMComment> CXMLDOMCommentObj; #endif // ___xmldomcomment_h___
[ [ [ 1, 101 ] ] ]
d75e4c4e854d82db653df5145f970c5ad302a314
59ce53af7ad5a1f9b12a69aadbfc7abc4c4bfc02
/src/SkinResourceEditTool/EditStringDlg.h
9385d4e2f394d78cd021ea8348048825ecebda3e
[]
no_license
fingomajom/skinengine
444a89955046a6f2c7be49012ff501dc465f019e
6bb26a46a7edac88b613ea9a124abeb8a1694868
refs/heads/master
2021-01-10T11:30:51.541442
2008-07-30T07:13:11
2008-07-30T07:13:11
47,892,418
0
0
null
null
null
null
UTF-8
C++
false
false
2,072
h
#pragma once #include "resource.h" class CEditStringDlg : public CDialogImpl<CEditStringDlg> { public: CEditStringDlg(void); ~CEditStringDlg(void); public: enum { IDD = IDD_EDITSTRING_DIALOG }; BEGIN_MSG_MAP(CAboutDlg) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) COMMAND_ID_HANDLER(IDOK, OnOk) COMMAND_ID_HANDLER(IDCANCEL, OnCloseCmd) COMMAND_HANDLER(IDC_ID_EDIT, EN_CHANGE, OnEnChangeIdEdit) COMMAND_HANDLER(IDC_CAPTION_EDIT, EN_CHANGE, OnEnChangeCaptionEdit) END_MSG_MAP() // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) WTL::CString m_strId; WTL::CString m_strCaption; LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { CenterWindow(GetParent()); if (m_strId == _T("")) m_strId = _T("IDS_"); SetDlgItemText(IDC_ID_EDIT, m_strId); SetDlgItemText(IDC_CAPTION_EDIT, m_strCaption); return TRUE; } LRESULT OnOk(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { TCHAR szBuffer[4096] = { 0 }; GetDlgItemText( IDC_ID_EDIT, szBuffer, 4096 ); m_strId = szBuffer; GetDlgItemText( IDC_CAPTION_EDIT, szBuffer, 4096 ); m_strCaption = szBuffer; EndDialog(wID); return 0; } LRESULT OnCloseCmd(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { EndDialog(wID); return 0; } LRESULT OnEnChangeIdEdit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); LRESULT OnEnChangeCaptionEdit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/); };
[ [ [ 1, 62 ] ] ]
d800f697d6e96d656d9775d28ca930dd09bb108f
5eb582292aeef7c56b13bc05accf71592d15931f
/include/raknet/DistributedNetworkObjectHeader.h
2816e3296754658dce47ae697586f0835c7660f9
[]
no_license
goebish/WiiBlob
9316a56f2a60a506ecbd856ab7c521f906b961a1
bef78fc2fdbe2d52749ed3bc965632dd699c2fea
refs/heads/master
2020-05-26T12:19:40.164479
2010-09-05T18:09:07
2010-09-05T18:09:07
188,229,195
0
0
null
null
null
null
UTF-8
C++
false
false
30,385
h
/* -*- mode: c++; c-file-style: raknet; tab-always-indent: nil; -*- */ /** * @ingroup RAKNET_DNO * @file * @brief Provide Macro for the Distributed Object System * * This file is part of RakNet Copyright 2003 Rakkarsoft LLC and Kevin Jenkins. * * Usage of Raknet is subject to the appropriate licence agreement. * "Shareware" Licensees with Rakkarsoft LLC are subject to the * shareware license found at * http://www.rakkarsoft.com/shareWareLicense.html which you agreed to * upon purchase of a "Shareware license" "Commercial" Licensees with * Rakkarsoft LLC are subject to the commercial license found at * http://www.rakkarsoft.com/sourceCodeLicense.html which you agreed * to upon purchase of a "Commercial license" * Custom license users are subject to the terms therein. * All other users are * subject to the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your * option) any later version. * * Refer to the appropriate license agreement for distribution, * modification, and warranty rights. */ #include "DistributedNetworkObjectStub.h" #include "DistributedNetworkObject.h" #include "BitStream.h" #include "GetTime.h" #include <memory.h> #include <assert.h> /** * @ingroup RAKNET_DNO * This define should be put after the class definition, once per * class that you want to be distributed */ #define REGISTER_DISTRIBUTED_CLASS(className) \ DistributedNetworkObjectStub<className> distributedNetworkObjectStub_##className(#className); /** * @ingroup RAKNET_DNO * DOM stands for distributed object member - * COPY will send data without interpolation. When the packet arrives the remote value will immediately take the new value. * INTERPOLATE will send data and use interpolation. * When the packet arrives the remote value will gradually take the new value according to DistributedNetworkObject::maximumUpdateFrequency * Uncompressed should be used for non-native types, such as structures, or native types whose values take the range of the entire variable. * At this time Uncompressed will not work with arrays or pointers. However, you can enclose arrays in a struct or register each element * Compressed can only be used for native types, and will result in data compression if the variable value is less than half of its maximum range */ #define DOM_COPY_UNCOMPRESSED #define DOM_COPY_COMPRESSED #define DOM_INTERPOLATE_UNCOMPRESSED #define DOM_INTERPOLATE_COMPRESSED #define DOM_SERVER_AUTHORITATIVE (isServerAuthoritative==true) #define DOM_CLIENT_AUTHORITATIVE (isServerAuthoritative==false) /** * @ingroup RAKNET_DNO * REGISTER_DISTRIBUTED_OBJECT_MEMBERS is optional. If you use it, it must be put in the public section of the class that you want to have * automatically synchronized member variables. * Base class should be the class the enclosing class immediately derives from. You can pass DistributedNetworkObject if it derives from no other class. * AuthoritativeNetwork should be DOM_SERVER_AUTHORITATIVE or DOM_CLIENT_AUTHORITATIVE depending on which system is the authority for an object * SynchronizationMethod should be any of the values immediately above * Variable type can be any type other than a pointer. However, for interpolation it must also have *, +, -, and = defined. * Variable name should be the name of the variable to synchronize and its type must match the type specified immediately prior. */ #pragma deprecated(REGISTER_1_DISTRIBUTED_OBJECT_MEMBERS) // This whole file is depreciated. Use the new object replication system instead #define REGISTER_1_DISTRIBUTED_OBJECT_MEMBERS(BaseClass, SynchronizationMethod1, AuthoritativeNetwork1, VariableType1, VariableName1)\ SynchronizationMethod1##_INTERPOLATION_MEMBERS(VariableType1, VariableName1) \ VariableType1 VariableName1##_LastReadValue, VariableName1##_LastWriteValue; \ \ virtual void DistributedMemoryInit(bool isServerAuthoritative) \ { \ BaseClass::DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_MEMORY_INIT(VariableName1) \ } \ virtual bool ProcessDistributedMemoryStack(RakNet::BitStream *bitStream, bool isWrite, bool forceWrite, bool isServerAuthoritative) \ { \ bool anyDataWritten=false; \ bool dataChanged=false; \ if (distributedMemoryInitialized==false) \ { \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ } \ else \ { \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ } \ \ if (BaseClass::ProcessDistributedMemoryStack(bitStream, isWrite, forceWrite,isServerAuthoritative)==true) \ anyDataWritten=true;\ return anyDataWritten; \ } \ \ virtual void InterpolateDistributedMemory(bool isServerAuthoritative) \ { \ unsigned int currentTime=RakNet::GetTime(); \ if (distributedMemoryInitialized==false) \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_CODE(AuthoritativeNetwork1, VariableName1) \ } #define DOM_COPY_UNCOMPRESSED_INTERPOLATION_CODE(AuthoritativeNetwork,VariableName) #define DOM_COPY_COMPRESSED_INTERPOLATION_CODE(AuthoritativeNetwork,VariableName) #define DOM_INTERPOLATE_UNCOMPRESSED_INTERPOLATION_CODE(AuthoritativeNetwork,VariableName) DOM_INTERPOLATION_CODE(AuthoritativeNetwork,VariableName) #define DOM_INTERPOLATE_COMPRESSED_INTERPOLATION_CODE(AuthoritativeNetwork,VariableName) DOM_INTERPOLATION_CODE(AuthoritativeNetwork,VariableName) /** * @ingroup RAKNET_DNO * This is called when you call DistributedNetworkObject::InterpolateDistributedMemory, one per interpolated member */ #define DOM_INTERPOLATION_CODE(AuthoritativeNetwork, VariableName) \ if (VariableName!=VariableName##_FinalValue && VariableName##_LastKnownValue!=VariableName##_LastReadValue && VariableName##_LastKnownValue==VariableName) \ { \ if (currentTime >= VariableName##_InterpolationEndTime) \ VariableName=VariableName##_FinalValue; \ else \ { \ VariableName = VariableName##_InitialValue + (currentTime - VariableName##_InterpolationStartTime) / (float)(VariableName##_InterpolationEndTime - VariableName##_InterpolationStartTime) * (VariableName##_FinalValue - VariableName##_InitialValue); \ } \ VariableName##_LastKnownValue = VariableName; \ } \ #define DOM_COPY_UNCOMPRESSED_INTERPOLATION_MEMBERS(VariableType, VariableName) #define DOM_COPY_COMPRESSED_INTERPOLATION_MEMBERS(VariableType, VariableName) #define DOM_INTERPOLATE_UNCOMPRESSED_INTERPOLATION_MEMBERS(VariableType, VariableName) unsigned int VariableName##_InterpolationStartTime,VariableName##_InterpolationEndTime; VariableType VariableName##_InitialValue, VariableName##_FinalValue, VariableName##_LastKnownValue; #define DOM_INTERPOLATE_COMPRESSED_INTERPOLATION_MEMBERS(VariableType, VariableName) unsigned int VariableName##_InterpolationStartTime,VariableName##_InterpolationEndTime; VariableType VariableName##_InitialValue, VariableName##_FinalValue, VariableName##_LastKnownValue; #define DOM_COPY_UNCOMPRESSED_INTERPOLATION_MEMORY_INIT(VariableName) #define DOM_COPY_COMPRESSED_INTERPOLATION_MEMORY_INIT(VariableName) #define DOM_INTERPOLATE_UNCOMPRESSED_INTERPOLATION_MEMORY_INIT(VariableName) memcpy((char*)&VariableName##_LastReadValue,(char*)&VariableName, sizeof(VariableName)); memcpy((char*)&VariableName##_LastKnownValue,(char*)&VariableName, sizeof(VariableName)); memcpy((char*)&VariableName##_FinalValue,(char*)&VariableName, sizeof(VariableName)); #define DOM_INTERPOLATE_COMPRESSED_INTERPOLATION_MEMORY_INIT(VariableName) memcpy((char*)&VariableName##_LastReadValue,(char*)&VariableName, sizeof(VariableName)); memcpy((char*)&VariableName##_LastKnownValue,(char*)&VariableName, sizeof(VariableName)); memcpy((char*)&VariableName##_FinalValue,(char*)&VariableName, sizeof(VariableName)); #define DOM_COPY_UNCOMPRESSED_EXPANDED(AuthoritativeNetwork,VariableType, VariableName)\ DOM_COPY_EXPANDED2(AuthoritativeNetwork,VariableType,VariableName, readSuccess=bitStream->Read((char*)&VariableName##_LastReadValue, sizeof(VariableName));,\ readSuccess=bitStream->Read((char*)&dummy, sizeof(VariableName));,\ bitStream->Write((char*)&VariableName, sizeof(VariableName));) #define DOM_COPY_COMPRESSED_EXPANDED(AuthoritativeNetwork,VariableType, VariableName)\ DOM_COPY_EXPANDED2(AuthoritativeNetwork,VariableType,VariableName, readSuccess=bitStream->ReadCompressed(VariableName##_LastReadValue);,\ readSuccess=bitStream->ReadCompressed(dummy);,\ bitStream->WriteCompressed(VariableName);) #define DOM_INTERPOLATE_UNCOMPRESSED_EXPANDED(AuthoritativeNetwork,VariableType, VariableName)\ DOM_INTERPOLATE_EXPANDED2(AuthoritativeNetwork,VariableType,VariableName, readSuccess=bitStream->Read((char*)&VariableName##_LastReadValue, sizeof(VariableName));,\ readSuccess=bitStream->Read((char*)&dummy, sizeof(VariableName));,\ if (VariableName##_LastKnownValue!=VariableName##_LastReadValue && VariableName##_LastKnownValue==VariableName) bitStream->Write((char*)&VariableName##_FinalValue, sizeof(VariableName));\ else bitStream->Write((char*)&VariableName, sizeof(VariableName));) #define DOM_INTERPOLATE_COMPRESSED_EXPANDED(AuthoritativeNetwork,VariableType, VariableName)\ DOM_INTERPOLATE_EXPANDED2(AuthoritativeNetwork,VariableType,VariableName, readSuccess=bitStream->ReadCompressed(VariableName##_LastReadValue);,\ readSuccess=bitStream->ReadCompressed(dummy);,\ if (VariableName##_LastKnownValue!=VariableName##_LastReadValue && VariableName##_LastKnownValue==VariableName) bitStream->WriteCompressed(VariableName##_FinalValue);\ else bitStream->WriteCompressed(VariableName);) #define DOM_COPY_EXPANDED2(AuthoritativeNetwork,VariableType,VariableName, ReadCode, ReadDummyCode, WriteCode) \ DOM_CORE_EXPANDED(AuthoritativeNetwork,VariableType,VariableName, ReadCode, ReadDummyCode, WriteCode, true) \ if (isWrite==false && dataChanged==true) \ VariableName=VariableName##_LastReadValue; #define DOM_INTERPOLATE_EXPANDED2(AuthoritativeNetwork,VariableType,VariableName, ReadCode, ReadDummyCode, WriteCode) \ DOM_CORE_EXPANDED(AuthoritativeNetwork,VariableType,VariableName, ReadCode, ReadDummyCode, WriteCode, VariableName!=VariableName##_LastKnownValue) \ if (isWrite==false && dataChanged==true) \ { \ VariableName##_InterpolationStartTime=RakNet::GetTime(); \ VariableName##_InterpolationEndTime=VariableName##_InterpolationStartTime+maximumUpdateFrequency; \ VariableName##_InitialValue=VariableName; \ VariableName##_FinalValue=VariableName##_LastReadValue; \ VariableName##_LastKnownValue=VariableName; \ } #define DOM_CORE_EXPANDED(AuthoritativeNetwork,VariableType,VariableName, ReadCode, ReadDummyCode, WriteCode, InterpolationWriteCondition) \ assert(sizeof(VariableName)==sizeof(VariableName##_LastWriteValue)); \ if (isWrite) \ { \ if (forceWrite) \ { \ bitStream->Write(true); \ WriteCode \ memcpy(&VariableName##_LastWriteValue, &VariableName, sizeof(VariableName)); \ anyDataWritten=true; \ } \ else \ { \ if (AuthoritativeNetwork && memcmp(&VariableName, &VariableName##_LastWriteValue, sizeof(VariableName))!=0 && InterpolationWriteCondition)\ { \ bitStream->Write(true); \ WriteCode \ memcpy(&VariableName##_LastWriteValue, &VariableName, sizeof(VariableName)); \ anyDataWritten=true; \ } \ else \ { \ bitStream->Write(false); \ } \ } \ } \ else \ { \ if (bitStream->Read(dataChanged)==false) \ { \ assert(0==1); \ return false; \ } \ if (dataChanged) \ { \ if (isServerAuthoritative==false || AuthoritativeNetwork==0) \ { \ bool readSuccess; \ ReadCode\ if (readSuccess==false) \ { \ assert(0==2); \ return false; \ } \ if (isServerAuthoritative==false) \ memcpy((char*)&VariableName##_LastWriteValue, (char*)&VariableName##_LastReadValue, sizeof(VariableName##_LastWriteValue)); \ } \ else \ { \ VariableType dummy; \ bool readSuccess; \ ReadDummyCode\ if (readSuccess==false) \ { \ assert(0==2); \ return false; \ } \ } \ } \ } // ------------------------------------------------------------------------------------------------------------------------------------------- #define REGISTER_2_DISTRIBUTED_OBJECT_MEMBERS(BaseClass, SynchronizationMethod1, AuthoritativeNetwork1, VariableType1, VariableName1 \ , SynchronizationMethod2, AuthoritativeNetwork2, VariableType2, VariableName2 \ )\ SynchronizationMethod1##_INTERPOLATION_MEMBERS(VariableType1, VariableName1) \ SynchronizationMethod2##_INTERPOLATION_MEMBERS(VariableType2, VariableName2) \ VariableType1 VariableName1##_LastReadValue, VariableName1##_LastWriteValue; \ VariableType2 VariableName2##_LastReadValue, VariableName2##_LastWriteValue; \ \ virtual void DistributedMemoryInit(bool isServerAuthoritative) \ { \ BaseClass::DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_MEMORY_INIT(VariableName1) \ SynchronizationMethod2##_INTERPOLATION_MEMORY_INIT(VariableName2) \ } \ virtual bool ProcessDistributedMemoryStack(RakNet::BitStream *bitStream, bool isWrite, bool forceWrite, bool isServerAuthoritative) \ { \ bool anyDataWritten=false; \ bool dataChanged=false; \ if (distributedMemoryInitialized==false) \ { \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ SynchronizationMethod2##_EXPANDED(AuthoritativeNetwork2, VariableType2, VariableName2) \ } \ else \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ SynchronizationMethod2##_EXPANDED(AuthoritativeNetwork2, VariableType2, VariableName2) \ if (BaseClass::ProcessDistributedMemoryStack(bitStream, isWrite, forceWrite,isServerAuthoritative)==true) \ anyDataWritten=true;\ return anyDataWritten; \ } \ \ virtual void InterpolateDistributedMemory(bool isServerAuthoritative) \ { \ unsigned int currentTime=RakNet::GetTime(); \ float percentageOfTimeElapsed; \ if (distributedMemoryInitialized==false) \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_CODE(AuthoritativeNetwork1, VariableName1) \ SynchronizationMethod2##_INTERPOLATION_CODE(AuthoritativeNetwork2, VariableName2) \ } // ------------------------------------------------------------------------------------------------------------------------------------------- #define REGISTER_3_DISTRIBUTED_OBJECT_MEMBERS(BaseClass, SynchronizationMethod1, AuthoritativeNetwork1, VariableType1, VariableName1 \ , SynchronizationMethod2, AuthoritativeNetwork2, VariableType2, VariableName2 \ , SynchronizationMethod3, AuthoritativeNetwork3, VariableType3, VariableName3 \ )\ SynchronizationMethod1##_INTERPOLATION_MEMBERS(VariableType1, VariableName1) \ SynchronizationMethod2##_INTERPOLATION_MEMBERS(VariableType2, VariableName2) \ SynchronizationMethod3##_INTERPOLATION_MEMBERS(VariableType3, VariableName3) \ VariableType1 VariableName1##_LastReadValue, VariableName1##_LastWriteValue; \ VariableType2 VariableName2##_LastReadValue, VariableName2##_LastWriteValue; \ VariableType3 VariableName3##_LastReadValue, VariableName3##_LastWriteValue; \ \ virtual void DistributedMemoryInit(bool isServerAuthoritative) \ { \ BaseClass::DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_MEMORY_INIT(VariableName1) \ SynchronizationMethod2##_INTERPOLATION_MEMORY_INIT(VariableName2) \ SynchronizationMethod3##_INTERPOLATION_MEMORY_INIT(VariableName3) \ } \ virtual bool ProcessDistributedMemoryStack(RakNet::BitStream *bitStream, bool isWrite, bool forceWrite, bool isServerAuthoritative) \ { \ bool anyDataWritten=false; \ bool dataChanged=false; \ if (distributedMemoryInitialized==false) \ { \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ SynchronizationMethod2##_EXPANDED(AuthoritativeNetwork2, VariableType2, VariableName2) \ SynchronizationMethod3##_EXPANDED(AuthoritativeNetwork3, VariableType3, VariableName3) \ } \ else \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ SynchronizationMethod2##_EXPANDED(AuthoritativeNetwork2, VariableType2, VariableName2) \ SynchronizationMethod3##_EXPANDED(AuthoritativeNetwork3, VariableType3, VariableName3) \ if (BaseClass::ProcessDistributedMemoryStack(bitStream, isWrite, forceWrite,isServerAuthoritative)==true) \ anyDataWritten=true;\ return anyDataWritten; \ } \ \ virtual void InterpolateDistributedMemory(bool isServerAuthoritative) \ { \ unsigned int currentTime=RakNet::GetTime(); \ float percentageOfTimeElapsed; \ if (distributedMemoryInitialized==false) \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_CODE(AuthoritativeNetwork1, VariableName1) \ SynchronizationMethod2##_INTERPOLATION_CODE(AuthoritativeNetwork2, VariableName2) \ SynchronizationMethod3##_INTERPOLATION_CODE(AuthoritativeNetwork3, VariableName3) \ } // ------------------------------------------------------------------------------------------------------------------------------------------- #define REGISTER_4_DISTRIBUTED_OBJECT_MEMBERS(BaseClass, SynchronizationMethod1, AuthoritativeNetwork1, VariableType1, VariableName1 \ , SynchronizationMethod2, AuthoritativeNetwork2, VariableType2, VariableName2 \ , SynchronizationMethod3, AuthoritativeNetwork3, VariableType3, VariableName3 \ , SynchronizationMethod4, AuthoritativeNetwork4, VariableType4, VariableName4 \ )\ SynchronizationMethod1##_INTERPOLATION_MEMBERS(VariableType1, VariableName1) \ SynchronizationMethod2##_INTERPOLATION_MEMBERS(VariableType2, VariableName2) \ SynchronizationMethod3##_INTERPOLATION_MEMBERS(VariableType3, VariableName3) \ SynchronizationMethod4##_INTERPOLATION_MEMBERS(VariableType4, VariableName4) \ VariableType1 VariableName1##_LastReadValue, VariableName1##_LastWriteValue; \ VariableType2 VariableName2##_LastReadValue, VariableName2##_LastWriteValue; \ VariableType3 VariableName3##_LastReadValue, VariableName3##_LastWriteValue; \ VariableType4 VariableName4##_LastReadValue, VariableName4##_LastWriteValue; \ \ virtual void DistributedMemoryInit(bool isServerAuthoritative) \ { \ BaseClass::DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_MEMORY_INIT(VariableName1) \ SynchronizationMethod2##_INTERPOLATION_MEMORY_INIT(VariableName2) \ SynchronizationMethod3##_INTERPOLATION_MEMORY_INIT(VariableName3) \ SynchronizationMethod4##_INTERPOLATION_MEMORY_INIT(VariableName4) \ } \ virtual bool ProcessDistributedMemoryStack(RakNet::BitStream *bitStream, bool isWrite, bool forceWrite, bool isServerAuthoritative) \ { \ bool anyDataWritten=false; \ bool dataChanged=false; \ if (distributedMemoryInitialized==false) \ { \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ SynchronizationMethod2##_EXPANDED(AuthoritativeNetwork2, VariableType2, VariableName2) \ SynchronizationMethod3##_EXPANDED(AuthoritativeNetwork3, VariableType3, VariableName3) \ SynchronizationMethod4##_EXPANDED(AuthoritativeNetwork4, VariableType4, VariableName4) \ } \ else \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ SynchronizationMethod2##_EXPANDED(AuthoritativeNetwork2, VariableType2, VariableName2) \ SynchronizationMethod3##_EXPANDED(AuthoritativeNetwork3, VariableType3, VariableName3) \ SynchronizationMethod4##_EXPANDED(AuthoritativeNetwork4, VariableType4, VariableName4) \ if (BaseClass::ProcessDistributedMemoryStack(bitStream, isWrite, forceWrite,isServerAuthoritative)==true) \ anyDataWritten=true;\ return anyDataWritten; \ } \ \ virtual void InterpolateDistributedMemory(bool isServerAuthoritative) \ { \ unsigned int currentTime=RakNet::GetTime(); \ float percentageOfTimeElapsed; \ if (distributedMemoryInitialized==false) \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_CODE(AuthoritativeNetwork1, VariableName1) \ SynchronizationMethod2##_INTERPOLATION_CODE(AuthoritativeNetwork2, VariableName2) \ SynchronizationMethod3##_INTERPOLATION_CODE(AuthoritativeNetwork3, VariableName3) \ SynchronizationMethod4##_INTERPOLATION_CODE(AuthoritativeNetwork4, VariableName4) \ } // ------------------------------------------------------------------------------------------------------------------------------------------- #define REGISTER_5_DISTRIBUTED_OBJECT_MEMBERS(BaseClass, SynchronizationMethod1, AuthoritativeNetwork1, VariableType1, VariableName1 \ , SynchronizationMethod2, AuthoritativeNetwork2, VariableType2, VariableName2 \ , SynchronizationMethod3, AuthoritativeNetwork3, VariableType3, VariableName3 \ , SynchronizationMethod4, AuthoritativeNetwork4, VariableType4, VariableName4 \ , SynchronizationMethod5, AuthoritativeNetwork5, VariableType5, VariableName5 \ )\ SynchronizationMethod1##_INTERPOLATION_MEMBERS(VariableType1, VariableName1) \ SynchronizationMethod2##_INTERPOLATION_MEMBERS(VariableType2, VariableName2) \ SynchronizationMethod3##_INTERPOLATION_MEMBERS(VariableType3, VariableName3) \ SynchronizationMethod4##_INTERPOLATION_MEMBERS(VariableType4, VariableName4) \ SynchronizationMethod5##_INTERPOLATION_MEMBERS(VariableType5, VariableName5) \ VariableType1 VariableName1##_LastReadValue, VariableName1##_LastWriteValue; \ VariableType2 VariableName2##_LastReadValue, VariableName2##_LastWriteValue; \ VariableType3 VariableName3##_LastReadValue, VariableName3##_LastWriteValue; \ VariableType4 VariableName4##_LastReadValue, VariableName4##_LastWriteValue; \ VariableType5 VariableName5##_LastReadValue, VariableName5##_LastWriteValue; \ \ virtual void DistributedMemoryInit(bool isServerAuthoritative) \ { \ BaseClass::DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_MEMORY_INIT(VariableName1) \ SynchronizationMethod2##_INTERPOLATION_MEMORY_INIT(VariableName2) \ SynchronizationMethod3##_INTERPOLATION_MEMORY_INIT(VariableName3) \ SynchronizationMethod4##_INTERPOLATION_MEMORY_INIT(VariableName4) \ SynchronizationMethod5##_INTERPOLATION_MEMORY_INIT(VariableName5) \ } \ virtual bool ProcessDistributedMemoryStack(RakNet::BitStream *bitStream, bool isWrite, bool forceWrite, bool isServerAuthoritative) \ { \ bool anyDataWritten=false; \ bool dataChanged=false; \ if (distributedMemoryInitialized==false) \ { \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ SynchronizationMethod2##_EXPANDED(AuthoritativeNetwork2, VariableType2, VariableName2) \ SynchronizationMethod3##_EXPANDED(AuthoritativeNetwork3, VariableType3, VariableName3) \ SynchronizationMethod4##_EXPANDED(AuthoritativeNetwork4, VariableType4, VariableName4) \ SynchronizationMethod5##_EXPANDED(AuthoritativeNetwork5, VariableType5, VariableName5) \ } \ else \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ SynchronizationMethod2##_EXPANDED(AuthoritativeNetwork2, VariableType2, VariableName2) \ SynchronizationMethod3##_EXPANDED(AuthoritativeNetwork3, VariableType3, VariableName3) \ SynchronizationMethod4##_EXPANDED(AuthoritativeNetwork4, VariableType4, VariableName4) \ SynchronizationMethod5##_EXPANDED(AuthoritativeNetwork5, VariableType5, VariableName5) \ if (BaseClass::ProcessDistributedMemoryStack(bitStream, isWrite, forceWrite,isServerAuthoritative)==true) \ anyDataWritten=true;\ return anyDataWritten; \ } \ \ virtual void InterpolateDistributedMemory(bool isServerAuthoritative) \ { \ unsigned int currentTime=RakNet::GetTime(); \ float percentageOfTimeElapsed; \ if (distributedMemoryInitialized==false) \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_CODE(AuthoritativeNetwork1, VariableName1) \ SynchronizationMethod2##_INTERPOLATION_CODE(AuthoritativeNetwork2, VariableName2) \ SynchronizationMethod3##_INTERPOLATION_CODE(AuthoritativeNetwork3, VariableName3) \ SynchronizationMethod4##_INTERPOLATION_CODE(AuthoritativeNetwork4, VariableName4) \ SynchronizationMethod5##_INTERPOLATION_CODE(AuthoritativeNetwork5, VariableName5) \ } // ------------------------------------------------------------------------------------------------------------------------------------------- #define REGISTER_6_DISTRIBUTED_OBJECT_MEMBERS(BaseClass, SynchronizationMethod1, AuthoritativeNetwork1, VariableType1, VariableName1 \ , SynchronizationMethod2, AuthoritativeNetwork2, VariableType2, VariableName2 \ , SynchronizationMethod3, AuthoritativeNetwork3, VariableType3, VariableName3 \ , SynchronizationMethod4, AuthoritativeNetwork4, VariableType4, VariableName4 \ , SynchronizationMethod5, AuthoritativeNetwork5, VariableType5, VariableName5 \ , SynchronizationMethod6, AuthoritativeNetwork6, VariableType6, VariableName6 \ )\ SynchronizationMethod1##_INTERPOLATION_MEMBERS(VariableType1, VariableName1) \ SynchronizationMethod2##_INTERPOLATION_MEMBERS(VariableType2, VariableName2) \ SynchronizationMethod3##_INTERPOLATION_MEMBERS(VariableType3, VariableName3) \ SynchronizationMethod4##_INTERPOLATION_MEMBERS(VariableType4, VariableName4) \ SynchronizationMethod5##_INTERPOLATION_MEMBERS(VariableType5, VariableName5) \ SynchronizationMethod6##_INTERPOLATION_MEMBERS(VariableType6, VariableName6) \ VariableType1 VariableName1##_LastReadValue, VariableName1##_LastWriteValue; \ VariableType2 VariableName2##_LastReadValue, VariableName2##_LastWriteValue; \ VariableType3 VariableName3##_LastReadValue, VariableName3##_LastWriteValue; \ VariableType4 VariableName4##_LastReadValue, VariableName4##_LastWriteValue; \ VariableType5 VariableName5##_LastReadValue, VariableName5##_LastWriteValue; \ VariableType6 VariableName6##_LastReadValue, VariableName6##_LastWriteValue; \ \ virtual void DistributedMemoryInit(bool isServerAuthoritative) \ { \ BaseClass::DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_MEMORY_INIT(VariableName1) \ SynchronizationMethod2##_INTERPOLATION_MEMORY_INIT(VariableName2) \ SynchronizationMethod3##_INTERPOLATION_MEMORY_INIT(VariableName3) \ SynchronizationMethod4##_INTERPOLATION_MEMORY_INIT(VariableName4) \ SynchronizationMethod5##_INTERPOLATION_MEMORY_INIT(VariableName5) \ SynchronizationMethod6##_INTERPOLATION_MEMORY_INIT(VariableName6) \ } \ virtual bool ProcessDistributedMemoryStack(RakNet::BitStream *bitStream, bool isWrite, bool forceWrite, bool isServerAuthoritative) \ { \ bool anyDataWritten=false; \ bool dataChanged=false; \ if (distributedMemoryInitialized==false) \ { \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ SynchronizationMethod2##_EXPANDED(AuthoritativeNetwork2, VariableType2, VariableName2) \ SynchronizationMethod3##_EXPANDED(AuthoritativeNetwork3, VariableType3, VariableName3) \ SynchronizationMethod4##_EXPANDED(AuthoritativeNetwork4, VariableType4, VariableName4) \ SynchronizationMethod5##_EXPANDED(AuthoritativeNetwork5, VariableType5, VariableName5) \ SynchronizationMethod6##_EXPANDED(AuthoritativeNetwork6, VariableType6, VariableName6) \ } \ else \ SynchronizationMethod1##_EXPANDED(AuthoritativeNetwork1, VariableType1, VariableName1) \ SynchronizationMethod2##_EXPANDED(AuthoritativeNetwork2, VariableType2, VariableName2) \ SynchronizationMethod3##_EXPANDED(AuthoritativeNetwork3, VariableType3, VariableName3) \ SynchronizationMethod4##_EXPANDED(AuthoritativeNetwork4, VariableType4, VariableName4) \ SynchronizationMethod5##_EXPANDED(AuthoritativeNetwork5, VariableType5, VariableName5) \ SynchronizationMethod6##_EXPANDED(AuthoritativeNetwork6, VariableType6, VariableName6) \ if (BaseClass::ProcessDistributedMemoryStack(bitStream, isWrite, forceWrite,isServerAuthoritative)==true) \ anyDataWritten=true;\ return anyDataWritten; \ } \ \ virtual void InterpolateDistributedMemory(bool isServerAuthoritative) \ { \ unsigned int currentTime=RakNet::GetTime(); \ float percentageOfTimeElapsed; \ if (distributedMemoryInitialized==false) \ DistributedMemoryInit(isServerAuthoritative); \ SynchronizationMethod1##_INTERPOLATION_CODE(AuthoritativeNetwork1, VariableName1) \ SynchronizationMethod2##_INTERPOLATION_CODE(AuthoritativeNetwork2, VariableName2) \ SynchronizationMethod3##_INTERPOLATION_CODE(AuthoritativeNetwork3, VariableName3) \ SynchronizationMethod4##_INTERPOLATION_CODE(AuthoritativeNetwork4, VariableName4) \ SynchronizationMethod5##_INTERPOLATION_CODE(AuthoritativeNetwork5, VariableName5) \ SynchronizationMethod6##_INTERPOLATION_CODE(AuthoritativeNetwork6, VariableName6) \ } /** * @internal * @note Extend this pattern as many times as necessary. If anyone * figures out a way to automate a way to do that with the * preprocessor let me know */
[ [ [ 1, 517 ] ] ]
4441057e42bd85a2c3fa5b69517ea7b726d83f62
d8f64a24453c6f077426ea58aaa7313aafafc75c
/PickingManager.cpp
1dca24c0dc465ee3502a55071b0f74e378c99ce6
[]
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
3,830
cpp
#include "commons.h" #include "PickingManager.h" #include "utils.h" #include <cml/cml.h> #include "OGLUtils.h" #define _SECURE_SCL 0 using namespace std; using namespace utils; using namespace game_objects; using namespace cml; namespace game_utils { namespace managers { CPickingManager::CPickingManager(): CManager() { lastPickedBlock = NULL; } CPickingManager::~CPickingManager() { } bool CPickingManager::init() { return true; } bool CPickingManager::update() { // 1. block picking // 1.1 draw pickable blocks std::vector<CBlock*> *rBlocks = CV_GAME_MANAGER->getRenderManager()->getRenderedBlocks(); if (rBlocks->size()==0) { return true; } //using a map is very slow std::vector<pair<vector3ub, CBlock*>> colorBlockRef; sColor sCol(50,50,50); // transform view CV_GAME_MANAGER->getControlManager()->getCamera()->transformView(); for (std::vector<CBlock*>::iterator bIter = rBlocks->begin(); bIter != rBlocks->end(); bIter++) { CBlock *block = *bIter; sBoundingBox *bbox = block->getBoundingBox(); vector3f a(bbox->A); vector3f b(bbox->B); vector3f c(bbox->C); vector3f d(bbox->D); vector3f e(bbox->E); vector3f f(bbox->F); vector3f g(bbox->G); vector3f h(bbox->H); a[1]=b[1]=c[1]=d[1]=CV_BLOCK_HEIGHT+CV_BLOCK_HEIGHT/4.0f; e[1]=f[1]=g[1]=h[1]=CV_BLOCK_HEIGHT/4.0f; vector3ub col = sCol.getNextColorUB(); colorBlockRef.push_back(pair<vector3ub, CBlock*>(col, block)); glColor3ubv(&col[0]); glBegin(GL_QUADS); { if (block->isFaceVisible(CBlock::BFS_TOP)) { glVertex3fv(&a[0]); glVertex3fv(&b[0]); glVertex3fv(&c[0]); glVertex3fv(&d[0]); if (block->isFaceVisible(CBlock::BFS_RIGHT)) { glVertex3fv(&c[0]); glVertex3fv(&b[0]); glVertex3fv(&f[0]); glVertex3fv(&g[0]); } if (block->isFaceVisible(CBlock::BFS_LEFT)) { glVertex3fv(&h[0]); glVertex3fv(&e[0]); glVertex3fv(&a[0]); glVertex3fv(&d[0]); } if (block->isFaceVisible(CBlock::BFS_FRONT)) { glVertex3fv(&e[0]); glVertex3fv(&f[0]); glVertex3fv(&b[0]); glVertex3fv(&a[0]); } if (block->isFaceVisible(CBlock::BFS_BACK)) { glVertex3fv(&g[0]); glVertex3fv(&h[0]); glVertex3fv(&d[0]); glVertex3fv(&c[0]); } }else{ glVertex3fv(&e[0]); glVertex3fv(&f[0]); glVertex3fv(&g[0]); glVertex3fv(&h[0]); } } glEnd(); } // 1.2 pick from backbuffer vector2i mousePos = CV_GAME_MANAGER->getControlManager()->getInput()->getMousePos(); //convert mouse pos to relative to this window RECT cl,wnd; GetClientRect(CV_WINDOW_HANDLE,&cl); GetWindowRect(CV_WINDOW_HANDLE,&wnd); int border=(wnd.right-wnd.left-cl.right)/2; int titlebar=wnd.bottom-wnd.top-cl.bottom-border; mousePos[0] -= border+wnd.left; mousePos[1] -= titlebar+wnd.top; if(lastPickedBlock) lastPickedBlock->setHighlighted(false); vector3ub pickedColor = COGLUtils::getColor(mousePos); for(std::vector<pair<vector3ub, CBlock*>>::iterator i = colorBlockRef.begin(); i != colorBlockRef.end(); i++) if(i->first == pickedColor) lastPickedBlock = i->second; if(lastPickedBlock) lastPickedBlock->setHighlighted(true); // 1.3 clear the backbuffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); return true; } bool CPickingManager::shutdown() { return true; } CBlock *CPickingManager::getLastPickedBlock() { return lastPickedBlock; } }; };
[ [ [ 1, 6 ], [ 10, 32 ], [ 34, 44 ], [ 47, 62 ], [ 67, 68 ], [ 70, 72 ], [ 74, 78 ], [ 121, 126 ], [ 142, 142 ], [ 149, 166 ] ], [ [ 7, 9 ], [ 33, 33 ], [ 45, 46 ], [ 63, 66 ], [ 69, 69 ], [ 73, 73 ], [ 79, 120 ], [ 127, 141 ], [ 143, 148 ] ] ]
261af1c58aef711aba3eec48738a01016380f6bc
a2904986c09bd07e8c89359632e849534970c1be
/topcoder/completed/LotteryTicket.cpp
61a9da9ef6d33c81d41fb4e653b6d8e01ea3f17c
[]
no_license
naturalself/topcoder_srms
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
refs/heads/master
2021-01-22T04:36:40.592620
2010-11-29T17:30:40
2010-11-29T17:30:40
444,669
1
0
null
null
null
null
UTF-8
C++
false
false
3,754
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "LotteryTicket.cpp" #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> using namespace std; #define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i) #define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i) #define all(a) a.begin(), a.end() class LotteryTicket { public: string buy(int price, int b1, int b2, int b3, int b4) { #if 1 vector <int> b(4); int sum=0; b.push_back(b1); b.push_back(b2); b.push_back(b3); b.push_back(b4); do{ for(int i=1;i<(int)b.size();i++){ for(int j=0;j<i;j++){ sum += b[j]; //cout << sum << endl; if(sum == price){ return "POSSIBLE"; } } sum = 0; } }while(next_permutation(all(b))); #else int dp[4005]={0},i; dp[0]=1; for(i=4000;i>=b1;i--) if(dp[i-b1]==1) dp[i]=1; for(i=4000;i>=b2;i--) if(dp[i-b2]==1) dp[i]=1; for(i=4000;i>=b3;i--) if(dp[i-b3]==1) dp[i]=1; for(i=4000;i>=b4;i--) if(dp[i-b4]==1) dp[i]=1; if(dp[price]==1) return "POSSIBLE"; #endif return "IMPOSSIBLE"; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 10; int Arg1 = 1; int Arg2 = 5; int Arg3 = 10; int Arg4 = 50; string Arg5 = "POSSIBLE"; verify_case(0, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_1() { int Arg0 = 15; int Arg1 = 1; int Arg2 = 5; int Arg3 = 10; int Arg4 = 50; string Arg5 = "POSSIBLE"; verify_case(1, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_2() { int Arg0 = 65; int Arg1 = 1; int Arg2 = 5; int Arg3 = 10; int Arg4 = 50; string Arg5 = "POSSIBLE"; verify_case(2, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_3() { int Arg0 = 66; int Arg1 = 1; int Arg2 = 5; int Arg3 = 10; int Arg4 = 50; string Arg5 = "POSSIBLE"; verify_case(3, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_4() { int Arg0 = 1000; int Arg1 = 999; int Arg2 = 998; int Arg3 = 997; int Arg4 = 996; string Arg5 = "IMPOSSIBLE"; verify_case(4, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_5() { int Arg0 = 20; int Arg1 = 5; int Arg2 = 5; int Arg3 = 5; int Arg4 = 5; string Arg5 = "POSSIBLE"; verify_case(5, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } void test_case_6() { int Arg0 = 2; int Arg1 = 1; int Arg2 = 5; int Arg3 = 10; int Arg4 = 50; string Arg5 = "IMPOSSIBLE"; verify_case(6, Arg5, buy(Arg0, Arg1, Arg2, Arg3, Arg4)); } // END CUT HERE }; // BEGIN CUT HERE int main() { LotteryTicket ___test; ___test.run_test(-1); } // END CUT HERE
[ "shin@CF-7AUJ41TT52JO.(none)" ]
[ [ [ 1, 95 ] ] ]
11bbaef965c0ef267e55897514366a92ceb2f4ff
40b507c2dde13d14bb75ee1b3c16b4f3f82912d1
/public/IRootConsoleMenu.h
dd0da8c96b678afc10ee0e46ce7f85acef5a9977
[]
no_license
Nephyrin/-furry-octo-nemesis
5da2ef75883ebc4040e359a6679da64ad8848020
dd441c39bd74eda2b9857540dcac1d98706de1de
refs/heads/master
2016-09-06T01:12:49.611637
2008-09-14T08:42:28
2008-09-14T08:42:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,876
h
/** * vim: set ts=4 : * ============================================================================= * SourceMod * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. * * Version: $Id$ */ #ifndef _INCLUDE_SOURCEMOD_ROOT_CONSOLE_MENU_H_ #define _INCLUDE_SOURCEMOD_ROOT_CONSOLE_MENU_H_ /** * @file IRootConsoleMenu.h * @brief Defines the interface for adding options to the "sm" console command. * * You must be using the compat_wrappers.h header file to use this on * Original/Episode1 builds. */ #define SMINTERFACE_ROOTCONSOLE_NAME "IRootConsole" #define SMINTERFACE_ROOTCONSOLE_VERSION 1 class CCommand; namespace SourceMod { /** * @brief Handles a root console menu action. */ class IRootConsoleCommand { public: virtual void OnRootConsoleCommand(const char *cmdname, const CCommand &command) =0; }; /** * @brief Manages the root console menu - the "sm" command for servers. */ class IRootConsole : public SMInterface { public: /** * @brief Adds a root console command handler. The command must be unique. * * @param cmd String containing the console command. * @param text Description text. * @param pHandler An IRootConsoleCommand pointer to handle the command. * @return True on success, false on too many commands or duplicate command. */ virtual bool AddRootConsoleCommand(const char *cmd, const char *text, IRootConsoleCommand *pHandler) =0; /** * @brief Removes a root console command handler. * * @param cmd String containing the console command. * @param pHandler An IRootConsoleCommand pointer for verification. * @return True on success, false otherwise. */ virtual bool RemoveRootConsoleCommand(const char *cmd, IRootConsoleCommand *pHandler) =0; /** * @brief Prints text back to the console. * * @param fmt Format of string. * @param ... Format arguments. */ virtual void ConsolePrint(const char *fmt, ...) =0; /** * @brief Draws a generic command/description pair. * NOTE: The pair is currently four spaces indented and 16-N spaces of separation, * N being the length of the command name. This is subject to change in case we * account for Valve's font choices. * * @param cmd String containing the command option. * @param text String containing the command description. */ virtual void DrawGenericOption(const char *cmd, const char *text) =0; }; } #endif //_INCLUDE_SOURCEMOD_ROOT_CONSOLE_MENU_H_
[ [ [ 1, 2 ], [ 4, 5 ], [ 7, 7 ], [ 11, 11 ], [ 16, 16 ], [ 19, 19 ], [ 28, 55 ], [ 57, 102 ], [ 104, 105 ] ], [ [ 3, 3 ], [ 6, 6 ], [ 8, 10 ], [ 12, 15 ], [ 17, 18 ], [ 20, 27 ], [ 103, 103 ] ], [ [ 56, 56 ] ] ]
ab77a1c5383f11d43315e8350fae716586a043f8
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/CommonSources/TreePopSheet/PropPageFrame.cpp
c04ae763f73c2371f9b5d5b566b14e29303e09a3
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
3,935
cpp
/******************************************************************** * * Copyright (c) 2002 Sven Wiegand <[email protected]> * * You can use this and modify this in any way you want, * BUT LEAVE THIS HEADER INTACT. * * Redistribution is appreciated. * * $Workfile:$ * $Revision: 1.1 $ * $Modtime:$ * $Author: Alex $ * * Revision History: * $History:$ * *********************************************************************/ #include "stdafx.h" #include "PropPageFrame.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif namespace TreePropSheet { //------------------------------------------------------------------- // class CPropPageFrame //------------------------------------------------------------------- CPropPageFrame::CPropPageFrame() : m_bShowCaption(FALSE), m_nCaptionHeight(0), m_hCaptionIcon(NULL), m_dwMsgFormat(DT_CENTER|DT_VCENTER|DT_NOPREFIX|DT_SINGLELINE) { } CPropPageFrame::~CPropPageFrame() { } ///////////////////////////////////////////////////////////////////// // Operations void CPropPageFrame::ShowCaption(BOOL bEnable) { m_bShowCaption = bEnable; SafeUpdateWindow(CalcCaptionArea()); } BOOL CPropPageFrame::GetShowCaption() const { return m_bShowCaption; } void CPropPageFrame::SetCaption(LPCTSTR lpszCaption, HICON hIcon /*= NULL*/) { m_strCaption = lpszCaption; m_hCaptionIcon = hIcon; SafeUpdateWindow(CalcCaptionArea()); } CString CPropPageFrame::GetCaption(HICON *pIcon /* = NULL */) const { if (pIcon) *pIcon = m_hCaptionIcon; return m_strCaption; } void CPropPageFrame::SetCaptionHeight(int nCaptionHeight) { m_nCaptionHeight = nCaptionHeight; SafeUpdateWindow(CalcCaptionArea()); } int CPropPageFrame::GetCaptionHeight() const { return m_nCaptionHeight; } void CPropPageFrame::SetMsgText(LPCTSTR lpszMsg) { m_strMsg = lpszMsg; SafeUpdateWindow(CalcMsgArea()); } CString CPropPageFrame::GetMsgText() const { return m_strMsg; } void CPropPageFrame::SetMsgFormat(DWORD dwFormat) { m_dwMsgFormat = dwFormat; SafeUpdateWindow(CalcMsgArea()); } DWORD CPropPageFrame::GetMsgFormat() const { return m_dwMsgFormat; } ///////////////////////////////////////////////////////////////////// // Overridable implementation helpers void CPropPageFrame::Draw(CDC *pDc) { if (GetShowCaption()) DrawCaption(pDc, CalcCaptionArea(), m_strCaption, m_hCaptionIcon); DrawMsg(pDc, CalcMsgArea(), m_strMsg, m_dwMsgFormat); } CRect CPropPageFrame::CalcMsgArea() { ASSERT(IsWindow(GetWnd()->GetSafeHwnd())); CRect rectMsg; GetWnd()->GetClientRect(rectMsg); if (GetShowCaption()) rectMsg.top+= GetCaptionHeight(); return rectMsg; } void CPropPageFrame::DrawMsg(CDC *pDc, CRect rect, LPCTSTR lpszMsg, DWORD dwFormat) { CFont *pPrevFont = dynamic_cast<CFont*>(pDc->SelectStockObject(DEFAULT_GUI_FONT)); int nPrevBkMode = pDc->SetBkMode(TRANSPARENT); pDc->DrawText(GetMsgText(), rect, GetMsgFormat()); pDc->SetBkMode(nPrevBkMode); pDc->SelectObject(pPrevFont); } CRect CPropPageFrame::CalcCaptionArea() { ASSERT(IsWindow(GetWnd()->GetSafeHwnd())); CRect rectCaption; GetWnd()->GetClientRect(rectCaption); if (!GetShowCaption()) rectCaption.bottom = rectCaption.top; else rectCaption.bottom = rectCaption.top+GetCaptionHeight(); return rectCaption; } void CPropPageFrame::DrawCaption(CDC *pDc, CRect rect, LPCTSTR lpszCaption, HICON hIcon) { // should be implemented by specialized classes } ///////////////////////////////////////////////////////////////////// // Implementation helpers void CPropPageFrame::SafeUpdateWindow(LPCRECT lpRect /* = NULL */) { if (!IsWindow(GetWnd()->GetSafeHwnd())) return; GetWnd()->InvalidateRect(lpRect, TRUE); } } //namespace TreePropSheet
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 195 ] ] ]
ee38c5392b33e1059f7ec0a6d30ed3fe0dc1b6c4
c1a2953285f2a6ac7d903059b7ea6480a7e2228e
/deitel/ch07/Fig07_23_25/GradeBook.h
9804a69bf972c575284b723e8f99f0a23478d641
[]
no_license
tecmilenio/computacion2
728ac47299c1a4066b6140cebc9668bf1121053a
a1387e0f7f11c767574fcba608d94e5d61b7f36c
refs/heads/master
2016-09-06T19:17:29.842053
2008-09-28T04:27:56
2008-09-28T04:27:56
50,540
4
3
null
null
null
null
UTF-8
C++
false
false
2,426
h
// Fig. 7.23: GradeBook.h // Definition of class GradeBook that uses a // two-dimensional array to store test grades. // Member functions are defined in GradeBook.cpp #include <string> // program uses C++ Standard Library string class using std::string; // GradeBook class definition class GradeBook { public: // constants const static int students = 10; // number of students const static int tests = 3; // number of tests // constructor initializes course name and array of grades GradeBook( string, const int [][ tests ] ); void setCourseName( string ); // function to set the course name string getCourseName(); // function to retrieve the course name void displayMessage(); // display a welcome message void processGrades(); // perform various operations on the grade data int getMinimum(); // find the minimum grade in the grade book int getMaximum(); // find the maximum grade in the grade book double getAverage( const int [], const int ); // get student's average void outputBarChart(); // output bar chart of grade distribution void outputGrades(); // output the contents of the grades array private: string courseName; // course name for this grade book int grades[ students ][ tests ]; // two-dimensional array of grades }; // end class GradeBook /************************************************************************** * (C) Copyright 1992-2008 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
[ [ [ 1, 46 ] ] ]
4784e2e52f5264447a43ced40c075b97a0b22c3f
0b55a33f4df7593378f58b60faff6bac01ec27f3
/Konstruct/Common/Utility/kpuVector.cpp
f9ceaea73945b2b086be702147cb0864cfbc5e9a
[]
no_license
RonOHara-GG/dimgame
8d149ffac1b1176432a3cae4643ba2d07011dd8e
bbde89435683244133dca9743d652dabb9edf1a4
refs/heads/master
2021-01-10T21:05:40.480392
2010-09-01T20:46:40
2010-09-01T20:46:40
32,113,739
1
0
null
null
null
null
UTF-8
C++
false
false
397
cpp
#include "StdAfx.h" #include "Common\Utility\kpuVector.h" const kpuVector kpuv_Zero(0.0f, 0.0f, 0.0f, 0.0f); const kpuVector kpuv_OneX(1.0f, 0.0f, 0.0f, 0.0f); const kpuVector kpuv_OneY(0.0f, 1.0f, 0.0f, 0.0f); const kpuVector kpuv_OneZ(0.0f, 0.0f, 1.0f, 0.0f); const kpuVector kpuv_OneW(0.0f, 0.0f, 0.0f, 1.0f); kpuVector::kpuVector(void) { } kpuVector::~kpuVector(void) { }
[ "acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e" ]
[ [ [ 1, 17 ] ] ]
fe5acbaaa8d5b0059f92a17f39a90168c2d997b7
555ce7f1e44349316e240485dca6f7cd4496ea9c
/DirectShowFilters/LiveMedia555/MediaPortal/MPTaskScheduler.cpp
c7be688184031a72b26a57b62fefc61f7b959410
[]
no_license
Yura80/MediaPortal-1
c71ce5abf68c70852d261bed300302718ae2e0f3
5aae402f5aa19c9c3091c6d4442b457916a89053
refs/heads/master
2021-04-15T09:01:37.267793
2011-11-25T20:02:53
2011-11-25T20:11:02
2,851,405
2
0
null
null
null
null
UTF-8
C++
false
false
1,414
cpp
/* * Copyright (C) 2006-2009 Team MediaPortal * http://www.team-mediaportal.com * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GNU Make; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #ifndef IMN_PIM #include "MPTaskScheduler.h" ////////// BasicTaskScheduler ////////// MPTaskScheduler* MPTaskScheduler::createNew() { return new MPTaskScheduler(); } MPTaskScheduler::MPTaskScheduler() : BasicTaskScheduler() { } MPTaskScheduler::~MPTaskScheduler() { } void MPTaskScheduler::doEventLoop(char* watchVariable) { // Repeatedly loop, handling readble sockets and timed events: //for (int i=0; i < 10;++i) { // if (watchVariable != NULL && *watchVariable != 0) break; SingleStep(1000000LL); //delay time is in micro seconds } } #endif
[ [ [ 1, 49 ] ] ]
66a15be66999d269e8ca3e1a41b6f6e48fd41a22
9b402d093b852a574dccb869fbe4bada1ef069c6
/code/foundation/kernel/timer.h
142ee21ca36279a37d46e3d07f2aa7daef9b96dc
[]
no_license
wangscript007/foundation-engine
adb24d4ccc932d7a8f8238170029de6d2db0cbfb
2982b06d8f6b69c0654e0c90671aaef9cfc6cc40
refs/heads/master
2021-05-27T17:26:15.178095
2010-06-30T22:06:45
2010-06-30T22:06:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,288
h
#if !defined(__F_TIMER_H_) #define __F_TIMER_H_ #include "debug.h" #include "memoryManager.h" #if FOUNDATION_PLATFORM == FOUNDATION_PLATFORM_LINUX # include <sys/time.h> # include <unistd.h> #elif FOUNDATION_PLATFORM == FOUNDATION_PLATFORM_WIN # define WIN32_LEAN_AND_MEAN # include <windows.h> #endif namespace Foundation { /** Class to provide an internal clock. @remarks API defines an OS independant representation of time. */ class TimeManager { public: /** Get the singleton class. */ static TimeManager& getSingleton(); /** Return the engine time. */ static double getTime(); /** Allows the thread to sleep. @param Time in milliseconds to sleep */ static void sleep(int milliseconds); /** Set the simulation factor @par Allows adjust of time. */ static void setSimulationFactor(double _factor); protected: TimeManager(); TimeManager(const TimeManager&); TimeManager& operator=(const TimeManager&); ~TimeManager(); private: #if FOUNDATION_PLATFORM == FOUNDATION_PLATFORM_WIN static LARGE_INTEGER m_nStartTime; #elif FOUNDATION_PLATFORM == FOUNDATION_PLATFORM_LINUX static int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y); static timeval m_nStartTime; #else static double m_fStartTime; #endif static double m_fSimulationFactor; }; /** Class to provide a wrapper for singleton class TimeManager @remarks This is used to keep Python happy with our singleton class. */ class TimeManager_PythonWrap { public: /** Default constructor */ TimeManager_PythonWrap(); /** Get the time from the real TimeManager */ double getTime(); /** Allows the thread to sleep @param Time in milliseconds. */ void sleep(int milliseconds); /** Set the simulation factor @par Allows adjust of time. */ void setSimulationFactor(double _factor); }; /** Class to provide timer implementation. @par Interaces with the TimeManager to provide a stopwatch timer. */ class Timer { public: Timer(); Timer(const Timer&); //Timer& operator=(const Timer&); ~Timer(); /** Pause the timer. @par Updates the running time and pauses the timer. */ void pause(); /** Resume the timer. @par Resumes the timer if it is paused. */ void resume(); /** Reset the timer. @par Resets the running time to 0 and pauses the timer. */ void reset(); /** Return the current timer value. */ double getTime(); private: double m_fStartTime; double m_fRunningTime; bool m_bPaused; }; }; #endif // __F_TIMER_H_
[ "drivehappy@a5d1a9aa-f497-11dd-9d1a-b59b2e1864b6" ]
[ [ [ 1, 127 ] ] ]
65630bfb62b9d73e434e159e636b78d56b9d6567
203f8465075e098f69912a6bbfa3498c36ce2a60
/motion_planning/planning_research/dynamic_planning/src/discrete_space_information/nav3ddyn/environment_nav3Ddyn.h
bddef35e15c4c70ba0ae8c8990769744e11a6827
[]
no_license
robcn/personalrobots-pkg
a4899ff2db9aef00a99274d70cb60644124713c9
4dcf3ca1142d3c3cb85f6d42f7afa33c59e2240a
refs/heads/master
2021-06-20T16:28:29.549716
2009-09-04T23:56:10
2009-09-04T23:56:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,174
h
/* * Copyright (c) 2008, Maxim Likhachev * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Pennsylvania nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef __ENVIRONMENT_NAV3DDYN_H_ #define __ENVIRONMENT_NAV3DDYN_H_ //eight-connected grid #define NAV3DDYN_XYWIDTH 1 #define NAV3DDYN_DEFAULTOBSTHRESH 254 //number of theta directions #define NAV3DDYN_THETADIRS 8 //number of actions per x,y,theta state #define NAV3DDYN_ACTIONWIDTH 5 //decrease, increase, same angle while moving plus decrease, increase angle while standing. #define NAV3DDYN_COSTMULT 1000 #define NAV3DDYN_MAXRV 1.57 //max rotational velocity - radians per second #define NAV3DDYN_NUMRV 5 //number of rotational velocity values to try //seconds #define NAV3DDYN_LONGDUR 1 #define NAV3DDYN_DURDISC 0.1 #define MIN(x,y) (x < y ? x : y) #define MAX(x,y) (x > y ? x : y) #define INFINITE_COST 1000000 typedef unsigned int cost_t; struct EnvNAV3DDYN2Dpt_t{ double x; double y; bool operator==(const EnvNAV3DDYN2Dpt_t &p) const{ return (x == p.x && y==p.y); } bool operator<(const EnvNAV3DDYN2Dpt_t &p) const{ return (x < p.x || (x == p.x && y < p.y)); } }; struct EnvNAV3DDYNContPose_t{ double X; double Y; double Theta; bool operator==(const EnvNAV3DDYNContPose_t &p) const{ return (X==p.X && Y==p.Y && Theta==p.Theta); } }; struct EnvNAV3DDYNContPoseWAction_t{ int ThetaId; int ActionId; double X; double Y; double Theta; bool operator==(const EnvNAV3DDYNContPose_t &p) const{ return (X==p.X && Y==p.Y && Theta==p.Theta); } }; struct EnvNAV3DDYNDiscPose_t { int X; int Y; int Theta; bool operator==(const EnvNAV3DDYNDiscPose_t &p) const{ return (X==p.X && Y==p.Y && Theta==p.Theta); } }; typedef struct{ EnvNAV3DDYN2Dpt_t center; double radius; }EnvNAV3DDYNCircle_t; typedef struct { int dX; //change in x during action int dY; //change in y int dTheta; //change in theta cost_t cost; double rv; //rotational velocity for action double tv; //translational velocity for action vector<EnvNAV3DDYNContPose_t> path_cont; //for debugging purposes vector<EnvNAV3DDYNDiscPose_t> path; //path of center of robot vector<EnvNAV3DDYN2Dpt_t> footprint; //footprint swept during action vector<EnvNAV3DDYNCircle_t> footprint_circles; int time; //time to execute action } EnvNAV3DDYNAction_t; //configuration parameters typedef struct ENV_NAV3DDYN_CONFIG { int EnvWidth_c; int EnvHeight_c; int StartX_c; int StartY_c; int StartTheta; int EndX_c; int EndY_c; int EndTheta; unsigned char ObsThresh; int OptimizeFootprint; unsigned char** Grid2D; unsigned char** Grid2D_expanded; double nominalvel_mpersecs; //translational velocity double timetoturnoneunitinplace_secs; double cellsize_m; int dXY[NAV3DDYN_XYWIDTH][2]; //footprint of robot vector <EnvNAV3DDYN2Dpt_t> FootprintPolygon; //real world coordinates vector <EnvNAV3DDYNCircle_t> FootprintCircles; EnvNAV3DDYNAction_t** ActionsV; //array of actions, ActionsV[i][j] - jth action for sourcetheta = i vector<EnvNAV3DDYNAction_t*>* PredActionsV; } EnvNAV3DDYNConfig_t; typedef struct { int stateID; int X; int Y; char Theta; } EnvNAV3DDYNHashEntry_t; //variables that dynamically change (e.g., array of states, ...) typedef struct { int startstateid; int goalstateid; //hash table of size x_size*y_size. Maps from coords to stateId int HashTableSize; vector<EnvNAV3DDYNHashEntry_t*>* Coord2StateIDHashTable; //vector that maps from stateID to coords vector<EnvNAV3DDYNHashEntry_t*> StateID2CoordTable; //any additional variables }EnvironmentNAV3DDYN_t; class EnvironmentNAV3DDYN : public DiscreteSpaceInformation { public: EnvironmentNAV3DDYN(); ~EnvironmentNAV3DDYN(){}; const EnvNAV3DDYNConfig_t* GetEnvNavConfig(); //environment initialization functions bool InitializeEnv(const char* sEnvFile); bool InitializeEnv(int width, int height, const unsigned char* mapdata, double startx, double starty, double starttheta, double goalx, double goaly, double goaltheta, double goaltol_x, double goaltol_y, double goaltol_theta, const vector<sbpl_2Dpt_t> & perimeterptsV, double cellsize_m, double nominalvel_mpersecs, double timetoturnoneunitinplace_secs, unsigned char obsthresh); void PrecomputeActions(); void CalculateFootprintForPath(vector<EnvNAV3DDYNContPose_t> path, vector<EnvNAV3DDYN2Dpt_t>* footprint, vector<EnvNAV3DDYNCircle_t>* footprint_circles, double tv, double rv); void CalculateFootprintForPose(EnvNAV3DDYNContPose_t pose, vector<EnvNAV3DDYN2Dpt_t>* footprint, double tv, double rv); void RemoveDuplicatesFromPath(vector<EnvNAV3DDYNDiscPose_t>* path); void RemoveDuplicatesFromFootprint(vector<EnvNAV3DDYN2Dpt_t>* footprint); void PadEnvironment(); void CalculateCircleCoverageInFootprint(EnvNAV3DDYNCircle_t circle, vector<EnvNAV3DDYN2Dpt_t> footprint, vector<EnvNAV3DDYN2Dpt_t>* swept_area); void RemoveAreaFromFootprint(vector<EnvNAV3DDYN2Dpt_t>* area, vector<EnvNAV3DDYN2Dpt_t>* footprint); //planning initialization functions bool InitializeMDPCfg(MDPConfig *MDPCfg); int SetStart(double x, double y, double theta); int SetGoal(double x, double y, double theta); void EnableOptimizeFootprint(); void DisableOptimizeFootprint(); void SetObsThresh(unsigned char thresh); //planning functions void GetSuccs(int SourceStateID, vector<int>* SuccIDV, vector<int>* CostV); void GetPreds(int TargetStateID, vector<int>* PredIDV, vector<int>* CostV); int GetFromToHeuristic(int FromStateID, int ToStateID); bool UpdateCost(int x, int y, int new_status); void GetCoordFromState(int stateID, int& x, int& y, int& theta) const; int GetStateFromCoord(int x, int y, int theta); bool IsObstacle(int x, int y); //debugging functions void PrintConfigurationToFile(const char* logFile); void PrintActionsToFile(const char* logFile); void PrintState(int stateID, bool bVerbose, FILE* fOut=NULL); void PrintTimeStat(FILE* fOut); void PrintCheckedCells(FILE* fOut); int SizeofCreatedEnv(); void GetEnvParms(int *size_x, int *size_y, double* startx, double* starty, double* starttheta, double* goalx, double* goaly, double* goaltheta, double* cellsize_m, unsigned char* obsthresh); void GetContPathFromStateIds(vector<int> stateIdV, vector<EnvNAV3DDYNContPoseWAction_t>* path); //functions updated but not tested int GetGoalHeuristic(int stateID); int GetStartHeuristic(int stateID); //Not Yet Implemented void SetAllActionsandAllOutcomes(CMDPSTATE* state); void SetAllPreds(CMDPSTATE* state); void PrintEnv_Config(FILE* fOut); void GetPredsofChangedEdges(vector<nav2dcell_t>* changedcellsV, vector<int> *preds_of_changededgesIDV); private: //member data EnvNAV3DDYNConfig_t EnvNAV3DDYNCfg; EnvironmentNAV3DDYN_t EnvNAV3DDYN; //2D search for heuristic computations bool bNeedtoRecomputeStartHeuristics; SBPL2DGridSearch* grid2Dsearch; int CheckedCells_100k; int CheckedCells; //hash table functions unsigned int GETHASHBIN(unsigned int X, unsigned int Y, unsigned int Theta); EnvNAV3DDYNHashEntry_t* GetHashEntry(int X, int Y, int Theta); //Initialization functions void ReadConfiguration(FILE* fCfg); void SetConfiguration(int width, int height, const unsigned char* mapdata, int startx, int starty, int starttheta, int goalx, int goaly, int goaltheta, double cellsize_m, double nominalvel_mpersecs, double timetoturnoneunitinplace_secs, const vector<sbpl_2Dpt_t> & robot_perimeterV); bool InitGeneral(); void InitializeEnvConfig(); void InitializeEnvironment(); void ComputeHeuristicValues(); int InsideFootprint(EnvNAV3DDYN2Dpt_t pt, vector<EnvNAV3DDYN2Dpt_t>* bounding_polygon); void CreateStartandGoalStates(); //utility functions cost_t GetCostOfCell(EnvNAV3DDYN2Dpt_t cell); cost_t GetCostOfCell(EnvNAV3DDYNCircle_t cell); cost_t ComputeCostOfFootprint(vector<EnvNAV3DDYN2Dpt_t> footprint, vector<EnvNAV3DDYNCircle_t> footprint_circles, int xOffset, int yOffset); //debugging functions void PrintHashTableHist(); bool IsValidCell(int X, int Y); bool IsWithinMapCell(int X, int Y); bool CheckQuant(FILE* fOut); EnvNAV3DDYNHashEntry_t* CreateNewHashEntry(int X, int Y, int Theta); }; #endif
[ "jeking@f5854215-dd47-0410-b2c4-cdd35faa7885" ]
[ [ [ 1, 323 ] ] ]
dc7fc2e4f08e27cebc98de4983431c7dc3247734
111599781f886c42099cb9f4ccadff397cab51e8
/RowContainer.cpp
c5e58c3ee0e447ea26f92b7d00ca84005ec8bd6a
[]
no_license
victorliu/ColumnViewBrowser
6fd5f02cc37b4834aec59c736d3b9006ba3fc183
a37b8bcf272c125041492b681bdb280f051fa478
refs/heads/master
2020-05-29T17:30:33.683440
2011-02-05T10:45:03
2011-02-05T10:45:03
528,279
2
0
null
null
null
null
UTF-8
C++
false
false
10,840
cpp
#include "StdAfx.h" #include "RowContainer.h" #include "CPidlMgr.h" #include <stack> /* BOOL CRowContainer::PreTranslateMessage(MSG* pMsg){ if(WM_MOUSEWHEEL == pMsg->message){ POINT p; p.x = GET_X_LPARAM(pMsg->lParam); p.y = GET_Y_LPARAM(pMsg->lParam); HWND hWndPt = WindowFromPoint(p); if(NULL != hWndPt){ ::PostMessage(hWndPt, WM_MOUSEWHEEL, pMsg->wParam, pMsg->lParam); return TRUE; } } return FALSE; }*/ int CRowContainer::OnCreate(LPCREATESTRUCT lpCreateStruct){ CRowContainer::LPCreateParams pcp = (CRowContainer::LPCreateParams)lpCreateStruct->lpCreateParams; m_nFirstPaneOffset = 0; RecomputeTotalPanesWidth(); SetMsgHandled(FALSE); return 0; } void CRowContainer::OnDestroy(){ RemoveAllPanes(); } void CRowContainer::RemoveAllPanes(){ PaneList_t::iterator pane_iter = m_panes.begin(); while(pane_iter != m_panes.end()){ PaneList_t::iterator current = pane_iter++; current->DestroyWindow(); current->m_hWnd = NULL; m_panes.erase(current); } // m_panes.clear(); } void CRowContainer::OnSize(UINT nType, CSize size){ RECT rc; GetClientRect(&rc); UpdateColumnLayout(&rc, 0); UpdateScrollBar(); } // TODO: optimize this to only erase visible part of bkgnd LRESULT CRowContainer::OnEraseBkgnd(CDCHandle dc){ RECT rc; GetClientRect(&rc); dc.FillRect(&rc, COLOR_3DFACE); return TRUE; } int CRowContainer::OnPaneResize(HWND hPane){ RECT rc; GetRowRect(&rc); BOOL bFound = FALSE; int nWidthSoFar = 0; PaneList_t::iterator pane_iter; for(pane_iter = m_panes.begin(); pane_iter != m_panes.end(); ++pane_iter){ RECT crc; pane_iter->GetClientRect(&crc); if(bFound || (hPane == pane_iter->m_hWnd)){ pane_iter->MoveWindow(m_nFirstPaneOffset+nWidthSoFar, rc.top, crc.right-crc.left, rc.bottom-rc.top); bFound = TRUE; } nWidthSoFar += crc.right-crc.left; } m_nTotalPanesWidth = nWidthSoFar; int nOffsetOld = m_nFirstPaneOffset; int rcWidth = rc.right - rc.left; BOOL bFitsInContainer = (m_nTotalPanesWidth < rcWidth); BOOL bRightSidePinned = (m_nFirstPaneOffset + m_nTotalPanesWidth <= rcWidth); if(bFitsInContainer){ // if all panes fit in the RowContainer, just pin the root pane at the left edge if(m_nFirstPaneOffset != 0){ m_nFirstPaneOffset = 0; UpdateColumnLayout(&rc, 0); } }else if(bRightSidePinned){ m_nFirstPaneOffset = rcWidth - m_nTotalPanesWidth; UpdateColumnLayout(&rc, 0); } UpdateScrollBar(); return 0; } void CRowContainer::GetRowRect(RECT *rc){ GetClientRect(rc); } //LRESULT CRowContainer::OnGetGetRowRect(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/){ // LPRECT prc = (LPRECT)wParam; // if(NULL != prc){ // GetRowRect(prc); // } // return 0; //} void CRowContainer::UpdateColumnLayout(RECT *rc, UINT startcol){ if(startcol >= m_panes.size()){ return; } // Get to the startcol int nWidthSoFar = 0; PaneList_t::iterator pane_iter = m_panes.begin(); for(UINT col = 0; col < startcol; ++col){ RECT crc; pane_iter->GetClientRect(&crc); nWidthSoFar += crc.right-crc.left; ++pane_iter; } while(pane_iter != m_panes.end()){ RECT crc; pane_iter->GetClientRect(&crc); pane_iter->MoveWindow(m_nFirstPaneOffset+nWidthSoFar, rc->top, crc.right-crc.left, rc->bottom-rc->top); nWidthSoFar += crc.right-crc.left; ++pane_iter; } m_nTotalPanesWidth = nWidthSoFar; } void CRowContainer::RecomputeTotalPanesWidth(){ m_nTotalPanesWidth = 0; PaneList_t::iterator pane_iter = m_panes.begin(); while(pane_iter != m_panes.end()){ RECT rc; pane_iter->GetClientRect(&rc); m_nTotalPanesWidth += rc.right-rc.left; ++pane_iter; } } // Assumes m_nTotalPanesWidth and m_nFirstPaneOffset are correct void CRowContainer::UpdateScrollBar(BOOL bScrollToEnd){ CRect rc; GetClientRect(&rc); SCROLLINFO si; si.cbSize = sizeof(SCROLLINFO); si.nMin = 0; si.nPage = rc.right; si.nMax = m_nTotalPanesWidth; if(bScrollToEnd){ si.nPos = si.nMax; }else{ si.nPos = -m_nFirstPaneOffset; } si.fMask = SIF_DISABLENOSCROLL | SIF_PAGE | SIF_POS | SIF_RANGE; SetScrollInfo(SB_HORZ, &si, TRUE); } void CRowContainer::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar pScrollBar){ SCROLLINFO si; si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_PAGE; GetScrollInfo(SB_HORZ, &si); int page = si.nPage; switch(nSBCode){ case SB_LINELEFT: ScrollDelta(-CRowContainer::m_nScrollPixels); break; case SB_LINERIGHT: ScrollDelta(+CRowContainer::m_nScrollPixels); break; case SB_PAGELEFT: ScrollDelta(-page); break; case SB_PAGERIGHT: ScrollDelta(+page); break; case SB_THUMBPOSITION: ScrollTo(nPos); break; case SB_THUMBTRACK: ScrollTo(nPos); break; case SB_LEFT: ScrollTo(0); break; case SB_RIGHT: ScrollTo(MAXLONG); break; } } void CRowContainer::ScrollTo(LONG pos){ RECT rc; GetRowRect(&rc); pos = max(pos, 0); pos = min(pos, m_nTotalPanesWidth - rc.right); m_nFirstPaneOffset = -pos; UpdateColumnLayout(&rc, 0); SCROLLINFO si; si.cbSize = sizeof(SCROLLINFO); si.fMask = SIF_POS | SIF_TRACKPOS; si.nTrackPos = si.nPos = -m_nFirstPaneOffset; SetScrollInfo(SB_HORZ, &si, TRUE); } void CRowContainer::ScrollDelta(LONG dpos){ ScrollTo(-m_nFirstPaneOffset + dpos); } void CRowContainer::RemovePanesAfter(HWND hPane){ BOOL bFound = FALSE; PaneList_t::iterator pane_iter; for(pane_iter = m_panes.begin(); pane_iter != m_panes.end(); ++pane_iter){ if((*pane_iter) == hPane){ ++pane_iter; break; } } while(pane_iter != m_panes.end()){ PaneList_t::iterator current = pane_iter++; current->DestroyWindow(); current->m_hWnd = NULL; m_panes.erase(current); } } void CRowContainer::AppendPane(LPSHELLFOLDER parent, LPITEMIDLIST pidl){ RECT rc, crc; GetClientRect(&crc); CopyRect(&rc, &crc); // Must set the width of the rect passed to a CColumnPane::Create rc.left = m_nFirstPaneOffset + m_nTotalPanesWidth; rc.right = rc.left + CRowContainer::m_nPaneDefaultWidth; int dx = rc.right - crc.right; // after this, dx is amount protruding past right edge of container // Automatically set the position of the new pane visible (right adjusted if possible) m_nTotalPanesWidth += CRowContainer::m_nPaneDefaultWidth; int width = crc.right - crc.left; if(m_nTotalPanesWidth > width){ m_nFirstPaneOffset = width - m_nTotalPanesWidth; }else{ m_nTotalPanesWidth = 0; } m_panes.push_back(CColumnPane()); CColumnPane::CreateParams cp; cp.parent_folder = parent; cp.rel_pidl = pidl; cp.is_folder = true; m_panes.back().Create(*this, &rc, NULL, 0, 0, (HMENU)(m_nPaneBaseID+m_panes.size()), &cp); } void CRowContainer::NewRootPane(LPITEMIDLIST pidl){ RemoveAllPanes(); { LPSHELLFOLDER pIDesktop; if(S_OK == SHGetDesktopFolder(&pIDesktop)){ AppendPane(CComPtr<IShellFolder>(pIDesktop), pidl); // need to notify MainFrm to update address bar { CColumnPane::NMLISTVIEWSELECTPIDL nmhdr; nmhdr.parent_folder = pIDesktop; nmhdr.selected_pidl = pidl; nmhdr.hdr.code = m_nAddressUpdateNotification; nmhdr.hdr.idFrom = GetDlgCtrlID(); nmhdr.hdr.hwndFrom = m_hWnd; GetParent().SendMessage(WM_NOTIFY, (WPARAM)nmhdr.hdr.idFrom, (LPARAM)&nmhdr); } } } UpdateScrollBar(TRUE); } LRESULT CRowContainer::OnPaneItemSelected(int id, LPNMHDR lParam, BOOL &bHandled){ CColumnPane::LPNMLISTVIEWSELECTPIDL plvsp = (CColumnPane::LPNMLISTVIEWSELECTPIDL)lParam; HWND hFrom = plvsp->hdr.hwndFrom; RemovePanesAfter(hFrom); AppendPane(plvsp->parent_folder, plvsp->selected_pidl); // need to notify MainFrm to update address bar { CColumnPane::NMLISTVIEWSELECTPIDL nmhdr; nmhdr.parent_folder = plvsp->parent_folder; nmhdr.selected_pidl = plvsp->selected_pidl; nmhdr.hdr.code = m_nAddressUpdateNotification; nmhdr.hdr.idFrom = GetDlgCtrlID(); nmhdr.hdr.hwndFrom = m_hWnd; GetParent().SendMessage(WM_NOTIFY, (WPARAM)nmhdr.hdr.idFrom, (LPARAM)&nmhdr); } UpdateScrollBar(TRUE); return 0; } LRESULT CRowContainer::OnPaneItemDeselected(int id, LPNMHDR lParam, BOOL &bHandled){ CColumnPane::LPNMLISTVIEWSELECTPIDL plvsp = (CColumnPane::LPNMLISTVIEWSELECTPIDL)lParam; HWND hFrom = plvsp->hdr.hwndFrom; RemovePanesAfter(hFrom); UpdateScrollBar(TRUE); return 0; } LRESULT CRowContainer::OnPaneFocused(int id, LPNMHDR lParam, BOOL &bHandled){ m_hwndActivePane = lParam->hwndFrom; return 0; } /* BOOL CRowContainer::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt){ UINT uScroll = 0; if(!SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &uScroll, 0)) { uScroll = 3; }else{ } if(uScroll == WHEEL_PAGESCROLL){ uScroll = CRowContainer::m_nPaneDefaultWidth; // not great, but works for now } if(0 == uScroll){ return FALSE; } int dAmountToScroll = zDelta * (int)uScroll / (WHEEL_DELTA * CRowContainer::m_nScrollPixels); ScrollDelta(-dAmountToScroll); return 0; } */ int CRowContainer::GetActivePaneIndex(){ int j = 0; for(PaneList_t::const_iterator i = m_panes.begin(); i != m_panes.end(); ++i){ if(HWND(*i) == m_hwndActivePane){ return j; } ++j; } return -1; } void CRowContainer::SetActivePaneIndex(int index){ int j = 0; for(PaneList_t::iterator i = m_panes.begin(); i != m_panes.end(); ++i){ if(j == index){ i->SetFocus(); break; } } } CColumnPane* CRowContainer::GetActivePane(){ for(PaneList_t::iterator i = m_panes.begin(); i != m_panes.end(); ++i){ if(HWND(*i) == m_hwndActivePane){ return &(*i); } } return NULL; } CColumnPane* CRowContainer::GetPane(int index){ int j = 0; for(PaneList_t::iterator i = m_panes.begin(); i != m_panes.end(); ++i){ if(j == index){ return &(*i); } ++j; } return NULL; } void CRowContainer::BrowseToPath(LPTSTR path){ LPSHELLFOLDER psfParent; if(SUCCEEDED(SHGetDesktopFolder(&psfParent))){ LPITEMIDLIST pidl; SFGAOF sfgaoOut = 0; if(SUCCEEDED(psfParent->ParseDisplayName(NULL, NULL, path, NULL, &pidl, &sfgaoOut))){ // Call SHGetDesktopFolder to obtain IShellFolder for the desktop folder. LPITEMIDLIST curpidl = pidl; if(NULL != curpidl){ // Trim off drive letter part of PIDL RemoveAllPanes(); do{ LPITEMIDLIST curpidlcopy = CPidlMgr::Copy(curpidl,1); LPSHELLFOLDER pShellFolder; if(S_OK != psfParent->BindToObject(curpidlcopy, NULL, IID_IShellFolder, (void**)&pShellFolder)){ break; } AppendPane(psfParent, curpidlcopy); psfParent->Release(); psfParent = pShellFolder; }while(NULL != (curpidl = CPidlMgr::GetNextItem(curpidl))); UpdateScrollBar(TRUE); CPidlMgr::Delete(pidl); } } psfParent->Release(); } }
[ [ [ 1, 377 ] ] ]
d5d1eb0ec99ea361cdf8d3ae7445df17b9607dc8
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Source/Nuclex/Support/Cacheable.cpp
ad75226e7d264c6f532fff4ab1f2c26ee22bd0ba
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
1,129
cpp
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## Cacheable.cpp - Cacheable object  // // ### # # ###  // // # ### # ### Attribute for cacheable objects  // // # ## # # ## ##  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #include "Nuclex/Support/Cacheable.h" using namespace Nuclex; using namespace Nuclex::Support; Cacheable::CacheID Cacheable::s_nNextUniqueID = 0; // ####################################################################### // // # Nuclex::Support::Cacheable::createUniqueID() # // // ####################################################################### // /** Creates a new unique id */ size_t Cacheable::createUniqueID() { return ++s_nNextUniqueID; }
[ [ [ 1, 23 ] ] ]
ea309fb7d6aac8a380a9bc723ded71d616115b25
ed8cbdeb94cdc3364586c6e73d48427eab3dd624
/benchmarks/win32/Programming Projects/Columbia/VC/EvtDisp/AMTSEvtDisp.h
861bdbf33b699c4ccd2ecad170a3640f715fb435
[]
no_license
Programming-Systems-Lab/archived-events
3b5281b1f3013cc4a3943e52cfd616d2daeba6f2
61d521b39996393ad7ad6d9430dbcdab4b2b36c6
refs/heads/master
2020-09-17T23:37:34.037734
2002-12-20T15:45:08
2002-12-20T15:45:08
67,139,857
0
0
null
null
null
null
UTF-8
C++
false
false
1,131
h
// AMTSEvtDisp.h : Declaration of the AMTSEvtDisp #ifndef __AMTSEVTDISP_H_ #define __AMTSEVTDISP_H_ #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // AMTSEvtDisp class ATL_NO_VTABLE AMTSEvtDisp : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<AMTSEvtDisp, &CLSID_AMTSEvtDisp>, public ISupportErrorInfo, public IAMTSEvtDisp, public ICallFactory //implemement ICallFactory interface { public: AMTSEvtDisp() { } DECLARE_REGISTRY_RESOURCEID(IDR_AMTSEVTDISP) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(AMTSEvtDisp) COM_INTERFACE_ENTRY(IAMTSEvtDisp) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY(ICallFactory) END_COM_MAP() // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); // IAMTSEvtDisp public: STDMETHOD(FireDirectedEvent)(/*[in]*/ BSTR bstrData, /*[in]*/ BSTR bstrDest ); // ICallFactory STDMETHOD(CreateCall)( REFIID riid1, IUnknown* pUnk, REFIID riid2, IUnknown** ppv ); }; #endif //__AMTSEVTDISP_H_
[ "jjp32" ]
[ [ [ 1, 46 ] ] ]
efcd7d143dc78d201809ce71f538c2ab69d63f68
27550bf27ce87364642a29b350dfcecb740de34e
/dalek.h
29cad6e4527d850eb2437bbf9cd710ad8f11c18d
[]
no_license
clholgat/Asteroids
e3a1e17fa18d47a6658b8bd9274334fa41c7e7a5
a468ed28945c3a35f247ec79ecfc28248f3d52b2
refs/heads/master
2021-01-18T14:07:38.369932
2011-12-06T16:18:45
2011-12-06T16:18:45
2,925,994
0
0
null
null
null
null
UTF-8
C++
false
false
836
h
#ifndef DALEK_H #define DALEK_H #include "model.h" #include "shot.h" #include "tardis.h" class Dalek: public Model{ public: Dalek(); void draw(); void init(double scaleFactor); void modelInit(int num); bool update(); double scale; bool initialized; list<Shot*> shots; list<Shot*>::iterator itS; void shoot(Tardis *tardis, list<Asteroid*> *asteroids); bool checkShots(Model *model); bool checkDalek(Model *model); private: void drawBase(float base[][3], float y); void drawSides(); void drawHead(); void drawArms(); void drawSph(float bot[][3], float top[][3]); int mod(int num, int mod); void drawThing(float len, float scale); float dalekBase [9][3]; float dalekTop [9][3]; float yAng; float corners[4][2]; float current[4][2]; float head[2]; float currentHead[2]; }; #endif
[ [ [ 1, 41 ] ] ]
a69c56105ce43b8c7cb3965bf55a9efe09c437ea
b654c48c6a1f72140ca14defd05b835d4dec5a75
/prog2/prog2.cpp
8ca00568bedb9686be22455dee0c70463f0b7c9a
[]
no_license
johntalton/cs470
036ca995c48712d2506665a337a6d814ab11d347
187c87a60e2b2fdacd038eddb683a68ecd9c711d
refs/heads/master
2021-01-22T17:57:09.139203
1999-06-28T17:32:00
2017-08-18T18:09:22
100,736,624
0
0
null
null
null
null
UTF-8
C++
false
false
1,137
cpp
#include "../glcontrol.h" //Include the basics for adding this into OpenGL #include "../globals.h" #include "../prog1/prog1.h" //Include OUR old basic code #include "prog2.h" // this is what we are now makeing #include <math.h> int Animate = TRUE; // Use this to tell user whater we want to constanly redraw or not /************************************************************************** * DrawScene * This is our function that is called on draw. This is really the * only thing that neads to be in here. * @param void * @return void **************************************************************************/ void DrawScene() { Point2 p0[10],p1[10]; int x; p0[0].x = 40;//80.3; p0[0].y = 58.8; p0[1].x = 101.6; p0[1].y = 71.9; p0[2].x = -10;//93.6 p0[2].y = -10;//25.2 p0[3].x = 147.7; p0[3].y = 45.1; setColor(0.0,0.0,1.0); polyfill(4,p0); setColor(1.0,1.0,0.0); polygon(4,p0); setClipWindow(5,5,100,100); polyclip(4,p0,x,p1); gradfillFrom(1.0,0.0,0.0); gradfillTo(1.0,1.0,0.0); polyfillgrad(x,p1); }
[ [ [ 1, 39 ] ] ]
6bc3396c709de5704b6e425df6b378d47cf8f36c
ce262ae496ab3eeebfcbb337da86d34eb689c07b
/SEFoundation/SEShaders/SEVertexShader.h
20ff77cc208179e786b50c6b8e31e319fab46bd2
[]
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,745
h
// 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 #ifndef Swing_VertexShader_H #define Swing_VertexShader_H #include "SEFoundationLIB.h" #include "SEPlatforms.h" #include "SEShader.h" #include "SEVertexProgram.h" namespace Swing { //---------------------------------------------------------------------------- // Description: // Author:Sun Che // Date:20080701 //---------------------------------------------------------------------------- class SE_FOUNDATION_API SEVertexShader : public SEShader { SE_DECLARE_RTTI; SE_DECLARE_NAME_ID; SE_DECLARE_STREAM; public: SEVertexShader(const std::string& rShaderName); virtual ~SEVertexShader(void); SEVertexProgram* GetProgram(void) const; protected: SEVertexShader(void); }; typedef SESmartPointer<SEVertexShader> SEVertexShaderPtr; } #endif
[ "[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac" ]
[ [ [ 1, 57 ] ] ]
8e125871f4e1d87593c57267f45ff557f29f1632
c436aa4235117da3d21fafeeafd96076ee8fea78
/exports.cpp
a88c533e90700ce7160008fdb364bf2638cb7739
[]
no_license
tinku99/ahkmingw
95bb91840b5b596f7c9c2e42b9fd6f554dc99623
8ee59d8a0c4262bab2069953514bda8ed116116d
refs/heads/master
2020-12-30T14:56:10.907187
2010-02-16T10:37:34
2010-02-16T10:37:34
290,514
3
1
null
null
null
null
UTF-8
C++
false
false
9,975
cpp
#include "stdafx.h" // pre-compiled headers #include "globaldata.h" // for access to many global vars #include "application.h" // for MsgSleep() #include "exports.h" #include "script.h" // Naveen: v1. ahkgetvar() EXPORT VarSizeType ahkgetvar(char *name, char *output) { Var *ahkvar = g_script.FindOrAddVar(name); return ahkvar->Get(output); // var.getText() added in V1. } EXPORT int ahkassign(char *name, char *value) // ahkwine 0.1 { Var *var; if ( !(var = g_script.FindOrAddVar(name, strlen(name))) ) return -1; // Realistically should never happen. var->Assign(value); return 0; // success } EXPORT int ximportfunc(ahkx_int_str func1, ahkx_int_str func2, ahkx_int_str_str func3) // Naveen ahkx N11 { g_script.xifwinactive = func1 ; g_script.xwingetid = func2 ; g_script.xsend = func3; return 0; } EXPORT unsigned int ahkFindFunc(char *funcname) { return (unsigned int)g_script.FindFunc(funcname); } void BIF_FindFunc(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) // Added in Nv8. { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = ""; // Get the first arg, which is the string used as the source of the extraction. Call it "findfunc" for clarity. char funcname_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. char *funcname = ExprTokenToString(*aParam[0], funcname_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int funcname_length = (int)EXPR_TOKEN_LENGTH(aParam[0], funcname); aResultToken.value_int64 = (__int64)ahkFindFunc(funcname); return; } EXPORT int ahkLabel(char *aLabelName) { Label *aLabel = g_script.FindLabel(aLabelName) ; if (aLabel) { PostMessage(g_hWnd, AHK_EXECUTE_LABEL, (LPARAM)aLabel, (LPARAM)aLabel); return 0; } else return -1; } EXPORT int ahkKey(char *keys) // N11 sendahk { // SendKeys(keys, false, SM_EVENT, 0, 1); // sc_type aSC = TextToSC(keys); // vk_type aVK = TextToVK(keys); // keybd_event((byte)aVK, (byte)aSC, 0, 0); // char buf[10] = {0}; // strncpy(buf, keys, 10); // printf("in ahkkey with %s", buf); PostMessage(g_hWnd, AHK_SENDKEYS, (WPARAM)keys, (LPARAM)keys); return 0; } void BIF_sendahk(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) // Added in N11 { aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = ""; char keys_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. char *keys = ExprTokenToString(*aParam[0], keys_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int keys_length = (int)EXPR_TOKEN_LENGTH(aParam[0], keys); SendKeys(keys, false, SM_EVENT, 0, 1); aResultToken.value_int64 = 0; return; } // Naveen: v6 addFile() // Todo: support for #Directives, and proper treatment of mIsReadytoExecute EXPORT unsigned int addFile(char *fileName, bool aAllowDuplicateInclude, int aIgnoreLoadFailure) { // dynamically include a file into a script !! // labels, hotkeys, functions. Line *oldLastLine = g_script.mLastLine; if (aIgnoreLoadFailure > 1) // if third param is > 1, reset all functions, labels, remove hotkeys { g_script.mFirstFunc = NULL; // Naveen g_script.mFirstLabel = NULL ; g_script.mLastLabel = NULL ; g_script.mLastFunc = NULL ; g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, aIgnoreLoadFailure); } else { g_script.LoadIncludedFile(fileName, aAllowDuplicateInclude, (bool) aIgnoreLoadFailure); } g_script.PreparseBlocks(oldLastLine->mNextLine); // return (unsigned int) oldLastLine->mNextLine; // } void BIF_Import(ExprTokenType &aResultToken, ExprTokenType *aParam[], int aParamCount) // Added in Nv8. { // Set default return value in case of early return. aResultToken.symbol = SYM_INTEGER ; aResultToken.marker = ""; bool aIgnoreLoadFailure = false ; bool aAllowDuplicateInclude = false ; // Get the first arg, which is the string used as the source of the extraction. Call it "haystack" for clarity. char haystack_buf[MAX_NUMBER_SIZE]; // A separate buf because aResultToken.buf is sometimes used to store the result. char *haystack = ExprTokenToString(*aParam[0], haystack_buf); // 46 uses tokens differently // char *haystack = TokenToString(*aParam[0], haystack_buf); // Remember that aResultToken.buf is part of a union, though in this case there's no danger of overwriting it since our result will always be of STRING type (not int or float). int haystack_length = (int)EXPR_TOKEN_LENGTH(aParam[0], haystack); if (aParamCount < 2)// Load-time validation has ensured that at least the first parameter is present: { aResultToken.value_int64 = (__int64)addFile(haystack, false, 0); // Hotkey::HookUp() ; didn't work: see if we can remove dependence on having to suspend * 2 to enable hotkeys Nv8. return; } else aAllowDuplicateInclude = (bool)ExprTokenToInt64(*aParam[1]); // 46 has different tokens // aAllowDuplicateInclude = (bool)TokenToInt64(*aParam[1]); // The one-based starting position in haystack (if any). Convert it to zero-based. __int64 clear = ExprTokenToInt64(*aParam[2]) ; // __int64 clear = TokenToInt64(*aParam[2]) ; #ifndef AUTOHOTKEYSC aResultToken.value_int64 = (__int64)addFile(haystack, aAllowDuplicateInclude, (int)clear); #endif return; } EXPORT int ahkFunction(char *func, char *param1, char *param2, char *param3, char *param4) { Func *aFunc = g_script.FindFunc(func) ; if (aFunc) { g_script.mTempFunc = aFunc ; PostMessage(g_hWnd, AHK_EXECUTE_FUNCTION, (WPARAM)param1, (LPARAM)param2); return 0; } else return -1; } bool callFunc(WPARAM awParam, LPARAM alParam) { Func &func = *(Func *)g_script.mTempFunc ; if (!INTERRUPTIBLE_IN_EMERGENCY) return false; if (g_nThreads >= g_MaxThreadsTotal) // Below: Only a subset of ACT_IS_ALWAYS_ALLOWED is done here because: // 1) The omitted action types seem too obscure to grant always-run permission for msg-monitor events. // 2) Reduction in code size. if (func.mJumpToLine->mActionType != ACT_EXITAPP && func.mJumpToLine->mActionType != ACT_RELOAD) return false; // Need to check if backup is needed in case script explicitly called the function rather than using // it solely as a callback. UPDATE: And now that max_instances is supported, also need it for that. // See ExpandExpression() for detailed comments about the following section. VarBkp *var_backup = NULL; // If needed, it will hold an array of VarBkp objects. int var_backup_count; // The number of items in the above array. if (func.mInstances > 0) // Backup is needed. if (!Var::BackupFunctionVars(func, var_backup, var_backup_count)) // Out of memory. return false; // Since we're in the middle of processing messages, and since out-of-memory is so rare, // it seems justifiable not to have any error reporting and instead just avoid launching // the new thread. // Since above didn't return, the launch of the new thread is now considered unavoidable. // See MsgSleep() for comments about the following section. char ErrorLevel_saved[ERRORLEVEL_SAVED_SIZE]; strlcpy(ErrorLevel_saved, g_ErrorLevel->Contents(), sizeof(ErrorLevel_saved)); global_struct global_saved; CopyMemory(&global_saved, &g, sizeof(global_struct)); InitNewThread(0, false, true, func.mJumpToLine->mActionType); // See ExpandExpression() for detailed comments about the following section. if (func.mParamCount > 0) { // Copy the appropriate values into each of the function's formal parameters. func.mParam[0].var->Assign((char *)awParam); // Assign parameter #1: wParam if (func.mParamCount > 1) // Assign parameter #2: lParam { // v1.0.38.01: LPARAM is now written out as a DWORD because the majority of system messages // use LPARAM as a pointer or other unsigned value. This shouldn't affect most scripts because // of the way ATOI64() and ATOU() wrap a negative number back into the unsigned domain for // commands such as PostMessage/SendMessage. func.mParam[1].var->Assign((char *)alParam); } } // v1.0.38.04: Below was added to maximize responsiveness to incoming messages. The reasoning // is similar to why the same thing is done in MsgSleep() prior to its launch of a thread, so see // MsgSleep for more comments: g_script.mLastScriptRest = g_script.mLastPeekTime = GetTickCount(); char *return_value; func.Call(return_value); // Call the UDF. // Fix for v1.0.47: Must handle return_value BEFORE calling FreeAndRestoreFunctionVars() because return_value // might be the contents of one of the function's local variables (which are about to be free'd). /* bool block_further_processing = *return_value; // No need to check the following because they're implied for *return_value!=0: result != EARLY_EXIT && result != FAIL; if (block_further_processing) aMsgReply = (LPARAM)ATOI64(return_value); // Use 64-bit in case it's an unsigned number greater than 0x7FFFFFFF, in which case this allows it to wrap around to a negative. //else leave aMsgReply uninitialized because we'll be returning false later below, which tells our caller // to ignore aMsgReply. */ Var::FreeAndRestoreFunctionVars(func, var_backup, var_backup_count); ResumeUnderlyingThread(&global_saved, ErrorLevel_saved, true); return 0 ; // block_further_processing; // If false, the caller will ignore aMsgReply and process this message normally. If true, aMsgReply contains the reply the caller should immediately send for this message. }
[ [ [ 1, 233 ] ] ]
d28c940476919abc0a2274045be0dae892179b6e
aa7df9e17e92eaa856ee823e76e154287f4068d4
/diagramtextitem.h
3538d39775b8bedd708bd09427dbc91b19cc7496
[]
no_license
andrey013/petri
9c5d5175c74c9b3fc040d1d263b6807ff48bfc18
de6c57e0e0f273b087a41cd7c7b433b475b591e1
refs/heads/master
2021-01-01T19:02:39.404438
2011-06-19T17:44:08
2011-06-19T17:44:08
1,920,063
0
0
null
null
null
null
UTF-8
C++
false
false
802
h
#ifndef DIAGRAMTEXTITEM_H #define DIAGRAMTEXTITEM_H #include <QGraphicsTextItem> #include <QPen> QT_BEGIN_NAMESPACE class QFocusEvent; class QGraphicsItem; class QGraphicsScene; class QGraphicsSceneMouseEvent; QT_END_NAMESPACE class DiagramTextItem : public QGraphicsTextItem { Q_OBJECT public: enum { Type = UserType + 3 }; DiagramTextItem(QGraphicsItem *parent = 0, QGraphicsScene *scene = 0); int type() const { return Type; } signals: void lostFocus(DiagramTextItem *item); void selectedChange(QGraphicsItem *item); protected: QVariant itemChange(GraphicsItemChange change, const QVariant &value); void focusOutEvent(QFocusEvent *event); void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); }; #endif
[ [ [ 1, 36 ] ] ]
c723ba366d6fc94c4944ffaec02b8e95bea18f78
fb8a3d68c676c977b9b6d3389debd785c2f25634
/Graphics/Library/Source/Graphics.cpp
34b61af4224d2c02f9ce06637f782a8e1e4f189b
[]
no_license
skevy/CSC-350-Assignment2
ef1a1e5fae8c9b9ab4ca2b97390974751ad1dedb
98811d2cbbc221af9cc9aa601a990e7969920f7e
refs/heads/master
2021-01-01T20:35:26.246966
2011-02-17T01:57:03
2011-02-17T01:57:03
1,376,632
0
0
null
null
null
null
UTF-8
C++
false
false
7,413
cpp
//***************************************************************************// // HabuGraphics Base Class Implementation // // Created Jan 01, 2005 // By: Jeremy M Miller // // Copyright (c) 2005-2010 Jeremy M Miller. All rights reserved. // This source code module, and all information, data, and algorithms // associated with it, are part of BlueHabu technology (tm). // //***************************************************************************// // System Includes #include <assert.h> // 3rd Party Includes #include <GL\glew.h> // Must be called before GL.h // Platform Includes #include <Windows.h> #include <GL\GL.h> #include <GL\GLU.h> // Local Includes #include "Graphics.hpp" GLfloat Zmin = 0.100000f; GLfloat Zmax = 100.0f; GLfloat FOV = 49.1343395f; extern float fDT; //DEFINES #define CLEAR_COLOR 0xFFEEEEEE namespace Victor { HDC Graphics::smhDeviceContext = NULL; HGLRC Graphics::smhRenderingContext = NULL; HWND Graphics::smhWindow = NULL; HINSTANCE Graphics::smhInstance = NULL; // Constructor Graphics::Graphics(bool bWindowed, string filename) { this->scene = new Scene("monkey", filename); this->mulWindowHeight = DEFAULT_WINDOW_HEIGHT; this->mulWindowWidth = DEFAULT_WINDOW_WIDTH; } // Destructor Graphics::~Graphics() { } long Graphics::Initialize(HWND hWindow, unsigned long ulWidth, unsigned long ulHeight) { // Create a data member to hold the result of this method. In this method's // case it will hold any error codes. By default set to 1 to signal no error. long lResultCode = 1; smhWindow = hWindow; static PIXELFORMATDESCRIPTOR pfd= { // pfd Tells Windows How We Want Things To Be sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; GLuint PixelFormat; if(!(smhDeviceContext = GetDC(hWindow))) { lResultCode = -1; smhDeviceContext = NULL; } // Did Windows Find A Matching Pixel Format? if(lResultCode > 0 && !(PixelFormat = ChoosePixelFormat(smhDeviceContext, &pfd))) { lResultCode = -1; } // Are We Able To Set The Pixel Format? if(lResultCode > 0 && !SetPixelFormat(smhDeviceContext, PixelFormat, &pfd)) { lResultCode = -1; } // Are We Able To Get A Rendering Context? if(lResultCode > 0 && !(smhRenderingContext = wglCreateContext(smhDeviceContext))) { lResultCode = -1; } // Try To Activate The Rendering Context if(lResultCode > 0 && !wglMakeCurrent(smhDeviceContext, smhRenderingContext)) { lResultCode = -1; } // Check Required Extensions GLenum err = glewInit(); if(err == GLEW_OK) { glewGetString(GLEW_VERSION); if(GLEW_ARB_vertex_buffer_object) { glShadeModel(GL_SMOOTH); // Enable Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing //glEnable ( GL_LIGHTING ) ; glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); } else { lResultCode = -1; } } else { glewGetErrorString(err); lResultCode = -1; } //Init viewport and perspective glViewport(0,0,DEFAULT_WINDOW_WIDTH,DEFAULT_WINDOW_HEIGHT); this->scene->setAspectRatio((float)DEFAULT_WINDOW_WIDTH / DEFAULT_WINDOW_HEIGHT); this->scene->load(); return lResultCode; } // End of long Graphics::Initialize(HWND hWindow) long Graphics::Uninitialize() { long lReturnCode = 1; if(smhRenderingContext) { // Do We Have A Rendering Context? if(!wglMakeCurrent(NULL,NULL)) { // Are We Able To Release The DC And RC Contexts? MessageBox(NULL,"Release Of DC And RC Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); lReturnCode = -1; } if(!wglDeleteContext(smhRenderingContext)) { // Are We Able To Delete The RC? MessageBox(NULL,"Release Rendering Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); lReturnCode = -1; } smhRenderingContext = NULL; // Set RC To NULL } if(smhDeviceContext && !ReleaseDC(smhWindow, smhDeviceContext)) { // Are We Able To Release The DC MessageBox(NULL,"Release Device Context Failed.","SHUTDOWN ERROR",MB_OK | MB_ICONINFORMATION); smhDeviceContext = NULL; // Set DC To NULL lReturnCode = -1; } return lReturnCode; } // End of long Graphics::Uninitialize() void Graphics::WindowDimensions(unsigned long ulWidth, unsigned long ulHeight) { this->mulWindowWidth = ulWidth; this->mulWindowHeight = ulHeight; } unsigned long Graphics::WindowWidth() const { return this->mulWindowWidth; } unsigned long Graphics::WindowHeight() const { return this->mulWindowHeight; } Scene* Graphics::getActiveScene() { return this->scene; } // Base::RenderScene() clears the depth and color buffer and starts // rendering the scene int Graphics::Render(float fDT) { static float runtimesec=0.0f; float syncfpsrate= 1.0f/60.0f; runtimesec+=fDT; if(runtimesec>syncfpsrate){ this->scene->render(); //Render the scene //adjust our runtimesec. Remember that by doing this, we tighten //the sync and make overflow impossible. runtimesec-=syncfpsrate; }//big sync if statement ends return 0; } // Base::SwapBuffers void Graphics::SwapBuffer() { SwapBuffers(smhDeviceContext); } }
[ [ [ 1, 199 ] ] ]
72c7071a5767fe59755a545d12958b9368aa5184
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/WORLDSERVER/DPSrvrLux.cpp
e46b044c5fc8b4537de778f88ecc761d40442d34
[]
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
5,995
cpp
#include "stdafx.h" #include "defineText.h" #include "defineItem.h" #include "defineSkill.h" #include "defineObj.h" #include "dpcoreclient.h" #include "dpdatabaseclient.h" #include "dpsrvr.h" #include "user.h" #include "worldmng.h" #include "misc.h" #include "guild.h" extern CGuildMng g_GuildMng; #include "..\_Common\Ship.h" #include "..\_aiinterface\AIPet.h" #include "Party.h" extern CPartyMng g_PartyMng; extern CUserMng g_UserMng; extern CDPDatabaseClient g_dpDBClient; extern CDPCoreClient g_DPCoreClient; extern CWorldMng g_WorldMng; #include "..\_Network\ErrorCode.h" void CDPSrvr::OnUseSkill( CAr & ar, DPID dpidCache, DPID dpidUser, LPBYTE lpBuf, u_long uBufSize ) { WORD wType; // 직업스킬이냐, 라이선스스킬이냐 구분하는 변수 - 2005.10.04 의미없음 WORD wId; OBJID objid; int nUseType = 0; ar >> wType >> wId >> objid >> nUseType; #if __VER >= 8 // __S8_PK BOOL bControl; ar >> bControl; #endif // __VER >= 8 // __S8_PK int nIdx = wId; if( nIdx < 0 || nIdx >= MAX_SKILL_JOB ) return; wType = 0; CUser* pUser = g_UserMng.GetUser( dpidCache, dpidUser ); if( IsValidObj( (CObj*)pUser ) ) { if( pUser->m_vtInfo.VendorIsVendor() ) return; #ifdef __S_SERVER_UNIFY if( pUser->m_bAllAction == FALSE ) return; #endif // __S_SERVER_UNIFY LPSKILL pSkill = pUser->GetSkill( wType, nIdx ); if( !pSkill ) return; if( pSkill->dwSkill == DWORD(-1) ) return; ItemProp* pSkillProp = prj.GetSkillProp( pSkill->dwSkill ); if( !pSkillProp ) return; #ifdef __SKILL0517 DWORD dwLevel = pUser->GetSkillLevel( pSkill ); #else // __SKILL0517 DWORD dwLevel = pSkill->dwLevel; #endif // __SKILL0517 if( dwLevel == 0 || dwLevel > pSkillProp->dwExpertMax ) return; #if __VER >= 8 // __S8_PK BOOL fSuccess = pUser->DoUseSkill( wType, nIdx, objid, (SKILLUSETYPE)nUseType, bControl ); #else // __VER >= 8 // __S8_PK BOOL fSuccess = pUser->DoUseSkill( wType, nIdx, objid, (SKILLUSETYPE)nUseType ); #endif // __VER >= 8 // __S8_PK if( fSuccess == TRUE ) // 스킬사용에 성공했고 { if( nUseType == SUT_QUEUESTART ) // 스킬큐로 실행하라고 한거였다. { pUser->m_playTaskBar.m_nUsedSkillQueue = 0; // 스킬큐 실행중인 표시 남김. } } if( TRUE == fSuccess ) { } else // 서버에서 UseSkill을 실패하면 그것을 그 클라한테 알려줘야 한다. { TRACE( "Fail %d, ", nIdx ); pUser->AddHdr( GETID( pUser ), SNAPSHOTTYPE_CLEAR_USESKILL ); } } } void CDPSrvr::OnDoCollect( CAr & ar, DPID dpidCache, DPID dpidUser, LPBYTE lpBuf, u_long uBufSize ) { OBJID idTarget; CUser* pUser = g_UserMng.GetUser( dpidCache, dpidUser ); if( IsValidObj( pUser ) ) { ar >> idTarget; g_UserMng.AddDoCollect( pUser, idTarget ); CMover *pTarget = prj.GetMover( idTarget ); if( IsValidObj( pTarget ) ) pUser->DoCollect( pTarget ); } } // 클라이언트로 부터 받은 에러코드를 로그로 남긴다. void CDPSrvr::OnError( CAr & ar, DPID dpidCache, DPID dpidUser, LPBYTE lpBuf, u_long uBufSize) { int nCode, nData; CUser* pUser = g_UserMng.GetUser( dpidCache, dpidUser ); if( IsValidObj( pUser ) ) { ar >> nCode >> nData; switch( nCode ) { case FE_GENERAL: break; case FE_INVALIDATTACKER: // 클라이언트에서 어태커가 invalid한경우(유령몹 버그) { #ifndef _DEBUG OBJID idAttacker = (OBJID)nData; CMover *pAttacker = prj.GetMover( idAttacker ); if( IsValidObj(pAttacker) ) { Error( "2OnError : FE_INVALIDATTACKER 피해자:%s(%f,%f,%f), 공격자:%s(%f,%f,%f)", pUser->GetName(), pUser->GetPos().x, pUser->GetPos().y, pUser->GetPos().z, pAttacker->GetName(), pAttacker->GetPos().x, pAttacker->GetPos().y, pAttacker->GetPos().z ); pUser->AddCorrReq( pAttacker ); // 요청한 클라에게 인밸리드한 어태커를 다시 보내줌. } else Error( "2OnError : FE_INVALIDATTACKER 피해자:%s(%f,%f,%f) 이런젠장 서버에서도 pAttacker는 Invalid다. 0x%08x", pUser->GetName(), pUser->GetPos().x, pUser->GetPos().y, pUser->GetPos().z, nData ); #endif // not debug // case NEXT: } break; } } else Error( "CDPSrvr::OnError pUser - Invalid %d %d", dpidCache, dpidUser ); } void CDPSrvr::OnShipActMsg( CAr & ar, DPID dpidCache, DPID dpidUser, LPBYTE lpBuf, u_long uBufSize ) { DWORD dwMsg; OBJID idShip; int nParam1, nParam2; ar >> dwMsg >> nParam1 >> nParam2 >> idShip; CUser* pUser = g_UserMng.GetUser( dpidCache, dpidUser ); if( IsValidObj( pUser ) ) { if( IsInvalidObj( pUser->GetIAObjLink() ) ) return; if( idShip != pUser->GetIAObjLink()->GetId() ) { Error( "OnShipActMsg : 클라에서 보내온 아이디(%d)와 서버에서의 아이디(%d)가 다르다", idShip, pUser->GetIAObjLink()->GetId() ); return; } CShip *pShip = prj.GetShip( idShip ); if( IsValidObj( pShip ) ) { pShip->SendActMsg( (OBJMSG)dwMsg, nParam1, nParam2, 0 ); // g_DPCoreClient.SendShipActMsg( pUser, dwMsg, nParam1, nParam2 ); g_UserMng.AddShipActMsg( pUser, pShip, dwMsg, nParam1, nParam2 ); } } } void CDPSrvr::OnLocalPosFromIA( CAr & ar, DPID dpidCache, DPID dpidUser, LPBYTE lpBuf, u_long uBufSize ) { D3DXVECTOR3 vLocal; OBJID idIA; ar >> vLocal >> idIA; CUser* pUser = g_UserMng.GetUser( dpidCache, dpidUser ); if( IsValidObj( pUser ) ) { // 클라이언트로부터 착지한지점의 상대좌표를 받았다. // 이 좌표를 서버에서 동기화 하자 CShip *pIA = prj.GetShip( idIA ); if( IsInvalidObj( pIA ) ) return; D3DXVECTOR3 vPos = pIA->GetPos() + vLocal; // 서버상에서의 IA오브젝트와 클라에서 받은 로컬좌표를 합쳐서 새로운 좌표생성 pUser->SetPos( vPos ); pUser->SetIAObjLink( pIA ); } }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278", "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 99 ], [ 101, 102 ], [ 116, 116 ], [ 118, 203 ] ], [ [ 100, 100 ], [ 103, 115 ], [ 117, 117 ] ] ]
7751ce9363a1e39001ad45377fb92788fcedb481
78fb44a7f01825c19d61e9eaaa3e558ce80dcdf5
/guidriverMyGUIOgre/include/guceMyGUIOgre_CFormBackendImp.h
0991882119751e58e628a89b58c81d9f97a0c047
[]
no_license
LiberatorUSA/GUCE
a2d193e78d91657ccc4eab50fab06de31bc38021
a4d6aa5421f8799cedc7c9f7dc496df4327ac37f
refs/heads/master
2021-01-02T08:14:08.541536
2011-09-08T03:00:46
2011-09-08T03:00:46
41,840,441
0
0
null
null
null
null
UTF-8
C++
false
false
5,718
h
/* * guceMyGUIOgre: glue module for the MyGUI+Ogre GUI backend * Copyright (C) 2002 - 2008. Dinand Vanvelzen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef GUCE_MYGUIOGRE_CFORMBACKENDIMP_H #define GUCE_MYGUIOGRE_CFORMBACKENDIMP_H /*-------------------------------------------------------------------------// // // // INCLUDES // // // //-------------------------------------------------------------------------*/ #include <map> #include <MyGUI.h> #ifndef GUCEF_GUI_CFORMBACKEND_H #include "gucefGUI_CFormBackend.h" #define GUCEF_GUI_CFORMBACKEND_H #endif /* GUCEF_GUI_CFORMBACKEND_H ? */ #ifndef GUCE_CORE_CIOACCESSARCHIVE_H #include "CIOAccessArchive.h" #define GUCE_CORE_CIOACCESSARCHIVE_H #endif /* GUCE_CORE_CIOACCESSARCHIVE_H ? */ #ifndef GUCE_MYGUIOGRE_CWIDGETIMP_H #include "guceMyGUIOgre_CWidgetImp.h" #define GUCE_MYGUIOGRE_CWIDGETIMP_H #endif /* GUCE_MYGUIOGRE_CWIDGETIMP_H ? */ #ifndef GUCE_MYGUIOGRE_MACROS_H #include "guceMyGUIOgre_macros.h" /* often used guceMYGUIOGRE macros */ #define GUCE_MYGUIOGRE_MACROS_H #endif /* GUCE_MYGUIOGRE_MACROS_H ? */ /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ namespace GUCE { namespace MYGUIOGRE { /*-------------------------------------------------------------------------// // // // CLASSES // // // //-------------------------------------------------------------------------*/ /** * Class used by the form class to abstract from the backend. * This allows you to descend from the CForm class as you wish without having * to create a matching backend implementation for every form type. */ class GUCE_MYGUIOGRE_EXPORT_CPP CFormBackendImp : public GUCEF::GUI::CFormBackend { public: typedef std::map< CString, GUCEF::GUI::CWidget* > TWidgetMap; CFormBackendImp( void ); virtual ~CFormBackendImp(); virtual bool LoadLayout( const GUCEF::CORE::CString& layoutStoragePath ); virtual bool SaveLayout( const GUCEF::CORE::CString& layoutStoragePath ); virtual bool LoadLayout( GUCEF::CORE::CIOAccess& layoutStorage ); virtual bool SaveLayout( GUCEF::CORE::CIOAccess& layoutStorage ); virtual GUCEF::GUI::CWidget* GetRootWidget( void ); virtual const GUCEF::GUI::CWidget* GetRootWidget( void ) const; virtual GUCEF::GUI::CWidget* GetWidget( const CString& widgetName ); virtual void GetWidgetVector( const CString& widgetName , TWidgetVector& widgetVector ); private: CFormBackendImp( const CFormBackendImp& src ); CFormBackendImp& operator=( const CFormBackendImp& other ); GUCEF::GUI::CWidget* CreateAndHookWrapperForWindow( MyGUI::Widget* window ); void WrapAndHookChildWindows( MyGUI::Widget* window ); private: TWidgetMap m_widgetMap; GUCEF::GUI::CWidget* m_rootWindow; CString m_widgetNamePrefix; CString m_resourceGroupName; CORE::CIOAccessArchive* m_dummyArchive; }; /*-------------------------------------------------------------------------// // // // NAMESPACE // // // //-------------------------------------------------------------------------*/ }; /* namespace MYGUIOGRE */ }; /* namespace GUCE */ /*-------------------------------------------------------------------------*/ #endif /* GUCE_MYGUIOGRE_CFORMBACKENDIMP_H ? */ /*-------------------------------------------------------------------------// // // // Info & Changes // // // //-------------------------------------------------------------------------// - 18-08-2007 : - Dinand: Initial implementation -----------------------------------------------------------------------------*/
[ [ [ 1, 142 ] ] ]
a2bf5472e17f66d54e7350656b2f496e02186bf2
c497f6d85bdbcbb21e93ae701c5570f16370f0ae
/Sync/Lets_try_all_engine/backup/trrr/SatMedtypes.hpp
51fb799f0f296f40945ff2e39c52a6403f761f7d
[]
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
973
hpp
#include "DayTime.hpp" #include "Position.hpp" #include "satdbtypes.hpp" #include "EngineFramework.hpp" #include "SatDgen.hpp" #include "SatDb.hpp" #ifndef SATMDEOSTRUCT #define SATMDEOSTRUCT using namespace gpstk; typedef struct { //std::vector<satDb_ostruct> *satDb_ref; SatDgen *satDgen; SatDb *satDb; Position rxXvt; DayTime measTime; }satMDE_actIstruct; typedef struct { double minElev; }satMDE_psvIstruct; typedef struct { SatID prn; satDgen_opDataPort dataNmeas; double rangeRate; double carrierDopplerL1 ; double codeDopplerCaL1; double carrierDopplerL2; double codeDopplerCaL2; double carrierDopplerL5 ; double codeDopplerPyL5; bool measurementHealth; }satMDE_ostruct; typedef struct { SatID prn; double range; }satMDE_range; struct phaseData { // Default constructor initializing the data in the structure phaseData() : previousPhase(0.0) {}; double previousPhase; }; #endif
[ "priyankguddu@6c0848c6-feae-43ef-b685-015bb26c21a7" ]
[ [ [ 1, 60 ] ] ]
730f5f077fd8a85acec717b30552bdb7831d2a86
83c85d3cae31e27285ca07e192cc9bbad8081736
/loger/Loger.cpp
469ed809dd87321a7da9f4466a8c7e40a4550321
[]
no_license
yjfcool/poitool
0768d7299a453335cbd1ae1045440285b3295801
1068837ab32dbb9c6df18bbab1ea64bc70942cbf
refs/heads/master
2016-09-05T11:37:18.585724
2010-04-09T06:16:14
2010-04-09T06:16:14
42,576,080
0
0
null
null
null
null
UTF-8
C++
false
false
79
cpp
#include "Loger.h" CLoger::CLoger() { } CLoger::~CLoger() { }
[ "dulton@370d939e-410d-02cf-1e1d-9a5f4ca5de21" ]
[ [ [ 1, 12 ] ] ]
cb492d367298dfd9f6655673b9030410a1a2b9ad
d9f1cc8e697ae4d1c74261ae6377063edd1c53f8
/src/graphics/ColorModifierManager.cpp
a7ece5dbf9d31c48c5ab33c5acec2394f54b06ec
[]
no_license
commel/opencombat2005
344b3c00aaa7d1ec4af817e5ef9b5b036f2e4022
d72fc2b0be12367af34d13c47064f31d55b7a8e0
refs/heads/master
2023-05-19T05:18:54.728752
2005-12-01T05:11:44
2005-12-01T05:11:44
375,630,282
0
0
null
null
null
null
UTF-8
C++
false
false
5,661
cpp
#include "ColorModifierManager.h" #import <msxml4.dll> raw_interfaces_only using namespace MSXML2; #include <misc\SAXContentHandlerImpl.h> #include <misc\Stack.h> #include <stdio.h> #include <direct.h> #include <misc\Array.h> // Instantiate the global color modifier ColorModifiers g_ColorModifiers[MAX_COLOR_MODIFIERS]; int g_NumColorModifiers = 0; ColorModifierManager::ColorModifierManager() { } ColorModifierManager::~ColorModifierManager() { // XXX/GWS: Todo } #define PSF_COLOR_MODIFIER 0x01 enum ParserState { PS_UNKNOWN, PS_NAME, PS_RED, PS_GREEN, PS_BLUE, PS_COLOR_MODIFIER, PS_BODY, PS_LEGS, PS_HEAD, PS_BELT, PS_BOOTS, PS_WEAPON }; struct AttrState { wchar_t *Name; ParserState State; }; class StackState { public: StackState(ParserState s) { parserState = s; } virtual ~StackState() {} ParserState parserState; }; static AttrState _states[] = { { L"Name", PS_NAME}, { L"Red", PS_RED}, { L"Green", PS_GREEN}, { L"Blue", PS_BLUE}, { L"ColorModifier", PS_COLOR_MODIFIER}, { L"Body", PS_BODY}, { L"Legs", PS_LEGS}, { L"Head", PS_HEAD}, { L"Belt", PS_BELT}, { L"Boots", PS_BOOTS}, { L"Weapon", PS_WEAPON}, { NULL, PS_UNKNOWN } /* Must be last */ }; class ColorModifierContentHandler : public SAXContentHandlerImpl { public: ColorModifierContentHandler() : SAXContentHandlerImpl() { idnt = 0; _parserFlags = 0; } virtual ~ColorModifierContentHandler() {} virtual HRESULT STDMETHODCALLTYPE startElement( unsigned short __RPC_FAR *pwchNamespaceUri, int cchNamespaceUri, unsigned short __RPC_FAR *pwchLocalName, int cchLocalName, unsigned short __RPC_FAR *pwchQName, int cchQName, ISAXAttributes __RPC_FAR *pAttributes) { UNREFERENCED_PARAMETER(cchNamespaceUri); UNREFERENCED_PARAMETER(pwchNamespaceUri); UNREFERENCED_PARAMETER(cchLocalName); UNREFERENCED_PARAMETER(pwchQName); UNREFERENCED_PARAMETER(cchQName); UNREFERENCED_PARAMETER(pAttributes); int idx = 0; while(_states[idx].Name != NULL) { if(wcsicmp((wchar_t*)_states[idx].Name, (wchar_t*)pwchLocalName) == 0) { _stack.Push(new StackState(_states[idx].State)); switch(_states[idx].State) { case PS_COLOR_MODIFIER: _currentModifierIdx = g_NumColorModifiers; _parserFlags ^= PSF_COLOR_MODIFIER; break; case PS_BODY: _currentModifier = &(g_ColorModifiers[g_NumColorModifiers].Body); break; case PS_LEGS: _currentModifier = &(g_ColorModifiers[g_NumColorModifiers].Legs); break; case PS_HEAD: _currentModifier = &(g_ColorModifiers[g_NumColorModifiers].Head); break; case PS_BELT: _currentModifier = &(g_ColorModifiers[g_NumColorModifiers].Belt); break; case PS_BOOTS: _currentModifier = &(g_ColorModifiers[g_NumColorModifiers].Boots); break; case PS_WEAPON: _currentModifier = &(g_ColorModifiers[g_NumColorModifiers].Weapon); break; } return S_OK; } ++idx; } _stack.Push(new StackState(PS_UNKNOWN)); return S_OK; } virtual HRESULT STDMETHODCALLTYPE endElement( unsigned short __RPC_FAR *pwchNamespaceUri, int cchNamespaceUri, unsigned short __RPC_FAR *pwchLocalName, int cchLocalName, unsigned short __RPC_FAR *pwchQName, int cchQName) { UNREFERENCED_PARAMETER(cchNamespaceUri); UNREFERENCED_PARAMETER(pwchNamespaceUri); UNREFERENCED_PARAMETER(cchLocalName); UNREFERENCED_PARAMETER(pwchQName); UNREFERENCED_PARAMETER(cchQName); int idx = 0; while(_states[idx].Name != NULL) { if(wcsicmp((wchar_t*)_states[idx].Name, (wchar_t*)pwchLocalName) == 0) { switch(_states[idx].State) { case PS_COLOR_MODIFIER: g_NumColorModifiers++; _parserFlags ^= PSF_COLOR_MODIFIER; break; } } ++idx; } delete _stack.Pop(); return S_OK; } virtual HRESULT STDMETHODCALLTYPE characters(unsigned short *pwchChars, int cchChars) { // Get the current parser state StackState *s = (StackState *) _stack.Peek(); switch(s->parserState) { case PS_NAME: { char fileName[256]; wcstombs(fileName, (wchar_t*)pwchChars, cchChars); fileName[cchChars] = '\0'; strcpy(g_ColorModifiers[g_NumColorModifiers].Name, fileName); } break; case PS_RED: _currentModifier->Red = 8*ToInt(pwchChars, cchChars); break; case PS_GREEN: _currentModifier->Green = 8*ToInt(pwchChars, cchChars); break; case PS_BLUE: _currentModifier->Blue = 8*ToInt(pwchChars, cchChars); break; } return S_OK; } virtual HRESULT STDMETHODCALLTYPE startDocument() { return S_OK; } private: int idnt; ColorModifier *_currentModifier; int _currentModifierIdx; Stack<StackState> _stack; unsigned int _parserFlags; }; void ColorModifierManager::Load(char *configFile) { // Create the reader ISAXXMLReader* pRdr = NULL; HRESULT hr = CoCreateInstance(__uuidof(SAXXMLReader), NULL, CLSCTX_ALL, __uuidof(ISAXXMLReader), (void **)&pRdr); g_NumColorModifiers = 0; if(!FAILED(hr)) { ColorModifierContentHandler *pMc = new ColorModifierContentHandler(); hr = pRdr->putContentHandler(pMc); static wchar_t URL[1000]; mbstowcs( URL, configFile, 999 ); wprintf(L"\nParsing document: %s\n", URL); hr = pRdr->parseURL((unsigned short *)URL); printf("\nParse result code: %08x\n\n",hr); pRdr->Release(); } else { printf("\nError %08X\n\n", hr); } }
[ "opencombat" ]
[ [ [ 1, 238 ] ] ]
ecf98fa2bcd84107414d30bf96d1065fecf8e91d
a84b013cd995870071589cefe0ab060ff3105f35
/webdriver/branches/android/jobbie/src/cpp/InternetExplorerDriver/InternetExplorerDriver.cpp
0e03950113b5e43ef79c406975fcabd08d9f9e90
[ "Apache-2.0" ]
permissive
vdt/selenium
137bcad58b7184690b8785859d77da0cd9f745a0
30e5e122b068aadf31bcd010d00a58afd8075217
refs/heads/master
2020-12-27T21:35:06.461381
2009-08-18T15:56:32
2009-08-18T15:56:32
13,650,409
1
0
null
null
null
null
UTF-8
C++
false
false
13,846
cpp
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Portions copyright 2007 ThoughtWorks, Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "StdAfx.h" #include "utils.h" #include "InternalCustomMessage.h" #include "jsxpath.h" #include "errorcodes.h" using namespace std; IeThread* g_IE_Thread = NULL; InternetExplorerDriver::InternetExplorerDriver() : p_IEthread(NULL) { if (NULL == gSafe) { gSafe = new safeIO(); } SCOPETRACER speed = 0; p_IEthread = ThreadFactory(); p_IEthread->pIED = this; ResetEvent(p_IEthread->sync_LaunchIE); p_IEthread->PostThreadMessageW(_WD_START, 0, 0); WaitForSingleObject(p_IEthread->sync_LaunchIE, 60000); closeCalled = false; } InternetExplorerDriver::InternetExplorerDriver(InternetExplorerDriver *other) { ScopeTracer D(("Constructor_from_other")); this->p_IEthread = other->p_IEthread; } InternetExplorerDriver::~InternetExplorerDriver() { SCOPETRACER close(); } IeThread* InternetExplorerDriver::ThreadFactory() { SCOPETRACER if(!g_IE_Thread) { // Spawning the GUI worker thread, which will instantiate the ActiveX component g_IE_Thread = p_IEthread = new IeThread(); p_IEthread->hThread = CreateThread (NULL, 0, (DWORD (__stdcall *)(LPVOID)) (IeThread::runProcessStatic), (void *)p_IEthread, 0, NULL); p_IEthread->pIED = this; ResetEvent(p_IEthread->sync_LaunchThread); ResumeThread(p_IEthread->hThread); WaitForSingleObject(p_IEthread->sync_LaunchThread, 60000); } return g_IE_Thread; } void InternetExplorerDriver::close() { SCOPETRACER if (closeCalled) return; closeCalled = true; SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_QUIT_IE,) } bool InternetExplorerDriver::getVisible() { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_GETVISIBLE,) return data.output_bool_; } void InternetExplorerDriver::setVisible(bool isVisible) { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_SETVISIBLE, (int)isVisible) } LPCWSTR InternetExplorerDriver::getCurrentUrl() { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_GETCURRENTURL,) return data.output_string_.c_str(); } LPCWSTR InternetExplorerDriver::getPageSource() { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_GETPAGESOURCE,) return data.output_string_.c_str(); } LPCWSTR InternetExplorerDriver::getTitle() { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_GETTITLE,) return data.output_string_.c_str(); } void InternetExplorerDriver::get(const wchar_t *url) { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_GETURL, url) } void InternetExplorerDriver::goForward() { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_GOFORWARD,) } void InternetExplorerDriver::goBack() { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_GOBACK,) } std::wstring InternetExplorerDriver::getHandle() { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_GET_HANDLE,); return data.output_string_.c_str(); } ElementWrapper* InternetExplorerDriver::getActiveElement() { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_GETACTIVEELEMENT,) return new ElementWrapper(this, data.output_html_element_); } int InternetExplorerDriver::selectElementByXPath(IHTMLElement *pElem, const wchar_t *input_string, ElementWrapper** element) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTBYXPATH) if (data.error_code != SUCCESS) { return data.error_code; }; *element = new ElementWrapper(this, data.output_html_element_); return SUCCESS; } std::vector<ElementWrapper*>* InternetExplorerDriver::selectElementsByXPath(IHTMLElement *pElem, const wchar_t *input_string) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTSBYXPATH) std::vector<ElementWrapper*> *toReturn = new std::vector<ElementWrapper*>(); if(data.output_long_) {std::wstring Err(L"Cannot find elements by Xpath"); throw Err;} std::vector<IHTMLElement*>& allElems = data.output_list_html_element_; std::vector<IHTMLElement*>::const_iterator cur, end = allElems.end(); for(cur = allElems.begin();cur < end; cur++) { IHTMLElement* elem = *cur; toReturn->push_back(new ElementWrapper(this, elem)); } return toReturn; } int InternetExplorerDriver::selectElementById(IHTMLElement *pElem, const wchar_t *input_string, ElementWrapper** element) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTBYID) if (data.error_code != SUCCESS) { return data.error_code; } *element = new ElementWrapper(this, data.output_html_element_); return SUCCESS; } std::vector<ElementWrapper*>* InternetExplorerDriver::selectElementsById(IHTMLElement *pElem, const wchar_t *input_string) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTSBYID) if(1 == data.output_long_) {std::wstring Err(L"Cannot find elements by Id"); throw Err;} std::vector<ElementWrapper*> *toReturn = new std::vector<ElementWrapper*>(); std::vector<IHTMLElement*>& allElems = data.output_list_html_element_; std::vector<IHTMLElement*>::const_iterator cur, end = allElems.end(); for(cur = allElems.begin();cur < end; cur++) { IHTMLElement* elem = *cur; toReturn->push_back(new ElementWrapper(this, elem)); } return toReturn; } int InternetExplorerDriver::selectElementByLink(IHTMLElement *pElem, const wchar_t *input_string, ElementWrapper** element) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTBYLINK) if (data.error_code == SUCCESS) { *element = new ElementWrapper(this, data.output_html_element_); } return data.error_code; } std::vector<ElementWrapper*>* InternetExplorerDriver::selectElementsByPartialLink(IHTMLElement *pElem, const wchar_t *input_string) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTSBYPARTIALLINK) if(1 == data.output_long_) {std::wstring Err(L"Cannot find elements by Link"); throw Err;} std::vector<ElementWrapper*> *toReturn = new std::vector<ElementWrapper*>(); std::vector<IHTMLElement*>& allElems = data.output_list_html_element_; std::vector<IHTMLElement*>::const_iterator cur, end = allElems.end(); for(cur = allElems.begin();cur < end; cur++) { IHTMLElement* elem = *cur; toReturn->push_back(new ElementWrapper(this, elem)); } return toReturn; } int InternetExplorerDriver::selectElementByPartialLink(IHTMLElement *pElem, const wchar_t *input_string, ElementWrapper** element) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTBYPARTIALLINK) if (data.error_code == SUCCESS) { *element = new ElementWrapper(this, data.output_html_element_); } return data.error_code; } std::vector<ElementWrapper*>* InternetExplorerDriver::selectElementsByLink(IHTMLElement *pElem, const wchar_t *input_string) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTSBYLINK) if(1 == data.output_long_) {std::wstring Err(L"Cannot find elements by Link"); throw Err;} std::vector<ElementWrapper*> *toReturn = new std::vector<ElementWrapper*>(); std::vector<IHTMLElement*>& allElems = data.output_list_html_element_; std::vector<IHTMLElement*>::const_iterator cur, end = allElems.end(); for(cur = allElems.begin();cur < end; cur++) { IHTMLElement* elem = *cur; toReturn->push_back(new ElementWrapper(this, elem)); } return toReturn; } int InternetExplorerDriver::selectElementByName(IHTMLElement *pElem, const wchar_t *input_string, ElementWrapper** element) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTBYNAME) if (data.error_code == SUCCESS) { *element = new ElementWrapper(this, data.output_html_element_); } return data.error_code; } std::vector<ElementWrapper*>* InternetExplorerDriver::selectElementsByName(IHTMLElement *pElem, const wchar_t *input_string) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTSBYNAME) if(1 == data.output_long_) {std::wstring Err(L"Cannot find elements by Name"); throw Err;} std::vector<ElementWrapper*> *toReturn = new std::vector<ElementWrapper*>(); std::vector<IHTMLElement*>& allElems = data.output_list_html_element_; std::vector<IHTMLElement*>::const_iterator cur, end = allElems.end(); for(cur = allElems.begin();cur < end; cur++) { IHTMLElement* elem = *cur; toReturn->push_back(new ElementWrapper(this, elem)); } return toReturn; } int InternetExplorerDriver::selectElementByTagName(IHTMLElement *pElem, const wchar_t *input_string, ElementWrapper** element) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTBYTAGNAME) if (data.error_code == SUCCESS) { *element = new ElementWrapper(this, data.output_html_element_); } return data.error_code; } std::vector<ElementWrapper*>* InternetExplorerDriver::selectElementsByTagName(IHTMLElement *pElem, const wchar_t *input_string) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTSBYTAGNAME) if(1 == data.output_long_) {std::wstring Err(L"Cannot find elements by tag name"); throw Err;} std::vector<ElementWrapper*> *toReturn = new std::vector<ElementWrapper*>(); std::vector<IHTMLElement*>& allElems = data.output_list_html_element_; std::vector<IHTMLElement*>::const_iterator cur, end = allElems.end(); for(cur = allElems.begin();cur < end; cur++) { IHTMLElement* elem = *cur; toReturn->push_back(new ElementWrapper(this, elem)); } return toReturn; } int InternetExplorerDriver::selectElementByClassName(IHTMLElement *pElem, const wchar_t *input_string, ElementWrapper** element) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTBYCLASSNAME) if (data.error_code == SUCCESS) { *element = new ElementWrapper(this, data.output_html_element_); } return data.error_code; } std::vector<ElementWrapper*>* InternetExplorerDriver::selectElementsByClassName(IHTMLElement *pElem, const wchar_t *input_string) { SCOPETRACER SEND_MESSAGE_ABOUT_ELEM(_WD_SELELEMENTSBYCLASSNAME) if(1 == data.output_long_) {std::wstring Err(L"Cannot find elements by ClassName"); throw Err;} std::vector<ElementWrapper*> *toReturn = new std::vector<ElementWrapper*>(); std::vector<IHTMLElement*>& allElems = data.output_list_html_element_; std::vector<IHTMLElement*>::const_iterator cur, end = allElems.end(); for(cur = allElems.begin();cur < end; cur++) { IHTMLElement* elem = *cur; toReturn->push_back(new ElementWrapper(this, elem)); } return toReturn; } void InternetExplorerDriver::waitForNavigateToFinish() { SCOPETRACER DataMarshaller& data = prepareCmData(); p_IEthread->m_EventToNotifyWhenNavigationCompleted = data.synchronization_flag_; sendThreadMsg(_WD_WAITFORNAVIGATIONTOFINISH, data); } bool InternetExplorerDriver::switchToFrame(LPCWSTR pathToFrame) { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_SWITCHTOFRAME, pathToFrame) return data.output_bool_; } LPCWSTR InternetExplorerDriver::getCookies() { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_GETCOOKIES,) return data.output_string_.c_str(); } int InternetExplorerDriver::addCookie(const wchar_t *cookieString) { SCOPETRACER SEND_MESSAGE_WITH_MARSHALLED_DATA(_WD_ADDCOOKIE, cookieString) return data.error_code; } CComVariant& InternetExplorerDriver::executeScript(const wchar_t *script, SAFEARRAY* args, bool tryAgain) { SCOPETRACER DataMarshaller& data = prepareCmData(script); data.input_safe_array_ = args; sendThreadMsg(_WD_EXECUTESCRIPT, data); return data.output_variant_; } void InternetExplorerDriver::setSpeed(int speed) { this->speed = speed; } int InternetExplorerDriver::getSpeed() { return speed; } ///////////////////////////////////////////////////////////// bool InternetExplorerDriver::sendThreadMsg(UINT msg, DataMarshaller& data) { ResetEvent(data.synchronization_flag_); // NOTE(alexis.j.vuillemin): do not do here data.resetOutputs() // it has to be performed FROM the worker thread (see ON_THREAD_COMMON). p_IEthread->PostThreadMessageW(msg, 0, 0); DWORD res = WaitForSingleObject(data.synchronization_flag_, 120000); data.resetInputs(); if(WAIT_TIMEOUT == res) { safeIO::CoutA("Unexpected TIME OUT."); p_IEthread->m_EventToNotifyWhenNavigationCompleted = NULL; std::wstring Err(L"Error: had to TIME OUT as a request to the worker thread did not complete after 2 min."); if(p_IEthread->m_HeartBeatListener != NULL) { PostMessage(p_IEthread->m_HeartBeatListener, _WD_HB_CRASHED, 0 ,0 ); } throw Err; } if(data.exception_caught_) { safeIO::CoutA("Caught exception from worker thread."); p_IEthread->m_EventToNotifyWhenNavigationCompleted = NULL; std::wstring Err(data.output_string_); throw Err; } return true; } inline DataMarshaller& InternetExplorerDriver::prepareCmData() { return commandData(); } DataMarshaller& InternetExplorerDriver::prepareCmData(LPCWSTR str) { DataMarshaller& data = prepareCmData(); data.input_string_ = str; return data; } DataMarshaller& InternetExplorerDriver::prepareCmData(IHTMLElement *pElem, LPCWSTR str) { DataMarshaller& data = prepareCmData(str); data.input_html_element_ = pElem; return data; } DataMarshaller& InternetExplorerDriver::prepareCmData(int v) { DataMarshaller& data = prepareCmData(); data.input_long_ = (long) v; return data; }
[ "alexber@07704840-8298-11de-bf8c-fd130f914ac9" ]
[ [ [ 1, 479 ] ] ]
55c4d3c035c28c2c7eef1dc4b7ed5329768a7049
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/statechart/test/TuTest.hpp
dc37b2b343bf053f676cc318265d87c70a294826
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,290
hpp
#ifndef BOOST_STATECHART_TEST_TU_TEST_HPP_INCLUDED #define BOOST_STATECHART_TEST_TU_TEST_HPP_INCLUDED ////////////////////////////////////////////////////////////////////////////// // Copyright 2005-2006 Andreas Huber Doenni // Distributed under the Boost Software License, Version 1.0. (See accompany- // ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ////////////////////////////////////////////////////////////////////////////// #include <boost/statechart/event.hpp> #include <boost/statechart/state_machine.hpp> #include <boost/config.hpp> #ifdef BOOST_HAS_DECLSPEC #ifdef BOOST_STATECHART_TEST_DYNAMIC_LINK #ifdef BOOST_STATECHART_TEST_DLL_EXPORT #define BOOST_STATECHART_DECL __declspec(dllexport) #else #define BOOST_STATECHART_DECL __declspec(dllimport) #endif #endif #endif #ifndef BOOST_STATECHART_DECL #define BOOST_STATECHART_DECL #endif namespace sc = boost::statechart; struct BOOST_STATECHART_DECL EvX : sc::event< EvX > {}; struct BOOST_STATECHART_DECL EvY : sc::event< EvY > {}; struct Initial; struct BOOST_STATECHART_DECL TuTest : sc::state_machine< TuTest, Initial > { void initiate(); void unconsumed_event( const sc::event_base & ); }; #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 48 ] ] ]
c706b10d7e226e2dc120acb79a689ab97e67d315
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/openredalert/src/game/ActionEventQueue.cpp
b8431bcb3bb0d28c0de6777ef4c793e4d8f6fbe3
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
2,094
cpp
// ActionEventQueue.cpp // 1.0 // This file is part of OpenRedAlert. // // OpenRedAlert is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 2 of the License. // // OpenRedAlert 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 OpenRedAlert. If not, see <http://www.gnu.org/licenses/>. #include "ActionEventQueue.h" #include "SDL/SDL_timer.h" #include "include/Logger.h" #include "ActionEvent.h" #include "Comp.h" /** * Constructor, starts the timer */ ActionEventQueue::ActionEventQueue() { // Save the current time starttick = SDL_GetTicks(); } /** * Destructor, removes the timer and empties the ActionEventQueue */ ActionEventQueue::~ActionEventQueue() { ActionEvent *ev; // Free all action event while( !eventqueue.empty() ) { ev = eventqueue.top(); eventqueue.pop(); if (ev != NULL) delete ev; ev = NULL; } } /** * Schedules event for later execution. * * @param event ActionEvent object to run. */ void ActionEventQueue::scheduleEvent(ActionEvent* event) { event->addCurtick(getCurtick()); eventqueue.push(event); } /** * Run all events in the actionqueue. */ void ActionEventQueue::runEvents() { Uint32 curtick = getCurtick(); // run all events in the queue with a prio lower than curtick while( !eventqueue.empty() && eventqueue.top()->getPrio() <= curtick ) { eventqueue.top()->run(); eventqueue.pop(); } } Uint32 ActionEventQueue::getElapsedTime() { return SDL_GetTicks() - starttick; } Uint32 ActionEventQueue::getCurtick() { return (SDL_GetTicks() - starttick) >> 5; }
[ [ [ 1, 86 ] ] ]
95fe1d1e54a89c79af9e962775bd587decf4db37
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/Hunter/NewGame/SanController/src/OgreNodeDebuggerComponent.cpp
87ae7e83d67c8176bce1b0ce4455e3ec9e8faf99
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,987
cpp
#include "SanControllerBaseStableHeaders.h" #include "OgreNodeDebuggerComponent.h" #include "COgreNodeDebuggerInterface.h" #include "CUpdateInterface.h" using namespace Orz; inline void Left(Ogre::SceneNode * sn, TimeType i) { sn->translate(i * 500, 0.f, 0.f, Ogre::Node::TS_WORLD); } inline void Right(Ogre::SceneNode * sn, TimeType i) { sn->translate(i * -500, 0.f, 0.f, Ogre::Node::TS_WORLD); } inline void Forward(Ogre::SceneNode * sn, TimeType i) { sn->translate(0.f, 0.f,i * 500, Ogre::Node::TS_WORLD); } inline void Backward(Ogre::SceneNode * sn, TimeType i) { sn->translate(0.f, 0.f,i * -500, Ogre::Node::TS_WORLD); } inline void Up(Ogre::SceneNode * sn, TimeType i) { sn->translate(0.f, i * 500, 0.f, Ogre::Node::TS_WORLD); } inline void Down(Ogre::SceneNode * sn, TimeType i) { sn->translate(0.f, i * -500, 0.f, Ogre::Node::TS_WORLD); } inline void Big(Ogre::SceneNode * sn, TimeType i) { sn->scale(Ogre::Vector3(1, 1, 1) * (1+i)); } inline void Small(Ogre::SceneNode * sn, TimeType i) { sn->scale(Ogre::Vector3(1, 1, 1) * (1-i)); } inline void Yaw(Ogre::SceneNode * sn, TimeType i, bool forward) { Ogre::Radian r(i ); if(!forward) r *= -1; sn->yaw(r); } inline void Reset(Ogre::SceneNode * sn, Ogre::Camera * camera, const Ogre::Vector3 & vec) { sn->setScale(vec); sn->resetOrientation(); sn->setPosition( camera->getCameraToViewportRay(0.5f, 0.5f).getPoint(100.f)); } inline void Print(Ogre::SceneNode * sn) { ORZ_LOG_NOTIFICATION_MESSAGE("Node Debugger Message:" + boost::lexical_cast<std::string>(sn->getPosition()) +boost::lexical_cast<std::string>(sn->getScale())+boost::lexical_cast<std::string>(sn->getOrientation())); } OgreNodeDebuggerComponent::OgreNodeDebuggerComponent(void):KeyListener(true), _debuggerInterface(new COgreNodeDebuggerInterface()),_num(0),_activeNode(NULL), _update(new CUpdateInterface()) { _debuggerInterface->pushNode = boost::bind(&OgreNodeDebuggerComponent::pushNode, this, _1); _debuggerInterface->removeNode = boost::bind(&OgreNodeDebuggerComponent::removeNode, this, _1); _debuggerInterface->enable = boost::bind(&OgreNodeDebuggerComponent::enable, this); _debuggerInterface->disable = boost::bind(&OgreNodeDebuggerComponent::disable, this); _update->update = boost::bind(&OgreNodeDebuggerComponent::update, this, _1); } OgreNodeDebuggerComponent::~OgreNodeDebuggerComponent(void) { } bool OgreNodeDebuggerComponent::onKeyPressed(const KeyEvent & evt) { KeyMap::iterator it = _keyMap.find(evt.getKey()); if(it != _keyMap.end()) { it->second.first = true; } if(KC_P == evt.getKey()) Print(_activeNode); if(Orz::KC_TAB == evt.getKey()) { next(); } return false; } bool OgreNodeDebuggerComponent::update(TimeType interval) { KeyMap::iterator it; for(it = _keyMap.begin(); it != _keyMap.end(); ++it) { if(it->second.first) { it->second.second(interval); } } return true; } bool OgreNodeDebuggerComponent::onKeyReleased(const KeyEvent & evt) { KeyMap::iterator it = _keyMap.find(evt.getKey()); if(it != _keyMap.end()) { it->second.first = false; } return false; } void OgreNodeDebuggerComponent::pushNode(Ogre::SceneNode * sn) { _nodes.push_back(sn); } void OgreNodeDebuggerComponent::removeNode(Ogre::SceneNode * sn) { _nodes.erase(std::remove(_nodes.begin(), _nodes.end(), sn), _nodes.end()); } ComponentInterface * OgreNodeDebuggerComponent::_queryInterface(const TypeInfo & info) const { if(info == TypeInfo(typeid(COgreNodeDebuggerInterface))) { return _debuggerInterface.get(); }else if(info == TypeInfo(typeid(CUpdateInterface))) { return _update.get(); } return NULL; } bool OgreNodeDebuggerComponent::enable(void) { _num = 0; IInputManager::getSingleton().addKeyListener(this); if(active()) { _keyMap.insert(std::make_pair(KC_A, std::make_pair(false, boost::bind(&Left, boost::cref(_activeNode), _1)) )); _keyMap.insert(std::make_pair(KC_D, std::make_pair(false, boost::bind(&Right,boost::cref( _activeNode), _1)) )); _keyMap.insert(std::make_pair(KC_W, std::make_pair(false, boost::bind(&Forward, boost::cref(_activeNode), _1)) )); _keyMap.insert(std::make_pair(KC_S, std::make_pair(false, boost::bind(&Backward, boost::cref(_activeNode), _1)) )); _keyMap.insert(std::make_pair(KC_PGUP, std::make_pair(false, boost::bind(&Up, boost::cref(_activeNode), _1)) )); _keyMap.insert(std::make_pair(KC_PGDOWN, std::make_pair(false, boost::bind(&Down, boost::cref(_activeNode), _1)) )); _keyMap.insert(std::make_pair(KC_COMMA, std::make_pair(false, boost::bind(&Big, boost::cref(_activeNode), _1)) )); _keyMap.insert(std::make_pair(KC_PERIOD, std::make_pair(false, boost::bind(&Small, boost::cref(_activeNode), _1)) )); _keyMap.insert(std::make_pair(KC_RIGHT, std::make_pair(false, boost::bind(&Yaw, boost::cref(_activeNode), _1, true)) )); _keyMap.insert(std::make_pair(KC_LEFT, std::make_pair(false, boost::bind(&Yaw, boost::cref(_activeNode), _1, false)) )); _keyMap.insert(std::make_pair(KC_R, std::make_pair(false, boost::bind(&Reset, boost::cref(_activeNode), Orz::OgreGraphicsManager::getSingleton().getCamera(), _scale)))); return true; } return false; } bool OgreNodeDebuggerComponent::active(void) { if(_num < _nodes.size()) { _activeNode = _nodes.at(_num); _activeNode->showBoundingBox(true); _scale = _activeNode->getScale(); return true; } return false; } void OgreNodeDebuggerComponent::disable(void) { IInputManager::getSingleton().removeKeyListener(this); if(_activeNode) _activeNode->showBoundingBox(false); _activeNode = NULL; _keyMap.clear(); _num = 0; } void OgreNodeDebuggerComponent::next(void) { if(_activeNode) _activeNode->showBoundingBox(false); _activeNode = NULL; _num ++; if(_num >= _nodes.size()) { _num = 0; } active(); }
[ [ [ 1, 207 ] ] ]
613941140deb7af0e6c5852d28b06a38f4adb292
d0cf8820b4ad21333e15f7cec1e4da54efe1fdc5
/hgeParticleEditor/EditorUI.cpp
acc27885b98d46dbc2894dc4f7c21e499da45509
[]
no_license
CBE7F1F65/c1bf2614b1ec411ee7fe4eb8b5cfaee6
296b31d342e39d1d931094c3dfa887dbb2143e54
09ed689a34552e62316e0e6442c116bf88a5a88b
refs/heads/master
2020-05-30T14:47:27.645751
2010-10-12T16:06:11
2010-10-12T16:06:11
32,192,658
0
0
null
null
null
null
UTF-8
C++
false
false
59,106
cpp
#include "EditorUI.h" #include "EditorRes.h" #include "Data.h" EditorUI ui; EditorUI::EditorUI() { timer = 0; } EditorUI::~EditorUI() { } void EditorUI::SetupInit() { for(int i=UIITEM_ITEMBEGIN; i<UIITEMMAX; i++) { eres.iteminfo[i].state = 0; } } void EditorUI::SetupEB(bool updateList) { editmode = UIEDITMODE_EB; if(eres.eff[ebnum]) { char buffer[M_STRMAX]; eres.iteminfo[UIITEM_EB_NLIFETIME].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EB_NLIFETIME].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EB_NLIFETIME].info, "nLifeTime"); eres.iteminfo[UIITEM_EB_NLIFETIME_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EB_NLIFETIME_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EB_NLIFETIME_VALUE].info, itoa(eres.eff[ebnum]->ebi.nLifeTime, buffer, 10)); eres.iteminfo[UIITEM_EB_NREPEATDELAY].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EB_NREPEATDELAY].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EB_NREPEATDELAY].info, "nRpDelay"); eres.iteminfo[UIITEM_EB_NREPEATDELAY_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EB_NREPEATDELAY_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EB_NREPEATDELAY_VALUE].info, itoa(eres.eff[ebnum]->ebi.nRepeatDelay, buffer, 10)); eres.iteminfo[UIITEM_EB_TEX].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EB_TEX].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EB_TEX].info, "Texure"); eres.iteminfo[UIITEM_EB_TEX_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EB_TEX_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EB_TEX_VALUE].info, itoa(eres.texnum[ebnum], buffer, 10)); if(updateList) { emitterItem = eres.eff[ebnum]->eiList; if(emitterItem) { emitter = &(emitterItem->emitter); } else { emitter = NULL; } if(emitter) { affectorItem = emitter->eaiList; if(affectorItem) { affector = &(emitter->eaiList->affector); } } else { affector = NULL; } eres.eff[ebnum]->Fire(); } } else { for(int i=UIITEM_ITEMBEGIN; i<UIITEM_EB_END; i++) { eres.iteminfo[i].state = 0; } emitterItem = NULL; emitter = NULL; affectorItem = NULL; affector = NULL; } for(int i=UIITEM_EB_END; i<UIITEMMAX; i++) { eres.iteminfo[i].state = 0; } } void EditorUI::SetupEE(bool updateList) { editmode = UIEDITMODE_EE; if(emitter) { char buffer[M_STRMAX]; eres.iteminfo[UIITEM_EE_NSTARTTIME].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_NSTARTTIME].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_NSTARTTIME].info, "nStartTime"); eres.iteminfo[UIITEM_EE_NSTARTTIME_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_NSTARTTIME_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_NSTARTTIME_VALUE].info, itoa(emitter->eei.nStartTime, buffer, 10)); eres.iteminfo[UIITEM_EE_NENDTIME].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_NENDTIME].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_NENDTIME].info, "nEndTime"); eres.iteminfo[UIITEM_EE_NENDTIME_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_NENDTIME_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_NENDTIME_VALUE].info, itoa(emitter->eei.nEndTime, buffer, 10)); eres.iteminfo[UIITEM_EE_NLIFETIMEMIN].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_NLIFETIMEMIN].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_NLIFETIMEMIN].info, "nLifeMin"); eres.iteminfo[UIITEM_EE_NLIFETIMEMIN_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_NLIFETIMEMIN_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_NLIFETIMEMIN_VALUE].info, itoa(emitter->eei.nLfieTimeMin, buffer, 10)); eres.iteminfo[UIITEM_EE_NLIFETIMEMAX].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_NLIFETIMEMAX].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_NLIFETIMEMAX].info, "nLifeMax"); eres.iteminfo[UIITEM_EE_NLIFETIMEMAX_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_NLIFETIMEMAX_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_NLIFETIMEMAX_VALUE].info, itoa(emitter->eei.nLifeTimeMax, buffer, 10)); eres.iteminfo[UIITEM_EE_FEMITNUM].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FEMITNUM].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FEMITNUM].info, "fEmitNum"); eres.iteminfo[UIITEM_EE_FEMITNUM_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FEMITNUM_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fEmitNum); strcpy(eres.iteminfo[UIITEM_EE_FEMITNUM_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FROTATIONX].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FROTATIONX].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FROTATIONX].info, "fRotationX"); eres.iteminfo[UIITEM_EE_FROTATIONX_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FROTATIONX_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fRotationX); strcpy(eres.iteminfo[UIITEM_EE_FROTATIONX_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FROTATIONY].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FROTATIONY].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FROTATIONY].info, "fRotationY"); eres.iteminfo[UIITEM_EE_FROTATIONY_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FROTATIONY_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fRotationY); strcpy(eres.iteminfo[UIITEM_EE_FROTATIONY_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FRADIUS].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FRADIUS].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FRADIUS].info, "fRadius"); eres.iteminfo[UIITEM_EE_FRADIUS_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FRADIUS_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fRadius); strcpy(eres.iteminfo[UIITEM_EE_FRADIUS_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FRADIUSINNER].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FRADIUSINNER].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FRADIUSINNER].info, "fRInner"); eres.iteminfo[UIITEM_EE_FRADIUSINNER_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FRADIUSINNER_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fRadiusInner); strcpy(eres.iteminfo[UIITEM_EE_FRADIUSINNER_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FTHETASTART].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTHETASTART].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FTHETASTART].info, "fThetaStart"); eres.iteminfo[UIITEM_EE_FTHETASTART_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTHETASTART_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fThetaStart); strcpy(eres.iteminfo[UIITEM_EE_FTHETASTART_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FTHETASTEP].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTHETASTEP].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FTHETASTEP].info, "fThetaStep"); eres.iteminfo[UIITEM_EE_FTHETASTEP_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTHETASTEP_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fThetaStep); strcpy(eres.iteminfo[UIITEM_EE_FTHETASTEP_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FTRACERESISTANCE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTRACERESISTANCE].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FTRACERESISTANCE].info, "fTraceResist"); eres.iteminfo[UIITEM_EE_FTRACERESISTANCE_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTRACERESISTANCE_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fTraceResistance); strcpy(eres.iteminfo[UIITEM_EE_FTRACERESISTANCE_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FTEXTUREX].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTEXTUREX].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FTEXTUREX].info, "fTextureX"); eres.iteminfo[UIITEM_EE_FTEXTUREX_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTEXTUREX_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fTextureX); strcpy(eres.iteminfo[UIITEM_EE_FTEXTUREX_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FTEXTUREY].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTEXTUREY].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FTEXTUREY].info, "fTextureY"); eres.iteminfo[UIITEM_EE_FTEXTUREY_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTEXTUREY_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fTextureY); strcpy(eres.iteminfo[UIITEM_EE_FTEXTUREY_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FTEXTUREW].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTEXTUREW].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FTEXTUREW].info, "fTextureW"); eres.iteminfo[UIITEM_EE_FTEXTUREW_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTEXTUREW_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fTextureW); strcpy(eres.iteminfo[UIITEM_EE_FTEXTUREW_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FTEXTUREH].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTEXTUREH].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FTEXTUREH].info, "fTextureH"); eres.iteminfo[UIITEM_EE_FTEXTUREH_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FTEXTUREH_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fTextureH); strcpy(eres.iteminfo[UIITEM_EE_FTEXTUREH_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FHOTX].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FHOTX].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FHOTX].info, "fHotX"); eres.iteminfo[UIITEM_EE_FHOTX_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FHOTX_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fHotX); strcpy(eres.iteminfo[UIITEM_EE_FHOTX_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_FHOTY].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FHOTY].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EE_FHOTY].info, "fHotY"); eres.iteminfo[UIITEM_EE_FHOTY_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_FHOTY_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", emitter->eei.fHotY); strcpy(eres.iteminfo[UIITEM_EE_FHOTY_VALUE].info, buffer); eres.iteminfo[UIITEM_EE_BLEND].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_BLEND].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_BLEND].info, "Blend"); eres.iteminfo[UIITEM_EE_BLEND_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_BLEND_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_BLEND_VALUE].info, itoa(emitter->eei.blend, buffer, 10)); eres.iteminfo[UIITEM_EE_BTRACE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_BTRACE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_BTRACE].info, "bTrace"); eres.iteminfo[UIITEM_EE_BTRACE_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_BTRACE_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_BTRACE_VALUE].info, itoa(emitter->eei.bTrace, buffer, 10)); eres.iteminfo[UIITEM_EE_BADJUSTDIRECTION].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_BADJUSTDIRECTION].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_BADJUSTDIRECTION].info, "bAdjustDir"); eres.iteminfo[UIITEM_EE_BADJUSTDIRECTION_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EE_BADJUSTDIRECTION_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EE_BADJUSTDIRECTION_VALUE].info, itoa(emitter->eei.bAdjustDirection, buffer, 10)); if(updateList) { affectorItem = emitter->eaiList; if(affectorItem) { affector = &(affectorItem->affector); } else { affector = NULL; } } } else { for(int i=UIITEM_ITEMBEGIN; i<UIITEM_EE_END; i++) { eres.iteminfo[i].state = 0; } affectorItem = NULL; affector = NULL; } for(int i=UIITEM_EE_END; i<UIITEMMAX; i++) { eres.iteminfo[i].state = 0; } } void EditorUI::SetupEA() { editmode = UIEDITMODE_EA; if(affector) { bool dwordmode = false; if(affector->eai.type == HGEEFFECT_AFFECTORTYPE_COLOR) dwordmode = true; char buffer[M_STRMAX]; eres.iteminfo[UIITEM_EA_NAFFECTORSTARTTIME].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_NAFFECTORSTARTTIME].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_NAFFECTORSTARTTIME].info, "nStartTime"); eres.iteminfo[UIITEM_EA_NAFFECTORSTARTTIME_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_NAFFECTORSTARTTIME_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_NAFFECTORSTARTTIME_VALUE].info, itoa(affector->eai.nAffectorStartTime, buffer, 10)); eres.iteminfo[UIITEM_EA_NAFFECTORENDTIME].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_NAFFECTORENDTIME].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_NAFFECTORENDTIME].info, "nEndTime"); eres.iteminfo[UIITEM_EA_NAFFECTORENDTIME_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_NAFFECTORENDTIME_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_NAFFECTORENDTIME_VALUE].info, itoa(affector->eai.nAffectorEndTime, buffer, 10)); eres.iteminfo[UIITEM_EA_NRANDOMPICKINTERVAL].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_NRANDOMPICKINTERVAL].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_NRANDOMPICKINTERVAL].info, "nPickInter"); eres.iteminfo[UIITEM_EA_NRANDOMPICKINTERVAL_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_NRANDOMPICKINTERVAL_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_NRANDOMPICKINTERVAL_VALUE].info, itoa(affector->eai.nRandomPickInterval, buffer, 10)); eres.iteminfo[UIITEM_EA_FSTARTVALUEMIN].state = UIITEM_STATE_NORMAL; if(dwordmode) { eres.iteminfo[UIITEM_EA_FSTARTVALUEMIN].inputtype = UIINPUTTYPE_DWORD; strcpy(eres.iteminfo[UIITEM_EA_FSTARTVALUEMIN].info, "uStartValMin"); } else { eres.iteminfo[UIITEM_EA_FSTARTVALUEMIN].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EA_FSTARTVALUEMIN].info, "fStartValMin"); } eres.iteminfo[UIITEM_EA_FSTARTVALUEMIN_VALUE].state = UIITEM_STATE_NORMAL; if(dwordmode) eres.iteminfo[UIITEM_EA_FSTARTVALUEMIN_VALUE].inputtype = UIINPUTTYPE_DWORD; else eres.iteminfo[UIITEM_EA_FSTARTVALUEMIN_VALUE].inputtype = UIINPUTTYPE_FLOAT; if(dwordmode) sprintf(buffer, "%08x", *(DWORD *)&(affector->eai.fStartValueMin)); else sprintf(buffer, "%f", affector->eai.fStartValueMin); strcpy(eres.iteminfo[UIITEM_EA_FSTARTVALUEMIN_VALUE].info, buffer); eres.iteminfo[UIITEM_EA_FSTARTVALUEMAX].state = UIITEM_STATE_NORMAL; if(dwordmode) { eres.iteminfo[UIITEM_EA_FSTARTVALUEMAX].inputtype = UIINPUTTYPE_DWORD; strcpy(eres.iteminfo[UIITEM_EA_FSTARTVALUEMAX].info, "uStartValMax"); } else { eres.iteminfo[UIITEM_EA_FSTARTVALUEMAX].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EA_FSTARTVALUEMAX].info, "fStartValMax"); } eres.iteminfo[UIITEM_EA_FSTARTVALUEMAX_VALUE].state = UIITEM_STATE_NORMAL; if(dwordmode) eres.iteminfo[UIITEM_EA_FSTARTVALUEMAX_VALUE].inputtype = UIINPUTTYPE_DWORD; else eres.iteminfo[UIITEM_EA_FSTARTVALUEMAX_VALUE].inputtype = UIINPUTTYPE_FLOAT; if(dwordmode) sprintf(buffer, "%08x", *(DWORD *)&(affector->eai.fStartValueMax)); else sprintf(buffer, "%f", affector->eai.fStartValueMax); strcpy(eres.iteminfo[UIITEM_EA_FSTARTVALUEMAX_VALUE].info, buffer); eres.iteminfo[UIITEM_EA_FENDVALUEMIN].state = UIITEM_STATE_NORMAL; if(dwordmode) { eres.iteminfo[UIITEM_EA_FENDVALUEMIN].inputtype = UIINPUTTYPE_DWORD; strcpy(eres.iteminfo[UIITEM_EA_FENDVALUEMIN].info, "uEndValMin"); } else { eres.iteminfo[UIITEM_EA_FENDVALUEMIN].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EA_FENDVALUEMIN].info, "fEndValMin"); } eres.iteminfo[UIITEM_EA_FENDVALUEMIN_VALUE].state = UIITEM_STATE_NORMAL; if(dwordmode) eres.iteminfo[UIITEM_EA_FENDVALUEMIN_VALUE].inputtype = UIINPUTTYPE_DWORD; else eres.iteminfo[UIITEM_EA_FENDVALUEMIN_VALUE].inputtype = UIINPUTTYPE_FLOAT; if(dwordmode) sprintf(buffer, "%08x", *(DWORD *)&(affector->eai.fEndValueMin)); else sprintf(buffer, "%f", affector->eai.fEndValueMin); strcpy(eres.iteminfo[UIITEM_EA_FENDVALUEMIN_VALUE].info, buffer); eres.iteminfo[UIITEM_EA_FENDVALUEMAX].state = UIITEM_STATE_NORMAL; if(dwordmode) { eres.iteminfo[UIITEM_EA_FENDVALUEMAX].inputtype = UIINPUTTYPE_DWORD; strcpy(eres.iteminfo[UIITEM_EA_FENDVALUEMAX].info, "uEndValMax"); } else { eres.iteminfo[UIITEM_EA_FENDVALUEMAX].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EA_FENDVALUEMAX].info, "fEndValMax"); } eres.iteminfo[UIITEM_EA_FENDVALUEMAX_VALUE].state = UIITEM_STATE_NORMAL; if(dwordmode) eres.iteminfo[UIITEM_EA_FENDVALUEMAX_VALUE].inputtype = UIINPUTTYPE_DWORD; else eres.iteminfo[UIITEM_EA_FENDVALUEMAX_VALUE].inputtype = UIINPUTTYPE_FLOAT; if(dwordmode) sprintf(buffer, "%08x", *(DWORD *)&(affector->eai.fEndValueMax)); else sprintf(buffer, "%f", affector->eai.fEndValueMax); strcpy(eres.iteminfo[UIITEM_EA_FENDVALUEMAX_VALUE].info, buffer); eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMIN].state = UIITEM_STATE_NORMAL; if(dwordmode) { eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMIN].inputtype = UIINPUTTYPE_DWORD; strcpy(eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMIN].info, "uIncMin"); } else { eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMIN].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMIN].info, "fIncMin"); } eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMIN_VALUE].state = UIITEM_STATE_NORMAL; if(dwordmode) eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMIN_VALUE].inputtype = UIINPUTTYPE_DWORD; else eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMIN_VALUE].inputtype = UIINPUTTYPE_FLOAT; if(dwordmode) sprintf(buffer, "%08x", *(DWORD *)&(affector->eai.fIncrementValueMin)); else sprintf(buffer, "%f", affector->eai.fIncrementValueMin); strcpy(eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMIN_VALUE].info, buffer); eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMAX].state = UIITEM_STATE_NORMAL; if(dwordmode) { eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMAX].inputtype = UIINPUTTYPE_DWORD; strcpy(eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMAX].info, "uIncMax"); } else { eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMAX].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMAX].info, "fIncMax"); } eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMAX_VALUE].state = UIITEM_STATE_NORMAL; if(dwordmode) eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMAX_VALUE].inputtype = UIINPUTTYPE_DWORD; else eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMAX_VALUE].inputtype = UIINPUTTYPE_FLOAT; if(dwordmode) sprintf(buffer, "%08x", *(DWORD *)&(affector->eai.fIncrementValueMax)); else sprintf(buffer, "%f", affector->eai.fIncrementValueMax); strcpy(eres.iteminfo[UIITEM_EA_FINCREMENTVALUEMAX_VALUE].info, buffer); eres.iteminfo[UIITEM_EA_FINCREMENTSCALE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_FINCREMENTSCALE].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EA_FINCREMENTSCALE].info, "fIncScale"); eres.iteminfo[UIITEM_EA_FINCREMENTSCALE_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_FINCREMENTSCALE_VALUE].inputtype = UIINPUTTYPE_FLOAT; sprintf(buffer, "%f", affector->eai.fIncrementScale); strcpy(eres.iteminfo[UIITEM_EA_FINCREMENTSCALE_VALUE].info, buffer); eres.iteminfo[UIITEM_EA_FACCELERATION].state = UIITEM_STATE_NORMAL; if(dwordmode) { eres.iteminfo[UIITEM_EA_FACCELERATION].inputtype = UIINPUTTYPE_DWORD; strcpy(eres.iteminfo[UIITEM_EA_FACCELERATION].info, "uAccel"); } else { eres.iteminfo[UIITEM_EA_FACCELERATION].inputtype = UIINPUTTYPE_FLOAT; strcpy(eres.iteminfo[UIITEM_EA_FACCELERATION].info, "fAccel"); } eres.iteminfo[UIITEM_EA_FACCELERATION_VALUE].state = UIITEM_STATE_NORMAL; if(dwordmode) eres.iteminfo[UIITEM_EA_FACCELERATION_VALUE].inputtype = UIINPUTTYPE_DWORD; else eres.iteminfo[UIITEM_EA_FACCELERATION_VALUE].inputtype = UIINPUTTYPE_FLOAT; if(dwordmode) sprintf(buffer, "%08x", *(DWORD *)&(affector->eai.fAcceleration)); else sprintf(buffer, "%f", affector->eai.fAcceleration); strcpy(eres.iteminfo[UIITEM_EA_FACCELERATION_VALUE].info, buffer); eres.iteminfo[UIITEM_EA_BUSESTARTVALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_BUSESTARTVALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_BUSESTARTVALUE].info, "bUseStart"); eres.iteminfo[UIITEM_EA_BUSESTARTVALUE_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_BUSESTARTVALUE_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_BUSESTARTVALUE_VALUE].info, itoa(affector->eai.bUseStartValue, buffer, 10)); eres.iteminfo[UIITEM_EA_BUSEENDVALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_BUSEENDVALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_BUSEENDVALUE].info, "bUseEnd"); eres.iteminfo[UIITEM_EA_BUSEENDVALUE_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_BUSEENDVALUE_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_BUSEENDVALUE_VALUE].info, itoa(affector->eai.bUseEndValue, buffer, 10)); eres.iteminfo[UIITEM_EA_TYPE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_TYPE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_TYPE].info, "Type"); eres.iteminfo[UIITEM_EA_TYPE_VALUE].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EA_TYPE_VALUE].inputtype = UIINPUTTYPE_INT; strcpy(eres.iteminfo[UIITEM_EA_TYPE_VALUE].info, itoa(affector->eai.type, buffer, 10)); } else { for(int i=UIITEM_ITEMBEGIN; i<UIITEM_EA_END; i++) { eres.iteminfo[i].state = 0; } } for(int i=UIITEM_EA_END; i<UIITEMMAX; i++) { eres.iteminfo[i].state = 0; } } void EditorUI::PageUp() { if(editmode == UIEDITMODE_EB) { bool bFound = false; for(int i=ebnum-1; i>=0; i--) { if(eres.eff[i]) { ebnum = i; bFound = true; break; } } if(!bFound) { for(int i=EFFECTSYSTYPEMAX-1; i> ebnum; i--) { if(eres.eff[i]) { ebnum = i; bFound = true; break; } } } if(bFound) SetupEB(true); } else if(editmode == UIEDITMODE_EE) { if(eres.eff[ebnum]) { if(emitter && emitterItem) { emitterItem = emitterItem->next; } if(!emitterItem) { emitterItem = eres.eff[ebnum]->eiList; } if(emitterItem) { emitter = &(emitterItem->emitter); SetupEE(true); } else emitter = NULL; } } else if(editmode == UIEDITMODE_EA) { if(eres.eff[ebnum] && emitter && emitterItem) { if(affector && affectorItem) { affectorItem = affectorItem->next; } if(!affectorItem) { affectorItem = emitter->eaiList; } if(affectorItem) { affector = &(affectorItem->affector); SetupEA(); } else affector = NULL; } } } void EditorUI::PageDown() { if(editmode == UIEDITMODE_EB) { bool bFound = false; for(int i=ebnum+1; i<EFFECTSYSTYPEMAX; i++) { if(eres.eff[i]) { ebnum = i; bFound = true; break; } } if(!bFound) { for(int i=0; i<ebnum; i++) { if(eres.eff[i]) { ebnum = i; bFound = true; break; } } } if(bFound) SetupEB(true); } else if(editmode == UIEDITMODE_EE) { if(eres.eff[ebnum]) { CEmitterList * _emitterItem = eres.eff[ebnum]->eiList; bool bFirst = false; if(emitterItem == _emitterItem) bFirst = true; while(_emitterItem) { if(_emitterItem->next == emitterItem) { emitterItem = _emitterItem; break; } if(bFirst && _emitterItem->next == NULL) { emitterItem = _emitterItem; break; } _emitterItem = _emitterItem->next; } if(emitterItem) { emitter = &(emitterItem->emitter); SetupEE(true); } else emitter = NULL; } } else if(editmode == UIEDITMODE_EA) { if(eres.eff[ebnum] && emitter && emitterItem) { CAffectorList * _affectorItem = emitter->eaiList; bool bFirst = false; if(affectorItem == _affectorItem) bFirst = true; while(_affectorItem) { if(_affectorItem->next == affectorItem) { affectorItem = _affectorItem; break; } if(bFirst && _affectorItem->next == NULL) { affectorItem = _affectorItem; break; } _affectorItem = _affectorItem->next; } if(affectorItem) { affector = &(affectorItem->affector); SetupEA(); } else affector = NULL; } } } void EditorUI::Refresh() { if(eres.eff[ebnum]) { eres.eff[ebnum]->Fire(); } zpos = 0; } void EditorUI::ChangePanel(BYTE info) { switch(info) { case UIITEM_EBINFO: eres.iteminfo[UIITEM_EBINFO].state = UIITEM_STATE_SELECTED; eres.iteminfo[UIITEM_EEINFO].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EAINFO].state = UIITEM_STATE_NORMAL; SetupEB(); break; case UIITEM_EEINFO: eres.iteminfo[UIITEM_EEINFO].state = UIITEM_STATE_SELECTED; eres.iteminfo[UIITEM_EBINFO].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EAINFO].state = UIITEM_STATE_NORMAL; SetupEE(); break; case UIITEM_EAINFO: eres.iteminfo[UIITEM_EAINFO].state = UIITEM_STATE_SELECTED; eres.iteminfo[UIITEM_EBINFO].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_EEINFO].state = UIITEM_STATE_NORMAL; SetupEA(); break; } } void EditorUI::Operate() { if(!editmode) return; eres.iteminfo[oper].state = UIITEM_STATE_SELECTED; eres.iteminfo[UIITEM_INPUTINFO].state = UIITEM_STATE_SELECTED; strcpy(input, ""); } bool EditorUI::Save() { if(!eres.eff[ebnum]) return false; return eres.Save(ebnum); } bool EditorUI::isListNull() { if(!editmode) return true; switch(editmode) { case UIEDITMODE_EA: if(!affector || !affectorItem) return true; case UIEDITMODE_EE: if(!emitter || !emitterItem) return true; case UIEDITMODE_EB: if(!eres.eff[ebnum]) return true; } return false; } void EditorUI::Update() { timer++; if(timer == 1) { eres.Init(); SetupInit(); input = eres.iteminfo[UIITEM_INPUTINFO].info; title = eres.iteminfo[UIITEM_TITLEINFO].info; addinfo = eres.iteminfo[UIITEM_ADDINFO].info; oper = -1; ebnum = 0; zpos = 0; emitter = NULL; affector = NULL; editmode = UIEDITMODE_EB; ChangePanel(UIITEM_EBINFO); SetupEB(true); } hge->Input_GetMousePos(&mx, &my); wheel = 0; clickdown = false; clickup = false; while(hge->Input_GetEvent(&inputevent)) { if(inputevent.type == INPUT_MBUTTONDOWN) { clickdown = true; } else if(inputevent.type == INPUT_MBUTTONUP) { clickup = true; } else if(inputevent.type == INPUT_MOUSEWHEEL) { wheel = inputevent.wheel; if(wheel) { if(hge->Input_GetDIKey(DIK_RSHIFT)) { zpos += wheel; } else { zpos += wheel * 10; } } } } if(mx < M_ACTIVECLIENT_RIGHT) hge->System_SetState(HGE_HIDEMOUSE, true); else hge->System_SetState(HGE_HIDEMOUSE, false); if(hge->Input_GetDIKey(DIK_RCONTROL) && hge->Input_GetDIKey(DIK_NEXT, DIKEY_DOWN)) { ChangeBGTex(); } if(hge->Input_GetDIKey(DIK_RCONTROL) && hge->Input_GetDIKey(DIK_PRIOR, DIKEY_DOWN)) { bool bFound = false; if(eres.bgtex == -1) eres.bgtex = TEXMAX; int i; for(i=eres.bgtex-1; i>=0; i--) { if(eres.tex[i]) { bFound = true; break; } } if(!bFound) { for(i=TEXMAX-1; i>eres.bgtex; i--) { if(eres.tex[i]) { bFound = true; break; } } } if(bFound) ChangeBGTex(i); } for(int i=0; i<UIITEMMAX; i++) { if(eres.iteminfo[i].state) { if(eres.iteminfo[i].state != UIITEM_STATE_SELECTED) { if(mx > eres.iteminfo[i].x && mx < eres.iteminfo[i].x + eres.iteminfo[i].w && my > eres.iteminfo[i].y && my < eres.iteminfo[i].y + eres.iteminfo[i].h) { if(clickdown && oper == -1) { ChangePanel(i); } if(clickup && oper == -1) { if(i == UIITEM_REFRESHINFO) { Refresh(); } else if(i == UIITEM_PAGEUPINFO) { PageUp(); } else if(i == UIITEM_PAGEDOWNINFO) { PageDown(); } else if(i == UIITEM_SAVEINFO) { Save(); } else if(i == UIITEM_ADDINFO) { if(hge->Input_GetDIKey(DIK_RCONTROL)) Delete(); else Add(); } else if(i == UIITEM_BGINFO) { ChangeBGTex(); } if(oper < 0) { if(i >= UIITEM_ITEMBEGIN) { eres.iteminfo[i].state = UIITEM_STATE_SELECTED; eres.iteminfo[UIITEM_INPUTINFO].state = UIITEM_STATE_SELECTED; oper = i; if(oper >= UIITEM_ITEMBEGIN) { oper = ((oper>>1)<<1)+1; eres.iteminfo[oper].state = UIITEM_STATE_SELECTED; eres.iteminfo[oper-1].state = UIITEM_STATE_NORMAL; } strcpy(input, ""); } } } else if(eres.iteminfo[i].state != UIITEM_STATE_SELECTED) eres.iteminfo[i].state = UIITEM_STATE_OVER; } else { eres.iteminfo[i].state = UIITEM_STATE_NORMAL; } } } } if(oper >= 0) { if(UpdateInput()) { if(UpdateValue()) { eres.iteminfo[oper].state = UIITEM_STATE_NORMAL; eres.iteminfo[UIITEM_INPUTINFO].state = UIITEM_STATE_NORMAL; strcpy(eres.iteminfo[UIITEM_INPUTINFO].info, "Input"); if(oper >= UIITEM_ITEMBEGIN) { if(hge->Input_GetDIKey(DIK_UP, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_UP) && pushtimer == M_PUSH_FIRST) { oper -= 2; if(oper < UIITEM_ITEMBEGIN) { switch(editmode) { case UIEDITMODE_EB: oper = UIITEM_EB_END - 1; break; case UIEDITMODE_EE: oper = UIITEM_EE_END - 1; break; case UIEDITMODE_EA: oper = UIITEM_EA_END - 1; break; default: oper = -1; break; } } } else if(hge->Input_GetDIKey(DIK_DOWN, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_DOWN) && pushtimer == M_PUSH_FIRST) { oper += 2; switch(editmode) { case UIEDITMODE_EB: if(oper > UIITEM_EB_END) oper = UIITEM_ITEMBEGIN + 1; break; case UIEDITMODE_EE: if(oper > UIITEM_EE_END) oper = UIITEM_ITEMBEGIN + 1; break; case UIEDITMODE_EA: if(oper > UIITEM_EA_END) oper = UIITEM_ITEMBEGIN + 1; break; default: oper = -1; break; } } else oper = -1; } else oper = -1; if(oper >= 0) { Operate(); } } else { strcpy(input, ""); } } } char buff[M_STRITOAMAX]; switch(editmode) { case 0: strcpy(title, "Title"); break; case UIEDITMODE_EB: if(eres.eff[ebnum]) { strcpy(title, "EffectSystem_"); strcat(title, itoa(ebnum, buff, 10)); } else { strcpy(title, "Title"); } break; case UIEDITMODE_EE: if(emitter) { strcpy(title, "Emitter_"); strcat(title, itoa(ebnum, buff, 10)); strcat(title, "_"); strcat(title, itoa(emitter->ID, buff, 10)); } else { strcpy(title, "Title"); } break; case UIEDITMODE_EA: if(affector) { strcpy(title, eres.GetAffectorName(affector->eai.type)); strcat(title, "_"); strcat(title, itoa(ebnum, buff, 10)); strcat(title, "_"); strcat(title, itoa(emitter->ID, buff, 10)); strcat(title, "_"); strcat(title, itoa(affector->ID, buff, 10)); } else { strcpy(title, "Title"); } break; } nlives = 0; if(eres.eff[ebnum]) { if(mx < M_ACTIVECLIENT_RIGHT) eres.eff[ebnum]->MoveTo(mx, my, zpos); eres.eff[ebnum]->Update(); nlives = eres.eff[ebnum]->GetEffectObjectAlive(); } if(hge->Input_GetDIKey(DIK_RCONTROL)) { strcpy(addinfo, "Delete"); } else { strcpy(addinfo, "Add"); } if(oper == -1) { if(hge->Input_GetDIKey(DIK_LEFT) || hge->Input_GetDIKey(DIK_RIGHT)) { if(pushtimer < M_PUSH_FIRST) pushtimer++; else if(pushtimer == M_PUSH_FIRST) pushtimer = M_PUSH_FIRST - M_PUSH_SKIP; } else pushtimer = 0; if(!hge->Input_GetDIKey(DIK_RCONTROL) && hge->Input_GetDIKey(DIK_PRIOR, DIKEY_DOWN)) PageUp(); else if(!hge->Input_GetDIKey(DIK_RCONTROL) && hge->Input_GetDIKey(DIK_NEXT, DIKEY_DOWN)) PageDown(); else if(hge->Input_GetDIKey(DIK_TAB, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_RIGHT, DIKEY_DOWN) || pushtimer == M_PUSH_FIRST) { BYTE _info = 0; switch(editmode) { case UIEDITMODE_EB: _info = UIITEM_EEINFO; break; case UIEDITMODE_EE: _info = UIITEM_EAINFO; break; case UIEDITMODE_EA: _info = UIITEM_EBINFO; break; } ChangePanel(_info); } else if(hge->Input_GetDIKey(DIK_LEFT, DIKEY_DOWN) || pushtimer == M_PUSH_FIRST) { BYTE _info = 0; switch(editmode) { case UIEDITMODE_EB: _info = UIITEM_EAINFO; break; case UIEDITMODE_EE: _info = UIITEM_EBINFO; break; case UIEDITMODE_EA: _info = UIITEM_EEINFO; break; } ChangePanel(_info); } else if(hge->Input_GetDIKey(DIK_END, DIKEY_DOWN) && !hge->Input_GetDIKey(DIK_RCONTROL) || isListNull() && (hge->Input_GetDIKey(DIK_UP, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_DOWN, DIKEY_DOWN))) { Add(); } else if(hge->Input_GetDIKey(DIK_END, DIKEY_DOWN) && hge->Input_GetDIKey(DIK_RCONTROL)) { Delete(); } else if(hge->Input_GetDIKey(DIK_UP ,DIKEY_DOWN) || pushtimer == M_PUSH_FIRST) { if(editmode && oper == -1) { switch(editmode) { case UIEDITMODE_EB: if(eres.eff[ebnum]) oper = UIITEM_EB_END - 1; break; case UIEDITMODE_EE: if(eres.eff[ebnum] && emitter && emitterItem) oper = UIITEM_EE_END - 1; break; case UIEDITMODE_EA: if(eres.eff[ebnum] && emitter && emitterItem && affector && affectorItem) oper = UIITEM_EA_END - 1; break; } } if(oper >= 0) Operate(); } else if(hge->Input_GetDIKey(DIK_DOWN, DIKEY_DOWN)) { if(editmode && oper == -1) { switch(editmode) { case UIEDITMODE_EB: if(eres.eff[ebnum]) oper = UIITEM_ITEMBEGIN + 1; break; case UIEDITMODE_EE: if(eres.eff[ebnum] && emitter && emitterItem) oper = UIITEM_ITEMBEGIN + 1; break; case UIEDITMODE_EA: if(eres.eff[ebnum] && emitter && emitterItem && affector && affectorItem) oper = UIITEM_ITEMBEGIN + 1; break; } } if(oper >= 0) Operate(); } else if(hge->Input_GetDIKey(DIK_RCONTROL) && hge->Input_GetDIKey(DIK_DELETE, DIKEY_DOWN)) { Delete(); } else if(hge->Input_GetDIKey(DIK_HOME, DIKEY_DOWN)) { Refresh(); } else if(hge->Input_GetDIKey(DIK_INSERT, DIKEY_DOWN)) { Save(); } } } bool EditorUI::UpdateInput() { if(hge->Input_GetDIKey(DIK_UP) || hge->Input_GetDIKey(DIK_DOWN)) { if(pushtimer < M_PUSH_FIRST) pushtimer++; else if(pushtimer == M_PUSH_FIRST) pushtimer = M_PUSH_FIRST - M_PUSH_SKIP; } else pushtimer = 0; if(hge->Input_GetDIKey(DIK_RETURN, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPADENTER, DIKEY_DOWN)) { return true; } if(oper >= UIITEM_ITEMBEGIN && (hge->Input_GetDIKey(DIK_UP, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_DOWN, DIKEY_DOWN) || pushtimer == M_PUSH_FIRST)) { return true; } if(hge->Input_GetDIKey(DIK_0, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPAD0, DIKEY_DOWN)) { bool link = true; if(eres.iteminfo[oper].inputtype != UIINPUTTYPE_DWORD && (input[0] == '0' || input[0] == '-' && (eres.iteminfo[oper].inputtype == UIINPUTTYPE_INT && strlen(input) < 2 || input[1] == '0'))) { link = false; if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_FLOAT) { for(int i=0; i<strlen(input); i++) { if(input[i] == '.') { link = true; break; } } } } if(link) strcat(input, "0"); } else if(hge->Input_GetDIKey(DIK_1, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPAD1, DIKEY_DOWN)) { input[UIEDITINPUT_MAX] = 0; strcat(input, "1"); } else if(hge->Input_GetDIKey(DIK_2, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPAD2, DIKEY_DOWN)) { input[UIEDITINPUT_MAX] = 0; strcat(input, "2"); } else if(hge->Input_GetDIKey(DIK_3, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPAD3, DIKEY_DOWN)) { input[UIEDITINPUT_MAX] = 0; strcat(input, "3"); } else if(hge->Input_GetDIKey(DIK_4, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPAD4, DIKEY_DOWN)) { input[UIEDITINPUT_MAX] = 0; strcat(input, "4"); } else if(hge->Input_GetDIKey(DIK_5, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPAD5, DIKEY_DOWN)) { input[UIEDITINPUT_MAX] = 0; strcat(input, "5"); } else if(hge->Input_GetDIKey(DIK_6, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPAD6, DIKEY_DOWN)) { input[UIEDITINPUT_MAX] = 0; strcat(input, "6"); } else if(hge->Input_GetDIKey(DIK_7, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPAD7, DIKEY_DOWN)) { input[UIEDITINPUT_MAX] = 0; strcat(input, "7"); } else if(hge->Input_GetDIKey(DIK_8, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPAD8, DIKEY_DOWN)) { input[UIEDITINPUT_MAX] = 0; strcat(input, "8"); } else if(hge->Input_GetDIKey(DIK_9, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_NUMPAD9, DIKEY_DOWN)) { input[UIEDITINPUT_MAX] = 0; strcat(input, "9"); } else if(hge->Input_GetDIKey(DIK_MINUS, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_SUBTRACT, DIKEY_DOWN)) { bool link = true; if(strlen(input) != 0 || eres.iteminfo[oper].inputtype == UIINPUTTYPE_DWORD) { link = false; } if(link) strcat(input, "-"); } else if(hge->Input_GetDIKey(DIK_PERIOD, DIKEY_DOWN) || hge->Input_GetDIKey(DIK_DECIMAL, DIKEY_DOWN)) { if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_FLOAT) { bool link = true; for(int i=0; i<strlen(input); i++) { if(input[i] == '.') { link = false; break; } } if(link) strcat(input, "."); } } else if(hge->Input_GetDIKey(DIK_A, DIKEY_DOWN)) { if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_DWORD) strcat(input, "A"); } else if(hge->Input_GetDIKey(DIK_B, DIKEY_DOWN)) { if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_DWORD) strcat(input, "B"); } else if(hge->Input_GetDIKey(DIK_C, DIKEY_DOWN)) { if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_DWORD) strcat(input, "C"); } else if(hge->Input_GetDIKey(DIK_D, DIKEY_DOWN)) { if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_DWORD) strcat(input, "D"); } else if(hge->Input_GetDIKey(DIK_E, DIKEY_DOWN)) { if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_DWORD) strcat(input, "E"); } else if(hge->Input_GetDIKey(DIK_F, DIKEY_DOWN)) { if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_DWORD) strcat(input, "F"); } if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_DWORD) { input[8] = 0; } else { input[UIEDITINPUT_MAX + 1] = 0; } if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_FLOAT) { char buffer[M_STRITOAMAX]; strcpy(buffer, input); fval = (float)atof(buffer); } else if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_INT) { if(input[0] == '0' && strlen(input) > 1) { strcpy(input, &input[1]); } char buffer[M_STRITOAMAX]; strcpy(buffer, input); ival = atoi(buffer); } else if(eres.iteminfo[oper].inputtype == UIINPUTTYPE_DWORD) { sscanf(input, "%x", &uval); } return false; } bool EditorUI::Delete() { if(editmode == 0) return false; if(editmode == UIEDITMODE_EB) { char buffer[M_STRMAX]; strcpy(buffer, "Delete "); strcat(buffer, eres.GetFullFilename(ebnum)); strcat(buffer, " ?"); if(MessageBox(NULL, buffer, "", MB_OKCANCEL) == IDOK) { data.SetEffectSystemResourceName(ebnum, ""); DeleteFile(hge->Resource_MakePath(eres.fullfilename)); delete eres.eff[ebnum]; eres.eff[ebnum] = NULL; eres.texnum[ebnum] = -1; PageDown(); } SetupEB(true); return true; } if(editmode == UIEDITMODE_EE) { if(!eres.eff[ebnum]) return false; if(emitter && emitterItem) { char buffer[M_STRMAX]; strcpy(buffer, "Delete "); strcat(buffer, title); strcat(buffer, " ? ("); strcat(buffer, eres.GetFullFilename(ebnum)); strcat(buffer, ")"); if(MessageBox(NULL, buffer, "", MB_OKCANCEL) == IDOK) { int delID = emitter->ID; eres.eff[ebnum]->DeleteEmitter(delID); emitterItem = eres.eff[ebnum]->eiList; CEmitterList * _emitterItem = emitterItem; while (_emitterItem) { if (_emitterItem->emitter.ID > delID) { _emitterItem->emitter.ID--; } _emitterItem = _emitterItem->next; } if(emitterItem) emitter = &(emitterItem->emitter); else emitter = NULL; } SetupEE(true); } return true; } if(editmode == UIEDITMODE_EA) { if(!eres.eff[ebnum] || !emitter || !emitterItem) return false; if(affector && affectorItem) { char buffer[M_STRMAX]; strcpy(buffer, "Delete "); strcat(buffer, title); strcat(buffer, " ? ("); strcat(buffer, eres.GetFullFilename(ebnum)); strcat(buffer, ")"); if(MessageBox(NULL, buffer, "", MB_OKCANCEL) == IDOK) { int delID = affector->ID; eres.eff[ebnum]->DeleteAffector(emitter->ID, delID); affectorItem = emitter->eaiList; CAffectorList * _affectorItem = affectorItem; while (_affectorItem) { if (_affectorItem->affector.ID > delID) { _affectorItem->affector.ID--; } _affectorItem = _affectorItem->next; } if(affectorItem) affector = &(affectorItem->affector); else affector = NULL; } SetupEA(); } return true; } return false; } bool EditorUI::Add() { if(editmode == 0) return false; if(editmode == UIEDITMODE_EB) { int i = 0; for(; i<EFFECTSYSTYPEMAX; i++) { if(!eres.eff[i]) break; } if(i >= 0 && i < EFFECTSYSTYPEMAX) { if(!eres.eff[i]) { char buffer[M_STRMAX]; char buff[M_STRITOAMAX]; strcpy(buffer, "EffectSystem_"); strcat(buffer, itoa(i, buff, 10)); strcat(buffer, ".effect"); data.SetEffectSystemResourceName(i, buffer); eres.eff[i] = new hgeEffectSystem; ZeroMemory(eres.eff[i], sizeof(hgeEffectSystem)); ebnum = i; SetupEB(true); return true; } } return false; } if(editmode == UIEDITMODE_EE) { if(!eres.eff[ebnum]) return false; int i = 1; CEmitterList * _emitterItem = eres.eff[ebnum]->eiList; while(_emitterItem) { i++; _emitterItem = _emitterItem->next; } if(i > 0 && i < HGEEFFECT_EMITTERMAX) { _emitterItem = eres.eff[ebnum]->eiList; hgeEffectEmitterInfo _eei; ZeroMemory(&_eei, sizeof(hgeEffectEmitterInfo)); eres.eff[ebnum]->AddEmitter(i, &_eei); emitterItem = NULL; emitter = NULL; _emitterItem = eres.eff[ebnum]->eiList; while(_emitterItem) { if(_emitterItem->emitter.ID == i) { emitterItem = _emitterItem; emitter = &(emitterItem->emitter); break; } _emitterItem = _emitterItem->next; } emitter->sprite->SetTexture(eres.eff[ebnum]->ebi.tex); SetupEE(true); return true; } return false; } if(editmode == UIEDITMODE_EA) { if(!eres.eff[ebnum] || !emitter || !emitterItem) return false; int i = 1; CAffectorList * _affectorItem = emitter->eaiList; while(_affectorItem) { i++; _affectorItem = _affectorItem->next; } if(i > 0 && i < HGEEFFECT_AFFECTORMAX) { _affectorItem = emitter->eaiList; hgeEffectAffectorInfo _eai; ZeroMemory(&_eai, sizeof(hgeEffectAffectorInfo)); eres.eff[ebnum]->AddAffector(emitter->ID, i, &_eai); affectorItem = NULL; affector = NULL; _affectorItem = emitter->eaiList; while(_affectorItem) { if(_affectorItem->affector.ID == i) { affectorItem = _affectorItem; affector = &(affectorItem->affector); break; } _affectorItem = _affectorItem->next; } SetupEA(); return true; } return false; } return false; } bool EditorUI::ChangeBGTex(int texnum) { if(texnum == -1) { bool bFound = false; int i; for(i=eres.bgtex+1; i<TEXMAX; i++) { if(eres.tex[i]) { bFound = true; break; } } if(!bFound) { for(i=0; i<eres.bgtex; i++) { if(eres.tex[i]) { bFound = true; break; } } } if(bFound) texnum = i; } if(eres.tex[texnum]) { eres.bg->SetTexture(eres.tex[texnum]); eres.bg->SetTextureRect(0, 0, hge->Texture_GetWidth(eres.tex[texnum]), hge->Texture_GetHeight(eres.tex[texnum])); eres.bgtex = texnum; return true; } return false; } bool EditorUI::UpdateValue() { if(!strlen(input)) return true; if(oper > UIITEM_ITEMBEGIN) { if(editmode == UIEDITMODE_EB) { return EditEB(); } if(editmode == UIEDITMODE_EE) { return EditEE(); } if(editmode == UIEDITMODE_EA) { return EditEA(); } return true; } return false; } bool EditorUI::EditEB() { if(isListNull()) return true; if(oper == UIITEM_EB_NLIFETIME_VALUE) { if(ival >= 0) { eres.eff[ebnum]->ebi.nLifeTime = ival; SetupEB(); return true; } } else if(oper == UIITEM_EB_NREPEATDELAY_VALUE) { if(ival >= 0) { eres.eff[ebnum]->ebi.nRepeatDelay = ival; SetupEB(); return true; } } else if(oper == UIITEM_EB_TEX_VALUE) { if(ival >= 0 && ival < TEXMAX) { if(eres.tex[ival]) { eres.eff[ebnum]->ebi.tex = eres.tex[ival]; eres.texnum[ebnum] = ival; CEmitterList * _emitterItem = eres.eff[ebnum]->eiList; while(_emitterItem) { _emitterItem->emitter.sprite->SetTexture(eres.tex[ival]); _emitterItem = _emitterItem->next; } SetupEB(); return true; } } } return false; } bool EditorUI::EditEE() { if(isListNull()) return true; if(oper == UIITEM_EE_NSTARTTIME_VALUE) { if(ival >= 0) { emitter->eei.nStartTime = ival; if(emitter->eei.nEndTime < ival) emitter->eei.nEndTime = ival; SetupEE(); return true; } } else if(oper == UIITEM_EE_NENDTIME_VALUE) { if(ival >= 0) { emitter->eei.nEndTime = ival; if(emitter->eei.nStartTime > ival) emitter->eei.nStartTime = ival; SetupEE(); return true; } } else if(oper == UIITEM_EE_NLIFETIMEMIN_VALUE) { if(ival >= 0) { emitter->eei.nLfieTimeMin = ival; if(emitter->eei.nLifeTimeMax < ival) emitter->eei.nLifeTimeMax = ival; SetupEE(); return true; } } else if(oper == UIITEM_EE_NLIFETIMEMAX_VALUE) { if(ival >= 0) { emitter->eei.nLifeTimeMax = ival; if(emitter->eei.nLfieTimeMin > ival) emitter->eei.nLfieTimeMin = ival; SetupEE(); return true; } } else if(oper == UIITEM_EE_FEMITNUM_VALUE) { if(fval >= 0) { emitter->eei.fEmitNum = fval; SetupEE(); return true; } } else if(oper == UIITEM_EE_FROTATIONX_VALUE) { emitter->eei.fRotationX = fval; SetupEE(); return true; } else if(oper == UIITEM_EE_FROTATIONY_VALUE) { emitter->eei.fRotationY = fval; SetupEE(); return true; } else if(oper == UIITEM_EE_FRADIUS_VALUE) { if(fval >= 0) { emitter->eei.fRadius = fval; if(emitter->eei.fRadiusInner > fval) emitter->eei.fRadiusInner = fval; SetupEE(); return true; } } else if(oper == UIITEM_EE_FRADIUSINNER_VALUE) { if(fval >= 0) { emitter->eei.fRadiusInner = fval; if(emitter->eei.fRadius < fval) emitter->eei.fRadius = fval; SetupEE(); return true; } } else if(oper == UIITEM_EE_FTHETASTART_VALUE) { emitter->eei.fThetaStart = fval; SetupEE(); return true; } else if(oper == UIITEM_EE_FTHETASTEP_VALUE) { emitter->eei.fThetaStep = fval; SetupEE(); return true; } else if(oper == UIITEM_EE_FTRACERESISTANCE_VALUE) { emitter->eei.fTraceResistance = fval; SetupEE(); return true; } else if(oper == UIITEM_EE_FTEXTUREX_VALUE) { emitter->eei.fTextureX = fval; emitter->sprite->SetTextureRect(emitter->eei.fTextureX, emitter->eei.fTextureY, emitter->eei.fTextureW, emitter->eei.fTextureH); SetupEE(); return true; } else if(oper == UIITEM_EE_FTEXTUREY_VALUE) { emitter->eei.fTextureY = fval; emitter->sprite->SetTextureRect(emitter->eei.fTextureX, emitter->eei.fTextureY, emitter->eei.fTextureW, emitter->eei.fTextureH); SetupEE(); return true; } else if(oper == UIITEM_EE_FTEXTUREW_VALUE) { emitter->eei.fTextureW = fval; emitter->sprite->SetTextureRect(emitter->eei.fTextureX, emitter->eei.fTextureY, emitter->eei.fTextureW, emitter->eei.fTextureH); SetupEE(); return true; } else if(oper == UIITEM_EE_FTEXTUREH_VALUE) { emitter->eei.fTextureH = fval; emitter->sprite->SetTextureRect(emitter->eei.fTextureX, emitter->eei.fTextureY, emitter->eei.fTextureW, emitter->eei.fTextureH); SetupEE(); return true; } else if(oper == UIITEM_EE_FHOTX_VALUE) { emitter->eei.fHotX = fval; emitter->sprite->SetHotSpot(emitter->eei.fHotX, emitter->eei.fHotY); SetupEE(); return true; } else if(oper == UIITEM_EE_FHOTY_VALUE) { emitter->eei.fHotY = fval; emitter->sprite->SetHotSpot(emitter->eei.fHotX, emitter->eei.fHotY); SetupEE(); return true; } else if(oper == UIITEM_EE_BLEND_VALUE) { if(ival >= 0 && ival < 8) { emitter->eei.blend = ival; emitter->sprite->SetBlendMode(ival); SetupEE(); return true; } } else if(oper == UIITEM_EE_BTRACE_VALUE) { if(ival) emitter->eei.bTrace = 1; else emitter->eei.bTrace = 0; SetupEE(); return true; } else if(oper == UIITEM_EE_BADJUSTDIRECTION_VALUE) { if(ival) emitter->eei.bAdjustDirection = 1; else emitter->eei.bAdjustDirection = 0; SetupEE(); return true; } return false; } bool EditorUI::EditEA() { if(isListNull()) return true; bool dwordmode = false; if(affector->eai.type == HGEEFFECT_AFFECTORTYPE_COLOR) dwordmode = true; if(oper == UIITEM_EA_NAFFECTORSTARTTIME_VALUE) { if(ival >= 0) { affector->eai.nAffectorStartTime = ival; if(affector->eai.nAffectorEndTime < ival) affector->eai.nAffectorEndTime = ival; SetupEA(); return true; } } else if(oper == UIITEM_EA_NAFFECTORENDTIME_VALUE) { if(ival >= 0) { affector->eai.nAffectorEndTime = ival; if(affector->eai.nAffectorStartTime > ival) affector->eai.nAffectorStartTime = ival; SetupEA(); return true; } } else if(oper == UIITEM_EA_NRANDOMPICKINTERVAL_VALUE) { if(ival >= 0) { affector->eai.nRandomPickInterval = ival; SetupEA(); return true; } } else if(oper == UIITEM_EA_FSTARTVALUEMIN_VALUE) { if(dwordmode) { affector->eai.fStartValueMin = *(float *)&uval; DWORD maxval = *(DWORD *)(&(affector->eai.fStartValueMax)); if(GETA(maxval) < GETA(uval) || GETR(maxval) < GETR(uval) || GETG(maxval) < GETG(uval) || GETB(maxval) < GETB(uval)) affector->eai.fStartValueMax = *(float *)&uval; } else { affector->eai.fStartValueMin = fval; if(affector->eai.fStartValueMax < fval) affector->eai.fStartValueMax = fval; } SetupEA(); return true; } else if(oper == UIITEM_EA_FSTARTVALUEMAX_VALUE) { if(dwordmode) { affector->eai.fStartValueMax = *(float *)&uval; DWORD minval = *(DWORD *)(&(affector->eai.fStartValueMin)); if(GETA(minval) > GETA(uval) || GETR(minval) > GETR(uval) || GETG(minval) > GETG(uval) || GETB(minval) > GETB(uval)) affector->eai.fStartValueMin = *(float *)&uval; } else { affector->eai.fStartValueMax = fval; if(affector->eai.fStartValueMin > fval) affector->eai.fStartValueMin = fval; } SetupEA(); return true; } else if(oper == UIITEM_EA_FENDVALUEMIN_VALUE) { if(dwordmode) { affector->eai.fEndValueMin = *(float *)&uval; DWORD maxval = *(DWORD *)(&(affector->eai.fEndValueMax)); if(GETA(maxval) < GETA(uval) || GETR(maxval) < GETR(uval) || GETG(maxval) < GETG(uval) || GETB(maxval) < GETB(uval)) affector->eai.fEndValueMax = *(float *)&uval; } else { affector->eai.fEndValueMin = fval; if(affector->eai.fEndValueMax < fval) affector->eai.fEndValueMax = fval; } SetupEA(); return true; } else if(oper == UIITEM_EA_FENDVALUEMAX_VALUE) { if(dwordmode) { affector->eai.fEndValueMax = *(float *)&uval; DWORD minval = *(DWORD *)(&(affector->eai.fEndValueMin)); if(GETA(minval) > GETA(uval) || GETR(minval) > GETR(uval) || GETG(minval) > GETG(uval) || GETB(minval) > GETB(uval)) affector->eai.fEndValueMin = *(float *)&uval; } else { affector->eai.fEndValueMax = fval; if(affector->eai.fEndValueMin > fval) affector->eai.fEndValueMin = fval; } SetupEA(); return true; } else if(oper == UIITEM_EA_FINCREMENTVALUEMIN_VALUE) { if(dwordmode) { affector->eai.fIncrementValueMin = *(float *)&uval; DWORD maxval = *(DWORD *)(&(affector->eai.fIncrementValueMax)); if(GETA(maxval) < GETA(uval) || GETR(maxval) < GETR(uval) || GETG(maxval) < GETG(uval) || GETB(maxval) < GETB(uval)) affector->eai.fIncrementValueMax = *(float *)&uval; } else { affector->eai.fIncrementValueMin = fval; if(affector->eai.fIncrementValueMax < fval) affector->eai.fIncrementValueMax = fval; } SetupEA(); return true; } else if(oper == UIITEM_EA_FINCREMENTVALUEMAX_VALUE) { if(dwordmode) { affector->eai.fIncrementValueMax = *(float *)&uval; DWORD minval = *(DWORD *)(&(affector->eai.fIncrementValueMin)); if(GETA(minval) > GETA(uval) || GETR(minval) > GETR(uval) || GETG(minval) > GETG(uval) || GETB(minval) > GETB(uval)) affector->eai.fIncrementValueMin = *(float *)&uval; } else { affector->eai.fIncrementValueMax = fval; if(affector->eai.fIncrementValueMin > fval) affector->eai.fIncrementValueMin = fval; } SetupEA(); return true; } else if(oper == UIITEM_EA_FINCREMENTSCALE_VALUE) { affector->eai.fIncrementScale = fval; SetupEA(); return true; } else if (oper == UIITEM_EA_FACCELERATION_VALUE) { if(dwordmode) { affector->eai.fAcceleration = *(float *)&uval; DWORD minval = *(DWORD *)(&(affector->eai.fAcceleration)); if(GETA(minval) > GETA(uval) || GETR(minval) > GETR(uval) || GETG(minval) > GETG(uval) || GETB(minval) > GETB(uval)) affector->eai.fAcceleration = *(float *)&uval; } else { affector->eai.fAcceleration = fval; if(affector->eai.fAcceleration > fval) affector->eai.fAcceleration = fval; } SetupEA(); return true; } else if(oper == UIITEM_EA_BUSESTARTVALUE_VALUE) { if(ival) affector->eai.bUseStartValue = 1; else affector->eai.bUseStartValue = 0; SetupEA(); return true; } else if(oper == UIITEM_EA_BUSEENDVALUE_VALUE) { if(ival) affector->eai.bUseEndValue = 1; else affector->eai.bUseEndValue = 0; SetupEA(); return true; } else if(oper == UIITEM_EA_TYPE_VALUE) { if(ival >= HGEEFFECT_AFFECTORTYPE_NONE && ival < HGEEFFECT_AFFECTORTYPE_END) { ZeroMemory(&(affector->eai), sizeof(hgeEffectAffectorInfo)); affector->eai.type = ival; SetupEA(); return true; } } return false; } void EditorUI::Render() { if(eres.bg) { // eres.bg->SetZ(0); eres.bg->RenderStretch(M_ACTIVECLIENT_LEFT, M_ACTIVECLIENT_TOP, M_ACTIVECLIENT_RIGHT, M_ACTIVECLIENT_BOTTOM); } hge->Gfx_RenderLine(mx-5, my, mx+5, my, 0xffffffff, zpos > 0 ? 0 : zpos); hge->Gfx_RenderLine(mx, my-5, mx, my+5, 0xffffffff, zpos > 0 ? 0 : zpos); if(eres.eff[ebnum]) { eres.eff[ebnum]->Render(); } if(eres.panel) { eres.panel->RenderStretch(M_ACTIVECLIENT_RIGHT, M_ACTIVECLIENT_TOP, M_CLIENT_RIGHT, M_ACTIVECLIENT_BOTTOM); } if(eres.button) { for(int i=0; i<UIITEMMAX; i++) { if(eres.iteminfo[i].state) { if(eres.iteminfo[i].state == UIITEM_STATE_NORMAL) eres.button->SetColor(0xff0000aa); else if(eres.iteminfo[i].state == UIITEM_STATE_SELECTED) eres.button->SetColor(0xff00aaaa); else if(eres.iteminfo[i].state == UIITEM_STATE_OVER) eres.button->SetColor(0xffaaaa00); eres.button->RenderStretch( eres.iteminfo[i].x + UIITEM_EDGE, eres.iteminfo[i].y + UIITEM_EDGE, eres.iteminfo[i].x + eres.iteminfo[i].w - UIITEM_EDGE, eres.iteminfo[i].y + eres.iteminfo[i].h - UIITEM_EDGE); } } } for(int i=0; i<UIITEMMAX; i++) { if(eres.iteminfo[i].state) { eres.font->printfb(eres.iteminfo[i].x, eres.iteminfo[i].y, eres.iteminfo[i].w, eres.iteminfo[i].h, HGETEXT_MIDDLE | HGETEXT_CENTER, "%s", eres.iteminfo[i].info); } } if(eres.font) { eres.font->printf(M_ACTIVECLIENT_RIGHT, M_ACTIVECLIENT_BOTTOM - UIITEM_FONT, HGETEXT_RIGHT, "%f", hge->Timer_GetFPS(35)); eres.font->printf(M_ACTIVECLIENT_LEFT, M_ACTIVECLIENT_BOTTOM - UIITEM_FONT, HGETEXT_LEFT, "(%d, %d, %d) nLives=%d", (int)mx, (int)my, (int)zpos, nlives); } }
[ "CBE7F1F65@e00939f0-95ee-11de-8df0-bd213fda01be" ]
[ [ [ 1, 2143 ] ] ]
c1b989ce49fb232b96b3cff256dc5462fe208a41
a92598d0a8a2e92b424915d2944212f2f13e7506
/PtRPG/PhotonLib/Common-cpp/inc/ValueObject.h
489df6ff5e94b8b38e0d8cf4f7c098915b7fd95a
[ "MIT" ]
permissive
peteo/RPG_Learn
0cc4facd639bd01d837ac56cf37a07fe22c59211
325fd1802b14e055732278f3d2d33a9577608c39
refs/heads/master
2021-01-23T11:07:05.050645
2011-12-12T08:47:27
2011-12-12T08:47:27
2,299,148
2
0
null
null
null
null
UTF-8
C++
false
false
16,721
h
/* Exit Games Common - C++ Client Lib * Copyright (C) 2004-2011 by Exit Games GmbH. All rights reserved. * http://www.exitgames.com * mailto:[email protected] */ #ifndef __VALUE_OBJECT_H #define __VALUE_OBJECT_H #include "ConfirmAllowed.h" #ifndef _EG_BREW_PLATFORM namespace ExitGames { #endif /* Summary Container class template for objects to be stored as values in a Hashtable. Description Please refer to <link Hashtable> for more information and an \example. */ template<typename Etype> class ValueObject : public Object { public: ValueObject(const ValueObject<Etype>& toCopy); ValueObject(const Object& obj); ValueObject(const Object* const obj); ValueObject(typename ConfirmAllowed<Etype>::type data); ~ValueObject(void); ValueObject<Etype>& operator=(const ValueObject<Etype>& toCopy); ValueObject<Etype>& operator=(const Object& toCopy); Etype getDataCopy(void); Etype* getDataAddress(void); private: typedef Object super; void convert(const Object* const obj, nByte type); }; template<typename Etype> class ValueObject<Etype*> : public Object { public: ValueObject(const ValueObject<Etype*>& toCopy); ValueObject(const Object& obj); ValueObject(const Object* const obj); ValueObject(typename ConfirmAllowed<Etype*>::type data, short size); ValueObject(typename ConfirmAllowed<Etype*>::type data, const short* const sizes); ~ValueObject(void); ValueObject<Etype*>& operator=(const ValueObject<Etype*>& toCopy); ValueObject<Etype*>& operator=(const Object& toCopy); Etype* getDataCopy(void); Etype** getDataAddress(void); private: typedef Object super; void convert(const Object* const obj, nByte type, unsigned int dimensions); }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CONSTRUCTORS // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* Summary Copy-Constructor. Creates an object out of a deep copy of its parameter. The parameter has to be of the same template overload as the \object, you want to create. Parameters toCopy : The object to copy. */ template<typename Etype> ValueObject<Etype>::ValueObject(const ValueObject<Etype> &toCopy) : Object(toCopy) { } /* Summary Constructor. Creates an object out of a deep copy of the passed <link ExitGames::Object, Object>&. If the type of the content of the passed object does not match the template overload of the object to create, an empty \object is created instead of a copy of the passed object, which leads to <link ExitGames::KeyObject::getDataCopy, getDataCopy()> and <link ExitGames::KeyObject::getDataAddress, getDataAddress()> returning 0. Parameters obj : The <link ExitGames::Object, Object>& to copy. */ template <typename Etype> ValueObject<Etype>::ValueObject(const Object& obj) { convert(&obj, ConfirmAllowed<Etype>::typeName); } template <typename Etype> ValueObject<Etype*>::ValueObject(const Object& obj) { convert(&obj, ConfirmAllowed<Etype*>::typeName, ConfirmAllowed<Etype*>::dimensions); } /* Summary Constructor. Creates an object out of a deep copy of the passed <link ExitGames::Object, Object>*. If the type of the content of the passed object does not match the template overload of the object to create, an empty \object is created instead of a copy of the passed object, which leads to <link ExitGames::KeyObject::getDataCopy, getDataCopy()> and <link ExitGames::KeyObject::getDataAddress, getDataAddress()> return 0. Parameters obj : The <link ExitGames::Object, Object>* to copy. */ template <typename Etype> ValueObject<Etype>::ValueObject(const Object* const obj) { convert(obj, ConfirmAllowed<Etype>::typeName); } template <typename Etype> ValueObject<Etype*>::ValueObject(const Object* const obj) { convert(obj, ConfirmAllowed<Etype*>::typeName, ConfirmAllowed<Etype*>::dimensions); } /* Summary Constructor. Creates an object out of a deep copy of the passed scalar Etype. Parameters data : The value to copy. Has to be of a supported type. */ template <typename Etype> ValueObject<Etype>::ValueObject(typename ConfirmAllowed<Etype>::type data) { COMPILE_TIME_ASSERT_TRUE_MSG(!ConfirmAllowed<Etype>::dimensions, ERROR_THIS_OVERLOAD_IS_ONLY_FOR_SCALAR_TYPES); set(&data, ConfirmAllowed<Etype>::typeName, ConfirmAllowed<Etype>::customTypeName, true); } /* Summary Constructor. Creates an object out of a deep copy of the passed single-dimensional Etype-array. Parameters data : The array to copy. size : The element count of data. */ template <typename Etype> ValueObject<Etype*>::ValueObject(typename ConfirmAllowed<Etype*>::type data, short size) { COMPILE_TIME_ASSERT_TRUE_MSG(ConfirmAllowed<Etype*>::dimensions==1, ERROR_THIS_OVERLOAD_IS_ONLY_FOR_1D_ARRAYS); set(data, ConfirmAllowed<Etype*>::typeName, ConfirmAllowed<Etype*>::customTypeName, size, true); } /* Summary Constructor. Creates an object out of a deep copy of the passed multi-dimensional Etype-array. Parameters data : The array to copy. sizes : The array of element counts for the different dimensions of data. */ template <typename Etype> ValueObject<Etype*>::ValueObject(typename ConfirmAllowed<Etype*>::type data, const short* const sizes) { COMPILE_TIME_ASSERT_TRUE_MSG((bool)ConfirmAllowed<Etype>::dimensions, ERROR_THIS_OVERLOAD_IS_ONLY_FOR_FOR_ARRAYS); set(data, ConfirmAllowed<Etype*>::typeName, ConfirmAllowed<Etype*>::customTypeName, ConfirmAllowed<Etype*>::dimensions, sizes, true); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // DESTRUCTOR // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* Summary Destructor.*/ template <typename Etype> ValueObject<Etype>::~ValueObject(void) { } template <typename Etype> ValueObject<Etype*>::~ValueObject(void) { } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // OPERATORS // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* Summary Operator = : Makes a deep copy of its right operand into its left operand. This overwrites old data in the left operand. */ template<typename Etype> ValueObject<Etype>& ValueObject<Etype>::operator=(const ValueObject<Etype>& toCopy) { return super::operator=(toCopy); } template<typename Etype> ValueObject<Etype*>& ValueObject<Etype*>::operator=(const ValueObject<Etype*>& toCopy) { return super::operator=(toCopy); } /* Summary Operator = : Makes a deep copy of its right operand into its left operand. This overwrites old data in the left operand. If the type of the content of the right operand does not match the template overload of the left operand, then the left operand stays unchanged. */ template<typename Etype> ValueObject<Etype>& ValueObject<Etype>::operator=(const Object& toCopy) { if(ConfirmAllowed<Etype>::typeName == toCopy.getType()) *((Object*)this) = toCopy; return *this; } template<typename Etype> ValueObject<Etype*>& ValueObject<Etype*>::operator=(const Object& toCopy) { if(ConfirmAllowed<Etype>::typeName == toCopy.getType() && ConfirmAllowed<Etype>::dimensions == toCopy.getDimensions()) *((Object*)this) = toCopy; return *this; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // getDataCopy // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* Summary \Returns a deep copy of the content of the object. If you \only need access to the content, while the object still exists, you can use <link ValueObject::getDataAddress, getDataAddress()> instead to avoid the deep copy. That is especially interesting for large content, of course. If successful, the template overloads for array types of this method allocate the data for the copy, so you have to free (for arrays of primitive types) or delete (for arrays of class objects) it, as soon, as you do not need the array anymore. All non-array copies free there memory automatically, as soon as they leave their scope, same as the single indices of the array, as soon, as the array is freed. In case of an error this function returns 0 for primitive return types and for arrays and empty objects for classes. Returns a deep copy of the content of the object if successful, 0 or an empty object otherwise. */ template <typename Etype> inline Etype ValueObject<Etype>::getDataCopy(void) { return (_type == EG_CUSTOM && !_dimensions)?**(Etype**)EG_Object_internal_duplicateData(*(Etype**)_data, EG_CUSTOM, (*(Etype**)_data)->TypeCode):0; } template <typename Etype> inline Etype* ValueObject<Etype*>::getDataCopy(void) { return (_type == EG_CUSTOM && _dimensions == 1)?*(Etype**)EG_Object_internal_duplicateDataArray(*(Etype**)_data, EG_CUSTOM, (*(Etype**)_data)->TypeCode, *_size):0; } template <> inline nByte ValueObject<nByte>::getDataCopy(void) { return (_type == EG_BYTE && !_dimensions)?*(nByte*)_data:0; } template <> inline short ValueObject<short>::getDataCopy(void) { return (_type == EG_SHORT && !_dimensions)?*(short*)_data:0; } template <> inline int ValueObject<int>::getDataCopy(void) { return (_type == EG_INTEGER && !_dimensions)?*(int*)_data:0; } template <> inline int64 ValueObject<int64>::getDataCopy(void) { return (_type == EG_LONG && !_dimensions)?*(int64*)_data:0; } template <> inline float ValueObject<float>::getDataCopy(void) { return (_type == EG_FLOAT && !_dimensions)?*(float*)_data:0; } template <> inline double ValueObject<double>::getDataCopy(void) { return (_type == EG_DOUBLE && !_dimensions)?*(double*)_data:0; } template <> inline bool ValueObject<bool>::getDataCopy(void) { return (_type == EG_BOOLEAN && !_dimensions)?*(bool*)_data:false; } template <> inline JString ValueObject<JString>::getDataCopy(void) { return (_type == EG_STRING && !_dimensions)?*(JString*)_data:JString(""); } template <> inline JVector<Object> ValueObject<JVector<Object> >::getDataCopy(void) { return (_type == EG_VECTOR && !_dimensions)?JVector<Object>(*(JVector<Object>*)_data):JVector<Object>(); } template <> inline Hashtable ValueObject<Hashtable>::getDataCopy(void) { return (_type == EG_HASHTABLE && !_dimensions)?Hashtable(*(Hashtable*)_data):Hashtable(); } template <> inline nByte* ValueObject<nByte*>::getDataCopy(void) { return (_type == EG_BYTE && _dimensions == 1)?(nByte*)EG_Object_internal_duplicateDataArray(_data, EG_BYTE, 0, *_size):0; } template <> inline short* ValueObject<short*>::getDataCopy(void) { return (_type == EG_SHORT && _dimensions == 1)?(short*)EG_Object_internal_duplicateDataArray(_data, EG_SHORT, 0, *_size):0; } template <> inline int* ValueObject<int*>::getDataCopy(void) { return (_type == EG_INTEGER && _dimensions == 1)?(int*)EG_Object_internal_duplicateDataArray(_data, EG_INTEGER, 0, *_size):0; } template <> inline int64* ValueObject<int64*>::getDataCopy(void) { return (_type == EG_LONG && _dimensions == 1)?(int64*)EG_Object_internal_duplicateDataArray(_data, EG_LONG, 0, *_size):0; } template <> inline float* ValueObject<float*>::getDataCopy(void) { return (_type == EG_FLOAT && _dimensions == 1)?(float*)EG_Object_internal_duplicateDataArray(_data, EG_FLOAT, 0, *_size):0; } template <> inline double* ValueObject<double*>::getDataCopy(void) { return (_type == EG_DOUBLE && _dimensions == 1)?(double*)EG_Object_internal_duplicateDataArray(_data, EG_DOUBLE, 0, *_size):0; } template <> inline bool* ValueObject<bool*>::getDataCopy(void) { return (_type == EG_BOOLEAN && _dimensions == 1)?(bool*)EG_Object_internal_duplicateDataArray(_data, EG_BOOLEAN, 0, *_size):0; } template <> inline JString* ValueObject<JString*>::getDataCopy(void) { if(_type == EG_STRING && _dimensions == 1) { JString* temp = new JString[*_size]; for(short i=0; i<*_size; i++) temp[i] = (((JString*)(_data))[i]); return temp; } else return 0; } template <> inline Hashtable* ValueObject<Hashtable*>::getDataCopy(void) { if(_type == EG_HASHTABLE && _dimensions == 1) { Hashtable* temp = new Hashtable[*_size]; for(short i=0; i<*_size; i++) temp[i] = (((Hashtable*)(_data))[i]); return temp; } else return 0; } template <> inline Object* ValueObject<Object*>::getDataCopy(void) { if(_type == EG_OBJECT && _dimensions == 1) { Object* temp = new Object[*_size]; for(short i=0; i<*_size; i++) temp[i] = (((Object*)(_data))[i]); return temp; } else return 0; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // getDataAddress // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* Summary \Returns the address of the original content of the object. If you need access to the data above lifetime of the object, call <link KeyObject::getDataCopy, getDataCopy()>. The return type is a pointer to the data, so it is a double-pointer, of course, for template overloads, which data already is a pointer. In case of an error, this method returns NULL. Returns the address of the original content of the object, if successful, NULL otherwise. */ template <typename Etype> Etype* ValueObject<Etype>::getDataAddress(void) { return (_type == ConfirmAllowed<Etype>::typeName && _dimensions == ConfirmAllowed<Etype>::dimensions)?(Etype*)(_type==EG_CUSTOM?_dimensions?_data:*(Etype**)_data:_dimensions?&_data:_data):NULL; } template <typename Etype> Etype** ValueObject<Etype*>::getDataAddress(void) { return (_type == ConfirmAllowed<Etype*>::typeName && _dimensions == ConfirmAllowed<Etype*>::dimensions)?(Etype**)(_type==EG_CUSTOM?_dimensions?_data:*(Etype**)_data:_dimensions?&_data:_data):NULL; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // INTERNALS // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Etype> void ValueObject<Etype>::convert(const Object* const obj, nByte type) { if(obj && type == obj->getType()) *((Object*)this) = *obj; else { _type = 0; _size = NULL; _dimensions = 0; _data = NULL; } } template<typename Etype> void ValueObject<Etype*>::convert(const Object* const obj, nByte type, unsigned int dimensions) { if(obj && type == obj->getType() && dimensions == obj->getDimensions()) *((Object*)this) = *obj; else { _type = 0; _size = NULL; _dimensions = 0; _data = NULL; } } #ifndef _EG_BREW_PLATFORM } #endif #endif
[ [ [ 1, 501 ] ] ]
8f582918eaa9fd8e9d065fc029fdae5b8fbc7015
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Common/Base/Memory/hkDebugMemorySnapshot.h
58b922a321f025ee409439392b0764f3d8d664e7
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,996
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_DEBUG_MEMORY_SNAPSHOT_H #define HK_DEBUG_MEMORY_SNAPSHOT_H #include <Common/Base/Memory/Memory/Debug/hkDebugMemory.h> class hkDebugMemorySnapshot { public: hkDebugMemorySnapshot():m_pointers(HK_NULL),m_info(HK_NULL),m_size(0) {} ~hkDebugMemorySnapshot() { reset(); } /// Empties out all allocations void reset(); /// Subtract all of the allocations in rhs void subtract(hkDebugMemorySnapshot& rhs); /// Sorts the pointers into ascending order void ascendingOrder(); void** m_pointers; hkDebugMemory::PointerInfo* m_info; int m_size; protected: static HK_FORCE_INLINE hkBool _comparePointers( void** a, void** b ) { return (char*)(*a) < (char*)(*b); } }; #endif // HK_DEBUG_MEMORY_SNAPSHOT_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 55 ] ] ]
c5b2aee847315e3a788ade0760ea0237d1f4dc07
f77f105963cd6447d0f392b9ee7d923315a82ac6
/Box2DandOgre/include/OgreGpuCommandBufferFlush.h
4f7f622521b79481996eea6f007c111c816af09d
[]
no_license
GKimGames/parkerandholt
8bb2b481aff14cf70a7a769974bc2bb683d74783
544f7afa462c5a25c044445ca9ead49244c95d3c
refs/heads/master
2016-08-07T21:03:32.167272
2010-08-26T03:01:35
2010-08-26T03:01:35
32,834,451
0
0
null
null
null
null
UTF-8
C++
false
false
945
h
#ifndef __GPUCOMMANDBUFFERFLUSH_H__ #define __GPUCOMMANDBUFFERFLUSH_H__ #include "OgrePrerequisites.h" #include "OgreFrameListener.h" namespace Ogre { /** Helper class which can assist you in making sure the GPU command buffer is regularly flushed, so in cases where the CPU is outpacing the GPU we do not hit a situation where the CPU suddenly has to stall to wait for more space in the buffer. */ class GpuCommandBufferFlush : public FrameListener { protected: bool mUseOcclusionQuery; typedef std::vector<HardwareOcclusionQuery*> HOQList; HOQList mHOQList; size_t mMaxQueuedFrames; size_t mCurrentFrame; bool mStartPull; bool mStarted; public: GpuCommandBufferFlush(); virtual ~GpuCommandBufferFlush(); void start(size_t maxQueuedFrames = 2); void stop(); bool frameStarted(const FrameEvent& evt); bool frameEnded(const FrameEvent& evt); }; } #endif
[ "mapeki@34afb35a-be5b-11de-bb5c-85734917f5ce" ]
[ [ [ 1, 41 ] ] ]
8e9040c4484d6ddb6a4abf2c0fe2d2827a456f3a
7f72fc855742261daf566d90e5280e10ca8033cf
/branches/full-calibration/ground/src/libs/opmapcontrol/src/core/opmaps.h
6389f03c1909597e3919696263f87312829ad0e2
[]
no_license
caichunyang2007/my_OpenPilot_mods
8e91f061dc209a38c9049bf6a1c80dfccb26cce4
0ca472f4da7da7d5f53aa688f632b1f5c6102671
refs/heads/master
2023-06-06T03:17:37.587838
2011-02-28T10:25:56
2011-02-28T10:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,886
h
/** ****************************************************************************** * * @file OPMaps.h * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. * @brief * @see The GNU Public License (GPL) Version 3 * @defgroup OPMapWidget * @{ * *****************************************************************************/ /* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef OPMaps_H #define OPMaps_H #include "debugheader.h" #include "memorycache.h" #include "rawtile.h" #include "cache.h" #include "accessmode.h" #include "languagetype.h" #include "cacheitemqueue.h" #include "tilecachequeue.h" #include "pureimagecache.h" #include "alllayersoftype.h" #include "urlfactory.h" //#include "point.h" namespace core { class OPMaps: public MemoryCache,public AllLayersOfType,public UrlFactory { public: ~OPMaps(); static OPMaps* Instance(); bool ImportFromGMDB(const QString &file); bool ExportToGMDB(const QString &file); /// <summary> /// timeout for map connections /// </summary> QByteArray GetImageFrom(const MapType::Types &type,const core::Point &pos,const int &zoom); bool UseMemoryCache(){return useMemoryCache;}//TODO void setUseMemoryCache(const bool& value){useMemoryCache=value;} void setLanguage(const LanguageType::Types& language){Language=language;}//TODO LanguageType::Types GetLanguage(){return Language;}//TODO AccessMode::Types GetAccessMode()const{return accessmode;} void setAccessMode(const AccessMode::Types& mode){accessmode=mode;} int RetryLoadTile; private: bool useMemoryCache; LanguageType::Types Language; AccessMode::Types accessmode; // PureImageCache ImageCacheLocal;//TODO Criar acesso Get Set TileCacheQueue TileDBcacheQueue; OPMaps(); OPMaps(OPMaps const&){} OPMaps& operator=(OPMaps const&){ return *this; } static OPMaps* m_pInstance; protected: // MemoryCache TilesInMemory; }; } #endif // OPMaps_H
[ "jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba" ]
[ [ [ 1, 92 ] ] ]
80927f12c0ed68ea816d0464d5704d161eba8d6f
3856c39683bdecc34190b30c6ad7d93f50dce728
/LastProject/Source/Input.h
846febecace5c4cf381aecdfd1a95e4e4ea14ea3
[]
no_license
yoonhada/nlinelast
7ddcc28f0b60897271e4d869f92368b22a80dd48
5df3b6cec296ce09e35ff0ccd166a6937ddb2157
refs/heads/master
2021-01-20T09:07:11.577111
2011-12-21T22:12:36
2011-12-21T22:12:36
34,231,967
0
0
null
null
null
null
UHC
C++
false
false
1,841
h
/** @file Input.h @date 2011/09/27 @author 백경훈 @brief 키보드, 마우스 처리 클래스 */ #ifndef _INPUT_H_ #define _INPUT_H_ class CInput : public CSingleton<CInput> { friend class CSingleton<CInput>; public: CInput(); virtual ~CInput(); VOID Clear(); HRESULT Create( HWND a_hWnd ); HRESULT Release(); VOID Update( FLOAT a_fCameraMoveSpeed, FLOAT a_fCameraRotateSpeed, FLOAT a_fFrameTime ); // Get D3DXVECTOR3& Get_Pos() { return m_vPos; } FLOAT& Get_MouseYRotate() { return m_fYRotate; } FLOAT& Get_MouseXRotate() { return m_fXRotate; } BOOL Get_Lbutton() { return ( m_bLbutton == TRUE ); } BOOL Get_Rbutton() { return ( m_bRbutton == TRUE ); } BOOL Get_ESCKey() { return ( m_bESCKey == TRUE ); } BOOL Get_Endbutton() { return ( m_bEndbutton ); } BOOL Get_Homebutton() { return ( m_bHomebutton ); } BOOL Get_F1button() { return ( m_bF1button == TRUE ); } BOOL Get_F8button() { return ( m_bF8button == TRUE ); } BOOL Get_F9button() { return ( m_bF9button == TRUE ); } BOOL Get_FunKey(INT nInput); BOOL Get_NumKey(INT nInput); // Set VOID EnableInput( BOOL bEnable ); private: HWND m_hWnd; ///< 윈도우 핸들 POINT m_MousePos; ///< 현재 마우스 위치 POINT m_MousePosOld; ///< 이전 마우스 위치 D3DXVECTOR3 m_vRotate; ///< 회전 값 D3DXVECTOR3 m_vPos; FLOAT m_fYRotate; FLOAT m_fXRotate; BOOL m_bLbutton; ///< 왼쪽 버튼 BOOL m_bRbutton; ///< 오른쪽 버튼 BOOL m_bESCKey; BOOL m_bEndbutton; BOOL m_bHomebutton; BOOL m_bF1button; BOOL m_bF8button; BOOL m_bF9button; BOOL m_bFunKey[12]; BOOL m_bNumKey[10]; D3DXMATRIXA16 m_matMatrix; BOOL m_bEnable; ///< 입력 활성화 VOID MouseMoveCenter(); }; #endif
[ "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0", "[email protected]@d02aaf57-2019-c8cd-d06c-d029ef2af4e0" ]
[ [ [ 1, 23 ], [ 25, 25 ], [ 31, 31 ], [ 46, 46 ], [ 48, 57 ], [ 60, 61 ], [ 66, 66 ], [ 71, 74 ] ], [ [ 24, 24 ], [ 26, 30 ], [ 32, 45 ], [ 47, 47 ], [ 58, 59 ], [ 62, 65 ], [ 67, 70 ] ] ]
b7aa3a0a94276fffc44e8df69c7b20ceebc152fd
822ab63b75d4d4e2925f97b9360a1b718b5321bc
/History/History.cpp
0742b607189db1c1c166494a7e53245e953acffb
[]
no_license
sriks/decii
71e4becff5c30e77da8f87a56383e02d48b78b28
02c58fbaea69c2448249710d13f2e774762da2c3
refs/heads/master
2020-05-17T23:03:27.822905
2011-12-16T07:29:38
2011-12-16T07:29:38
32,251,281
0
0
null
null
null
null
UTF-8
C++
false
false
740
cpp
#include "History.h" #include "qmlapplicationviewer.h" #include "HistoryEngine.h" struct HistoryPrivate { HistoryEngine* engine; QmlApplicationViewer* qmlViewer; ~HistoryPrivate() { delete qmlViewer; qmlViewer = NULL; } }; History::History(QObject *parent) : QObject(parent) { d = new HistoryPrivate; d->engine = new HistoryEngine(this); connect(d->engine,SIGNAL(updateReady(HistoryInfo*)),this,SLOT(onUpdateAvailable(HistoryInfo*))); d->qmlViewer = new QmlApplicationViewer; } History::~History() { delete d; } void History::startEngine() { d->engine->update(); } void History::onUpdateAvailable(HistoryInfo *info) { // notify qml view }
[ "srikanthsombhatla@016151e7-202e-141d-2e90-f2560e693586" ]
[ [ [ 1, 32 ] ] ]
0eb8567616ec89e4bb0a9386656ad84a3448b7bc
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2006-04-24/pcbnew/class_module.h
86803b4c8b7d6f595d01d0ea60e8b0375924e4f1
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
UTF-8
C++
false
false
4,135
h
/*******************************************************/ /* class_module.h : module description (excepted pads) */ /*******************************************************/ class Pcb3D_GLCanvas; class Struct3D_Master; /************************************/ /* Modules (footprints) description */ /* pad are in class_pad.xx */ /************************************/ /* Format des modules: Description generale Description segments contour Description textes Description pastilles */ /* Flags :*/ enum Mod_Attribut /* Attributs d'un module */ { MOD_DEFAULT = 0, /* Type default */ MOD_CMS = 1, /* Pour module apparaissant dans les fichiers de placement automatique (principalement modules CMS */ MOD_VIRTUAL = 2 /* Module virtuel constitue par un dessin sur circuit (connecteur, trou de percage..) */ }; /* flags for autoplace and autoroute (.m_ModuleStatus member) */ #define MODULE_is_LOCKED 0x01 /* module LOCKED: no autoplace allowed */ #define MODULE_is_PLACED 0x02 /* In autoplace: module automatically placed */ #define MODULE_to_PLACE 0x04 /* In autoplace: module waiting fot autoplace */ class MODULE: public EDA_BaseStruct { public: int m_Layer; // layer number wxPoint m_Pos; // Real coord on board D_PAD * m_Pads; /* Pad list (linked list) */ EDA_BaseStruct * m_Drawings; /* Graphic items list (linked list) */ Struct3D_Master * m_3D_Drawings; /* Pointeur sur la liste des elements de trace 3D*/ TEXTE_MODULE * m_Reference; // texte reference du composant (U34, R18..) TEXTE_MODULE * m_Value; // texte valeur du composant (74LS00, 22K..) wxString m_LibRef; /* nom du module en librairie */ int m_Attributs; /* Flags bits a bit ( voir enum Mod_Attribut ) */ int m_Orient ; /* orientation en 1/10 degres */ int flag ; /* flag utilise en trace rastnest et routage auto */ int m_ModuleStatus; /* For autoplace: flags (LOCKED, AUTOPLACED) */ EDA_Rect m_BoundaryBox ; /* position/taille du cadre de reperage (coord locales)*/ EDA_Rect m_RealBoundaryBox ; /* position/taille du module (coord relles) */ int m_PadNum; // Nombre total de pads int m_AltPadNum; // en placement auto Nombre de pads actifs pour // les calculs int m_CntRot90; // Placement auto: cout ( 0..10 ) de la rotation 90 degre int m_CntRot180; // Placement auto: cout ( 0..10 ) de la rotation 180 degre wxSize m_Ext; // marges de "garde": utilise en placement auto. float m_Surface; // surface du rectangle d'encadrement long m_Link; // variable temporaire ( pour editions, ...) long m_LastEdit_Time; // Date de la derniere modification du module (gestion de librairies) wxString m_Doc; // Texte de description du module wxString m_KeyWord; // Liste des mots cles relatifs au module public: MODULE(BOARD * parent); MODULE(MODULE * module); ~MODULE(void); void Copy(MODULE * Module); // Copy structure MODULE * Next(void) { return (MODULE *) Pnext; } void Set_Rectangle_Encadrement(void); /* mise a jour du rect d'encadrement en coord locales (orient 0 et origine = pos module) */ void SetRectangleExinscrit(void); /* mise a jour du rect d'encadrement et de la surface en coord reelles */ // deplacements void SetPosition(const wxPoint & newpos); void SetOrientation(int newangle); /* supprime du chainage la structure Struct */ void UnLink( void ); /* Readind and writing data on files */ int WriteDescr( FILE * File ); int Write_3D_Descr( FILE * File ); int ReadDescr( FILE * File, int * LineNum = NULL); int Read_3D_Descr( FILE * File, int * LineNum = NULL); /* drawing functions */ void Draw(WinEDA_DrawPanel * panel, wxDC * DC, const wxPoint & offset, int draw_mode); void Draw3D(Pcb3D_GLCanvas * glcanvas); void DrawEdgesOnly(WinEDA_DrawPanel * panel, wxDC * DC, const wxPoint & offset,int draw_mode); void DrawAncre(WinEDA_DrawPanel * panel, wxDC * DC, const wxPoint & offset, int dim_ancre, int draw_mode); /* miscellaneous */ void Display_Infos(WinEDA_BasePcbFrame * frame); };
[ "fcoiffie@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 108 ] ] ]
87d0315bb843fb3ca6888525d114b9aa919e01a8
2139c9f6c7d201e394631dfd54a3e658269e9e68
/Resources/OpenGL/FramebufferObject.h
96d7e019202b2ed25a2c932c780378c808dbc535
[]
no_license
OpenEngineDK/branches-PostProcessing
294b87604d8d8e73b12ab7a6fd704a83ca33f3c9
2497ce3879973c410469618d2cf01b051bd4edbb
refs/heads/master
2020-12-24T21:10:50.209919
2009-04-27T10:12:37
2009-04-27T10:12:37
58,073,279
0
0
null
null
null
null
ISO-8859-15
C++
false
false
3,473
h
#ifndef __FRAMEBUFFEROBJECT_H__ #define __FRAMEBUFFEROBJECT_H__ #include <Resources/IFramebufferObject.h> #include <Resources/IRenderBuffer.h> #include <Resources/ITexture2D.h> //#include "RenderBuffer.h" //#include "Texture2D.h" #include <Resources/PPEResourceException.h> #include <Logging/Logger.h> #include <Meta/OpenGL.h> namespace OpenEngine { namespace Resources { /** Objects of this class represents a Framebuffer object * @author Bjarke N. Laustsen */ class FramebufferObject : public IFramebufferObject { private: GLuint fboID; // max number of color-attachments this gfx-card allows GLint maxNumColorAttachments; // attached renderbuffers/textures (remembered, so they can be returned through the get functions) IImagePtr colorAttachments[16]; IImagePtr depthAttachment; IImagePtr stencilAttachment; // helper array - contains all the enums for the color attachment points static const GLenum colorAttachmentEnums[]; GLenum GetAttachmentType(GLenum attachmentEnum); GLuint GetAttachmentID(GLenum attachmentEnum); /* Since glPushAttrib/glPopAttrib doesn't work for FBOs and since the only setting we wish to preserve unchanged across methodcalls is the currently bound FBO (the methodcalls shouldnt have the sideeffect of changing this value of the OpenGL state), we use this way instead (See spec item (81))*/ GLint savedFboID; void GuardedBind(); // to avoid unwanted side effects void GuardedUnbind();// to avoid unwanted side effects public: FramebufferObject(); ~FramebufferObject(); void Bind(); void Unbind(); // note: no need to unbind between bind calls! // todo: use IImagePtr as argument to the attach-methods instead, to only have 3 functions. void AttachColorRenderBuffer (IRenderBufferPtr rb, int attachmentPoint); void AttachDepthRenderBuffer (IRenderBufferPtr rb); void AttachStencilRenderBuffer(IRenderBufferPtr rb); void AttachColorTexture(ITexture2DPtr tex, int attachmentPoint); void AttachDepthTexture(ITexture2DPtr tex); void AttachStencilTexture(ITexture2DPtr tex); void DetachColorAttachment (int attachmentPoint); // ok bare at brug rb'er? Eller skal man detache for den resource type der er bundet? void DetachDepthAttachment (); void DetachStencilAttachment(); /* must be called after all color attachments you want to render to are attached, and before drawing, to select which color bufs to render to */ /* the selected buffers will be remembered through bind, undbind (etc) calls, and applies to this FBO only! */ void SelectDrawBuffers(); // <- sets default (=all attached buffers are targets in order (incl. GL_NONE) (buf0=att0, buf1=att1, ...) - so COLOR0 in the shader corresponds to ATT0, etc) void SelectDrawBuffers(int attachmentPoint); // <- sets one color buffer as the target (evt. også hav version for array) int GetMaxNumColorAttachments(); int GetID(); // check framebuffer errors bool CheckFrameBufferStatus(); // get objects currently attached to this FBO IImagePtr GetColorAttachment(int attachmentPoint); // smart-pointer NULL if none IImagePtr GetDepthAttachment(); // smart-pointer NULL if none IImagePtr GetStencilAttachment(); // smart-pointer NULL if none }; } // NS Resources } // NS OpenEngine #endif
[ [ [ 1, 92 ] ] ]
fa6e52d87ae3e0bda0e0477ccc67ff6562d74b28
d397b0d420dffcf45713596f5e3db269b0652dee
/src/Lib/PropertySystem/Array.hpp
8456b96b11b8095e077b21de156f76ba016dabdf
[]
no_license
irov/Axe
62cf29def34ee529b79e6dbcf9b2f9bf3709ac4f
d3de329512a4251470cbc11264ed3868d9261d22
refs/heads/master
2021-01-22T20:35:54.710866
2010-09-15T14:36:43
2010-09-15T14:36:43
85,337,070
0
0
null
null
null
null
UTF-8
C++
false
false
594
hpp
# pragma once # include "Base.hpp" # include <vector> namespace AxeProperty { typedef std::vector<BasePtr> TVectorElements; class Array : public Base { PROPERTY_VISITOR_DECLARE() public: Array( const TypePtr & _type ); public: void clearValue(); public: void addElement( const BasePtr & _property ); const BasePtr & getElement( std::size_t _index ) const; public: const TVectorElements & getElements() const; std::size_t countElement() const; protected: TVectorElements m_array; }; typedef AxeHandle<Array> ArrayPtr; }
[ "yuriy_levchenko@b35ac3e7-fb55-4080-a4c2-184bb04a16e0" ]
[ [ [ 1, 35 ] ] ]
10d70c033d4b2d30647530bc8289e1a29f92e2f9
e2c533535bebf3b57db8e09f260ed65b5679f61c
/Touchy/Touchy.h
0dcd711aa34dbad9c3f6dcac1117a7b49f7fad7e
[]
no_license
richy486/drumkitsim
bbfb24e1a83cc09dd761b585e180219a0c42ec75
cdb27629aac834742a3638404f00f6ff073d8fab
refs/heads/master
2020-05-17T13:21:37.315947
2009-07-29T12:55:55
2009-07-29T12:55:55
32,398,859
0
0
null
null
null
null
UTF-8
C++
false
false
362
h
// Touchy.h #pragma once #include "SynKit.h" using namespace System; namespace Touchy { public ref class TouchyFeely { // TODO: Add your methods for this class here. public: TouchyFeely(); ~TouchyFeely(); !TouchyFeely(); System::Boolean InitializeTouchPad(); private: ISynAPI* m_pAPI; ISynDevice* m_pDevice; }; }
[ "richy486@c710760a-7c2d-11de-acf3-6b2d83488292" ]
[ [ [ 1, 25 ] ] ]
2e3e1211eb204ea2170d240c5fc6b0a78fe9865f
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
/sense/urg_server_t.hpp
39a9297b040887fb7d7041dbd21d35ea79cdcc3c
[]
no_license
chenbk85/alcordev
41154355a837ebd15db02ecaeaca6726e722892a
bdb9d0928c80315d24299000ca6d8c492808f1d5
refs/heads/master
2021-01-10T13:36:29.338077
2008-10-22T15:57:50
2008-10-22T15:57:50
44,953,286
0
1
null
null
null
null
UTF-8
C++
false
false
1,186
hpp
#ifndef urg_server_t_H_INCLUDED #define urg_server_t_H_INCLUDED #include <alcor/core/server_base_t.hpp> #include <alcor/core/iniWrapper.h> #include "urg_laser_t.hpp" #include "urg_server_data_t.hpp" namespace all { namespace sense { class urg_server_t:public server_base_t { public: urg_server_t(char* ini_file="config/urg_server.ini"); void set_laser_on(client_connection_ptr_t, net_packet_ptr_t); void set_laser_off(client_connection_ptr_t, net_packet_ptr_t); void set_d_mode(client_connection_ptr_t, net_packet_ptr_t); void set_s_mode(client_connection_ptr_t, net_packet_ptr_t); void do_scan(client_connection_ptr_t, net_packet_ptr_t); void do_multiple_scan(client_connection_ptr_t, net_packet_ptr_t); void start_continous_scan(client_connection_ptr_t, net_packet_ptr_t); void stop_continous_scan(client_connection_ptr_t, net_packet_ptr_t); private: void send_scan_data(all::sense::urg_scan_data_ptr, client_connection_ptr_t); void send_multiple_scan_data(all::sense::urg_scan_data_ptr, client_connection_ptr_t); private: urg_laser_t _urg; iniWrapper _ini_config; urg_server_data_t _urg_data; }; }} #endif
[ "stefano.marra@1c7d64d3-9b28-0410-bae3-039769c3cb81" ]
[ [ [ 1, 45 ] ] ]
c5d864dc03a29a952e3a71c85f034089b2a0e1b2
d609fb08e21c8583e5ad1453df04a70573fdd531
/trunk/开发库/include/HHtmlCtrl.h
19729d99604354a78a9457de891d77746324150a
[]
no_license
svn2github/openxp
d68b991301eaddb7582b8a5efd30bc40e87f2ac3
56db08136bcf6be6c4f199f4ac2a0850cd9c7327
refs/heads/master
2021-01-19T10:29:42.455818
2011-09-17T10:27:15
2011-09-17T10:27:15
21,675,919
0
1
null
null
null
null
GB18030
C++
false
false
774
h
#ifndef __HHTEMLCTRL__H__ #define __HHTEMLCTRL__H__ #pragma once #include <afxhtml.h> #include <afxadv.h> #include <afxcview.h> #define HTML_OPEN_VIEW 0x0001 //使用HtmlView在对话框中打开 #define HTML_OPEN_DEFAULT 0x0002 //使用默认浏览器打开 #define HTML_OPEN_DIALOG 0x0003 //使用HtmlDialog打开 class TEMPLATE_CONTROL_API HHtmlCtrl : public CHtmlView { public: HHtmlCtrl(); virtual ~HHtmlCtrl(); BOOL CreateFromStatic(UINT nID, CWnd* pParent); void OpenURL(LPCTSTR lpszURL,UINT nOpenType=HTML_OPEN_VIEW); protected: virtual void PostNcDestroy(); afx_msg void OnDestroy(); afx_msg int OnMouseActivate(CWnd* pDesktopWnd, UINT nHitTest, UINT msg); DECLARE_MESSAGE_MAP(); DECLARE_DYNAMIC(HHtmlCtrl) }; #endif
[ "[email protected]@f92b348d-55a1-4afa-8193-148a6675784b" ]
[ [ [ 1, 28 ] ] ]
847dd36c739e6c384c0f0d96476d2fa33c6c6219
01c236af2890d74ca5b7c25cec5e7b1686283c48
/Src/HumanPlayer.cpp
52462cc4d62f7b7538c28ac3e308b6797968373a
[ "MIT" ]
permissive
muffinista/palm-pitch
80c5900d4f623204d3b837172eefa09c4efbe5e3
aa09c857b1ccc14672b3eb038a419bd13abc0925
refs/heads/master
2021-01-19T05:43:04.740676
2010-07-08T14:42:18
2010-07-08T14:42:18
763,958
1
0
null
null
null
null
UTF-8
C++
false
false
544
cpp
#include "HumanPlayer.h" HumanPlayer::HumanPlayer() { } HumanPlayer::HumanPlayer(char c) : Player(c, "human") { } HumanPlayer::HumanPlayer(char c, CString name) : Player(c, name) { } HumanPlayer::~HumanPlayer() { } /* when human plays Card */ Boolean HumanPlayer::PickCard(Trick * trk) { return false; } Int16 HumanPlayer::BeginBidProcess(Player *dealer, Player *current_winner) { return bid; } // function for setting trump if player wins bid Card::suit_t HumanPlayer::Trump() { return bestSuit; }
[ [ [ 1, 29 ] ] ]
aca60575248a2b64bd1ddad1555aa0a532b969a1
ba200ae9f30b89d1e32aee6a6e5ef2c991cee157
/trunk/Gosu/WinUtility.hpp
b7338f309b6aa6d54efe729b5ada7bc0907a54cc
[ "MIT" ]
permissive
clebertavares/gosu
1d5fd08d22825d18f2840dfe1c53c96f700b665f
e534e0454648a4ef16c7934d3b59b80ac9ec7a44
refs/heads/master
2020-04-08T15:36:38.697104
2010-02-20T16:57:25
2010-02-20T16:57:25
537,484
1
0
null
null
null
null
UTF-8
C++
false
false
2,664
hpp
//! \file WinUtility.hpp //! Contains some functions which are used to implement Gosu on Windows and //! might be useful for advanced users who try to integrate Gosu in a Win32 //! application. #ifndef GOSU_WINUTILITY_HPP #define GOSU_WINUTILITY_HPP #include <windows.h> #include <Gosu/Platform.hpp> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> #include <string> namespace Gosu { //! Implementation helpers for the Windows platform. namespace Win { //! Returns the instance handle of the application. HINSTANCE instance(); //! Blocking function which waits for the next message, processes it, //! then returns. void handleMessage(); //! Non-blocking function which processes all waiting messages but does //! not wait for further incoming messages. void processMessages(); //! Registers a function to be called by handleMessage and //! processMessages. Every message is passed to the hooks and not //! processed further if any hook function returns true. void registerMessageHook(const boost::function<bool (MSG&)>& hook); //! Throws an exception according to the error which GetLastError() //! returns, optionally prefixed with "While (action), the following //! error occured: ". GOSU_NORETURN void throwLastError(const std::string& action = ""); //! Small helper function that throws an exception whenever the value //! passed through is false. Note that this doesn't make sense for all //! Windows API functions, but for most of them. template<typename T> inline T check(T valToCheck, const std::string& action = "") { if (!valToCheck) throwLastError(action); return valToCheck; } // IMPR: Why can't I use mem_fn for releasing objects even though it is // shown like that in the shared_ptr documentation? template<typename T> void releaseComPtr(T* ptr) { ptr->Release(); } //! Small helper function that transfers ownership of a COM interface //! to a boost::shared_ptr. template<typename T> inline boost::shared_ptr<T> shareComPtr(T* ptr) { return boost::shared_ptr<T>(ptr, releaseComPtr<T>); } //! Returns the executable's filename. std::wstring appFilename(); //! Returns the executable's containing directory. std::wstring appDirectory(); } } #endif
[ [ [ 1, 76 ] ] ]
3ded980cd9a251365872889141a7cca02fffface
6e563096253fe45a51956dde69e96c73c5ed3c18
/Sockets/File.cpp
e8cc271754bef443fe20529197a64edb4116b0df
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,084
cpp
/** \file File.cpp ** \date 2005-04-25 ** \author [email protected] **/ /* Copyright (C) 2004-2009 Anders Hedstrom This library is made available under the terms of the GNU GPL, with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. If you would like to use this library in a closed-source application, a separate license agreement is available. For information about the closed-source license agreement for the C++ sockets library, please visit http://www.alhem.net/Sockets/license.html and/or email [email protected]. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include "File.h" #ifdef SOCKETS_NAMESPACE namespace SOCKETS_NAMESPACE { #endif File::File() :m_fil(NULL) ,m_rptr(0) ,m_wptr(0) { } File::~File() { fclose(); } bool File::fopen(const std::string& path, const std::string& mode) { m_path = path; m_mode = mode; m_fil = ::fopen(path.c_str(), mode.c_str()); return m_fil ? true : false; } void File::fclose() const { if (m_fil) { ::fclose(m_fil); m_fil = NULL; } } size_t File::fread(char *ptr, size_t size, size_t nmemb) const { size_t r = 0; if (m_fil) { fseek(m_fil, m_rptr, SEEK_SET); r = ::fread(ptr, size, nmemb, m_fil); m_rptr = ftell(m_fil); } return r; } size_t File::fwrite(const char *ptr, size_t size, size_t nmemb) { size_t r = 0; if (m_fil) { fseek(m_fil, m_wptr, SEEK_SET); r = ::fwrite(ptr, size, nmemb, m_fil); m_wptr = ftell(m_fil); } return r; } char *File::fgets(char *s, int size) const { char *r = NULL; if (m_fil) { fseek(m_fil, m_rptr, SEEK_SET); r = ::fgets(s, size, m_fil); m_rptr = ftell(m_fil); } return r; } void File::fprintf(const char *format, ...) { if (!m_fil) return; va_list ap; va_start(ap, format); fseek(m_fil, m_rptr, SEEK_SET); vfprintf(m_fil, format, ap); m_rptr = ftell(m_fil); va_end(ap); } off_t File::size() const { struct stat st; if (stat(m_path.c_str(), &st) == -1) { return 0; } return st.st_size; } bool File::eof() const { if (m_fil) { if (feof(m_fil)) return true; } return false; } void File::reset_read() const { m_rptr = 0; } void File::reset_write() { m_wptr = 0; } #ifdef SOCKETS_NAMESPACE } #endif
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 169 ] ] ]
2ae1306d6fdbabb9c4ed763c8fe139244709f092
be7df324d5509c7ebb368c884b53ea9445d32e4f
/GUI/dicomConvert/dcmDialog.cpp
5c137d13836e9eccd4530880baff31285ecb720e
[]
no_license
shadimsaleh/thesis.code
b75281001aa0358282e9cceefa0d5d0ecfffdef1
085931bee5b07eec9e276ed0041d494c4a86f6a5
refs/heads/master
2021-01-11T12:20:13.655912
2011-10-19T13:34:01
2011-10-19T13:34:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,930
cpp
#include "dcmDialog.h" #include <QString> #include "dcmtk/config/osconfig.h" #include "dcmtk/dcmdata/dctk.h" // #include "dcmDataSeries.h" #include "saveVolumeDialog.h" // analyze support ... #include "dbh.h" dcmDialog::dcmDialog(QWidget *parent) : QDialog(parent) { ui.setupUi(this); ui.m_pPreview->setColumnCount(6); // ui.m_pPreview->setIconSize(QSize(64, 64)); // ui.m_pPreview->setIconSize(QSize(24, 24)); QStringList headers; headers << tr("Subject") << tr("Protocol") << tr("Study ID") << tr("Series") << tr("Dimensions") << tr("kV"); ui.m_pPreview->setHeaderLabels(headers); ui.m_pPreview->setSelectionMode(QAbstractItemView::ExtendedSelection); ui.m_pPreview->setSortingEnabled(true); ui.m_pPreview->sortByColumn(3); connect( ui.m_pPreview, SIGNAL(itemExpanded ( QTreeWidgetItem * )), this, SLOT(resizeCols()) ); connect( ui.m_pPreview, SIGNAL(itemSelectionChanged ()), this, SLOT(updatePreview()) ); connect( ui.m_pDirBrowseBut, SIGNAL( clicked() ), this, SLOT( changeDir())); // connect( ui.m_pScanBut, SIGNAL( clicked() ), this, SLOT( scanDir())); connect( ui.m_pScanBut, SIGNAL( clicked() ), this, SLOT( scanDirRecursive())); connect( ui.m_pSave3dBut, SIGNAL( clicked() ), this, SLOT( save3D())); connect( ui.m_pSave4dBut, SIGNAL( clicked() ), this, SLOT( save4D())); } void dcmDialog::changeDir() { // get new directory ... and set it in the list view ... QString s = QFileDialog::getExistingDirectory( this, "Choose a directory", QDir::currentPath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); // now into the comboBox. ui.m_pDcmDir->addItem(s); ui.m_pDcmDir->setCurrentIndex(ui.m_pDcmDir->count() - 1); } bool dcmDialog::scanDirRecursive() { // re-implemented from dcmDialog. // need a list of stringlists ... QStringList patients; QStringList files; dseries.clear(); QString patient, protocol, ppos; int study, series; int x,y; int numFiles = 0, i=0; QDir directory( ui.m_pDcmDir->currentText() ); // need to scan the directory recursively and get the total number and list of files ... scanDir(directory.absolutePath(), files); numFiles = files.size(); // qDebug("HS: Files in all subdirs: %d", numFiles); // std::ofstream out("files.txt"); QProgressDialog progress("Scanning DICOM directory...", "Abort Scan", 0, numFiles, this); progress.setValue(i); foreach(QString fname, files) { progress.setValue(i++); // progress.setLabelText(filestring); qApp->processEvents(); if (progress.wasCanceled()) break; // filenames to avoid (mostly directories) ... if ( fname.contains(".calib", Qt::CaseInsensitive) || fname.contains(".avi", Qt::CaseInsensitive) || fname.contains("thumbnails", Qt::CaseInsensitive) || fname.contains("dti", Qt::CaseInsensitive) || fname.contains("dicomdir", Qt::CaseInsensitive) ) continue; // out << qPrintable(fname) << std::endl; // std::cout << qPrintable(fname) << std::endl; // continue; DcmFileFormat fileformat; OFCondition status = fileformat.loadFile(fname.toLatin1()); if (status.good()) { OFString tmpStr; if (fileformat.getDataset()->findAndGetOFString(DCM_PatientsName, tmpStr).good()) { patient = tmpStr.c_str (); // clean up up the patient name ... patient = patient.toLower(); patient = patient.split("^").join(", "); // patient.replace(QRegExp("^(.*), (.*)$"), "\\2 \\1"); if ( ! patients.contains(patient, Qt::CaseInsensitive) ) patients.append(patient); } else { patient = "MissingTag"; if ( ! patients.contains(patient, Qt::CaseInsensitive) ) patients.append(patient); qDebug("Error: cannot access Patient's Name!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_ProtocolName, tmpStr).good()) { protocol = tmpStr.c_str (); } else { protocol = "MissingTag"; qDebug("Error: cannot access Protocol Name!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_StudyID, tmpStr).good()) { study = atoi(tmpStr.c_str ()); } else { study = 1; qDebug("Error: cannot access Study Name!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_SeriesNumber, tmpStr).good()) { series = atoi(tmpStr.c_str ()); } else { series = 1; qDebug("Error: cannot access Series Name!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_SliceLocation, tmpStr).good()) { ppos = QString(tmpStr.c_str ()); } else { ppos = "0"; qDebug("Error: cannot access Patient position!"); } // kV unsigned int kvp; if (fileformat.getDataset()->findAndGetOFString(DCM_KVP, tmpStr).good()) { kvp = atoi(tmpStr.c_str ()); } else { kvp = 0; qDebug("Error: cannot access XRay KVP !"); } dcmDataSeries dsr(patient, protocol, study, series, ppos, kvp); // search to see if dsr is already in the list ... int idx = dseries.indexOf(dsr); if ( idx == -1){ dsr.files << fname; // DIMENSIONS if (fileformat.getDataset()->findAndGetOFString(DCM_Rows, tmpStr).good()) { y = atoi(tmpStr.c_str ()); } else { y=0; qDebug("Error: cannot access Image rows !"); } if (fileformat.getDataset()->findAndGetOFString(DCM_Columns, tmpStr).good()) { x = atoi(tmpStr.c_str ()); } else { x=0; qDebug("Error: cannot access Image Columns!"); } dsr.x = x; dsr.y = y; // data type ... unsigned int ba; if (fileformat.getDataset()->findAndGetOFString(DCM_BitsAllocated, tmpStr).good()) { ba = atoi(tmpStr.c_str ()); } else { ba=8; qDebug("Error: cannot access Image bits allocated !"); } // preview ... unsigned char *prvu = new unsigned char[4*x*y]; if (ba > 8) { const Uint16 *pixelData = NULL; unsigned long count = 0; if (fileformat.getDataset()->findAndGetUint16Array(DCM_PixelData, pixelData, &count).good()) { int _max = 0; for (int i=0; i<x*y; i++) if (_max < pixelData[i]) _max = pixelData[i]; float fac = 255.0/_max; // std::cout << "Max is " << _max << " and fac is " << fac << std::endl; /* convert the pixel data */ for (int i=0; i<x*y; i++) { prvu[4*i] = (unsigned char ) (fac*pixelData[i] ) ; prvu[4*i+1] = (unsigned char) (fac*pixelData[i]) ; prvu[4*i+2] = (unsigned char) (fac*pixelData[i]) ; prvu[4*i+3] = (unsigned char) (fac*pixelData[i]) ; } } else { qDebug("Error reading pixel data"); } } else { const Uint8 *pixelData = NULL; unsigned long count = 0; if (fileformat.getDataset()->findAndGetUint8Array(DCM_PixelData, pixelData, &count).good()) { for (int i=0; i<x*y; i++) { prvu[4*i] = pixelData[i] ; prvu[4*i+1] = pixelData[i] ; prvu[4*i+2] = pixelData[i] ; prvu[4*i+3] = pixelData[i] ; } } else { qDebug("Error reading pixel data"); } } // set this dsr.preview = prvu; dseries.append(dsr); } else { dseries[idx].files << fname; } } else qDebug("Error: cannot read DICOM file (%s)", status.text()); } progress.setValue(numFiles); // out.close(); // instead of std::out .. insert them into the list view ... ui.m_pPreview->clear(); QList<QTreeWidgetItem*> _patientList; // insert all patients as top level widgetitems ... for (i=0; i<patients.size(); i++) { QTreeWidgetItem *pat = new QTreeWidgetItem( ui.m_pPreview ); pat->setText(0, patients[i]); pat->setIcon(0, QIcon(QPixmap(":/res/images/patient.png"))); // pat->setText(1, QString("dummy")); _patientList.append(pat); } // QTreeWidgetItem *lastItem; // now enter all the protocols ... char my_series[100]; for (i=0; i<dseries.size(); i++) { int _pid = patients.indexOf(dseries[i].patient); QTreeWidgetItem *srs = new QTreeWidgetItem( _patientList[_pid] ); srs->setText(0, dseries[i].patient); srs->setText(1, dseries[i].protocol); srs->setText(2, QString::number(dseries[i].study)); sprintf(my_series, "%.2d", dseries[i].series); srs->setText(3, QString(my_series)); // srs->setText(3, QString::number(dseries[i].series)); srs->setText(4, QString("%1x%2x%3").arg(dseries[i].x).arg(dseries[i].y).arg(dseries[i].files.size())); srs->setText(5, QString::number(dseries[i].kvp)); // srs->setText(5, QString::number(frameCnt)); // show a preview as the icon ... QImage prv( dseries[i].preview, dseries[i].x, dseries[i].y, QImage::Format_RGB32 ); srs->setData(0, Qt::ToolTipRole, QPixmap::fromImage(prv) ); srs->setData(0, Qt::WhatsThisRole, dseries[i].ppos ); // free memory ... // delete [] dseries[i].preview; srs->setIcon(0, QIcon(QPixmap(":/res/images/data.png"))); // lastItem = srs; // srs->setIcon(0, QIcon(QPixmap::fromImage(prv ))); // ui.m_lblPreview->setPixmap( QPixmap::fromImage( prv ) ); } return true; } void dcmDialog::scanDir() { // get the current Index ... dcmDir.setPath( ui.m_pDcmDir->currentText() ); QStringList qsl; qsl += "*"; // need a list of stringlists ... QStringList patients; dseries.clear(); QString fname; QString patient, protocol, ppos; int study, series; int x,y; int numFiles = 0, i=0; foreach(QString filestring, dcmDir.entryList(qsl, QDir::Files)) numFiles++; qDebug("Files in dir: %d", numFiles); QProgressDialog progress("Scanning DICOM directory...", "Abort Scan", 0, numFiles, this); progress.setValue(i); foreach(QString filestring, dcmDir.entryList(qsl, QDir::Files)) { progress.setValue(i++); // progress.setLabelText(filestring); fname = dcmDir.filePath(filestring); qApp->processEvents(); if (progress.wasCanceled()) break; DcmFileFormat fileformat; OFCondition status = fileformat.loadFile(fname.toLatin1()); if (status.good()) { OFString tmpStr; if (fileformat.getDataset()->findAndGetOFString(DCM_PatientsName, tmpStr).good()) { patient = tmpStr.c_str (); // clean up up the patient name ... patient = patient.toLower(); patient = patient.split("^").join(", "); // patient.replace(QRegExp("^(.*), (.*)$"), "\\2 \\1"); if ( ! patients.contains(patient, Qt::CaseInsensitive) ) patients.append(patient); } else { qDebug("Error: cannot access Patient's Name!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_ProtocolName, tmpStr).good()) { protocol = tmpStr.c_str (); } else { qDebug("Error: cannot access Protocol Name!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_StudyID, tmpStr).good()) { study = atoi(tmpStr.c_str ()); } else { qDebug("Error: cannot access Study Name!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_SeriesNumber, tmpStr).good()) { series = atoi(tmpStr.c_str ()); } else { qDebug("Error: cannot access Series Name!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_SliceLocation, tmpStr).good()) { ppos = QString(tmpStr.c_str ()); } else { qDebug("Error: cannot access Patient position!"); } // kV unsigned int kvp; if (fileformat.getDataset()->findAndGetOFString(DCM_KVP, tmpStr).good()) { kvp = atoi(tmpStr.c_str ()); } else { kvp = 0; qDebug("Error: cannot access XRay KVP !"); } dcmDataSeries dsr(patient, protocol, study, series, ppos, kvp); // search to see if dsr is already in the list ... int idx = dseries.indexOf(dsr); if ( idx == -1){ dsr.files << filestring; // DIMENSIONS if (fileformat.getDataset()->findAndGetOFString(DCM_Rows, tmpStr).good()) { y = atoi(tmpStr.c_str ()); } else { qDebug("Error: cannot access Image rows !"); } if (fileformat.getDataset()->findAndGetOFString(DCM_Columns, tmpStr).good()) { x = atoi(tmpStr.c_str ()); } else { qDebug("Error: cannot access Image Columns!"); } dsr.x = x; dsr.y = y; // data type ... unsigned int ba; if (fileformat.getDataset()->findAndGetOFString(DCM_BitsAllocated, tmpStr).good()) { ba = atoi(tmpStr.c_str ()); } else { ba=8; qDebug("Error: cannot access Image bits allocated !"); } // preview ... unsigned char *prvu = new unsigned char[4*x*y]; if (ba > 8) { const Uint16 *pixelData = NULL; unsigned long count = 0; if (fileformat.getDataset()->findAndGetUint16Array(DCM_PixelData, pixelData, &count).good()) { int _max = 0; for (int i=0; i<x*y; i++) if (_max < pixelData[i]) _max = pixelData[i]; float fac = 255.0/_max; // std::cout << "Max is " << _max << " and fac is " << fac << std::endl; /* convert the pixel data */ for (int i=0; i<x*y; i++) { prvu[4*i] = (unsigned char ) (fac*pixelData[i] ) ; prvu[4*i+1] = (unsigned char) (fac*pixelData[i]) ; prvu[4*i+2] = (unsigned char) (fac*pixelData[i]) ; prvu[4*i+3] = (unsigned char) (fac*pixelData[i]) ; } } else { qDebug("Error reading pixel data"); } } else { const Uint8 *pixelData = NULL; unsigned long count = 0; if (fileformat.getDataset()->findAndGetUint8Array(DCM_PixelData, pixelData, &count).good()) { for (int i=0; i<x*y; i++) { prvu[4*i] = pixelData[i] ; prvu[4*i+1] = pixelData[i] ; prvu[4*i+2] = pixelData[i] ; prvu[4*i+3] = pixelData[i] ; } } else { qDebug("Error reading pixel data"); } } // set this dsr.preview = prvu; dseries.append(dsr); } else { dseries[idx].files << filestring; } } else qDebug("Error: cannot read DICOM file (%s)", status.text()); } progress.setValue(numFiles); // instead of std::out .. insert them into the list view ... ui.m_pPreview->clear(); QList<QTreeWidgetItem*> _patientList; // insert all patients as top level widgetitems ... for (i=0; i<patients.size(); i++) { QTreeWidgetItem *pat = new QTreeWidgetItem(ui.m_pPreview); pat->setText(0, patients[i]); pat->setIcon(0, QIcon(QPixmap(":/res/images/patient.png"))); // pat->setText(1, QString("dummy")); _patientList.append(pat); } // now enter all the protocols ... char my_series[100]; for (i=0; i<dseries.size(); i++) { int _pid = patients.indexOf(dseries[i].patient); QTreeWidgetItem *srs = new QTreeWidgetItem( _patientList[_pid] ); srs->setText(0, dseries[i].patient); srs->setText(1, dseries[i].protocol); srs->setText(2, QString::number(dseries[i].study)); sprintf(my_series, "%.2d", dseries[i].series); srs->setText(3, QString(my_series)); // srs->setText(3, QString::number(dseries[i].series)); srs->setText(4, QString::number(dseries[i].files.size())); srs->setText(5, QString::number(dseries[i].kvp)); // show a preview as the icon ... QImage prv( dseries[i].preview, dseries[i].x, dseries[i].y, QImage::Format_RGB32 ); srs->setData(0, Qt::ToolTipRole, QPixmap::fromImage(prv) ); srs->setIcon(0, QIcon(QPixmap(":/res/images/data.png"))); // srs->setIcon(0, QIcon(QPixmap::fromImage(prv ))); // ui.m_lblPreview->setPixmap( QPixmap::fromImage( prv ) ); } // resize columns ... ui.m_pPreview->resizeColumnToContents(2); ui.m_pPreview->resizeColumnToContents(0); ui.m_pPreview->resizeColumnToContents(1); } void dcmDialog::resizeCols() { for (int i=0; i<5; i++) ui.m_pPreview->resizeColumnToContents(i); } void dcmDialog::save3D() { // Lets save 3D ... :) QList<dcmDataSeries> _saveseries; // QList<dcmDataSeries> _series; dcmDataSeries dsr; bool ok; FILE *fp1; // first get the selection from m_pPreview ... QList<QTreeWidgetItem *> items = ui.m_pPreview->selectedItems(); if ( ! items.size() ) { qDebug("No Items selected"); return; } // this can be changed into a list of dcmDataSeries ... for (int i=0; i<items.size(); i++) { dsr.patient = items[i]->text(0); dsr.protocol = items[i]->text(1); dsr.study = items[i]->text(2).toInt(&ok); dsr.series = items[i]->text(3).toInt(&ok); QVariant ppos = items[i]->data(0, Qt::WhatsThisRole); dsr.ppos = ppos.value<QString>(); int idx = dseries.indexOf(dsr); _saveseries.append(dseries[idx]); } // Get path to directory ... + prefix ... makes sense ? saveVolumeDialog dlg; int stat = dlg.exec(); if (stat) { // now use dcmtk to stack the correct volumes together ... // std::cout << "Yes" << std::endl; // collect all the info required for the entire set first ... int x, y,z; // x/y/z dims ; double sx=1.0, sy=1.0, sz=1.0; // pixel spacing in the x,y and x dimensions ... int bitsAlloc, bitsStored; // @todo need to get offset and orientation too ... int cnt = _saveseries.size(); QProgressDialog progress("Saving 3D volume(S)...", "Abort Scan", 0, cnt, this); progress.setValue(0); // std::cout << "Starting Loop" << std::endl; // outer loop over all subjects ... for (int t=0; t<cnt; t++) { progress.setLabelText("Saving Volume Frame "+ QString::number(t)); z = _saveseries[t].files.size(); // use the first slice of the frame to get most of the info ... QString fname = dcmDir.filePath(_saveseries[t].files[0]); DcmFileFormat fileformat; OFCondition status = fileformat.loadFile(fname.toLatin1()); if (status.good()) { OFString tmpStr; // First check if Transfer Syntax is all right ... /* if (fileformat.getDataset()->findAndGetOFString(DCM_TransferSyntaxUID, tmpStr).good()) { std::cout << "Transfer Syntax: " << tmpStr; } else { qDebug("Error: cannot access Transfer Syntax !"); } */ // DIMENSIONS if (fileformat.getDataset()->findAndGetOFString(DCM_Rows, tmpStr).good()) { y = atoi(tmpStr.c_str ()); std::cout << "Y " << tmpStr; } else { qDebug("Error: cannot access Image rows !"); } if (fileformat.getDataset()->findAndGetOFString(DCM_Columns, tmpStr).good()) { x = atoi(tmpStr.c_str ()); std::cout << " X " << tmpStr; } else { qDebug("Error: cannot access Image Columns!"); } // SPACING if (fileformat.getDataset()->findAndGetOFString(DCM_PixelSpacing, tmpStr).good()) { std::cout << " Spacing is " << tmpStr << std::endl; sx = sy = atof(tmpStr.c_str() ); } else { qDebug("Error: cannot access Pixel Spacing!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_SliceThickness, tmpStr).good()) { sz = atof(tmpStr.c_str() ); } else { qDebug("Error: cannot access Pixel Spacing - (slice thickness)!"); } // pixel info ... if (fileformat.getDataset()->findAndGetOFString(DCM_BitsAllocated, tmpStr).good()) { bitsAlloc = atoi(tmpStr.c_str() ); } else { qDebug("Error: cannot access Pixel BitsAllocated!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_BitsStored, tmpStr).good()) { bitsStored = atoi(tmpStr.c_str() ); } else { qDebug("Error: cannot access Pixel BitsStored!"); } } // std::cout << "Bits: " << bitsAlloc << " " << bitsStored << std::endl; std::cout << "Got INFO" << std::endl; // Prepare the header based on the format ... if (dlg.getSaveFormat() == QString("MetaIO")) std::cout << "Write MHD" << std::endl; else std::cout << "Write Analyze" << std::endl; // create the volInfo ... volInfo info; info.x = x; info.y = y; info.z = z; info.sx = sx; info.sy = sy; info.sz = sz; info.bs = 8; info.ba = 8; // @bug @todo for now I shall convert all unsigned short images to // normalized unsigned char images. I think works better this way. // allocate memory for a single volume ... unsigned char *vol = new unsigned char[x*y*z]; unsigned short *vol2 = new unsigned short[x*y*z]; saveHeader(VOL_FMT_ANALYZE, dlg.getSavePath() +"/" + dlg.getFilePrefix() + QString().sprintf(".%02d", t) + ".hdr", info); for (int k=0; k<z; k++) { // load the correct dataset ... fname = dcmDir.filePath(_saveseries[t].files[k]); // fname = dcmDir.filePath(_series[t].files[k]); status = fileformat.loadFile(fname.toLatin1()); progress.setValue(t); qApp->processEvents(); // std::cout << qPrintable(fname) << std::endl; // read in the slices ... const Uint16 *pixelData = NULL; unsigned long count = 0; if (fileformat.getDataset()->findAndGetUint16Array(DCM_PixelData, pixelData, &count).good()) { /* convert the pixel data */ // std::cout << "Converting pizedl data" << std::endl; for (int i=0; i<x*y; i++) vol2[k*x*y + i] = pixelData[i]; } else { qDebug("Error reading pixel data"); } } // convert image to unsigned char ... unsigned int _max =0; for (int i=0; i<x*y*z; i++) { if ( _max < vol2[i]) _max = vol2[i]; } for (int i=0; i<x*y*z; i++) vol[i] = static_cast<unsigned char>((250.0/_max)* vol2[i]); // write out image ... QString volname = dlg.getSavePath() +"/" + dlg.getFilePrefix() + QString().sprintf(".%02d", t) + ".img"; fp1 = fopen( volname.toLatin1(), "wb"); fwrite(vol, 1, x*y*z, fp1); fclose(fp1); delete [] vol; delete [] vol2; } progress.setValue(cnt); } // if stat ... } void dcmDialog::save4D() { // Lets save 4D ... :) QList<dcmDataSeries> _saveseries; // QList<dcmDataSeries> _series; dcmDataSeries dsr; bool ok; FILE *fp1; // first get the selection from m_pPreview ... QList<QTreeWidgetItem *> items = ui.m_pPreview->selectedItems(); if ( ! items.size() ) { qDebug("No Items selected"); return; } // this can be changed into a list of dcmDataSeries ... for (int i=0; i<items.size(); i++) { dsr.patient = items[i]->text(0); dsr.protocol = items[i]->text(1); dsr.study = items[i]->text(2).toInt(&ok); dsr.series = items[i]->text(3).toInt(&ok); QVariant ppos = items[i]->data(0, Qt::WhatsThisRole); dsr.ppos = ppos.value<QString>(); int idx = dseries.indexOf(dsr); _saveseries.append(dseries[idx]); } // check to see if all of them have the same length ... int len = _saveseries[0].files.size(); int z = _saveseries.size(); for (int i=1; i<_saveseries.size(); i++) { if ( len != _saveseries[i].files.size() ) { // error message ... QMessageBox::critical(0, "Dicom Import", QString("The selected sequences do not have the same number of frames.\n\n") + QString("Please retry\n")); return; } } // Get path to directory ... + prefix ... makes sense ? saveVolumeDialog dlg; int stat = dlg.exec(); if (stat) { // now use dcmtk to stack the correct volumes together ... std::cout << "Yes" << std::endl; // collect all the info required for the entire set first ... int x, y; // x/y dims ... we already know z and t; double sx=1.0, sy=1.0, sz=1.0; // pixel spacing in the x,y and x dimensions ... int bitsAlloc, bitsStored; // @todo need to get offset and orientation too ... // use the first slice of the first frame to get most of the info ... QString fname = dcmDir.filePath(_saveseries[0].files[0]); DcmFileFormat fileformat; OFCondition status = fileformat.loadFile(fname.toLatin1()); if (status.good()) { OFString tmpStr; // First check if Transfer Syntax is all right ... /* if (fileformat.getDataset()->findAndGetOFString(DCM_TransferSyntaxUID, tmpStr).good()) { std::cout << "Transfer Syntax: " << tmpStr; } else { qDebug("Error: cannot access Transfer Syntax !"); } */ // DIMENSIONS if (fileformat.getDataset()->findAndGetOFString(DCM_Rows, tmpStr).good()) { y = atoi(tmpStr.c_str ()); std::cout << "Y " << tmpStr; } else { qDebug("Error: cannot access Image rows !"); } if (fileformat.getDataset()->findAndGetOFString(DCM_Columns, tmpStr).good()) { x = atoi(tmpStr.c_str ()); std::cout << " X " << tmpStr; } else { qDebug("Error: cannot access Image Columns!"); } // SPACING if (fileformat.getDataset()->findAndGetOFString(DCM_PixelSpacing, tmpStr).good()) { std::cout << " Spacing is " << tmpStr << std::endl; sx = sy = atof(tmpStr.c_str() ); } else { qDebug("Error: cannot access Pixel Spacing!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_SliceThickness, tmpStr).good()) { sz = atof(tmpStr.c_str() ); } else { qDebug("Error: cannot access Pixel Spacing - (slice thickness)!"); } // pixel info ... if (fileformat.getDataset()->findAndGetOFString(DCM_BitsAllocated, tmpStr).good()) { bitsAlloc = atoi(tmpStr.c_str() ); } else { qDebug("Error: cannot access Pixel BitsAllocated!"); } if (fileformat.getDataset()->findAndGetOFString(DCM_BitsStored, tmpStr).good()) { bitsStored = atoi(tmpStr.c_str() ); } else { qDebug("Error: cannot access Pixel BitsStored!"); } } std::cout << "Bits: " << bitsAlloc << " " << bitsStored << std::endl; // Prepare the header based on the format ... if (dlg.getSaveFormat() == QString("MetaIO")) std::cout << "Write MHD" << std::endl; else std::cout << "Write Analyze" << std::endl; // create the volInfo ... volInfo info; info.x = x; info.y = y; info.z = z; info.sx = sx; info.sy = sy; info.sz = sz; info.bs = 8; info.ba = 8; // @bug @todo for now I shall convert all unsigned short images to // normalized unsigned char images. I think works better this way. // allocate memory for a single volume ... unsigned char *vol = new unsigned char[x*y*z]; /// compute the total number of images to be read so that the progress //counter can be set ... int cnt = z*len, ii=0; QProgressDialog progress("Saving 4D volume...", "Abort Scan", 0, cnt, this); progress.setValue(ii); // outer loop over len ... for (int t=0; t<len; t++) { progress.setLabelText("Saving Volume Frame "+ QString::number(t)); saveHeader(VOL_FMT_ANALYZE, dlg.getSavePath() +"/" + dlg.getFilePrefix() + QString().sprintf(".%02d", t) + ".hdr", info); for (int k=0; k<z; k++) { // load the correct dataset ... fname = dcmDir.filePath(_saveseries[k].files[t]); // fname = dcmDir.filePath(_series[t].files[k]); status = fileformat.loadFile(fname.toLatin1()); progress.setValue(ii++); qApp->processEvents(); std::cout << qPrintable(fname) << std::endl; // read in the slices ... const Uint16 *pixelData = NULL; unsigned long count = 0; if (fileformat.getDataset()->findAndGetUint16Array(DCM_PixelData, pixelData, &count).good()) { /* convert the pixel data */ // std::cout << "Converting pizedl data" << std::endl; for (int i=0; i<x*y; i++) vol[k*x*y + i] = (unsigned char )( pixelData[i] >> 1); } else { qDebug("Error reading pixel data"); } } // write out image ... QString volname = dlg.getSavePath() +"/" + dlg.getFilePrefix() + QString().sprintf(".%02d", t) + ".img"; fp1 = fopen( volname.toLatin1(), "wb"); fwrite(vol, 1, x*y*z, fp1); fclose(fp1); } progress.setValue(cnt); delete [] vol; } // if stat ... } void dcmDialog::saveHeader(int format, QString fname, volInfo _info) { if (format == VOL_FMT_MHD ) { // Write out MHD header. } else if (format == VOL_FMT_ANALYZE) { struct dsr hdr; FILE *fp; static char DataTypes[9][12] = {"UNKNOWN", "BINARY", "CHAR", "SHORT", "INT","FLOAT", "COMPLEX", "DOUBLE", "RGB"}; static int DataTypeSizes[9] = {0,1,8,16,32,32,64,64,24}; // std::cout << "Saving to file : " << qPrintable(fname) << std::endl; memset(&hdr,0, sizeof(struct dsr)); for(int i=0;i<8;i++) hdr.dime.pixdim[i] = 0.0; hdr.dime.vox_offset = 0.0; hdr.dime.funused1 = 0.0; hdr.dime.funused2 = 0.0; hdr.dime.funused3 = 0.0; hdr.dime.cal_max = 0.0; hdr.dime.cal_min = 0.0; hdr.dime.datatype = -1; for(int i=1;i<=8;i++) if(!strcmp("CHAR", DataTypes[i])) { hdr.dime.datatype = (1<<(i-1)); hdr.dime.bitpix = DataTypeSizes[i]; break; } if((fp=fopen(fname.toLatin1(),"w"))==0) { qDebug("unable to create header file"); return; } hdr.dime.dim[0] = 4; /* all Analyze images are taken as 4 dimensional */ hdr.hk.regular = 'r'; hdr.hk.sizeof_hdr = sizeof(struct dsr); hdr.dime.dim[1] = _info.x; /* slice width in pixels */ hdr.dime.dim[2] = _info.y; /* slice height in pixels */ hdr.dime.dim[3] = _info.z; /* volume depth in slices */ hdr.dime.dim[4] = 1; /* number of volumes per file */ hdr.dime.glmax = 0; /* maximum voxel value */ hdr.dime.glmin = 255; /* minimum voxel value */ /* Set the voxel dimension fields: A value of 0.0 for these fields implies that the value is unknown. Change these values to what is appropriate for your data or pass additional command line arguments */ hdr.dime.pixdim[1] = _info.sx; /* voxel x dimension */ hdr.dime.pixdim[2] = _info.sy; /* voxel y dimension */ hdr.dime.pixdim[3] = _info.sz; /* pixel z dimension, slice thickness */ /* Assume zero offset in .img file, byte at which pixel data starts in the image file */ hdr.dime.vox_offset = 0.0; /* Planar Orientation; */ /* Movie flag OFF: 0 = transverse, 1 = coronal, 2 = sagittal Movie flag ON: 3 = transverse, 4 = coronal, 5 = sagittal */ hdr.hist.orient = 0; /* up to 3 characters for the voxels units label; i.e. mm., um., cm. */ strcpy(hdr.dime.vox_units," "); /* up to 7 characters for the calibration units label; i.e. HU */ strcpy(hdr.dime.cal_units," "); /* Calibration maximum and minimum values; values of 0.0 for both fields imply that no calibration max and min values are used */ hdr.dime.cal_max = 0.0; hdr.dime.cal_min = 0.0; fwrite(&hdr,sizeof(struct dsr),1,fp); fclose(fp); } else { qDebug("Unknown output format"); } } void dcmDialog::updatePreview() { QList<QTreeWidgetItem *> items = ui.m_pPreview->selectedItems(); // only update on single item ... if (items.size() == 1) { QVariant pix = items[0]->data(0, Qt::ToolTipRole); // update the preview .. ui.m_lblPreview->setPixmap(pix.value<QPixmap>()); } } // Private utility functions ... void dcmDialog::addFilesFromDir( const QString& dcmDir, QStringList& fileList) { QDir theDir( dcmDir ); QStringList localList; theDir.setFilter(QDir::Files); foreach(QString filestring, theDir.entryList()) { // skip DICOMDIR for now .... if (filestring.toLower() == QString("dicomdir")) continue; fileList << theDir.filePath(filestring); } } void dcmDialog::scanDir(const QString& dcmDir, QStringList& fileList) { QString currentPath; QStringList dirList; QDir dir(dcmDir); // Stop recursion if the directory doesn't exist. if (!dir.exists()) { return; } dir.setSorting(QDir::Name); dir.setFilter(QDir::Dirs); dirList = dir.entryList(); // Remove '.' and '..' dirList.erase(dirList.begin()); dirList.erase(dirList.begin()); // Recurse through all directories QStringList::Iterator it; for( it = dirList.begin(); it != dirList.end(); ++it) { // Recursive call to fetch subdirectories currentPath = dcmDir + "//" + (*it); scanDir( currentPath, fileList ); } // Add files in THIS directory as well. addFilesFromDir( dcmDir, fileList ); }
[ [ [ 1, 989 ] ] ]
a801db54c454ef33c8f03580936a628d1eac9639
65dee2b7ed8a91f952831525d78bfced5abd713f
/winmob/XfMobile_WM6/Gamepe/VividTree.cpp
8f1e468189d97dd061d92031cffec3f2be858912
[]
no_license
felixnicitin1968/XFMobile
0249f90f111f0920a423228691bcbef0ecb0ce23
4a442d0127366afa9f80bdcdaaa4569569604dac
refs/heads/master
2016-09-06T05:02:18.589338
2011-07-05T17:25:39
2011-07-05T17:25:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,238
cpp
/////////////////////////////////////////////////////////////////////////// // VividTree.cpp : Implementation of Class VividTree /////////////////////////////////////////////////////////////////////////// // // Copyright(C) 2005 Jim Alsup All rights reserved // email: [email protected] // // License: This code is provided "as is" with no expressed or implied // warranty. You may use, or derive works from this file without // any restrictions except those listed below. // // - This original header must be kept in the derived work. // // - If your derived work is distributed in any form, you must // notify the author via the email address above and provide a // short description of the product and intended audience. // // - You may not sell this code or a derived version of it as part of // a comercial code library. // // - Offering the author a free licensed copy of any end product // using this code is not required, but does endear you with a // bounty of good karma. // /////////////////////////////////////////////////////////////////////////// // // This owner draw tree control allows for the creation of a tree control // that loosely resembles the user interface used by Skype's main window. // // Beside demonstrating the basics of creating an ownerdrawn tree control, // but more importantly, demonstrates gradient backgrounds fills, bitmap // backgrounds, flicker free drawing, and how to deal with these in a // scrollable and resizable dialog. // // The underlying gradient or bitmap image is sized according the natural // size of the visible (on screen or not) tree data. This can be more // readily understood and seen by opening and collasping the tree leaf // with a long text name. Notice the bmp or gradient resizes to the // actual screen content. // // Version History // // Sept 1, 2005 1.0.0 Initial Version #include "stdafx.h" #include "VividTree.h" #include ".\vividtree.h" #include "XfireCore.h" #define _OWNER_DRAWN 1 // Set to 0 to use Windows draw code. // Gradient Filling Helper Routine void GradientFillRect( CDC *pDC, CRect &rect, COLORREF col_from, COLORREF col_to, bool vert_grad ) { TRIVERTEX vert[2]; GRADIENT_RECT mesh; vert[0].x = rect.left; vert[0].y = rect.top; vert[0].Alpha = 0x0000; vert[0].Blue = GetBValue(col_from) << 8; vert[0].Green = GetGValue(col_from) << 8; vert[0].Red = GetRValue(col_from) << 8; vert[1].x = rect.right; vert[1].y = rect.bottom; vert[1].Alpha = 0x0000; vert[1].Blue = GetBValue(col_to) << 8; vert[1].Green = GetGValue(col_to) << 8; vert[1].Red = GetRValue(col_to) << 8; mesh.UpperLeft = 0; mesh.LowerRight = 1; GradientFill( pDC->m_hDC, vert, 2, &mesh, 1, vert_grad ? GRADIENT_FILL_RECT_V : GRADIENT_FILL_RECT_H ); } // CTreeCtrlEx IMPLEMENT_DYNAMIC(VividTree, CTreeCtrl) VividTree::VividTree() { m_gradient_bkgd_sel = RGB( 0x0, 0x0, 0xFF ); //Blueish m_gradient_bkgd_from = RGB( 0xf0, 0x130, 0x0 ); //White m_gradient_bkgd_to = RGB( 0x0, 0xc0, 0xe5 ); //Light Greyish Blue m_bkgd_mode = BK_MODE_GRADIENT; m_bmp_tiled_mode = false; m_gradient_horz = true; VERIFY( m_bmp_tree_closed.LoadBitmap( IDB_TREE_CLOSED ) ) ; m_bmp_tree_closed.GetSafeHandle(); VERIFY( m_bmp_tree_open.LoadBitmap( IDB_TREE_OPENED ) ) ; m_bmp_tree_open.GetSafeHandle(); m_icon = NULL; } VividTree::~VividTree() { if (m_bmp_back_ground.GetSafeHandle()) m_bmp_back_ground.DeleteObject(); if (m_bmp_tree_closed.GetSafeHandle()) m_bmp_tree_closed.DeleteObject(); if (m_bmp_tree_open.GetSafeHandle()) m_bmp_tree_open.DeleteObject(); } BEGIN_MESSAGE_MAP(VividTree, CTreeCtrl) ON_WM_ERASEBKGND() #if _OWNER_DRAWN ON_WM_PAINT() #endif ON_NOTIFY_REFLECT(TVN_ITEMEXPANDING, OnTvnItemexpanding) ON_NOTIFY_REFLECT(TVN_SELCHANGED, OnItemChanged) ON_NOTIFY_REFLECT(TVN_SELCHANGING, OnItemChanging) //ON_NOTIFY_REFLECT(NM_DBLCLK, OnDblclk) // ON_WM_CREATE() END_MESSAGE_MAP() // CVividTree message handlers BOOL VividTree::OnEraseBkgnd(CDC* pDC) { // nothing to do here -- see OnPaint return TRUE; } #if _OWNER_DRAWN void VividTree::OnPaint() { CPaintDC dc(this); // Device context for painting CDC dc_ff; // Memory base device context for flicker free painting CBitmap bm_ff; // The bitmap we paint into CBitmap *bm_old; CFont *font, *old_font; CFont fontDC; int old_mode; GetClientRect(&m_rect); SCROLLINFO scroll_info; // Determine window portal to draw into taking into account // scrolling position if ( GetScrollInfo( SB_HORZ, &scroll_info, SIF_POS | SIF_RANGE ) ) { m_h_offset = -scroll_info.nPos; m_h_size = max( scroll_info.nMax+1, m_rect.Width()); } else { m_h_offset = m_rect.left; m_h_size = m_rect.Width(); } if (0)// GetScrollInfo( SB_VERT, &scroll_info, SIF_POS | SIF_RANGE ) ) { if ( scroll_info.nMin == 0 && scroll_info.nMax == 100) scroll_info.nMax = 0; //m_v_offset = -scroll_info.nPos * GetItemHeight(); //m_v_size = max( (scroll_info.nMax+2)*((int)GetItemHeight()+1), m_rect.Height() ); } else { m_v_offset = m_rect.top; m_v_size = m_rect.Height(); } // Create an offscreen dc to paint with (prevents flicker issues) dc_ff.CreateCompatibleDC( &dc ); bm_ff.CreateCompatibleBitmap( &dc, m_rect.Width(), m_rect.Height() ); // Select the bitmap into the off-screen DC. bm_old = (CBitmap *)dc_ff.SelectObject( &bm_ff ); // Default font in the DC is not the font used by // the tree control, so grab it and select it in. font = GetFont(); old_font = dc_ff.SelectObject( font ); // We're going to draw text transparently old_mode = dc_ff.SetBkMode( TRANSPARENT ); DrawBackGround( &dc_ff ); DrawItems( &dc_ff ); // Now Blt the changes to the real device context - this prevents flicker. dc.BitBlt( m_rect.left, m_rect.top, m_rect.Width(), m_rect.Height(), &dc_ff, 0, 0, SRCCOPY); dc_ff.SelectObject( old_font ); dc_ff.SetBkMode( old_mode ); dc_ff.SelectObject( bm_old ); } #endif // Draw TreeCtrl Background - void VividTree::DrawBackGround( CDC* pDC ) { BkMode mode = m_bkgd_mode; if ( mode == BK_MODE_BMP ) { if ( !m_bmp_back_ground.GetSafeHandle() ) mode = BK_MODE_GRADIENT; } if ( mode == BK_MODE_GRADIENT ) { GradientFillRect( pDC, CRect( m_h_offset, m_v_offset, m_h_size + m_h_offset, m_v_size + m_v_offset ), m_gradient_bkgd_from, m_gradient_bkgd_to, !m_gradient_horz ); } else if ( mode == BK_MODE_FILL ) pDC->FillSolidRect( m_rect, pDC->GetBkColor() ); else if ( mode == BK_MODE_BMP ) { BITMAP bm; CDC dcMem; VERIFY(m_bmp_back_ground.GetObject(sizeof(bm), (LPVOID)&bm)); dcMem.CreateCompatibleDC(NULL); CBitmap* bmp_old = (CBitmap*)dcMem.SelectObject( &m_bmp_back_ground ); if ( m_bmp_tiled_mode ) // BitMap Tile Mode { for ( int y = 0; y <= (m_v_size / bm.bmHeight); y++ ) { for ( int x = 0; x <= (m_h_size / bm.bmWidth); x++ ) { pDC->BitBlt((x*bm.bmWidth) + m_h_offset, (y*bm.bmHeight) + m_v_offset, bm.bmWidth, bm.bmHeight, &dcMem, 0, 0, SRCCOPY); } } } else // BITMAP Stretch Mode { pDC->StretchBlt( m_h_offset, m_v_offset, m_h_size, m_v_size, &dcMem, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY ); } // CleanUp dcMem.SelectObject( bmp_old ); } else ASSERT( 0 ); // Unknown BackGround Mode } // Draw TreeCtrl Items void VividTree::DrawItems( CDC *pDC ) { // draw items HTREEITEM show_item, parent; CRect rc_item; CString name; COLORREF color; DWORD tree_style; BITMAP bm; CDC dc_mem; CBitmap *button; int count = 0; int state; bool selected; bool has_children; show_item = GetFirstVisibleItem(); if ( show_item == NULL ) return; dc_mem.CreateCompatibleDC(NULL); color = pDC->GetTextColor(); //color = pDC->SetTextColor(RGB(0x255,0x255,0x255) );//xxx color= pDC->SetTextColor( RGB(0x8A,0xBA,0xF1) ); tree_style = ::GetWindowLong( m_hWnd, GWL_STYLE ); do { state = GetItemState( show_item, TVIF_STATE ); parent = GetParentItem( show_item ); has_children = ItemHasChildren( show_item ) || parent == NULL; selected = (state & TVIS_SELECTED) && ((this == GetFocus()) || (tree_style & TVS_SHOWSELALWAYS)); if ( GetItemRect( show_item, rc_item, TRUE ) ) { if ( has_children || selected ) { COLORREF from; CRect rect; // Show if (1)//selected ) from = m_gradient_bkgd_sel; else from = m_gradient_bkgd_to - (m_gradient_bkgd_from - m_gradient_bkgd_to); rect.top = rc_item.top; rect.bottom = rc_item.bottom; rect.right = m_h_size + m_h_offset; if ( !has_children ) rect.left = rc_item.left + m_h_offset; else rect.left = m_h_offset; GradientFillRect( pDC, rect, from, m_gradient_bkgd_to, FALSE ); if (has_children){ pDC->SetTextColor(RGB(0x12,0x28,0x3f) ); }else { // pDC->SetTextColor( RGB(0x255,0x255,0x255) ); pDC->SetTextColor( RGB(0x8A,0xBA,0xF1) ); } if ( has_children ) { // Draw an Open/Close button if ( state & TVIS_EXPANDED ) button = &m_bmp_tree_open; else button = &m_bmp_tree_closed; VERIFY(button->GetObject(sizeof(bm), (LPVOID)&bm)); CBitmap *bmp_old = (CBitmap*)dc_mem.SelectObject(button); pDC->BitBlt( rc_item.left - bm.bmWidth - 2, rc_item.top, bm.bmWidth, bm.bmHeight, &dc_mem, 0, 0, SRCAND ); // CleanUp dc_mem.SelectObject( bmp_old ); } } if ( !has_children ) { // lookup the ICON instance (if any) and draw dit /*HICON icon; icon = GetItemIcon( show_item ); if ( icon != NULL ) DrawIconEx( pDC->m_hDC, rc_item.left - 18, rc_item.top, icon, 16, 16,0,0, DI_NORMAL ); */ long userid=GetItemData(show_item); if (GetItemData(GetParentItem(show_item))==CONV_SECTION) { if (CXfireCore::isFriendAway(userid)){ HICON icon; icon = GetAwayIcon( show_item ); DrawIconEx( pDC->m_hDC, rc_item.left - 18, rc_item.top+0, icon, 16, 16,0,0, DI_NORMAL ); }else{ HICON icon; icon = GetOnlineIcon( show_item ); DrawIconEx( pDC->m_hDC, rc_item.left - 18, rc_item.top+0, icon, 16, 16,0,0, DI_NORMAL ); } //HICON icon; //icon = GetOnlineIcon( show_item ); // DrawIconEx( pDC->m_hDC, rc_item.left - 18, rc_item.top, icon, 16, 16,0,0, DI_NORMAL ); //pDC->SetTextColor( RGB(255,255,255) ); pDC->SetTextColor( RGB(0x8A,0xBA,0xF1) ); }else if (CXfireCore::isFriendAway(userid)) { HICON icon; icon = GetAwayIcon( show_item ); DrawIconEx( pDC->m_hDC, rc_item.left - 18, rc_item.top+0, icon, 16, 16,0,0, DI_NORMAL ); }else{ HICON icon; icon = GetOnlineIcon( show_item ); DrawIconEx( pDC->m_hDC, rc_item.left - 18, rc_item.top+0, icon, 16, 16,0,0, DI_NORMAL ); } int gameid=CXfireCore::getGameId(userid); if (gameid !=0 && gameid>=4096 && gameid<=6047){ HICON hIcon = CXfireCore::geContactGameImage(userid); if (hIcon!=NULL){ DrawIconEx( pDC->m_hDC, rc_item.left - 18, rc_item.top+0, hIcon, 16, 16,0,0, DI_NORMAL ); } } } name = GetItemText( show_item ); rc_item.DeflateRect( 0,1,0,1 ); if (selected ) { if ( !has_children ) { pDC->SetTextColor( GetSysColor(RGB(255,255,255)) ); //COLOR_HIGHLIGHTTEXT } COLORREF col = pDC->GetBkColor(); //pDC->SetTextColor( RGB(255,255,255) ); pDC->SetTextColor( RGB(0x8A,0xBA,0xF1) ); pDC->DrawText( name, rc_item, DT_LEFT ); pDC->SetTextColor( color ); pDC->SetBkColor( col ); } else { //pDC->SetTextColor(RGB(255,255,255)); pDC->SetTextColor( RGB(0x8A,0xBA,0xF1) ); pDC->DrawText( name, rc_item, DT_LEFT ); } //if ( state & TVIS_BOLD ) // pDC->SelectObject( font ); } } while ( (show_item = GetNextVisibleItem( show_item )) != NULL ); } void VividTree::SetBitmapID( UINT id ) { // delete any existing bitmap if (m_bmp_back_ground.GetSafeHandle()) m_bmp_back_ground.DeleteObject(); // add in the new bitmap VERIFY( m_bmp_back_ground.LoadBitmap( id ) ) ; m_bmp_back_ground.GetSafeHandle(); } // Determine if a referenced item is visible within the control window bool VividTree::ItemIsVisible( HTREEITEM item ) { HTREEITEM scan_item; scan_item = GetFirstVisibleItem(); while ( scan_item != NULL ) { if ( item == scan_item ) return true; scan_item = GetNextVisibleItem( scan_item ); } return false; } // For a given tree node return an ICON for display on the left side. // This default implementation only returns one icon. // This function is virtual and meant to be overriden by deriving a class // from VividTree and supplying your own icon images. HICON VividTree::GetOnlineIcon( HTREEITEM item ) { return m_icon; // default implementation - overridable } // If the background is a bitmap, and a tree is expanded/collapsed we // need to redraw the entire background because windows moves the bitmap // up (on collapse) destroying the position of the background. void VividTree::OnTvnItemexpanding(NMHDR *pNMHDR, LRESULT *pResult) { LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); if ( GetBkMode() == VividTree::BK_MODE_BMP && ItemIsVisible( pNMTreeView->itemNew.hItem ) ) Invalidate(); // redraw everything *pResult = 0; } void VividTree::OnItemChanging(NMHDR* pNMHDR, LRESULT* pResult) { } void VividTree::OnItemChanged(NMHDR* pNMHDR, LRESULT* pResult) { LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); long userid=GetItemData(pNMTreeView->itemNew.hItem); if (!userid) return; if (g_SelectedUserID!=userid){ g_SelectedUserID=userid; return; } XfireContact *xontact=CXfireCore::getContactByID(g_SelectedUserID); if (!xontact) { xontact=CXfireCore::getClanMember(g_SelectedUserID); if (xontact==NULL) { return; } } g_hSelectedItem=pNMTreeView->itemNew.hItem; //::SendMessage(g_hMainDlg,WM_NEW_CHAT_WND,(WPARAM)xontact,0); } void VividTree::OnDblclk(NMHDR* pNMHDR, LRESULT* pResult) { /*LPNMTREEVIEW pNMTreeView = reinterpret_cast<LPNMTREEVIEW>(pNMHDR); long userid=GetItemData(pNMTreeView->itemNew.hItem); if (!userid) return; g_SelectedUserID=userid; XfireContact *xontact=CXfireCore::getContactByID(g_SelectedUserID); if (!xontact) return; g_hSelectedItem=pNMTreeView->itemNew.hItem; ::SendMessage(g_hMainDlg,WM_NEW_CHAT_WND,(WPARAM)xontact,0);*/ }
[ [ [ 1, 574 ] ] ]
076e50330768318e42061840399ce9e86b2b62db
3d7d8969d540b99a1e53e00c8690e32e4d155749
/IEBgps/inc/IEImageDecoder.h
12629f639b81fc89ebd3466317d8d4acf594f7e8
[]
no_license
SymbianSource/oss.FCL.sf.incubator.photobrowser
50c4ea7142102068f33fc62e36baab9d14f348f9
818b5857895d2153c4cdd653eb0e10ba6477316f
refs/heads/master
2021-01-11T02:45:51.269916
2010-10-15T01:18:29
2010-10-15T01:18:29
70,931,013
0
0
null
null
null
null
UTF-8
C++
false
false
1,822
h
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: Juha Kauppinen, Mika Hokkanen * * Description: Photo Browser * */ #ifndef __IEIMAGEDECODER_H__ #define __IEIMAGEDECODER_H__ // Include files #include <e32base.h> #include <f32file.h> #include <fbs.h> #include <ImageConversion.h> #include <IclExtJpegApi.h> class MDecodingObserver { public: //virtual void YuvImageReady(TInt aError) = 0; virtual void BitmapReady(TInt aError) = 0; }; // Forward class declarations // Class declaration class CIEImageDecoder : CActive { public: static CIEImageDecoder* NewL(RFs& aFileServer, MDecodingObserver& aObserver); ~CIEImageDecoder(); private: void ConstructL(); CIEImageDecoder(RFs& aFileServer, MDecodingObserver& aObserver); public: // From CAtive void RunL() ; void DoCancel(); public: void GetImageSizeL(const TFileName aFileName, TSize& aSize); void ConvertJpeg2YuvL(const TDesC& aSourceFile, HBufC8& aBuffer); void ConvertJpeg2BitmapL(CFbsBitmap& aDestBitmap, TDesC8& aSourceData); TPtr8 GetVisualFrame(); void CancelDecoding(); private: // Data RFs& iFileServer; MDecodingObserver& iObserver; CImageDecoder* iImageDecoder; CExtJpegDecoder* iExtImageDecoder; CVisualFrame* iVisualFrame; TBool iDecoderBusy; TBool iDecode2Yuv; TBool iDecode2Bitmap; TPtr8 iSrcPtr; TUint8* iBufU; TInt iNumOfBitmaps; }; #endif // __IEIMAGEDECODER_H__
[ "none@none" ]
[ [ [ 1, 78 ] ] ]
96d9947464562701517fc64665df09c61015262a
cbf000c79b3e286b811a06068f160405ae637ed2
/src/CommandPanel.cpp
da390a7a063f052c00a63b95afbb92bc5d191ac1
[]
no_license
ajpalkovic/e
ee071fb89d8b55b014498858ea87bccdd7b8d1d0
adeb49928889e282c3851fba7d08222c9137b012
refs/heads/master
2021-01-18T11:00:39.166075
2011-02-16T01:23:59
2011-02-16T01:23:59
435,884
7
3
null
null
null
null
UTF-8
C++
false
false
2,572
cpp
#include "CommandPanel.h" #include "CloseButton.h" #include "EditorFrame.h" #include "EditorCtrl.h" // Ctrl id's enum { COMMANDP_CLOSE = 100, COMMANDP_BOX, }; BEGIN_EVENT_TABLE(CommandPanel, wxPanel) EVT_BUTTON(COMMANDP_CLOSE, CommandPanel::OnCloseButton) EVT_IDLE(CommandPanel::OnIdle) END_EVENT_TABLE() CommandPanel::CommandPanel(EditorFrame& parentFrame, wxWindow* parent) : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL|wxCLIP_CHILDREN|wxNO_BORDER|wxNO_FULL_REPAINT_ON_RESIZE), m_parentFrame(parentFrame) { // Create the controls CloseButton* closeButton = new CloseButton(this, COMMANDP_CLOSE); wxStaticText* commandlabel = new wxStaticText(this, wxID_ANY, _("Command: ")); m_commandbox = new wxTextCtrl(this, COMMANDP_BOX, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_READONLY); m_selStatic = new wxStaticText(this, wxID_ANY, wxEmptyString); // Create the sizer layout wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL); sizer->AddSpacer(5); sizer->Add(closeButton, 0, wxALIGN_CENTER|wxRIGHT, 2); sizer->Add(commandlabel, 0, wxALIGN_CENTER); sizer->Add(m_commandbox, 3, wxALIGN_CENTER|wxEXPAND|wxTOP|wxBOTTOM, 2); sizer->Add(m_selStatic, 0, wxALIGN_CENTER); sizer->AddSpacer(5); SetSizer(sizer); // Set the correct size const wxSize minsize = sizer->GetMinSize(); SetSize(minsize); // Make sure sizes get the right min/max sizes SetSizeHints(minsize.x, minsize.y, -1, minsize.y); } void CommandPanel::ShowCommand(const wxString& cmd) { m_commandbox->SetValue(cmd); } void CommandPanel::OnCloseButton(wxCommandEvent& WXUNUSED(evt)) { m_parentFrame.ShowCommandMode(false); } void CommandPanel::OnIdle(wxIdleEvent& WXUNUSED(evt)) { const EditorCtrl* editor = m_parentFrame.GetEditorCtrl(); if (!editor) return; const size_t selectionCount = editor->GetSelections().size(); const size_t rangeCount = editor->GetSearchRange().size(); if (selectionCount == m_selectionCount && rangeCount == m_rangeCount) return; wxString seltext; if (rangeCount == 1) seltext += wxT("1 range"); else if (rangeCount) seltext += wxString::Format(wxT("%d ranges"), rangeCount); if (selectionCount) { if (!seltext.empty()) seltext += wxT(", "); if (selectionCount == 1) seltext += wxT("1 selection"); else seltext += wxString::Format(wxT("%d selections"), selectionCount); } if (!seltext.empty()) seltext.insert(0, wxT(" ")); // spacer m_selStatic->SetLabel(seltext); GetSizer()->Layout(); m_selectionCount = selectionCount; m_rangeCount = rangeCount; }
[ [ [ 1, 77 ] ] ]
121fb42fc229dcb5801c3643040b8f590fd81830
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osg/FrameBufferObject
76f9652beacc086cfefe09f04d0cef08649696f3
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
19,613
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ // initial FBO support written by Marco Jez, June 2005. #ifndef OSG_FRAMEBUFFEROBJECT #define OSG_FRAMEBUFFEROBJECT 1 #include <osg/GL> #include <osg/Texture> #include <osg/buffered_value> #include <osg/Camera> #ifndef GL_EXT_framebuffer_object #define GL_EXT_framebuffer_object 1 #define GL_FRAMEBUFFER_EXT 0x8D40 #define GL_RENDERBUFFER_EXT 0x8D41 // #define GL_STENCIL_INDEX_EXT 0x8D45 // removed in rev. #114 of the spec #define GL_STENCIL_INDEX1_EXT 0x8D46 #define GL_STENCIL_INDEX4_EXT 0x8D47 #define GL_STENCIL_INDEX8_EXT 0x8D48 #define GL_STENCIL_INDEX16_EXT 0x8D49 #define GL_RENDERBUFFER_WIDTH_EXT 0x8D42 #define GL_RENDERBUFFER_HEIGHT_EXT 0x8D43 #define GL_RENDERBUFFER_INTERNAL_FORMAT_EXT 0x8D44 #define GL_RENDERBUFFER_RED_SIZE_EXT 0x8D50 #define GL_RENDERBUFFER_GREEN_SIZE_EXT 0x8D51 #define GL_RENDERBUFFER_BLUE_SIZE_EXT 0x8D52 #define GL_RENDERBUFFER_ALPHA_SIZE_EXT 0x8D53 #define GL_RENDERBUFFER_DEPTH_SIZE_EXT 0x8D54 #define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT 0x8CD0 #define GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT 0x8CD1 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT 0x8CD2 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT 0x8CD3 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT 0x8CD4 #define GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT 0x8CD4 #define GL_COLOR_ATTACHMENT0_EXT 0x8CE0 #define GL_COLOR_ATTACHMENT1_EXT 0x8CE1 #define GL_COLOR_ATTACHMENT2_EXT 0x8CE2 #define GL_COLOR_ATTACHMENT3_EXT 0x8CE3 #define GL_COLOR_ATTACHMENT4_EXT 0x8CE4 #define GL_COLOR_ATTACHMENT5_EXT 0x8CE5 #define GL_COLOR_ATTACHMENT6_EXT 0x8CE6 #define GL_COLOR_ATTACHMENT7_EXT 0x8CE7 #define GL_COLOR_ATTACHMENT8_EXT 0x8CE8 #define GL_COLOR_ATTACHMENT9_EXT 0x8CE9 #define GL_COLOR_ATTACHMENT10_EXT 0x8CEA #define GL_COLOR_ATTACHMENT11_EXT 0x8CEB #define GL_COLOR_ATTACHMENT12_EXT 0x8CEC #define GL_COLOR_ATTACHMENT13_EXT 0x8CED #define GL_COLOR_ATTACHMENT14_EXT 0x8CEE #define GL_COLOR_ATTACHMENT15_EXT 0x8CEF #define GL_DEPTH_ATTACHMENT_EXT 0x8D00 #define GL_STENCIL_ATTACHMENT_EXT 0x8D20 #define GL_FRAMEBUFFER_COMPLETE_EXT 0x8CD5 #define GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT 0x8CD6 #define GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT 0x8CD7 #define GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT_EXT 0x8CD8 #define GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT 0x8CD9 #define GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT 0x8CDA #define GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT 0x8CDB #define GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT 0x8CDC #define GL_FRAMEBUFFER_UNSUPPORTED_EXT 0x8CDD #define GL_FRAMEBUFFER_BINDING_EXT 0x8CA6 #define GL_RENDERBUFFER_BINDING_EXT 0x8CA7 #define GL_MAX_COLOR_ATTACHMENTS_EXT 0x8CDF #define GL_MAX_RENDERBUFFER_SIZE_EXT 0x84E8 #define GL_INVALID_FRAMEBUFFER_OPERATION_EXT 0x0506 #endif #ifndef GL_EXT_framebuffer_blit #define GL_EXT_framebuffer_blit 1 #define GL_DRAW_FRAMEBUFFER_BINDING_EXT 0x8CA6 #define GL_READ_FRAMEBUFFER_EXT 0x8CA8 #define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 #define GL_READ_FRAMEBUFFER_BINDING_EXT 0x8CAA #endif #ifndef GL_EXT_framebuffer_multisample #define GL_EXT_framebuffer_multisample 1 #define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB #define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 #define GL_MAX_SAMPLES_EXT 0x8D57 #endif #ifndef GL_MAX_SAMPLES_EXT // Workaround for Centos 5 and other distros that define // GL_EXT_framebuffer_multisample but not GL_MAX_SAMPLES_EXT #define GL_MAX_SAMPLES_EXT 0x8D57 #endif #ifndef GL_NV_framebuffer_multisample_coverage #define GL_NV_framebuffer_multisample_coverage 1 #define GL_RENDERBUFFER_COVERAGE_SAMPLES_NV 0x8CAB #define GL_RENDERBUFFER_COLOR_SAMPLES_NV 0x8E10 #define GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV 0x8E11 #define GL_MULTISAMPLE_COVERAGE_MODES_NV 0x8E12 #endif #ifndef GL_DEPTH_COMPONENT #define GL_DEPTH_COMPONENT 0x1902 #endif #ifndef GL_VERSION_1_4 #define GL_DEPTH_COMPONENT16 0x81A5 #define GL_DEPTH_COMPONENT24 0x81A6 #define GL_DEPTH_COMPONENT32 0x81A7 #endif #ifndef GL_EXT_packed_depth_stencil #define GL_EXT_packed_depth_stencil 1 #define GL_DEPTH_STENCIL_EXT 0x84F9 #define GL_UNSIGNED_INT_24_8_EXT 0x84FA #define GL_DEPTH24_STENCIL8_EXT 0x88F0 #define GL_TEXTURE_STENCIL_SIZE_EXT 0x88F1 #endif namespace osg { /************************************************************************** * FBOExtensions **************************************************************************/ class OSG_EXPORT FBOExtensions : public osg::Referenced { public: typedef void APIENTRY TglBindRenderbuffer(GLenum, GLuint); typedef void APIENTRY TglDeleteRenderbuffers(GLsizei n, const GLuint *renderbuffers); typedef void APIENTRY TglGenRenderbuffers(GLsizei, GLuint *); typedef void APIENTRY TglRenderbufferStorage(GLenum, GLenum, GLsizei, GLsizei); typedef void APIENTRY TglRenderbufferStorageMultisample(GLenum, GLsizei, GLenum, GLsizei, GLsizei); typedef void APIENTRY TglRenderbufferStorageMultisampleCoverageNV(GLenum, GLsizei, GLsizei, GLenum, GLsizei, GLsizei); typedef void APIENTRY TglBindFramebuffer(GLenum, GLuint); typedef void APIENTRY TglDeleteFramebuffers(GLsizei n, const GLuint *framebuffers); typedef void APIENTRY TglGenFramebuffers(GLsizei, GLuint *); typedef GLenum APIENTRY TglCheckFramebufferStatus(GLenum); typedef void APIENTRY TglFramebufferTexture1D(GLenum, GLenum, GLenum, GLuint, GLint); typedef void APIENTRY TglFramebufferTexture2D(GLenum, GLenum, GLenum, GLuint, GLint); typedef void APIENTRY TglFramebufferTexture3D(GLenum, GLenum, GLenum, GLuint, GLint, GLint); typedef void APIENTRY TglFramebufferTextureLayer(GLenum, GLenum, GLuint, GLint, GLint); typedef void APIENTRY TglFramebufferRenderbuffer(GLenum, GLenum, GLenum, GLuint); typedef void APIENTRY TglGenerateMipmap(GLenum); typedef void APIENTRY TglBlitFramebuffer(GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum); TglBindRenderbuffer* glBindRenderbuffer; TglGenRenderbuffers* glGenRenderbuffers; TglDeleteRenderbuffers* glDeleteRenderbuffers; TglRenderbufferStorage* glRenderbufferStorage; TglRenderbufferStorageMultisample* glRenderbufferStorageMultisample; TglRenderbufferStorageMultisampleCoverageNV* glRenderbufferStorageMultisampleCoverageNV; TglBindFramebuffer* glBindFramebuffer; TglDeleteFramebuffers* glDeleteFramebuffers; TglGenFramebuffers* glGenFramebuffers; TglCheckFramebufferStatus* glCheckFramebufferStatus; TglFramebufferTexture1D* glFramebufferTexture1D; TglFramebufferTexture2D* glFramebufferTexture2D; TglFramebufferTexture3D* glFramebufferTexture3D; TglFramebufferTextureLayer* glFramebufferTextureLayer; TglFramebufferRenderbuffer* glFramebufferRenderbuffer; TglGenerateMipmap* glGenerateMipmap; TglBlitFramebuffer* glBlitFramebuffer; static FBOExtensions* instance(unsigned contextID, bool createIfNotInitalized); bool isSupported() const { return _supported; } bool isMultisampleSupported() const { return glRenderbufferStorageMultisample != 0; } bool isMultisampleCoverageSupported() const { return glRenderbufferStorageMultisampleCoverageNV != 0; } bool isPackedDepthStencilSupported() const { return _packed_depth_stencil_supported; } protected: FBOExtensions(unsigned int contextID); bool _supported; bool _packed_depth_stencil_supported; }; /************************************************************************** * RenderBuffer **************************************************************************/ class OSG_EXPORT RenderBuffer: public Object { public: RenderBuffer(); RenderBuffer(int width, int height, GLenum internalFormat, int samples=0, int colorSamples=0); RenderBuffer(const RenderBuffer& copy, const CopyOp& copyop = CopyOp::SHALLOW_COPY); META_Object(osg, RenderBuffer); inline int getWidth() const; inline int getHeight() const; inline void setWidth(int w); inline void setHeight(int h); inline void setSize(int w, int h); inline GLenum getInternalFormat() const; inline void setInternalFormat(GLenum format); inline int getSamples() const; inline int getColorSamples() const; inline void setSamples(int samples); inline void setColorSamples(int colorSamples); GLuint getObjectID(unsigned int contextID, const FBOExtensions *ext) const; inline int compare(const RenderBuffer &rb) const; /** Mark internal RenderBuffer for deletion. * Deletion requests are queued until they can be executed * in the proper GL context. */ static void deleteRenderBuffer(unsigned int contextID, GLuint rb); /** flush all the cached RenderBuffers which need to be deleted * in the OpenGL context related to contextID.*/ static void flushDeletedRenderBuffers(unsigned int contextID,double currentTime, double& availableTime); /** discard all the cached RenderBuffers which need to be deleted in the OpenGL context related to contextID. * Note, unlike flush no OpenGL calls are made, instead the handles are all removed. * this call is useful for when an OpenGL context has been destroyed. */ static void discardDeletedRenderBuffers(unsigned int contextID); static int getMaxSamples(unsigned int contextID, const FBOExtensions *ext); protected: virtual ~RenderBuffer(); RenderBuffer &operator=(const RenderBuffer &) { return *this; } inline void dirtyAll() const; private: mutable buffered_value<GLuint> _objectID; mutable buffered_value<int> _dirty; GLenum _internalFormat; int _width; int _height; // "samples" in the framebuffer_multisample extension is equivalent to // "coverageSamples" in the framebuffer_multisample_coverage extension. int _samples; int _colorSamples; }; // INLINE METHODS inline int RenderBuffer::getWidth() const { return _width; } inline int RenderBuffer::getHeight() const { return _height; } inline void RenderBuffer::setWidth(int w) { _width = w; dirtyAll(); } inline void RenderBuffer::setHeight(int h) { _height = h; dirtyAll(); } inline void RenderBuffer::setSize(int w, int h) { _width = w; _height = h; dirtyAll(); } inline GLenum RenderBuffer::getInternalFormat() const { return _internalFormat; } inline void RenderBuffer::setInternalFormat(GLenum format) { _internalFormat = format; dirtyAll(); } inline int RenderBuffer::getSamples() const { return _samples; } inline int RenderBuffer::getColorSamples() const { return _colorSamples; } inline void RenderBuffer::setSamples(int samples) { _samples = samples; dirtyAll(); } inline void RenderBuffer::setColorSamples(int colorSamples) { _colorSamples = colorSamples; dirtyAll(); } inline void RenderBuffer::dirtyAll() const { _dirty.setAllElementsTo(1); } inline int RenderBuffer::compare(const RenderBuffer &rb) const { if (&rb == this) return 0; if (_internalFormat < rb._internalFormat) return -1; if (_internalFormat > rb._internalFormat) return 1; if (_width < rb._width) return -1; if (_width > rb._width) return 1; if (_height < rb._height) return -1; if (_height > rb._height) return 1; return 0; } /************************************************************************** * FrameBufferAttachement **************************************************************************/ class Texture1D; class Texture2D; class Texture3D; class Texture2DArray; class TextureCubeMap; class TextureRectangle; class OSG_EXPORT FrameBufferAttachment { public: FrameBufferAttachment(); FrameBufferAttachment(const FrameBufferAttachment& copy); explicit FrameBufferAttachment(RenderBuffer* target); explicit FrameBufferAttachment(Texture1D* target, int level = 0); explicit FrameBufferAttachment(Texture2D* target, int level = 0); explicit FrameBufferAttachment(Texture3D* target, int zoffset, int level = 0); explicit FrameBufferAttachment(Texture2DArray* target, int layer, int level = 0); explicit FrameBufferAttachment(TextureCubeMap* target, int face, int level = 0); explicit FrameBufferAttachment(TextureRectangle* target); explicit FrameBufferAttachment(Camera::Attachment& attachment); ~FrameBufferAttachment(); FrameBufferAttachment&operator = (const FrameBufferAttachment& copy); bool isMultisample() const; void createRequiredTexturesAndApplyGenerateMipMap(State& state, const FBOExtensions* ext) const; void attach(State &state, GLenum target, GLenum attachment_point, const FBOExtensions* ext) const; int compare(const FrameBufferAttachment &fa) const; RenderBuffer* getRenderBuffer(); const RenderBuffer* getRenderBuffer() const; Texture* getTexture(); const Texture* getTexture() const; int getCubeMapFace() const; int getTextureLevel() const; int getTexture3DZOffset() const; int getTextureArrayLayer() const; private: // use the Pimpl idiom to avoid dependency from // all Texture* headers struct Pimpl; Pimpl* _ximpl; }; /************************************************************************** * FrameBufferObject **************************************************************************/ class OSG_EXPORT FrameBufferObject: public StateAttribute { public: typedef std::map<Camera::BufferComponent, FrameBufferAttachment> AttachmentMap; typedef std::vector<GLenum> MultipleRenderingTargets; typedef Camera::BufferComponent BufferComponent; FrameBufferObject(); FrameBufferObject(const FrameBufferObject& copy, const CopyOp& copyop = CopyOp::SHALLOW_COPY); META_StateAttribute(osg, FrameBufferObject, (StateAttribute::Type)0x101010/*FrameBufferObject*/); inline const AttachmentMap& getAttachmentMap() const; void setAttachment(BufferComponent attachment_point, const FrameBufferAttachment &attachment); inline const FrameBufferAttachment& getAttachment(BufferComponent attachment_point) const; inline bool hasAttachment(BufferComponent attachment_point) const; inline bool hasMultipleRenderingTargets() const { return !_drawBuffers.empty(); } inline const MultipleRenderingTargets& getMultipleRenderingTargets() const { return _drawBuffers; } bool isMultisample() const; int compare(const StateAttribute &sa) const; void apply(State &state) const; enum BindTarget { READ_FRAMEBUFFER = GL_READ_FRAMEBUFFER_EXT, DRAW_FRAMEBUFFER = GL_DRAW_FRAMEBUFFER_EXT, READ_DRAW_FRAMEBUFFER = GL_FRAMEBUFFER_EXT }; /** Bind the FBO as either the read or draw target, or both. */ void apply(State &state, BindTarget target) const; /** Mark internal FBO for deletion. * Deletion requests are queued until they can be executed * in the proper GL context. */ static void deleteFrameBufferObject(unsigned int contextID, GLuint program); /** flush all the cached FBOs which need to be deleted * in the OpenGL context related to contextID.*/ static void flushDeletedFrameBufferObjects(unsigned int contextID,double currentTime, double& availableTime); /** discard all the cached FBOs which need to be deleted * in the OpenGL context related to contextID.*/ static void discardDeletedFrameBufferObjects(unsigned int contextID); protected: virtual ~FrameBufferObject(); FrameBufferObject& operator = (const FrameBufferObject&) { return *this; } void updateDrawBuffers(); inline void dirtyAll(); GLenum convertBufferComponentToGLenum(BufferComponent attachment_point) const; private: AttachmentMap _attachments; // Buffers passed to glDrawBuffers when using multiple render targets. MultipleRenderingTargets _drawBuffers; mutable buffered_value<int> _dirtyAttachmentList; mutable buffered_value<int> _unsupported; mutable buffered_value<GLuint> _fboID; }; // INLINE METHODS inline const FrameBufferObject::AttachmentMap &FrameBufferObject::getAttachmentMap() const { return _attachments; } inline bool FrameBufferObject::hasAttachment(FrameBufferObject::BufferComponent attachment_point) const { return _attachments.find(attachment_point) != _attachments.end(); } inline const FrameBufferAttachment &FrameBufferObject::getAttachment(FrameBufferObject::BufferComponent attachment_point) const { return _attachments.find(attachment_point)->second; } inline void FrameBufferObject::dirtyAll() { _dirtyAttachmentList.setAllElementsTo(1); } } #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 488 ] ] ]
2b6bd17b6a596a5081ea5a36f5ad7a37ed72d35d
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Mathematics/Wm4BSplineVolume.h
0fbc1d7b6975b75cca82dcf9a94dd9096bb72966
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
2,411
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4BSPLINEVOLUME_H #define WM4BSPLINEVOLUME_H #include "Wm4FoundationLIB.h" #include "Wm4BSplineBasis.h" #include "Wm4Vector3.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM BSplineVolume { public: // Construction and destruction of an open uniform B-spline volume. The // class will allocate space for the control points. The caller is // responsible for setting the values with the member function // ControlPoint. BSplineVolume (int iNumUCtrlPoints, int iNumVCtrlPoints, int iNumWCtrlPoints, int iUDegree, int iVDegree, int iWDegree); ~BSplineVolume (); int GetNumCtrlPoints (int iDim) const; int GetDegree (int iDim) const; // Control points may be changed at any time. If any input index is // invalid, the returned point is a vector whose components are all // MAX_REAL. void SetControlPoint (int iUIndex, int iVIndex, int iWIndex, const Vector3<Real>& rkCtrlPoint); Vector3<Real> GetControlPoint (int iUIndex, int iVIndex, int iWIndex) const; // The spline is defined for 0 <= u <= 1, 0 <= v <= 1, and 0 <= w <= 1. // The input values should be in this domain. Any inputs smaller than 0 // are clamped to 0. Any inputs larger than 1 are clamped to 1. Vector3<Real> GetPosition (Real fU, Real fV, Real fW) const; Vector3<Real> GetDerivativeU (Real fU, Real fV, Real fW) const; Vector3<Real> GetDerivativeV (Real fU, Real fV, Real fW) const; Vector3<Real> GetDerivativeW (Real fU, Real fV, Real fW) const; // for array indexing: i = 0 for u, i = 1 for v, i = 2 for w Vector3<Real> GetPosition (Real afP[3]) const; Vector3<Real> GetDerivative (int i, Real afP[3]) const; private: Vector3<Real>*** m_aaakCtrlPoint; // ctrl[unum][vnum][wnum] BSplineBasis<Real> m_akBasis[3]; }; typedef BSplineVolume<float> BSplineVolumef; typedef BSplineVolume<double> BSplineVolumed; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 68 ] ] ]
d7b0610903dd443555663abada448d890294a03a
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/internal/XMLScanner.cpp
16325c74e368b7e9f3f713f02246893a2fc53cd0
[ "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
79,144
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: XMLScanner.cpp,v 1.73 2004/09/30 15:20:14 peiyongz Exp $ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/internal/XMLScanner.hpp> #include <xercesc/internal/ValidationContextImpl.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/Mutexes.hpp> #include <xercesc/util/RuntimeException.hpp> #include <xercesc/util/UnexpectedEOFException.hpp> #include <xercesc/util/XMLMsgLoader.hpp> #include <xercesc/util/XMLRegisterCleanup.hpp> #include <xercesc/framework/LocalFileInputSource.hpp> #include <xercesc/framework/URLInputSource.hpp> #include <xercesc/framework/XMLDocumentHandler.hpp> #include <xercesc/framework/XMLEntityHandler.hpp> #include <xercesc/framework/XMLPScanToken.hpp> #include <xercesc/framework/XMLValidator.hpp> #include <xercesc/internal/EndOfEntityException.hpp> #include <xercesc/validators/DTD/DocTypeHandler.hpp> #include <xercesc/validators/common/GrammarResolver.hpp> #include <xercesc/util/OutOfMemoryException.hpp> #include <xercesc/util/XMLResourceIdentifier.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Local static data // --------------------------------------------------------------------------- static XMLUInt32 gScannerId; static bool sRegistered = false; static XMLMutex* sScannerMutex = 0; static XMLRegisterCleanup scannerMutexCleanup; static XMLMsgLoader* gMsgLoader = 0; static XMLRegisterCleanup cleanupMsgLoader; // --------------------------------------------------------------------------- // Local, static functions // --------------------------------------------------------------------------- // Cleanup for the message loader void XMLScanner::reinitMsgLoader() { delete gMsgLoader; gMsgLoader = 0; } // Cleanup for the scanner mutex void XMLScanner::reinitScannerMutex() { delete sScannerMutex; sScannerMutex = 0; sRegistered = false; } // // We need to fault in this mutex. But, since its used for synchronization // itself, we have to do this the low level way using a compare and swap. // static XMLMutex& gScannerMutex() { if (!sRegistered) { XMLMutexLock lockInit(XMLPlatformUtils::fgAtomicMutex); if (!sRegistered) { sScannerMutex = new XMLMutex; scannerMutexCleanup.registerCleanup(XMLScanner::reinitScannerMutex); sRegistered = true; } } return *sScannerMutex; } static XMLMsgLoader& gScannerMsgLoader() { if (!gMsgLoader) { XMLMutexLock lockInit(&gScannerMutex()); // If we haven't loaded our message yet, then do that if (!gMsgLoader) { gMsgLoader = XMLPlatformUtils::loadMsgSet(XMLUni::fgXMLErrDomain); if (!gMsgLoader) XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain); // Register this object to be cleaned up at termination cleanupMsgLoader.registerCleanup(XMLScanner::reinitMsgLoader); } } return *gMsgLoader; } // --------------------------------------------------------------------------- // XMLScanner: Constructors and Destructor // --------------------------------------------------------------------------- XMLScanner::XMLScanner(XMLValidator* const valToAdopt, GrammarResolver* const grammarResolver, MemoryManager* const manager) : fBufferSize(1024 * 1024) , fStandardUriConformant(false) , fCalculateSrcOfs(false) , fDoNamespaces(false) , fExitOnFirstFatal(true) , fValidationConstraintFatal(false) , fInException(false) , fStandalone(false) , fHasNoDTD(true) , fValidate(false) , fValidatorFromUser(false) , fDoSchema(false) , fSchemaFullChecking(false) , fIdentityConstraintChecking(true) , fToCacheGrammar(false) , fUseCachedGrammar(false) , fLoadExternalDTD(true) , fNormalizeData(true) , fGenerateSyntheticAnnotations(false) , fValidateAnnotations(false) , fErrorCount(0) , fEntityExpansionLimit(0) , fEntityExpansionCount(0) , fEmptyNamespaceId(0) , fUnknownNamespaceId(0) , fXMLNamespaceId(0) , fXMLNSNamespaceId(0) , fSchemaNamespaceId(0) , fUIntPool(0) , fUIntPoolRow(0) , fUIntPoolCol(0) , fUIntPoolRowTotal(2) , fScannerId(0) , fSequenceId(0) , fAttrList(0) , fAttrDupChkRegistry(0) , fDocHandler(0) , fDocTypeHandler(0) , fEntityHandler(0) , fErrorReporter(0) , fErrorHandler(0) , fPSVIHandler(0) , fValidationContext(0) , fEntityDeclPoolRetrieved(false) , fReaderMgr(manager) , fValidator(valToAdopt) , fValScheme(Val_Never) , fGrammarResolver(grammarResolver) , fGrammarPoolMemoryManager(grammarResolver->getGrammarPoolMemoryManager()) , fGrammar(0) , fRootGrammar(0) , fURIStringPool(0) , fRootElemName(0) , fExternalSchemaLocation(0) , fExternalNoNamespaceSchemaLocation(0) , fSecurityManager(0) , fXMLVersion(XMLReader::XMLV1_0) , fMemoryManager(manager) , fBufMgr(manager) , fAttNameBuf(1023, manager) , fAttValueBuf(1023, manager) , fCDataBuf(1023, manager) , fQNameBuf(1023, manager) , fPrefixBuf(1023, manager) , fURIBuf(1023, manager) , fElemStack(manager) { commonInit(); if (fValidator) { fValidatorFromUser = true; initValidator(fValidator); } } XMLScanner::XMLScanner( XMLDocumentHandler* const docHandler , DocTypeHandler* const docTypeHandler , XMLEntityHandler* const entityHandler , XMLErrorReporter* const errHandler , XMLValidator* const valToAdopt , GrammarResolver* const grammarResolver , MemoryManager* const manager) : fBufferSize(1024 * 1024) , fStandardUriConformant(false) , fCalculateSrcOfs(false) , fDoNamespaces(false) , fExitOnFirstFatal(true) , fValidationConstraintFatal(false) , fInException(false) , fStandalone(false) , fHasNoDTD(true) , fValidate(false) , fValidatorFromUser(false) , fDoSchema(false) , fSchemaFullChecking(false) , fIdentityConstraintChecking(true) , fToCacheGrammar(false) , fUseCachedGrammar(false) , fLoadExternalDTD(true) , fNormalizeData(true) , fGenerateSyntheticAnnotations(false) , fValidateAnnotations(false) , fErrorCount(0) , fEntityExpansionLimit(0) , fEntityExpansionCount(0) , fEmptyNamespaceId(0) , fUnknownNamespaceId(0) , fXMLNamespaceId(0) , fXMLNSNamespaceId(0) , fSchemaNamespaceId(0) , fUIntPool(0) , fUIntPoolRow(0) , fUIntPoolCol(0) , fUIntPoolRowTotal(2) , fScannerId(0) , fSequenceId(0) , fAttrList(0) , fAttrDupChkRegistry(0) , fDocHandler(docHandler) , fDocTypeHandler(docTypeHandler) , fEntityHandler(entityHandler) , fErrorReporter(errHandler) , fErrorHandler(0) , fPSVIHandler(0) , fValidationContext(0) , fEntityDeclPoolRetrieved(false) , fReaderMgr(manager) , fValidator(valToAdopt) , fValScheme(Val_Never) , fGrammarResolver(grammarResolver) , fGrammarPoolMemoryManager(grammarResolver->getGrammarPoolMemoryManager()) , fGrammar(0) , fRootGrammar(0) , fURIStringPool(0) , fRootElemName(0) , fExternalSchemaLocation(0) , fExternalNoNamespaceSchemaLocation(0) , fSecurityManager(0) , fXMLVersion(XMLReader::XMLV1_0) , fMemoryManager(manager) , fBufMgr(manager) , fAttNameBuf(1023, manager) , fAttValueBuf(1023, manager) , fCDataBuf(1023, manager) , fQNameBuf(1023, manager) , fPrefixBuf(1023, manager) , fURIBuf(1023, manager) , fElemStack(manager) { commonInit(); if (valToAdopt){ fValidatorFromUser = true; initValidator(fValidator); } } XMLScanner::~XMLScanner() { delete fAttrList; delete fAttrDupChkRegistry; delete fValidationContext; fMemoryManager->deallocate(fRootElemName);//delete [] fRootElemName; fMemoryManager->deallocate(fExternalSchemaLocation);//delete [] fExternalSchemaLocation; fMemoryManager->deallocate(fExternalNoNamespaceSchemaLocation);//delete [] fExternalNoNamespaceSchemaLocation; // delete fUIntPool for (unsigned int i=0; i<=fUIntPoolRow; i++) { fMemoryManager->deallocate(fUIntPool[i]); } fMemoryManager->deallocate(fUIntPool); } void XMLScanner::setValidator(XMLValidator* const valToAdopt) { if (fValidatorFromUser) delete fValidator; fValidator = valToAdopt; fValidatorFromUser = true; initValidator(fValidator); } // --------------------------------------------------------------------------- // XMLScanner: Main entry point to scan a document // --------------------------------------------------------------------------- void XMLScanner::scanDocument( const XMLCh* const systemId) { // First we try to parse it as a URL. If that fails, we assume its // a file and try it that way. InputSource* srcToUse = 0; try { // Create a temporary URL. Since this is the primary document, // it has to be fully qualified. If not, then assume we are just // mistaking a file for a URL. XMLURL tmpURL(fMemoryManager); if (XMLURL::parse(systemId, tmpURL)) { if (tmpURL.isRelative()) { if (!fStandardUriConformant) srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager); else { // since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr // emit the error directly MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_NoProtocolPresent, fMemoryManager); fInException = true; emitError ( XMLErrs::XMLException_Fatal , e.getType() , e.getMessage() ); return; } } else { if (fStandardUriConformant && tmpURL.hasInvalidChar()) { MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager); fInException = true; emitError ( XMLErrs::XMLException_Fatal , e.getType() , e.getMessage() ); return; } srcToUse = new (fMemoryManager) URLInputSource(tmpURL, fMemoryManager); } } else { if (!fStandardUriConformant) srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager); else { // since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr // emit the error directly // lazy bypass ... since all MalformedURLException are fatal, no need to check the type MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager); fInException = true; emitError ( XMLErrs::XMLException_Fatal , e.getType() , e.getMessage() ); return; } } } catch(const XMLException& excToCatch) { // For any other XMLException, // emit the error and catch any user exception thrown from here. fInException = true; if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning) emitError ( XMLErrs::XMLException_Warning , excToCatch.getType() , excToCatch.getMessage() ); else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal) emitError ( XMLErrs::XMLException_Fatal , excToCatch.getType() , excToCatch.getMessage() ); else emitError ( XMLErrs::XMLException_Error , excToCatch.getType() , excToCatch.getMessage() ); return; } Janitor<InputSource> janSrc(srcToUse); scanDocument(*srcToUse); } void XMLScanner::scanDocument( const char* const systemId) { // We just delegate this to the XMLCh version after transcoding XMLCh* tmpBuf = XMLString::transcode(systemId, fMemoryManager); ArrayJanitor<XMLCh> janBuf(tmpBuf, fMemoryManager); scanDocument(tmpBuf); } // This method begins a progressive parse. It scans through the prolog and // returns a token to be used on subsequent scanNext() calls. If the return // value is true, then the token is legal and ready for further use. If it // returns false, then the scan of the prolog failed and the token is not // going to work on subsequent scanNext() calls. bool XMLScanner::scanFirst( const XMLCh* const systemId , XMLPScanToken& toFill) { // First we try to parse it as a URL. If that fails, we assume its // a file and try it that way. InputSource* srcToUse = 0; try { // Create a temporary URL. Since this is the primary document, // it has to be fully qualified. If not, then assume we are just // mistaking a file for a URL. XMLURL tmpURL(fMemoryManager); if (XMLURL::parse(systemId, tmpURL)) { if (tmpURL.isRelative()) { if (!fStandardUriConformant) srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager); else { // since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr // emit the error directly MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_NoProtocolPresent, fMemoryManager); fInException = true; emitError ( XMLErrs::XMLException_Fatal , e.getType() , e.getMessage() ); return false; } } else { if (fStandardUriConformant && tmpURL.hasInvalidChar()) { MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager); fInException = true; emitError ( XMLErrs::XMLException_Fatal , e.getType() , e.getMessage() ); return false; } srcToUse = new (fMemoryManager) URLInputSource(tmpURL, fMemoryManager); } } else { if (!fStandardUriConformant) srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager); else { // since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr // emit the error directly // lazy bypass ... since all MalformedURLException are fatal, no need to check the type MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL); fInException = true; emitError ( XMLErrs::XMLException_Fatal , e.getType() , e.getMessage() ); return false; } } } catch(const XMLException& excToCatch) { // For any other XMLException, // emit the error and catch any user exception thrown from here. fInException = true; if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning) emitError ( XMLErrs::XMLException_Warning , excToCatch.getType() , excToCatch.getMessage() ); else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal) emitError ( XMLErrs::XMLException_Fatal , excToCatch.getType() , excToCatch.getMessage() ); else emitError ( XMLErrs::XMLException_Error , excToCatch.getType() , excToCatch.getMessage() ); return false; } Janitor<InputSource> janSrc(srcToUse); return scanFirst(*srcToUse, toFill); } bool XMLScanner::scanFirst( const char* const systemId , XMLPScanToken& toFill) { // We just delegate this to the XMLCh version after transcoding XMLCh* tmpBuf = XMLString::transcode(systemId, fMemoryManager); ArrayJanitor<XMLCh> janBuf(tmpBuf, fMemoryManager); return scanFirst(tmpBuf, toFill); } bool XMLScanner::scanFirst( const InputSource& src , XMLPScanToken& toFill) { // Bump up the sequence id for this new scan cycle. This will invalidate // any previous tokens we've returned. fSequenceId++; // Reset the scanner and its plugged in stuff for a new run. This // resets all the data structures, creates the initial reader and // pushes it on the stack, and sets up the base document path scanReset(src); // If we have a document handler, then call the start document if (fDocHandler) fDocHandler->startDocument(); try { // Scan the prolog part, which is everything before the root element // including the DTD subsets. This is all that is done on the scan // first. scanProlog(); // If we got to the end of input, then its not a valid XML file. // Else, go on to scan the content. if (fReaderMgr.atEOF()) { emitError(XMLErrs::EmptyMainEntity); } } // NOTE: // // In all of the error processing below, the emitError() call MUST come // before the flush of the reader mgr, or it will fail because it tries // to find out the position in the XML source of the error. catch(const XMLErrs::Codes) { // This is a 'first failure' exception so reset and return a failure fReaderMgr.reset(); return false; } catch(const XMLValid::Codes) { // This is a 'first fatal error' type exit, so reset and reuturn failure fReaderMgr.reset(); return false; } catch(const XMLException& excToCatch) { // Emit the error and catch any user exception thrown from here. Make // sure in all cases we flush the reader manager. fInException = true; try { if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning) emitError ( XMLErrs::XMLException_Warning , excToCatch.getType() , excToCatch.getMessage() ); else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal) emitError ( XMLErrs::XMLException_Fatal , excToCatch.getType() , excToCatch.getMessage() ); else emitError ( XMLErrs::XMLException_Error , excToCatch.getType() , excToCatch.getMessage() ); } catch(const OutOfMemoryException&) { throw; } catch(...) { // Reset and rethrow the user error fReaderMgr.reset(); throw; } // Reset and return a failure fReaderMgr.reset(); return false; } catch(const OutOfMemoryException&) { throw; } catch(...) { // Reset and rethrow original error fReaderMgr.reset(); throw; } // Fill in the caller's token to make it legal and return success toFill.set(fScannerId, fSequenceId); return true; } void XMLScanner::scanReset(XMLPScanToken& token) { // Make sure this token is still legal if (!isLegalToken(token)) ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Scan_BadPScanToken, fMemoryManager); // Reset the reader manager fReaderMgr.reset(); // And invalidate any tokens by bumping our sequence number fSequenceId++; // Reset our error count fErrorCount = 0; } void XMLScanner::setParseSettings(XMLScanner* const refScanner) { setDocHandler(refScanner->getDocHandler()); setDocTypeHandler(refScanner->getDocTypeHandler()); setErrorHandler(refScanner->getErrorHandler()); setErrorReporter(refScanner->getErrorReporter()); setEntityHandler(refScanner->getEntityHandler()); setDoNamespaces(refScanner->getDoNamespaces()); setDoSchema(refScanner->getDoSchema()); setCalculateSrcOfs(refScanner->getCalculateSrcOfs()); setStandardUriConformant(refScanner->getStandardUriConformant()); setExitOnFirstFatal(refScanner->getExitOnFirstFatal()); setValidationConstraintFatal(refScanner->getValidationConstraintFatal()); setIdentityConstraintChecking(refScanner->getIdentityConstraintChecking()); setValidationSchemaFullChecking(refScanner->getValidationSchemaFullChecking()); cacheGrammarFromParse(refScanner->isCachingGrammarFromParse()); useCachedGrammarInParse(refScanner->isUsingCachedGrammarInParse()); setLoadExternalDTD(refScanner->getLoadExternalDTD()); setNormalizeData(refScanner->getNormalizeData()); setExternalSchemaLocation(refScanner->getExternalSchemaLocation()); setExternalNoNamespaceSchemaLocation(refScanner->getExternalNoNamespaceSchemaLocation()); setValidationScheme(refScanner->getValidationScheme()); setSecurityManager(refScanner->getSecurityManager()); setPSVIHandler(refScanner->getPSVIHandler()); } // --------------------------------------------------------------------------- // XMLScanner: Private helper methods. // --------------------------------------------------------------------------- // This method handles the common initialization, to avoid having to do // it redundantly in multiple constructors. void XMLScanner::commonInit() { // We have to do a little init that involves statics, so we have to // use the mutex to protect it. { XMLMutexLock lockInit(&gScannerMutex()); // And assign ourselves the next available scanner id fScannerId = ++gScannerId; } // Create the attribute list, which is used to store attribute values // during start tag processing. Give it a reasonable initial size that // will serve for most folks, though it will grow as required. fAttrList = new (fMemoryManager) RefVectorOf<XMLAttr>(32, true, fMemoryManager); // Create the id ref list. This is used to enforce XML 1.0 ID ref // semantics, i.e. all id refs must refer to elements that exist fValidationContext = new (fMemoryManager) ValidationContextImpl(fMemoryManager); // Create the GrammarResolver //fGrammarResolver = new GrammarResolver(); // create initial, 64-element, fUIntPool fUIntPool = (unsigned int **)fMemoryManager->allocate(sizeof(unsigned int *) *fUIntPoolRowTotal); fUIntPool[0] = (unsigned int *)fMemoryManager->allocate(sizeof(unsigned int) << 6); memset(fUIntPool[0], 0, sizeof(unsigned int) << 6); fUIntPool[1] = 0; // Register self as handler for XMLBufferFull events on the CDATA buffer fCDataBuf.setFullHandler(this, fBufferSize); } void XMLScanner::initValidator(XMLValidator* theValidator) { // Tell the validator about the stuff it needs to know in order to // do its work. theValidator->setScannerInfo(this, &fReaderMgr, &fBufMgr); theValidator->setErrorReporter(fErrorReporter); } // --------------------------------------------------------------------------- // XMLScanner: Error emitting methods // --------------------------------------------------------------------------- // These methods are called whenever the scanner wants to emit an error. // It handles getting the message loaded, doing token replacement, etc... // and then calling the error handler, if its installed. bool XMLScanner::emitErrorWillThrowException(const XMLErrs::Codes toEmit) { if (XMLErrs::isFatal(toEmit) && fExitOnFirstFatal && !fInException) return true; return false; } void XMLScanner::emitError(const XMLErrs::Codes toEmit) { // Bump the error count if it is not a warning if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning) incrementErrorCount(); if (fErrorReporter) { // Load the message into a local for display const unsigned int msgSize = 1023; XMLCh errText[msgSize + 1]; if (!gScannerMsgLoader().loadMsg(toEmit, errText, msgSize)) { // <TBD> Probably should load a default msg here } // Create a LastExtEntityInfo structure and get the reader manager // to fill it in for us. This will give us the information about // the last reader on the stack that was an external entity of some // sort (i.e. it will ignore internal entities. ReaderMgr::LastExtEntityInfo lastInfo; fReaderMgr.getLastExtEntityInfo(lastInfo); fErrorReporter->error ( toEmit , XMLUni::fgXMLErrDomain , XMLErrs::errorType(toEmit) , errText , lastInfo.systemId , lastInfo.publicId , lastInfo.lineNumber , lastInfo.colNumber ); } // Bail out if its fatal an we are to give up on the first fatal error if (emitErrorWillThrowException(toEmit)) throw toEmit; } void XMLScanner::emitError( const XMLErrs::Codes toEmit , const XMLCh* const text1 , const XMLCh* const text2 , const XMLCh* const text3 , const XMLCh* const text4) { // Bump the error count if it is not a warning if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning) incrementErrorCount(); if (fErrorReporter) { // Load the message into alocal and replace any tokens found in // the text. const unsigned int maxChars = 2047; XMLCh errText[maxChars + 1]; if (!gScannerMsgLoader().loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, fMemoryManager)) { // <TBD> Should probably load a default message here } // Create a LastExtEntityInfo structure and get the reader manager // to fill it in for us. This will give us the information about // the last reader on the stack that was an external entity of some // sort (i.e. it will ignore internal entities. ReaderMgr::LastExtEntityInfo lastInfo; fReaderMgr.getLastExtEntityInfo(lastInfo); fErrorReporter->error ( toEmit , XMLUni::fgXMLErrDomain , XMLErrs::errorType(toEmit) , errText , lastInfo.systemId , lastInfo.publicId , lastInfo.lineNumber , lastInfo.colNumber ); } // Bail out if its fatal an we are to give up on the first fatal error if (emitErrorWillThrowException(toEmit)) throw toEmit; } void XMLScanner::emitError( const XMLErrs::Codes toEmit , const char* const text1 , const char* const text2 , const char* const text3 , const char* const text4) { // Bump the error count if it is not a warning if (XMLErrs::errorType(toEmit) != XMLErrorReporter::ErrType_Warning) incrementErrorCount(); if (fErrorReporter) { // Load the message into alocal and replace any tokens found in // the text. const unsigned int maxChars = 2047; XMLCh errText[maxChars + 1]; if (!gScannerMsgLoader().loadMsg(toEmit, errText, maxChars, text1, text2, text3, text4, fMemoryManager)) { // <TBD> Should probably load a default message here } // Create a LastExtEntityInfo structure and get the reader manager // to fill it in for us. This will give us the information about // the last reader on the stack that was an external entity of some // sort (i.e. it will ignore internal entities. ReaderMgr::LastExtEntityInfo lastInfo; fReaderMgr.getLastExtEntityInfo(lastInfo); fErrorReporter->error ( toEmit , XMLUni::fgXMLErrDomain , XMLErrs::errorType(toEmit) , errText , lastInfo.systemId , lastInfo.publicId , lastInfo.lineNumber , lastInfo.colNumber ); } // Bail out if its fatal an we are to give up on the first fatal error if (emitErrorWillThrowException(toEmit)) throw toEmit; } // --------------------------------------------------------------------------- // XMLScanner: Getter methods // --------------------------------------------------------------------------- // This method allows the caller to query the current location of the scanner. // It will return the sys/public ids of the current entity, and the line/col // position within it. // // NOTE: This API returns the location with the last external file. So if its // currently scanning an entity, the position returned will be the end of // the entity reference in the file that had the reference. // /*bool XMLScanner::getLastExtLocation( XMLCh* const sysIdToFill , const unsigned int maxSysIdChars , XMLCh* const pubIdToFill , const unsigned int maxPubIdChars , XMLSSize_t& lineToFill , XMLSSize_t& colToFill) const { // Create a local info object and get it filled in by the reader manager ReaderMgr::LastExtEntityInfo lastInfo; fReaderMgr.getLastExtEntityInfo(lastInfo); // Fill in the line and column number lineToFill = lastInfo.lineNumber; colToFill = lastInfo.colNumber; // And copy over as much of the ids as will fit sysIdToFill[0] = 0; if (lastInfo.systemId) { if (XMLString::stringLen(lastInfo.systemId) > maxSysIdChars) return false; XMLString::copyString(sysIdToFill, lastInfo.systemId); } pubIdToFill[0] = 0; if (lastInfo.publicId) { if (XMLString::stringLen(lastInfo.publicId) > maxPubIdChars) return false; XMLString::copyString(pubIdToFill, lastInfo.publicId); } return true; }*/ // --------------------------------------------------------------------------- // XMLScanner: Private scanning methods // --------------------------------------------------------------------------- // This method is called after the end of the root element, to handle // any miscellaneous stuff hanging around. void XMLScanner::scanMiscellaneous() { // Get a buffer for this work XMLBufBid bbCData(&fBufMgr); while (true) { try { const XMLCh nextCh = fReaderMgr.peekNextChar(); // Watch for end of file and break out if (!nextCh) break; if (nextCh == chOpenAngle) { if (checkXMLDecl(true)) { // Can't have an XML decl here emitError(XMLErrs::NotValidAfterContent); fReaderMgr.skipPastChar(chCloseAngle); } else if (fReaderMgr.skippedString(XMLUni::fgPIString)) { scanPI(); } else if (fReaderMgr.skippedString(XMLUni::fgCommentString)) { scanComment(); } else { // This can't be possible, so just give up emitError(XMLErrs::ExpectedCommentOrPI); fReaderMgr.skipPastChar(chCloseAngle); } } else if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh)) { // If we have a doc handler, then gather up the spaces and // call back. Otherwise, just skip over whitespace. if (fDocHandler) { fReaderMgr.getSpaces(bbCData.getBuffer()); fDocHandler->ignorableWhitespace ( bbCData.getRawBuffer() , bbCData.getLen() , false ); } else { fReaderMgr.skipPastSpaces(); } } else { emitError(XMLErrs::ExpectedCommentOrPI); fReaderMgr.skipPastChar(chCloseAngle); } } catch(const EndOfEntityException&) { // Some entity leaked out of the content part of the document. Issue // a warning and keep going. emitError(XMLErrs::EntityPropogated); } } } // Scans a PI and calls the appropriate callbacks. At entry we have just // scanned the <? part, and need to now start on the PI target name. void XMLScanner::scanPI() { const XMLCh* namePtr = 0; const XMLCh* targetPtr = 0; // If there are any spaces here, then warn about it. If we aren't in // 'first error' mode, then we'll come back and can easily pick up // again by just skipping them. if (fReaderMgr.lookingAtSpace()) { emitError(XMLErrs::PINameExpected); fReaderMgr.skipPastSpaces(); } // Get a buffer for the PI name and scan it in XMLBufBid bbName(&fBufMgr); if (!fReaderMgr.getName(bbName.getBuffer())) { emitError(XMLErrs::PINameExpected); fReaderMgr.skipPastChar(chCloseAngle); return; } // Point the name pointer at the raw data namePtr = bbName.getRawBuffer(); // See if it is some form of 'xml' and emit a warning if (!XMLString::compareIString(namePtr, XMLUni::fgXMLString)) emitError(XMLErrs::NoPIStartsWithXML); // If namespaces are enabled, then no colons allowed if (fDoNamespaces) { if (XMLString::indexOf(namePtr, chColon) != -1) emitError(XMLErrs::ColonNotLegalWithNS); } // If we don't hit a space next, then the PI has no target. If we do // then get out the target. Get a buffer for it as well XMLBufBid bbTarget(&fBufMgr); if (fReaderMgr.skippedSpace()) { // Skip any leading spaces fReaderMgr.skipPastSpaces(); bool gotLeadingSurrogate = false; // It does have a target, so lets move on to deal with that. while (1) { const XMLCh nextCh = fReaderMgr.getNextChar(); // Watch for an end of file, which is always bad here if (!nextCh) { emitError(XMLErrs::UnterminatedPI); ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); } // Watch for potential terminating character if (nextCh == chQuestion) { // It must be followed by '>' to be a termination of the target if (fReaderMgr.skippedChar(chCloseAngle)) break; } // Check for correct surrogate pairs if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { if (gotLeadingSurrogate) emitError(XMLErrs::Expected2ndSurrogateChar); else gotLeadingSurrogate = true; } else { if (gotLeadingSurrogate) { if ((nextCh < 0xDC00) || (nextCh > 0xDFFF)) emitError(XMLErrs::Expected2ndSurrogateChar); } // Its got to at least be a valid XML character else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); emitError(XMLErrs::InvalidCharacter, tmpBuf); } gotLeadingSurrogate = false; } bbTarget.append(nextCh); } } else { // No target, but make sure its terminated ok if (!fReaderMgr.skippedChar(chQuestion)) { emitError(XMLErrs::UnterminatedPI); fReaderMgr.skipPastChar(chCloseAngle); return; } if (!fReaderMgr.skippedChar(chCloseAngle)) { emitError(XMLErrs::UnterminatedPI); fReaderMgr.skipPastChar(chCloseAngle); return; } } // Point the target pointer at the raw data targetPtr = bbTarget.getRawBuffer(); // If we have a handler, then call it if (fDocHandler) { fDocHandler->docPI ( namePtr , targetPtr ); } //mark PI is seen within the current element if (! fElemStack.isEmpty()) fElemStack.setCommentOrPISeen(); } // Scans all the input from the start of the file to the root element. // There does not have to be anything in the prolog necessarily, but usually // there is at least an XMLDecl. // // On exit from here we are either at the end of the file or about to read // the opening < of the root element. void XMLScanner::scanProlog() { // Get a buffer for whitespace processing XMLBufBid bbCData(&fBufMgr); // Loop through the prolog. If there is no content, this could go all // the way to the end of the file. try { while (true) { const XMLCh nextCh = fReaderMgr.peekNextChar(); if (nextCh == chOpenAngle) { // Ok, it could be the xml decl, a comment, the doc type line, // or the start of the root element. if (checkXMLDecl(true)) { // There shall be at lease --ONE-- space in between // the tag '<?xml' and the VersionInfo. // // If we are not at line 1, col 6, then the decl was not // the first text, so its invalid. const XMLReader* curReader = fReaderMgr.getCurrentReader(); if ((curReader->getLineNumber() != 1) || (curReader->getColumnNumber() != 7)) { emitError(XMLErrs::XMLDeclMustBeFirst); } scanXMLDecl(Decl_XML); } else if (fReaderMgr.skippedString(XMLUni::fgPIString)) { scanPI(); } else if (fReaderMgr.skippedString(XMLUni::fgCommentString)) { scanComment(); } else if (fReaderMgr.skippedString(XMLUni::fgDocTypeString)) { scanDocTypeDecl(); // if reusing grammar, this has been validated already in first scan // skip for performance if (fValidate && !fGrammar->getValidated()) { // validate the DTD scan so far fValidator->preContentValidation(fUseCachedGrammar, true); } } else { // Assume its the start of the root element return; } } else if (fReaderMgr.getCurrentReader()->isWhitespace(nextCh)) { // If we have a document handler then gather up the // whitespace and call back. Otherwise just skip over spaces. if (fDocHandler) { fReaderMgr.getSpaces(bbCData.getBuffer()); fDocHandler->ignorableWhitespace ( bbCData.getRawBuffer() , bbCData.getLen() , false ); } else { fReaderMgr.skipPastSpaces(); } } else { emitError(XMLErrs::InvalidDocumentStructure); // Watch for end of file and break out if (!nextCh) break; else fReaderMgr.skipPastChar(chCloseAngle); } } } catch(const EndOfEntityException&) { // We should never get an end of entity here. They should only // occur within the doc type scanning method, and not leak out to // here. emitError ( XMLErrs::UnexpectedEOE , "in prolog" ); } } // Scans the <?xml .... ?> line. This stuff is all sequential so we don't // do any state machine loop here. We just bull straight through it. It ends // past the closing bracket. If there is a document handler, then its called // on the XMLDecl callback. // // On entry, the <?xml has been scanned, and we pick it up from there. // // NOTE: In order to provide good recovery from bad XML here, we try to be // very flexible. No matter what order the stuff is in, we'll keep going // though we'll issue errors. // // The parameter tells us which type of decl we should expect, Text or XML. // [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>' // [77] TextDecl::= '<?xml' VersionInfo? EncodingDecl S? '?>' void XMLScanner::scanXMLDecl(const DeclTypes type) { // Get us some buffers to use XMLBufBid bbVersion(&fBufMgr); XMLBufBid bbEncoding(&fBufMgr); XMLBufBid bbStand(&fBufMgr); XMLBufBid bbDummy(&fBufMgr); XMLBufBid bbName(&fBufMgr); // We use this little enum and array to keep up with what we found // and what order we found them in. This lets us get them free form // without too much overhead, but still know that they were in the // wrong order. enum Strings { VersionString , EncodingString , StandaloneString , UnknownString , StringCount }; int flags[StringCount] = { -1, -1, -1, -1 }; // Also set up a list of buffers in the right order so that we know // where to put stuff. XMLBuffer* buffers[StringCount] ; buffers[0] = &bbVersion.getBuffer(); buffers[1] = &bbEncoding.getBuffer(); buffers[2] = &bbStand.getBuffer(); buffers[3] = &bbDummy.getBuffer(); int curCount = 0; Strings curString; XMLBuffer& nameBuf = bbName.getBuffer(); while (true) { // Skip any spaces const unsigned int spaceCount = fReaderMgr.skipPastSpaces(true); // If we are looking at a question mark, then break out if (fReaderMgr.lookingAtChar(chQuestion)) break; // If this is not the first string, then we require the spaces if (!spaceCount && curCount) emitError(XMLErrs::ExpectedWhitespace); // Get characters up to the next whitespace or equal's sign. if (!scanUpToWSOr(nameBuf, chEqual)) emitError(XMLErrs::ExpectedDeclString); // See if it matches any of our expected strings if (XMLString::equals(nameBuf.getRawBuffer(), XMLUni::fgVersionString)) curString = VersionString; else if (XMLString::equals(nameBuf.getRawBuffer(), XMLUni::fgEncodingString)) curString = EncodingString; else if (XMLString::equals(nameBuf.getRawBuffer(), XMLUni::fgStandaloneString)) curString = StandaloneString; else curString = UnknownString; // If its an unknown string, then give that error. Else check to // see if this one has been done already and give that error. if (curString == UnknownString) emitError(XMLErrs::ExpectedDeclString, nameBuf.getRawBuffer()); else if (flags[curString] != -1) emitError(XMLErrs::DeclStringRep, nameBuf.getRawBuffer()); else if (flags[curString] == -1) flags[curString] = ++curCount; // Scan for an equal's sign. If we don't find it, issue an error // but keep trying to go on. if (!scanEq(true)) emitError(XMLErrs::ExpectedEqSign); // Get a quote string into the buffer for the string that we are // currently working on. if (!getQuotedString(*buffers[curString])) { emitError(XMLErrs::ExpectedQuotedString); fReaderMgr.skipPastChar(chCloseAngle); return; } // And validate the value according which one it was const XMLCh* rawValue = buffers[curString]->getRawBuffer(); if (curString == VersionString) { if (XMLString::equals(rawValue, XMLUni::fgVersion1_1)) { if (type == Decl_XML) { fXMLVersion = XMLReader::XMLV1_1; fReaderMgr.setXMLVersion(XMLReader::XMLV1_1); } else { if (fXMLVersion != XMLReader::XMLV1_1) emitError(XMLErrs::UnsupportedXMLVersion, rawValue); } } else if (XMLString::equals(rawValue, XMLUni::fgVersion1_0)) { if (type == Decl_XML) { fXMLVersion = XMLReader::XMLV1_0; fReaderMgr.setXMLVersion(XMLReader::XMLV1_0); } } else emitError(XMLErrs::UnsupportedXMLVersion, rawValue); } else if (curString == EncodingString) { if (!XMLString::isValidEncName(rawValue)) emitError(XMLErrs::BadXMLEncoding, rawValue); } else if (curString == StandaloneString) { if (XMLString::equals(rawValue, XMLUni::fgYesString)) fStandalone = true; else if (XMLString::equals(rawValue, XMLUni::fgNoString)) fStandalone = false; else { emitError(XMLErrs::BadStandalone); if (!XMLString::compareIString(rawValue, XMLUni::fgYesString)) fStandalone = true; else if (!XMLString::compareIString(rawValue, XMLUni::fgNoString)) fStandalone = false; } } } // Make sure that the strings present are in order. We don't care about // which ones are present at this point, just that any there are in the // right order. int curTop = 0; for (int index = VersionString; index < StandaloneString; index++) { if (flags[index] != -1) { if (flags[index] != curTop + 1) { emitError(XMLErrs::DeclStringsInWrongOrder); break; } curTop = flags[index]; } } // If its an XML decl, the version must be present. // If its a Text decl, then encoding must be present AND standalone must not be present. if ((type == Decl_XML) && (flags[VersionString] == -1)) emitError(XMLErrs::XMLVersionRequired); else if (type == Decl_Text) { if (flags[StandaloneString] != -1) emitError(XMLErrs::StandaloneNotLegal); if (flags[EncodingString] == -1) emitError(XMLErrs::EncodingRequired); } if (!fReaderMgr.skippedChar(chQuestion)) { emitError(XMLErrs::UnterminatedXMLDecl); fReaderMgr.skipPastChar(chCloseAngle); } else if (!fReaderMgr.skippedChar(chCloseAngle)) { emitError(XMLErrs::UnterminatedXMLDecl); fReaderMgr.skipPastChar(chCloseAngle); } // Do this before we possibly update the reader with the // actual encoding string. Otherwise, we will pass the wrong thing // for the last parameter! const XMLCh* actualEnc = fReaderMgr.getCurrentEncodingStr(); // Ok, we've now seen the real encoding string, if there was one, so // lets call back on the current reader and tell it what the real // encoding string was. If it fails, that's because it represents some // sort of contradiction with the autosensed format, and it keeps the // original encoding. // // NOTE: This can fail for a number of reasons, such as a bogus encoding // name or because its in flagrant contradiction of the auto-sensed // format. if (flags[EncodingString] != -1) { if (!fReaderMgr.getCurrentReader()->setEncoding(bbEncoding.getRawBuffer())) emitError(XMLErrs::ContradictoryEncoding, bbEncoding.getRawBuffer()); else actualEnc = bbEncoding.getRawBuffer(); } // If we have a document handler then call the XML Decl callback. if (type == Decl_XML) { if (fDocHandler) fDocHandler->XMLDecl ( bbVersion.getRawBuffer() , bbEncoding.getRawBuffer() , bbStand.getRawBuffer() , actualEnc ); } else if (type == Decl_Text) { if (fDocTypeHandler) fDocTypeHandler->TextDecl ( bbVersion.getRawBuffer() , bbEncoding.getRawBuffer() ); } } const XMLCh* XMLScanner::getURIText(const unsigned int uriId) const { if (fURIStringPool->exists(uriId)) { // Look up the URI in the string pool and return its id const XMLCh* value = fURIStringPool->getValueForId(uriId); if (!value) return XMLUni::fgZeroLenString; return value; } else return XMLUni::fgZeroLenString; } bool XMLScanner::getURIText( const unsigned int uriId , XMLBuffer& uriBufToFill) const { if (fURIStringPool->exists(uriId)) { // Look up the URI in the string pool and return its id const XMLCh* value = fURIStringPool->getValueForId(uriId); if (!value) return false; uriBufToFill.set(value); return true; } else return false; } bool XMLScanner::checkXMLDecl(bool startWithAngle) { // [23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>' // [24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"') // // [3] S ::= (#x20 | #x9 | #xD | #xA)+ if (startWithAngle) { if (fReaderMgr.peekString(XMLUni::fgXMLDeclString)) { if (fReaderMgr.skippedString(XMLUni::fgXMLDeclStringSpace) || fReaderMgr.skippedString(XMLUni::fgXMLDeclStringHTab) || fReaderMgr.skippedString(XMLUni::fgXMLDeclStringLF) || fReaderMgr.skippedString(XMLUni::fgXMLDeclStringCR)) { return true; } else if (fReaderMgr.skippedString(XMLUni::fgXMLDeclStringSpaceU) || fReaderMgr.skippedString(XMLUni::fgXMLDeclStringHTabU) || fReaderMgr.skippedString(XMLUni::fgXMLDeclStringLFU) || fReaderMgr.skippedString(XMLUni::fgXMLDeclStringCRU)) { // Just in case, check for upper case. If found, issue // an error, but keep going. emitError(XMLErrs::XMLDeclMustBeLowerCase); return true; } } } else { if (fReaderMgr.peekString(XMLUni::fgXMLString)) { if (fReaderMgr.skippedString(XMLUni::fgXMLStringSpace) || fReaderMgr.skippedString(XMLUni::fgXMLStringHTab) || fReaderMgr.skippedString(XMLUni::fgXMLStringLF) || fReaderMgr.skippedString(XMLUni::fgXMLStringCR)) { return true; } else if (fReaderMgr.skippedString(XMLUni::fgXMLStringSpaceU) || fReaderMgr.skippedString(XMLUni::fgXMLStringHTabU) || fReaderMgr.skippedString(XMLUni::fgXMLStringLFU) || fReaderMgr.skippedString(XMLUni::fgXMLStringCRU)) { // Just in case, check for upper case. If found, issue // an error, but keep going. emitError(XMLErrs::XMLDeclMustBeLowerCase); return true; } } } return false; } // --------------------------------------------------------------------------- // XMLScanner: Grammar preparsing // --------------------------------------------------------------------------- Grammar* XMLScanner::loadGrammar(const XMLCh* const systemId , const short grammarType , const bool toCache) { InputSource* srcToUse = 0; if (fEntityHandler){ ReaderMgr::LastExtEntityInfo lastInfo; fReaderMgr.getLastExtEntityInfo(lastInfo); XMLResourceIdentifier resourceIdentifier(XMLResourceIdentifier::ExternalEntity, systemId, 0, XMLUni::fgZeroLenString, lastInfo.systemId); srcToUse = fEntityHandler->resolveEntity(&resourceIdentifier); } // First we try to parse it as a URL. If that fails, we assume its // a file and try it that way. if (!srcToUse) { try { // Create a temporary URL. Since this is the primary document, // it has to be fully qualified. If not, then assume we are just // mistaking a file for a URL. XMLURL tmpURL(fMemoryManager); if (XMLURL::parse(systemId, tmpURL)) { if (tmpURL.isRelative()) { if (!fStandardUriConformant) srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager); else { // since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr // emit the error directly MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_NoProtocolPresent, fMemoryManager); fInException = true; emitError ( XMLErrs::XMLException_Fatal , e.getType() , e.getMessage() ); return 0; } } else { if (fStandardUriConformant && tmpURL.hasInvalidChar()) { MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL, fMemoryManager); fInException = true; emitError ( XMLErrs::XMLException_Fatal , e.getType() , e.getMessage() ); return 0; } srcToUse = new (fMemoryManager) URLInputSource(tmpURL, fMemoryManager); } } else { if (!fStandardUriConformant) srcToUse = new (fMemoryManager) LocalFileInputSource(systemId, fMemoryManager); else { // since this is the top of the try/catch, cannot call ThrowXMLwithMemMgr // emit the error directly // lazy bypass ... since all MalformedURLException are fatal, no need to check the type MalformedURLException e(__FILE__, __LINE__, XMLExcepts::URL_MalformedURL); fInException = true; emitError ( XMLErrs::XMLException_Fatal , e.getType() , e.getMessage() ); return 0; } } } catch(const XMLException& excToCatch) { // For any other XMLException, // emit the error and catch any user exception thrown from here. fInException = true; if (excToCatch.getErrorType() == XMLErrorReporter::ErrType_Warning) emitError ( XMLErrs::XMLException_Warning , excToCatch.getType() , excToCatch.getMessage() ); else if (excToCatch.getErrorType() >= XMLErrorReporter::ErrType_Fatal) emitError ( XMLErrs::XMLException_Fatal , excToCatch.getType() , excToCatch.getMessage() ); else emitError ( XMLErrs::XMLException_Error , excToCatch.getType() , excToCatch.getMessage() ); return 0; } } Janitor<InputSource> janSrc(srcToUse); return loadGrammar(*srcToUse, grammarType, toCache); } Grammar* XMLScanner::loadGrammar(const char* const systemId , const short grammarType , const bool toCache) { // We just delegate this to the XMLCh version after transcoding XMLCh* tmpBuf = XMLString::transcode(systemId, fMemoryManager); ArrayJanitor<XMLCh> janBuf(tmpBuf, fMemoryManager); return loadGrammar(tmpBuf, grammarType, toCache); } // --------------------------------------------------------------------------- // XMLScanner: Setter methods // --------------------------------------------------------------------------- void XMLScanner::setURIStringPool(XMLStringPool* const stringPool) { fURIStringPool = stringPool; fEmptyNamespaceId = fURIStringPool->addOrFind(XMLUni::fgZeroLenString); fUnknownNamespaceId = fURIStringPool->addOrFind(XMLUni::fgUnknownURIName); fXMLNamespaceId = fURIStringPool->addOrFind(XMLUni::fgXMLURIName); fXMLNSNamespaceId = fURIStringPool->addOrFind(XMLUni::fgXMLNSURIName); } // --------------------------------------------------------------------------- // XMLScanner: Private helper methods // --------------------------------------------------------------------------- /*** * In reusing grammars (cacheing grammar from parse, or use cached grammar), internal * dtd is allowed conditionally. * * In the case of cacheing grammar from parse, it is NOT allowed. * * In the case of use cached grammar, * if external dtd is present and it is parsed before, then it is not allowed, * otherwise it is allowed. * ***/ void XMLScanner::checkInternalDTD(bool hasExtSubset, const XMLCh* const sysId) { if (fToCacheGrammar) ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Val_CantHaveIntSS, fMemoryManager); if (fUseCachedGrammar && hasExtSubset ) { InputSource* sysIdSrc = resolveSystemId(sysId); Janitor<InputSource> janSysIdSrc(sysIdSrc); Grammar* grammar = fGrammarResolver->getGrammar(sysIdSrc->getSystemId()); if (grammar && grammar->getGrammarType() == Grammar::DTDGrammarType) { ThrowXMLwithMemMgr(RuntimeException, XMLExcepts::Val_CantHaveIntSS, fMemoryManager); } } } // This method is called after the content scan to insure that all the // ID/IDREF attributes match up (i.e. that all IDREFs refer to IDs.) This is // an XML 1.0 rule, so we can do here in the core. void XMLScanner::checkIDRefs() { // Iterate the id ref list. If we find any entries here which are used // but not declared, then that's an error. RefHashTableOfEnumerator<XMLRefInfo> refEnum(fValidationContext->getIdRefList(), false, fMemoryManager); while (refEnum.hasMoreElements()) { // Get a ref to the current element const XMLRefInfo& curRef = refEnum.nextElement(); // If its used but not declared, then its an error if (!curRef.getDeclared() && curRef.getUsed() && fValidate) fValidator->emitError(XMLValid::IDNotDeclared, curRef.getRefName()); } } // This just does a simple check that the passed progressive scan token is // legal for this scanner. bool XMLScanner::isLegalToken(const XMLPScanToken& toCheck) { return ((fScannerId == toCheck.fScannerId) && (fSequenceId == toCheck.fSequenceId)); } // This method will handle figuring out what the next top level token is // in the input stream. It will return an enumerated value that indicates // what it believes the next XML level token must be. It will eat as many // chars are required to figure out what is next. XMLScanner::XMLTokens XMLScanner::senseNextToken(unsigned int& orgReader) { // Get the next character and use it to guesstimate what the next token // is going to be. We turn on end of entity exceptions when we do this // in order to catch the scenario where the current entity ended at // the > of some markup. XMLCh nextCh; { ThrowEOEJanitor janMgr(&fReaderMgr, true); nextCh = fReaderMgr.peekNextChar(); } // Check for special chars. Start with the most // obvious end of file, which should be legal here at top level. if (!nextCh) return Token_EOF; // If it's not a '<' we must be in content. // // This includes entity references '&' of some sort. These must // be character data because that's the only place a reference can // occur in content. if (nextCh != chOpenAngle) return Token_CharData; // Ok it had to have been a '<' character. So get it out of the reader // and store the reader number where we saw it, passing it back to the // caller. fReaderMgr.getNextChar(); orgReader = fReaderMgr.getCurrentReaderNum(); // Ok, so lets go through the things that it could be at this point which // are all some form of markup. nextCh = fReaderMgr.peekNextChar(); if (nextCh == chForwardSlash) { fReaderMgr.getNextChar(); return Token_EndTag; } else if (nextCh == chBang) { static const XMLCh gCDATAStr[] = { chBang, chOpenSquare, chLatin_C, chLatin_D, chLatin_A , chLatin_T, chLatin_A, chNull }; static const XMLCh gCommentString[] = { chBang, chDash, chDash, chNull }; if (fReaderMgr.skippedString(gCDATAStr)) return Token_CData; if (fReaderMgr.skippedString(gCommentString)) return Token_Comment; emitError(XMLErrs::ExpectedCommentOrCDATA); return Token_Unknown; } else if (nextCh == chQuestion) { // It must be a PI fReaderMgr.getNextChar(); return Token_PI; } // Assume its an element name, so return with a start tag token. If it // turns out not to be, then it will fail when it cannot get a valid tag. return Token_StartTag; } // --------------------------------------------------------------------------- // XMLScanner: Private parsing methods // --------------------------------------------------------------------------- // This guy just scans out a single or double quoted string of characters. // It does not pass any judgement on the contents and assumes that it is // illegal to have another quote of the same kind inside the string's // contents. // // NOTE: This is for simple stuff like the strings in the XMLDecl which // cannot have any entities inside them. So this guy does not handle any // end of entity stuff. bool XMLScanner::getQuotedString(XMLBuffer& toFill) { // Reset the target buffer toFill.reset(); // Get the next char which must be a single or double quote XMLCh quoteCh; if (!fReaderMgr.skipIfQuote(quoteCh)) return false; while (true) { // Get another char const XMLCh nextCh = fReaderMgr.getNextChar(); // See if it matches the starting quote char if (nextCh == quoteCh) break; // We should never get either an end of file null char here. If we // do, just fail. It will be handled more gracefully in the higher // level code that called us. if (!nextCh) return false; // Else add it to the buffer toFill.append(nextCh); } return true; } // This method scans a character reference and returns the character that // was refered to. It assumes that we've already scanned the &# characters // that prefix the numeric code. bool XMLScanner::scanCharRef(XMLCh& toFill, XMLCh& second) { bool gotOne = false; unsigned int value = 0; // Set the radix. Its supposed to be a lower case x if hex. But, in // order to recover well, we check for an upper and put out an error // for that. unsigned int radix = 10; if (fReaderMgr.skippedChar(chLatin_x)) { radix = 16; } else if (fReaderMgr.skippedChar(chLatin_X)) { emitError(XMLErrs::HexRadixMustBeLowerCase); radix = 16; } while (true) { const XMLCh nextCh = fReaderMgr.peekNextChar(); // Watch for EOF if (!nextCh) ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); // Break out on the terminating semicolon if (nextCh == chSemiColon) { fReaderMgr.getNextChar(); break; } // Convert this char to a binary value, or bail out if its not // one. unsigned int nextVal; if ((nextCh >= chDigit_0) && (nextCh <= chDigit_9)) nextVal = (unsigned int)(nextCh - chDigit_0); else if ((nextCh >= chLatin_A) && (nextCh <= chLatin_F)) nextVal= (unsigned int)(10 + (nextCh - chLatin_A)); else if ((nextCh >= chLatin_a) && (nextCh <= chLatin_f)) nextVal = (unsigned int)(10 + (nextCh - chLatin_a)); else { // Return a zero toFill = 0; // If we got at least a sigit, then do an unterminated ref error. // Else, do an expected a numerical ref thing. if (gotOne) emitError(XMLErrs::UnterminatedCharRef); else emitError(XMLErrs::ExpectedNumericalCharRef); // Return failure return false; } // Make sure its valid for the radix. If not, then just eat the // digit and go on after issueing an error. Else, update the // running value with this new digit. if (nextVal >= radix) { XMLCh tmpStr[2]; tmpStr[0] = nextCh; tmpStr[1] = chNull; emitError(XMLErrs::BadDigitForRadix, tmpStr); } else { value = (value * radix) + nextVal; // Guard against overflow. if (value > 0x10FFFF) { // Character reference was not in the valid range emitError(XMLErrs::InvalidCharacterRef); return false; } } // Indicate that we got at least one good digit gotOne = true; // And eat the last char fReaderMgr.getNextChar(); } // Return the char (or chars) // And check if the character expanded is valid or not if (value >= 0x10000 && value <= 0x10FFFF) { value -= 0x10000; toFill = XMLCh((value >> 10) + 0xD800); second = XMLCh((value & 0x3FF) + 0xDC00); } else if (value <= 0xFFFD) { toFill = XMLCh(value); second = 0; if (!fReaderMgr.getCurrentReader()->isXMLChar(toFill) && !fReaderMgr.getCurrentReader()->isControlChar(toFill)) { // Character reference was not in the valid range emitError(XMLErrs::InvalidCharacterRef); return false; } } else { // Character reference was not in the valid range emitError(XMLErrs::InvalidCharacterRef); return false; } return true; } // We get here after the '<!--' part of the comment. We scan past the // terminating '-->' It will calls the appropriate handler with the comment // text, if one is provided. A comment can be in either the document or // the DTD, so the fInDocument flag is used to know which handler to send // it to. void XMLScanner::scanComment() { enum States { InText , OneDash , TwoDashes }; // Get a buffer for this XMLBufBid bbComment(&fBufMgr); // Get the comment text into a temp buffer. Be sure to use temp buffer // two here, since its to be used for stuff that is potentially longer // than just a name. States curState = InText; bool gotLeadingSurrogate = false; while (true) { // Get the next character const XMLCh nextCh = fReaderMgr.getNextChar(); // Watch for an end of file if (!nextCh) { emitError(XMLErrs::UnterminatedComment); ThrowXMLwithMemMgr(UnexpectedEOFException, XMLExcepts::Gen_UnexpectedEOF, fMemoryManager); } // Check for correct surrogate pairs if ((nextCh >= 0xD800) && (nextCh <= 0xDBFF)) { if (gotLeadingSurrogate) emitError(XMLErrs::Expected2ndSurrogateChar); else gotLeadingSurrogate = true; } else { if (gotLeadingSurrogate) { if ((nextCh < 0xDC00) || (nextCh > 0xDFFF)) emitError(XMLErrs::Expected2ndSurrogateChar); } // Its got to at least be a valid XML character else if (!fReaderMgr.getCurrentReader()->isXMLChar(nextCh)) { XMLCh tmpBuf[9]; XMLString::binToText ( nextCh , tmpBuf , 8 , 16 , fMemoryManager ); emitError(XMLErrs::InvalidCharacter, tmpBuf); } gotLeadingSurrogate = false; } if (curState == InText) { // If its a dash, go to OneDash state. Otherwise take as text if (nextCh == chDash) curState = OneDash; else bbComment.append(nextCh); } else if (curState == OneDash) { // If its another dash, then we change to the two dashes states. // Otherwise, we have to put in the deficit dash and the new // character and go back to InText. if (nextCh == chDash) { curState = TwoDashes; } else { bbComment.append(chDash); bbComment.append(nextCh); curState = InText; } } else if (curState == TwoDashes) { // The next character must be the closing bracket if (nextCh != chCloseAngle) { emitError(XMLErrs::IllegalSequenceInComment); fReaderMgr.skipPastChar(chCloseAngle); return; } break; } } // If we have an available handler, call back with the comment. if (fDocHandler) { fDocHandler->docComment ( bbComment.getRawBuffer() ); } //mark comment is seen within the current element if (! fElemStack.isEmpty()) fElemStack.setCommentOrPISeen(); } // Most equal signs can have white space around them, so this little guy // just makes the calling code cleaner by eating whitespace. bool XMLScanner::scanEq(bool inDecl) { fReaderMgr.skipPastSpaces(inDecl); if (fReaderMgr.skippedChar(chEqual)) { fReaderMgr.skipPastSpaces(inDecl); return true; } return false; } unsigned int XMLScanner::scanUpToWSOr(XMLBuffer& toFill, const XMLCh chEndChar) { fReaderMgr.getUpToCharOrWS(toFill, chEndChar); return toFill.getLen(); } unsigned int *XMLScanner::getNewUIntPtr() { // this method hands back a new pointer initialized to 0 unsigned int *retVal; if(fUIntPoolCol < 64) { retVal = fUIntPool[fUIntPoolRow]+fUIntPoolCol; fUIntPoolCol++; return retVal; } // time to grow the pool... if(fUIntPoolRow+1 == fUIntPoolRowTotal) { // and time to add some space for new rows: fUIntPoolRowTotal <<= 1; unsigned int **newArray = (unsigned int **)fMemoryManager->allocate(sizeof(unsigned int *) * fUIntPoolRowTotal ); memcpy(newArray, fUIntPool, (fUIntPoolRow+1) * sizeof(unsigned int *)); fMemoryManager->deallocate(fUIntPool); fUIntPool = newArray; // need to 0 out new elements we won't need: for (unsigned int i=fUIntPoolRow+2; i<fUIntPoolRowTotal; i++) fUIntPool[i] = 0; } // now to add a new row; we just made sure we have space fUIntPoolRow++; fUIntPool[fUIntPoolRow] = (unsigned int *)fMemoryManager->allocate(sizeof(unsigned int) << 6); memset(fUIntPool[fUIntPoolRow], 0, sizeof(unsigned int) << 6); // point to next element fUIntPoolCol = 1; return fUIntPool[fUIntPoolRow]; } void XMLScanner::resetUIntPool() { // to reuse the unsigned int pool--and the hashtables that use it-- // simply reinitialize everything to 0's for(unsigned int i = 0; i<= fUIntPoolRow; i++) memset(fUIntPool[i], 0, sizeof(unsigned int) << 6); } void XMLScanner::recreateUIntPool() { // this allows a bloated unsigned int pool to be dispensed with // first, delete old fUIntPool for (unsigned int i=0; i<=fUIntPoolRow; i++) { fMemoryManager->deallocate(fUIntPool[i]); } fMemoryManager->deallocate(fUIntPool); fUIntPoolRow = fUIntPoolCol = 0; fUIntPoolRowTotal = 2; fUIntPool = (unsigned int **)fMemoryManager->allocate(sizeof(unsigned int *) * fUIntPoolRowTotal); fUIntPool[0] = (unsigned int *)fMemoryManager->allocate(sizeof(unsigned int) << 6); memset(fUIntPool[fUIntPoolRow], 0, sizeof(unsigned int) << 6); fUIntPool[1] = 0; } XERCES_CPP_NAMESPACE_END
[ [ [ 1, 2222 ] ] ]
18f3b1260419b665d059a032290207adae3f2687
f9351a01f0e2dec478e5b60c6ec6445dcd1421ec
/itl/src/itl/itl_date_time.hpp
4bb2e6471590d679335076df220cba1aeff3fa50
[ "BSL-1.0" ]
permissive
WolfgangSt/itl
e43ed68933f554c952ddfadefef0e466612f542c
6609324171a96565cabcf755154ed81943f07d36
refs/heads/master
2016-09-05T20:35:36.628316
2008-11-04T11:44:44
2008-11-04T11:44:44
327,076
0
1
null
null
null
null
UTF-8
C++
false
false
2,787
hpp
/*----------------------------------------------------------------------------+ Copyright (c) 2007-2008: Joachim Faulhaber +-----------------------------------------------------------------------------+ Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------- Function-templates for discrete Datatypes like int, unsigned or any class that provides a ++ operator c.f. iterators -----------------------------------------------------------------------------*/ #ifndef __itl_date_time_JOFA_080416_H__ #define __itl_date_time_JOFA_080416_H__ #include <stdio.h> #include <string> #include <sstream> #include <boost/date_time/posix_time/posix_time.hpp> namespace itl { boost::posix_time::ptime operator ++(boost::posix_time::ptime& x) { return x + boost::posix_time::ptime::time_duration_type::unit(); } boost::posix_time::ptime operator --(boost::posix_time::ptime& x) { return x - boost::posix_time::ptime::time_duration_type::unit(); } // ------------------------------------------------------------------------ template<> inline boost::posix_time::ptime type<boost::posix_time::ptime>::neutron() { return boost::posix_time::ptime(boost::posix_time::min_date_time); } } // namespace itl #endif
[ "jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a" ]
[ [ [ 1, 68 ] ] ]
fc9d784a85f1fde1b459fce773b21faa59f048a3
6fd162d2cade2db745e68f11d7e9722a3855f033
/Source/BetterVSM_2009_08_31_SAVSM_64BitFloatSAT/SoftShadowMap.h
ecf8627c3f8cc7d30df4db7c52b613a66d66e3c1
[]
no_license
SenichiFSeiei/oursavsm
8f418325bc9883bcb245e139dbd0249e72c18d78
379e77cab67b3b1423a4c6f480b664f79b03afa9
refs/heads/master
2021-01-10T21:00:52.797565
2010-04-27T13:18:19
2010-04-27T13:18:19
41,737,615
0
0
null
null
null
null
UTF-8
C++
false
false
3,801
h
//---------------------------------------------------------------------------------- // File: S3UTMesh.h // Author: Baoguang Yang // // Copyright (c) 2009 S3Graphics Corporation. All rights reserved. // // Contains code manipulating shadow map and // 1. HSM // 2. MSSM // 3. SAT // //---------------------------------------------------------------------------------- #ifndef SSMAP #define SSMAP #include <dxut.h> #include <dxutgui.h> #include <dxutsettingsdlg.h> #include "CommonDef.h" class S3UTMesh; class S3UTCamera; class SSMap { public: ID3D10Texture2D *m_pDepthTex[1], *m_pDepthMip2, *m_pBigDepth2; ///< textures for rendering ID3D10DepthStencilView *m_pDepthDSView[1]; ///< depth stencil view ID3D10RenderTargetView **m_pDepthMip2RTViews, *m_pBigDepth2RTView; ID3D10StateBlock *m_pOldRenderState; ///< we save rendering state here ID3D10RasterizerState *m_pRasterState; ///< render state we use to render shadow map ID3D10DepthStencilState *m_pDSState; ///< render state we use to render shadow map ID3D10ShaderResourceView *m_pDepthSRView[1], *m_pDepthMip2SRView, **m_pDepthMip2SRViews, *m_pBigDepth2SRView; int nMips; ///< number of depth mips (depends on the depth map resolution) //------ NBuffer ------------------------------------------------ ID3D10Texture2D *m_pNBuffers; ID3D10ShaderResourceView *m_pNBufferSRView; ID3D10RenderTargetView **m_pNBufferRTViews; ID3D10ShaderResourceView **m_pNBufferSRViews; //--------------------------------------------------------------- //------ VSM ------------------------------------------------ ID3D10Texture2D *m_pVSMMip2; ID3D10RenderTargetView **m_pVSMMip2RTViews; ID3D10ShaderResourceView *m_pVSMMip2SRView, **m_pVSMMip2SRViews; //--------------------------------------------------------------- //------ SAT VSM --------------------------------------------- static const int NUM_SAT_TMP_TEX = 2;//with the scissor optimization, this number should always be 2 ID3D10Texture2D *m_pSatTexes[NUM_SAT_TMP_TEX]; ID3D10RenderTargetView *m_pSatRTViews[NUM_SAT_TMP_TEX]; ID3D10ShaderResourceView *m_pSatSRViews[NUM_SAT_TMP_TEX]; ID3D10ShaderResourceView *m_pSatSRView; static const int m_cSatRes = DEPTH_RES; static const int m_cSampleBatch = 8; //--------------------------------------------------------------- ID3D10Effect *m_pShadowMapEffect; int m_nDepthRes; ID3D10InputLayout *m_pDepthLayout; ///< layout with only POSITION semantic in it ID3D10EffectTechnique *m_pDRenderTechnique; SSMap(); void OnDestroy(); void OnWindowResize(); void OnD3D10CreateDevice(ID3D10Device* pDev10, const DXGI_SURFACE_DESC *pBackBufferSurfaceDesc, void* pUserContext); //You can not remove this, this bool shows some magical affect to the entire code. //I'll find the root later. Too much unclear outer dependencies, oops! bool bAccurateShadow; D3DXMATRIX mLightViewProj, mLightProj; void set_parameters( bool par_bBuildHSM, bool par_bBuildMSSM, bool par_bBuildSAT, bool par_bBuildVSM ); void Render(ID3D10Device *a, S3UTMesh *b, S3UTCamera& d,float fTime, float fElapsedTime,bool dump_sm); bool m_bBuildHSM; bool m_bBuildMSSM; bool m_bBuildSAT; bool m_bBuildVSM; bool m_bShaderChanged; void PrepareBuildingHSM( ID3D10Device *par_pDev10 ); void BuildHSM( ID3D10Device *par_pDev10 ); void PrepareBuildingNBuffer( ID3D10Device *par_pDev10 ); void BuildNBuffer( ID3D10Device *par_pDev10 ); void PrepareBuildingVSM( ID3D10Device *par_pDev10 ); void BuildVSM( ID3D10Device *par_pDev10 ); void PrepareBuildingSAT( ID3D10Device *par_pDev10 ); void BuildSAT( ID3D10Device *par_pDev10 ); void CreateShader(ID3D10Device* pDev10); }; #endif
[ [ [ 1, 98 ] ] ]
0319d8212db88d21877b3ce944f8eba99422434b
6a925ad6f969afc636a340b1820feb8983fc049b
/librtsp/librtsp/inc/RTSPServer.h
8dc872cf040d2b19902ce993372b99060bf5b1a5
[]
no_license
dulton/librtsp
c1ac298daecd8f8008f7ab1c2ffa915bdbb710ad
8ab300dc678dc05085f6926f016b32746c28aec3
refs/heads/master
2021-05-29T14:59:37.037583
2010-05-30T04:07:28
2010-05-30T04:07:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,803
h
/*!@file RTSPServer.h @brief Copyright (c) 2009 HUST ITEC VoIP Lab. All rights reserved. @author Wentao Tang @date 2009.3.21 @version 1.0 */ #pragma once #include "RTSPSessionBase.h" #include "SocketBase.h" #include <pthread.h> class RTSPSessionBase; class RTSPListener; class ServerMediaSession; class RTSPServer { public: typedef map<int, RTSPSessionBase *> RTSPSessionTable; typedef RTSPSessionTable::iterator RTSPSessionItor; typedef RTSPSessionTable::const_iterator Const_RTSPSessionItor; typedef map<string, ServerMediaSession *> MediaSessionTable; public: RTSPServer(unsigned short port); ~RTSPServer(void); //! Start services, it created a thread /** @return: void */ void Start(); //! Let the thread jump out the loop, then stop /** @return: void */ void Stop(); //! thread func, process incoming connection request and incoming data of connected socket /** @param: void * arg @return: void * */ static void *ProcessThread(void *); //! @brief Add a Session to session list /** @param: int session_id the id of session, in fact it is a socket fd @param: RTSPSessionBase * session pointer to session @return: bool added success or not */ bool AddRTSPSession(int session_id, RTSPSessionBase *session); //! @brief Delete a session from session list by its id /** @param: int session_id the id of session, in fact it is a socket fd @return: bool */ bool DeleteRTSPSession(int session_id); //! @brief Add A MediaSession /** @param: string streamname @param: ServerMediaSession * session @return: bool */ bool AddMediaSession(string streamname, ServerMediaSession *session); //! @brief Find MediaSession by streamname /** @param: string streamname @return: ServerMediaSession * */ ServerMediaSession *FindMediaSessionByStreamName(string streamname); void SetLoaclIPAddr(string ip) { localIPAddr_ = ip; } string GetLocalIPAddr() { return localIPAddr_; } private: //! End the thread /** @return: void */ void Joint(); //! build fd_set again, we need to call this before every 'select()' /** @return: bool */ bool BuildFDSETs(); private: MediaSessionTable mediaSessions_; RTSPSessionTable rtspSessions_; fd_set fdsets_; int nfds_; bool exitThread_; bool started_; pthread_t threadid_; RTSPListener *listener_; unsigned short listenPort_; string localIPAddr_; };
[ "TangWentaoHust@95ff1050-1aa1-11de-b6aa-3535bc3264a2" ]
[ [ [ 1, 119 ] ] ]
b4d05efb0f250be3426bf81d0e411aa1e86c3ff5
5f28f9e0948b026058bafe651ba0ce03971eeafa
/LindsayAR Client MultiMulti/ARToolkitPlus/src/core/paramDistortion.cpp
d9279e0cbcd42b806636dee442394432a7942ebc
[]
no_license
TheProjecter/surfacetoar
cbe460d9f41a2f2d7a677a697114e4eea7516218
4ccba52e55b026b63473811319ceccf6ae3fbc1f
refs/heads/master
2020-05-17T15:41:31.087874
2010-11-08T00:09:25
2010-11-08T00:09:25
42,946,053
0
0
null
null
null
null
UTF-8
C++
false
false
4,498
cpp
/** * Copyright (C) 2010 ARToolkitPlus Authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Authors: * Daniel Wagner */ #include <cstdio> #include <cmath> #include <cassert> #include <cstring> #include "Tracker.h" #include "Camera.h" #include "Camera.h" namespace ARToolKitPlus { int Tracker::arCameraObserv2Ideal_std(Camera* pCam, ARFloat ox, ARFloat oy, ARFloat *ix, ARFloat *iy) { pCam->observ2Ideal(ox, oy, ix, iy); return (0); } int Tracker::arCameraIdeal2Observ_std(Camera* pCam, ARFloat ix, ARFloat iy, ARFloat *ox, ARFloat *oy) { pCam->ideal2Observ(ix, iy, ox, oy); return (0); } int Tracker::arCameraObserv2Ideal_none(Camera* pCam, ARFloat ox, ARFloat oy, ARFloat *ix, ARFloat *iy) { *ix = ox; *iy = oy; return (0); } // // these functions store 2 values (x & y) in a single 32-bit unsigned integer // each value is stored as 11.5 fixed point // inline void floatToFixed(ARFloat nX, ARFloat nY, unsigned int &nFixed) { short sx = (short) (nX * 32); short sy = (short) (nY * 32); unsigned short *ux = (unsigned short*) &sx; unsigned short *uy = (unsigned short*) &sy; nFixed = (*ux << 16) | *uy; } inline void fixedToFloat(unsigned int nFixed, ARFloat& nX, ARFloat& nY) { unsigned short ux = (nFixed >> 16); unsigned short uy = (nFixed & 0xffff); short *sx = (short*) &ux; short *sy = (short*) &uy; nX = (*sx) / 32.0f; nY = (*sy) / 32.0f; } int Tracker::arCameraObserv2Ideal_LUT(Camera* pCam, ARFloat ox, ARFloat oy, ARFloat *ix, ARFloat *iy) { if (!undistO2ITable) buildUndistO2ITable(pCam); int x = (int) ox, y = (int) oy; fixedToFloat(undistO2ITable[x + y * arImXsize], *ix, *iy); return 0; } void Tracker::buildUndistO2ITable(Camera* pCam) { int x, y; ARFloat cx, cy, ox, oy; unsigned int fixed; char* cachename = NULL; bool loaded = false; if (loadCachedUndist) { assert(pCam->getFileName() != ""); cachename = new char[strlen(pCam->getFileName().c_str()) + 5]; strcpy(cachename, pCam->getFileName().c_str()); strcat(cachename, ".LUT"); } // we have to take care here when using a memory manager that can not free memory // (usually this lookup table should only be built once - unless we change camera resolution) // if (undistO2ITable) delete[] undistO2ITable; undistO2ITable = new unsigned int[arImXsize * arImYsize]; if (loadCachedUndist) { if (FILE* fp = fopen(cachename, "rb")) { size_t numBytes = fread(undistO2ITable, 1, arImXsize * arImYsize * sizeof(unsigned int), fp); fclose(fp); if (numBytes == arImXsize * arImYsize * sizeof(unsigned int)) loaded = true; } } if (!loaded) { for (x = 0; x < arImXsize; x++) { for (y = 0; y < arImYsize; y++) { arCameraObserv2Ideal_std(pCam, (ARFloat) x, (ARFloat) y, &cx, &cy); floatToFixed(cx, cy, fixed); fixedToFloat(fixed, ox, oy); undistO2ITable[x + y * arImXsize] = fixed; } } if (loadCachedUndist) if (FILE* fp = fopen(cachename, "wb")) { fwrite(undistO2ITable, 1, arImXsize * arImYsize * sizeof(unsigned int), fp); fclose(fp); } } delete cachename; } int Tracker::arCameraObserv2Ideal(Camera *pCam, ARFloat ox, ARFloat oy, ARFloat *ix, ARFloat *iy) { pCam->observ2Ideal(ox, oy, ix, iy); return (0); } int Tracker::arCameraIdeal2Observ(Camera *pCam, ARFloat ix, ARFloat iy, ARFloat *ox, ARFloat *oy) { pCam->ideal2Observ(ix, iy, ox, oy); return (0); } } // namespace ARToolKitPlus
[ [ [ 1, 149 ] ] ]
e3abfb31179ddc9c351500baf28ae4c65d9a138f
22d9640edca14b31280fae414f188739a82733e4
/Code/VTK/include/vtk-5.2/vtkInformationIdTypeKey.h
12d707b36b4d76d0054601f20e9d11aa95c51962
[]
no_license
tack1/Casam
ad0a98febdb566c411adfe6983fcf63442b5eed5
3914de9d34c830d4a23a785768579bea80342f41
refs/heads/master
2020-04-06T03:45:40.734355
2009-06-10T14:54:07
2009-06-10T14:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,423
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkInformationIdTypeKey.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkInformationIdTypeKey - Key for vtkIdType values in vtkInformation. // .SECTION Description // vtkInformationIdTypeKey is used to represent keys for vtkIdType values // in vtkInformation. #ifndef __vtkInformationIdTypeKey_h #define __vtkInformationIdTypeKey_h #include "vtkInformationKey.h" #include "vtkCommonInformationKeyManager.h" // Manage instances of this type. class VTK_COMMON_EXPORT vtkInformationIdTypeKey : public vtkInformationKey { public: vtkTypeRevisionMacro(vtkInformationIdTypeKey,vtkInformationKey); void PrintSelf(ostream& os, vtkIndent indent); vtkInformationIdTypeKey(const char* name, const char* location); ~vtkInformationIdTypeKey(); // Description: // Get/Set the value associated with this key in the given // information object. void Set(vtkInformation* info, vtkIdType); vtkIdType Get(vtkInformation* info); int Has(vtkInformation* info); // Description: // Copy the entry associated with this key from one information // object to another. If there is no entry in the first information // object for this key, the value is removed from the second. virtual void ShallowCopy(vtkInformation* from, vtkInformation* to); // Description: // Print the key's value in an information object to a stream. virtual void Print(ostream& os, vtkInformation* info); protected: // Description: // Get the address at which the actual value is stored. This is // meant for use from a debugger to add watches and is therefore not // a public method. vtkIdType* GetWatchAddress(vtkInformation* info); private: vtkInformationIdTypeKey(const vtkInformationIdTypeKey&); // Not implemented. void operator=(const vtkInformationIdTypeKey&); // Not implemented. }; #endif
[ "nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f" ]
[ [ [ 1, 65 ] ] ]
8ac5034dbf44e45858e1862bdffd4e1b2beec741
85d9531c984cd9ffc0c9fe8058eb1210855a2d01
/QxOrm/include/QxFunction/QxFunction_2.h
d9b58fcc2beca9853f77351fc4f3e68d68e0f028
[]
no_license
padenot/PlanningMaker
ac6ece1f60345f857eaee359a11ee6230bf62226
d8aaca0d8cdfb97266091a3ac78f104f8d13374b
refs/heads/master
2020-06-04T12:23:15.762584
2011-02-23T21:36:57
2011-02-23T21:36:57
1,125,341
0
1
null
null
null
null
UTF-8
C++
false
false
5,359
h
/**************************************************************************** ** ** http://www.qxorm.com/ ** http://sourceforge.net/projects/qxorm/ ** Original file by Lionel Marty ** ** This file is part of the QxOrm library ** ** This software is provided 'as-is', without any express or implied ** warranty. In no event will the authors be held liable for any ** damages arising from the use of this software. ** ** GNU Lesser General Public License Usage ** This file must be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file 'license.lgpl.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you have questions regarding the use of this file, please contact : ** [email protected] ** ****************************************************************************/ #ifndef _QX_FUNCTION_2_H_ #define _QX_FUNCTION_2_H_ #ifdef _MSC_VER #pragma once #endif #include <QxFunction/IxFunction.h> #include <QxFunction/QxParameters.h> namespace qx { template <class Owner, typename R, typename P1, typename P2> class QxFunction_2 : public IxFunction { public: typedef boost::function<R (Owner *, P1, P2)> type_fct; typedef typename qx::trait::remove_attr<P1, false>::type type_P1; typedef typename qx::trait::remove_attr<P2, false>::type type_P2; QX_FUNCTION_CLASS_MEMBER_FCT(QxFunction_2); virtual qx_bool isValidParams(const QString & params) const { Q_UNUSED(params); return true; } virtual qx_bool isValidParams(const type_any_params & params) const { Q_UNUSED(params); return true; } private: template <class T, bool bReturnValue /* = false */> struct QxInvokerFct { static inline qx_bool invoke(void * pOwner, const T & params, boost::any * ret, const QxFunction_2 * pThis) { QX_FUNCTION_INVOKE_START_WITH_OWNER(); QX_FUNCTION_FETCH_PARAM(type_P1, p1, get_param_1); QX_FUNCTION_FETCH_PARAM(type_P2, p2, get_param_2); try { pThis->m_fct(static_cast<Owner *>(pOwner), p1, p2); } QX_FUNCTION_CATCH_AND_RETURN_INVOKE(); } }; template <class T> struct QxInvokerFct<T, true> { static inline qx_bool invoke(void * pOwner, const T & params, boost::any * ret, const QxFunction_2 * pThis) { QX_FUNCTION_INVOKE_START_WITH_OWNER(); QX_FUNCTION_FETCH_PARAM(type_P1, p1, get_param_1); QX_FUNCTION_FETCH_PARAM(type_P2, p2, get_param_2); try { R retTmp = pThis->m_fct(static_cast<Owner *>(pOwner), p1, p2); if (ret) { (* ret) = boost::any(retTmp); } } QX_FUNCTION_CATCH_AND_RETURN_INVOKE(); } }; }; template <typename R, typename P1, typename P2> class QxFunction_2<void, R, P1, P2> : public IxFunction { public: typedef boost::function<R (P1, P2)> type_fct; typedef typename qx::trait::remove_attr<P1, false>::type type_P1; typedef typename qx::trait::remove_attr<P2, false>::type type_P2; QX_FUNCTION_CLASS_FCT(QxFunction_2); virtual qx_bool isValidParams(const QString & params) const { Q_UNUSED(params); return true; } virtual qx_bool isValidParams(const type_any_params & params) const { Q_UNUSED(params); return true; } private: template <class T, bool bReturnValue /* = false */> struct QxInvokerFct { static inline qx_bool invoke(const T & params, boost::any * ret, const QxFunction_2 * pThis) { QX_FUNCTION_INVOKE_START_WITHOUT_OWNER(); QX_FUNCTION_FETCH_PARAM(type_P1, p1, get_param_1); QX_FUNCTION_FETCH_PARAM(type_P2, p2, get_param_2); try { pThis->m_fct(p1, p2); } QX_FUNCTION_CATCH_AND_RETURN_INVOKE(); } }; template <class T> struct QxInvokerFct<T, true> { static inline qx_bool invoke(const T & params, boost::any * ret, const QxFunction_2 * pThis) { QX_FUNCTION_INVOKE_START_WITHOUT_OWNER(); QX_FUNCTION_FETCH_PARAM(type_P1, p1, get_param_1); QX_FUNCTION_FETCH_PARAM(type_P2, p2, get_param_2); try { R retTmp = pThis->m_fct(p1, p2); if (ret) { (* ret) = boost::any(retTmp); } } QX_FUNCTION_CATCH_AND_RETURN_INVOKE(); } }; }; namespace function { template <class Owner, typename R, typename P1, typename P2> IxFunction_ptr bind_fct_2(const typename QxFunction_2<Owner, R, P1, P2>::type_fct & fct) { typedef boost::is_same<Owner, void> qx_verify_owner_tmp; BOOST_STATIC_ASSERT(qx_verify_owner_tmp::value); IxFunction_ptr ptr; ptr.reset(new QxFunction_2<void, R, P1, P2>(fct)); return ptr; } template <class Owner, typename R, typename P1, typename P2> IxFunction_ptr bind_member_fct_2(const typename QxFunction_2<Owner, R, P1, P2>::type_fct & fct) { typedef boost::is_same<Owner, void> qx_verify_owner_tmp; BOOST_STATIC_ASSERT(! qx_verify_owner_tmp::value); IxFunction_ptr ptr; ptr.reset(new QxFunction_2<Owner, R, P1, P2>(fct)); return ptr; } } // namespace function } // namespace qx #endif // _QX_FUNCTION_2_H_
[ [ [ 1, 149 ] ] ]
fe7316241ee15d56fcca856edb45d3bfc3982a7e
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/qdbusabstractinterface.h
0601da3c52fb670c099991378153548d6a2094cb
[ "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
6,036
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtDBus 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 QDBUSABSTRACTINTERFACE_H #define QDBUSABSTRACTINTERFACE_H #include <QtCore/qstring.h> #include <QtCore/qvariant.h> #include <QtCore/qlist.h> #include <QtCore/qobject.h> #include <QtDBus/qdbusmessage.h> #include <QtDBus/qdbusextratypes.h> #include <QtDBus/qdbusconnection.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(DBus) class QDBusError; class QDBusPendingCall; class QDBusAbstractInterfacePrivate; class QDBUS_EXPORT QDBusAbstractInterface: public QObject { Q_OBJECT public: virtual ~QDBusAbstractInterface(); bool isValid() const; QDBusConnection connection() const; QString service() const; QString path() const; QString interface() const; QDBusError lastError() const; QDBusMessage call(const QString &method, const QVariant &arg1 = QVariant(), const QVariant &arg2 = QVariant(), const QVariant &arg3 = QVariant(), const QVariant &arg4 = QVariant(), const QVariant &arg5 = QVariant(), const QVariant &arg6 = QVariant(), const QVariant &arg7 = QVariant(), const QVariant &arg8 = QVariant()); QDBusMessage call(QDBus::CallMode mode, const QString &method, const QVariant &arg1 = QVariant(), const QVariant &arg2 = QVariant(), const QVariant &arg3 = QVariant(), const QVariant &arg4 = QVariant(), const QVariant &arg5 = QVariant(), const QVariant &arg6 = QVariant(), const QVariant &arg7 = QVariant(), const QVariant &arg8 = QVariant()); QDBusMessage callWithArgumentList(QDBus::CallMode mode, const QString &method, const QList<QVariant> &args); bool callWithCallback(const QString &method, const QList<QVariant> &args, QObject *receiver, const char *member, const char *errorSlot); bool callWithCallback(const QString &method, const QList<QVariant> &args, QObject *receiver, const char *member); QDBusPendingCall asyncCall(const QString &method, const QVariant &arg1 = QVariant(), const QVariant &arg2 = QVariant(), const QVariant &arg3 = QVariant(), const QVariant &arg4 = QVariant(), const QVariant &arg5 = QVariant(), const QVariant &arg6 = QVariant(), const QVariant &arg7 = QVariant(), const QVariant &arg8 = QVariant()); QDBusPendingCall asyncCallWithArgumentList(const QString &method, const QList<QVariant> &args); protected: QDBusAbstractInterface(const QString &service, const QString &path, const char *interface, const QDBusConnection &connection, QObject *parent); QDBusAbstractInterface(QDBusAbstractInterfacePrivate &, QObject *parent); void connectNotify(const char *signal); void disconnectNotify(const char *signal); QVariant internalPropGet(const char *propname) const; void internalPropSet(const char *propname, const QVariant &value); QDBusMessage internalConstCall(QDBus::CallMode mode, const QString &method, const QList<QVariant> &args = QList<QVariant>()) const; private: Q_DECLARE_PRIVATE(QDBusAbstractInterface) Q_PRIVATE_SLOT(d_func(), void _q_serviceOwnerChanged(QString,QString,QString)) }; QT_END_NAMESPACE QT_END_HEADER #endif
[ "alon@rogue.(none)" ]
[ [ [ 1, 146 ] ] ]
db5d1effd6872e43a5aa99209be8dfda011c7ee5
5506729a4934330023f745c3c5497619bddbae1d
/vst2.x/p_analog/p_analog.cpp
369b69dd010c1d34acd8237df4125e2383d0484f
[]
no_license
berak/vst2.0
9e6d1d7246567f367d8ba36cf6f76422f010739e
9d8f51ad3233b9375f7768be528525c15a2ba7a1
refs/heads/master
2020-03-27T05:42:19.762167
2011-02-18T13:35:09
2011-02-18T13:35:09
1,918,997
4
3
null
null
null
null
WINDOWS-1252
C++
false
false
38,410
cpp
/*----------------------------------------------------------------------------- © 2001, Ein Zwerg GmbH, All Rights Cracked -----------------------------------------------------------------------------*/ #ifndef __p_analog__ #include "p_analog.h" #endif static AudioEffect *_effect = 0; //bool oome = false; const double midiScaler = (1. / 127.); static float freqtab[kNumFrequencies]; //------------------------------------------------------------------------------------------------------- AudioEffect* createEffectInstance (audioMasterCallback audioMaster) { bool doEdit = true; _effect = doEdit ? new p_analogEdit (audioMaster) : new p_analog (audioMaster); return _effect; } //AEffect *main (audioMasterCallback audioMaster); //AEffect *main (audioMasterCallback audioMaster) { // // get vst version // if(!audioMaster (0, audioMasterVersion, 0, 0, 0, 0)) // return 0; // old version // // effect = doEdit ? // new p_analogEdit (audioMaster) : // new p_analog (audioMaster); // if (!effect) // return 0; // if (oome) // { // delete effect; // return 0; // } // return effect->getAeffect (); //} #if MAC #pragma export off #endif // //#if WIN32 //#include <windows.h> //void* hInstance; //BOOL WINAPI DllMain (HINSTANCE hInst, DWORD dwReason, LPVOID lpvReserved) //{ // hInstance = hInst; // return 1; //} //#endif //----------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------- // p_analogProgram //----------------------------------------------------------------------------------------- p_analogProgram::p_analogProgram () { for (long i=0; i<2; i++ ) { wave[i] = .5f; wspot[i] = .5f; freq[i] = .0f; vol[i] = .5f; attack[i] = .0f; decay[i] = .2f; sustain[i] = .0f; release[i] = .0f; lfoFreq[i] = .5f; lfoFac[i] = .5f; filFreq[i] = .0f; filFac[i] = .02f; // filTyp[i] = .5f; } lfoFreq[2]=lfoFac[2]=.5f; volume = .9f; modulation = .0f; pan = .5f; strcpy (name, "init"); for (long a=0; a<kNRealPar; a++ ) for (long b=0; b<kNumSwitches; b++ ) matrix[a][b] = false; } //----------------------------------------------------------------------------------------- // p_analog //----------------------------------------------------------------------------------------- p_analog::p_analog (audioMasterCallback audioMaster) : AudioEffectX (audioMaster, kNumPrograms, kNumParams) , p_analogProgram() { pWaves = new p_analogWave[2]; programs = new p_analogProgram[kNumPrograms]; voices = new p_analogVoice[kNumVoices]; currentPoti = 0; if (audioMaster) { setNumInputs (0); // no inputs setNumOutputs (kNumOutputs); // 2 outputs, 1 for each osciallator canProcessReplacing (); ///PPP hasClip (false); isSynth (); } setUniqueID ('aNNa'); initProcess (); if (programs) setProgram(0); // suspend (); resume(); } //----------------------------------------------------------------------------------------- p_analog::~p_analog () { if (programs) delete[] programs; if (pWaves) delete[] pWaves; if (voices) delete[] voices; } //----------------------------------------------------------------------------------------- void p_analog::setProgram (VstInt32 program) { p_analogProgram *ap = &programs[program]; curProgram = program; for ( long i=0; i<2; i++ ) { wave[i] = ap->wave[i]; wspot[i] = ap->wspot[i]; calcWave(i,long(wave[i]*kNumWaves)); freq[i] = ap->freq[i]; vol[i] = ap->vol[i]; adsr[i].set_a( attack[i] = ap->attack[i] ); adsr[i].set_d( decay[i] = ap->decay[i] ); adsr[i].set_s( sustain[i] = ap->sustain[i]); adsr[i].set_r( release[i] = ap->release[i]); lfoFreq[i] = ap->lfoFreq[i]; lfoFac[i] = ap->lfoFac[i]; float f = filFreq[i] = ap->filFreq[i]; float w = filFac[i] = ap->filFac[i]; filter[i].set(f,w); } lfoFreq[2] = ap->lfoFreq[2]; lfoFac[2] = ap->lfoFac[2]; modulation = ap->modulation; volume = ap->volume; pan = ap->pan; for (long a=0; a<kNRealPar; a++ ) for (long b=0; b<kNumSwitches; b++ ) matrix[a][b] = ap->matrix[a][b]; } //----------------------------------------------------------------------------------------- void p_analog::setProgramName (char *name) { strcpy (programs[curProgram].name, name); } //----------------------------------------------------------------------------------------- void p_analog::getProgramName (char *name) { strcpy (name, programs[curProgram].name); } //----------------------------------------------------------------------------------------- void p_analog::getParameterLabel (VstInt32 index, char *label) { } //----------------------------------------------------------------------------------------- void p_analog::getParameterDisplay (VstInt32 index, char *text) { } //----------------------------------------------------------------------------------------- void p_analog::getParameterName (VstInt32 index, char *label) { switch (index) { case kWave0: strcpy (label, " Wave 1"); break; case kWspot0: strcpy (label, " Wspot 1"); break; case kFreq0: strcpy (label, " Freq 1"); break; case kVol0: strcpy (label, " Vol 1"); break; case kAttack0: strcpy (label, " Attack 1"); break; case kSustain0: strcpy (label, " Sustain 1"); break; case kDecay0: strcpy (label, " Decay 1"); break; case kRelease0: strcpy (label, " Release 1"); break; case kWave1: strcpy (label, " Wave 2"); break; case kWspot1: strcpy (label, " Wspot 2"); break; case kFreq1: strcpy (label, " Freq 2"); break; case kVol1: strcpy (label, " Vol 2"); break; case kAttack1: strcpy (label, " Attack 2"); break; case kSustain1: strcpy (label, " Sustain 2"); break; case kDecay1: strcpy (label, " Decay 2"); break; case kRelease1: strcpy (label, " Release 2"); break; case kVolume: strcpy (label, " Volume "); break; case kMod: strcpy (label, " Mod type"); break; case kPan: strcpy (label, " Pan "); break; case kLfoFreq0: strcpy (label, " Lfo freq 1"); break; case kLfoFac0: strcpy (label, " Lfo fac 1"); break; case kLfoFreq1: strcpy (label, " Lfo freq 2"); break; case kLfoFac1: strcpy (label, " Lfo fac 2"); break; case kLfoFreq2: strcpy (label, " Lfo freq 3"); break; case kLfoFac2: strcpy (label, " Lfo fac 3"); break; case kFilFreq0: strcpy (label, " Fil freq 1"); break; case kFilFac0: strcpy (label, " Fil fac 1"); break; // case kFilTyp0: strcpy (label, " Fil typ 1"); break; case kFilFreq1: strcpy (label, " Fil freq 2"); break; case kFilFac1: strcpy (label, " Fil fac 2"); break; // case kFilTyp1: strcpy (label, " Fil typ 2"); break; } } //----------------------------------------------------------------------------------------- void p_analog::setParameter (VstInt32 index, float value) { p_analogProgram *ap = &programs[curProgram]; switch (index) { case kPotiName: currentPoti = (long)value; break; case kWave0: wave[0] = ap->wave[0] = value; calcWave(0,long(value*kNumWaves));break; case kWspot0: wspot[0] = ap->wspot[0] = value; calcWave(0,long(wave[0]*kNumWaves)); break; case kFreq0: freq[0] = ap->freq[0] = value; break; case kVol0: vol[0] = ap->vol[0] = value; break; case kAttack0: attack[0] = ap->attack[0] = value; adsr[0].set_a(value); break; case kDecay0: decay[0] = ap->decay[0] = value; adsr[0].set_d(value); break; case kSustain0: sustain[0] = ap->sustain[0] = value; adsr[0].set_s(value); break; case kRelease0: release[0] = ap->release[0] = value; adsr[0].set_r(value); break; case kWave1: wave[1] = ap->wave[1] = value; calcWave(1,long(value*kNumWaves));break; case kWspot1: wspot[1] = ap->wspot[1] = value; calcWave(1,long(wave[1]*kNumWaves)); break; case kFreq1: freq[1] = ap->freq[1] = value; break; case kVol1: vol[1] = ap->vol[1] = value; break; case kAttack1: attack[1] = ap->attack[1] = value; adsr[1].set_a(value); break; case kDecay1: decay[1] = ap->decay[1] = value; adsr[1].set_d(value); break; case kSustain1: sustain[1] = ap->sustain[1] = value; adsr[1].set_s(value); break; case kRelease1: release[1] = ap->release[1] = value; adsr[1].set_r(value); break; case kMod: modulation = ap->modulation = value; break; case kVolume: volume = ap->volume = value; break; case kPan: pan = ap->pan = value; break; case kLfoFreq0: lfoFreq[0] = ap->lfoFreq[0] = value; lfo[0].setTime(value); break; case kLfoFac0: lfoFac[0] = ap->lfoFac[0] = value; lfo[0].setSpot(value); break; case kLfoFreq1: lfoFreq[1] = ap->lfoFreq[1] = value; lfo[1].setTime(value); break; case kLfoFac1: lfoFac[1] = ap->lfoFac[1] = value; lfo[1].setSpot(value); break; case kLfoFreq2: lfoFreq[2] = ap->lfoFreq[2] = value; lfo[2].setTime(value); break; case kLfoFac2: lfoFac[2] = ap->lfoFac[2] = value; lfo[2].setSpot(value); break; case kSKey: matrix[currentPoti][0] = ap->matrix[currentPoti][0] = value; break; case kSVel: matrix[currentPoti][1] = ap->matrix[currentPoti][1] = value; break; case kSPan: matrix[currentPoti][2] = ap->matrix[currentPoti][2] = value; break; case kSExp: matrix[currentPoti][3] = ap->matrix[currentPoti][3] = value; break; case kSLfo0: matrix[currentPoti][4] = ap->matrix[currentPoti][4] = value; break; case kSLfo1: matrix[currentPoti][5] = ap->matrix[currentPoti][5] = value; break; case kSLfo2: matrix[currentPoti][6] = ap->matrix[currentPoti][6] = value; break; case kSEnv0: matrix[currentPoti][7] = ap->matrix[currentPoti][7] = value; break; case kSEnv1: matrix[currentPoti][8] = ap->matrix[currentPoti][8] = value; break; case kFilFreq0: filFreq[0] = ap->filFreq[0] = value; filter[0].set(filFreq[0], filFac[0]); break; case kFilFac0: filFac[0] = ap->filFac[0] = value; filter[0].set(filFreq[0], filFac[0]); break; // case kFilTyp0: filTyp[0] = ap->filTyp[0] = value; filter[0].setType(int(3*value)); break; case kFilFreq1: filFreq[1] = ap->filFreq[1] = value; filter[1].set(filFreq[1], filFac[1]); break; case kFilFac1: filFac[1] = ap->filFac[1] = value; filter[1].set(filFreq[1], filFac[1]); break; // case kFilTyp1: filTyp[1] = ap->filTyp[1] = value; filter[1].setType(int(3*value)); break; default: return; } } //----------------------------------------------------------------------------------------- float p_analog::getParameter (VstInt32 index) { float value = 0; switch (index) { case kWave0: value = wave[0]; break; case kWspot0: value = wspot[0]; break; case kFreq0: value = freq[0]; break; case kVol0: value = vol[0]; break; case kAttack0: value = attack[0]; break; case kDecay0: value = decay[0]; break; case kSustain0: value = sustain[0]; break; case kRelease0: value = release[0]; break; case kWave1: value = wave[1]; break; case kWspot1: value = wspot[1]; break; case kFreq1: value = freq[1]; break; case kVol1: value = vol[1]; break; case kAttack1: value = attack[1]; break; case kDecay1: value = decay[1]; break; case kSustain1: value = sustain[1]; break; case kRelease1: value = release[1]; break; case kMod: value = modulation; break; case kVolume: value = volume; break; case kPan: value = pan; break; case kLfoFreq0: value = lfoFreq[0]; break; case kLfoFac0: value = lfoFac[0]; break; case kLfoFreq1: value = lfoFreq[1]; break; case kLfoFac1: value = lfoFac[1]; break; case kLfoFreq2: value = lfoFreq[2]; break; case kLfoFac2: value = lfoFac[2]; break; case kFilFreq0: value = filFreq[0]; break; case kFilFac0: value = filFac[0]; break; // case kFilTyp0: value = filTyp[0]; break; case kFilFreq1: value = filFreq[1]; break; case kFilFac1: value = filFac[1]; break; // case kFilTyp1: value = filTyp[1]; break; case kSKey: value = matrix[currentPoti][0]; break; case kSVel: value = matrix[currentPoti][1]; break; case kSPan: value = matrix[currentPoti][2]; break; case kSExp: value = matrix[currentPoti][3]; break; case kSLfo0: value = matrix[currentPoti][4]; break; case kSLfo1: value = matrix[currentPoti][5]; break; case kSLfo2: value = matrix[currentPoti][6]; break; case kSEnv0: value = matrix[currentPoti][7]; break; case kSEnv1: value = matrix[currentPoti][8]; break; case kPotiName: value = (float)currentPoti; break; } return value; } //----------------------------------------------------------------------------------------- bool p_analog::getOutputProperties (long index, VstPinProperties* properties) { if (index < kNumOutputs) { sprintf (properties->label, "aNNa %1d", index + 1); properties->flags = kVstPinIsActive; if (index < 2) properties->flags |= kVstPinIsStereo; // test, make channel 1+2 stereo return true; } return false; } //----------------------------------------------------------------------------------------- bool p_analog::getProgramNameIndexed (long category, long index, char* text) { if (index < kNumPrograms) { strcpy (text, programs[index].name); return true; } return false; } //----------------------------------------------------------------------------------------- bool p_analog::copyProgram (long destination) { if (destination < kNumPrograms) { programs[destination] = programs[curProgram]; return true; } return false; } //----------------------------------------------------------------------------------------- bool p_analog::getEffectName (char* name) { strcpy (name, "p_analog"); return true; } //----------------------------------------------------------------------------------------- bool p_analog::getVendorString (char* text) { strcpy (text, "ein zwerg"); return true; } //----------------------------------------------------------------------------------------- bool p_analog::getProductString (char* text) { strcpy (text, "analogsynth"); return true; } //----------------------------------------------------------------------------------------- VstInt32 p_analog::canDo (char* text) { if (!strcmp (text, "receiveVstEvents")) return 1; if (!strcmp (text, "receiveVstMidiEvent")) return 1; return -1; // explicitly can't do; 0 => don't know } //----------------------------------------------------------------------------------------- void p_analog::setSampleRate (float sampleRate) { AudioEffectX::setSampleRate (sampleRate); } //----------------------------------------------------------------------------------------- void p_analog::setBlockSize (long blockSize) { AudioEffectX::setBlockSize (blockSize); // you may need to have to do something here... } //----------------------------------------------------------------------------------------- void p_analog::resume () { AudioEffectX::resume (); ///PPP wantEvents (); } //----------------------------------------------------------------------------------------- void p_analog::calcWave (long n, long w) { long i; float d0,d1,v; char _acid[152] = "In the Top 40, half the songs are secret messages to the teen world to drop out, turn on, and groove with the chemicals and light shows at discotheques"; // make waveforms long ws = (long)( wspot[n] * (double)kWaveSize ); switch(w) { case 0: strcpy( pWaves[n].name, " sinus" ); for (i = 0; i < kWaveSize; i++) pWaves[n].data[i] = (float)sin( 2.0 * Pi * (double)i / (double)kWaveSize); break; case 1: strcpy( pWaves[n].name, " triangle" ); d0 = 1.0f/ws; d1 =-1.0f/(kWaveSize-ws); v =-1.0f; for (i = 0; i < kWaveSize; i++) { v += (i<ws) ? d0 : d1; pWaves[n].data[i] = v; } break; case 2: strcpy( pWaves[n].name, " pulse" ); for (i = 0; i < kWaveSize; i++) pWaves[n].data[i] = (i < ws) ? -1.f : 1.f; break; case 3: strcpy( pWaves[n].name, " acid" ); for (i = 0; i < kWaveSize; i++) pWaves[n].data[i] = float( 1.f - ( _acid[long(3+i*.08f*wspot[n]*wspot[n])%152] - 32 ) / 47.5f ) ; break; case 4: strcpy( pWaves[n].name, " noize" ); for (i = 0; i < kWaveSize; i++) pWaves[n].data[i] = (rand()%2)?1.0f:-1.0f ; break; } } //----------------------------------------------------------------------------------------- void p_analog::initProcess () { noteIsOn = false; currentDelta = 0; // make waveforms calcWave(0,0); calcWave(1,0); // make frequency (Hz) table: float fScaler = (float)((double)kWaveSize / 44100.); // we don't know the sample rate yet double k = 1.059463094359; // 12th root of 2 double a = 6.875; // a a *= k; // b a *= k; // bb a *= k; // c, frequency of midi note 0 for (long i = 0; i < kNumFrequencies; i++) // 128 midi notes { freqtab[i] = (float)a * fScaler; a *= k; } } //----------------------------------------------------------------------------------------- float p_analog::getSwitch( long index, float defVal ) { float *p = matrix[index]; if ( *p++ ) defVal *= voices[currentVoice].noteScaled; if ( *p++ ) defVal *= voices[currentVoice].velocityScaled; if ( *p++ ) defVal *= pan; if ( *p++ ) defVal *= midiExp; if ( *p++ ) defVal *= lfo[0].level; if ( *p++ ) defVal *= lfo[1].level; if ( *p++ ) defVal *= lfo[2].level; if ( *p++ ) defVal *= voices[currentVoice].a_level[0]; if ( *p++ ) defVal *= voices[currentVoice].a_level[1]; return defVal; } //----------------------------------------------------------------------------------------- void p_analog::sub_process (bool add, float **outputs, long sampleFrames) { if (noteIsOn == false) return; float* outl = outputs[0]; float* outr = outputs[1]; float amp[2], frq[2], main_vol, pan_l, pan_r; long i=0; for ( i=0; i<3; i++ ) lfo[i].tick(); if ( currentDelta ) { outl += currentDelta; outr += currentDelta; sampleFrames -= currentDelta; currentDelta = 0; } if ( add ) { // WILL YOU PLEEEAAZZZE SHUT UP ??!! memset( outl, 0, sampleFrames * sizeof(float) ); memset( outr, 0, sampleFrames * sizeof(float) ); } if ( filFreq[0] ) filter[0].set( getSwitch( kFilFreq0, filFreq[0] ), getSwitch( kFilFac0,filFac[0] ) ); if ( filFreq[1] ) filter[1].set( getSwitch( kFilFreq1, filFreq[1] ), getSwitch( kFilFac1, filFac[1] ) ); pan_l = 1 + (pan-0.5f); pan_r = 1 - (pan-0.5f); main_vol = getSwitch( kVolume, volume ); amp[0] = getSwitch( kVol0, vol[0] ); amp[1] = getSwitch( kVol1, vol[1] ); frq[0] = getSwitch( kFreq0, kfMul * freq[0] ); frq[1] = getSwitch( kFreq1, kfMul * freq[1] ); while ( noteIsOn && (--sampleFrames >= 0) ) { int playing = 0; int ds = 0; float mono = 0.0f; for ( i=0; i<kNumVoices; i++ ) { p_analogVoice *av = &voices[i]; if ( av->active == false ) continue; float w = 0.0f; for ( int osc=0; osc<2; osc++ ) { float env = adsr[osc].val( av, osc ); if ( av->phase[osc] >= kWaveSize ) av->phase[osc] -= kWaveSize; if ( av->phase[osc] < 0.0f ) av->phase[osc] += kWaveSize; if ( osc == 1 && (modulation<.6f) && (modulation>0.3f) ) { // osc1 -> ring : w *= amp[osc] * env * pWaves[osc].data[long(av->phase[osc])]; } else if ( osc == 1 && (modulation>.6f) ) { // osc1 -> phase: w = amp[osc] * env * pWaves[osc].data[abs(int(av->phase[osc]*w))%kWaveSize]; } else { // osc0 or mix: w += amp[osc] * env * pWaves[osc].data[long(av->phase[osc])]; } av->phase[osc] += frq[osc] + freqtab[av->note]; } mono += w; playing++; } if ( ! playing ) { noteIsOn = false; filter[0].stop(); filter[1].stop(); return; } // filter: float m1 = ( filFreq[0] ) ? filter[0].value(mono) : mono; float m2 = ( filFreq[1] ) ? filter[1].value(mono) : mono; // send to outputs: mono = (m1+m2) * main_vol / (kNumVoices); // normalize: if ( mono > 1 ) mono = 1.0f; if ( mono < -1 ) mono = -1.0f; if ( add ) { (*outl++) += mono * (pan_l); (*outr++) += mono * pan_r; } else { (*outl++) = mono * (pan_l); (*outr++) = mono * pan_r; } } } //----------------------------------------------------------------------------------------- void p_analog::process (float **inputs, float **outputs, VstInt32 sampleFrames) { sub_process( true, outputs, sampleFrames ); } //----------------------------------------------------------------------------------------- void p_analog::processReplacing (float **inputs, float **outputs, VstInt32 sampleFrames) { sub_process( false, outputs, sampleFrames ); } //----------------------------------------------------------------------------------------- VstInt32 p_analog::processEvents (VstEvents* ev) { for (long i = 0; i < ev->numEvents; i++) { if ((ev->events[i])->type != kVstMidiType) continue; VstMidiEvent* event = (VstMidiEvent*)ev->events[i]; char* midiData = event->midiData; long status = midiData[0] & 0xf0; // ignoring channel if ( status == 0x80 ) { // note off long note = midiData[1] & 0x7f; long velocity = midiData[2] & 0x7f; noteOff (note, velocity, event->deltaFrames); } else if ( status == 0x90 ) { // note on long note = midiData[1] & 0x7f; long velocity = midiData[2] & 0x7f; if ( velocity ) { noteOn (note, velocity, event->deltaFrames); } else { noteOff (note, velocity, event->deltaFrames); } } else if ( status == 0xb0 ) { // controller: switch( midiData[1] ) { case 0x01 : // expression midiExp = float(midiData[2] / 127.0f ); break; case 0x07 : // vol setParameter( kVolume, (float)midiData[2] / 127.0f ); break; case 0x08 : // balance case 0x0a : // pan setParameter( kPan, (float)midiData[2] / 127.0f ); break; case 0x7e : // all notes off for ( long i=0; i<kNumVoices; i++ ) voices[i].stop(); noteIsOn = false; break; } } event++; } return 1; // want more } //----------------------------------------------------------------------------------------- void p_analog::noteOff (long note, long velocity, long delta) { for ( long i=0; i<kNumVoices; i++ ) if ( note == voices[i].note ) voices[i].hold = false; } //----------------------------------------------------------------------------------------- void p_analog::noteOn (long note, long velocity, long delta) { currentVoice +=1; currentVoice %= kNumVoices; voices[currentVoice].start(); voices[currentVoice].active = (velocity ? true : false ); voices[currentVoice].note = note; voices[currentVoice].velocity = velocity; voices[currentVoice].noteScaled = note / 128.0f; voices[currentVoice].velocityScaled = velocity / 128.0f; currentDelta = delta; noteIsOn = true; // trigger lfo's: if ( matrix[kLfoFac0][0] ) lfo[0].start(); if ( matrix[kLfoFac1][0] ) lfo[1].start(); if ( matrix[kLfoFac2][0] ) lfo[2].start(); } //----------------------------------------------------------------------------- // prototype string convert float -> percent void percentStringConvert (float value, char* string) { sprintf (string, "%d%%", (int)(100 * value)); } void poti2string(float value, char* string) { _effect->getParameterName( (long) value, string ); } //----------------------------------------------------------------------------- // p_Editor class implementation //----------------------------------------------------------------------------- p_Editor::p_Editor (AudioEffect *effect) : AEffGUIEditor (effect) { hFaderHandle = 0; hKnobHandle = 0; hKnobBg = 0; hparBG = 0; hWave = 0; hMat = 0; hLfo = 0; for( long i=0; i<kNControls; i++ ) control[i] = 0; // load the background bitmap // we don't need to load all bitmaps, this could be done when open is called hBackground = new CBitmap (kBackgroundId); // init the size of the plugin rect.left = 0; rect.top = 0; rect.right = (short)hBackground->getWidth (); rect.bottom = (short)hBackground->getHeight (); } //----------------------------------------------------------------------------- p_Editor::~p_Editor () { // free background bitmap if (hBackground) hBackground->forget (); hBackground = 0; } //----------------------------------------------------------------------------- bool p_Editor::open (void *ptr) { // !!! always call this !!! AEffGUIEditor::open (ptr); // load some bitmaps if (!hparBG) hparBG = new CBitmap (kparBGId); if (!hFaderHandle) hFaderHandle = new CBitmap (kFaderHandleId); if (!hKnobHandle) hKnobHandle = new CBitmap (kKnobHandleId); if (!hKnobBg) hKnobBg = new CBitmap (kKnobBgId); if (!hWave) hWave = new CBitmap (kWaveId); // if (!hFil) // hFil = new CBitmap (kFilId); if (!hMat) hMat = new CBitmap (kMatId); if (!hLfo) hLfo = new CBitmap (kLfoId); //--init background frame----------------------------------------------- CRect size (0, 0, hBackground->getWidth (), hBackground->getHeight ()); frame = new CFrame (size, ptr, this); frame->setBackground (hBackground); //--init the Knobs------------------------------------------------ CPoint point (0, 0); CPoint offset (1, 0); int id = kWave0; int fmin=0,fmax=0; int x = 11, y = 10; // oscillators: long k=0; for ( k=0;k<2;k++ ) { x=11+k*173; y = 10; control[id] = new CVerticalSwitch ( CRect(x, y, x + hWave->getWidth(), y + 60 ), this, id, 5, 60, 6, hWave, point); control[id]->setValue (effect->getParameter (id)); frame->addView(control[id++]); x += 28; y += 7; // 39,17 size (x, y, x + hparBG->getWidth (), y + hparBG->getHeight ()); fmin = x+3, fmax = x+hparBG->getWidth()-4; control[id] = new CHorizontalSlider ( CRect(x,y,x+hparBG->getWidth(),y+hparBG->getHeight()), this, id, fmin, fmax, hFaderHandle, hparBG, point, kLeft); ((CHorizontalSlider*)control[id])->setOffsetHandle (CPoint(0,4)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); y += (hparBG->getHeight() + 6); control[id] = new CHorizontalSlider ( CRect(x,y,x+hparBG->getWidth(),y+hparBG->getHeight()), this, id, fmin, fmax, hFaderHandle, hparBG, point, kLeft); ((CHorizontalSlider*)control[id])->setOffsetHandle (CPoint(0,4)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); y += (hparBG->getHeight() + 6); control[id] = new CHorizontalSlider ( CRect(x,y,x+hparBG->getWidth(),y+hparBG->getHeight()), this, id, fmin, fmax, hFaderHandle, hparBG, point, kLeft); ((CHorizontalSlider*)control[id])->setOffsetHandle (CPoint(0,4)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); x +=64; y = 16;// 103,16 size (x, y, x + 30, y + 30 ); control[id] = new CKnob ( size, this, id, hKnobBg, hKnobHandle, CPoint(0,0)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); x +=36; size (x, y, x + 30, y + 30 ); control[id] = new CKnob ( size, this, id, hKnobBg, hKnobHandle, CPoint(0,0)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); x -= 36; y += 39; size (x, y, x + 30, y + 30 ); control[id] = new CKnob ( size, this, id, hKnobBg, hKnobHandle, CPoint(0,0)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); x +=36; size (x, y, x + 30, y + 30 ); control[id] = new CKnob ( size, this, id, hKnobBg, hKnobHandle, CPoint(0,0)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); } // filtors: for ( k=0;k<2;k++ ) { x=22+k*90; y = 112; size (x, y, x + 30, y + 30 ); control[id] = new CKnob ( size, this, id, hKnobBg, hKnobHandle, CPoint(0,0)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); x -= 9; y += 36; // 13,149 fmin = x+3, fmax = x+hparBG->getWidth()-4; control[id] = new CHorizontalSlider ( CRect(x,y,x+hparBG->getWidth(),y+hparBG->getHeight()), this, id, fmin, fmax, hFaderHandle, hparBG, point, kLeft); ((CHorizontalSlider*)control[id])->setOffsetHandle (CPoint(0,4)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); /* x +=54; y -= 36; // 67,112; control[id] = new CVerticalSwitch ( CRect(x, y, x + hFil->getWidth(), y + 56 ), this, id, 4, 56, 4, hFil, point); control[id]->setValue (effect->getParameter (id )); frame->addView(control[id++]); */ } // vol/pan: x=276; y = 111; size (x, y, x + 30, y + 30 ); control[id] = new CKnob ( size, this, id, hKnobBg, hKnobHandle, CPoint(0,0)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); x = 313; size (x, y, x + 30, y + 30 ); control[id] = new CKnob ( size, this, id, hKnobBg, hKnobHandle, CPoint(0,0)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); // modulation: x = 276; y = 232; fmin = x+3, fmax = x+hparBG->getWidth()-4; control[id=kMod] = new CHorizontalSlider ( CRect(x,y,x+hparBG->getWidth(),y+hparBG->getHeight()), this, id, fmin, fmax, hFaderHandle, hparBG, point, kLeft); ((CHorizontalSlider*)control[id])->setOffsetHandle (CPoint(0,4)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); // lfo for ( k=0;k<3;k++ ) { x=19+k*60; y = 196; size (x, y, x + 30, y + 30 ); control[id] = new CKnob ( size, this, id, hKnobBg, hKnobHandle, CPoint(0,0)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); x -= 9; y += 36; // 10,232 fmin = x+3, fmax = x+hparBG->getWidth()-4; control[id] = new CHorizontalSlider ( CRect(x,y,x+hparBG->getWidth(),y+hparBG->getHeight()), this, id, fmin, fmax, hFaderHandle, hparBG, point, kLeft); ((CHorizontalSlider*)control[id])->setOffsetHandle (CPoint(0,4)); control[id]->setValue (effect->getParameter (id )); frame->addView (control[id++]); } // switches: x = 192; y = 105; size( x, y, x + hMat->getWidth(), y + hMat->getHeight()/2 ); for (id=kSKey;id<kSKey+kNumSwitches;id++) { control[id]= new COnOffButton ( size, this, id, hMat); control[id]->setValue( effect->getParameter(id) ); frame->addView( control[id] ); size.offset(0, hMat->getHeight()/2) ; } // potiName: x = 192; y = 244; size (x, y, x + 50, y + 18); control[kPotiName] = new CParamDisplay (size, hparBG, kCenterText); ((CParamDisplay*)control[kPotiName])->setFont (kNormalFontSmall); ((CParamDisplay*)control[kPotiName])->setFontColor (kYellowCColor); control[kPotiName]->setValue (effect->getParameter (kPotiName)); ((CParamDisplay*)control[kPotiName])->setStringConvert (poti2string); frame->addView (control[kPotiName]); // strip: x = 266; y = 166; int wh = hLfo->getHeight()/10; control[kStrip] = new CMovieBitmap ( CRect (x,y,x+hLfo->getWidth(),y+wh), this, kStrip, 10, wh, hLfo, point); control[kStrip]->setValue (effect->getParameter (kStrip)); frame->addView (control[kStrip]); return true; } //----------------------------------------------------------------------------- void p_Editor::close () { delete frame; frame = 0; // free some bitmaps if (hFaderHandle) hFaderHandle->forget (); hFaderHandle = 0; if (hKnobHandle) hKnobHandle->forget (); hKnobHandle = 0; if (hKnobBg) hKnobBg->forget (); hKnobBg = 0; if (hparBG) hparBG->forget (); hparBG = 0; /* if (hFil) hFil->forget (); hFil = 0; */ if (hWave) hWave->forget (); hWave = 0; if (hMat) hMat->forget (); hMat = 0; if (hLfo) hLfo->forget (); hLfo = 0; } //----------------------------------------------------------------------------- void p_Editor:: setParameter (VstInt32 index, float value) { if ( ! frame ) return; if ( index < kNControls ) { if ( control[index] ) control[index]->setValue(value); ///PPP postUpdate (); } } //----------------------------------------------------------------------------- void p_Editor::valueChanged (CDrawContext* context, CControl* control) { long tag = control->getTag(); if ( tag < kNControls ) { effect->setParameterAutomated( tag, control->getValue() ); ///PPP control->update( context ); } } //----------------------------------------------------------------------------- p_analogEdit::p_analogEdit (audioMasterCallback audioMaster) : p_analog (audioMaster) { editor = new p_Editor (this); // if ( doEdit ) editor = new p_Editor (this); // if ( ! editor ) oome = true; } //----------------------------------------------------------------------------- p_analogEdit::~p_analogEdit () { // the editor gets deleted by the // AudioEffect base class } //----------------------------------------------------------------------------- void p_analogEdit::setProgram (long index) { currentPoti = 0l; p_analog::setProgram(index); for(long i=0; i<kNControls; i++ ) ((p_Editor*)editor)->setParameter( i, getParameter(i) ); updateDisplay(); } int anim=0,lastSelected = 0; //----------------------------------------------------------------------------- void p_analogEdit::setParameter (VstInt32 index, float value) { p_Editor* ed =(p_Editor*)editor; if ( ! ed ) return; p_analog::setParameter (index, value); ed->setParameter (index, getParameter(index)); if (index<kNRealPar && index != lastSelected ) { lastSelected = index; setParameter( kPotiName, (float) index ); for (long id=kSKey;id<kSKey+kNumSwitches;id++) ed->setParameter( id, getParameter(id) ); } ed->setParameter( kStrip, float(++anim%10)/10 ); }
[ [ [ 1, 997 ] ] ]
85ef41060a4657df3e726d28cc6065dab27aeb9f
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/_代码统计专用文件夹/C++Primer中文版(第4版)/第十四章 重载操作符与转换/20090221_习题14.24_定义解引用操作符和下标操作符.cpp
efbf21bd97b9c56cfbe8c5d5ad178391d0d742d8
[]
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
647
cpp
int& CheckedPtr::operator[](const size_t index) { if (beg + index >= end || beg + index < beg) //end指向数组最后一个元素的下一位置 throw out_of_range ("invalid index"); return *(beg + index); } const int& CheckPtr::operator[](const size_t index) { if (beg + index >= end || beg + index < beg) throw out_of_range ("invalid index"); return *(beg + index); } int& CheckPtr::operator*() { if (curr == end) throw out_of_range ("invalid current pointer"); return *curr; } const int& CheckPtr::operator*() const { if (curr == end) throw out_of_range ("invalid current pointer"); return *curr; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 27 ] ] ]
3b055ad46dc3fb1a5d4fddab65e10c9711de562f
accd6e4daa3fc1103c86d245c784182e31681ea4
/HappyHunter/Core/Rectangle2D.h
184369312498e3f1dfba1d97a2f6e94dd38c1dc0
[]
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
WINDOWS-1252
C++
false
false
3,316
h
#pragma once #include "basicmath.h" namespace zerO { /// //2D¾ØÐÎÄ£°å /// template<typename T> class CBasicRectangle2D { public: CBasicRectangle2D(void) {} CBasicRectangle2D(const CBasicRectangle2D<T>& Rect); T GetSizeX()const; T GetSizeY()const; T GetMaxX()const; T GetMinX()const; T GetMaxY()const; T GetMinY()const; T& GetMaxX(); T& GetMinX(); T& GetMaxY(); T& GetMinY(); void Set(const T& MinX, const T& MaxX, const T& MinY, const T& MaxY); virtual bool IsValuable()const; CBasicRectangle2D<T>& operator =(const CBasicRectangle2D<T>& Rect); CBasicRectangle2D<T>& operator +=(const CBasicRectangle2D<T>& Rect); CBasicRectangle2D<T>& operator *=(const CBasicRectangle2D<T>& Rect); protected: T m_MaxX; T m_MinX; T m_MaxY; T m_MinY; }; template<typename T> inline CBasicRectangle2D<T>::CBasicRectangle2D(const CBasicRectangle2D<T>& Rect) { m_MaxX = Rect.m_MaxX; m_MinX = Rect.m_MinX; m_MaxY = Rect.m_MaxY; m_MinY = Rect.m_MinY; } template<typename T> inline T CBasicRectangle2D<T>::GetSizeX()const { return m_MaxX - m_MinX; } template<typename T> inline T CBasicRectangle2D<T>::GetSizeY()const { return m_MaxY - m_MinY; } template<typename T> inline T CBasicRectangle2D<T>::GetMaxX()const { return m_MaxX; } template<typename T> inline T CBasicRectangle2D<T>::GetMinX()const { return m_MinX; } template<typename T> inline T CBasicRectangle2D<T>::GetMaxY()const { return m_MaxY; } template<typename T> inline T CBasicRectangle2D<T>::GetMinY()const { return m_MinY; } template<typename T> inline T& CBasicRectangle2D<T>::GetMaxX() { return m_MaxX; } template<typename T> inline T& CBasicRectangle2D<T>::GetMinX() { return m_MinX; } template<typename T> inline T& CBasicRectangle2D<T>::GetMaxY() { return m_MaxY; } template<typename T> inline T& CBasicRectangle2D<T>::GetMinY() { return m_MinY; } template<typename T> inline void CBasicRectangle2D<T>::Set(const T& MinX, const T& MaxX, const T& MinY, const T& MaxY) { m_MinX = MinX; m_MaxX = MaxX; m_MinY = MinY; m_MaxY = MaxY; } template<typename T> inline CBasicRectangle2D<T>& CBasicRectangle2D<T>::operator =(const CBasicRectangle2D<T>& Rect) { m_MaxX = Rect.m_MaxX; m_MinX = Rect.m_MinX; m_MaxY = Rect.m_MaxY; m_MinY = Rect.m_MinY; return *this; } template<typename T> inline CBasicRectangle2D<T>& CBasicRectangle2D<T>::operator +=(const CBasicRectangle2D<T>& Rect) { m_MaxX += Rect.m_MaxX; m_MinX += Rect.m_MinX; m_MaxY += Rect.m_MaxY; m_MinY += Rect.m_MinY; return *this; } template<typename T> inline CBasicRectangle2D<T>& CBasicRectangle2D<T>::operator *=(const CBasicRectangle2D<T>& Rect) { m_MaxX *= Rect.m_MaxX; m_MinX *= Rect.m_MinX; m_MaxY *= Rect.m_MaxY; m_MinY *= Rect.m_MinY; return *this; } /// //2D¾ØÐÎ /// template<typename T> inline bool CBasicRectangle2D<T>::IsValuable()const { return m_MaxX > m_MinX && m_MaxY > m_MinX; } class CRectangle2D : public CBasicRectangle2D<FLOAT> { public: CRectangle2D(void); ~CRectangle2D(void); }; }
[ [ [ 1, 173 ] ] ]
ad351643b2a14f4ec33e405db72ba29baaae6047
3e6e5d5b2ec9b8616288ae20c55ea3a1f5900178
/3DTetris/source/TGameMenuOptions.cpp
f3c19fec7a1b2abaee42d47216234957afe960ca
[]
no_license
sanke/3dtetrisgame
8ad404dcdd764eb13db0bfc949edb34a77eb0f21
e5bcf219e4ee3b0995809d70a83d92e001e7e50d
refs/heads/master
2021-01-16T21:18:41.949403
2010-06-27T20:58:27
2010-06-27T20:58:27
32,506,729
0
0
null
null
null
null
UTF-8
C++
false
false
132
cpp
#include "TGameMenuOptions.h" TGameMenuOptions::TGameMenuOptions(void) { } TGameMenuOptions::~TGameMenuOptions(void) { }
[ "unocoder@localhost" ]
[ [ [ 1, 9 ] ] ]
ecf05a6ae6aa1b033c4e9081cbea6240fd1a0abd
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume II/00299.cpp
f6caea27c2888aff45e22410ab61a013eb2d4236
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
603
cpp
///////////////////////////////// // 00299 - Train Swapping ///////////////////////////////// #include<cstdio> #define MAX 50 int v[50]; int i, j,k,size, cases,swaps,aux; void bubble(){ for(j = 0; j < size; j++) for(k = 0; k < size-1-j; k++) if(v[k] > v[k+1]){ aux = v[k]; v[k] = v[k+1]; v[k+1] = aux; swaps++; } } int main(void){ scanf("%d",&cases); for(i = 0; i < cases; i++){ scanf("%d",&size); swaps = 0; for(j = 0; j < size; j++) scanf("%d",&v[j]); bubble(); printf("Optimal train swapping takes %d swaps.\n",swaps); } return 0; }
[ [ [ 1, 28 ] ] ]
873f1531c8bddc57acc6f1e5a420bc80d683aa6b
23df069203762da415d03da6f61cdf340e84307b
/2009-2010/winter10/csci245/archive/eval/number.h
29a1a9840f7885b5c20734e85d242ed7f5ce322f
[]
no_license
grablisting/ray
9356e80e638f3a20c5280b8dba4b6577044d4c6e
967f8aebe2107c8052c18200872f9389e87d19c1
refs/heads/master
2016-09-10T19:51:35.133301
2010-09-29T13:37:26
2010-09-29T13:37:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,308
h
#ifndef NUMBER_H #define NUMBER_H #include "sexpr.h" #include <iostream> #include "bignum.h" class Number : public Sexpr { public: Number(){}; /** Stores an integer as a new bignum. @param b is the integer used to create the bignum. */ Number(int b); /** Creates a new bignum. @param b is the bignum used to create the bignum. */ Number(bignum b); /** Reads numbers. @param in is the source. */ void read(istream& in); /** Prints numbers. @param out is the destination. */ void print(ostream& out); /** Calls bignum_add. @param other is the number to add. @param return is a pointer to the result. */ Sexpr* add(Sexpr* other); /** Calls bignum_subtract. @param other is the number to subtract. @param return is a pointer to the difference. */ Sexpr* subtract(Sexpr* other); /** Calls bignum_multiply. @param other is the number to multiply. @param return is a pointer to the product. */ Sexpr* multiply(Sexpr* other); /** Returns the value of the Sexpr::Number. @param return is the Sexpr::Number. */ bignum get_number(); /** Compares Val[0] to zero. @param return is a boolean answer. */ bool zero(); private: bignum Val; }; #endif
[ "Bobbbbommmbb@Bobbbbommmbb-PC.(none)" ]
[ [ [ 1, 73 ] ] ]
902b681642adf7953e810252252e2cbb8c87bba7
5fa57a0bf6492f713b33847752d8be7059d7cd5f
/master.h
51872c4889045fa4d7f5a7df80b66543ce4f43ba
[]
no_license
smitec/workers
75bad36602ee3d341a7261612cd6e3e6d1a8d3e0
875dec02c7f604361838949972443c30243db3ea
refs/heads/master
2021-01-18T13:49:45.115527
2011-09-24T07:57:10
2011-09-24T07:57:10
2,261,180
0
0
null
null
null
null
UTF-8
C++
false
false
800
h
#ifndef MASTER_H #define MASTER_H #include "Worker.h" #include <pthread.h> /* Master starts and the tread is running until it is killed. A master is assigned a Worker, makes it execute its task After the task is collected it waits again for a new Worker Masters are designed to remove thread overhead */ void* master_thread(void* masterPtr); class master { public: master(); virtual ~master(); bool assign_worker(Worker* newWorker, bool noHang = false); void start_master(); void kill(); Worker* currentJob; bool busy; bool newJob; bool killMe; bool pending; bool jobCollected; pthread_t threadID; protected: private: }; #endif // MASTER_H
[ [ [ 1, 41 ] ] ]
d008c9a51c8883358250fe5baeb530bf27109c69
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/tools/wftools.cc
50902f3e350402a2e653ecbce1e89f0d48e1ba8a
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,239
cc
//-------------------------------------------------------------------- // wftools.cc // // Allgemeine Support-Routinen fuer wf-Tools. // // (C) 1998 A.Weissflog //-------------------------------------------------------------------- #include "tools/wftools.h" #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <string.h> #include <math.h> //-------------------------------------------------------------------- // wf_findarg() // // 27-Dec-98 floh created //-------------------------------------------------------------------- int wf_findarg(int argc, char *argv[], char *opt) { int i; for (i=1; i<argc; i++) { char *arg = argv[i]; if (strcmp(arg,opt)==0) return i; } return 0; } //-------------------------------------------------------------------- // wf_getfloatarg() // wf_getstrarg() // wf_getintarg() // wf_getboolarg() // // Suche Argument-Wert definiert durch "opt", wenn nicht // existent, returniere "def", wenn Fehler, exit(); // Die "bool" Funktion returniert true, wenn die Option // existiert, false, wenn nicht. // // 27-Dec-98 floh created //-------------------------------------------------------------------- float wf_getfloatarg(int argc, char *argv[], char *opt, float def) { int i = wf_findarg(argc,argv,opt); if (i == 0) return def; else if (++i < argc) return (float) atof(argv[i]); else { fprintf(stderr,"arg error after %s\n", opt); exit(10); } return 0.0f; } char *wf_getstrarg(int argc, char *argv[], char *opt, char *def) { int i = wf_findarg(argc,argv,opt); if (i == 0) return def; else if (++i < argc) return argv[i]; else { fprintf(stderr,"arg error after %s\n", opt); exit(10); } return NULL; } int wf_getintarg(int argc, char *argv[], char *opt, int def) { int i = wf_findarg(argc,argv,opt); if (i == 0) return def; else if (++i < argc) return atoi(argv[i]); else { fprintf(stderr,"arg error after %s\n", opt); exit(10); } return 0; } bool wf_getboolarg(int argc, char *argv[], char *opt) { int i = wf_findarg(argc,argv,opt); if (i == 0) return false; else return true; } //-------------------------------------------------------------------- // wf_getstrargs() // // Sucht das uebergebene Keyword und returniert im uebergebenen // Buffer alle Args, die nach dem Keyword kommen, bis zum // letzten Arg, oder bis ein Arg kommt, welches mit '-' // anfaengt. // // 17-Aug-99 floh created //-------------------------------------------------------------------- char *wf_getstrargs(int argc, char *argv[], char *opt, char *buf, int buf_size) { buf[0] = 0; int i = wf_findarg(argc,argv,opt); int l = 1; if (i > 0) { for (++i; i<argc; i++) { // beim naechsten Arg, welches mit '-' anfaengt, // abbrechen if (argv[i][0] == '-') break; l += strlen(argv[i]) + 1; if (l < buf_size) { strcat(buf,argv[i]); strcat(buf," "); } } } return buf; } //-------------------------------------------------------------------- // wf_openfiles() // Check command line if in/out files are given, if not, // use stdin/stdout. // 24-Oct-00 floh created //-------------------------------------------------------------------- bool wf_openfiles(int argc, char *argv[], FILE *& in, FILE *& out) { char *in_str = wf_getstrarg(argc, argv, "-in", NULL); char *out_str = wf_getstrarg(argc, argv, "-out", NULL); if (in_str) { in = fopen(in_str,"r"); if (!in) { fprintf(stderr, "Could not open '%s' for reading!\n",in_str); in = NULL; out = NULL; return false; } } else { in = stdin; } if (out_str) { out = fopen(out_str,"w"); if (!out) { fprintf(stderr, "Could not open '%s' for writing!\n",out_str); in = NULL; out = NULL; return false; } } else { out = stdout; } return true; } //-------------------------------------------------------------------- // wf_closefiles() // Close file handles opened by wf_openfiles() // 24-Oct-00 floh created //-------------------------------------------------------------------- void wf_closefiles(FILE *in, FILE *out) { if (in) { if (in != stdin) fclose(in); } if (out) { if (out != stdout) fclose(out); } } //-------------------------------------------------------------------- // EOF //--------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 338 ] ] ]
2eacc7677e38efa6d68dfe6f668bf89abc714acb
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/src/ParticleObservers/ParticleUniverseOnCountObserverTokens.cpp
cb10e50bba1c3b6c57de3f451bb8a1bfea136dfe
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,294
cpp
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #include "ParticleUniversePCH.h" #ifndef PARTICLE_UNIVERSE_EXPORTS #define PARTICLE_UNIVERSE_EXPORTS #endif #include "ParticleObservers/ParticleUniverseOnCountObserver.h" #include "ParticleObservers/ParticleUniverseOnCountObserverTokens.h" namespace ParticleUniverse { //----------------------------------------------------------------------- bool OnCountObserverTranslator::translateChildProperty(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { Ogre::PropertyAbstractNode* prop = reinterpret_cast<Ogre::PropertyAbstractNode*>(node.get()); ParticleObserver* ob = Ogre::any_cast<ParticleObserver*>(prop->parent->context); OnCountObserver* observer = static_cast<OnCountObserver*>(ob); if (prop->name == token[TOKEN_ONCOUNT_THRESHOLD]) { // Property: count_threshold if (passValidatePropertyNumberOfValues(compiler, prop, token[TOKEN_ONCOUNT_THRESHOLD], 2)) { Ogre::String compareType; Ogre::uint val = 0; Ogre::AbstractNodeList::const_iterator i = prop->values.begin(); if(getString(*i, &compareType)) { if (compareType == token[TOKEN_LESS_THAN]) { observer->setCompare(CO_LESS_THAN); } else if (compareType == token[TOKEN_GREATER_THAN]) { observer->setCompare(CO_GREATER_THAN); } ++i; if(getUInt(*i, &val)) { observer->setThreshold(val); return true; } } } } return false; } //----------------------------------------------------------------------- bool OnCountObserverTranslator::translateChildObject(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { // No objects return false; } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- void OnCountObserverWriter::write(ParticleScriptSerializer* serializer, const IElement* element) { // Cast the element to a OnCountObserver const OnCountObserver* observer = static_cast<const OnCountObserver*>(element); // Write the header of the OnCountObserver serializer->writeLine(token[TOKEN_OBSERVER], observer->getObserverType(), observer->getName(), 8); serializer->writeLine("{", 8); // Write base attributes ParticleObserverWriter::write(serializer, element); // Write own attributes Ogre::String compare = token[TOKEN_GREATER_THAN]; if (observer->getCompare() == CO_LESS_THAN) compare = token[TOKEN_LESS_THAN]; serializer->writeLine(token[TOKEN_ONCOUNT_THRESHOLD], compare, Ogre::StringConverter::toString(observer->getThreshold()), 12); // Write the close bracket serializer->writeLine("}", 8); } }
[ [ [ 1, 90 ] ] ]
6f15b067d6f23c9fe44b186cb32f722ab9016015
441f38f6cec9ff04ea02ee4aa509bcb7d23fb59d
/src/DateManipulator.cpp
ee4c5be782a16e456bb0782faf18faceaa4bfce1
[]
no_license
ptrv/drawinglife_datemanipulator
4b5e4ce41f44534d6bc23ad1c2de21ceccb09c06
cc06254fbad5c135f5720b3e5025fca851128c11
refs/heads/master
2020-05-16T22:05:51.285772
2010-05-31T08:31:07
2010-05-31T08:31:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,888
cpp
/*========================================================== Copyright (c) avp::ptr, 2010 ==========================================================*/ #include "DateManipulator.h" #include <sstream> #include <limits> #include <cmath> #include <ctime> void DateManipulator::manipulate(const GpsPoint& reference, std::vector<GpsPoint>& points) { // Reset the former closest point. cp.setGpsPoint(0, 0.0, 0.0, 0.0, "0000-00-00T00:00:00Z"); // Return if there is nothing to do. if (points.size() == 0) return; // Get closest point to reference. std::vector<GpsPoint>::iterator point = getClosestPoint(reference, points); // Remeber that point before manipulating its timestamp. cp = *point; // Manipulate all timestamps so that they match to the given reference. this->setTimestamps(reference, points.begin(), points.end(), point); } GpsPoint DateManipulator::getClosestGpsPoint() { return cp; } std::vector<GpsPoint>::iterator DateManipulator::getClosestPoint(const GpsPoint& reference, std::vector<GpsPoint>& points) { // reference values double rLat = reference.getLatitude(); double rLon = reference.getLongitude(); double dist = std::numeric_limits<double>::max(); std::vector<GpsPoint>::iterator closest; std::vector<GpsPoint>::iterator it = points.begin(); std::vector<GpsPoint>::iterator end = points.end(); while (it != end) { double deltaLat = it->getLatitude() - rLat; double deltaLon = it->getLongitude() - rLon; double distance = deltaLat * deltaLat + deltaLon * deltaLon; if (distance < dist) { dist = distance; closest = it; } ++it; } return closest; } void DateManipulator::setTimestamps(const GpsPoint& reference, std::vector<GpsPoint>::iterator begin, std::vector<GpsPoint>::iterator end, std::vector<GpsPoint>::iterator point) { // Get refence time in unix-time. time_t refTimestamp = getUnixTime(reference.getTimestamp()); // Get current time in unix-time. time_t curTimestamp = getUnixTime(point->getTimestamp()); // Change all timestamps before the current point. std::vector<GpsPoint>::iterator it = begin; while (it < point) { time_t timestamp = getUnixTime(it->getTimestamp()); time_t delta = curTimestamp - timestamp; time_t newTimestamp = refTimestamp - delta; it->setTimestamp(this->getTimestamp(newTimestamp)); ++it; } // Change all timestamps after the current point. it = point + 1; while (it < end) { time_t timestamp = getUnixTime(it->getTimestamp()); time_t delta = timestamp - curTimestamp; time_t newTimestamp = refTimestamp + delta; it->setTimestamp(this->getTimestamp(newTimestamp)); ++it; } // Change timestamp of the current point itself. point->setTimestamp(reference.getTimestamp()); } time_t DateManipulator::getUnixTime(const std::string& d) { int year, month, day, hour, minute, second; // Split given date. std::string date = d.substr(0, d.find('T')); std::string time = d.substr(d.find('T') + 1, 8); // Split date. std::stringstream(date.substr(0, 4)) >> year; // 2010 std::stringstream(date.substr(5, 7)) >> month; // 02 std::stringstream(date.substr(8, 10)) >> day; // 09 // Split time. std::stringstream(time.substr(0, 2)) >> hour; // 10 std::stringstream(time.substr(3, 5)) >> minute; // 39 std::stringstream(time.substr(6, 8)) >> second; // 05 tm t; t.tm_year = year - 1900; t.tm_mon = month; t.tm_mday = day; t.tm_hour = hour + 1; t.tm_min = minute; t.tm_sec = second; return mktime(&t); } std::string DateManipulator::getTimestamp(const time_t& uTime) { // Convert from unix time to a readable format. tm* time = gmtime(&uTime); std::stringstream date; // Year date << (time->tm_year + 1900); date << "-"; // Month if (time->tm_mon < 10) date << 0; date << time->tm_mon; date << "-"; // Day if (time->tm_mday < 10) date << 0; date << time->tm_mday; date << "T"; // Hour if (time->tm_hour < 10) date << 0; date << time->tm_hour; date << ":"; // Minute if (time->tm_min < 10) date << 0; date << time->tm_min; date << ":"; // Second if (time->tm_sec < 10) date << 0; date << time->tm_sec; date << "Z"; return date.str(); } // ----------------------------------------------------------------------------- // Unit testing // ----------------------------------------------------------------------------- /* int main(int argc, char** argv) { // Create reference point. GpsPoint leipzig; leipzig.setGpsPoint(0, 6, 7, 0, std::string("1989-11-20T17:15:25Z")); // Create sample points. GpsPoint a, b, c, d, e; a.setGpsPoint(1, 2, 2, 0, std::string("2010-02-09T10:39:05Z")); b.setGpsPoint(2, 4, 4, 0, std::string("2010-02-09T10:45:05Z")); c.setGpsPoint(3, 4, 6, 0, std::string("2010-02-09T10:50:05Z")); d.setGpsPoint(4, 6, 6, 0, std::string("2010-02-09T10:55:05Z")); e.setGpsPoint(5, 9, 9, 0, std::string("2010-02-09T11:01:05Z")); std::vector<GpsPoint> points; points.push_back(a); points.push_back(b); points.push_back(c); points.push_back(d); points.push_back(e); // Print all points. std::cout << "Points before timestamp manipulation." << std::endl; for (unsigned int i = 0; i < points.size(); i++) { std::cout << points.at(i) << std::endl; } // Manipulate all their time stamps. std::cout << "" << std::endl; std::cout << "Find closest GpsPoint to that reference GpsPoint" << std::endl; std::cout << leipzig << std::endl; std::cout << "" << std::endl; DateManipulator dm; dm.manipulate(leipzig, points); // Print all points again. std::cout << "Manipulate all GpsPoint in the way that they match to the refrence." << std::endl; for (unsigned int i = 0; i < points.size(); i++) { std::cout << points.at(i) << std::endl; } return 0; } */
[ [ [ 1, 4 ], [ 31, 31 ] ], [ [ 5, 30 ], [ 32, 200 ] ] ]
64db563b2a0dff927e7b348fdd6f11a9b5938166
0ea3a623e3a514184649a087c636338c53e25d93
/src/Unknown.h
390d6417db11fb46a05ca728517faf583bfd83dd
[]
no_license
scottrick/rt
7c660f3ae2dd6bd51fd470f2f9830700632a1306
e3b3d31b4c56629a9cd8708e36e2de12be4a6486
refs/heads/master
2021-01-20T10:56:38.764827
2011-04-24T00:29:13
2011-04-24T00:29:13
1,647,923
0
0
null
null
null
null
UTF-8
C++
false
false
269
h
#ifndef _UNKNOWN_H_ #define _UNKNOWN_H_ class Unknown { public: Unknown() {}; ~Unknown() {}; virtual void Print() = 0; virtual void Refresh(int DeltaTime) = 0; private: }; #endif
[ [ [ 1, 18 ] ] ]
730a8aaacedfc921a7ef87b79a6be29419c8a217
e01dc698db930a300bd6e27412cd027635151f6a
/rodador-de-mepa/rodador_mepa/mepa.h
d61dad5923790bc92a997d894febe6c7a5d193e8
[]
no_license
lucasjcastro/rodador-de-mepa
becda6a9cdb6bbbec6e339f7bb52ec1dda48a89f
933fe3f522f55c55e8056c182016f9f06280b3e0
refs/heads/master
2021-01-10T07:37:40.226661
2008-09-25T02:27:58
2008-09-25T02:27:58
46,521,554
0
0
null
null
null
null
ISO-8859-1
C++
false
false
689
h
/* * A função dessa classe é executar a traducao propriamente dita da MEPA * */ #ifndef MEPA_H_ #define MEPA_H_ #include <iostream> #include <fstream> #include <string> #include <vector> #include "node.h" class mepa{ public: //construtor mepa(); //inicia analise da lista MEPA void traducao(std::vector<node> comandos); //metodo para a instrucao CRCT void crct(node comando); private: int s, i; //??? M, P; }; #endif /*MEPA_H_*/
[ "solenoide.spm@33f839a4-89d3-11dd-bc3c-d57f4316d18f" ]
[ [ [ 1, 31 ] ] ]
dd329ed25c4d55bffd3958d326d58b37cfabf958
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/terralib/src/terralib/functions/TeImportMIF.cpp
657f82eb7b3f67ff3e285bc12da7d5cd307ca73d
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,914
cpp
/************************************************************************************ TerraLib - a library for developing GIS applications. Copyright � 2001-2007 INPE and Tecgraf/PUC-Rio. This code is part of the TerraLib library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. You should have received a copy of the GNU Lesser General Public License along with this library. The authors reassure the license terms regarding the warranties. They specifically disclaim any warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. The library provided hereunder is on an "as is" basis, and the authors have no obligation to provide maintenance, support, updates, enhancements, or modifications. In no event shall INPE and Tecgraf / PUC-Rio be held liable to any party for direct, indirect, special, incidental, or consequential damages arising out of the use of this library and its documentation. *************************************************************************************/ #include <string> #include <iostream> #include <list> #ifdef WIN32 #include <io.h> #else #include <unistd.h> #endif using namespace std; #include "../kernel/TeTable.h" #include "../kernel/TeGeometry.h" #include "../kernel/TeAsciiFile.h" #include "TeMIFProjection.h" #include "../kernel/TeException.h" #include "../kernel/TeProjection.h" #include "../kernel/TeAttribute.h" #include "../kernel/TeTable.h" #include "../kernel/TeAssertions.h" #include "../kernel/TeUtils.h" #include "../kernel/TeLayer.h" #include "../kernel/TeGeometryAlgorithms.h" #include "../kernel/TeDatabase.h" #include "TeDriverMIDMIF.h" void TeMIFRegionDecode ( TeAsciiFile& mifFile, TePolygonSet& temp, string& index); void TeMIFLineDecode (TeAsciiFile& mifFile, TeLineSet& temp, string& index); void TeMIFPlineDecode (TeAsciiFile& mifFile, TeLineSet& temp, string& index); void TeMIFPointDecode (TeAsciiFile& mifFile, TePointSet& temp, string& index); void TeMIFMultiPointDecode (TeAsciiFile& mifFile, TePointSet& temp, string& index); void TeMIFTextDecode (TeAsciiFile& mifFile, TeTextSet& temp, string& index); void TeMIFCollectionDecode(TeAsciiFile& mifFile, TePointSet& ps, TeLineSet& ls, TePolygonSet& pols, string& index); void TeMIFRectDecode (TeAsciiFile& mifFile, TePolygonSet& temp, string& index); void TeMIFOthersDecode ( TeAsciiFile& ); void TeMIFTransformDecode ( TeAsciiFile& ); bool TeReadMIFAttributes(TeAsciiFile& midFile, TeTable& attTable, int ncolumns, int nrecords=-1, int delta = 0, bool createAuto=false); bool TeImportMIFGeometries(TeLayer* layer,const string& mifFileName, vector<string> &indexes, unsigned int chunckSize); char TeReadMIFSeparator(const string& mifFileName); double glXmulti = 1., glYmulti = 1; TeCoord2D glAdd (0., 0. ); TeLayer* TeImportMIF(const string& mifFileName, TeDatabase* db, const string& layerName) { if (!db || mifFileName.empty()) return 0; // check if format is complete (MID and MIF files exist) string filePrefix = TeGetName(mifFileName.c_str()); string ftest = filePrefix + ".mid"; if (access(ftest.c_str(),04) == -1) { ftest = filePrefix + ".MID"; if (access(ftest.c_str(),04) == -1) return 0; } ftest = filePrefix + ".mif"; if (access(ftest.c_str(),04) == -1) { ftest = filePrefix + ".MIF"; if (access(ftest.c_str(),04) == -1) return 0; } // found a valid layer name string lName; string baseName = TeGetBaseName(mifFileName.c_str()); if (layerName.empty()) lName = baseName; else lName = layerName; string newLayerName = lName; TeLayerMap& layerMap = db->layerMap(); TeLayerMap::iterator it; bool flag = true; int n = 1; while (flag) { for (it = layerMap.begin(); it != layerMap.end(); ++it) { if (TeStringCompare(it->second->name(),newLayerName)) break; } if (it == layerMap.end()) flag = 0; else newLayerName = lName + "_" +Te2String(n); n++; } // find projection TeProjection* mifProj = TeReadMIFProjection(ftest); TeLayer* newLayer = new TeLayer(newLayerName,db,mifProj); if (newLayer->id() <= 0 ) return 0; // couldn�t create new layer bool res = TeImportMIF(newLayer,ftest); delete mifProj; if (res) return newLayer; else { db->deleteLayer(newLayer->id()); delete newLayer; return 0; } } bool TeImportMIF(TeLayer* layer, const string& mifFileName, string attrTableName, string objectIdAttr, unsigned int chunkSize) { // check if format is complete (MID and MIF files exist) string filePrefix = TeGetName(mifFileName.c_str()); string ftest = filePrefix + ".mid"; if (access(ftest.c_str(),04) == -1) { ftest = filePrefix + ".MID"; if (access(ftest.c_str(),04) == -1) return false; } string midfilename = ftest; ftest = filePrefix + ".mif"; if (access(ftest.c_str(),04) == -1) { ftest = filePrefix + ".MIF"; if (access(ftest.c_str(),04) == -1) return false; } string miffilename = ftest; //-- Step 1: Read any adicional information (ex. projection) if (!layer->projection()) { TeProjection* mifProj = TeReadMIFProjection(miffilename); if (mifProj) layer->setProjection(mifProj); } char separator = TeReadMIFSeparator(miffilename); //read the attribute list information TeAttributeList attList; TeReadMIFAttributeList(miffilename, attList); // define a TeAttributeTable if (attrTableName.empty()) { if (layer->name().empty()) return false; else attrTableName = layer->name(); } string aux = attrTableName; int c = 1; while (layer->database()->tableExist(aux)) { aux = attrTableName + "_" + Te2String(c); ++c; } attrTableName = aux; int linkCol=-1, j=0; bool autoIndex = false; // if no geometry link name is given, creates one called 'object_id' if (objectIdAttr.empty()) { objectIdAttr = "object_id_"+Te2String(layer->id()); TeAttribute at; at.rep_.type_ = TeSTRING; at.rep_.numChar_ = 16; at.rep_.name_ = objectIdAttr; at.rep_.isPrimaryKey_ = true; attList.push_back(at); autoIndex = true; } else { // check if given index is valid TeAttributeList::iterator it = attList.begin(); while (it != attList.end()) { if (TeConvertToUpperCase((*it).rep_.name_) == TeConvertToUpperCase(objectIdAttr)) // index found { if ((*it).rep_.type_ != TeSTRING) // make sure it is a String type { (*it).rep_.type_ = TeSTRING; (*it).rep_.numChar_ = 16; } linkCol=j; (*it).rep_.isPrimaryKey_ = true; break; } it++; j++; } if (it == attList.end()) // index not found { TeAttribute at; at.rep_.type_ = TeSTRING; at.rep_.numChar_ = 16; at.rep_.name_ = objectIdAttr; at.rep_.isPrimaryKey_ = true; attList.push_back(at); autoIndex = true; } } if (autoIndex) linkCol = attList.size()-1; TeTable attTable (attrTableName,attList,objectIdAttr,objectIdAttr,TeAttrStatic); attTable.setSeparator(separator); // insert the table into the database if (!layer->createAttributeTable(attTable)) return false; vector<string> objectIds; int ncol = attList.size(); if (autoIndex) ncol--; TeAsciiFile midFile(midfilename); int delta = 0; while (TeReadMIFAttributes(midFile,attTable,ncol,chunkSize,delta, autoIndex)) { for (unsigned int n=0; n<attTable.size();++n) objectIds.push_back(attTable.operator ()(n,linkCol)); // save table if (!layer->saveAttributeTable( attTable )) { attTable.clear(); break; } delta += attTable.size(); attTable.clear(); } // Import the geometries bool res = TeImportMIFGeometries(layer,miffilename,objectIds,chunkSize); // Create the spatial indexes int rep = layer->geomRep(); if (rep & TePOINTS) { layer->database()->insertMetadata(layer->tableName(TePOINTS),layer->database()->getSpatialIdxColumn(TePOINTS), 0.0005,0.0005,layer->box()); layer->database()->createSpatialIndex(layer->tableName(TePOINTS),layer->database()->getSpatialIdxColumn(TePOINTS), (TeSpatialIndexType)TeRTREE); } if (rep & TeLINES) { layer->database()->insertMetadata(layer->tableName(TeLINES),layer->database()->getSpatialIdxColumn(TeLINES), 0.0005,0.0005,layer->box()); layer->database()->createSpatialIndex(layer->tableName(TeLINES),layer->database()->getSpatialIdxColumn(TeLINES), (TeSpatialIndexType)TeRTREE); } if (rep & TePOLYGONS) { layer->database()->insertMetadata(layer->tableName(TePOLYGONS),layer->database()->getSpatialIdxColumn(TePOLYGONS), 0.0005,0.0005,layer->box()); layer->database()->createSpatialIndex(layer->tableName(TePOLYGONS),layer->database()->getSpatialIdxColumn(TePOLYGONS), (TeSpatialIndexType)TeRTREE); } return res; } bool TeReadMIFAttributes(TeAsciiFile& midFile, TeTable& attTable, int ncolumns, int nrecords, int delta, bool createAuto ) { if (!midFile.isNotAtEOF() || nrecords <=0 || ncolumns <= 0) return false; char separator = attTable.separator(); int count; for (count=0; count<nrecords; count++) { if (!midFile.isNotAtEOF()) break; TeTableRow row; for (int n=0; n<ncolumns; n++) { string value; try { value = midFile.readStringCSVNoQuote(separator); } catch(...) { if (count > 0) return true; else return false; } row.push_back ( value ); } if (createAuto) row.push_back(Te2String(count+delta)); attTable.add(row); midFile.findNewLine(); } return true; } char TeReadMIFSeparator(const string& mifFileName) { TeAsciiFile mifFile(mifFileName); string name = mifFile.readString (); while ( mifFile.isNotAtEOF() && !TeStringCompare(name,"Delimiter")) name = mifFile.readString (); if (mifFile.isNotAtEOF()) return mifFile.readQuotedChar(); else return '\t'; } TeProjection* TeReadMIFProjection(const string& mifFileName) { TeProjection* proj = 0; TeAsciiFile mifFile(mifFileName); string name = mifFile.readString (); while ( mifFile.isNotAtEOF() && !TeStringCompare(name,"CoordSys") && !TeStringCompare(name,"Columns")) name = mifFile.readString (); if (mifFile.isNotAtEOF() && TeStringCompare(name,"CoordSys")) { string option = mifFile.readString(); vector<string> argList; if (TeStringCompare(option,"Earth")) // expect Projection clause { string projRef = mifFile.readString (); if (!TeStringCompare(projRef,"Projection")) { proj = new TeNoProjection(); return proj; } mifFile.readStringListCSV(argList,','); proj = TeMIFProjectionFactory::make ( argList ); // create projection from parameters } else if (TeStringCompare(option,"Nonearth")) // non earth { // look for units specification while (mifFile.isNotAtEOF() && !TeStringCompare(name,"Units") && !TeStringCompare(name,"Columns")) name = mifFile.readString (); if (TeStringCompare(name,"Units")) { name = mifFile.readString(); proj = new TeNoProjection(name); } else proj = new TeNoProjection(name); } } else // no CoordSys clause specified { // it should be assumed that the data is stored in Lat Long TeDatum datum = TeDatumFactory::make("Spherical"); proj = new TeLatLong(datum); } return proj; } void TeReadMIFAttributeList ( const string& mifFileName, TeAttributeList& attList ) { TeAsciiFile mifFile(mifFileName); string name = mifFile.readString (); while ( mifFile.isNotAtEOF() && !TeStringCompare(name,"Columns")) name = mifFile.readString (); if (mifFile.isNotAtEOF()) { int ncol = mifFile.readInt(); mifFile.findNewLine(); TeAttribute attribute; for ( int i = 0; i< ncol; i++ ) { attribute.rep_.name_ = mifFile.readString(); string attType = mifFile.readStringCSVNoSpace ('('); if ( TeStringCompare(attType,"Integer") || TeStringCompare(attType,"Smallint") || TeStringCompare(attType,"Logical") ) { attribute.rep_.type_ = TeINT; } else if (TeStringCompare(attType,"Float")) { attribute.rep_.type_ = TeREAL; attribute.rep_.numChar_ = 20; attribute.rep_.decimals_ = 1; } else if (TeStringCompare(attType,"Date")) { attribute.rep_.type_ = TeDATETIME; attribute.dateTimeFormat_="YYYYMMDD"; } else if (TeStringCompare(attType,"Decimal")) { attribute.rep_.type_ = TeREAL; attribute.rep_.numChar_ = mifFile.readIntCSV(); attribute.rep_.decimals_ = mifFile.readIntCSV(')'); } else { attribute.rep_.type_ = TeSTRING; attribute.rep_.numChar_ = mifFile.readIntCSV(')'); } attList.push_back ( attribute ); mifFile.findNewLine(); } } } bool TeImportMIFGeometries(TeLayer* layer,const string& mifFileName, vector<string> &indexes, unsigned int chunckSize) { TePointSet pointSet; TeLineSet lineSet; TePolygonSet polySet; TeTextSet textSet; string textTableName = layer->name() + "Texto"; double oldPrec = TePrecision::instance().precision(); try { if(layer) { TePrecision::instance().setPrecision(TeGetPrecision(layer->projection())); } else { TePrecision::instance().setPrecision(TeGetPrecision(0)); } TeAsciiFile mifFile(mifFileName); int n = 0; while ( mifFile.isNotAtEOF() ) { string name = mifFile.readString (); if (TeStringCompare(name,"Region")) { TeMIFRegionDecode ( mifFile, polySet, indexes[n]); n++; if ( polySet.size() == chunckSize ) { layer->addPolygons( polySet ); polySet.clear(); } } else if (TeStringCompare(name,"Pline")) { TeMIFPlineDecode ( mifFile, lineSet, indexes[n] ); n++; if ( lineSet.size() == chunckSize ) { layer->addLines( lineSet ); lineSet.clear(); } } else if (TeStringCompare(name,"Line")) { TeMIFLineDecode ( mifFile, lineSet, indexes[n] ); n++; if ( lineSet.size() == chunckSize ) { layer->addLines( lineSet ); lineSet.clear(); } } else if (TeStringCompare(name,"Point")) { TeMIFPointDecode ( mifFile, pointSet, indexes[n] ); n++; if ( pointSet.size() == chunckSize ) { layer->addPoints( pointSet ); pointSet.clear(); } } else if (TeStringCompare(name,"Multipoint")) { TeMIFMultiPointDecode ( mifFile, pointSet, indexes[n] ); n++; if ( pointSet.size() == chunckSize ) { layer->addPoints( pointSet ); pointSet.clear(); } } else if (TeStringCompare(name,"Text")) { TeMIFTextDecode ( mifFile, textSet,indexes[n]); n++; if ( textSet.size() == chunckSize ) { layer->addText( textSet,textTableName ); textSet.clear(); } } else if (TeStringCompare(name,"Rect")) { TeMIFRectDecode(mifFile,polySet,indexes[n]); n++; if (polySet.size() == chunckSize ) { layer->addPolygons(polySet); polySet.clear(); } } else if (TeStringCompare(name,"Collection")) { TeMIFCollectionDecode(mifFile,pointSet,lineSet, polySet,indexes[n]); n++; if (lineSet.size() == chunckSize ) { layer->addLines(lineSet); lineSet.clear(); } if (polySet.size() == chunckSize ) { layer->addPolygons(polySet); polySet.clear(); } if (pointSet.size() == chunckSize ) { layer->addPoints(pointSet); pointSet.clear(); } } else if (TeStringCompare(name,"Transform")) TeMIFTransformDecode ( mifFile ); else if (TeStringCompare(name,"NONE")) n++; else TeMIFOthersDecode ( mifFile ); } // save the remaining geometries if (pointSet.size() > 0 ) { layer->addPoints( pointSet ); pointSet.clear(); } if (lineSet.size() > 0 ) { layer->addLines( lineSet ); lineSet.clear(); } if (polySet.size() > 0 ) { layer->addPolygons( polySet ); polySet.clear(); } if (textSet.size() > 0) { layer->addText( textSet,textTableName ); textSet.clear(); } } catch(...) { TePrecision::instance().setPrecision(oldPrec); return false; } TePrecision::instance().setPrecision(oldPrec); return true; } void TeMIFRectDecode (TeAsciiFile& mifFile, TePolygonSet& temp, string& index) { if (index.empty()) index = "te_nulo"; TeCoord2D ll = mifFile.readCoord2D(); TeCoord2D ur = mifFile.readCoord2D(); TeBox rec(ll.x_,ll.y_,ur.x_,ur.y_); TePolygon pol = polygonFromBox(rec); pol.objectId(index); temp.add(pol); } void TeMIFRegionDecode ( TeAsciiFile& mifFile, TePolygonSet& temp, string& index) { if (index.empty()) index = "te_nulo"; int npolyg = mifFile.readInt(); mifFile.findNewLine(); TeCoord2D pt; TePolygon pol; typedef list<TePolygon> PolyList; PolyList pList; for ( int i = 0; i < npolyg; i++ ) { TeLine2D line; int ncoord = mifFile.readInt(); mifFile.findNewLine(); for ( int j = 0; j < ncoord; j++ ) { pt = mifFile.readCoord2D(); pt.scale( glXmulti, glYmulti); pt += glAdd; mifFile.findNewLine(); line.add ( pt ); } if ( line.size() <= 3 ) continue; // to avoid dangling rings if ( !line.isRing() ) //close the ring { line.add(line[0]); // throw TeException ( MIF_REGION_CLOSE ); } TeLinearRing ring (line); bool inside = false; PolyList::iterator it = pList.begin(); while ( it != pList.end() ) { TePolygon p1; p1.add(ring); TePolygon p2 = (*it); short rel = TeRelation(p1, p2); if((rel & TeWITHIN) || (rel & TeCOVEREDBY)) { inside = true; ring.objectId(p2[0].objectId()); p2.add ( ring );// add a closed region } ++it; } if ( !inside ) { TePolygon poly; ring.objectId(index); poly.add ( ring ); // add an outer region poly.objectId(index); pList.push_back ( poly ); } } PolyList::iterator it = pList.begin(); while ( it != pList.end() ) { temp.add ( *it ); // add a polygon to a layer ++it; } } void TeMIFLineDecode (TeAsciiFile& mifFile, TeLineSet& temp, string& index) { if (index.empty()) index = "te_nulo"; TeLine2D line; TeCoord2D pt; for ( int i= 0; i < 2; i++ ) { pt = mifFile.readCoord2D(); pt.scale( glXmulti, glYmulti); pt += glAdd; line.add ( pt ); } line.objectId( index ); temp.add ( line ); mifFile.findNewLine(); } void TeMIFPlineDecode (TeAsciiFile& mifFile, TeLineSet& temp, string& index) { if (index.empty()) index = "te_nulo"; int numSections = 1; int ncoord = 0; // Read the Pline parameters vector<string> strList; mifFile.readStringList ( strList ); // Are we dealing with MULTIPLE sections ?? // If there are two parameters for the pline, // the first MUST be a "Multiple" keyword bool hasMultiple = false; if ( strList.size() == 2 ) { hasMultiple = true; ensure (TeStringCompare(strList[0],"Multiple")); numSections = atoi ( strList[1].c_str() ); } else ncoord = atoi ( strList[0].c_str()); mifFile.findNewLine(); // go to the next line // If there is a single PLine, there is a single // section ( numSections = 1 ) and will read // the number of points within the loop for ( int i= 0; i < numSections; i++ ) { TeLine2D line; TeCoord2D pt; if ( hasMultiple == true ) { ncoord = mifFile.readInt(); mifFile.findNewLine(); // go to the next line } for ( int j = 0; j < ncoord; j++ ) { pt = mifFile.readCoord2D(); pt.scale( glXmulti, glYmulti); pt += glAdd; mifFile.findNewLine(); line.add ( pt ); } line.objectId( index ); temp.add ( line ); } } void TeMIFPointDecode (TeAsciiFile& mifFile, TePointSet& temp, string& index) { if (index.empty()) index = "te_nulo"; TePoint point; // Read the coordinates TeCoord2D pt = mifFile.readCoord2D(); pt.scale( glXmulti, glYmulti); pt += glAdd; point.add ( pt ); point.objectId( index ); // Add a point to the Point Set temp.add ( point ); mifFile.findNewLine(); } void TeMIFMultiPointDecode (TeAsciiFile& mifFile, TePointSet& temp, string& index) { if (index.empty()) index = "te_nulo"; int npts = mifFile.readInt(); mifFile.findNewLine(); for (int i=0; i<npts;i++) { // Read points TePoint point; TeCoord2D pt = mifFile.readCoord2D(); pt.scale( glXmulti, glYmulti); pt += glAdd; point.add ( pt ); point.objectId( index ); // Add a point to the Point Set temp.add ( point ); } mifFile.findNewLine(); } void TeMIFTransformDecode ( TeAsciiFile& mifFile ) { // read the tansformation params double param = mifFile.readFloatCSV(); if ( param != 0. ) glXmulti = param; param = mifFile.readFloatCSV(); if ( param != 0. ) glYmulti = param; double x = mifFile.readFloatCSV(); double y = mifFile.readFloatCSV(); TeCoord2D pt ( x, y ); glAdd = pt; // Go to the next line mifFile.findNewLine (); } void TeMIFTextDecode (TeAsciiFile& mifFile, TeTextSet& temp, string& index) { std::string strFont; double angle=0; string txt = mifFile.readQuotedString(); // read the text string mifFile.findNewLine (); TeBox box = mifFile.readBox(); // read the text box strFont=mifFile.readFont(); angle=mifFile.readAngle(strFont); TeCoord2D lowerLeft = box.lowerLeft(); TeText text(lowerLeft,txt); text.setBox(box); text.setAngle(angle); text.objectId(index); text.setHeight(box.height()); temp.add(text); //mifFile.findNewLine (); // go to the next line } void TeMIFOthersDecode ( TeAsciiFile& mifFile ) { // Simply go to the next line mifFile.findNewLine (); } void TeMIFCollectionDecode(TeAsciiFile& mifFile, TePointSet& ps, TeLineSet& ls, TePolygonSet& pols, string& index) { int nparts = mifFile.readInt(); if (nparts == 0) nparts = 3; mifFile.findNewLine(); for (int i=0; i<nparts; i++) { string part = mifFile.readString (); if (TeStringCompare(part,"Region")) TeMIFRegionDecode (mifFile, pols, index); else if(TeStringCompare(part,"Pline")) TeMIFPlineDecode (mifFile, ls, index); else if (TeStringCompare(part,"Multipoint")) TeMIFMultiPointDecode (mifFile,ps, index); } }
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 920 ] ] ]
737ebd0131a782b47a7dfd4f06108456ec606530
3970f1a70df104f46443480d1ba86e246d8f3b22
/imebra/src/base/include/stream.h
12615b4caaa2efae1d58bcd3ad6f72ea740a8a5c
[]
no_license
zhan2016/vimrid
9f8ea8a6eb98153300e6f8c1264b2c042c23ee22
28ae31d57b77df883be3b869f6b64695df441edb
refs/heads/master
2021-01-20T16:24:36.247136
2009-07-28T18:32:31
2009-07-28T18:32:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,449
h
/* 0.0.46 Imebra: a C++ dicom library. Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 by Paolo Brandoli This program is free software; you can redistribute it and/or modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 for more details. You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE Version 3 along with this program; If not, see http://www.gnu.org/licenses/ ------------------- If you want to use Imebra commercially then you have to buy the commercial license available at http://puntoexe.com After you buy the commercial license then you can use Imebra according to the terms described in the Imebra Commercial License Version 1. A copy of the Imebra Commercial License Version 1 is available in the documentation pages. Imebra is available at http://puntoexe.com The author can be contacted by email at [email protected] or by mail at the following address: Paolo Brandoli Preglov trg 6 1000 Ljubljana Slovenia */ /*! \file stream.h \brief Declaration of the stream class. */ #if !defined(imebraStream_3146DA5A_5276_4804_B9AB_A3D54C6B123A__INCLUDED_) #define imebraStream_3146DA5A_5276_4804_B9AB_A3D54C6B123A__INCLUDED_ #include "baseStream.h" #include <ios> #include <stdio.h> /////////////////////////////////////////////////////////// // // Everything is in the namespace puntoexe // /////////////////////////////////////////////////////////// namespace puntoexe { /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// /// \brief This class derives from the baseStream /// class and implements a file stream. /// /// This class can be used to read/write on physical files /// in the mass storage. /// /////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////// class stream : public baseStream { protected: // Destructor /////////////////////////////////////////////////////////// virtual ~stream(); public: // Constructor /////////////////////////////////////////////////////////// stream(): m_openFile(0){} /// \brief Open a file. /// /// The function uses the standard library function /// fopen to open the specified file. /// /// The created file object will be automatically /// closed and destroyed when one of the following events /// will occur: /// - the stream class will be destroyed /// - this function will be called again /// /// @param fileName the name of the file to be opened /// @param mode the opening mode. /// Can be the combination of one or /// more of the following values: /// - ios_base::in the file will be opened /// for reading operations /// - ios_base::out the file will be /// opened for writing operations /// - ios_base::app the writing operations /// will append data to the existing file /// - ios_base::trunc the existing file /// will be truncated to zero length /// - ios_base::binary the file will be /// opened in binary mode. Please note /// that this flag is useless, since all /// the files ARE OPENED IN BINARY MODE. /// /////////////////////////////////////////////////////////// void openFile(std::string fileName, int mode); void openFile(std::wstring fileName, int mode); /////////////////////////////////////////////////////////// // // Virtual stream's functions // /////////////////////////////////////////////////////////// virtual void write(imbxUint32 startPosition, imbxUint8* pBuffer, imbxUint32 bufferLength); virtual imbxUint32 read(imbxUint32 startPosition, imbxUint8* pBuffer, imbxUint32 bufferLength); protected: FILE* m_openFile; }; } // namespace puntoexe #endif // !defined(imebraStream_3146DA5A_5276_4804_B9AB_A3D54C6B123A__INCLUDED_)
[ [ [ 1, 132 ] ] ]
02a3d4eaa8bf8d301fd70ebdd0199060f1c5df72
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Sensors/ParkingMcGhee/ParkingMcGhee/Parker.h
48490aba35cdc3bca1373531d6a82b788245ab8e
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,627
h
#ifndef _PARKER_H #define _PARKER_H #ifdef __cplusplus_cli #pragma managed(push,off) #endif #include "math.h" #include <iostream> using namespace std; struct VehicleParameters{ double back_bumper; // distance from back axle to back bumper double front_bumper; // distance from back axle to front bumper double min_turning_rad; //the area defined by the width of a tire times the wheel radius double width; int skat; }; struct VehicleState{ double x, y; //rear diff postion double hx, hy;//orientation. Don't like vector orientation definitions? kiss my stuff. void Normalize(); }; struct ParkingSpaceParameters{ double corner_xs[2]; double corner_ys[2]; //The parking area is defined by a rectangle. Two opposite corners of the rectangle are nececarry to define it completely. VehicleState park_point; //this defines the final orientation of the vehicle when it is parked. It is important that the angle of park_point //agree with the angle of the rectangle; it needs to be parallel to one set of edges. double pullout_point_x, pullout_point_y; //In pulling out mode, the car will pull out of the spot and align itself parallel to the walls. //You control which direction it points with pullout_point. Place pullout_point on the side of the // "parking axis" that you want the car to point. }; struct MovingOrder{ bool forward; // direction = forward / reverse double turning_radius; //the turning radius describes the center of the circle relative to the vehicle. //The sign indicates the direction, but is independant from the direction the vehicle is traveling. //A positive value indicates that the center of roation is to the left of the vehicle. VehicleState dest_state; double center_x, center_y; }; class Parker{ public: Parker(); Parker(VehicleParameters vehicle, ParkingSpaceParameters space); ~Parker(); bool GetNextParkingOrder(MovingOrder& order, VehicleState state); //give it your current state. It returns true if there's more work to be done, in which case it fills order with values. //return false if its done. bool GetNextPulloutOrder(MovingOrder& order, VehicleState state); //Debugging stuff that you don't care about bool InBounds(VehicleState vs); void GetFourCorners(double* xs, double* ys); //private: VehicleParameters vehicle; double wall_sep; double neg_x_bound; double pos_x_bound; double front_wall_px; double front_wall_py; double front_wall_x; double front_wall_y; double forward_park_position; bool pullout_to_plus_x; bool Get_PA_PA_Traversal_Gentile(VehicleState s1, VehicleState s2, MovingOrder& m1, MovingOrder& m2); //get point-angle - point-angle traversal struct DestinationSlot{ VehicleState state; double utility; DestinationSlot(VehicleState vs); DestinationSlot(); }; void Trans_I_O(VehicleState& vs); void Trans_O_I(VehicleState& vs); void PolishMovingOrder(MovingOrder& mo); static const int angular_resolution = 31; static const int width_resolution = 40; static const int turning_radius_width_range_multiple = 3; DestinationSlot* slots; static const double slot_definition_safety_fraction; int num_slots; VehicleState ideal_back; VehicleState ideal_front; double ReflectionPointUtilityMeasure(VehicleState vs); double* best_angle_for_top_offset; double bafto_idx_loc_conv; double bafto_y_sample; bool QueryComplete(VehicleState vs); //todo static const double complete_distance_fudge; static const double complete_angular_fudge; void NudgeInBounds(VehicleState& vs); MovingOrder GetMaximumLockExtent(VehicleState vs, bool direction, bool left, double stop_at_heading); void GetWiggleRoom(VehicleState vs, double& front_wiggle, double& back_wiggle); VehicleState GetClosestExtent(double angle, double seperation, double horiz); //should be removed VehicleState GetXWallHits(double angle, double horiz, double wall, bool pos, bool front); VehicleState GetYWallHits(double angle, double horiz, double wall, bool pos, bool front); bool FinishingOrder(VehicleState vs, MovingOrder& order); MovingOrder ConstructOneMoveTraversal(VehicleState start, double to_x, double to_y, bool forward); bool GetOneMoveTraversal(VehicleState start, VehicleState to, MovingOrder& order); bool FinalAlignment(VehicleState vs, MovingOrder& order); bool SubFinalAlignment(VehicleState vs, MovingOrder& order, double& util); double GetFinalAlignmentUtility(double finish_y, double turning_rad, double arc_len); bool QueryStateCompletesMovement(VehicleState vs, MovingOrder order); double QueryStaticViolation(VehicleState vs); double QueryMovementViolation(VehicleState start, MovingOrder order); void GetStaticExtents(VehicleState vs, double& max_y, double& min_y, double& max_x, double& min_x); void GetMovementExtents(VehicleState vs, MovingOrder order, double& max_y, double& min_y, double& max_x, double& min_x); void DrawArc(double c_x, double c_y, double x1, double y1, double x2, double y2, bool cw); void FillVehicleCorners(double* xs, double* ys, VehicleState vs); void Show(VehicleState s1, VehicleState s2, VehicleState s3, VehicleState s4, char* name); double AbsAngleDiff(double a1, double a2); bool ClockHitsAFirst(double start_x, double start_y, double a_x, double a_y, double b_x, double b_y); double ArcLen(VehicleState start, MovingOrder order); }; //CvPoint cvPoint(double x, double y); #ifdef __cplusplus_cli #pragma managed(pop) #endif #endif //_PARKER_H
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 165 ] ] ]
4efaaaaa6cb8f8912c6381d67e26490dde0adbe0
4813a54584f8e8a8a2d541291a08b244640a7f77
/libxl/include/lockable.h
a90510bafb989557f16dd7e91c0680891e48e474
[]
no_license
cyberscorpio/libxl
fcc0c67390dd8eae4bb7d36f6a459ffed368183a
8d27566f45234af214a7a1e19c455e9721073e8c
refs/heads/master
2021-01-19T16:56:51.990977
2010-06-30T08:18:41
2010-06-30T08:18:41
38,444,794
0
0
null
null
null
null
UTF-8
C++
false
false
712
h
#ifndef XL_LOCKABLE_H #define XL_LOCKABLE_H /** * implements the ILockable interface */ #include <assert.h> #include <Windows.h> #include "common.h" #include "interfaces.h" XL_BEGIN ////////////////////////////////////////////////////////////////////////// /// user lock, use critical section in windows class CUserLock : public ILockable { protected: mutable CRITICAL_SECTION m_cs; mutable int m_level; public: CUserLock (uint spinCount = 0); virtual ~CUserLock (); virtual void lock () const; virtual void unlock () const; virtual bool tryLock () const; int getLockLevel () const; }; XL_END #endif
[ "doudehou@59b6eb50-eb15-11de-b362-3513cf04e977", "[email protected]" ]
[ [ [ 1, 19 ], [ 21, 22 ], [ 24, 29 ], [ 31, 36 ] ], [ [ 20, 20 ], [ 23, 23 ], [ 30, 30 ] ] ]
0ee8163b428cdd536f9db5d199a7f7279ab48859
bd89d3607e32d7ebb8898f5e2d3445d524010850
/adaptationlayer/modematadaptation/modematcontroller_dll/inc/csignalindreq.h
2c29562922fc33229f0318a4f13a210adae12e79
[]
no_license
wannaphong/symbian-incubation-projects.fcl-modemadaptation
9b9c61ba714ca8a786db01afda8f5a066420c0db
0e6894da14b3b096cffe0182cedecc9b6dac7b8d
refs/heads/master
2021-05-30T05:09:10.980036
2010-10-19T10:16:20
2010-10-19T10:16:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
960
h
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #ifndef CSIGNALINDREQ_H #define CSIGNALINDREQ_H #include <e32base.h> class RModemAtController; class CSignalIndReq : public CActive { public: CSignalIndReq( RModemAtController* aClient); ~CSignalIndReq(); static CSignalIndReq* NewL( RModemAtController* aClient); void ConstructL(); protected: // from CActive void RunL(); void DoCancel(); private: //data RModemAtController* iClient; }; #endif // CSIGNALINDREQ_H
[ "dalarub@localhost" ]
[ [ [ 1, 47 ] ] ]
89a240f03a1033b42c0766347b7142a3ea2388d0
30e4267e1a7fe172118bf26252aa2eb92b97a460
/code/pkg_UnitTest/Modules/TestCore/TestConfigDB.h
d962efc1e51c95dc1ff0058717353337fb35ebf9
[ "Apache-2.0" ]
permissive
thinkhy/x3c_extension
f299103002715365160c274314f02171ca9d9d97
8a31deb466df5d487561db0fbacb753a0873a19c
refs/heads/master
2020-04-22T22:02:44.934037
2011-01-07T06:20:28
2011-01-07T06:20:28
1,234,211
2
0
null
null
null
null
UTF-8
C++
false
false
1,970
h
// Copyright 2008-2011 Zhang Yun Gui, [email protected] // https://sourceforge.net/projects/x3c/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "BaseTest.h" class TestConfigDB : public BaseTest { CPPUNIT_TEST_SUITE( TestConfigDB ); CPPUNIT_TEST( testOpenAccessDB ); CPPUNIT_TEST( testAddRecord ); CPPUNIT_TEST( testAddRecordUseMaxID ); CPPUNIT_TEST( testAddRecordUseMaxIDAndReturnNewID ); CPPUNIT_TEST( testSelectSQL ); CPPUNIT_TEST( testSQLWithOrderBy ); CPPUNIT_TEST( testSQLWithLike ); CPPUNIT_TEST( testEditRecord ); CPPUNIT_TEST( testEditFieldDateTime ); CPPUNIT_TEST( testEditFieldDate ); CPPUNIT_TEST( testEditFieldGetCurDate ); CPPUNIT_TEST( testReadFieldDate ); CPPUNIT_TEST( testRecordsetTransaction ); CPPUNIT_TEST( testDelRecord ); CPPUNIT_TEST_SUITE_END(); public: TestConfigDB(); virtual void setUp(); virtual void tearDown(); void testOpenAccessDB(); void testAddRecord(); void testAddRecordUseMaxID(); void testAddRecordUseMaxIDAndReturnNewID(); void testSelectSQL(); void testSQLWithOrderBy(); void testSQLWithLike(); void testEditRecord(); void testEditFieldDateTime(); void testEditFieldDate(); void testEditFieldGetCurDate(); void testReadFieldDate(); void testDelRecord(); void testRecordsetTransaction(); private: Cx_Ptr GetDatabase(LPCWSTR filename = L"TestAccess.mdb"); private: std::wstring m_dbfile; };
[ "rhcad1@71899303-b18e-48b3-b26e-8aaddbe541a3" ]
[ [ [ 1, 65 ] ] ]
e197d4f71128a031b4a680606fe59335ec81e1e4
bbbced1defe4a25cacd2e3e457c3f6a757682d92
/asteragy_server/stdafx.h
8639adc28472f3fda9591c3d8f6cecbbbfb77eb2
[]
no_license
ForestLight/asteragy
5409debae0660a33662b80fa2f1c99cf1e791d1c
1b497522a3669d78c7326598d999ca228ab1a5dd
refs/heads/master
2016-08-12T23:13:29.936709
2009-12-06T21:59:59
2009-12-06T21:59:59
36,563,577
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,192
h
#ifndef STDAFX_H_ #define STDAFX_H_ #ifdef _MSC_VER #if _MSC_VER >= 1020 #pragma once #endif #if _MSC_VER >= 1400 #define _CRT_SECURE_NO_WARNINGS #define _SCL_SECURE_NO_WARNINGS #endif #pragma warning(push) #pragma warning(disable: 4819 4127 4512 4510 4610 4100 4251) #else #define __assume(x) ((void)0) #endif //_MSC_VER #ifdef __CYGWIN__ #define _WIN32 #endif #if defined _WIN32 || defined _WIN64 //_WIN32だけ見ればよいのはわかっているけど……。 #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include "targetver.h" #include <winsock2.h> #include <windows.h> #define __USE_W32_SOCKETS // MinGW/Cygwin用 #endif #include <iostream> #include <string> #include <map> #include <utility> #include <algorithm> #include <cassert> #define BOOST_ALL_DYN_LINK #include <boost/range.hpp> #include <boost/bind.hpp> //Asioのプレースホルダを使うためTR1にできない #include <boost/utility.hpp> #include <boost/mpl/identity.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/asio.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #endif /*STDAFX_H_*/
[ "[email protected]", "yusuke.ichinohe@05ab3c7c-673e-0410-85c5-735cf5110427" ]
[ [ [ 1, 2 ], [ 4, 4 ], [ 8, 9 ], [ 21, 21 ], [ 26, 26 ], [ 36, 41 ], [ 43, 47 ], [ 49, 50 ], [ 53, 55 ], [ 57, 59 ] ], [ [ 3, 3 ], [ 5, 7 ], [ 10, 20 ], [ 22, 25 ], [ 27, 35 ], [ 42, 42 ], [ 48, 48 ], [ 51, 52 ], [ 56, 56 ] ] ]
0487802d7d93dff6a236051e80b9045b653df39d
d397b0d420dffcf45713596f5e3db269b0652dee
/src/Axe/Proxy.hpp
e4aa7f3abd740f5361e46e619d8023483177b42b
[]
no_license
irov/Axe
62cf29def34ee529b79e6dbcf9b2f9bf3709ac4f
d3de329512a4251470cbc11264ed3868d9261d22
refs/heads/master
2021-01-22T20:35:54.710866
2010-09-15T14:36:43
2010-09-15T14:36:43
85,337,070
0
0
null
null
null
null
UTF-8
C++
false
false
1,978
hpp
# pragma once # include <Axe/Connection.hpp> # include <Axe/Response.hpp> namespace Axe { typedef AxeHandle<class ProxyConnectionProvider> ProxyConnectionProviderPtr; typedef AxeHandle<class Response> ResponsePtr; class ArchiveDispatcher; class ArchiveInvocation; class Response_Servant_destroy : public Response { public: virtual void response() = 0; public: void responseCall( Axe::ArchiveDispatcher & _ar, std::size_t _size ) override; }; typedef AxeHandle<class Response_Servant_destroy> Response_Servant_destroyPtr; class Proxy : virtual public AxeUtil::Shared { public: Proxy( std::size_t _servantId, const ProxyConnectionProviderPtr & _adaterProvider ); public: std::size_t getServantId() const; const ProxyConnectionProviderPtr & getConnectionProvider() const; public: ArchiveInvocation & beginMessage( std::size_t _methodId, const ResponsePtr & _response ); void processMessage(); public: void destroy_async( const Response_Servant_destroyPtr & _response ); public: void write( ArchiveInvocation & _ar ) const; protected: std::size_t m_servantId; ProxyConnectionProviderPtr m_connectionProvider; }; typedef AxeHandle<Proxy> ProxyPtr; template<class T> inline T uncheckedCast( const ProxyPtr & _proxy ) { std::size_t servantId = _proxy->getServantId(); const ProxyConnectionProviderPtr & provider = _proxy->getConnectionProvider(); typedef typename T::element_type element_type; return new element_type( servantId, provider ); } const ProxyConnectionProviderPtr & makeProxyConnectionProvider( ArchiveDispatcher & ar, std::size_t & servantId ); template<class T> T makeProxy( ArchiveDispatcher & _ar ) { std::size_t servantId; const ProxyConnectionProviderPtr & provider = makeProxyConnectionProvider( _ar, servantId ); typedef typename T::element_type El; return new El( servantId, provider ); } }
[ "yuriy_levchenko@b35ac3e7-fb55-4080-a4c2-184bb04a16e0" ]
[ [ [ 1, 78 ] ] ]
39edd47d23df93a574fcb3951ffbc529abe8b892
af260b99d9f045ac4202745a3c7a65ac74a5e53c
/trunk/gui/EngineWrapper/AssemblyInfo.cpp
617cb2cd02c6390466e561e9fc64b557a68972de
[]
no_license
BackupTheBerlios/snap-svn
560813feabcf5d01f25bc960d474f7e218373da0
a99b5c64384cc229e8628b22f3cf6a63a70ed46f
refs/heads/master
2021-01-22T09:43:37.862180
2008-02-17T15:50:06
2008-02-17T15:50:06
40,819,397
0
0
null
null
null
null
UTF-8
C++
false
false
1,324
cpp
#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitleAttribute("Miew")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("")]; [assembly:AssemblyProductAttribute("Miew")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) 2006")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly:AssemblyVersionAttribute("1.0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
[ "aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478" ]
[ [ [ 1, 40 ] ] ]
25d23aff7e903f4d54ba61c868a1fa09b38765a5
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/websrv/web_service_messaging_api/src/newsoapclassescases.cpp
b53238b34b8fcd8428d8adb2ba3466ee1a6f798c
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
136,256
cpp
/* * Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: ?Description * */ // INCLUDE FILES #include <StifTestModule.h> #include <e32math.h> #include <libc\assert.h> #include <e32panic.h> #include "NewSoapClassesBCtest.h" #include "TestMSenMessage.h" // ============================ MEMBER FUNCTIONS =============================== // ----------------------------------------------------------------------------- // CNewSoapClassesBCTest::Case // Returns a test case by number. // // This function contains an array of all available test cases // i.e pair of case name and test function. If case specified by parameter // aCaseNumber is found from array, then that item is returned. // // The reason for this rather complicated function is to specify all the // test cases only in one place. It is not necessary to understand how // function pointers to class member functions works when adding new test // cases. See function body for instructions how to add new test case. // ----------------------------------------------------------------------------- // const TCaseInfo CNewSoapClassesBCTest::Case ( const TInt aCaseNumber ) const { /** * To add new test cases, implement new test case function and add new * line to KCases array specify the name of the case and the function * doing the test case * In practice, do following * 1) Make copy of existing test case function and change its name * and functionality. Note that the function must be added to * NewSoapClasses.cpp file and to NewSoapClasses.h * header file. * * 2) Add entry to following KCases array either by using: * * 2.1: FUNCENTRY or ENTRY macro * ENTRY macro takes two parameters: test case name and test case * function name. * * FUNCENTRY macro takes only test case function name as a parameter and * uses that as a test case name and test case function name. * * Or * * 2.2: OOM_FUNCENTRY or OOM_ENTRY macro. Note that these macros are used * only with OOM (Out-Of-Memory) testing! * * OOM_ENTRY macro takes five parameters: test case name, test case * function name, TBool which specifies is method supposed to be run using * OOM conditions, TInt value for first heap memory allocation failure and * TInt value for last heap memory allocation failure. * * OOM_FUNCENTRY macro takes test case function name as a parameter and uses * that as a test case name, TBool which specifies is method supposed to be * run using OOM conditions, TInt value for first heap memory allocation * failure and TInt value for last heap memory allocation failure. */ static TCaseInfoInternal const KCases[] = { ENTRY( "NewL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewLL ), ENTRY( "NewLC - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewLCL ), ENTRY( "NewL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewL_1L ), ENTRY( "NewLC - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewLC_1L ), ENTRY( "NewL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewL_2L ), ENTRY( "NewLC - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewLC_2L ), ENTRY( "Type - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_TypeL ), ENTRY( "Direction - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_DirectionL ), ENTRY( "TxnId - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_TxnIdL ), ENTRY( "Clone - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_CloneL ), ENTRY( "SoapVersion - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SoapVersionL ), ENTRY( "SetContext - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetContextL ), ENTRY( "Context - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_ContextL ), ENTRY( "SetProperties - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetPropertiesL ), ENTRY( "SetBodyL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetBodyLL ), ENTRY( "Properties - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_PropertiesL ), ENTRY( "IsSafeToCast - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_IsSafeToCastL ), ENTRY( "SetBodyL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetBodyL_1L ), ENTRY( "BodyL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_BodyLL ), ENTRY( "HeaderL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_HeaderLL ), ENTRY( "AddHeaderL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_AddHeaderLL ), ENTRY( "BodyAsStringL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_BodyAsStringLL ), ENTRY( "IsFault - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_IsFaultL ), ENTRY( "DetachFaultL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_DetachFaultLL ), ENTRY( "FaultL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_FaultLL ), ENTRY( "SetSoapActionL - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetSoapActionLL ), ENTRY( "SoapAction - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SoapActionL ), ENTRY( "HasHeader - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_HasHeaderL ), ENTRY( "HasBody - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_HasBodyL ), ENTRY( "Parse1 - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_Parse1L ), ENTRY( "Parse2 - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_Parse2L ), ENTRY( "Parse2 - CSenSoapEnvelope2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_Parse3L ), ENTRY( "NewL - CSenSoapFault2", CNewSoapClassesBCTest::MT_CSenSoapFault2_NewLL ), ENTRY( "NewL - CSenSoapFault2", CNewSoapClassesBCTest::MT_CSenSoapFault2_NewL_1L ), ENTRY( "NewL - CSenSoapFault2", CNewSoapClassesBCTest::MT_CSenSoapFault2_NewL_2L ), ENTRY( "FaultCode - CSenSoapFault2", CNewSoapClassesBCTest::MT_CSenSoapFault2_FaultCodeL ), ENTRY( "FaultSubcode - CSenSoapFault2", CNewSoapClassesBCTest::MT_CSenSoapFault2_FaultSubcodeL ), ENTRY( "FaultString - CSenSoapFault2", CNewSoapClassesBCTest::MT_CSenSoapFault2_FaultStringL ), ENTRY( "FaultActor - CSenSoapFault2", CNewSoapClassesBCTest::MT_CSenSoapFault2_FaultActorL ), ENTRY( "Detail - CSenSoapFault2", CNewSoapClassesBCTest::MT_CSenSoapFault2_DetailL ), ENTRY( "NewL - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLL ), ENTRY( "NewLC - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLCL ), ENTRY( "NewL - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_1L ), ENTRY( "NewLC - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_1L ), ENTRY( "NewL - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_2L ), ENTRY( "NewLC - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_2L ), ENTRY( "NewL - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_3L ), ENTRY( "NewLC - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_3L ), ENTRY( "NewL - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_4L ), ENTRY( "NewLC - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_4L ), ENTRY( "NewL - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_5L ), ENTRY( "NewLC - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_5L ), ENTRY( "NewL - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_6L ), ENTRY( "NewLC - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_6L ), ENTRY( "NewL - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewLL ), ENTRY( "Type - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_TypeL ), ENTRY( "Clone - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_CloneL ), ENTRY( "Parse - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_Parse1L ), ENTRY( "SetSecurityHeaderL - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_SetSecurityHeaderLL ), ENTRY( "AddSecurityTokenL - CSenSoapMessage2", CNewSoapClassesBCTest::MT_CSenSoapMessage2_AddSecurityTokenLL ), ENTRY( "NewL - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewLL ), ENTRY( "NewLC - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewLCL ), ENTRY( "NewL - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewL_1L ), ENTRY( "NewLC - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewLC_1L ), ENTRY( "NewL - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewL_2L ), ENTRY( "NewLC - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewLC_2L ), ENTRY( "UsernameTokenL - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_UsernameTokenLL ), ENTRY( "UsernameTokenL - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_UsernameTokenL_1L ), ENTRY( "UsernameTokenL - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_UsernameTokenL_2L ), ENTRY( "UsernameTokenL - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_UsernameTokenL_3L ), ENTRY( "UsernameTokenL - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_UsernameTokenL_4L ), ENTRY( "TimestampL - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_TimestampLL ), ENTRY( "TimestampL - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_TimestampL_1L ), ENTRY( "XmlNs - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_XmlNsL ), ENTRY( "XmlNsPrefix - CSenWsSecurityHeader2", CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_XmlNsPrefixL ), ENTRY( "Type - MSenMessage", CNewSoapClassesBCTest::MT_CTestMSenMessage_Type), ENTRY( "Direction - MSenMessage", CNewSoapClassesBCTest::MT_CTestMSenMessage_Direction), ENTRY( "Context - MSenMessage", CNewSoapClassesBCTest::MT_CTestMSenMessage_Context), ENTRY( "SetContext - MSenMessage", CNewSoapClassesBCTest::MT_CTestMSenMessage_SetContext), ENTRY( "Properties - MSenMessage", CNewSoapClassesBCTest::MT_CTestMSenMessage_Properties), ENTRY( "SetProperties - MSenMessage", CNewSoapClassesBCTest::MT_CTestMSenMessage_SetProperties), ENTRY( "IsSafeToCast - MSenMessage", CNewSoapClassesBCTest:: MT_CTestMSenMessage_IsSafeToCast), ENTRY( "TxnId - MSenMessage", CNewSoapClassesBCTest::MT_CTestMSenMessage_TxnId), ENTRY( "CloneL - MSenMessage", CNewSoapClassesBCTest::MT_CTestMSenMessage_CloneL), // Example how to use OOM functionality //OOM_ENTRY( "Loop test with OOM", CNewSoapClassesBCTest::LoopTest, ETrue, 2, 3), //OOM_FUNCENTRY( CNewSoapClassesBCTest::PrintTest, ETrue, 1, 3 ), }; // Verify that case number is valid if( (TUint) aCaseNumber >= sizeof( KCases ) / sizeof( TCaseInfoInternal ) ) { // Invalid case, construct empty object TCaseInfo null( (const TText*) L"" ); null.iMethod = NULL; null.iIsOOMTest = EFalse; null.iFirstMemoryAllocation = 0; null.iLastMemoryAllocation = 0; return null; } // Construct TCaseInfo object and return it TCaseInfo tmp ( KCases[ aCaseNumber ].iCaseName ); tmp.iMethod = KCases[ aCaseNumber ].iMethod; tmp.iIsOOMTest = KCases[ aCaseNumber ].iIsOOMTest; tmp.iFirstMemoryAllocation = KCases[ aCaseNumber ].iFirstMemoryAllocation; tmp.iLastMemoryAllocation = KCases[ aCaseNumber ].iLastMemoryAllocation; return tmp; } void CNewSoapClassesBCTest::SetupL( ){ } void CNewSoapClassesBCTest::Teardown( ){ } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewLL( TTestResult& aResult ) { SetupL(); _LIT8(KEnvelopeString, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewLCL( TTestResult& aResult ) { SetupL(); _LIT8(KEnvelopeString, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewLC(); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pEnvelope); //CleanupStack::PopAndDestroy(); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewL_1L( TTestResult& aResult ) { SetupL(); _LIT8(KEnvelopeString, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); MSenMessageContext* mContext = NULL; CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(*mContext); CleanupStack::PushL(pEnvelope); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewLC_1L( TTestResult& aResult ) { SetupL(); _LIT8(KEnvelopeString, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); MSenMessageContext* mContext = NULL; CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewLC(*mContext); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pEnvelope); //CleanupStack::PopAndDestroy(); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewL_2L( TTestResult& aResult ) { SetupL(); _LIT8(KEnvelopeString, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapEnvelope2* pEnvelope, *pEnvelope1 = CSenSoapEnvelope2::NewL(); pEnvelope = CSenSoapEnvelope2::NewL(*pEnvelope1); CleanupStack::PushL(pEnvelope); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pEnvelope); delete pEnvelope1; pEnvelope1 = NULL; Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_NewLC_2L( TTestResult& aResult ) { SetupL(); _LIT8(KEnvelopeString, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapEnvelope2* pEnvelope, *pEnvelope1 = CSenSoapEnvelope2::NewL(); pEnvelope = CSenSoapEnvelope2::NewLC(*pEnvelope1); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pEnvelope); //CleanupStack::PopAndDestroy(); delete pEnvelope1; pEnvelope1 = NULL; Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_TypeL( TTestResult& aResult ) { SetupL(); MSenMessage::TClass var = MSenMessage::ESoapEnvelope2; _LIT8(KEnvelopeString, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); TL(var == pEnvelope->Type()); CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_DirectionL( TTestResult& aResult ) { SetupL(); MSenMessage::TDirection var = MSenMessage::EOutbound; _LIT8(KEnvelopeString, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); TL(var == pEnvelope->Direction()); CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_TxnIdL( TTestResult& aResult ) { SetupL(); _LIT8(KEnvelopeString, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapEnvelope2* pEnvelope, *pEnvelope1 = CSenSoapEnvelope2::NewL(); pEnvelope = CSenSoapEnvelope2::NewL(*pEnvelope1); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); TInt var = pEnvelope->TxnId(); TBool Flag; if(var >= 0) if(!(Flag)) return KErrArgument; __ASSERT_ALWAYS_NO_LEAVE(delete pEnvelope); pEnvelope = NULL; delete pEnvelope1; pEnvelope1 = NULL; Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_CloneL( TTestResult& aResult ) { SetupL(); TBool Flag; CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); CSenSoapEnvelope2* pClone = NULL; pClone = (CSenSoapEnvelope2*)pEnvelope->CloneL(); if(pClone != NULL) Flag = 1; if(!(Flag)) return KErrArgument; delete pClone; CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SoapVersionL( TTestResult& aResult ) { SetupL(); TSOAPVersion var = ESOAP11; _LIT8(KEnvelopeString, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); TL(var == pEnvelope->SoapVersion()); CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetContextL( TTestResult& aResult ) { SetupL(); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); MSenMessageContext* mContext = NULL; CSenXmlProperties* prop = CSenXmlProperties::NewL(); // CSenMessageContext* mContext1 = CSenMessageContext::NewL(SenContext::EOutgoing, prop); TL(KErrArgument == pEnvelope->SetContext(mContext)); // TL(KErrNone == pEnvelope->SetContext(mContext1)); TL(mContext == pEnvelope->Context()); CleanupStack::PopAndDestroy(pEnvelope); // delete mContext1; Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_ContextL( TTestResult& aResult ) { SetupL(); TTestResult Result; CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetContextL(Result); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetPropertiesL( TTestResult& aResult ) { SetupL(); CSenXmlProperties* prop = CSenXmlProperties::NewL(); CleanupStack::PushL(prop); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::Pop(); CleanupStack::PushL(pEnvelope); TL(KErrNone == pEnvelope->SetProperties(prop)); CleanupStack::PopAndDestroy(); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_PropertiesL( TTestResult& aResult ) { SetupL(); CSenXmlProperties* prop = CSenXmlProperties::NewL(); CleanupStack::PushL(prop); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::Pop(); CleanupStack::PushL(pEnvelope); TL(KErrNone == pEnvelope->SetProperties(prop)); TL(prop == pEnvelope->Properties()); CleanupStack::PopAndDestroy(); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_IsSafeToCastL( TTestResult& aResult ) { SetupL(); MSenMessage::TClass var = MSenMessage::ESoapEnvelope2; TBool retVal = ETrue; CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); retVal == pEnvelope->IsSafeToCast(var); if(retVal == EFalse) return KErrArgument; CleanupStack::PopAndDestroy(); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetBodyLL( TTestResult& aResult ) { SetupL(); _LIT8(KBodyContentString, "<Test>Content</Test>"); _LIT8(KEnvelopeString, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Body><Test>Content</Test></S:Body>\ </S:Envelope>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); pEnvelope->SetBodyL(KBodyContentString); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetBodyL_1L( TTestResult& aResult ) { SetupL(); _LIT8(KBodyElementName, "BodyElement"); _LIT8(KBodyContent, "BodyContent"); _LIT8(KBodyElementName2, "BodyElement2"); _LIT8(KBodyContent2, "BodyContent2"); _LIT8(KEnvelopeString, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Body><BodyElement>BodyContent</BodyElement></S:Body>\ </S:Envelope>"); _LIT8(KEnvelopeString2, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Body><BodyElement2>BodyContent2</BodyElement2></S:Body>\ </S:Envelope>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement bodyElement = document.CreateDocumentElementL(KBodyElementName()); bodyElement.AddTextL(KBodyContent()); pEnvelope->SetBodyL(bodyElement); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString )) KErrArgument; CleanupStack::PopAndDestroy(pAsXml); TXmlEngElement bodyElement2 = document.CreateDocumentElementL(KBodyElementName2()); bodyElement2.AddTextL(KBodyContent2()); pEnvelope->SetBodyL(bodyElement2); pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelopeString2 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(1); // document CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_BodyLL( TTestResult& aResult ) { SetupL(); _LIT8(KBodyContentString, "Test"); _LIT8(KBodyString, "<S:Body>Test</S:Body>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); pEnvelope->SetBodyL(KBodyContentString); TXmlEngElement element = pEnvelope->BodyL(); RSenDocument document = pEnvelope->AsDocumentL(); TXmlEngSerializationOptions options; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> options.iOptions = options.iOptions | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, element, options); // Serialized body should contain only body as XML. if(!( asXml == KBodyString )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_HeaderLL( TTestResult& aResult ) { SetupL(); _LIT8(KHeaderString, "<S:Header/>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); TXmlEngElement element = pEnvelope->HeaderL(); RSenDocument document = pEnvelope->AsDocumentL(); TXmlEngSerializationOptions options; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> options.iOptions = options.iOptions | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, element, options); // Serialized header should contain only header as XML. if(!( asXml == KHeaderString )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_AddHeaderLL( TTestResult& aResult ) { SetupL(); _LIT8(KHeaderElementName, "HeaderElement"); _LIT8(KHeaderContent, "HeaderContent"); _LIT8(KHeaderElementName2, "HeaderElement2"); _LIT8(KHeaderContent2, "HeaderContent2"); _LIT8(KEnvelope, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header>\ <HeaderElement>HeaderContent</HeaderElement>\ </S:Header>\ <S:Body/></S:Envelope>"); _LIT8(KEnvelope2, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header>\ <HeaderElement>HeaderContent</HeaderElement>\ <HeaderElement2>HeaderContent2</HeaderElement2>\ </S:Header>\ <S:Body/></S:Envelope>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement headerElement = document.CreateDocumentElementL(KHeaderElementName()); headerElement.AddTextL(KHeaderContent()); pEnvelope->AddHeaderL(headerElement); HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelope )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); TXmlEngElement headerElement2 = document.CreateDocumentElementL(KHeaderElementName2()); headerElement2.AddTextL(KHeaderContent2()); pEnvelope->AddHeaderL(headerElement2); pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KEnvelope2 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(1); // document CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_BodyAsStringLL( TTestResult& aResult ) { SetupL(); _LIT8(KBodyElementName, "BodyElement"); _LIT8(KBodyElementContent, "BodyElementContent"); _LIT8(KBodyContent, "BodyContent"); _LIT8(KBodyAsString1, "<S:Body xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">BodyContent</S:Body>"); _LIT8(KBodyAsString2, "<S:Body xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <BodyElement>BodyElementContent</BodyElement>\ </S:Body>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement bodyElement = document.CreateDocumentElementL(KBodyElementName()); bodyElement.AddTextL(KBodyElementContent()); pEnvelope->SetBodyL(KBodyContent); // If Body element does not contain any elements // whole Body element is returned (and detached // => needed namespace declarations are moved into // Body) HBufC8* pAsXml = pEnvelope->BodyAsStringL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KBodyAsString1 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); pEnvelope->SetBodyL(bodyElement); // If Body element contains element(s) // only first element (and all its child elements) // from Body element is returned and detached // (not Body element). pAsXml = pEnvelope->BodyAsStringL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KBodyAsString2 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(1); // document CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_IsFaultL( TTestResult& aResult ) { SetupL(); _LIT8(KFaultElementName, "Fault"); _LIT8(KFaultContent, "FaultContent"); _LIT8(KFaultInputString, "<SOAP:Envelope \ xmlns:SOAP=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <SOAP:Header>\ <HeaderElement>HeaderContent</HeaderElement>\ </SOAP:Header>\ <SOAP:Body><SOAP:Fault>FaultContent</SOAP:Fault></SOAP:Body>\ </SOAP:Envelope>"); // 1. Test that IsFault return EFalse by default CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); //if(!( pEnvelope->IsFault() == EFalse )) return KErrArgument; TL( pEnvelope->IsFault() == EFalse ) // 2. Test that IsFault returns ETrue when fault is added // using SetBodyL method RSenDocument document = RSenDocument::NewLC(); TXmlEngElement faultElement = document.CreateDocumentElementL(KFaultElementName(), pEnvelope->NsUri()); faultElement.AddTextL(KFaultContent()); pEnvelope->SetBodyL(faultElement); if(!( pEnvelope->IsFault())) return KErrArgument; CleanupStack::PopAndDestroy(1); // document CleanupStack::PopAndDestroy(pEnvelope); // 3. Test that IsFault returns ETrue if fault is added // when Envelope is parsed CSenParser* pParser = CSenParser::NewLC(); pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); pParser->ParseL(KFaultInputString, *pEnvelope); if(!( pEnvelope->IsFault())) return KErrArgument; CleanupStack::PopAndDestroy(pEnvelope); CleanupStack::PopAndDestroy(pParser); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_DetachFaultLL( TTestResult& aResult ) { SetupL(); _LIT8(KFaultElementName, "Fault"); _LIT8(KFaultContent, "FaultContent"); _LIT8(KFaultElement, "<S:Fault xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">FaultContent</S:Fault>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); TXmlEngElement body = pEnvelope->BodyL(); TXmlEngElement faultElement = body.AddNewElementWithNsL(KFaultElementName(), pEnvelope->NsUri()); faultElement.AddTextL(KFaultContent()); CSenSoapFault2* pFault = pEnvelope->DetachFaultL(); CleanupStack::PushL(pFault); HBufC8* pAsXml = pFault->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KFaultElement )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pFault); CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_FaultLL( TTestResult& aResult ) { SetupL(); _LIT8(KFaultElementName, "Fault"); _LIT8(KFaultContent, "FaultContent"); _LIT8(KFaultElement, "<S:Fault>FaultContent</S:Fault>"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); TXmlEngElement body = pEnvelope->BodyL(); TXmlEngElement faultElement = body.AddNewElementWithNsL(KFaultElementName(), pEnvelope->NsUri()); faultElement.AddTextL(KFaultContent()); CSenSoapFault2* pFault = pEnvelope->FaultL(); CleanupStack::PushL(pFault); HBufC8* pAsXml = pFault->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KFaultElement )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pFault); CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SetSoapActionLL( TTestResult& aResult ) { SetupL(); _LIT8(KSoapActionValue, "SoapActionValue"); _LIT8(KSoapActionValueInQuotes, "\"SoapActionValue\""); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); TPtrC8 retVal = pEnvelope->SetSoapActionL(KSoapActionValue); if(!( retVal == KSoapActionValueInQuotes )) return KErrArgument; TPtrC8 soapAction = pEnvelope->SoapAction(); if(!( soapAction == KSoapActionValueInQuotes )) return KErrArgument; TPtrC8 retVal2 = pEnvelope->SetSoapActionL(KSoapActionValueInQuotes); if(!( retVal2 == KSoapActionValueInQuotes )) return KErrArgument; TPtrC8 soapAction2 = pEnvelope->SoapAction(); if(!( soapAction2 == KSoapActionValueInQuotes )) return KErrArgument; CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_SoapActionL( TTestResult& aResult ) { SetupL(); _LIT8(KSoapActionValue, "SoapActionValue"); _LIT8(KSoapActionValueInQuotes, "\"SoapActionValue\""); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); TPtrC8 retVal = pEnvelope->SetSoapActionL(KSoapActionValue); if(!( retVal == KSoapActionValueInQuotes )) return KErrArgument; TPtrC8 soapAction = pEnvelope->SoapAction(); if(!( soapAction == KSoapActionValueInQuotes )) return KErrArgument; TPtrC8 retVal2 = pEnvelope->SetSoapActionL(KSoapActionValueInQuotes) ; if(!( retVal2 == KSoapActionValueInQuotes )) return KErrArgument; TPtrC8 soapAction2 = pEnvelope->SoapAction(); if(!( soapAction2 == KSoapActionValueInQuotes )) return KErrArgument; CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_HasHeaderL( TTestResult& aResult ) { SetupL(); _LIT8(KHeaderElementName, "HeaderElement"); _LIT8(KHeaderContent, "HeaderContent"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); if(!( pEnvelope->HasHeader() == EFalse )) return KErrArgument; RSenDocument document = RSenDocument::NewLC(); TXmlEngElement headerElement = document.CreateDocumentElementL(KHeaderElementName()); headerElement.AddTextL(KHeaderContent()); pEnvelope->AddHeaderL(headerElement); if(!( pEnvelope->HasHeader())) return KErrArgument; CleanupStack::PopAndDestroy(1); // document CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_HasBodyL( TTestResult& aResult ) { SetupL(); _LIT8(KBodyElementName, "BodyElement"); _LIT8(KBodyElementContent, "BodyElementContent"); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); if(!( pEnvelope->HasBody() == EFalse )) return KErrArgument; RSenDocument document = RSenDocument::NewLC(); TXmlEngElement bodyElement = document.CreateDocumentElementL(KBodyElementName()); bodyElement.AddTextL(KBodyElementContent()); pEnvelope->SetBodyL(bodyElement); if(!( pEnvelope->HasBody())) return KErrArgument; CleanupStack::PopAndDestroy(1); // document CleanupStack::PopAndDestroy(pEnvelope); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_Parse1L( TTestResult& aResult ) { SetupL(); _LIT8(KInputString, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header>\ <sb:Correlation xmlns:sb=\"urn:liberty:sb:2003-08\" \ messageID=\"URN:UUID:860949DC-134D-A989-E328-2FD7F20E31CE\" timestamp=\"2006-06-01T14:53:19Z\"/>\ <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/>\ </S:Header>\ <S:Body>\ <sa:SASLRequest xmlns:sa=\"urn:liberty:sa:2004-04\" mechanism=\"ANONYMOUS PLAIN CRAM-MD5\" authzID=\"testuser1\"/>\ </S:Body>\ </S:Envelope>"); _LIT8(KBodyAsString, "\ <S:Body xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:sa=\"urn:liberty:sa:2004-04\">\ <sa:SASLRequest xmlns:sa=\"urn:liberty:sa:2004-04\" mechanism=\"ANONYMOUS PLAIN CRAM-MD5\" authzID=\"testuser1\"/>\ </S:Body>"); // TODO: there seems to be a bug in libxml2: ReconcileNamespacesL() copies extra // namespace declaration into Body tag: // xmlns:sa="urn:liberty:sa:2004-04" _LIT8(KEmptyBodyAsString, "<S:Body/>"); _LIT8(KEmptyBodyWithNsAsString, "<S:Body xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenParser* pParser = CSenParser::NewLC(); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); pParser->ParseL(KInputString, *pEnvelope); // 1) Check that parsed SoapEnvelope can be // serialized correctly HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KInputString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); // 2) Check that body can be detached from SoapEnvelope // correctly. // Note: Following "BodyAsStringL()" call will detach // Body from SoapEnvelope HBufC8* pBodyAsString = pEnvelope->BodyAsStringL(); CleanupStack::PushL(pBodyAsString); if(!( *pBodyAsString == KBodyAsString )) return KErrArgument; CleanupStack::PopAndDestroy(pBodyAsString); // 3) Check that body can be detached from SoapEnvelope // twice // In this case body does not have child elements. // => Empty body should be returned. // Note: Empty body should contain namespace // declaration because body is detached pBodyAsString = pEnvelope->BodyAsStringL(); CleanupStack::PushL(pBodyAsString); if(!( *pBodyAsString == KEmptyBodyWithNsAsString )) return KErrArgument; CleanupStack::PopAndDestroy(pBodyAsString); // 4) Check that body was detached from SoapEnvelope // correctly // => Getting body again should result empty body to be returned. TXmlEngElement bodyElement = pEnvelope->BodyL(); RSenDocument document = pEnvelope->AsDocumentL(); TUint optionFlags = 0; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> optionFlags = optionFlags | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; // Allow encoding declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionEncoding; // Allow standalone declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionStandalone; TXmlEngSerializationOptions options(optionFlags); RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, bodyElement, options); // Serielized body should be empty because "BodyAsStringL()" // previously detached body. if(!( asXml == KEmptyBodyAsString )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); CleanupStack::PopAndDestroy(pEnvelope); CleanupStack::PopAndDestroy(pParser); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_Parse2L( TTestResult& aResult ) { SetupL(); _LIT8(KInputString, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header>\ <sb:Correlation xmlns:sb=\"urn:liberty:sb:2003-08\" \ messageID=\"URN:UUID:860949DC-134D-A989-E328-2FD7F20E31CE\" timestamp=\"2006-06-01T14:53:19Z\"/>\ <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/>\ </S:Header>\ <S:Body>\ <sa:SASLRequest xmlns:sa=\"urn:liberty:sa:2004-04\" mechanism=\"ANONYMOUS PLAIN CRAM-MD5\" authzID=\"testuser1\"/>\ </S:Body>\ </S:Envelope>"); _LIT8(KWholeBodyAsString, "<S:Body>\ <sa:SASLRequest xmlns:sa=\"urn:liberty:sa:2004-04\" mechanism=\"ANONYMOUS PLAIN CRAM-MD5\" authzID=\"testuser1\"/>\ </S:Body>"); _LIT8(KWholeHeaderAsString, "<S:Header>\ <sb:Correlation xmlns:sb=\"urn:liberty:sb:2003-08\" \ messageID=\"URN:UUID:860949DC-134D-A989-E328-2FD7F20E31CE\" timestamp=\"2006-06-01T14:53:19Z\"/>\ <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/>\ </S:Header>"); CSenParser* pParser = CSenParser::NewLC(); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); pParser->ParseL(KInputString, *pEnvelope); // 1) Check that parsed SoapEnvelope can be // serialized correctly HBufC8* pAsXml = pEnvelope->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KInputString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); // 2) Check that body can be got from SoapEnvelope // correctly // Note: Body won't be detached. Only reference for // body TXmlEngElement inside SoapEnvelope is returned. TXmlEngElement bodyElement = pEnvelope->BodyL(); RSenDocument document = pEnvelope->AsDocumentL(); TUint optionFlags = 0; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> optionFlags = optionFlags | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; // Allow encoding declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionEncoding; // Allow standalone declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionStandalone; TXmlEngSerializationOptions options(optionFlags); RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, bodyElement, options); // Serielized body should be in exactly the same form // as in original SoapEnvelope if(!( asXml == KWholeBodyAsString )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); // 3) Check that header TXmlEngElement can be got from SoapEnvelope // correctly TXmlEngElement headerElement = pEnvelope->HeaderL(); RBuf8 headerAsXml; CleanupClosePushL(headerAsXml); document.SaveL(headerAsXml, headerElement, options); // Serielized header should be in exactly the same form // as in original SoapEnvelope if(!( headerAsXml == KWholeHeaderAsString )) return KErrArgument; CleanupStack::PopAndDestroy(&headerAsXml); CleanupStack::PopAndDestroy(pEnvelope); CleanupStack::PopAndDestroy(pParser); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapEnvelope2_Parse3L( TTestResult& aResult ) { SetupL(); _LIT8(KInputString, "<S:Envelope \ xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\" \ xmlns:wsa=\"http://schemas.xmlsoap.org/ws/2004/08/addressing\">\ <S:Header>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/>\ <wsa:MessageID>urn:uuid:7837d733-b9f8-3eb1-5c3f-7a509797e6b2</wsa:MessageID>\ <wsa:To>http://schemas.live.com/mws/2005/08/spaces</wsa:To>\ <wsa:Action>http://schemas.live.com/mws/2005/08/spaces/Post</wsa:Action>\ <wsa:ReplyTo><wsa:Address>id:7bbd5c5b-7857-44c4-b609-53498d0cab3b</wsa:Address></wsa:ReplyTo>\ </S:Header>\ <S:Body>\ <PostRequest xmlns=\"http://schemas.live.com/mws/2005/08/spaces\">\ <Item><Filename>sample1.wav</Filename><ItemType>8</ItemType><Image><Data></Data></Image></Item>\ </PostRequest>\ </S:Body>\ </S:Envelope>"); _LIT8(KOuterXml, "<S:Body>\ <PostRequest xmlns=\"http://schemas.live.com/mws/2005/08/spaces\">\ <Item><Filename>sample1.wav</Filename><ItemType>8</ItemType><Image><Data/></Image></Item>\ </PostRequest>\ </S:Body>"); CSenParser* pParser = CSenParser::NewL(); CleanupStack::PushL(pParser); CSenSoapEnvelope2* pEnvelope = CSenSoapEnvelope2::NewL(); CleanupStack::PushL(pEnvelope); pParser->ParseL(KInputString, *pEnvelope); TXmlEngElement element = pEnvelope->BodyL(); RBuf8 outerXml; CleanupClosePushL(outerXml); element.OuterXmlL(outerXml); if(!( outerXml == KOuterXml )) return KErrArgument; CleanupStack::PopAndDestroy(&outerXml); CleanupStack::PopAndDestroy(pEnvelope); CleanupStack::PopAndDestroy(pParser); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapFault2_NewLL( TTestResult& aResult ) { SetupL(); _LIT8(KFaultElementName, "Fault"); _LIT8(KFaultElementContent, "FaultContent"); _LIT8(KFaultElement, "<Fault>FaultContent</Fault>"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement faultElement = document.CreateDocumentElementL(KFaultElementName()); faultElement.AddTextL(KFaultElementContent()); CSenSoapFault2* pSoapFault = CSenSoapFault2::NewL(faultElement); CleanupStack::PopAndDestroy(1); // document CleanupStack::PushL(pSoapFault); HBufC8* pAsXml = pSoapFault->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KFaultElement )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapFault); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapFault2_NewL_1L( TTestResult& aResult ) { SetupL(); _LIT8(KFaultElementName, "Fault"); _LIT8(KFaultElementContent, "FaultContent"); _LIT8(KFaultElement, "<Fault>FaultContent</Fault>"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement faultElement = document.CreateDocumentElementL(KFaultElementName()); faultElement.AddTextL(KFaultElementContent()); CSenSoapFault2* pSoapFault = CSenSoapFault2::NewL(faultElement, document); CleanupStack::PopAndDestroy(1); // document CleanupStack::PushL(pSoapFault); HBufC8* pAsXml = pSoapFault->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KFaultElement )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapFault); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapFault2_NewL_2L( TTestResult& aResult ) { SetupL(); _LIT8(KParentName, "Parent"); _LIT8(KAttributeNsUri, "nsuri"); _LIT8(KAttributeNsPrefix, "pr"); _LIT8(KAttributeLocalName, "AttrName"); _LIT8(KAttributeValue, "Value"); _LIT8(KFaultNsUri, "http://schemas.xmlsoap.org/soap/envelope/"); _LIT8(KFaultNsPrefix, "S"); _LIT8(KFaultLocalName, "Fault"); _LIT8(KFaultElement, "<S:Fault \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\" \ xmlns:pr=\"nsuri\" pr:AttrName=\"Value\"/>"); _LIT8(KParentDocument, "<Parent><S:Fault \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\" \ xmlns:pr=\"nsuri\" pr:AttrName=\"Value\"/>\ </Parent>"); RSenDocument document = RSenDocument::NewL(); CleanupClosePushL(document); TXmlEngElement parentElement = document.CreateDocumentElementL(KParentName()); RStringPool stringPool; stringPool.OpenL(); CleanupClosePushL(stringPool); RString nsUriRString = stringPool.OpenStringL(KAttributeNsUri); CleanupClosePushL(nsUriRString); RString nsPrefixRString = stringPool.OpenStringL(KAttributeNsPrefix); CleanupClosePushL(nsPrefixRString); RString localNameRString = stringPool.OpenStringL(KAttributeLocalName); CleanupClosePushL(localNameRString); RString valueRString = stringPool.OpenStringL(KAttributeValue); CleanupClosePushL(valueRString); RAttribute attribute; attribute.Open(nsUriRString, nsPrefixRString, localNameRString, valueRString); // attribute took ownership of all RStrings // => All RStrings can be pop from CleanupStack CleanupStack::Pop(&valueRString); CleanupStack::Pop(&localNameRString); CleanupStack::Pop(&nsPrefixRString); CleanupStack::Pop(&nsUriRString); CleanupClosePushL(attribute); RAttributeArray attrArray; // append the namespace attribute (declaration) attrArray.AppendL(attribute); CleanupClosePushL(attrArray); CSenSoapFault2* pSoapFault = CSenSoapFault2::NewL(KFaultNsUri, KFaultLocalName, KFaultNsPrefix, attrArray, parentElement, document); CleanupStack::PushL(pSoapFault); HBufC8* pAsXml = pSoapFault->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KFaultElement )) return KErrArgument; RBuf8 buffer; CleanupClosePushL(buffer); parentElement.OuterXmlL(buffer); if(!( buffer == KParentDocument )) return KErrArgument; CleanupStack::PopAndDestroy(&buffer); CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapFault); CleanupStack::PopAndDestroy(&attrArray); CleanupStack::PopAndDestroy(&attribute); CleanupStack::PopAndDestroy(&stringPool); CleanupStack::PopAndDestroy(&document); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapFault2_FaultCodeL( TTestResult& aResult ) { SetupL(); _LIT8(KSenSoapEnvelopeXmlns, "http://schemas.xmlsoap.org/soap/envelope/"); _LIT8(KSenSoap12EnvelopeXmlns, "http://www.w3.org/2003/05/soap-envelope"); _LIT8(KFaultElementLocalname, "Fault"); _LIT8(KFaultNsPrefix, "S"); _LIT8(KFaultCodeLocalname, "faultcode"); _LIT8(KFault12CodeLocalname, "Code"); // Soap 1.2 _LIT8(KFault12ValueLocalname, "Value"); // Soap1.2 _LIT8(KFaultCodeValue, "123"); // 1) Fault code in Soap other than 1.2 // Note: In SOAP older than 1.2 fault elements are _NOT_ namespace qualified RSenDocument document = RSenDocument::NewLC(); TXmlEngElement faultElement = document.CreateDocumentElementL(KFaultElementLocalname(), KSenSoapEnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultCodeElement = faultElement.AddNewElementL(KFaultCodeLocalname()); faultCodeElement.AddTextL(KFaultCodeValue()); CSenSoapFault2* pSoapFault = CSenSoapFault2::NewL(faultElement, document); CleanupStack::PushL(pSoapFault); TPtrC8 faultCode = pSoapFault->FaultCode(); if(!( faultCode == KFaultCodeValue )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault); CleanupStack::PopAndDestroy(1); // document // 2) Fault code in Soap 1.2 // Note: SOAP 1.2 faults are structured differently to SOAP 1.1. // In particular all fault elements are now namespace _qualified_, // many have been renamed and fault codes are now hierarchical RSenDocument document2 = RSenDocument::NewLC(); TXmlEngElement faultElement2 = document2.CreateDocumentElementL(KFaultElementLocalname(), KSenSoap12EnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultCodeElement2 = faultElement2.AddNewElementSameNsL(KFault12CodeLocalname()); TXmlEngElement faultValueElement2 = faultCodeElement2.AddNewElementSameNsL(KFault12ValueLocalname()); faultValueElement2.AddTextL(KFaultCodeValue()); CSenSoapFault2* pSoapFault2 = CSenSoapFault2::NewL(faultElement2, document2); CleanupStack::PushL(pSoapFault2); TPtrC8 faultCode2 = pSoapFault2->FaultCode(); if(!( faultCode2 == KFaultCodeValue )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault2); CleanupStack::PopAndDestroy(1); // document2 Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapFault2_FaultSubcodeL( TTestResult& aResult ) { SetupL(); // FaultSubcodeL is supported only in Soap 1.2 // If other version of Soap is used return value will always be KNullDesC _LIT8(KSenSoapEnvelopeXmlns, "http://schemas.xmlsoap.org/soap/envelope/"); _LIT8(KSenSoap12EnvelopeXmlns, "http://www.w3.org/2003/05/soap-envelope"); _LIT8(KFaultElementLocalname, "Fault"); _LIT8(KFaultNsPrefix, "S"); // _LIT8(KFaultCodeLocalname, "faultcode"); _LIT8(KFault12CodeLocalname, "Code"); // Soap 1.2 _LIT8(KFault12SubcodeLocalname, "Subcode"); // Soap 1.2 _LIT8(KFault12ValueLocalname, "Value"); // Soap1.2 _LIT8(KFaultCodeValue, "123"); // 1) Fault subcode in Soap other than 1.2 // Note: In SOAP older than 1.2 there is _NO_ sobcode // => KNullDesC8 should be returned. // Note: In SOAP older than 1.2 fault elements are _NOT_ namespace qualified RSenDocument document = RSenDocument::NewLC(); TXmlEngElement faultElement = document.CreateDocumentElementL(KFaultElementLocalname(), KSenSoapEnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultCodeElement = faultElement.AddNewElementL(KFault12CodeLocalname()); TXmlEngElement faultSubCodeElement = faultCodeElement.AddNewElementSameNsL(KFault12SubcodeLocalname()); TXmlEngElement faultValueElement = faultSubCodeElement.AddNewElementSameNsL(KFault12ValueLocalname()); faultValueElement.AddTextL(KFaultCodeValue()); CSenSoapFault2* pSoapFault = CSenSoapFault2::NewL(faultElement, document); CleanupStack::PushL(pSoapFault); TPtrC8 faultCode = pSoapFault->FaultSubcode(); if(!( faultCode == KNullDesC8 )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault); CleanupStack::PopAndDestroy(1); // document // 2) Fault subcode in Soap 1.2 // Note: SOAP 1.2 faults are structured differently to SOAP 1.1. // In particular all fault elements are now namespace _qualified_, // many have been renamed and fault codes are now hierarchical RSenDocument document2 = RSenDocument::NewLC(); TXmlEngElement faultElement2 = document2.CreateDocumentElementL(KFaultElementLocalname(), KSenSoap12EnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultCodeElement2 = faultElement2.AddNewElementSameNsL(KFault12CodeLocalname()); TXmlEngElement faultSubCodeElement2 = faultCodeElement2.AddNewElementSameNsL(KFault12SubcodeLocalname()); TXmlEngElement faultValueElement2 = faultSubCodeElement2.AddNewElementSameNsL(KFault12ValueLocalname()); faultValueElement2.AddTextL(KFaultCodeValue()); CSenSoapFault2* pSoapFault2 = CSenSoapFault2::NewL(faultElement2, document2); CleanupStack::PushL(pSoapFault2); TPtrC8 faultCode2 = pSoapFault2->FaultSubcode(); if(!( faultCode2 == KFaultCodeValue )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault2); CleanupStack::PopAndDestroy(1); // document2 Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapFault2_FaultStringL( TTestResult& aResult ) { SetupL(); _LIT8(KSenSoapEnvelopeXmlns, "http://schemas.xmlsoap.org/soap/envelope/"); _LIT8(KSenSoap12EnvelopeXmlns, "http://www.w3.org/2003/05/soap-envelope"); _LIT8(KFaultElementLocalname, "Fault"); _LIT8(KFaultNsPrefix, "S"); _LIT8(KFaultStringLocalname, "faultstring"); _LIT8(KFault12ReasonLocalname, "Reason"); // Soap1.2 _LIT8(KFault12TextLocalname, "Text"); // Soap1.2 _LIT8(KFaultStringValue, "Fault code string"); // 1) Fault code in Soap other than 1.2 // Note: In SOAP older than 1.2 fault elements are _NOT_ namespace qualified RSenDocument document = RSenDocument::NewLC(); TXmlEngElement faultElement = document.CreateDocumentElementL(KFaultElementLocalname(), KSenSoapEnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultStringElement = faultElement.AddNewElementL(KFaultStringLocalname()); faultStringElement.AddTextL(KFaultStringValue()); CSenSoapFault2* pSoapFault = CSenSoapFault2::NewL(faultElement, document); CleanupStack::PushL(pSoapFault); TPtrC8 faultCode = pSoapFault->FaultString(); if(!( faultCode == KFaultStringValue )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault); CleanupStack::PopAndDestroy(1); // document // 2) Fault code in Soap 1.2 // Note: SOAP 1.2 faults are structured differently to SOAP 1.1. // In particular all fault elements are now namespace _qualified_, // many have been renamed and fault codes are now hierarchical RSenDocument document2 = RSenDocument::NewLC(); TXmlEngElement faultElement2 = document2.CreateDocumentElementL(KFaultElementLocalname(), KSenSoap12EnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultReasonElement2 = faultElement2.AddNewElementSameNsL(KFault12ReasonLocalname()); TXmlEngElement faultTextElement2 = faultReasonElement2.AddNewElementSameNsL(KFault12TextLocalname()); faultTextElement2.AddTextL(KFaultStringValue()); CSenSoapFault2* pSoapFault2 = CSenSoapFault2::NewL(faultElement2, document2); CleanupStack::PushL(pSoapFault2); TPtrC8 faultCode2 = pSoapFault2->FaultString(); if(!( faultCode2 == KFaultStringValue )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault2); CleanupStack::PopAndDestroy(1); // document2 Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapFault2_FaultActorL( TTestResult& aResult ) { SetupL(); _LIT8(KSenSoapEnvelopeXmlns, "http://schemas.xmlsoap.org/soap/envelope/"); _LIT8(KSenSoap12EnvelopeXmlns, "http://www.w3.org/2003/05/soap-envelope"); _LIT8(KFaultElementLocalname, "Fault"); _LIT8(KFaultNsPrefix, "S"); _LIT8(KFaultActorLocalname, "faultactor"); _LIT8(KFault12NodeLocalname, "Node"); // Node represents faultactor in Soap 1.2 _LIT8(KFaultActorValue, "http://www.wrox.com/heroes/endpoint.asp"); // 1) Faultactor in Soap other than 1.2 // "faultactor" is intended to provide information about which SOAP node // on the SOAP message path caused the fault to happen. // The value of the "faultactor" is a URI identifying the source of the fault. RSenDocument document = RSenDocument::NewLC(); TXmlEngElement faultElement = document.CreateDocumentElementL(KFaultElementLocalname(), KSenSoapEnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultCodeElement = faultElement.AddNewElementL(KFaultActorLocalname()); faultCodeElement.AddTextL(KFaultActorValue()); CSenSoapFault2* pSoapFault = CSenSoapFault2::NewL(faultElement, document); CleanupStack::PushL(pSoapFault); TPtrC8 faultActor = pSoapFault->FaultActor(); if(!( faultActor == KFaultActorValue )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault); CleanupStack::PopAndDestroy(1); // document // 2) Faultactor in Soap 1.2 // "Node" is intended to provide information about which SOAP node on the // SOAP message path caused the fault to happen. // "Node" contains the URI of the SOAP node that generated the fault. // // Note: In Soap 1.2 "Node" represents "faultactor" from previous SOAP versions. RSenDocument document2 = RSenDocument::NewLC(); TXmlEngElement faultElement2 = document2.CreateDocumentElementL(KFaultElementLocalname(), KSenSoap12EnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultNodeElement2 = faultElement2.AddNewElementSameNsL(KFault12NodeLocalname()); faultNodeElement2.AddTextL(KFaultActorValue()); CSenSoapFault2* pSoapFault2 = CSenSoapFault2::NewL(faultElement2, document2); CleanupStack::PushL(pSoapFault2); HBufC8* pAsXml = pSoapFault2->AsXmlL(); delete pAsXml; TPtrC8 faultCode2 = pSoapFault2->FaultActor(); if(!( faultCode2 == KFaultActorValue )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault2); CleanupStack::PopAndDestroy(1); // document2 Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapFault2_DetailL( TTestResult& aResult ) { SetupL(); _LIT8(KSenSoapEnvelopeXmlns, "http://schemas.xmlsoap.org/soap/envelope/"); _LIT8(KSenSoap12EnvelopeXmlns, "http://www.w3.org/2003/05/soap-envelope"); _LIT8(KFaultElementLocalname, "Fault"); _LIT8(KFaultNsPrefix, "S"); _LIT8(KDetailLocalname, "detail"); _LIT8(KFault12DetailLocalname, "Detail"); // Soap 1.2 _LIT8(KFaultDetailValue, "Detailed information"); // 1) Fault code in Soap other than 1.2 // Note: In SOAP older than 1.2 fault elements are _NOT_ namespace qualified RSenDocument document = RSenDocument::NewLC(); TXmlEngElement faultElement = document.CreateDocumentElementL(KFaultElementLocalname(), KSenSoapEnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultDetailElement = faultElement.AddNewElementL(KDetailLocalname()); faultDetailElement.AddTextL(KFaultDetailValue()); CSenSoapFault2* pSoapFault = CSenSoapFault2::NewL(faultElement, document); CleanupStack::PushL(pSoapFault); TPtrC8 faultDetail = pSoapFault->Detail(); if(!( faultDetail == KFaultDetailValue )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault); CleanupStack::PopAndDestroy(1); // document // 2) Fault code in Soap 1.2 // Note: SOAP 1.2 faults are structured differently to SOAP 1.1. // In particular all fault elements are now namespace _qualified_, // many have been renamed and fault codes are now hierarchical RSenDocument document2 = RSenDocument::NewLC(); TXmlEngElement faultElement2 = document2.CreateDocumentElementL(KFaultElementLocalname(), KSenSoap12EnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultDetailElement2 = faultElement2.AddNewElementSameNsL(KFault12DetailLocalname()); faultDetailElement2.AddTextL(KFaultDetailValue()); CSenSoapFault2* pSoapFault2 = CSenSoapFault2::NewL(faultElement2, document2); CleanupStack::PushL(pSoapFault2); TPtrC8 faultDetail2 = pSoapFault2->Detail(); if(!( faultDetail2 == KFaultDetailValue )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault2); CleanupStack::PopAndDestroy(1); // document2 Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLL( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewL(); CleanupStack::PushL(pSoapMessage); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLCL( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewLC(); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_1L( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); _LIT8(KSoapMessage12, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\"/>"); // 1) Test creating of SOAP 1.1 version SoapMessage CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewL(ESOAP11); CleanupStack::PushL(pSoapMessage); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2) Test creating of SOAP 1.2 version SoapMessage pSoapMessage = CSenSoapMessage2::NewL(ESOAP12); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_1L( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); _LIT8(KSoapMessage12, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\"/>"); // 1) Test creating of SOAP 1.1 version SoapMessage CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewLC(ESOAP11); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2) Test creating of SOAP 1.2 version SoapMessage pSoapMessage = CSenSoapMessage2::NewLC(ESOAP12); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_2L( TTestResult& aResult ) { SetupL(); _LIT8(KIllegalNamespace, "illegalNamespace"); _LIT8(KSecuritySchemeXmlNamespace, "http://schemas.xmlsoap.org/ws/2003/06/secext"); _LIT8(KSecurityXmlNamespace, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); _LIT8(KSoapMessage12, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header><wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage13, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header><wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage21, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\"/>"); _LIT8(KSoapMessage22, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header><wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage23, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header><wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); // 1.1) Test creating of SOAP 1.1 version SoapMessage with illegal namespace // => No security header should be added. CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewL(ESOAP11, KIllegalNamespace); CleanupStack::PushL(pSoapMessage); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 1.2) Test creating of SOAP 1.1 version SoapMessage with scheme namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewL(ESOAP11, KSecuritySchemeXmlNamespace); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 1.3) Test creating of SOAP 1.1 version SoapMessage with security namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewL(ESOAP11, KSecurityXmlNamespace); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage13 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.1) Test creating of SOAP 1.2 version SoapMessage with illegal namespace // => No security header should be added. pSoapMessage = CSenSoapMessage2::NewL(ESOAP12, KIllegalNamespace); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage21 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.2) Test creating of SOAP 1.2 version SoapMessage with scheme namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewL(ESOAP12, KSecuritySchemeXmlNamespace); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage22 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.3) Test creating of SOAP 1.2 version SoapMessage with security namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewL(ESOAP12, KSecurityXmlNamespace); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage23 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_2L( TTestResult& aResult ) { SetupL(); _LIT8(KIllegalNamespace, "illegalNamespace"); _LIT8(KSecuritySchemeXmlNamespace, "http://schemas.xmlsoap.org/ws/2003/06/secext"); _LIT8(KSecurityXmlNamespace, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); _LIT8(KSoapMessage12, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header><wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage13, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header><wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage21, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\"/>"); _LIT8(KSoapMessage22, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header><wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage23, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header><wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); // 1.1) Test creating of SOAP 1.1 version SoapMessage with illegal namespace // => No security header should be added. CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewLC(ESOAP11, KIllegalNamespace); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 1.2) Test creating of SOAP 1.1 version SoapMessage with scheme namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewLC(ESOAP11, KSecuritySchemeXmlNamespace); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 1.3) Test creating of SOAP 1.1 version SoapMessage with security namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewLC(ESOAP11, KSecurityXmlNamespace); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage13 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.1) Test creating of SOAP 1.2 version SoapMessage with illegal namespace // => No security header should be added. pSoapMessage = CSenSoapMessage2::NewLC(ESOAP12, KIllegalNamespace); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage21 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.2) Test creating of SOAP 1.2 version SoapMessage with scheme namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewLC(ESOAP12, KSecuritySchemeXmlNamespace); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage22 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.3) Test creating of SOAP 1.2 version SoapMessage with security namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewLC(ESOAP12, KSecurityXmlNamespace); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage23 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_3L( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapMessage2* pSoapMessage, *pSoapMessage1 = CSenSoapMessage2::NewL(); pSoapMessage = CSenSoapMessage2::NewL(*pSoapMessage1); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); __ASSERT_ALWAYS_NO_LEAVE(delete pSoapMessage); pSoapMessage = NULL; delete pSoapMessage1; pSoapMessage1 = NULL; Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_3L( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenSoapMessage2* pSoapMessage, *pSoapMessage1 = CSenSoapMessage2::NewL(); pSoapMessage = CSenSoapMessage2::NewLC(*pSoapMessage1); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); delete pSoapMessage1; pSoapMessage1 = NULL; Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_4L( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); MSenMessageContext* mContext = NULL; CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewL(*mContext); CleanupStack::PushL(pSoapMessage); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_4L( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); MSenMessageContext* mContext = NULL; CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewLC(*mContext); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_5L( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); _LIT8(KSoapMessage12, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\"/>"); MSenMessageContext* mContext = NULL; // 1) Test creating of SOAP 1.1 version SoapMessage CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewL(*mContext, ESOAP11); CleanupStack::PushL(pSoapMessage); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2) Test creating of SOAP 1.2 version SoapMessage pSoapMessage = CSenSoapMessage2::NewL(*mContext, ESOAP12 ); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_5L( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); _LIT8(KSoapMessage12, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\"/>"); MSenMessageContext* mContext = NULL; // 1) Test creating of SOAP 1.1 version SoapMessage CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewLC(*mContext, ESOAP11); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2) Test creating of SOAP 1.2 version SoapMessage pSoapMessage = CSenSoapMessage2::NewLC(*mContext, ESOAP12); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewL_6L( TTestResult& aResult ) { SetupL(); MSenMessageContext* mContext = NULL; _LIT8(KIllegalNamespace, "illegalNamespace"); _LIT8(KSecuritySchemeXmlNamespace, "http://schemas.xmlsoap.org/ws/2003/06/secext"); _LIT8(KSecurityXmlNamespace, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); _LIT8(KSoapMessage12, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header><wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage13, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header><wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage21, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\"/>"); _LIT8(KSoapMessage22, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header><wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage23, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header><wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); // 1.1) Test creating of SOAP 1.1 version SoapMessage with illegal namespace // => No security header should be added. CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewL(*mContext, ESOAP11, KIllegalNamespace); CleanupStack::PushL(pSoapMessage); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 1.2) Test creating of SOAP 1.1 version SoapMessage with scheme namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewL(*mContext,ESOAP11, KSecuritySchemeXmlNamespace); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 1.3) Test creating of SOAP 1.1 version SoapMessage with security namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewL(*mContext,ESOAP11, KSecurityXmlNamespace); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage13 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.1) Test creating of SOAP 1.2 version SoapMessage with illegal namespace // => No security header should be added. pSoapMessage = CSenSoapMessage2::NewL(*mContext,ESOAP12, KIllegalNamespace); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage21 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.2) Test creating of SOAP 1.2 version SoapMessage with scheme namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewL(*mContext,ESOAP12, KSecuritySchemeXmlNamespace); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage22 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.3) Test creating of SOAP 1.2 version SoapMessage with security namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewL(*mContext,ESOAP12, KSecurityXmlNamespace); CleanupStack::PushL(pSoapMessage); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage23 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_NewLC_6L(TTestResult& aResult ) { SetupL(); MSenMessageContext* mContext = NULL; _LIT8(KIllegalNamespace, "illegalNamespace"); _LIT8(KSecuritySchemeXmlNamespace, "http://schemas.xmlsoap.org/ws/2003/06/secext"); _LIT8(KSecurityXmlNamespace, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); _LIT8(KSoapMessage11, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); _LIT8(KSoapMessage12, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header><wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage13, "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header><wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage21, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\"/>"); _LIT8(KSoapMessage22, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header><wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage23, "<S:Envelope xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header><wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/></S:Header>\ <S:Body/>\ </S:Envelope>"); // 1.1) Test creating of SOAP 1.1 version SoapMessage with illegal namespace // => No security header should be added. CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewLC(*mContext,ESOAP11, KIllegalNamespace); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 1.2) Test creating of SOAP 1.1 version SoapMessage with scheme namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewLC(*mContext,ESOAP11, KSecuritySchemeXmlNamespace); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 1.3) Test creating of SOAP 1.1 version SoapMessage with security namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewLC(*mContext,ESOAP11, KSecurityXmlNamespace); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage13 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.1) Test creating of SOAP 1.2 version SoapMessage with illegal namespace // => No security header should be added. pSoapMessage = CSenSoapMessage2::NewLC(*mContext,ESOAP12, KIllegalNamespace); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage21 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.2) Test creating of SOAP 1.2 version SoapMessage with scheme namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewLC(*mContext,ESOAP12, KSecuritySchemeXmlNamespace); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage22 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2.3) Test creating of SOAP 1.2 version SoapMessage with security namespace // => Security header should be created with given namespace. pSoapMessage = CSenSoapMessage2::NewLC(*mContext,ESOAP12, KSecurityXmlNamespace); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage23 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_TypeL( TTestResult& aResult ) { SetupL(); CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewL(); CleanupStack::PushL(pSoapMessage); TL(MSenMessage::ESoapMessage2 == pSoapMessage->Type()); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_CloneL( TTestResult& aResult ) { SetupL(); TBool Flag; CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewL(); CleanupStack::PushL(pSoapMessage); CSenSoapMessage2* pClone = NULL; pClone = (CSenSoapMessage2*)pSoapMessage->CloneL(); if(pClone != NULL) Flag = 1; if(!(Flag)) return KErrArgument; delete pClone; CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_Parse1L( TTestResult& aResult ) { SetupL(); _LIT8(KInputString, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header>\ <sb:Correlation xmlns:sb=\"urn:liberty:sb:2003-08\" \ messageID=\"URN:UUID:860949DC-134D-A989-E328-2FD7F20E31CE\" timestamp=\"2006-06-01T14:53:19Z\"/>\ <wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2003/06/secext\"/>\ </S:Header>\ <S:Body>\ <sa:SASLRequest xmlns:sa=\"urn:liberty:sa:2004-04\" mechanism=\"ANONYMOUS PLAIN CRAM-MD5\" authzID=\"testuser1\"/>\ </S:Body>\ </S:Envelope>"); _LIT8(KBodyAsString, "\ <S:Body xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:sa=\"urn:liberty:sa:2004-04\">\ <sa:SASLRequest xmlns:sa=\"urn:liberty:sa:2004-04\" mechanism=\"ANONYMOUS PLAIN CRAM-MD5\" authzID=\"testuser1\"/>\ </S:Body>"); // TODO: there seems to be a bug in libxml2: ReconcileNamespacesL() copies extra // namespace declaration into Body tag: // xmlns:sa="urn:liberty:sa:2004-04" _LIT8(KEmptyBodyAsString, "<S:Body/>"); _LIT8(KEmptyBodyWithNsAsString, "<S:Body xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\"/>"); CSenParser* pParser = CSenParser::NewLC(); CSenSoapMessage2* pMessage = CSenSoapMessage2::NewL(); CleanupStack::PushL(pMessage); pParser->ParseL(KInputString, *pMessage); // 1) Check that parsed SoapEnvelope can be // serialized correctly HBufC8* pAsXml = pMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KInputString )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); // 2) Check that body can be detached from SoapEnvelope // correctly. // Note: Following "BodyAsStringL()" call will detach // Body from SoapEnvelope HBufC8* pBodyAsString = pMessage->BodyAsStringL(); CleanupStack::PushL(pBodyAsString); if(!( *pBodyAsString == KBodyAsString )) return KErrArgument; CleanupStack::PopAndDestroy(pBodyAsString); // 3) Check that body can be detached from SoapEnvelope // twice // In this case body does not have child elements. // => Empty body should be returned. // Note: Empty body should contain namespace // declaration because body is detached pBodyAsString = pMessage->BodyAsStringL(); CleanupStack::PushL(pBodyAsString); if(!( *pBodyAsString == KEmptyBodyWithNsAsString )) return KErrArgument; CleanupStack::PopAndDestroy(pBodyAsString); // 4) Check that body was detached from SoapEnvelope // correctly // => Getting body again should result empty body to be returned. TXmlEngElement bodyElement = pMessage->BodyL(); RSenDocument document = pMessage->AsDocumentL(); TUint optionFlags = 0; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> optionFlags = optionFlags | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; // Allow encoding declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionEncoding; // Allow standalone declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionStandalone; TXmlEngSerializationOptions options(optionFlags); RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, bodyElement, options); // Serielized body should be empty because "BodyAsStringL()" // previously detached body. if(!( asXml == KEmptyBodyAsString )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); CleanupStack::PopAndDestroy(pMessage); CleanupStack::PopAndDestroy(pParser); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_SetSecurityHeaderLL( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11_1, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\ <Credential/>\ </wsse:Security>\ </S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage11_2, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/>\ </S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage12_1, "<S:Envelope \ xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\ <Credential/>\ </wsse:Security>\ </S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage12_2, "<S:Envelope \ xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/>\ </S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KCredential, "<Credential/>"); // 1) Soap 1.1 - Test setting of SecurityHeader WITH Credential CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewL(ESOAP11); CleanupStack::PushL(pSoapMessage); pSoapMessage->SetSecurityHeaderL(KCredential); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11_1 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2) Soap 1.1 - Test setting of SecurityHeader WITHOUT Credential pSoapMessage = CSenSoapMessage2::NewL(ESOAP11); CleanupStack::PushL(pSoapMessage); pSoapMessage->SetSecurityHeaderL(KNullDesC8); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11_2 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 3) Soap 1.2 - Test setting of SecurityHeader WITH Credential pSoapMessage = CSenSoapMessage2::NewL(ESOAP12); CleanupStack::PushL(pSoapMessage); pSoapMessage->SetSecurityHeaderL(KCredential); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12_1 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 4) Soap 1.2 - Test setting of SecurityHeader WITH Credential pSoapMessage = CSenSoapMessage2::NewL(ESOAP12); CleanupStack::PushL(pSoapMessage); pSoapMessage->SetSecurityHeaderL(KNullDesC8); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12_2 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenSoapMessage2_AddSecurityTokenLL( TTestResult& aResult ) { SetupL(); _LIT8(KSoapMessage11_1, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\ <SecurityToken/>\ </wsse:Security>\ </S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage11_2, "<S:Envelope \ xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\ <S:Header>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\ <SecurityToken/>\ <SecurityToken2/>\ </wsse:Security>\ </S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage12_1, "<S:Envelope \ xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\ <SecurityToken/>\ </wsse:Security>\ </S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSoapMessage12_2, "<S:Envelope \ xmlns:S=\"http://www.w3.org/2003/05/soap-envelope\">\ <S:Header>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\ <SecurityToken/>\ <SecurityToken2/>\ </wsse:Security>\ </S:Header>\ <S:Body/>\ </S:Envelope>"); _LIT8(KSecurityToken, "<SecurityToken/>"); _LIT8(KSecurityToken2, "<SecurityToken2/>"); // 1) Soap 1.1 - Test adding of SecurityToken CSenSoapMessage2* pSoapMessage = CSenSoapMessage2::NewL(ESOAP11); CleanupStack::PushL(pSoapMessage); pSoapMessage->AddSecurityTokenL(KSecurityToken); HBufC8* pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11_1 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 2) Soap 1.1 - Test adding of two SecurityTokens pSoapMessage = CSenSoapMessage2::NewL(ESOAP11); CleanupStack::PushL(pSoapMessage); pSoapMessage->AddSecurityTokenL(KSecurityToken); pSoapMessage->AddSecurityTokenL(KSecurityToken2); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage11_2 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 3) Soap 1.2 - Test adding of SecurityToken pSoapMessage = CSenSoapMessage2::NewL(ESOAP12); CleanupStack::PushL(pSoapMessage); pSoapMessage->AddSecurityTokenL(KSecurityToken); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12_1 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); // 4) Soap 1.2 - Test adding of two SecurityTokens pSoapMessage = CSenSoapMessage2::NewL(ESOAP12); CleanupStack::PushL(pSoapMessage); pSoapMessage->AddSecurityTokenL(KSecurityToken); pSoapMessage->AddSecurityTokenL(KSecurityToken2); pAsXml = pSoapMessage->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSoapMessage12_2 )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pSoapMessage); Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewLL( TTestResult& aResult ) { SetupL(); _LIT8(KRootElement, "<RootElement>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/>\ </RootElement>"); _LIT8(KSecurityHeader, "\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/>"); _LIT8(KRootElementName, "RootElement"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewL(document, rootElement); CleanupStack::PushL(pWsSecHeader); TUint optionFlags = 0; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> optionFlags = optionFlags | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; // Allow encoding declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionEncoding; // Allow standalone declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionStandalone; TXmlEngSerializationOptions options(optionFlags); RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, rootElement, options); // Serialized document should contain all the Fragment data as XML. if(!( asXml == KRootElement )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); HBufC8* pAsXml = pWsSecHeader->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSecurityHeader )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewLCL( TTestResult& aResult ) { SetupL(); _LIT8(KRootElement, "<RootElement>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/>\ </RootElement>"); _LIT8(KSecurityHeader, "\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"/>"); _LIT8(KRootElementName, "RootElement"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); TUint optionFlags = 0; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> optionFlags = optionFlags | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; // Allow encoding declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionEncoding; // Allow standalone declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionStandalone; TXmlEngSerializationOptions options(optionFlags); RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, rootElement, options); // Serialized document should contain all the Fragment data as XML. if(!( asXml == KRootElement )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); HBufC8* pAsXml = pWsSecHeader->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSecurityHeader )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewL_1L( TTestResult& aResult ) { SetupL(); _LIT8(KRootElement, "<RootElement>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\ SecurityToken\ </wsse:Security>\ </RootElement>"); _LIT8(KSecurityHeader, "\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\ SecurityToken\ </wsse:Security>"); _LIT8(KRootElementName, "RootElement"); _LIT8(KSecurityToken, "SecurityToken"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewL(KSecurityToken, document, rootElement); CleanupStack::PushL(pWsSecHeader); TUint optionFlags = 0; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> optionFlags = optionFlags | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; // Allow encoding declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionEncoding; // Allow standalone declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionStandalone; TXmlEngSerializationOptions options(optionFlags); RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, rootElement, options); // Serialized document should contain all the Fragment data as XML. if(!( asXml == KRootElement )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); HBufC8* pAsXml = pWsSecHeader->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSecurityHeader )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewLC_1L( TTestResult& aResult ) { SetupL(); _LIT8(KRootElement, "<RootElement>\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\ SecurityToken\ </wsse:Security>\ </RootElement>"); _LIT8(KSecurityHeader, "\ <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">\ SecurityToken\ </wsse:Security>"); _LIT8(KRootElementName, "RootElement"); _LIT8(KSecurityToken, "SecurityToken"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(KSecurityToken, document, rootElement); TUint optionFlags = 0; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> optionFlags = optionFlags | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; // Allow encoding declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionEncoding; // Allow standalone declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionStandalone; TXmlEngSerializationOptions options(optionFlags); RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, rootElement, options); // Serialized document should contain all the Fragment data as XML. if(!( asXml == KRootElement )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); HBufC8* pAsXml = pWsSecHeader->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSecurityHeader )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewL_2L( TTestResult& aResult ) { SetupL(); _LIT8(KRootElement, "<RootElement>\ <wsse:Security xmlns:wsse=\"namespace\">\ SecurityToken\ </wsse:Security>\ </RootElement>"); _LIT8(KSecurityHeader, "\ <wsse:Security xmlns:wsse=\"namespace\">\ SecurityToken\ </wsse:Security>"); _LIT8(KRootElementName, "RootElement"); _LIT8(KSecurityToken, "SecurityToken"); _LIT8(KNamespace, "namespace"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewL(KSecurityToken, KNamespace, document, rootElement); CleanupStack::PushL(pWsSecHeader); TUint optionFlags = 0; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> optionFlags = optionFlags | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; // Allow encoding declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionEncoding; // Allow standalone declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionStandalone; TXmlEngSerializationOptions options(optionFlags); RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, rootElement, options); // Serialized document should contain all the Fragment data as XML. if(!( asXml == KRootElement )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); HBufC8* pAsXml = pWsSecHeader->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSecurityHeader )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_NewLC_2L( TTestResult& aResult ) { SetupL(); _LIT8(KRootElement, "<RootElement>\ <wsse:Security xmlns:wsse=\"namespace\">\ SecurityToken\ </wsse:Security>\ </RootElement>"); _LIT8(KSecurityHeader, "\ <wsse:Security xmlns:wsse=\"namespace\">\ SecurityToken\ </wsse:Security>"); _LIT8(KRootElementName, "RootElement"); _LIT8(KSecurityToken, "SecurityToken"); _LIT8(KNamespace, "namespace"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(KSecurityToken, KNamespace, document, rootElement); TUint optionFlags = 0; // Omit following declarations from the beginning of XML Document: // <?xml version=\"1.0\... // encoding="..." // standalone="..." // ?> optionFlags = optionFlags | TXmlEngSerializationOptions::KOptionOmitXMLDeclaration; // Allow encoding declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionEncoding; // Allow standalone declaration (if KOptionOmitXMLDeclaration is _not_ set) //optionFlags = optionFlags | TSerializationOptions::KOptionStandalone; TXmlEngSerializationOptions options(optionFlags); RBuf8 asXml; CleanupClosePushL(asXml); document.SaveL(asXml, rootElement, options); // Serialized document should contain all the Fragment data as XML. if(!( asXml == KRootElement )) return KErrArgument; CleanupStack::PopAndDestroy(&asXml); HBufC8* pAsXml = pWsSecHeader->AsXmlL(); CleanupStack::PushL(pAsXml); if(!( *pAsXml == KSecurityHeader )) return KErrArgument; CleanupStack::PopAndDestroy(pAsXml); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_UsernameTokenLL( TTestResult& aResult ) { SetupL(); _LIT8(KRootElementName, "RootElement"); _LIT8(KUserName, "UserName"); _LIT8(KUserNameToken, "<wsse:UsernameToken>\ <wsse:Username>UserName</wsse:Username>\ </wsse:UsernameToken>"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); HBufC8* pUserNameToken = NULL; pWsSecHeader->UsernameTokenL(KUserName, pUserNameToken); CleanupStack::PushL(pUserNameToken); if(!( *pUserNameToken == KUserNameToken )) return KErrArgument; CleanupStack::PopAndDestroy(pUserNameToken); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_UsernameTokenL_1L( TTestResult& aResult ) { SetupL(); _LIT8(KRootElementName, "RootElement"); _LIT8(KFakeEndPoint, "http://www.fake_endpoint.com/"); _LIT8(KUsername, "Username"); _LIT8(KPassword, "Password"); _LIT8(KUserNameToken, "<wsse:UsernameToken>\ <wsse:Username>Username</wsse:Username>\ <wsse:Password>Password</wsse:Password>\ </wsse:UsernameToken>"); _LIT8(KUserNameTokenDigest, "<wsse:UsernameToken>\ <wsse:Username>Username</wsse:Username>\ <wsse:Password Type=\"wsse:PasswordDigest\">Password</wsse:Password>\ </wsse:UsernameToken>"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenIdentityProvider* pIdP = CSenIdentityProvider::NewLC(KFakeEndPoint()); pIdP->SetUserInfoL(KUsername, KNullDesC8, KPassword); // 1) Test using CSenWsSecurityHeader2::EText CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); HBufC8* pUserNameToken = pWsSecHeader->UsernameTokenL(*pIdP, CSenWsSecurityHeader2::EText); CleanupStack::PushL(pUserNameToken); if(!( *pUserNameToken == KUserNameToken )) return KErrArgument; CleanupStack::PopAndDestroy(pUserNameToken); CleanupStack::PopAndDestroy(pWsSecHeader); // 2) Test using CSenWsSecurityHeader2::EDigest pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); pUserNameToken = pWsSecHeader->UsernameTokenL(*pIdP, CSenWsSecurityHeader2::EDigest); CleanupStack::PushL(pUserNameToken); if(!( *pUserNameToken == KUserNameTokenDigest )) return KErrArgument; CleanupStack::PopAndDestroy(pUserNameToken); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(pIdP); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_UsernameTokenL_2L( TTestResult& aResult ) { SetupL(); _LIT8(KRootElementName, "RootElement"); _LIT8(KUserName, "UserName"); _LIT8(KPassword, "Password"); _LIT8(KUserNameToken, "<wsse:UsernameToken>\ <wsse:Username>UserName</wsse:Username>\ <wsse:Password>Password</wsse:Password>\ </wsse:UsernameToken>"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); HBufC8* pUserNameToken = NULL; pWsSecHeader->UsernameTokenL(KUserName, KPassword, pUserNameToken); CleanupStack::PushL(pUserNameToken); if(!( *pUserNameToken == KUserNameToken )) return KErrArgument; CleanupStack::PopAndDestroy(pUserNameToken); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_UsernameTokenL_3L( TTestResult& aResult ) { SetupL(); _LIT8(KRootElementName, "RootElement"); _LIT8(KUserName, "UserName"); _LIT8(KPassword, "Password"); _LIT8(KUserNameToken, "<wsse:UsernameToken>\ <wsse:Username>UserName</wsse:Username>\ <wsse:Password>Password</wsse:Password>\ </wsse:UsernameToken>"); _LIT8(KUserNameTokenDigest, "<wsse:UsernameToken>\ <wsse:Username>UserName</wsse:Username>\ <wsse:Password Type=\"wsse:PasswordDigest\">Password</wsse:Password>\ </wsse:UsernameToken>"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); // 1) Test using CSenWsSecurityHeader2::EText CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); HBufC8* pUserNameToken = NULL; pWsSecHeader->UsernameTokenL(KUserName, KPassword, CSenWsSecurityHeader2::EText, pUserNameToken); CleanupStack::PushL(pUserNameToken); if(!( *pUserNameToken == KUserNameToken )) return KErrArgument; CleanupStack::PopAndDestroy(pUserNameToken); CleanupStack::PopAndDestroy(pWsSecHeader); // 2) Test using CSenWsSecurityHeader2::EDigest pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); pUserNameToken = NULL; pWsSecHeader->UsernameTokenL(KUserName, KPassword, CSenWsSecurityHeader2::EDigest, pUserNameToken); CleanupStack::PushL(pUserNameToken); if(!( *pUserNameToken == KUserNameTokenDigest )) return KErrArgument; CleanupStack::PopAndDestroy(pUserNameToken); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_UsernameTokenL_4L( TTestResult& aResult ) { SetupL(); _LIT8(KRootElementName, "RootElement"); _LIT8(KFakeEndPoint, "http://www.fake_endpoint.com/"); _LIT8(KUsername, "Username"); _LIT8(KPassword, "Password"); _LIT8(KUserNameToken, "<wsse:UsernameToken>\ <wsse:Username>Username</wsse:Username>\ </wsse:UsernameToken>"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); CSenIdentityProvider* pIdP = CSenIdentityProvider::NewLC(KFakeEndPoint()); pIdP->SetUserInfoL(KUsername, KNullDesC8, KPassword); HBufC8* pUserNameToken = pWsSecHeader->UsernameTokenL(*pIdP); CleanupStack::PushL(pUserNameToken); if(!( *pUserNameToken == KUserNameToken )) return KErrArgument; CleanupStack::PopAndDestroy(pUserNameToken); CleanupStack::PopAndDestroy(pIdP); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_TimestampLL( TTestResult& aResult ) { SetupL(); _LIT8(KRootElementName, "RootElement"); _LIT8(KCreated, "2001-09-13T08:42:00Z"); _LIT8(KExpires, "2002-09-13T08:42:00Z"); _LIT8(KTimeStamp, "\ <wsu:Timestamp xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\ <wsu:Created>2001-09-13T08:42:00Z</wsu:Created>\ <wsu:Expires>2002-09-13T08:42:00Z</wsu:Expires>\ </wsu:Timestamp>"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); HBufC8* pTimeStamp; pWsSecHeader->TimestampL(KCreated, KExpires, pTimeStamp); CleanupStack::PushL(pTimeStamp); if(!( *pTimeStamp == KTimeStamp )) return KErrArgument; CleanupStack::PopAndDestroy(pTimeStamp); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_TimestampL_1L( TTestResult& aResult ) { SetupL(); _LIT8(KRootElementName, "RootElement"); _LIT8(KCreated, "2001-09-13T08:42:00Z"); _LIT8(KTimeStamp, "\ <wsu:Timestamp xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\ <wsu:Created>2001-09-13T08:42:00Z</wsu:Created>\ </wsu:Timestamp>"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); HBufC8* pTimeStamp; pWsSecHeader->TimestampL(KCreated, pTimeStamp); CleanupStack::PushL(pTimeStamp); if(!( *pTimeStamp == KTimeStamp )) return KErrArgument; CleanupStack::PopAndDestroy(pTimeStamp); CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_XmlNsL( TTestResult& aResult ) { SetupL(); _LIT8(KRootElementName, "RootElement"); _LIT8(KSecurityNamespace, "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); TPtrC8 nameSpace = pWsSecHeader->XmlNs(); if(!( nameSpace == KSecurityNamespace )) return KErrArgument; CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CSenWsSecurityHeader2_XmlNsPrefixL( TTestResult& aResult ) { SetupL(); _LIT8(KRootElementName, "RootElement"); _LIT8(KSecurityNamespacePrefix, "wsse"); RSenDocument document = RSenDocument::NewLC(); TXmlEngElement rootElement = document.CreateDocumentElementL(KRootElementName()); CSenWsSecurityHeader2* pWsSecHeader = CSenWsSecurityHeader2::NewLC(document, rootElement); TPtrC8 prefix = pWsSecHeader->XmlNsPrefix(); if(!( prefix == KSecurityNamespacePrefix )) return KErrArgument; CleanupStack::PopAndDestroy(pWsSecHeader); CleanupStack::PopAndDestroy(1); // document Teardown(); return KErrNone; } TInt CNewSoapClassesBCTest::MT_CTestMSenMessage_Type( TTestResult& aResult ) { CTestMSenMessage* pTest = CTestMSenMessage::NewLC(); TRAPD(res,pTest->Type()); CleanupStack::PopAndDestroy(pTest); return res; } TInt CNewSoapClassesBCTest::MT_CTestMSenMessage_Direction( TTestResult& aResult ) { CTestMSenMessage* pTest = CTestMSenMessage::NewLC(); TRAPD(res,pTest->Direction()); CleanupStack::PopAndDestroy(pTest); return res; } TInt CNewSoapClassesBCTest::MT_CTestMSenMessage_Context( TTestResult& aResult ) { CTestMSenMessage* pTest = CTestMSenMessage::NewLC(); TRAPD(res,pTest->Context()); CleanupStack::PopAndDestroy(pTest); return res; } TInt CNewSoapClassesBCTest::MT_CTestMSenMessage_SetContext( TTestResult& aResult ) { CTestMSenMessage* pTest = CTestMSenMessage::NewLC(); MSenMessageContext* apNotOwnedContext =NULL; TRAPD(res,pTest->SetContext(apNotOwnedContext)); CleanupStack::PopAndDestroy(pTest); return res; } TInt CNewSoapClassesBCTest::MT_CTestMSenMessage_Properties( TTestResult& aResult ) { CTestMSenMessage* pTest = CTestMSenMessage::NewLC(); TRAPD(res,pTest->Properties()); CleanupStack::PopAndDestroy(pTest); return res; } TInt CNewSoapClassesBCTest::MT_CTestMSenMessage_SetProperties( TTestResult& aResult ) { CTestMSenMessage* pTest = CTestMSenMessage::NewLC(); MSenProperties* apOwnedProperties = NULL; TRAPD(res,pTest->SetProperties(apOwnedProperties )); CleanupStack::PopAndDestroy(pTest); return res; } TInt CNewSoapClassesBCTest::MT_CTestMSenMessage_IsSafeToCast( TTestResult& aResult ) { CTestMSenMessage* pTest = CTestMSenMessage::NewLC(); TRAPD(res,pTest->IsSafeToCast(MSenMessage::ESoapEnvelope2)); CleanupStack::PopAndDestroy(pTest); return res; } TInt CNewSoapClassesBCTest::MT_CTestMSenMessage_TxnId( TTestResult& aResult ) { CTestMSenMessage* pTest = CTestMSenMessage::NewLC(); TRAPD(res,pTest->TxnId()); CleanupStack::PopAndDestroy(pTest); return res; } TInt CNewSoapClassesBCTest::MT_CTestMSenMessage_CloneL( TTestResult& aResult ) { CTestMSenMessage* pTest = CTestMSenMessage::NewLC(); TRAPD(res,pTest->CloneL()); CleanupStack::PopAndDestroy(pTest); return res; } /* SetupL(); _LIT8(KSenSoapEnvelopeXmlns, "http://schemas.xmlsoap.org/soap/envelope/"); _LIT8(KSenSoap12EnvelopeXmlns, "http://www.w3.org/2003/05/soap-envelope"); _LIT8(KFaultElementLocalname, "Fault"); _LIT8(KFaultNsPrefix, "S"); _LIT8(KFaultCodeLocalname, "faultcode"); _LIT8(KFault12CodeLocalname, "Code"); // Soap 1.2 _LIT8(KFault12ValueLocalname, "Value"); // Soap1.2 _LIT8(KFaultCodeValue, "123"); TFileName path( _L("c:\\abc.txt")); RFile file; RFs fileSession; TInt err = fileSession.Connect(); err = file.Open(fileSession, path, EFileStreamText | EFileWrite); if ( err != KErrNone) err = file.Create(fileSession,path, EFileStreamText|EFileWrite|EFileShareAny); TFileText filetext; filetext.Set( file ); // 1) Fault code in Soap other than 1.2 // Note: In SOAP older than 1.2 fault elements are _NOT_ namespace qualified RSenDocument document = RSenDocument::NewLC(); filetext.Write(_L("RSenDocument::NewL")); // RSenDocument document1 = RSenDocument::NewL(); // filetext.Write(_L("RSenDocument::NewL")); TXmlEngElement faultElement = document.CreateDocumentElementL(KFaultElementLocalname(), KSenSoapEnvelopeXmlns(), KFaultNsPrefix()); filetext.Write(_L("document.CreateDocumentElementL")); TXmlEngElement faultCodeElement = faultElement.AddNewElementL(KFaultCodeLocalname()); filetext.Write(_L("faultElement.AddNewElementL")); faultCodeElement.AddTextL(KFaultCodeValue()); filetext.Write(_L("faultCodeElement.AddTextL(KFaultCodeValue());")); CSenSoapFault2* pSoapFault = CSenSoapFault2::NewL(faultElement);//, document); filetext.Write(_L("CSenSoapFault2::NewL(faultElement, document);")); CleanupStack::PushL(pSoapFault); filetext.Write(_L("CleanupStack::PushL(pSoapFault);")); TPtrC8 faultCode = pSoapFault->FaultCode(); filetext.Write(_L("TPtrC8 faultCode = pSoapFault->FaultCode();")); if(!( faultCode == KFaultCodeValue )) return KErrArgument; filetext.Write(_L("if(!( faultCode == KFaultCodeValue )) return KErrArgument;")); CleanupStack::PopAndDestroy(pSoapFault); filetext.Write(_L("CleanupStack::PopAndDestroy(pSoapFault);")); CleanupStack::PopAndDestroy(1); // document filetext.Write(_L("CleanupStack::PopAndDestroy(1); ")); /* // 2) Fault code in Soap 1.2 // Note: SOAP 1.2 faults are structured differently to SOAP 1.1. // In particular all fault elements are now namespace _qualified_, // many have been renamed and fault codes are now hierarchical RSenDocument document2 = RSenDocument::NewLC(); TXmlEngElement faultElement2 = document2.CreateDocumentElementL(KFaultElementLocalname(), KSenSoap12EnvelopeXmlns(), KFaultNsPrefix()); TXmlEngElement faultCodeElement2 = faultElement2.AddNewElementSameNsL(KFault12CodeLocalname()); TXmlEngElement faultValueElement2 = faultCodeElement2.AddNewElementSameNsL(KFault12ValueLocalname()); faultValueElement2.AddTextL(KFaultCodeValue()); CSenSoapFault2* pSoapFault2 = CSenSoapFault2::NewL(faultElement2, document2); CleanupStack::PushL(pSoapFault2); TPtrC8 faultCode2 = pSoapFault2->FaultCode(); if(!( faultCode2 == KFaultCodeValue )) return KErrArgument; CleanupStack::PopAndDestroy(pSoapFault2); CleanupStack::PopAndDestroy(1); // document2 *//* Teardown(); filetext.Write(_L("Teardown")); return KErrNone; */ // End of File
[ "none@none" ]
[ [ [ 1, 3451 ] ] ]
21462cc49b05e9bec7e0aa2f8a79f33fc0ea57c6
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/aux_/has_key_impl.hpp
079f329975cb11b9b286b3a746f10a8e97f8fe13
[]
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
1,010
hpp
#ifndef BOOST_MPL_AUX_HAS_KEY_IMPL_HPP_INCLUDED #define BOOST_MPL_AUX_HAS_KEY_IMPL_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2002-2004 // Copyright David Abrahams 2003 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/aux_/has_key_impl.hpp,v $ // $Date: 2006/04/17 23:47:07 $ // $Revision: 1.1 $ #include <boost/mpl/has_key_fwd.hpp> #include <boost/mpl/aux_/traits_lambda_spec.hpp> namespace boost { namespace mpl { // no default implementation; the definition is needed to make MSVC happy template< typename Tag > struct has_key_impl { template< typename AssociativeSequence, typename Key > struct apply; }; BOOST_MPL_ALGORITM_TRAITS_LAMBDA_SPEC(2,has_key_impl) }} #endif // BOOST_MPL_AUX_HAS_KEY_IMPL_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 34 ] ] ]
b5b931b4b5a0bd47bd79aec47f4c866b5b422f04
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Dynamics/Constraint/Bilateral/StiffSpring/hkpStiffSpringConstraintData.h
00316e92bf8bfd5b9bb19dd7215f5e6aeff74c7f
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,762
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_DYNAMICS2_STIFF_SPRING_CONSTRAINT_H #define HK_DYNAMICS2_STIFF_SPRING_CONSTRAINT_H #include <Physics/ConstraintSolver/Solve/hkpSolverResults.h> #include <Physics/Dynamics/Constraint/hkpConstraintData.h> #include <Physics/ConstraintSolver/Constraint/Atom/hkpConstraintAtom.h> extern const hkClass hkpStiffSpringConstraintDataClass; /// A stiff spring constraint. It holds the constrained bodies apart at a specified distance, /// as if they were attached at each end of an invisible rod. class hkpStiffSpringConstraintData : public hkpConstraintData { public: HK_DECLARE_REFLECTION(); hkpStiffSpringConstraintData(); /// Sets the spring up with world space information. /// Will compute a rest length too (so call setlength after this if needed) /// \param pivotA bodyA's pivot point, specified in world space. /// \param pivotB bodyB's pivot point, specified in world space. inline void setInWorldSpace(const hkTransform& bodyATransform, const hkTransform& bodyBTransform, const hkVector4& pivotAW, const hkVector4& pivotBW); /// Sets the spring up with body space information. /// \param pivotA bodyA's pivot point, specified in bodyA's space. /// \param pivotB bodyB's pivot point, specified in bodyB's space. /// \param restLength The length of the stiff spring when at rest inline void setInBodySpace(const hkVector4& pivotA, const hkVector4& pivotB, hkReal restLength); /// Gets the length of the stiff spring. inline hkReal getSpringLength(); /// Sets the length of the stiff spring when at rest. inline void setSpringLength( hkReal length ); /// Check consistency of constraint. hkBool isValid() const; /// Get type from this constraint. virtual int getType() const; public: enum { SOLVER_RESULT_LIN_0 = 0, // linear constraint SOLVER_RESULT_MAX = 1 }; struct Runtime { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DYNAMICS, hkpStiffSpringConstraintData::Runtime ); class hkpSolverResults m_solverResults[1/*VC6 doesn't like the scoping for SOLVER_RESULT_MAX*/]; }; inline const Runtime* getRuntime( hkpConstraintRuntime* runtime ){ return reinterpret_cast<Runtime*>(runtime); } struct Atoms { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_DYNAMICS, hkpStiffSpringConstraintData::Atoms ); HK_DECLARE_REFLECTION(); struct hkpSetLocalTranslationsConstraintAtom m_pivots; struct hkpStiffSpringConstraintAtom m_spring; Atoms(){} // get a pointer to the first atom const hkpConstraintAtom* getAtoms() const { return &m_pivots; } // get the size of all atoms (we can't use sizeof(*this) because of align16 padding) int getSizeOfAllAtoms() const { return hkGetByteOffsetInt(this, &m_spring+1); } Atoms(hkFinishLoadedObjectFlag f) : m_pivots(f), m_spring(f) {} }; HK_ALIGN16( struct Atoms m_atoms ); public: // Internal functions // hkpConstraintData interface implementations virtual void getConstraintInfo( ConstraintInfo& infoOut ) const; // hkpConstraintData interface implementations virtual void getRuntimeInfo( hkBool wantRuntime, hkpConstraintData::RuntimeInfo& infoOut ) const; public: hkpStiffSpringConstraintData(hkFinishLoadedObjectFlag f) : hkpConstraintData(f), m_atoms(f) {} }; #include <Physics/Dynamics/Constraint/Bilateral/StiffSpring/hkpStiffSpringConstraintData.inl> #endif // HK_DYNAMICS2_STIFF_SPRING_CONSTRAINT_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 129 ] ] ]