blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
146
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
7
| license_type
stringclasses 2
values | repo_name
stringlengths 6
79
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 4
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.07k
426M
⌀ | star_events_count
int64 0
27
| fork_events_count
int64 0
12
| gha_license_id
stringclasses 3
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 6
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 1
class | length_bytes
int64 20
6.28M
| extension
stringclasses 20
values | content
stringlengths 20
6.28M
| authors
listlengths 1
16
| author_lines
listlengths 1
16
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bb9516f3cc2f4ccac6bb1856503143ab37683242 | f8b364974573f652d7916c3a830e1d8773751277 | /emulator/allegrex/disassembler/DIV_S.h | 220dabbe595045e3ce9394c87e22a347c61f3d61 | []
| no_license | lemmore22/pspe4all | 7a234aece25340c99f49eac280780e08e4f8ef49 | 77ad0acf0fcb7eda137fdfcb1e93a36428badfd0 | refs/heads/master | 2021-01-10T08:39:45.222505 | 2009-08-02T11:58:07 | 2009-08-02T11:58:07 | 55,047,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | h | /* DIV_S */
void AllegrexInstructionTemplate< 0x46000003, 0xffe0003f >::disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment)
{
using namespace Allegrex;
::strcpy(opcode_name, "div.s");
::sprintf(operands, "%s, %s, %s", fpr_name[fd(opcode)], fpr_name[fs(opcode)], fpr_name[ft(opcode)]);
::strcpy(comment, "");
}
| [
"[email protected]"
]
| [
[
[
1,
9
]
]
]
|
29bee63ad6f318d724f15f8ca0338554ac62ad4e | c63685bfe2d1ecfdfebcda0eab70642f6fcf4634 | /HDRRendering/HDRRendering/3D/Matrix4.cpp | ff19ebbbed98d08c31dfd1a7f8b9e89337ff0019 | []
| no_license | Shell64/cgdemos | 8afa9272cef51e6d0544d672caa0142154e231fc | d34094d372fea0536a5b3a17a861bb1a1bfac8c4 | refs/heads/master | 2021-01-22T23:26:19.112999 | 2011-10-13T12:38:10 | 2011-10-13T12:38:10 | 35,008,078 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,745 | cpp | #include "Matrix4.h"
const Matrix4 Matrix4::IDENTITY(1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f );
const Matrix4 Matrix4::ZERO( 0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f );
Matrix4 mat4Translation(const Vector3 &v)
{
Matrix4 m(Matrix4::IDENTITY);
m[12] = v.x;
m[13] = v.y;
m[14] = v.z;
return m;
}
Matrix4 mat4RotationX(float rad)
{
float c = Math::cos(rad);
float s = Math::sin(rad);
Matrix4 m(Matrix4::IDENTITY);
m[5] = c;
m[6] = s;
m[9] = -s;
m[10] = c;
return m;
}
Matrix4 mat4RotationY(float rad)
{
float c = Math::cos(rad);
float s = Math::sin(rad);
Matrix4 m(Matrix4::IDENTITY);
m[0] = c;
m[2] = -s;
m[8] = s;
m[10] = c;
return m;
}
Matrix4 mat4RotationZ(float rad)
{
float c = Math::cos(rad);
float s = Math::sin(rad);
Matrix4 m(Matrix4::IDENTITY);
m[0] = c;
m[1] = s;
m[4] = -s;
m[5] = c;
return m;
}
Matrix4 mat4RotationAxis(const Vector3 &axis, float rad)
{
Matrix4 m(Matrix4::IDENTITY);
float fCos = Math::cos(rad);
float fSin = Math::sin(rad);
float fOneMinusCos = 1.0f - fCos;
float fX2 = axis.x*axis.x;
float fY2 = axis.y*axis.y;
float fZ2 = axis.z*axis.z;
float fXYM = axis.x*axis.y*fOneMinusCos;
float fXZM = axis.x*axis.z*fOneMinusCos;
float fYZM = axis.y*axis.z*fOneMinusCos;
float fXSin = axis.x*fSin;
float fYSin = axis.y*fSin;
float fZSin = axis.z*fSin;
m[0] = fX2*fOneMinusCos + fCos;
m[4] = fXYM-fZSin;
m[8] = fXZM+fYSin;
m[1] = fXYM+fZSin;
m[5] = fY2*fOneMinusCos + fCos;
m[9] = fYZM-fXSin;
m[2] = fXZM-fYSin;
m[6] = fYZM+fXSin;
m[10] = fZ2*fOneMinusCos + fCos;
return m;
}
Matrix4 mat4RotationX(float rad, const Vector3& center)
{
return mat4Translation(center) * mat4RotationX(rad) * mat4Translation(-center);
}
Matrix4 mat4RotationY(float rad, const Vector3& center)
{
return mat4Translation(center) * mat4RotationY(rad) * mat4Translation(-center);
}
Matrix4 mat4RotationZ(float rad, const Vector3& center)
{
return mat4Translation(center) * mat4RotationZ(rad) * mat4Translation(-center);
}
Matrix4 mat4Frustum(float left, float right, float bottom, float top, float near, float far)
{
if (right == left)
return Matrix4();
if (top == bottom)
return Matrix4();
if (near == far)
return Matrix4();
Matrix4 m = Matrix4::ZERO;
m(0,0) = 2.0f * near / (right - left);
m(1,1) = 2.0f * near / (top - bottom);
m(0,2) = (right + left) / (right - left);
m(1,2) = (top + bottom) / (top - bottom);
m(2,2) = - (far + near) / (far - near);
m(3,2) = -1.0f;
m(2,3) = - (2.0f * far * near) / (far - near);
return m;
}
Matrix4 mat4FrustumInf(float left, float right, float bottom, float top, float near)
{
assert(right != left);
assert(top != bottom);
assert(near > 0.0f);
Matrix4 m = Matrix4::ZERO;
m(0,0) = 2.0f * near / (right - left);
m(1,1) = 2.0f * near / (top - bottom);
m(0,2) = (right + left) / (right - left);
m(1,2) = (top + bottom) / (top - bottom);
m(2,2) = -1.0f;
m(3,2) = -1.0f;
m(2,3) = - 2.0f * near;
return m;
}
Matrix4 mat4LookAt(const Vector3 &eye, const Vector3 ¢er, const Vector3 &up)
{
// Forward vector
Vector3 f = eye - center;
f.normalize();
// Right vector
Vector3 r = vec3Cross(up, f);
r.normalize();
// Up vector
Vector3 u = vec3Cross(f, r);
u.normalize();
// Create matrix
Matrix4 mat(r.x, r.y, r.z, 0.0f,
u.x, u.y, u.z, 0.0f,
f.x, f.y, f.z, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f );
return mat * mat4Translation(-eye);
}
| [
"hpsoar@6e3944b4-cba9-11de-a8df-5d31f88aefc0"
]
| [
[
[
1,
171
]
]
]
|
f1f9d7dcf064ccd313ba05a49e874d136e6d1af8 | bd89d3607e32d7ebb8898f5e2d3445d524010850 | /adaptationlayer/systemstatemanageradaptation/iscservice/src/sa_common_trace.cpp | c63bbbb8b2098c10dee62361c29384bc069d4717 | []
| 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 | 5,439 | cpp | /*
* ==============================================================================
* Name: sa_common_trace.cpp
* Part of: System adaptation
* Description: Implementation of System Adaptation common traces
* %version: 1 %
* %date_modified: Tue Dec 29 15:59:38 2009 %
*
* 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:
* Implementation of System Adaptation common traces
*
*/
// INCLUDE FILES
#include <e32std.h>
#include <pn_const.h>
#include "sa_common_trace.h"
#ifdef _DEBUG
// EXTERNAL DATA STRUCTURES
// EXTERNAL FUNCTION PROTOTYPES
// CONSTANTS
// MACROS
// LOCAL CONSTANTS AND MACROS
const TInt KSASDataDumpTraceBytesPerLine( 10 );
_LIT8( KSATraceBuildDate, __DATE__ );
_LIT8( KSATraceBuildTime, __TIME__ );
_LIT( KSATraceDataDumpStart, " [ " );
_LIT( KSATraceDataDumpLineAlign, " " );
_LIT( KSATraceDataDumpStop, " ] " );
_LIT( KSATraceDataDumpValue, "%02x " );
// MODULE DATA STRUCTURES
// LOCAL FUNCTION PROTOTYPES
// FORWARD DECLARATIONS
// ============================= TRACE FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// AssertTraceFunc
// -----------------------------------------------------------------------------
void AssertTraceFunc( const TDesC& aPrefix, const TDesC8& aFile, TInt aLine )
{
HBufC* buffer = HBufC::New( aFile.Length() + 1 );
HBufC* date = HBufC::New( 32 );
HBufC* time = HBufC::New( 32 );
if ( ( buffer ) && ( date ) && ( time ) )
{
buffer->Des().Copy( aFile );
date->Des().Copy( KSATraceBuildDate );
time->Des().Copy( KSATraceBuildTime );
RDebug::Print( _L( "%S Assertion failed: file=%S, line=%d, compiled=%S %S" ),
&aPrefix, buffer, aLine, date, time );
}
else
{
RDebug::Print( _L( "Assertion and memory allocation failed" ) );
}
delete buffer;
delete date;
delete time;
}
// -----------------------------------------------------------------------------
// BuildTraceFunc
// -----------------------------------------------------------------------------
void BuildTraceFunc( const TDesC& aPrefix )
{
HBufC* buffer = HBufC::New( aPrefix.Length() + 1 );
HBufC* date = HBufC::New( 32 );
HBufC* time = HBufC::New( 32 );
if ( ( buffer ) && ( date ) && ( time ) )
{
buffer->Des().Copy( aPrefix );
date->Des().Copy( KSATraceBuildDate );
time->Des().Copy( KSATraceBuildTime );
RDebug::Print( _L( "%s: compiled=%s %s" ), buffer->Des().PtrZ(),
date->Des().PtrZ(), time->Des().PtrZ() );
#ifdef __WINS__
RDebug::Print( _L( "%s: __WINS__ enabled" ),
buffer->Des().PtrZ() );
#else
RDebug::Print( _L( "%s: __WINS__ disabled" ),
buffer->Des().PtrZ() );
#endif
#ifdef _DEBUG
RDebug::Print( _L( "%s: _DEBUG enabled" ),
buffer->Des().PtrZ() );
#else
RDebug::Print( _L( "%s: _DEBUG disabled" ),
buffer->Des().PtrZ() );
#endif
#ifdef SA_MODULE_TEST_FLAG
RDebug::Print( _L( "%s: SA_MODULE_TEST_FLAG enabled" ),
buffer->Des().PtrZ() );
#else
RDebug::Print( _L( "%s: SA_MODULE_TEST_FLAG disabled" ),
buffer->Des().PtrZ() );
#endif
}
delete buffer;
delete date;
delete time;
}
// -----------------------------------------------------------------------------
// DataDumpTraceFunc
// -----------------------------------------------------------------------------
void DataDumpTraceFunc( const TDesC& aPrefix, const TDesC8& aData )
{
HBufC* buffer = HBufC::New( 255 ); // max line length
if ( buffer )
{
buffer->Des().Copy( aPrefix );
buffer->Des().Append( KSATraceDataDumpStart );
for ( TInt i = 0; i < aData.Length(); i++)
{
buffer->Des().AppendFormat( KSATraceDataDumpValue, aData[i] );
if( (i % KSASDataDumpTraceBytesPerLine == ( KSASDataDumpTraceBytesPerLine - 1 ) )
&& (i + 1 < aData.Length()) )
{
RDebug::Print( buffer->Des() );
buffer->Des().Copy( aPrefix);
buffer->Des().Append( KSATraceDataDumpLineAlign );
}
}
buffer->Des().Append( KSATraceDataDumpStop );
RDebug::Print( buffer->Des() );
}
delete buffer;
}
// -----------------------------------------------------------------------------
// IsiMsgApiTrace
// -----------------------------------------------------------------------------
void IsiMsgApiTrace(const TDesC& aPrefix, const TDesC8& aData)
{
}
#endif
// End of File
| [
"[email protected]",
"mikaruus@localhost"
]
| [
[
[
1,
143
],
[
145,
181
]
],
[
[
144,
144
]
]
]
|
b57e198358942fec2455a1a5d3c822e979a36345 | d401482b965150d50fed0b78782dac66a2e2807f | /Game.h | 663bd270f6f869364e6bb52b9fdabb285fcb817c | []
| no_license | skrgice/uno2java | 2832aebc3a7b2abe467e15338fcefeee3da7523d | 0ffe4bf6356d3c439d114299a016255d906c5c31 | refs/heads/master | 2021-01-10T20:58:18.592867 | 2009-02-24T17:08:21 | 2009-02-24T17:08:21 | 32,478,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,335 | h | #pragma once
//the game class draws and handles input
//as well as handling all logic for the rules
//associated with UNO
//such as, whether or not a player can play a
//card on the discard pile
//this game required extensive research into UNO's
//rule set and has been coded to portray them
#include <time.h> //srand
#include <windows.h>
#include "Deck.h"
#include "Player.h"
#include "Map.h"
#include "cli.h"
#include "cursor.h"
#include "gameDefines.h"
#include "trackingDeck.h"
class Game
{
private:
Deck m_drawDeck, m_discardPile;
Player * m_playerList;
int m_playerCount;
int m_currentPlayer;
Map m_mask[MASK_NUM];
cursor m_cursor;
int m_direction;
int m_gamestate;
char m_input;
char m_wildColor;
bool hasDrawn, cursorLocked, cardPlayed, skipEffect, wildSelect;
bool unoCalled, unoFailed;
bool m_wantsToQuit;
int m_round;
public:
Game();
Game(int a_playerCount, char * a_filename);
Game(char * a_filename);
void load(int a_playerCount, char * a_filename);
void load(char * a_filename);
int inputPlayerCount();
void setup();
void initDraw();
void draw();
void initDrawHUD();
void drawHUD();
void initDrawTopCard();
void drawTopCard();
void clearArea(int color, int x1, int x2, int y1, int y2);
void loadMasks();
void handleInput(char a_input);
void printUnoLogo(int x, int y);
void drawPlayerHand();
void initDrawPlayerHand();
void initText();
void setCursorLimits(int numOfCards);
void moveCursor(int direction, int numOfCards);
void drawCursor();
void addSelectedCardToPile();
bool isCardLegal(int card);
void setCardEffect(char type, char color);
void calcNextPlayer();
void processGameLogic();
void processGamePlay();
void processGameWild();
void drawWildSelection();
void drawHotSeat();
void drawControlsMenu();
void lockCursorToDrawnCard();
void penalty(int player);
void callUno();
void failureToCallUno();
bool wantToQuit();
void endTurn();
void clearUnos();
bool calcWin();
int calcScore();
int scoreChart(char color, char type);
void drawRoundOver();
void drawGameOver();
void reload();
void setInitEffect(char type, char color);
void setEndEffect(char type, char color);
bool okayToAddCard(int player);
bool isWild4Legal();
void drawTopCardWildColor();
}; | [
"mutantveggie@3873034e-f493-11dd-8c4e-4bbb75a408b7"
]
| [
[
[
1,
93
]
]
]
|
a9fd96e03fd89357af5af55bec38d553afaa5fff | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /src/Aran/ArnAnimationController.cpp | bbc09f08f370f3998e56898ff1406d94e9b2b8bb | []
| no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,325 | cpp | #include "AranPCH.h"
#include "ArnAnimationController.h"
#include "ArnIpo.h"
#include "Animation.h"
#include "ArnMath.h"
#include "ArnAction.h"
#include "ArnBone.h"
#include "ArnMesh.h"
#include "ArnConsts.h"
ArnAnimationController::ArnAnimationController()
: m_dTime(0)
, m_outputCount(0)
, m_actionCount(0)
, m_eventCount(0)
, m_curActionIdx(0)
{
}
ArnAnimationController::~ArnAnimationController()
{
foreach (ArnAction* act, m_actions)
{
delete act;
}
m_actions.clear();
}
ArnAnimationController*
ArnAnimationController::create( UINT MaxNumAnimationOutputs, UINT MaxNumAnimationSets, UINT MaxNumTracks, UINT MaxNumEvents )
{
ArnAnimationController* ret = new ArnAnimationController();
ret->m_outputs.resize(MaxNumAnimationOutputs);
ret->m_actions.resize(MaxNumAnimationSets);
ret->m_tracks.resize(MaxNumTracks);
ret->m_events.resize(MaxNumEvents);
return ret;
}
unsigned int
ArnAnimationController::RegisterAnimationSet( ArnAction* ARN_OWNERSHIP action )
{
if (m_actionCount < m_actions.size())
{
m_actions[m_actionCount] = action;
++m_actionCount;
return m_actionCount-1;
}
else
{
fprintf(stderr, " ** Animation set number exceeds on this controller.\n");
return 0;
}
}
HRESULT
ArnAnimationController::RegisterIpo( ArnIpo* ipo )
{
m_ipos.push_back(ipo);
return S_OK;
}
void ArnAnimationController::SetTrackAnimationSet( UINT trackNum, UINT actionIdx )
{
if (trackNum < m_tracks.size())
{
assert(actionIdx < m_actionCount);
m_tracks[trackNum].ActionIdx = actionIdx;
}
else
{
fprintf(stderr, " ** Track index out of range.\n");
}
}
void
ArnAnimationController::SetTrackPosition( UINT trackNum, double trackPos )
{
if (trackNum < m_tracks.size())
m_tracks[trackNum].Position = trackPos;
else
ARN_THROW_UNEXPECTED_CASE_ERROR
}
void
ArnAnimationController::SetTrackSpeed( UINT trackNum, float trackSpeed )
{
if (trackNum < m_tracks.size())
m_tracks[trackNum].Speed = trackSpeed;
else
ARN_THROW_UNEXPECTED_CASE_ERROR
}
void
ArnAnimationController::SetTrackWeight( UINT trackNum, float trackWeight )
{
if (trackNum < m_tracks.size())
m_tracks[trackNum].Weight = trackWeight;
else
ARN_THROW_UNEXPECTED_CASE_ERROR
}
void
ArnAnimationController::SetTrackEnable( UINT trackNum, bool bEnable )
{
if (trackNum < m_tracks.size())
m_tracks[trackNum].Enable = bEnable;
else
ARN_THROW_UNEXPECTED_CASE_ERROR
}
HRESULT
ArnAnimationController::RegisterAnimationOutput( const char* pName, ArnMatrix* pMatrix, ArnVec3* pScale, ArnQuat* pRotation, ArnVec3* pTranslation )
{
assert(pScale || pRotation || pTranslation == 0);
if (m_outputCount < m_outputs.size())
{
m_outputs[m_outputCount].name = pName;
m_outputs[m_outputCount].mat = pMatrix;
m_outputs[m_outputCount].scale = pScale;
m_outputs[m_outputCount].quat = pRotation;
m_outputs[m_outputCount].trans = pTranslation;
++m_outputCount;
return S_OK;
}
else
{
fprintf(stderr, " ** Animation set number exceeds on this controller.\n");
return E_FAIL;
}
}
void
ArnAnimationController::Release()
{
// TODO: Is there anything to release?
}
void
ArnAnimationController::AdvanceTime( double dTime, void* callBack /*= 0*/ )
{
/*
if (dTime == 0)
return;
*/
m_dTime += dTime;
float totalWeight = 0;
for (unsigned int i = 0; i < m_tracks.size(); ++i)
{
if (m_tracks[i].Enable)
totalWeight += m_tracks[i].Weight;
}
for (unsigned int i = 0; i < m_tracks.size(); ++i)
{
ARNTRACK_DESC& track = m_tracks[i];
if (!track.Enable)
continue;
//printf("%.3f\n", (float)(m_dTime - track.Position));
assert(track.ActionIdx < m_actionCount);
//float normalizedWeight = track.Weight / totalWeight;
typedef std::pair<ArnNode*, ArnIpo*> ObjIpoPair;
foreach (ObjIpoPair p, m_actions[track.ActionIdx]->getObjectIpoMap())
{
ArnIpo* ipo = p.second;
assert(ipo);
ArnVec3 transKey = CreateArnVec3(0,0,0);
ArnVec3 scaleKey = CreateArnVec3(1,1,1);
ArnVec3 rotKey = CreateArnVec3(0,0,0);
ArnQuat quat = CreateArnQuat(0, 0, 0, 0);
foreach (const CurveData& cd, ipo->getCurves())
{
float val = Animation::EvalCurveInterp(&cd, (float)(m_dTime - track.Position)*FPS);
switch (cd.name)
{
case CN_LocX: transKey.x = val; break;
case CN_LocY: transKey.y = val; break;
case CN_LocZ: transKey.z = val; break;
case CN_ScaleX: scaleKey.x = val; break;
case CN_ScaleY: scaleKey.y = val; break;
case CN_ScaleZ: scaleKey.z = val; break;
case CN_RotX: rotKey.x = ArnToRadian(val); break;
case CN_RotY: rotKey.y = ArnToRadian(val); break;
case CN_RotZ: rotKey.z = ArnToRadian(val); break;
case CN_QuatW: quat.w = val; break;
case CN_QuatX: quat.x = val; break;
case CN_QuatY: quat.y = val; break;
case CN_QuatZ: quat.z = val; break;
default: throw MyError(MEE_UNSUPPORTED_CURVENAME);
}
}
if (quat != ArnQuat(0, 0, 0, 0))
{
assert((rotKey.x || rotKey.y || rotKey.z) == 0);
}
else
{
quat = ArnEulerToQuat(&rotKey);
}
// TODO: Quaternion should be normalized before a making composed transformation matrix.
// Any way to make this routine faster?
quat /= quat.getLength();
NODE_DATA_TYPE ndt = p.first->getType();
if ( ndt == NDT_RT_MESH
|| ndt == NDT_RT_CAMERA
|| ndt == NDT_RT_LIGHT
|| ndt == NDT_RT_BONE
|| ndt == NDT_RT_SKELETON)
{
ArnXformable* xformable = static_cast<ArnXformable*>(p.first);
xformable->setAnimLocalXform_Scale(scaleKey);
xformable->setAnimLocalXform_Rot(quat);
xformable->setAnimLocalXform_Trans(transKey);
xformable->recalcAnimLocalXform();
}
if ((m_dTime > (track.Position + (float)ipo->getEndKeyframe()/FPS)) && ipo->getPlaybackType() == ARNPLAY_LOOP)
{
// Reset the time if the end of animation reached.
track.Position += (float)ipo->getEndKeyframe()/FPS;
}
}
}
}
HRESULT
ArnAnimationController::GetTrackDesc( UINT trackNum, ARNTRACK_DESC* pDesc )
{
memcpy(pDesc, &m_tracks[trackNum], sizeof(ARNTRACK_DESC));
return S_OK;
}
HRESULT
ArnAnimationController::GetAnimationSet( UINT Index, ArnIpo** ppAnimationSet )
{
ARN_THROW_NOT_IMPLEMENTED_ERROR
}
void
ArnAnimationController::ResetTime()
{
ARN_THROW_NOT_IMPLEMENTED_ERROR
}
int
ArnAnimationController::GetNumAnimationSets() const
{
ARN_THROW_NOT_IMPLEMENTED_ERROR
}
void
ArnAnimationController::UnregisterAnimationSet( ArnIpo* animSet )
{
ARN_THROW_NOT_IMPLEMENTED_ERROR
}
void ArnAnimationController::update( double fTime, float fElapsedTime )
{
AdvanceTime(fElapsedTime, 0);
}
void ArnAnimationController::SetActionToNext()
{
++m_curActionIdx;
if (m_curActionIdx >= m_actionCount)
m_curActionIdx = 0;
}
//////////////////////////////////////////////////////////////////////////
HRESULT ArnCreateAnimationController( UINT MaxNumMatrices, UINT MaxNumAnimationSets, UINT MaxNumTracks, UINT MaxNumEvents, ArnAnimationController** ppAnimController )
{
*ppAnimController = ArnAnimationController::create(MaxNumMatrices, MaxNumAnimationSets, MaxNumTracks, MaxNumEvents);
return S_OK;
}
| [
"[email protected]"
]
| [
[
[
1,
276
]
]
]
|
9bb3c155d62e11972c2979060e7fa1c88e7b3f8c | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Components/Transforms/TranslationTransform/elxTranslationTransform.h | 4006adeef2007318869dfa89451602385796005c | []
| no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,668 | h | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __elxTranslationTransform_H_
#define __elxTranslationTransform_H_
#include "itkAdvancedTranslationTransform.h"
#include "itkTranslationTransformInitializer.h"
#include "elxIncludes.h"
namespace elastix
{
using namespace itk;
/**
* \class TranslationTransformElastix
* \brief A transform based on the itk::TranslationTransform.
*
* This transform is a translation transformation.
*
* The parameters used in this class are:
* \parameter Transform: Select this transform as follows:\n
* <tt>(%Transform "TranslationTransform")</tt>
* \parameter AutomaticTransformInitialization: whether or not the initial translation
* between images should be estimated as the distance between their centers.\n
* example: <tt>(AutomaticTransformInitialization "true")</tt> \n
* By default "false" is assumed. So, no initial translation.
*
* \ingroup Transforms
*/
template < class TElastix >
class TranslationTransformElastix:
public AdvancedCombinationTransform<
ITK_TYPENAME elx::TransformBase<TElastix>::CoordRepType,
elx::TransformBase<TElastix>::FixedImageDimension > ,
public elx::TransformBase<TElastix>
{
public:
/** Standard ITK-stuff. */
typedef TranslationTransformElastix Self;
typedef AdvancedCombinationTransform<
typename elx::TransformBase<TElastix>::CoordRepType,
elx::TransformBase<TElastix>::FixedImageDimension > Superclass1;
typedef elx::TransformBase<TElastix> Superclass2;
/** The ITK-class that provides most of the functionality, and
* that is set as the "CurrentTransform" in the CombinationTransform */
typedef AdvancedTranslationTransform<
typename elx::TransformBase<TElastix>::CoordRepType,
elx::TransformBase<TElastix>::FixedImageDimension > TranslationTransformType;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( TranslationTransformElastix, AdvancedCombinationTransform );
/** Name of this class.
* Use this name in the parameter file to select this specific transform. \n
* example: <tt>(Transform "TranslationTransform")</tt>\n
*/
elxClassNameMacro( "TranslationTransform" );
/** Dimension of the domain space. */
itkStaticConstMacro( SpaceDimension, unsigned int, Superclass2::FixedImageDimension );
/** Typedefs inherited from the superclass. */
typedef typename Superclass1::ScalarType ScalarType;
typedef typename Superclass1::ParametersType ParametersType;
typedef typename Superclass1::JacobianType JacobianType;
typedef typename Superclass1::InputVectorType InputVectorType;
typedef typename Superclass1::OutputVectorType OutputVectorType;
typedef typename Superclass1::InputCovariantVectorType InputCovariantVectorType;
typedef typename Superclass1::OutputCovariantVectorType OutputCovariantVectorType;
typedef typename Superclass1::InputVnlVectorType InputVnlVectorType;
typedef typename Superclass1::OutputVnlVectorType OutputVnlVectorType;
typedef typename Superclass1::InputPointType InputPointType;
typedef typename Superclass1::OutputPointType OutputPointType;
/** Typedef's from the TransformBase class. */
typedef typename Superclass2::ElastixType ElastixType;
typedef typename Superclass2::ElastixPointer ElastixPointer;
typedef typename Superclass2::ConfigurationType ConfigurationType;
typedef typename Superclass2::ConfigurationPointer ConfigurationPointer;
typedef typename Superclass2::RegistrationType RegistrationType;
typedef typename Superclass2::RegistrationPointer RegistrationPointer;
typedef typename Superclass2::CoordRepType CoordRepType;
typedef typename Superclass2::FixedImageType FixedImageType;
typedef typename Superclass2::MovingImageType MovingImageType;
typedef typename Superclass2::ITKBaseType ITKBaseType;
typedef typename Superclass2::CombinationTransformType CombinationTransformType;
/** Extra typedefs */
typedef TranslationTransformInitializer<
TranslationTransformType,
FixedImageType,
MovingImageType> TransformInitializerType;
typedef typename TransformInitializerType::Pointer TransformInitializerPointer;
typedef typename TranslationTransformType::Pointer TranslationTransformPointer;
/** Execute stuff before the actual registration:
* \li Call InitializeTransform.
*/
virtual void BeforeRegistration(void);
/** Initialize Transform.
* \li Set all parameters to zero.
* \li Set initial translation:
* the initial translation between fixed and moving image is guessed,
* if the user has set (AutomaticTransformInitialization "true").
*/
virtual void InitializeTransform(void);
protected:
/** The constructor. */
TranslationTransformElastix();
/** The destructor. */
virtual ~TranslationTransformElastix() {};
TranslationTransformPointer m_TranslationTransform;
private:
/** The private constructor. */
TranslationTransformElastix( const Self& ); // purposely not implemented
/** The private copy constructor. */
void operator=( const Self& ); // purposely not implemented
}; // end class TranslationTransformElastix
} // end namespace elastix
#ifndef ITK_MANUAL_INSTANTIATION
#include "elxTranslationTransform.hxx"
#endif
#endif // end #ifndef __elxTranslationTransform_H_
| [
"[email protected]"
]
| [
[
[
1,
157
]
]
]
|
78c0e1bb9f04cf6e8efb1bc243ff7d78749c839a | f25e9e8fd224f81cefd6d900f6ce64ce77abb0ae | /Exercises/Old Solutions/OpenGL5/OpenGL5/SceneNode.h | fc99c60e03391fa73423c404cc7a3b87a9246a78 | []
| no_license | giacomof/gameengines2010itu | 8407be66d1aff07866d3574a03804f2f5bcdfab1 | bc664529a429394fe5743d5a76a3d3bf5395546b | refs/heads/master | 2016-09-06T05:02:13.209432 | 2010-12-12T22:18:19 | 2010-12-12T22:18:19 | 35,165,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,201 | h | #pragma once
#ifndef sceneNode__H__
#define sceneNode__H__
#include "globals.h"
#include <SDL_mutex.h>
#include <string>
#include <list>
#include "linearAlgebraDLL.h" // Header File for our math library
#include "transformation.h"
#include "sceneObject.h"
#include "assetManager.h"
#include <btBulletDynamicsCommon.h>
using namespace linearAlgebraDLL;
using namespace std;
class SceneNode
{
public:
SDL_mutex *mutex_node; // Mutex for the Node
// default constructor
SceneNode() { mutex_node = SDL_CreateMutex(); };
// actual constructor
SceneNode( SceneNode * parentNode, char * str, SceneObject * g /*= 0*/,
Vector v,
Vector p_axis, float p_angle,
btRigidBody * rigidBody = 0);
// destructor
virtual ~SceneNode() { destroy(); }
// delete object
void release() { /*SDL_DestroyMutex ( mutex_node );*/ }
void update(float dt);
void destroy(void);
// add a child
void addChild( SceneNode * pNode );
// detach a child
//void detachChild( SceneNode & cNode );
// set parent node
void setParent ( SceneNode * pNode );
// get parent node
SceneNode* getParent(void);
// set the node name
void setName(char * name);
// get the node name
char * getName(void);
bool isVisible(void);
void setVisible(bool b);
void addSceneObject(SceneObject * g);
SceneObject* getSceneObject();
void rotateAboutAxis(Vector p_Axis, float p_Degree);
void translate(Vector translateVector);
void scale(float p_sX, float p_sY, float p_sZ);
void shear(float p_sxy, float p_sxz, float p_syx, float p_syz, float p_szx, float p_szy);
void setPosition(Vector t);
void setOrientation(Quaternion q);
Vector getWorldPosition(void);
Quaternion getWorldOrientation(void);
Transformation * getTransformation();
void applyTransformation(void);
void SceneNode::removeTransformation(void);
void drawGeometry(void);
void drawName(void);
string nodeNameString;
static unsigned int getNodeCount(void);
protected:
bool visible; // The node should be drawn or not
int id; // Unique id
char * nodeName; // Name
SceneNode * parentNode; // Parent Node
list<SceneNode*> childList; // List of child Nodes
Transformation nodeTransformation; // Transformation of the Node
SceneObject * geometry; // Mesh to render
btRigidBody * physicsGeometry;
void updateRigidBody(void);
};
class Root : public SceneNode
{
public: // Singleton
static Root _instance;
static SDL_mutex * rootMutex;
Root(void) { &getInstance(); }
//~Root(void);
Root(const Root &getInstance());
Root & operator=(Root &getInstance());
static Root &getInstance();
// set parent node
static void setParent( SceneNode * pNode );
// get parent node
static SceneNode * getParent(void);
// Update all the children
static void update(float dt);
// Draw the geometry of all the children
static void drawGeometry(void);
static list<SceneNode*> childOfRootList;
static unsigned int id;
static string nodeName;
};
#endif | [
"[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d",
"[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d"
]
| [
[
[
1,
2
],
[
7,
30
],
[
32,
53
],
[
55,
55
],
[
57,
79
],
[
81,
81
],
[
84,
89
],
[
91,
135
]
],
[
[
3,
6
],
[
31,
31
],
[
54,
54
],
[
56,
56
],
[
80,
80
],
[
82,
83
],
[
90,
90
],
[
136,
136
]
]
]
|
716c6cc80709f42793192f78355ff599a6029370 | 550e17ad61efc7bea2066db5844663c8b5835e4f | /Examples/Tutorial/UserInterface/10Container.cpp | 4be423d5416d31c62134f94dfe794e4397c018de | []
| no_license | danguilliams/OpenSGToolbox | 9287424c66c9c4b38856cf749a311f15d8aac4f0 | 102a9fb02ad1ceeaf5784e6611c2862c4ba84d61 | refs/heads/master | 2021-01-17T23:02:36.528911 | 2010-11-01T16:56:31 | 2010-11-01T16:56:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,009 | cpp | // OpenSG Tutorial Example: Using Containers (Frames and Panels)
//
// This tutorial explains how use Frame and Panel Containers
//
// Includes: creating and editing Frames, Panels, and adding
// Panels
// Note: in almost all cases, each Scene should have only ONE
// Frame, but may have unlimited Panels.
// General OpenSG configuration, needed everywhere
#include "OSGConfig.h"
// Methods to create simple geometry: boxes, spheres, tori etc.
#include "OSGSimpleGeometry.h"
// A little helper to simplify scene management and interaction
#include "OSGSimpleSceneManager.h"
#include "OSGNode.h"
#include "OSGGroup.h"
#include "OSGViewport.h"
// The general scene file loading handler
#include "OSGSceneFileHandler.h"
// Input
#include "OSGWindowUtils.h"
// UserInterface Headers
#include "OSGUIForeground.h"
#include "OSGInternalWindow.h"
#include "OSGUIDrawingSurface.h"
#include "OSGGraphics2D.h"
#include "OSGLookAndFeelManager.h"
// Activate the OpenSG namespace
OSG_USING_NAMESPACE
// The SimpleSceneManager to manage simple applications
SimpleSceneManager *mgr;
WindowEventProducerRefPtr TutorialWindow;
// Forward declaration so we can have the interesting stuff upfront
void display(void);
void reshape(Vec2f Size);
// 10Container Headers
#include "OSGButton.h"
#include "OSGLineBorder.h"
#include "OSGColorLayer.h"
#include "OSGAbsoluteLayout.h"
#include "OSGAbsoluteLayoutConstraints.h"
#include "OSGBoxLayout.h"
#include "OSGFlowLayout.h"
#include "OSGComponentContainer.h"
#include "OSGPanel.h"
#include "OSGLineBorder.h"
#include "OSGBevelBorder.h"
// Create a class to allow for the use of the Ctrl+q
class TutorialKeyListener : public KeyListener
{
public:
virtual void keyPressed(const KeyEventUnrecPtr e)
{
if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND)
{
TutorialWindow->closeWindow();
}
}
virtual void keyReleased(const KeyEventUnrecPtr e)
{
}
virtual void keyTyped(const KeyEventUnrecPtr e)
{
}
};
int main(int argc, char **argv)
{
// OSG init
osgInit(argc,argv);
// Set up Window
TutorialWindow = createNativeWindow();
TutorialWindow->initWindow();
TutorialWindow->setDisplayCallback(display);
TutorialWindow->setReshapeCallback(reshape);
TutorialKeyListener TheKeyListener;
TutorialWindow->addKeyListener(&TheKeyListener);
// Make Torus Node (creates Torus in background of scene)
NodeRefPtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);
// Make Main Scene Node and add the Torus
NodeRefPtr scene = OSG::Node::create();
scene->setCore(OSG::Group::create());
scene->addChild(TorusGeometryNode);
// Create the Graphics
GraphicsRefPtr TutorialGraphics = OSG::Graphics2D::create();
// Initialize the LookAndFeelManager to enable default settings
LookAndFeelManager::the()->getLookAndFeel()->init();
/******************************************************
Creates some Button components
and edit their Text.
******************************************************/
ButtonRefPtr ExampleButton1 = OSG::Button::create();
ButtonRefPtr ExampleButton2 = OSG::Button::create();
ButtonRefPtr ExampleButton3 = OSG::Button::create();
ButtonRefPtr ExampleButton4 = OSG::Button::create();
ButtonRefPtr ExampleButton5 = OSG::Button::create();
ButtonRefPtr ExampleButton6 = OSG::Button::create();
ExampleButton1->setText("This");
ExampleButton2->setText("is a");
ExampleButton3->setText("sample");
ExampleButton4->setText("two");
ExampleButton5->setText("ExamplePanel");
ExampleButton6->setText("layout");
/******************************************************
Create some Flow and BoxLayouts to be
used with the Main Frame and two
Panels.
******************************************************/
FlowLayoutRefPtr MainInternalWindowLayout = OSG::FlowLayout::create();
FlowLayoutRefPtr ExamplePanel1Layout = OSG::FlowLayout::create();
FlowLayoutRefPtr ExamplePanel2Layout = OSG::FlowLayout::create();
ExamplePanel1Layout->setOrientation(FlowLayout::VERTICAL_ORIENTATION);
/******************************************************
Create two Backgrounds to be used with
Panels and MainInternalWindow.
******************************************************/
ColorLayerRefPtr MainInternalWindowBackground = OSG::ColorLayer::create();
ColorLayerRefPtr ExamplePanelBackground = OSG::ColorLayer::create();
MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
ExamplePanelBackground->setColor(Color4f(0.0,0.0,0.0,1.0));
/******************************************************
Create a Border to be used with
the two Panels.
******************************************************/
LineBorderRefPtr ExamplePanelBorder = OSG::LineBorder::create();
ExamplePanelBorder->setColor(Color4f(0.9, 0.9, 0.9, 1.0));
ExamplePanelBorder->setWidth(3);
/******************************************************
Create MainInternalWindow and two Panel Components and
edit their characteristics.
-setPreferredSize(Vec2f): Determine the
size of the Panel.
-pushToChildren(ComponentName):
Adds a Component to the
ComponentContainer as a Child (meaning it
will be displayed within it).
-setLayout(LayoutName): Determines the
Layout of the ComponentContainer.
******************************************************/
InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
PanelRefPtr ExamplePanel1 = OSG::Panel::create();
PanelRefPtr ExamplePanel2 = OSG::Panel::create();
// Edit Panel1, Panel2
ExamplePanel1->setPreferredSize(Vec2f(200, 200));
ExamplePanel1->pushToChildren(ExampleButton1);
ExamplePanel1->pushToChildren(ExampleButton2);
ExamplePanel1->pushToChildren(ExampleButton3);
ExamplePanel1->setLayout(ExamplePanel1Layout);
ExamplePanel1->setBackgrounds(ExamplePanelBackground);
ExamplePanel1->setBorders(ExamplePanelBorder);
ExamplePanel2->setPreferredSize(Vec2f(200, 200));
ExamplePanel2->pushToChildren(ExampleButton4);
ExamplePanel2->pushToChildren(ExampleButton5);
ExamplePanel2->pushToChildren(ExampleButton6);
ExamplePanel2->setLayout(ExamplePanel2Layout);
ExamplePanel2->setBackgrounds(ExamplePanelBackground);
ExamplePanel2->setBorders(ExamplePanelBorder);
// Create The Main InternalWindow
MainInternalWindow->pushToChildren(ExamplePanel1);
MainInternalWindow->pushToChildren(ExamplePanel2);
MainInternalWindow->setLayout(MainInternalWindowLayout);
MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.5f,0.5f));
MainInternalWindow->setDrawTitlebar(false);
MainInternalWindow->setResizable(false);
MainInternalWindow->setAllInsets(5);
// Create the Drawing Surface
UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create();
TutorialDrawingSurface->setGraphics(TutorialGraphics);
TutorialDrawingSurface->setEventProducer(TutorialWindow);
TutorialDrawingSurface->openWindow(MainInternalWindow);
// Create the UI Foreground Object
UIForegroundRefPtr TutorialUIForeground = OSG::UIForeground::create();
TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);
// Create the SimpleSceneManager helper
mgr = new SimpleSceneManager;
// Tell the Manager what to manage
mgr->setWindow(TutorialWindow);
mgr->setRoot(scene);
// Add the UI Foreground Object to the Scene
ViewportRefPtr TutorialViewport = mgr->getWindow()->getPort(0);
TutorialViewport->addForeground(TutorialUIForeground);
// Show the whole Scene
mgr->showAll();
//Open Window
Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
TutorialWindow->openWindow(WinPos,
WinSize,
"10Container");
//Enter main Loop
TutorialWindow->mainLoop();
osgExit();
return 0;
}
// Callback functions
// Redraw the window
void display(void)
{
mgr->redraw();
}
// React to size changes
void reshape(Vec2f Size)
{
mgr->resize(Size.x(), Size.y());
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
12
],
[
14,
15
],
[
17,
18
],
[
23,
24
],
[
26,
27
],
[
29,
30
],
[
36,
41
],
[
43,
45
],
[
47,
48
],
[
60,
60
],
[
83,
88
],
[
94,
94
],
[
98,
98
],
[
100,
101
],
[
104,
106
],
[
108,
119
],
[
126,
146
],
[
150,
150
],
[
152,
156
],
[
158,
159
],
[
162,
162
],
[
164,
172
],
[
174,
179
],
[
181,
182
],
[
184,
184
],
[
186,
186
],
[
188,
189
],
[
191,
192
],
[
196,
197
],
[
202,
202
],
[
205,
205
],
[
210,
210
],
[
225,
225
],
[
227,
227
],
[
229,
229
],
[
232,
232
],
[
234,
240
],
[
242,
244
],
[
247,
250
],
[
263,
275
],
[
277,
277
]
],
[
[
13,
13
],
[
16,
16
],
[
19,
22
],
[
25,
25
],
[
28,
28
],
[
31,
35
],
[
42,
42
],
[
46,
46
],
[
49,
59
],
[
61,
82
],
[
89,
93
],
[
95,
97
],
[
99,
99
],
[
102,
103
],
[
107,
107
],
[
120,
125
],
[
147,
149
],
[
151,
151
],
[
157,
157
],
[
160,
161
],
[
163,
163
],
[
173,
173
],
[
180,
180
],
[
183,
183
],
[
185,
185
],
[
187,
187
],
[
190,
190
],
[
193,
195
],
[
198,
201
],
[
203,
204
],
[
206,
209
],
[
211,
224
],
[
226,
226
],
[
228,
228
],
[
230,
231
],
[
233,
233
],
[
241,
241
],
[
245,
246
],
[
251,
262
],
[
276,
276
],
[
278,
279
]
]
]
|
a59782cf43f73ae93ceac7ac286d662bf9455ade | 69aab86a56c78cdfb51ab19b8f6a71274fb69fba | /Code/src/Game.cpp | f5cee38d8a2aaa7a15d2e86a18927a52f1b27063 | [
"BSD-3-Clause"
]
| permissive | zc5872061/wonderland | 89882b6062b4a2d467553fc9d6da790f4df59a18 | b6e0153eaa65a53abdee2b97e1289a3252b966f1 | refs/heads/master | 2021-01-25T10:44:13.871783 | 2011-08-11T20:12:36 | 2011-08-11T20:12:36 | 38,088,714 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,879 | cpp | /*
* Game.cpp
*
* Created on: 2010-12-03
* Author: artur.m
*/
#include "Game.h"
#include "pi.h"
#include <cstdlib>
#include <ctime>
#include "GLRenderer.h"
#include "MathHelper.h"
#include "Actor.h"
#include "Board.h"
#include "Ball.h"
#include "BallsInformations.h"
Game* Game::s_instance = null;
Game& Game::getInstance()
{
if(s_instance == null)
{
s_instance = new Game();
}
return *s_instance;
}
void Game::cleanup()
{
delete s_instance;
s_instance = null;
}
Game::Game()
{
srand((unsigned int)time(null));
}
Game::~Game()
{
delete m_renderer;
delete m_resources;
delete m_meshes;
delete m_physics;
delete m_materialsManager;
}
void Game::initialize(std::auto_ptr<GameController> controller)
{
Log("New renderer");
m_renderer = new GLRenderer();
Log("New resources");
m_resources = new ResourceManager();
Log("New meshes");
m_meshes = new MeshManager();
Log("New physics");
m_physics = new PhysicsEngine();
Log("New materials");
m_materialsManager = new MaterialsManager();
m_gameController = controller;
Log("New fonts");
m_fontEngine = new FontEngine();
Log("Fonts initialized");
getFontEngine().initialize();
#ifndef SHP
getRenderer().initialize();
#endif
Log("Renderer initialize");
getRenderer().getCamera().initialize(Constants::SCREEN_NARROW, Constants::SCREEN_WIDE, 30, 1, 100, Vector(0, 0, -26));
Log("Resources initialize");
getResourceManager().initialize();
Log("Materials initialize");
getMaterialsManager().initialize();
Log("Game controller initialize");
m_gameController->initialize();
}
void Game::setHud(std::auto_ptr<HUD> hud)
{
Log("Hud set and initialize");
setHUD(hud);
getHUD().initialize();
}
#ifndef IOS
bool Game::initializeGraphics(EGLNativeWindowType window)
{
return getRenderer().initialize(window);
}
#endif
void Game::update(int milis)
{
deleteActors();
m_gameController->update(milis);
m_physics->update(milis);
}
void Game::touchPressed(int x, int y)
{
Log("Touch pressed - %d:%d", x, y);
if(m_hud->touchPressed(x, y))
{
return;
}
m_gameController->touchPressed(x, y);
}
void Game::touchReleased(int x, int y)
{
if(m_hud->touchReleased(x, y))
{
return;
}
m_gameController->touchReleased(x, y);
}
GLRenderer& Game::getRenderer()
{
return *m_renderer;
}
ResourceManager& Game::getResourceManager()
{
return *m_resources;
}
MeshManager& Game::getMeshManager()
{
return *m_meshes;
}
GameController* Game::getGameController()
{
return m_gameController.get();
}
void Game::setHUD(std::auto_ptr<HUD> hud)
{
m_hud = hud;
}
PhysicsEngine& Game::getPhysicsEngine()
{
return *m_physics;
}
MaterialsManager& Game::getMaterialsManager()
{
return *m_materialsManager;
}
FontEngine& Game::getFontEngine()
{
return *m_fontEngine;
}
HUD& Game::getHUD()
{
return *m_hud;
}
void Game::deleteActors()
{
DeletedContainer copy(m_actorsToDelete);
m_actorsToDelete.clear(); // this is done so that in an Actor's destructor it will be possible to destroy some Actor
copy.clear();
}
void Game::add(shared_ptr<Actor> actor)
{
getGameController()->addActor(actor);
getRenderer().draw(actor.get());
getPhysicsEngine().addActor(actor);
}
void Game::remove(shared_ptr<Actor> actor)
{
// shared_pointer created below will be destroyed in the next invocation
// of update for the Game. This is done this way so that actors will be able to
// do safely something like "delete this"
m_actorsToDelete.push_back(actor);
getGameController()->removeActor(actor);
getRenderer().drop(actor.get());
getPhysicsEngine().removeActor(actor);
}
| [
"[email protected]"
]
| [
[
[
1,
197
]
]
]
|
447b2be1370c84e109c5fbc052f5d44835fbb976 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/ogre/OgreNewt/boost/mpl/map/aux_/has_key_impl.hpp | ecd7ea24d28b848037458ebeb580f559853e9d11 | []
| 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,255 | hpp |
#ifndef BOOST_MPL_MAP_AUX_HAS_KEY_IMPL_HPP_INCLUDED
#define BOOST_MPL_MAP_AUX_HAS_KEY_IMPL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2003-2004
// Copyright David Abrahams 2003-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/map/aux_/has_key_impl.hpp,v $
// $Date: 2006/04/17 23:49:40 $
// $Revision: 1.1 $
#include <boost/mpl/has_key_fwd.hpp>
#include <boost/mpl/map/aux_/tag.hpp>
#include <boost/mpl/map/aux_/at_impl.hpp>
#include <boost/mpl/void.hpp>
#include <boost/mpl/aux_/config/typeof.hpp>
namespace boost { namespace mpl {
template<>
struct has_key_impl< aux::map_tag >
{
template< typename Map, typename Key > struct apply
#if defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES)
: is_not_void_<
typename at_impl<aux::map_tag>
::apply<Map,Key>::type
>
#else
: bool_< ( x_order_impl<Map,Key>::value > 1 ) >
#endif
{
};
};
}}
#endif // BOOST_MPL_MAP_AUX_HAS_KEY_IMPL_HPP_INCLUDED
| [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
]
| [
[
[
1,
44
]
]
]
|
07dabe954152ea80755f9e35e8251c24763b08da | 12732dc8a5dd518f35c8af3f2a805806f5e91e28 | /trunk/sdk/wxflatnotebook/src/wxFlatNotebook/popup_dlg.cpp | fda5166180102cad7a67fc297d45936c5f517399 | []
| no_license | BackupTheBerlios/codelite-svn | 5acd9ac51fdd0663742f69084fc91a213b24ae5c | c9efd7873960706a8ce23cde31a701520bad8861 | refs/heads/master | 2020-05-20T13:22:34.635394 | 2007-08-02T21:35:35 | 2007-08-02T21:35:35 | 40,669,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,383 | cpp | #include <wx/wxFlatNotebook/popup_dlg.h>
#include <wx/listctrl.h>
#include <wx/wxFlatNotebook/wxFlatNotebook.h>
#include <wx/wxFlatNotebook/renderer.h>
#include <wx/listbox.h>
#include <wx/image.h>
//#include <wx/mstream.h>
#include <wx/wxFlatNotebook/fnb_resources.h>
wxBitmap wxTabNavigatorWindow::m_bmp;
wxTabNavigatorWindow::wxTabNavigatorWindow(wxWindow* parent)
: m_listBox(NULL)
, m_selectedItem(-1)
, m_panel(NULL)
{
Create(parent);
GetSizer()->Fit(this);
GetSizer()->SetSizeHints(this);
GetSizer()->Layout();
Centre();
}
wxTabNavigatorWindow::wxTabNavigatorWindow()
: wxDialog()
, m_listBox(NULL)
, m_selectedItem(-1)
, m_panel(NULL)
{
}
wxTabNavigatorWindow::~wxTabNavigatorWindow()
{
}
void wxTabNavigatorWindow::Create(wxWindow* parent)
{
long style = 0;
if( !wxDialog::Create(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, style) )
return;
wxBoxSizer *sz = new wxBoxSizer( wxVERTICAL );
SetSizer( sz );
long flags = wxLB_SINGLE | wxNO_BORDER ;
m_listBox = new wxListBox(this, wxID_ANY, wxDefaultPosition, wxSize(200, 150), 0, NULL, flags);
static int panelHeight = 0;
if( panelHeight == 0 )
{
wxMemoryDC mem_dc;
// bitmap must be set before it can be used for anything
wxBitmap bmp(10, 10);
mem_dc.SelectObject(bmp);
wxFont font(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
font.SetWeight( wxBOLD );
mem_dc.SetFont(font);
int w;
mem_dc.GetTextExtent(wxT("Tp"), &w, &panelHeight);
panelHeight += 4; // Place a spacer of 2 pixels
// Out signpost bitmap is 24 pixels
if( panelHeight < 24 )
panelHeight = 24;
}
m_panel = new wxPanel( this, wxID_ANY, wxDefaultPosition, wxSize(200, panelHeight));
sz->Add( m_panel );
sz->Add( m_listBox, 1, wxEXPAND );
SetSizer( sz );
// Connect events to the list box
m_listBox->Connect(wxID_ANY, wxEVT_KEY_UP, wxKeyEventHandler(wxTabNavigatorWindow::OnKeyUp), NULL, this);
//Connect(wxEVT_CHAR_HOOK, wxCharEventHandler(wxTabNavigatorWindow::OnKeyUp), NULL, this);
m_listBox->Connect(wxID_ANY, wxEVT_NAVIGATION_KEY, wxNavigationKeyEventHandler(wxTabNavigatorWindow::OnNavigationKey), NULL, this);
m_listBox->Connect(wxID_ANY, wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, wxCommandEventHandler(wxTabNavigatorWindow::OnItemSelected), NULL, this);
// Connect paint event to the panel
m_panel->Connect(wxID_ANY, wxEVT_PAINT, wxPaintEventHandler(wxTabNavigatorWindow::OnPanelPaint), NULL, this);
m_panel->Connect(wxID_ANY, wxEVT_ERASE_BACKGROUND, wxEraseEventHandler(wxTabNavigatorWindow::OnPanelEraseBg), NULL, this);
SetBackgroundColour( wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE) );
m_listBox->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_3DFACE));
PopulateListControl( static_cast<wxFlatNotebook*>( parent ) );
// Create the bitmap, only once
if( !m_bmp.Ok() )
{
wxImage img(signpost_xpm);
img.SetAlpha(signpost_alpha, true);
m_bmp = wxBitmap(img);
}
}
void wxTabNavigatorWindow::OnKeyUp(wxKeyEvent &event)
{
if(event.GetKeyCode() == WXK_CONTROL)
{
CloseDialog();
}
}
void wxTabNavigatorWindow::OnNavigationKey(wxNavigationKeyEvent &event)
{
long selected = m_listBox->GetSelection();
wxFlatNotebook* bk = static_cast<wxFlatNotebook*>(GetParent());
long maxItems = bk->GetPageCount();
long itemToSelect;
if( event.GetDirection() )
{
// Select next page
if (selected == maxItems - 1)
itemToSelect = 0;
else
itemToSelect = selected + 1;
}
else
{
// Previous page
if( selected == 0 )
itemToSelect = maxItems - 1;
else
itemToSelect = selected - 1;
}
m_listBox->SetSelection( itemToSelect );
}
void wxTabNavigatorWindow::PopulateListControl(wxFlatNotebook *book)
{
int selection = book->GetSelection();
//int count = book->GetPageCount();
std::map<int, bool> temp;
m_listBox->Append( book->GetPageText(static_cast<int>(selection)) );
m_indexMap[0] = selection;
temp[selection] = true;
const wxArrayInt &arr = book->GetBrowseHistory();
for(size_t i=0; i<arr.GetCount(); i++)
{
if(temp.find(arr.Item(i)) == temp.end()){
m_listBox->Append( book->GetPageText(static_cast<int>(arr.Item(i))) );
m_indexMap[(int)m_listBox->GetCount()-1] = arr.Item(i);
temp[arr.Item(i)] = true;
}
}
// Select the next entry after the current selection
m_listBox->SetSelection( 0 );
wxNavigationKeyEvent dummy;
dummy.SetDirection(true);
OnNavigationKey(dummy);
}
void wxTabNavigatorWindow::OnItemSelected(wxCommandEvent & event )
{
wxUnusedVar( event );
CloseDialog();
}
void wxTabNavigatorWindow::CloseDialog()
{
wxFlatNotebook* bk = static_cast<wxFlatNotebook*>(GetParent());
m_selectedItem = m_listBox->GetSelection();
std::map<int, int>::iterator iter = m_indexMap.find(m_selectedItem);
bk->SetSelection( iter->second );
EndModal( wxID_OK );
}
void wxTabNavigatorWindow::OnPanelPaint(wxPaintEvent &event)
{
wxUnusedVar(event);
wxPaintDC dc(m_panel);
wxRect rect = m_panel->GetClientRect();
static bool first = true;
static wxBitmap bmp( rect.width, rect.height );
if( first )
{
first = false;
wxMemoryDC mem_dc;
mem_dc.SelectObject( bmp );
wxColour endColour( wxSystemSettings::GetColour(wxSYS_COLOUR_BTNSHADOW) );
wxColour startColour( wxFNBRenderer::LightColour(endColour, 50) );
wxFNBRenderer::PaintStraightGradientBox(mem_dc, rect, startColour, endColour);
// Draw the caption title and place the bitmap
wxPoint bmpPt;
wxPoint txtPt;
// get the bitmap optimal position, and draw it
bmpPt.y = (rect.height - m_bmp.GetHeight()) / 2;
bmpPt.x = 3;
mem_dc.DrawBitmap( m_bmp, bmpPt, true );
// get the text position, and draw it
int fontHeight(0), w(0);
wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
font.SetWeight( wxBOLD );
mem_dc.SetFont( font );
mem_dc.GetTextExtent( wxT("Tp"), &w, &fontHeight );
txtPt.x = bmpPt.x + m_bmp.GetWidth() + 4;
txtPt.y = (rect.height - fontHeight)/2;
mem_dc.SetTextForeground( *wxWHITE );
mem_dc.DrawText( wxT("Opened tabs:"), txtPt );
mem_dc.SelectObject( wxNullBitmap );
}
dc.DrawBitmap( bmp, 0, 0 );
}
void wxTabNavigatorWindow::OnPanelEraseBg(wxEraseEvent &event)
{
wxUnusedVar(event);
}
| [
"eranif@b1f272c1-3a1e-0410-8d64-bdc0ffbdec4b"
]
| [
[
[
1,
225
]
]
]
|
125c01545c43fbffa88605dc1c045a5567b7efc9 | b411e4861bc1478147bfc289c868b961a6136ead | /tags/DownhillRacing/Texture.h | 3e78b157ac3bf6dc1a2aa49faa92a2bc6d982148 | []
| no_license | mvm9289/downhill-racing | d05df2e12384d8012d5216bc0b976bc7df9ff345 | 038ec4875db17a7898282d6ced057d813a0243dc | refs/heads/master | 2021-01-20T12:20:31.383595 | 2010-12-19T23:29:02 | 2010-12-19T23:29:02 | 32,334,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | h | #pragma once
#include <gl/glut.h>
#pragma comment (lib, "corona")
class Texture
{
private:
GLuint id;
int width;
int height;
public:
Texture(void);
virtual ~Texture(void);
bool load(char *filename, int type = GL_RGBA, int wraps = GL_REPEAT, int wrapt = GL_REPEAT,
int magf = GL_LINEAR, int minf = GL_LINEAR, bool mipmap = false);
int getID();
void getSize(int *w, int *h);
};
| [
"mvm9289@06676c28-b993-0703-7cf1-698017e0e3c1"
]
| [
[
[
1,
22
]
]
]
|
9c722dd6300b20a464ccaf778072f5f01e5efa47 | 3daaefb69e57941b3dee2a616f62121a3939455a | /mgllib-test/mgl_test/mgl_test.cpp | 5aca77973f1258a681ed6bb21b1c4c9db17e228c | []
| no_license | myun2ext/open-mgl-legacy | 21ccadab8b1569af8fc7e58cf494aaaceee32f1e | 8faf07bad37a742f7174b454700066d53a384eae | refs/heads/master | 2016-09-06T11:41:14.108963 | 2009-12-28T12:06:58 | 2009-12-28T12:06:58 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 13,337 | cpp | #include "stdafx.h"
#include "mgl3d.h"
#include "dx_graphic.h"
#include <math.h>
LPDIRECT3DVERTEXBUFFER8 pVB = NULL; // 頂点バッファに使うオブジェクト
#define PI (3.1415926535f)
void GameMain(CMglTexture *pTexture);
void GameMain2(CMglTexture *pTexture);
// ----------------------------------------------------------------------------
// 頂点の定義
struct CUSTOMVERTEX
{
FLOAT x, y, z; // 位置
DWORD color; // 色
};
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE)
// ----------------------------------------------------------------------------
// Name: Render()
// Desc: ポリゴンの初期化
//-----------------------------------------------------------------------------
HRESULT InitRender(LPDIRECT3DDEVICE8 lpD3DDEV)
{
CUSTOMVERTEX vertices[] =
{
// x, y, z, color
{ 0.0f, 0.0f, 0.0f, D3DCOLOR_RGBA(0xff, 0xff, 0xff, 0xff), },
{ 1.0f, 0.0f, 0.0f, D3DCOLOR_RGBA(0xff, 0x00, 0x00, 0xff), },
{ 0.0f, 1.0f, 0.0f, D3DCOLOR_RGBA(0x00, 0xff, 0x00, 0xff), },
{ 0.0f, 0.0f, 1.0f, D3DCOLOR_RGBA(0x00, 0x00, 0xff, 0xff), },
{ 1.0f, 0.0f, 0.0f, D3DCOLOR_RGBA(0xff, 0x00, 0x00, 0xff), },
};
HRESULT hr;
hr = lpD3DDEV->CreateVertexBuffer( 5*sizeof(CUSTOMVERTEX),0,
D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &pVB);
if(FAILED(hr)) return E_FAIL;
VOID* pVertices;
hr = pVB->Lock( 0, sizeof(vertices), (BYTE**)&pVertices, 0);
if(FAILED(hr)) return E_FAIL;
memcpy( pVertices, vertices, sizeof(vertices) );
pVB->Unlock();
lpD3DDEV->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
lpD3DDEV->SetRenderState(D3DRS_LIGHTING, FALSE);
/* D3DXVECTOR3 vecDir;
D3DLIGHT8 light;
ZeroMemory( &light, sizeof(D3DLIGHT8) );
light.Type = D3DLIGHT_DIRECTIONAL;
light.Diffuse.r = 1.0f;
light.Diffuse.g = 0.3f;
light.Diffuse.b = 0.3f;
vecDir = D3DXVECTOR3(-1.0f, -1.0f, -0.1f);
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );
light.Range = 1000.0f;
lpD3DDEV->SetLight( 0, &light );
lpD3DDEV->LightEnable( 0, TRUE );
lpD3DDEV->SetRenderState( D3DRS_LIGHTING, TRUE );
lpD3DDEV->SetRenderState( D3DRS_AMBIENT, 0x00ffffff );*/
return S_OK;
}
LPD3DXMESH pMesh = NULL; // メッシュ
D3DMATERIAL8 *pMeshMaterials = NULL; // メッシュの質感
LPDIRECT3DTEXTURE8 *pMeshTextures = NULL; // メッシュのテクスチャー
DWORD dwNumMaterials = 0L; // マテリアルの数
// ----------------------------------------------------------------------------
// Name: Render()
// Desc: ポリゴンの初期化
//-----------------------------------------------------------------------------
HRESULT InitRender2(LPDIRECT3DDEVICE8 lpD3DDEV)
{
HRESULT hr;
LPD3DXBUFFER pD3DXMtrlBuffer;
// X ファイルのロード
hr = D3DXLoadMeshFromX( "car.x", D3DXMESH_SYSTEMMEM,
lpD3DDEV, NULL,
&pD3DXMtrlBuffer, &dwNumMaterials,
&pMesh );
if(FAILED(hr)) return E_FAIL;
// pD3DXMtrlBuffer から、質感やテクスチャーの情報を読み取る
D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer();
pMeshMaterials = new D3DMATERIAL8[dwNumMaterials];
pMeshTextures = new LPDIRECT3DTEXTURE8[dwNumMaterials];
for( DWORD i=0; i < dwNumMaterials; i++ ){
pMeshMaterials[i] = d3dxMaterials[i].MatD3D;// 質感のコピー
pMeshMaterials[i].Ambient = pMeshMaterials[i].Diffuse;// マテリアルの環境色を設定する
hr = D3DXCreateTextureFromFile( lpD3DDEV,
d3dxMaterials[i].pTextureFilename,
&pMeshTextures[i] );
if(FAILED(hr)) pMeshTextures[i] = NULL;
}
SAFE_RELEASE(pD3DXMtrlBuffer);
lpD3DDEV->SetRenderState( D3DRS_ZENABLE, TRUE);
D3DXVECTOR3 vecDir;
D3DLIGHT8 light;
ZeroMemory( &light, sizeof(D3DLIGHT8) );
light.Type = D3DLIGHT_DIRECTIONAL;
light.Diffuse.r = 1.0f;
light.Diffuse.g = 0.3f;
light.Diffuse.b = 0.3f;
vecDir = D3DXVECTOR3(-1.0f, -1.0f, -0.1f);
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );
light.Range = 1000.0f;
lpD3DDEV->SetLight( 0, &light );
lpD3DDEV->LightEnable( 0, TRUE );
lpD3DDEV->SetRenderState( D3DRS_LIGHTING, TRUE );
lpD3DDEV->SetRenderState( D3DRS_AMBIENT, 0x00202020 );
return S_OK;
}
// ----------------------------------------------------------------------------
// Name: Render()
// Desc: ポリゴンの描画
//-----------------------------------------------------------------------------
void Render(LPDIRECT3DDEVICE8 lpD3DDEV)
{
static int i=0;
i++;
D3DXMATRIX mWorld, mRotX, mRotY, mTrans;
float time = (float)timeGetTime();
//TODO: D3DXMatrixRotationY(&mRotY, time/600.0f);
//D3DXMatrixRotationY(&mRotY, 600.0f);
//D3DXMatrixRotationY(&mRotY, 60.0f);
D3DXMatrixRotationY(&mRotY, 0.0f);
// D3DXMatrixRotationX(&mRotX, time/300.0f);
D3DXMatrixRotationX(&mRotX, 0.0f);
D3DXMatrixTranslation(&mTrans, 0,0,0.0f);
mWorld = mRotX * mRotY * mTrans;
D3DXMATRIX mView, mProj;
/*
static POINT from;
D3DXMATRIX d3dm;
D3DXVECTOR3 view(0,2.0f,2.0f);
D3DXMatrixRotationY(&mView , D3DXToRadian(2);
mView = view;
view.x = mView.x * d3dm.m[0][0] +
mView.y * d3dm.m[1][0] + mView.z * d3dm.m[2][0];
view.y = mView.x * d3dm.m[0][1] +
mView.y * d3dm.m[1][1] + mView.z * d3dm.m[2][1];
view.z = mView.x * d3dm.m[0][2] +
mView.y * d3dm.m[1][2] + mView.z * d3dm.m[2][2];
view.y += from.y - (lp >> 16);
*/
D3DXMatrixLookAtLH(&mView
//,&D3DXVECTOR3(0-(i/100.0f),2.0f,2.0f-(i/100.0f)) // カメラ位置
,&D3DXVECTOR3(0-(i/100.0f),2.0f,2.0f) // カメラ位置
//,&mView // カメラ位置
//,&D3DXVECTOR3(0+(i/1000.0f),0,0) // カメラの注目点
,&D3DXVECTOR3(0+(i/1000.0f),0,0) // カメラの注目点
,&D3DXVECTOR3(0,1,0) // 上の向き
);
D3DXMatrixPerspectiveFovLH(&mProj
,60.0f*PI/180.0f // 視野角
,1.0f // アスペクト比
,0.01f // 最近接距離
,100.0f // 最遠方距離
);
lpD3DDEV->SetTransform(D3DTS_WORLD, &mWorld);
lpD3DDEV->SetTransform(D3DTS_VIEW, &mView);
lpD3DDEV->SetTransform(D3DTS_PROJECTION, &mProj);
lpD3DDEV->SetStreamSource( 0, pVB, sizeof(CUSTOMVERTEX) );
lpD3DDEV->SetVertexShader( D3DFVF_CUSTOMVERTEX );
lpD3DDEV->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 3 );
}
void Render2(LPDIRECT3DDEVICE8 lpD3DDEV)
{
D3DXMATRIX mWorld;
D3DXMatrixRotationY( &mWorld, timeGetTime()/1000.0f );
D3DXMATRIX mView, mProj;
D3DXMatrixLookAtLH( &mView, &D3DXVECTOR3( 0.0f, 3.0f, 4.0f ),
&D3DXVECTOR3( 0.0f, 0.0f, 0.0f ),
&D3DXVECTOR3( 0.0f, 1.0f, 0.0f ) );
D3DXMatrixPerspectiveFovLH(&mProj
,60.0f*PI/180.0f // 視野角
,1.0f // アスペクト比
,0.01f // 最近接距離
,100.0f // 最遠方距離
);
lpD3DDEV->SetTransform(D3DTS_WORLD, &mWorld);
lpD3DDEV->SetTransform(D3DTS_VIEW, &mView);
lpD3DDEV->SetTransform(D3DTS_PROJECTION, &mProj);
for( DWORD i=0; i < dwNumMaterials; i++ ){
lpD3DDEV->SetMaterial( &pMeshMaterials[i] );
lpD3DDEV->SetTexture( 0, pMeshTextures[i] );
pMesh->DrawSubset( i );
}
}
///////////////////////////////////////////////////////////////////
// メインフレームクラス
class CMglTestFrame : public CAugustWindow
{
private:
CAugustImage m_img;
CAugustText m_text;
CMgl3dImage m_img2;
public:
void OnInit(){
RegistControl(&m_img);
RegistControl(&m_text);
m_img.Load("test.jpg");
m_img2.CreateTextureFromFile("font_big.tga");
m_text.SetText("hoge");
m_text.SetFontSize(64);
m_text.SetColor(0x77000000);
m_audio.Load("hoge.wav");
m_audio.Load("hoge2.wav");
// キーボードイベントハンドラ登録
RegistKbHandler(
AUGUST_KB_EVT_HANDLER_EVTTYPE_ON_KEYDOWN,
DIK_Z,
(AUGUST_KB_EVT_HANDLER_CALLBACK)PlaySoundZ);
// キーボードイベントハンドラ登録
RegistKbHandler(
AUGUST_KB_EVT_HANDLER_EVTTYPE_ON_KEYDOWN,
DIK_X,
(AUGUST_KB_EVT_HANDLER_CALLBACK)PlaySoundX);
this->EnableEscEnd();
//////////////////////////////
InitRender(grp.GetD3dDevPtr());
//InitRender2(grp.GetD3dDevPtr());
}
/*bool DoFrame(){
Render(grp.GetD3dDevPtr());
return CAugustWindow::DoFrame();
}*/
void OnDraw(){
grp.Clear(0);
//Render(grp.GetD3dDevPtr());
//Render2(grp.GetD3dDevPtr());
// カメラ
static int i=0;
i++;
//grp.p3d->SetCamera( 0.0f+(sin(i/90.0f)*3), 0.0f, -3.0f+(1.0f-cos(i/90.0f))*3, 0,0,0 );
//grp.p3d->CameraRotation(MGL3D_Z, 1);
//grp.p3d->SetCameraAngle2(i/100.0f,0,0);
//grp.p3d->SetupProjection(
grp.p3d->MoveCamera(0.0015f,0.0005f,0.02f);
//grp.p3d->SetCamera( 0.0f+(sin(i/90.0f)*3), 0.0f, -3.0f+(sin((3.14159265/2)+i/90.0f))*3, 0,0,0 );
//grp.p3d->SetCamera( 0, 0.0f, -3.0f+(i/100.0f), 0,0,0 );
/*grp.p3d->SetCamera( 0-(i/100.0f),2.0f,2.0f-(i/100.0f),
0,0,0 );*/
grp.p3d->ReTransform();
g_pD3DDevice = grp.GetD3dDevPtr();
//GameMain(m_img2.GetDirect3dTexturePtr());
GameMain(&m_img2);
m_img2.Draw(0.05f,0.05f,-0.05f);
//GameMain2(&m_img2);
grp.SpriteEnd();
grp.SpriteBegin();
//GetVCtrlPtr(0)->Draw();
}
bool PlaySoundZ(){
m_audio.Play("hoge.wav");
return true;
}
bool PlaySoundX(){
m_audio.Play("hoge2.wav");
return true;
}
};
CMglTestFrame g_frame;
// WinMain
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow )
{
g_frame.Start();
return 0;
}
D3D_COORDINATE g_WorldFrame(D3DXVECTOR3(1,1,1), D3DXVECTOR3(0,0,0), D3DXVECTOR3(0,0,0));
void GameMain(CMglTexture* pTexture)
{
D3DCOLOR color = 0xffffffff;
// 頂点初期情報取得
MGL_SQUARE_VERTEXS vertexs;
pTexture->GetBmpVertexs( &vertexs );
// x, yに移動
//MglMoveVertexs( &vertexs, 0, 0 );
// 頂点の色
vertexs.lt.color = color;
vertexs.rt.color = color;
vertexs.lb.color = color;
vertexs.rb.color = color;
vertexs.lt.x /= 100;
vertexs.rt.x /= 100;
vertexs.lb.x /= 100;
vertexs.rb.x /= 100;
vertexs.lt.y /= 100;
vertexs.rt.y /= 100;
vertexs.lb.y /= 100;
vertexs.rb.y /= 100;
/////////////////////////////////////////////////////
g_pD3DDevice->SetTexture(0, pTexture->GetDirect3dTexturePtr()); // テクスチャをセット
// デバイスに使用する頂点フォーマットをセットする(光源無し、座標変換有り)
g_pD3DDevice->SetVertexShader(FVF_MYU_VERTEX);
// マトリックス生成
//g_WorldFrame.rotate.y += 0.01f; // Y軸回りに回転
//g_WorldFrame.SetMat(); // 座標変換用マトリックス作成
//g_pD3DDevice->SetTransform(D3DTS_WORLD, &g_WorldFrame.mat); // ワールドマトリックスセット
// 頂点バッファを使用せず直接データを渡して描画する
g_pD3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, &vertexs, sizeof(MGL_VERTEX));
}
inline void GrpLVertexSet2(MGL_VERTEX *v, float x, float y, float z, float tu, float tv, D3DCOLOR rgba)
{
v->x = x;
v->y = y;
v->z = z;
v->color = rgba;
//v->rhw = 1.0f;
v->tu = tu;
v->tv = tv;
}
void GameMain2(CMglTexture* pTexture)
{
static int i=0;
i++;
g_pD3DDevice->SetTexture(0, pTexture->GetDirect3dTexturePtr()); // テクスチャをセット
// 頂点情報設定(トライアングルストリップ形式)
// 頂点、X、Y、Z、テクスチャU、テクスチャV、RGBA
MGL_VERTEX v[4]; // 光源無し、座標変換有り頂点
GrpLVertexSet2(&v[0], -1, 1, 0, 0, 0, D3DCOLOR_RGBA(255, 255, 255, 255));
GrpLVertexSet2(&v[1], 1, 1, 0, 1, 0, D3DCOLOR_RGBA(255, 255, 255, 255));
GrpLVertexSet2(&v[2], -1,-1, 0, 0, 1, D3DCOLOR_RGBA(255, 255, 255, 255));
GrpLVertexSet2(&v[3], 1,-1, 0, 1, 1, D3DCOLOR_RGBA(255, 255, 255, 255));
D3DCOLOR color = 0xffffffff;
/////////////////////////////////////////////////////
// デバイスに使用する頂点フォーマットをセットする(光源無し、座標変換有り)
//g_pD3DDevice->SetVertexShader(D3DFVF_LVERTEX);
g_pD3DDevice->SetVertexShader(FVF_MYU_VERTEX);
// マトリックス生成
//g_WorldFrame.rotate.y += 0.01f; // Y軸回りに回転
g_WorldFrame.SetMat(); // 座標変換用マトリックス作成
g_pD3DDevice->SetTransform(D3DTS_WORLD, &g_WorldFrame.mat); // ワールドマトリックスセット
// 頂点バッファを使用せず直接データを渡して描画する
//g_pD3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(D3DLVERTEX));
g_pD3DDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, sizeof(MGL_VERTEX));
}
| [
"myun2@6d62ff88-fa28-0410-b5a4-834eb811a934"
]
| [
[
[
1,
418
]
]
]
|
97ad27e179677869ca9d8faa25ac3d72cdfec4c8 | 028d6009f3beceba80316daa84b628496a210f8d | /uidesigner/com.nokia.sdt.referenceprojects.test/data2/lists_3_0/reference/src/lists_3_0Document.cpp | 12887aa0125df0e877e561fc7cb2ead1a8eb9b2d | []
| no_license | JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp | fa50cafa69d3e317abf0db0f4e3e557150fd88b3 | 4420f338bc4e522c563f8899d81201857236a66a | refs/heads/master | 2020-12-30T16:45:28.474973 | 2010-10-20T16:19:31 | 2010-10-20T16:19:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,289 | cpp | // [[[ begin generated region: do not modify [Generated User Includes]
#include "lists_3_0Document.h"
#include "lists_3_0AppUi.h"
// ]]] end generated region [Generated User Includes]
/**
* @brief Constructs the document class for the application.
* @param anApplication the application instance
*/
Clists_3_0Document::Clists_3_0Document( CEikApplication& anApplication )
: CAknDocument( anApplication )
{
}
/**
* @brief Completes the second phase of Symbian object construction.
* Put initialization code that could leave here.
*/
void Clists_3_0Document::ConstructL()
{
}
/**
* Symbian OS two-phase constructor.
*
* Creates an instance of Clists_3_0Document, constructs it, and
* returns it.
*
* @param aApp the application instance
* @return the new Clists_3_0Document
*/
Clists_3_0Document* Clists_3_0Document::NewL( CEikApplication& aApp )
{
Clists_3_0Document* self = new ( ELeave ) Clists_3_0Document( aApp );
CleanupStack::PushL( self );
self->ConstructL();
CleanupStack::Pop( self );
return self;
}
/**
* @brief Creates the application UI object for this document.
* @return the new instance
*/
CEikAppUi* Clists_3_0Document::CreateAppUiL()
{
return new ( ELeave ) Clists_3_0AppUi;
}
| [
"[email protected]"
]
| [
[
[
1,
49
]
]
]
|
68adea8b121abaabde667b2aaef7cd8f58cb652c | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-04-24/pcbnew/editmod.cpp | 7b0ad03cffe3de8781d3a95a8658f0c4f7cfc89b | []
| 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 | IBM852 | C++ | false | false | 4,531 | cpp | /************************************************/
/* Module editor: Dialog box for editing module */
/* properties and carateristics */
/************************************************/
#include "fctsys.h"
#include "gr_basic.h"
#include "common.h"
#include "pcbnew.h"
#include "autorout.h"
#include "trigo.h"
#include "bitmaps.h"
#include "3d_struct.h"
#include "3d_viewer.h"
#include "protos.h"
/* Variables locales: */
bool GoToEditor = FALSE;
/**************************************/
/* class WinEDA_ModulePropertiesFrame */
/**************************************/
#include "dialog_edit_module.cpp"
/*******************************************************************/
void WinEDA_BasePcbFrame::InstallModuleOptionsFrame(MODULE * Module,
wxDC * DC, const wxPoint & pos)
/*******************************************************************/
/* Fonction relai d'installation de la frame d'Údition des proprietes
du module*/
{
WinEDA_ModulePropertiesFrame * frame = new WinEDA_ModulePropertiesFrame(this,
Module, DC, pos);
frame->ShowModal(); frame->Destroy();
if ( GoToEditor && GetScreen()->m_CurrentItem )
{
if (m_Parent->m_ModuleEditFrame == NULL )
{
m_Parent->m_ModuleEditFrame = new WinEDA_ModuleEditFrame(this,
m_Parent,_("Module Editor"),
wxPoint(-1, -1), wxSize(600,400) );
}
m_Parent->m_ModuleEditFrame->Load_Module_Module_From_BOARD(
(MODULE*)GetScreen()->m_CurrentItem);
GetScreen()->m_CurrentItem = NULL;
GoToEditor = FALSE;
m_Parent->m_ModuleEditFrame->Show(TRUE);
m_Parent->m_ModuleEditFrame->Iconize(FALSE);
}
}
/*******************************************************************/
void WinEDA_ModuleEditFrame::Place_Ancre(MODULE* pt_mod , wxDC * DC)
/*******************************************************************/
/*
Repositionne l'ancre sous le curseur souris
Le module doit etre d'abort selectionne
*/
{
int deltaX, deltaY;
EDA_BaseStruct * PtStruct;
D_PAD * pt_pad;
if(pt_mod == NULL) return ;
pt_mod->DrawAncre(DrawPanel, DC, wxPoint(0,0), DIM_ANCRE_MODULE, GR_XOR);
deltaX = pt_mod->m_Pos.x - GetScreen()->m_Curseur.x;
deltaY = pt_mod->m_Pos.y - GetScreen()->m_Curseur.y;
pt_mod->m_Pos = GetScreen()->m_Curseur;
/* Mise a jour des coord relatives des elements:
les coordonnees relatives sont relatives a l'ancre, pour orient 0.
il faut donc recalculer deltaX et deltaY en orientation 0 */
RotatePoint(&deltaX, &deltaY, - pt_mod->m_Orient);
/* Mise a jour des coord relatives des pads */
pt_pad = (D_PAD*)pt_mod->m_Pads;
for( ; pt_pad != NULL; pt_pad = (D_PAD*) pt_pad->Pnext)
{
pt_pad->m_Pos0.x += deltaX; pt_pad->m_Pos0.y += deltaY;
}
/* Mise a jour des coord relatives contours .. */
PtStruct = pt_mod->m_Drawings;
for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext)
{
switch( PtStruct->m_StructType)
{
case TYPEEDGEMODULE:
#undef STRUCT
#define STRUCT ((EDGE_MODULE*) PtStruct)
STRUCT->m_Start0.x += deltaX; STRUCT->m_Start0.y += deltaY;
STRUCT->m_End0.x += deltaX; STRUCT->m_End0.y += deltaY;
break;
case TYPETEXTEMODULE:
#undef STRUCT
#define STRUCT ((TEXTE_MODULE*) PtStruct)
STRUCT->m_Pos0.x += deltaX; STRUCT->m_Pos0.y += deltaY;
break;
default:
break;
}
}
pt_mod->Set_Rectangle_Encadrement();
pt_mod->DrawAncre(DrawPanel, DC, wxPoint(0,0), DIM_ANCRE_MODULE, GR_OR);
}
/**********************************************************************/
void WinEDA_ModuleEditFrame::RemoveStruct(EDA_BaseStruct * Item, wxDC * DC)
/**********************************************************************/
{
if ( Item == NULL ) return;
switch( Item->m_StructType )
{
case TYPEPAD:
DeletePad( (D_PAD*) Item, DC);
break;
case TYPETEXTEMODULE:
{
TEXTE_MODULE * text = (TEXTE_MODULE *) Item;
if ( text->m_Type == TEXT_is_REFERENCE )
{
DisplayError(this, _("Text is REFERENCE!") );
break;
}
if ( text->m_Type == TEXT_is_VALUE )
{
DisplayError(this, _("Text is VALUE!") );
break;
}
DeleteTextModule(text, DC);
}
break;
case TYPEEDGEMODULE:
Delete_Edge_Module((EDGE_MODULE *) Item, DC);
break;
case TYPEMODULE:
break;
default:
{
wxString Line;
Line.Printf( wxT(" Remove: StructType %d Inattendu"),
Item->m_StructType);
DisplayError(this, Line);
}
break;
}
}
| [
"fcoiffie@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
166
]
]
]
|
bd2a9c844d7bbccd96e63864b0b9ca94c1744cbb | 7255cd8bfe095854bb1f4dfb38a71c221f92262c | /math/math3d.cpp | 209417f179cecf1a6d07368f04d9dfd172e6177f | []
| no_license | leavittx/re | 5e97ea2ff6905767e47b568be1066450eb6f9b7f | 83e388b99ced2fc8502a0bf4ead9a1696897b974 | refs/heads/master | 2020-04-15T21:43:24.841947 | 2011-10-18T20:17:10 | 2011-10-18T20:17:10 | 2,357,548 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,968 | cpp | // math3d.cpp
// Math3D Library, version 0.95
/* Copyright (c) 2007-2009, Richard S. Wright Jr.
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 Richard S. Wright Jr. nor the names of other 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.
*/
// Implementation file for the Math3d library. The C-Runtime has math.h, these routines
// are meant to suppliment math.h by adding geometry/math routines
// useful for graphics, simulation, and physics applications (3D stuff).
// This library is meant to be useful on Win32, Mac OS X, various Linux/Unix distros,
// and mobile platforms. Although designed with OpenGL in mind, there are no OpenGL
// dependencies. Other than standard math routines, the only other outside routine
// used is memcpy (for faster copying of vector arrays).
// Most of the library is inlined. Some functions however are here as I judged them
// too big to be inlined all over the place... nothing prevents anyone from changing
// this if it better fits their project requirements.
// Richard S. Wright Jr.
// Most functions are in-lined... and are defined here
#include "math3d.h"
////////////////////////////////////////////////////////////
// LoadIdentity
// For 3x3 and 4x4 float and double matricies.
// 3x3 float
void m3dLoadIdentity33(M3DMatrix33f m)
{
// Don't be fooled, this is still column major
static M3DMatrix33f identity = { 1.0f, 0.0f, 0.0f ,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f };
memcpy(m, identity, sizeof(M3DMatrix33f));
}
// 3x3 double
void m3dLoadIdentity33(M3DMatrix33d m)
{
// Don't be fooled, this is still column major
static M3DMatrix33d identity = { 1.0, 0.0, 0.0 ,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0 };
memcpy(m, identity, sizeof(M3DMatrix33d));
}
// 4x4 float
void m3dLoadIdentity44(M3DMatrix44f m)
{
// Don't be fooled, this is still column major
static M3DMatrix44f identity = { 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f };
memcpy(m, identity, sizeof(M3DMatrix44f));
}
// 4x4 double
void m3dLoadIdentity44(M3DMatrix44d m)
{
static M3DMatrix44d identity = { 1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0 };
memcpy(m, identity, sizeof(M3DMatrix44d));
}
////////////////////////////////////////////////////////////////////////
// Return the square of the distance between two points
// Should these be inlined...?
float m3dGetDistanceSquared3(const M3DVector3f u, const M3DVector3f v)
{
float x = u[0] - v[0];
x = x*x;
float y = u[1] - v[1];
y = y*y;
float z = u[2] - v[2];
z = z*z;
return (x + y + z);
}
// Ditto above, but for doubles
double m3dGetDistanceSquared3(const M3DVector3d u, const M3DVector3d v)
{
double x = u[0] - v[0];
x = x*x;
double y = u[1] - v[1];
y = y*y;
double z = u[2] - v[2];
z = z*z;
return (x + y + z);
}
#define A(row,col) a[(col<<2)+row]
#define B(row,col) b[(col<<2)+row]
#define P(row,col) product[(col<<2)+row]
///////////////////////////////////////////////////////////////////////////////
// Multiply two 4x4 matricies
void m3dMatrixMultiply44(M3DMatrix44f product, const M3DMatrix44f a, const M3DMatrix44f b )
{
for (int i = 0; i < 4; i++) {
float ai0=A(i,0), ai1=A(i,1), ai2=A(i,2), ai3=A(i,3);
P(i,0) = ai0 * B(0,0) + ai1 * B(1,0) + ai2 * B(2,0) + ai3 * B(3,0);
P(i,1) = ai0 * B(0,1) + ai1 * B(1,1) + ai2 * B(2,1) + ai3 * B(3,1);
P(i,2) = ai0 * B(0,2) + ai1 * B(1,2) + ai2 * B(2,2) + ai3 * B(3,2);
P(i,3) = ai0 * B(0,3) + ai1 * B(1,3) + ai2 * B(2,3) + ai3 * B(3,3);
}
}
// Ditto above, but for doubles
void m3dMatrixMultiply44(M3DMatrix44d product, const M3DMatrix44d a, const M3DMatrix44d b )
{
for (int i = 0; i < 4; i++) {
double ai0=A(i,0), ai1=A(i,1), ai2=A(i,2), ai3=A(i,3);
P(i,0) = ai0 * B(0,0) + ai1 * B(1,0) + ai2 * B(2,0) + ai3 * B(3,0);
P(i,1) = ai0 * B(0,1) + ai1 * B(1,1) + ai2 * B(2,1) + ai3 * B(3,1);
P(i,2) = ai0 * B(0,2) + ai1 * B(1,2) + ai2 * B(2,2) + ai3 * B(3,2);
P(i,3) = ai0 * B(0,3) + ai1 * B(1,3) + ai2 * B(2,3) + ai3 * B(3,3);
}
}
#undef A
#undef B
#undef P
#define A33(row,col) a[(col*3)+row]
#define B33(row,col) b[(col*3)+row]
#define P33(row,col) product[(col*3)+row]
///////////////////////////////////////////////////////////////////////////////
// Multiply two 3x3 matricies
void m3dMatrixMultiply33(M3DMatrix33f product, const M3DMatrix33f a, const M3DMatrix33f b )
{
for (int i = 0; i < 3; i++) {
float ai0=A33(i,0), ai1=A33(i,1), ai2=A33(i,2);
P33(i,0) = ai0 * B33(0,0) + ai1 * B33(1,0) + ai2 * B33(2,0);
P33(i,1) = ai0 * B33(0,1) + ai1 * B33(1,1) + ai2 * B33(2,1);
P33(i,2) = ai0 * B33(0,2) + ai1 * B33(1,2) + ai2 * B33(2,2);
}
}
// Ditto above, but for doubles
void m3dMatrixMultiply33(M3DMatrix33d product, const M3DMatrix33d a, const M3DMatrix33d b )
{
for (int i = 0; i < 3; i++) {
double ai0=A33(i,0), ai1=A33(i,1), ai2=A33(i,2);
P33(i,0) = ai0 * B33(0,0) + ai1 * B33(1,0) + ai2 * B33(2,0);
P33(i,1) = ai0 * B33(0,1) + ai1 * B33(1,1) + ai2 * B33(2,1);
P33(i,2) = ai0 * B33(0,2) + ai1 * B33(1,2) + ai2 * B33(2,2);
}
}
#undef A33
#undef B33
#undef P33
////////////////////////////////////////////////////////////////////////////////////////////
// Create a projection matrix
// Similiar to the old gluPerspective... fov is in radians btw...
void m3dMakePerspectiveMatrix(M3DMatrix44f mProjection, float fFov, float fAspect, float zMin, float zMax)
{
m3dLoadIdentity44(mProjection); // Fastest way to get most valid values already in place
float yMax = zMin * tanf(fFov * 0.5f);
float yMin = -yMax;
float xMin = yMin * fAspect;
float xMax = -xMin;
mProjection[0] = (2.0f * zMin) / (xMax - xMin);
mProjection[5] = (2.0f * zMin) / (yMax - yMin);
mProjection[8] = (xMax + xMin) / (xMax - xMin);
mProjection[9] = (yMax + yMin) / (yMax - yMin);
mProjection[10] = -((zMax + zMin) / (zMax - zMin));
mProjection[11] = -1.0f;
mProjection[14] = -((2.0f * (zMax*zMin))/(zMax - zMin));
mProjection[15] = 0.0f;
}
///////////////////////////////////////////////////////////////////////////////
// Make a orthographic projection matrix
void m3dMakeOrthographicMatrix(M3DMatrix44f mProjection, float xMin, float xMax, float yMin, float yMax, float zMin, float zMax)
{
m3dLoadIdentity44(mProjection);
mProjection[0] = 2.0f / (xMax - xMin);
mProjection[5] = 2.0f / (yMax - yMin);
mProjection[10] = -2.0f / (zMax - zMin);
mProjection[12] = -((xMax + xMin)/(xMax - xMin));
mProjection[13] = -((yMax + yMin)/(yMax - yMin));
mProjection[14] = -((zMax + zMin)/(zMax - zMin));
mProjection[15] = 1.0f;
}
#define M33(row,col) m[col*3+row]
///////////////////////////////////////////////////////////////////////////////
// Creates a 3x3 rotation matrix, takes radians NOT degrees
void m3dRotationMatrix33(M3DMatrix33f m, float angle, float x, float y, float z)
{
float mag, s, c;
float xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c;
s = float(sin(angle));
c = float(cos(angle));
mag = float(sqrt( x*x + y*y + z*z ));
// Identity matrix
if (mag == 0.0f) {
m3dLoadIdentity33(m);
return;
}
// Rotation matrix is normalized
x /= mag;
y /= mag;
z /= mag;
xx = x * x;
yy = y * y;
zz = z * z;
xy = x * y;
yz = y * z;
zx = z * x;
xs = x * s;
ys = y * s;
zs = z * s;
one_c = 1.0f - c;
M33(0,0) = (one_c * xx) + c;
M33(0,1) = (one_c * xy) - zs;
M33(0,2) = (one_c * zx) + ys;
M33(1,0) = (one_c * xy) + zs;
M33(1,1) = (one_c * yy) + c;
M33(1,2) = (one_c * yz) - xs;
M33(2,0) = (one_c * zx) - ys;
M33(2,1) = (one_c * yz) + xs;
M33(2,2) = (one_c * zz) + c;
}
#undef M33
///////////////////////////////////////////////////////////////////////////////
// Creates a 4x4 rotation matrix, takes radians NOT degrees
void m3dRotationMatrix44(M3DMatrix44f m, float angle, float x, float y, float z)
{
float mag, s, c;
float xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c;
s = float(sin(angle));
c = float(cos(angle));
mag = float(sqrt( x*x + y*y + z*z ));
// Identity matrix
if (mag == 0.0f) {
m3dLoadIdentity44(m);
return;
}
// Rotation matrix is normalized
x /= mag;
y /= mag;
z /= mag;
#define M(row,col) m[col*4+row]
xx = x * x;
yy = y * y;
zz = z * z;
xy = x * y;
yz = y * z;
zx = z * x;
xs = x * s;
ys = y * s;
zs = z * s;
one_c = 1.0f - c;
M(0,0) = (one_c * xx) + c;
M(0,1) = (one_c * xy) - zs;
M(0,2) = (one_c * zx) + ys;
M(0,3) = 0.0f;
M(1,0) = (one_c * xy) + zs;
M(1,1) = (one_c * yy) + c;
M(1,2) = (one_c * yz) - xs;
M(1,3) = 0.0f;
M(2,0) = (one_c * zx) - ys;
M(2,1) = (one_c * yz) + xs;
M(2,2) = (one_c * zz) + c;
M(2,3) = 0.0f;
M(3,0) = 0.0f;
M(3,1) = 0.0f;
M(3,2) = 0.0f;
M(3,3) = 1.0f;
#undef M
}
///////////////////////////////////////////////////////////////////////////////
// Ditto above, but for doubles
void m3dRotationMatrix33(M3DMatrix33d m, double angle, double x, double y, double z)
{
double mag, s, c;
double xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c;
s = sin(angle);
c = cos(angle);
mag = sqrt( x*x + y*y + z*z );
// Identity matrix
if (mag == 0.0) {
m3dLoadIdentity33(m);
return;
}
// Rotation matrix is normalized
x /= mag;
y /= mag;
z /= mag;
#define M(row,col) m[col*3+row]
xx = x * x;
yy = y * y;
zz = z * z;
xy = x * y;
yz = y * z;
zx = z * x;
xs = x * s;
ys = y * s;
zs = z * s;
one_c = 1.0 - c;
M(0,0) = (one_c * xx) + c;
M(0,1) = (one_c * xy) - zs;
M(0,2) = (one_c * zx) + ys;
M(1,0) = (one_c * xy) + zs;
M(1,1) = (one_c * yy) + c;
M(1,2) = (one_c * yz) - xs;
M(2,0) = (one_c * zx) - ys;
M(2,1) = (one_c * yz) + xs;
M(2,2) = (one_c * zz) + c;
#undef M
}
///////////////////////////////////////////////////////////////////////////////
// Creates a 4x4 rotation matrix, takes radians NOT degrees
void m3dRotationMatrix44(M3DMatrix44d m, double angle, double x, double y, double z)
{
double mag, s, c;
double xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c;
s = sin(angle);
c = cos(angle);
mag = sqrt( x*x + y*y + z*z );
// Identity matrix
if (mag == 0.0) {
m3dLoadIdentity44(m);
return;
}
// Rotation matrix is normalized
x /= mag;
y /= mag;
z /= mag;
#define M(row,col) m[col*4+row]
xx = x * x;
yy = y * y;
zz = z * z;
xy = x * y;
yz = y * z;
zx = z * x;
xs = x * s;
ys = y * s;
zs = z * s;
one_c = 1.0f - c;
M(0,0) = (one_c * xx) + c;
M(0,1) = (one_c * xy) - zs;
M(0,2) = (one_c * zx) + ys;
M(0,3) = 0.0;
M(1,0) = (one_c * xy) + zs;
M(1,1) = (one_c * yy) + c;
M(1,2) = (one_c * yz) - xs;
M(1,3) = 0.0;
M(2,0) = (one_c * zx) - ys;
M(2,1) = (one_c * yz) + xs;
M(2,2) = (one_c * zz) + c;
M(2,3) = 0.0;
M(3,0) = 0.0;
M(3,1) = 0.0;
M(3,2) = 0.0;
M(3,3) = 1.0;
#undef M
}
////////////////////////////////////////////////////////////////////////////
/// This function is not exported by library, just for this modules use only
// 3x3 determinant
static float DetIJ(const M3DMatrix44f m, const int i, const int j)
{
int x, y, ii, jj;
float ret, mat[3][3];
x = 0;
for (ii = 0; ii < 4; ii++)
{
if (ii == i) continue;
y = 0;
for (jj = 0; jj < 4; jj++)
{
if (jj == j) continue;
mat[x][y] = m[(ii*4)+jj];
y++;
}
x++;
}
ret = mat[0][0]*(mat[1][1]*mat[2][2]-mat[2][1]*mat[1][2]);
ret -= mat[0][1]*(mat[1][0]*mat[2][2]-mat[2][0]*mat[1][2]);
ret += mat[0][2]*(mat[1][0]*mat[2][1]-mat[2][0]*mat[1][1]);
return ret;
}
////////////////////////////////////////////////////////////////////////////
/// This function is not exported by library, just for this modules use only
// 3x3 determinant
static double DetIJ(const M3DMatrix44d m, const int i, const int j)
{
int x, y, ii, jj;
double ret, mat[3][3];
x = 0;
for (ii = 0; ii < 4; ii++)
{
if (ii == i) continue;
y = 0;
for (jj = 0; jj < 4; jj++)
{
if (jj == j) continue;
mat[x][y] = m[(ii*4)+jj];
y++;
}
x++;
}
ret = mat[0][0]*(mat[1][1]*mat[2][2]-mat[2][1]*mat[1][2]);
ret -= mat[0][1]*(mat[1][0]*mat[2][2]-mat[2][0]*mat[1][2]);
ret += mat[0][2]*(mat[1][0]*mat[2][1]-mat[2][0]*mat[1][1]);
return ret;
}
////////////////////////////////////////////////////////////////////////////
///
// Invert matrix
void m3dInvertMatrix44(M3DMatrix44f mInverse, const M3DMatrix44f m)
{
int i, j;
float det, detij;
// calculate 4x4 determinant
det = 0.0f;
for (i = 0; i < 4; i++)
{
det += (i & 0x1) ? (-m[i] * DetIJ(m, 0, i)) : (m[i] * DetIJ(m, 0,i));
}
det = 1.0f / det;
// calculate inverse
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
detij = DetIJ(m, j, i);
mInverse[(i*4)+j] = ((i+j) & 0x1) ? (-detij * det) : (detij *det);
}
}
}
////////////////////////////////////////////////////////////////////////////
///
// Invert matrix
void m3dInvertMatrix44(M3DMatrix44d mInverse, const M3DMatrix44d m)
{
int i, j;
double det, detij;
// calculate 4x4 determinant
det = 0.0;
for (i = 0; i < 4; i++)
{
det += (i & 0x1) ? (-m[i] * DetIJ(m, 0, i)) : (m[i] * DetIJ(m, 0,i));
}
det = 1.0 / det;
// calculate inverse
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
detij = DetIJ(m, j, i);
mInverse[(i*4)+j] = ((i+j) & 0x1) ? (-detij * det) : (detij *det);
}
}
}
///////////////////////////////////////////////////////////////////////////////////////
// Get Window coordinates, discard Z...
void m3dProjectXY(M3DVector2f vPointOut, const M3DMatrix44f mModelView, const M3DMatrix44f mProjection, const int iViewPort[4], const M3DVector3f vPointIn)
{
M3DVector4f vBack, vForth;
memcpy(vBack, vPointIn, sizeof(float)*3);
vBack[3] = 1.0f;
m3dTransformVector4(vForth, vBack, mModelView);
m3dTransformVector4(vBack, vForth, mProjection);
if (!m3dCloseEnough(vBack[3], 0.0f, 0.000001f)) {
float div = 1.0f / vBack[3];
vBack[0] *= div;
vBack[1] *= div;
//vBack[2] *= div;
}
vPointOut[0] = float(iViewPort[0])+(1.0f+float(vBack[0]))*float(iViewPort[2])/2.0f;
vPointOut[1] = float(iViewPort[1])+(1.0f+float(vBack[1]))*float(iViewPort[3])/2.0f;
// This was put in for Grand Tour... I think it's right.
// .... please report any bugs
if (iViewPort[0] != 0) // Cast to float is expensive... avoid if posssible
vPointOut[0] -= float(iViewPort[0]);
if (iViewPort[1] != 0)
vPointOut[1] -= float(iViewPort[1]);
}
///////////////////////////////////////////////////////////////////////////////////////
// Get window coordinates, we also want Z....
void m3dProjectXYZ(M3DVector3f vPointOut, const M3DMatrix44f mModelView, const M3DMatrix44f mProjection, const int iViewPort[4], const M3DVector3f vPointIn)
{
M3DVector4f vBack, vForth;
memcpy(vBack, vPointIn, sizeof(float)*3);
vBack[3] = 1.0f;
m3dTransformVector4(vForth, vBack, mModelView);
m3dTransformVector4(vBack, vForth, mProjection);
if (!m3dCloseEnough(vBack[3], 0.0f, 0.000001f)) {
float div = 1.0f / vBack[3];
vBack[0] *= div;
vBack[1] *= div;
vBack[2] *= div;
}
vPointOut[0] = float(iViewPort[0])+(1.0f+float(vBack[0]))*float(iViewPort[2])/2.0f;
vPointOut[1] = float(iViewPort[1])+(1.0f+float(vBack[1]))*float(iViewPort[3])/2.0f;
if (iViewPort[0] != 0) // Cast to float is expensive... avoid if posssible
vPointOut[0] -= float(iViewPort[0]);
if (iViewPort[1] != 0)
vPointOut[1] -= float(iViewPort[1]);
vPointOut[2] = vBack[2];
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Misc. Utilities
///////////////////////////////////////////////////////////////////////////////
// Calculates the normal of a triangle specified by the three points
// p1, p2, and p3. Each pointer points to an array of three floats. The
// triangle is assumed to be wound counter clockwise.
void m3dFindNormal(M3DVector3f result, const M3DVector3f point1, const M3DVector3f point2,
const M3DVector3f point3)
{
M3DVector3f v1,v2; // Temporary vectors
// Calculate two vectors from the three points. Assumes counter clockwise
// winding!
v1[0] = point1[0] - point2[0];
v1[1] = point1[1] - point2[1];
v1[2] = point1[2] - point2[2];
v2[0] = point2[0] - point3[0];
v2[1] = point2[1] - point3[1];
v2[2] = point2[2] - point3[2];
// Take the cross product of the two vectors to get
// the normal vector.
m3dCrossProduct3(result, v1, v2);
}
// Ditto above, but for doubles
void m3dFindNormal(M3DVector3d result, const M3DVector3d point1, const M3DVector3d point2,
const M3DVector3d point3)
{
M3DVector3d v1,v2; // Temporary vectors
// Calculate two vectors from the three points. Assumes counter clockwise
// winding!
v1[0] = point1[0] - point2[0];
v1[1] = point1[1] - point2[1];
v1[2] = point1[2] - point2[2];
v2[0] = point2[0] - point3[0];
v2[1] = point2[1] - point3[1];
v2[2] = point2[2] - point3[2];
// Take the cross product of the two vectors to get
// the normal vector.
m3dCrossProduct3(result, v1, v2);
}
/////////////////////////////////////////////////////////////////////////////////////////
// Calculate the plane equation of the plane that the three specified points lay in. The
// points are given in clockwise winding order, with normal pointing out of clockwise face
// planeEq contains the A,B,C, and D of the plane equation coefficients
void m3dGetPlaneEquation(M3DVector4f planeEq, const M3DVector3f p1, const M3DVector3f p2, const M3DVector3f p3)
{
// Get two vectors... do the cross product
M3DVector3f v1, v2;
// V1 = p3 - p1
v1[0] = p3[0] - p1[0];
v1[1] = p3[1] - p1[1];
v1[2] = p3[2] - p1[2];
// V2 = P2 - p1
v2[0] = p2[0] - p1[0];
v2[1] = p2[1] - p1[1];
v2[2] = p2[2] - p1[2];
// Unit normal to plane - Not sure which is the best way here
m3dCrossProduct3(planeEq, v1, v2);
m3dNormalizeVector3(planeEq);
// Back substitute to get D
planeEq[3] = -(planeEq[0] * p3[0] + planeEq[1] * p3[1] + planeEq[2] * p3[2]);
}
// Ditto above, but for doubles
void m3dGetPlaneEquation(M3DVector4d planeEq, const M3DVector3d p1, const M3DVector3d p2, const M3DVector3d p3)
{
// Get two vectors... do the cross product
M3DVector3d v1, v2;
// V1 = p3 - p1
v1[0] = p3[0] - p1[0];
v1[1] = p3[1] - p1[1];
v1[2] = p3[2] - p1[2];
// V2 = P2 - p1
v2[0] = p2[0] - p1[0];
v2[1] = p2[1] - p1[1];
v2[2] = p2[2] - p1[2];
// Unit normal to plane - Not sure which is the best way here
m3dCrossProduct3(planeEq, v1, v2);
m3dNormalizeVector3(planeEq);
// Back substitute to get D
planeEq[3] = -(planeEq[0] * p3[0] + planeEq[1] * p3[1] + planeEq[2] * p3[2]);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// This function does a three dimensional Catmull-Rom curve interpolation. Pass four points, and a
// floating point number between 0.0 and 1.0. The curve is interpolated between the middle two points.
// Coded by RSW
void m3dCatmullRom(M3DVector3f vOut, const M3DVector3f vP0, const M3DVector3f vP1, const M3DVector3f vP2, const M3DVector3f vP3, float t)
{
float t2 = t * t;
float t3 = t2 * t;
// X
vOut[0] = 0.5f * ( ( 2.0f * vP1[0]) +
(-vP0[0] + vP2[0]) * t +
(2.0f * vP0[0] - 5.0f *vP1[0] + 4.0f * vP2[0] - vP3[0]) * t2 +
(-vP0[0] + 3.0f*vP1[0] - 3.0f *vP2[0] + vP3[0]) * t3);
// Y
vOut[1] = 0.5f * ( ( 2.0f * vP1[1]) +
(-vP0[1] + vP2[1]) * t +
(2.0f * vP0[1] - 5.0f *vP1[1] + 4.0f * vP2[1] - vP3[1]) * t2 +
(-vP0[1] + 3.0f*vP1[1] - 3.0f *vP2[1] + vP3[1]) * t3);
// Z
vOut[2] = 0.5f * ( ( 2.0f * vP1[2]) +
(-vP0[2] + vP2[2]) * t +
(2.0f * vP0[2] - 5.0f *vP1[2] + 4.0f * vP2[2] - vP3[2]) * t2 +
(-vP0[2] + 3.0f*vP1[2] - 3.0f *vP2[2] + vP3[2]) * t3);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// This function does a three dimensional Catmull-Rom curve interpolation. Pass four points, and a
// floating point number between 0.0 and 1.0. The curve is interpolated between the middle two points.
// Coded by RSW
void m3dCatmullRom(M3DVector3d vOut, const M3DVector3d vP0, const M3DVector3d vP1, const M3DVector3d vP2, const M3DVector3d vP3, double t)
{
double t2 = t * t;
double t3 = t2 * t;
// X
vOut[0] = 0.5 * ( ( 2.0 * vP1[0]) +
(-vP0[0] + vP2[0]) * t +
(2.0 * vP0[0] - 5.0 *vP1[0] + 4.0 * vP2[0] - vP3[0]) * t2 +
(-vP0[0] + 3.0*vP1[0] - 3.0 *vP2[0] + vP3[0]) * t3);
// Y
vOut[1] = 0.5 * ( ( 2.0 * vP1[1]) +
(-vP0[1] + vP2[1]) * t +
(2.0 * vP0[1] - 5.0 *vP1[1] + 4.0 * vP2[1] - vP3[1]) * t2 +
(-vP0[1] + 3*vP1[1] - 3.0 *vP2[1] + vP3[1]) * t3);
// Z
vOut[2] = 0.5 * ( ( 2.0 * vP1[2]) +
(-vP0[2] + vP2[2]) * t +
(2.0 * vP0[2] - 5.0 *vP1[2] + 4.0 * vP2[2] - vP3[2]) * t2 +
(-vP0[2] + 3.0*vP1[2] - 3.0 *vP2[2] + vP3[2]) * t3);
}
///////////////////////////////////////////////////////////////////////////////
// Determine if the ray (starting at point) intersects the sphere centered at
// sphereCenter with radius sphereRadius
// Return value is < 0 if the ray does not intersect
// Return value is 0.0 if ray is tangent
// Positive value is distance to the intersection point
// Algorithm from "3D Math Primer for Graphics and Game Development"
double m3dRaySphereTest(const M3DVector3d point, const M3DVector3d ray, const M3DVector3d sphereCenter, double sphereRadius)
{
//m3dNormalizeVector(ray); // Make sure ray is unit length
M3DVector3d rayToCenter; // Ray to center of sphere
rayToCenter[0] = sphereCenter[0] - point[0];
rayToCenter[1] = sphereCenter[1] - point[1];
rayToCenter[2] = sphereCenter[2] - point[2];
// Project rayToCenter on ray to test
double a = m3dDotProduct3(rayToCenter, ray);
// Distance to center of sphere
double distance2 = m3dDotProduct3(rayToCenter, rayToCenter); // Or length
double dRet = (sphereRadius * sphereRadius) - distance2 + (a*a);
if (dRet > 0.0) // Return distance to intersection
dRet = a - sqrt(dRet);
return dRet;
}
///////////////////////////////////////////////////////////////////////////////
// Determine if the ray (starting at point) intersects the sphere centered at
// ditto above, but uses floating point math
float m3dRaySphereTest(const M3DVector3f point, const M3DVector3f ray, const M3DVector3f sphereCenter, float sphereRadius)
{
//m3dNormalizeVectorf(ray); // Make sure ray is unit length
M3DVector3f rayToCenter; // Ray to center of sphere
rayToCenter[0] = sphereCenter[0] - point[0];
rayToCenter[1] = sphereCenter[1] - point[1];
rayToCenter[2] = sphereCenter[2] - point[2];
// Project rayToCenter on ray to test
float a = m3dDotProduct3(rayToCenter, ray);
// Distance to center of sphere
float distance2 = m3dDotProduct3(rayToCenter, rayToCenter); // Or length
float dRet = (sphereRadius * sphereRadius) - distance2 + (a*a);
if (dRet > 0.0) // Return distance to intersection
dRet = a - sqrtf(dRet);
return dRet;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Calculate the tangent basis for a triangle on the surface of a model
// This vector is needed for most normal mapping shaders
void m3dCalculateTangentBasis(M3DVector3f vTangent, const M3DVector3f vTriangle[3], const M3DVector2f vTexCoords[3], const M3DVector3f N)
{
M3DVector3f dv2v1, dv3v1;
float dc2c1t, dc2c1b, dc3c1t, dc3c1b;
float M;
m3dSubtractVectors3(dv2v1, vTriangle[1], vTriangle[0]);
m3dSubtractVectors3(dv3v1, vTriangle[2], vTriangle[0]);
dc2c1t = vTexCoords[1][0] - vTexCoords[0][0];
dc2c1b = vTexCoords[1][1] - vTexCoords[0][1];
dc3c1t = vTexCoords[2][0] - vTexCoords[0][0];
dc3c1b = vTexCoords[2][1] - vTexCoords[0][1];
M = (dc2c1t * dc3c1b) - (dc3c1t * dc2c1b);
M = 1.0f / M;
m3dScaleVector3(dv2v1, dc3c1b);
m3dScaleVector3(dv3v1, dc2c1b);
m3dSubtractVectors3(vTangent, dv2v1, dv3v1);
m3dScaleVector3(vTangent, M); // This potentially changes the direction of the vector
m3dNormalizeVector3(vTangent);
M3DVector3f B;
m3dCrossProduct3(B, N, vTangent);
m3dCrossProduct3(vTangent, B, N);
m3dNormalizeVector3(vTangent);
}
////////////////////////////////////////////////////////////////////////////
// Smoothly step between 0 and 1 between edge1 and edge 2
double m3dSmoothStep(const double edge1, const double edge2, const double x)
{
double t;
t = (x - edge1) / (edge2 - edge1);
if (t > 1.0)
t = 1.0;
if (t < 0.0)
t = 0.0f;
return t * t * ( 3.0 - 2.0 * t);
}
////////////////////////////////////////////////////////////////////////////
// Smoothly step between 0 and 1 between edge1 and edge 2
float m3dSmoothStep(const float edge1, const float edge2, const float x)
{
float t;
t = (x - edge1) / (edge2 - edge1);
if (t > 1.0f)
t = 1.0f;
if (t < 0.0)
t = 0.0f;
return t * t * ( 3.0f - 2.0f * t);
}
///////////////////////////////////////////////////////////////////////////
// Creae a projection to "squish" an object into the plane.
// Use m3dGetPlaneEquationf(planeEq, point1, point2, point3);
// to get a plane equation.
void m3dMakePlanarShadowMatrix(M3DMatrix44f proj, const M3DVector4f planeEq, const M3DVector3f vLightPos)
{
// These just make the code below easier to read. They will be
// removed by the optimizer.
float a = planeEq[0];
float b = planeEq[1];
float c = planeEq[2];
float d = planeEq[3];
float dx = -vLightPos[0];
float dy = -vLightPos[1];
float dz = -vLightPos[2];
// Now build the projection matrix
proj[0] = b * dy + c * dz;
proj[1] = -a * dy;
proj[2] = -a * dz;
proj[3] = 0.0;
proj[4] = -b * dx;
proj[5] = a * dx + c * dz;
proj[6] = -b * dz;
proj[7] = 0.0;
proj[8] = -c * dx;
proj[9] = -c * dy;
proj[10] = a * dx + b * dy;
proj[11] = 0.0;
proj[12] = -d * dx;
proj[13] = -d * dy;
proj[14] = -d * dz;
proj[15] = a * dx + b * dy + c * dz;
// Shadow matrix ready
}
///////////////////////////////////////////////////////////////////////////
// Creae a projection to "squish" an object into the plane.
// Use m3dGetPlaneEquationd(planeEq, point1, point2, point3);
// to get a plane equation.
void m3dMakePlanarShadowMatrix(M3DMatrix44d proj, const M3DVector4d planeEq, const M3DVector3f vLightPos)
{
// These just make the code below easier to read. They will be
// removed by the optimizer.
double a = planeEq[0];
double b = planeEq[1];
double c = planeEq[2];
double d = planeEq[3];
double dx = -vLightPos[0];
double dy = -vLightPos[1];
double dz = -vLightPos[2];
// Now build the projection matrix
proj[0] = b * dy + c * dz;
proj[1] = -a * dy;
proj[2] = -a * dz;
proj[3] = 0.0;
proj[4] = -b * dx;
proj[5] = a * dx + c * dz;
proj[6] = -b * dz;
proj[7] = 0.0;
proj[8] = -c * dx;
proj[9] = -c * dy;
proj[10] = a * dx + b * dy;
proj[11] = 0.0;
proj[12] = -d * dx;
proj[13] = -d * dy;
proj[14] = -d * dz;
proj[15] = a * dx + b * dy + c * dz;
// Shadow matrix ready
}
/////////////////////////////////////////////////////////////////////////////
// I want to know the point on a ray, closest to another given point in space.
// As a bonus, return the distance squared of the two points.
// In: vRayOrigin is the origin of the ray.
// In: vUnitRayDir is the unit vector of the ray
// In: vPointInSpace is the point in space
// Out: vPointOnRay is the poing on the ray closest to vPointInSpace
// Return: The square of the distance to the ray
double m3dClosestPointOnRay(M3DVector3d vPointOnRay, const M3DVector3d vRayOrigin, const M3DVector3d vUnitRayDir,
const M3DVector3d vPointInSpace)
{
M3DVector3d v;
m3dSubtractVectors3(v, vPointInSpace, vRayOrigin);
double t = m3dDotProduct3(vUnitRayDir, v);
// This is the point on the ray
vPointOnRay[0] = vRayOrigin[0] + (t * vUnitRayDir[0]);
vPointOnRay[1] = vRayOrigin[1] + (t * vUnitRayDir[1]);
vPointOnRay[2] = vRayOrigin[2] + (t * vUnitRayDir[2]);
return m3dGetDistanceSquared3(vPointOnRay, vPointInSpace);
}
// ditto above... but with floats
float m3dClosestPointOnRay(M3DVector3f vPointOnRay, const M3DVector3f vRayOrigin, const M3DVector3f vUnitRayDir,
const M3DVector3f vPointInSpace)
{
M3DVector3f v;
m3dSubtractVectors3(v, vPointInSpace, vRayOrigin);
float t = m3dDotProduct3(vUnitRayDir, v);
// This is the point on the ray
vPointOnRay[0] = vRayOrigin[0] + (t * vUnitRayDir[0]);
vPointOnRay[1] = vRayOrigin[1] + (t * vUnitRayDir[1]);
vPointOnRay[2] = vRayOrigin[2] + (t * vUnitRayDir[2]);
return m3dGetDistanceSquared3(vPointOnRay, vPointInSpace);
}
| [
"[email protected]"
]
| [
[
[
1,
1040
]
]
]
|
b4abae769ea5c15cdc01c476327ec8fc3b601a4f | cfa6cdfaba310a2fd5f89326690b5c48c6872a2a | /Sources/Server/M-Server Manager/Sources/Command/CMD_Handler.cpp | 9eaff3349b375191d06c76033f5a5696b913c078 | []
| no_license | asdlei00/project-jb | 1cc70130020a5904e0e6a46ace8944a431a358f6 | 0bfaa84ddab946c90245f539c1e7c2e75f65a5c0 | refs/heads/master | 2020-05-07T21:41:16.420207 | 2009-09-12T03:40:17 | 2009-09-12T03:40:17 | 40,292,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 359 | cpp | #include "stdAfx.h"
#include "CMD_Handler.h"
CCMDHandlerMgr::CCMDHandlerMgr()
{
}
CCMDHandlerMgr::~CCMDHandlerMgr()
{
}
PMSG_DATA CCMDHandlerMgr::CMD_Main_Handle(MSG_DATA msgData, CClientSock* pSock)
{
switch(msgData.msgHeader.nCommandType)
{
case MIDDLE_CMD:
{
return CMD_MS_Handle(msgData, pSock);
}
break;
}
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
13
],
[
15,
19
],
[
21,
26
]
],
[
[
14,
14
],
[
20,
20
]
]
]
|
9c64112d575a6be31c09175b2130317224db697b | 99527557aee4f1db979a7627e77bd7d644098411 | /utils/windowevents.h | b3745da5fba63ce17c601de99d4464ac8541adc0 | []
| no_license | GunioRobot/2deffects | 7aeb02400090bb7118d23f1fc435ffbdd4417c59 | 39d8e335102d6a51cab0d47a3a2dc7686d7a7c67 | refs/heads/master | 2021-01-18T14:10:32.049756 | 2008-09-15T15:56:50 | 2008-09-15T15:56:50 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,850 | h | #ifndef _SYD_EVENTS_H_
#define _SYD_EVENTS_H_
#include "utils/geometry.h"
#include <memory>
namespace syd {
class Window;
class WindowListener {
public:
virtual void windowResized ( Window& src ) =0;
virtual void windowClosing ( Window& src ) =0;
virtual void windowDeiconified ( Window& src ) =0;
virtual void windowIconified ( Window& src ) =0;
virtual ~WindowListener() {}
};
class WindowAdapter : public WindowListener {
public:
void windowResized ( Window& src ) {}
void windowClosing ( Window& src ) {}
void windowDeiconified ( Window& src ) {}
void windowIconified ( Window& src ) {}
~WindowAdapter(){};
};
class MouseEvent {
Window& src_;
Point point_;
int button_;
public:
enum { LEFT_BUTTON, MIDDLE_BUTTON, RIGHT_BUTTON };
public:
MouseEvent( Window& src, Point point, int button )
: src_( src ), point_( point ), button_( button ) {}
~MouseEvent() {}
public:
Window& getSource() const { return src_; }
Point getPoint() const { return point_; }
int getButton() const { return button_; }
};
class MouseListener {
public:
//SDL_MouseButtonEvent
// virtual void mouseClicked ( std::auto_ptr< MouseEvent > event ) =0;
virtual void mousePressed ( std::auto_ptr< MouseEvent > event ) =0;
virtual void mouseReleased ( std::auto_ptr< MouseEvent > event ) =0;
//SDL_MouseMotionEvent
// virtual void mouseDragged ( std::auto_ptr< MouseEvent > event ) =0;
virtual void mouseMoved ( std::auto_ptr< MouseEvent > event ) =0;
virtual ~MouseListener() {}
};
class MouseAdapter : public MouseListener {
public:
// void mouseClicked ( std::auto_ptr< MouseEvent > event ) {}
void mousePressed ( std::auto_ptr< MouseEvent > event ) {}
void mouseReleased ( std::auto_ptr< MouseEvent > event ) {}
// void mouseDragged ( std::auto_ptr< MouseEvent > event ) {}
void mouseMoved ( std::auto_ptr< MouseEvent > event ) {}
~MouseAdapter(){};
};
class KeyEvent {
Window& src_;
int keycode_;
public:
KeyEvent( Window& src, int keycode )
: src_( src ), keycode_( keycode ) {}
~KeyEvent() {}
public:
Window& getSource() const { return src_; }
int getKeycode() const { return keycode_; }
};
class KeyListener {
public:
//SDL_KEYBOARDEVENT‚Å
// virtual void keyPressed ( std::auto_ptr< KeyEvent > event ) =0;
virtual void keyReleased ( std::auto_ptr< KeyEvent > event ) =0;
virtual void keyTyped ( std::auto_ptr< KeyEvent > event ) =0;
virtual ~KeyListener() {}
};
class KeyAdapter : public KeyListener {
public:
// void keyPressed ( std::auto_ptr< KeyEvent > event ) {}
void keyReleased ( std::auto_ptr< KeyEvent > event ) {}
void keyTyped ( std::auto_ptr< KeyEvent > event ) {}
~KeyAdapter() {}
};
} //namespace syd
#endif //_SYD_EVENTS_H_
| [
"[email protected]"
]
| [
[
[
1,
131
]
]
]
|
05c93d7f95c77848558b06b2d7395222e9412879 | 7a8153e3fde0807462b6b6696b796d772639fa74 | /src/game/lifeforms/Monster.cpp | bdd27e1aacad8109ce51b854d8c29c55de377012 | []
| no_license | qaze/violetland | 7183f9670676d05da3970cd2fbd8cf7e5f5197c2 | 9f0fc9aff4ca1a4111b45fb105fc33fd9ae97dad | refs/heads/master | 2021-01-02T22:38:01.687080 | 2011-10-10T12:35:36 | 2011-10-10T12:35:36 | 32,754,552 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,319 | cpp | #ifdef _WIN32
#define _USE_MATH_DEFINES
#endif //_WIN32W
#include "Monster.h"
violetland::Monster::Monster(MonsterTemplate* base, int lvl) :
LifeForm(0, 0, 128, 128) {
Id = "10-" + Id;
Base = base;
Level = lvl;
float t = Base->Strength + Base->Agility + Base->Vitality;
float sp = Base->Strength / t;
float ap = Base->Agility / t;
float vp = Base->Vitality / t;
Strength = Base->Strength + 0.03f * Level * sp;
Agility = Base->Agility + 0.03f * Level * ap;
Vitality = Base->Vitality + 0.03f * Level * vp;
if ((rand() % 100) > 95) {
Strength *= 2.0f;
setMask(0.2f, 0.7f, 0.2f, 1.0f);
Name = "Strong " + Base->Name;
} else if ((rand() % 100) > 95) {
Agility *= 1.8f;
setMask(0.3f, 0.4f, 0.7f, 1.0f);
Name = "Fast " + Base->Name;
} else if ((rand() % 100) > 95) {
Vitality *= 2.0f;
setMask(1.0f, 0.2f, 0.2f, 1.0f);
Name = "Healthy " + Base->Name;
} else {
setMask(0.8f, 0.7f, 0.4f, 1.0f);
Name = "Regular " + Base->Name;
}
setHealth(MaxHealth());
HitR = 0.3;
Acceleration = 0.0004f;
if (Base->WalkTime > 0)
m_walkTime = (rand() % Base->WalkTime);
else
m_walkTime = 0;
m_walkDelay = 0;
m_body = new DynamicObject(0, 0, Base->WalkSprite);
m_hitSoundChannel = 0;
m_bleedDelay = 0;
m_bleedCount = 0;
Angry = false;
targetId = "ambient";
Type = LIFEFORM_MONSTER;
}
void violetland::Monster::rollFrame(bool forward) {
m_body->rollFrame(forward);
}
Sound* violetland::Monster::hit(float damage, bool poison, bool stop) {
LifeForm::hit(damage, poison);
m_bleedCount += damage * 5;
Poisoned = poison || Poisoned;
if (stop)
Speed = 0.0f;
Angle += ((rand() % 50) - 25) * damage;
if (m_walkDelay > 0)
m_walkDelay = 1;
if (!Base->HitSounds.empty()) {
int s = rand() % (int) Base->HitSounds.size();
return Base->HitSounds[s];
}
return NULL;
}
bool violetland::Monster::isBleeding() {
if (m_bleedCount > 0 && m_bleedDelay > 600) {
m_bleedDelay = 0;
m_bleedCount--;
return true;
} else {
return false;
}
}
void violetland::Monster::process(int deltaTime) {
LifeForm::process(deltaTime);
if (m_walkTime > 0) {
m_walkTime -= deltaTime;
if (m_walkTime <= 0) {
m_walkTime = 0;
m_walkDelay = Base->WalkDelay;
}
}
if (m_walkDelay > 0) {
m_walkDelay -= deltaTime;
if (m_walkDelay <= 0) {
m_walkTime = Base->WalkTime;
m_walkDelay = 0;
}
}
if (m_bleedCount > 0)
m_bleedDelay += deltaTime;
if (State == LIFEFORM_STATE_DYING) {
if (m_body->Frame == m_body->AnimSprite->getFramesCount() - 1) {
State = LIFEFORM_STATE_DIED;
} else {
m_body->rollFrame(true);
}
}
if (State == LIFEFORM_STATE_SMITTEN) {
delete m_body;
m_body = new DynamicObject(X, Y, Base->DeathSprite);
State = LIFEFORM_STATE_DYING;
}
}
StaticObject* violetland::Monster::getCorpse() {
StaticObject * corpse = new StaticObject(X, Y, m_width, m_height,
m_body->getFrame(), false);
corpse->Scale = Scale;
corpse->Angle = Object::fixAngle(180 - Angle);
corpse->setMask(RMask, GMask, BMask, AMask);
return corpse;
}
void violetland::Monster::draw() {
m_body->draw(X, Y, Angle, Scale, RMask, GMask, BMask, AMask);
}
violetland::Monster::~Monster() {
delete m_body;
}
| [
"5253450@c5058ba8-c010-11de-a759-a54c9d3330c2",
"[email protected]@c5058ba8-c010-11de-a759-a54c9d3330c2",
"[email protected]@c5058ba8-c010-11de-a759-a54c9d3330c2"
]
| [
[
[
1,
63
],
[
65,
68
],
[
73,
126
],
[
128,
148
]
],
[
[
64,
64
],
[
69,
72
]
],
[
[
127,
127
]
]
]
|
8922db977d3091a9834b426ff1fd73d326505341 | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/OgreMaxLoader/Include/Mouse.hpp | 77fc1dca605f2deb28b1f34ddcc38bc692a7732f | []
| 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 | 14,190 | hpp | /*
* OgreMaxViewer - An Ogre 3D-based viewer for .scene and .mesh files
* Copyright 2008 Derek Nedelman
*
* This code is available under the OgreMax Free License:
* -You may use this code for any purpose, commercial or non-commercial.
* -If distributing derived works (that use this source code) in binary or source code form,
* you must give the following credit in your work's end-user documentation:
* "Portions of this work provided by OgreMax (www.ogremax.com)"
*
* Derek Nedelman assumes no responsibility for any harm caused by using this code.
*
* OgreMaxViewer was written by Derek Nedelman and released at www.ogremax.com
*/
#ifndef OgreMax_Mouse_INCLUDED
#define OgreMax_Mouse_INCLUDED
//Includes---------------------------------------------------------------------
#include <OIS.h>
#include "InputSource.hpp"
//Classes----------------------------------------------------------------------
namespace OgreMax
{
/**
* Wrapper for a mouse device
* All public methods are safe to call with a null device
*/
class Mouse
{
friend class InputSystem;
public:
enum {AXIS_COUNT = 3};
const OIS::Mouse* GetMouse() const
{
return this->mouse;
}
bool IsNull() const
{
return this->mouse == 0;
}
bool PressedButton(OIS::MouseButtonID button) const
{
return
this->mouse != 0 &&
!this->previousMouseState.buttonDown(button) &&
this->mouse->getMouseState().buttonDown(button);
}
bool PressingButton(OIS::MouseButtonID button) const
{
return
this->mouse != 0 &&
this->mouse->getMouseState().buttonDown(button);
}
bool ReleasedButton(OIS::MouseButtonID button) const
{
return
this->mouse != 0 &&
this->previousMouseState.buttonDown(button) &&
!this->mouse->getMouseState().buttonDown(button);
}
bool PressedAnyButton() const
{
for (int buttonIndex = 0; buttonIndex < BUTTON_COUNT; buttonIndex++)
{
if (PressedButton((OIS::MouseButtonID)buttonIndex))
return true;
}
return false;
}
bool PressingAnyButton() const
{
return
this->mouse != 0 &&
this->mouse->getMouseState().buttons != 0;
}
bool ReleasedAnyButton() const
{
for (int buttonIndex = 0; buttonIndex < BUTTON_COUNT; buttonIndex++)
{
if (ReleasedButton((OIS::MouseButtonID)buttonIndex))
return true;
}
return false;
}
bool PressedAxis(int axis, int direction = 0) const
{
return
this->mouse != 0 &&
axis < AXIS_COUNT &&
!AxisActive(GetMouseAxis(this->previousMouseState, axis).rel, direction) &&
AxisActive(GetMouseAxis(this->mouse->getMouseState(), axis).rel, direction);
}
bool PressingAxis(int axis, int direction = 0) const
{
return
this->mouse != 0 &&
axis < AXIS_COUNT &&
AxisActive(GetMouseAxis(this->mouse->getMouseState(), axis).rel, direction);
}
bool ReleasedAxis(int axis, int direction = 0) const
{
return
this->mouse != 0 &&
axis < AXIS_COUNT &&
AxisActive(GetMouseAxis(this->previousMouseState, axis).rel, direction) &&
!AxisActive(GetMouseAxis(this->mouse->getMouseState(), axis).rel, direction);
}
bool PressedAnyAxis() const
{
bool pressed = false;
if (this->mouse != 0)
{
const OIS::MouseState& mouseState = this->mouse->getMouseState();
pressed =
(!AxisActive(this->previousMouseState.X.rel) && AxisActive(mouseState.X.rel)) ||
(!AxisActive(this->previousMouseState.Y.rel) && AxisActive(mouseState.Y.rel)) ||
(!AxisActive(this->previousMouseState.Z.rel) && AxisActive(mouseState.Z.rel));
}
return pressed;
}
bool PressingAnyAxis() const
{
bool pressing = false;
if (this->mouse != 0)
{
const OIS::MouseState& mouseState = this->mouse->getMouseState();
pressing =
AxisActive(mouseState.X.rel) ||
AxisActive(mouseState.Y.rel) ||
AxisActive(mouseState.Z.rel);
}
return pressing;
}
bool ReleasedAnyAxis() const
{
bool released = false;
if (this->mouse != 0)
{
const OIS::MouseState& mouseState = this->mouse->getMouseState();
released =
(AxisActive(this->previousMouseState.X.rel) && !AxisActive(mouseState.X.rel)) ||
(AxisActive(this->previousMouseState.Y.rel) && !AxisActive(mouseState.Y.rel)) ||
(AxisActive(this->previousMouseState.Z.rel) && !AxisActive(mouseState.Z.rel));
}
return released;
}
int GetPressedButton() const
{
for (int buttonIndex = 0; buttonIndex < BUTTON_COUNT; buttonIndex++)
{
if (PressedButton((OIS::MouseButtonID)buttonIndex))
return buttonIndex;
}
return -1;
}
int GetPressingButton() const
{
for (int buttonIndex = 0; buttonIndex < BUTTON_COUNT; buttonIndex++)
{
if (PressingButton((OIS::MouseButtonID)buttonIndex))
return buttonIndex;
}
return -1;
}
int GetReleasedButton() const
{
for (int buttonIndex = 0; buttonIndex < BUTTON_COUNT; buttonIndex++)
{
if (ReleasedButton((OIS::MouseButtonID)buttonIndex))
return buttonIndex;
}
return -1;
}
bool GetPressedAxisIndexAndDirection(int& index, int& direction) const
{
if (this->mouse != 0)
{
for (int axisIndex = 0; axisIndex < AXIS_COUNT; axisIndex++)
{
if (PressedAxis(axisIndex))
{
index = axisIndex;
direction = (GetAxis(axisIndex).rel < 0) ? -1 : 1;
return true;
}
}
}
return false;
}
bool GetPressingAxisIndexAndDirection(int& index, int& direction) const
{
if (this->mouse != 0)
{
for (int axisIndex = 0; axisIndex < AXIS_COUNT; axisIndex++)
{
if (PressingAxis(axisIndex))
{
index = axisIndex;
direction = (GetAxis(axisIndex).rel < 0) ? -1 : 1;
return true;
}
}
}
return false;
}
bool GetReleasedAxisIndexAndDirection(int& index, int& direction) const
{
if (this->mouse != 0)
{
for (int axisIndex = 0; axisIndex < AXIS_COUNT; axisIndex++)
{
if (ReleasedAxis(axisIndex))
{
index = axisIndex;
direction = (GetAxis(axisIndex).rel < 0) ? -1 : 1;
return true;
}
}
}
return false;
}
void GetPressedButtons(InputSourceVector& inputSources) const
{
InputSource inputSource;
inputSource.deviceType = InputSource::MOUSE_BUTTON;
for (inputSource.button = 0; inputSource.button < BUTTON_COUNT; inputSource.button++)
{
if (PressedButton((OIS::MouseButtonID)inputSource.button))
inputSources.push_back(inputSource);
}
}
void GetPressingButtons(InputSourceVector& inputSources) const
{
InputSource inputSource;
inputSource.deviceType = InputSource::MOUSE_BUTTON;
for (inputSource.button = 0; inputSource.button < BUTTON_COUNT; inputSource.button++)
{
if (PressingButton((OIS::MouseButtonID)inputSource.button))
inputSources.push_back(inputSource);
}
}
void GetReleasedButtons(InputSourceVector& inputSources) const
{
InputSource inputSource;
inputSource.deviceType = InputSource::MOUSE_BUTTON;
for (inputSource.button = 0; inputSource.button < BUTTON_COUNT; inputSource.button++)
{
if (ReleasedButton((OIS::MouseButtonID)inputSource.button))
inputSources.push_back(inputSource);
}
}
void GetPressedAxisIndicesAndDirections(InputSourceVector& inputSources) const
{
if (this->mouse != 0)
{
InputSource inputSource;
inputSource.deviceType = InputSource::MOUSE_AXIS;
for (inputSource.axis = 0; inputSource.axis < AXIS_COUNT; inputSource.axis++)
{
if (PressedAxis(inputSource.axis))
{
inputSource.direction = (GetAxis(inputSource.axis).rel < 0) ? -1 : 1;
inputSources.push_back(inputSource);
}
}
}
}
void GetPressingAxisIndicesAndDirections(InputSourceVector& inputSources) const
{
if (this->mouse != 0)
{
InputSource inputSource;
inputSource.deviceType = InputSource::MOUSE_AXIS;
for (inputSource.axis = 0; inputSource.axis < AXIS_COUNT; inputSource.axis++)
{
if (PressingAxis(inputSource.axis))
{
inputSource.direction = (GetAxis(inputSource.axis).rel < 0) ? -1 : 1;
inputSources.push_back(inputSource);
}
}
}
}
void GetReleasedAxisIndicesAndDirections(InputSourceVector& inputSources) const
{
if (this->mouse != 0)
{
InputSource inputSource;
inputSource.deviceType = InputSource::MOUSE_AXIS;
for (inputSource.axis = 0; inputSource.axis < AXIS_COUNT; inputSource.axis++)
{
if (ReleasedAxis(inputSource.axis))
{
inputSource.direction = (GetAxis(inputSource.axis).rel < 0) ? -1 : 1;
inputSources.push_back(inputSource);
}
}
}
}
/**
* Determines if the mouse has moved since the last Update(), using the
* conventional notion of the X/Y axes indicating mouse movement
*/
bool Moved() const
{
return
this->mouse != 0 &&
(AxisActive(this->mouse->getMouseState().X.rel) || AxisActive(this->mouse->getMouseState().Y.rel));
}
/** Gets the specified axis */
const OIS::Axis& GetAxis(int axis) const
{
static OIS::Axis nullAxis;
if (this->mouse != 0)
return GetMouseAxis(this->mouse->getMouseState(), axis);
else
return nullAxis;
}
private:
Mouse()
{
this->mouse = 0;
this->updatedOnce = false;
}
void Set(OIS::Mouse* mouse)
{
this->mouse = mouse;
this->updatedOnce = false;
}
void Update()
{
if (this->mouse != 0)
{
//Save current state as the previous state
this->previousMouseState = this->mouse->getMouseState();
//Get new state
this->mouse->capture();
//Copy current state to previous state if this is the first update
if (!this->updatedOnce)
{
this->previousMouseState = this->mouse->getMouseState();
this->updatedOnce = true;
}
}
}
static const OIS::Axis& GetMouseAxis(const OIS::MouseState& mouseState, int axis)
{
static OIS::Axis nullAxis;
switch (axis)
{
case 0: return mouseState.X;
case 1: return mouseState.Y;
case 2: return mouseState.Z;
default: return nullAxis;
}
}
static bool AxisActive(int value, int direction = 0, int deadZone = 0)
{
if (direction == 0)
return std::abs(value) > deadZone;
else
return value * direction > deadZone;
}
private:
enum {BUTTON_COUNT = 8};
OIS::Mouse* mouse;
OIS::MouseState previousMouseState;
bool updatedOnce;
};
}
#endif | [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
430
]
]
]
|
d775a2c7ba9adf591a27abdca1da5c7bcbb4b9df | be2e23022d2eadb59a3ac3932180a1d9c9dee9c2 | /GameServer/MapGroupKernel/Network/MsgAnnounceList.cpp | a09abecdf190c00b89dd920c26eaeea58c80be22 | []
| no_license | cronoszeu/revresyksgpr | 78fa60d375718ef789042c452cca1c77c8fa098e | 5a8f637e78f7d9e3e52acdd7abee63404de27e78 | refs/heads/master | 2020-04-16T17:33:10.793895 | 2010-06-16T12:52:45 | 2010-06-16T12:52:45 | 35,539,807 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,537 | cpp | #include "AllMsg.h"
#include "mapgroup.h"
bool CMsgAnnounceList::Create(USHORT usType, USHORT usAmount, ST_ANNOUNCE_TITLE* setAnnounce)
{
if(usAmount > 0)
CHECKF (setAnnounce);
m_unMsgType = _MSG_ANNOUNCE_LIST;
m_usType = usType;
for (int i=0; i<usAmount; i++)
{
m_setAnnounce.Append(setAnnounce[i]);
}
m_unMsgSize = sizeof(*this)-m_setAnnounce.GetFreeBufferSize();
return true;
}
bool CMsgAnnounceList::Append(OBJID idAnnounce, const char* pszTitle,int type)
{
CHECKF (pszTitle);
ST_ANNOUNCE_TITLE Announce;
Announce.idAnnounce = idAnnounce;
::SafeCopy(Announce.szName, pszTitle, 32);
m_setAnnounce.Append(Announce);
m_unMsgSize = sizeof(*this)-m_setAnnounce.GetFreeBufferSize();
return true;
}
void CMsgAnnounceList::Process(CMapGroup& mapGroup, CUser* pUser)
{
#ifdef _MYDEBUG
::LogSave("Process CMsgAnnounceList: type=%u, amount=%u, index=%u",
m_usType, m_usAmount, m_dwIndexFirst);
#endif
OBJID idUser = pUser->GetID();
switch(m_usType)
{
case CHECK_BY_INDEX:
mapGroup.GetAnnounce()->SendAnnounceList(mapGroup.GetRoleManager()->QueryRole(idUser),CHECK_BY_INDEX,m_nIndex);
break;
case CHECK_BY_ID:
mapGroup.GetAnnounce()->SendAnnounceList(mapGroup.GetRoleManager()->QueryRole(idUser),CHECK_BY_ID,m_idAnnounce);
break;
case CHECK_BY_OWNER:
mapGroup.GetAnnounce()->SendAnnounceList(mapGroup.GetRoleManager()->QueryRole(idUser),CHECK_BY_OWNER,m_usAmount);
break;
}
// ASSERT(!"CMsgAnnounceList::Process");
} | [
"rpgsky.com@cc92e6ba-efcf-11de-bf31-4dec8810c1c1"
]
| [
[
[
1,
51
]
]
]
|
7ce7cd53ddc4f9015de7c686646c1c901ec8c08e | 8c777d62435addb7c5657f4a0e722505e70dcbc1 | /openRad/reference/MAKECLAS.CPP | 14a6c9308cc712fd996bc4a1f758dd41667cd6d9 | []
| no_license | davidmc/w3metasite | 4e35601d68996dae92e6b7e85ae86aa1bb1a9093 | c8b98d0dd585a069a16116dea267fabf845ebc13 | refs/heads/master | 2016-09-05T10:47:09.368012 | 2010-01-01T19:44:13 | 2010-01-01T19:44:13 | 455,231 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 395 | cpp | #include<stdio.h>
#include<iostream.h>
#include<iomanip.h>
#include<fstream.h>
#include<string.h>
#include"makeclas.hpp"
int main( int argc, char * argv[] )
{
if (argc != 2)
{
cerr << "usage:" << endl;
cerr << "makeclas classfile" << endl;
return(1);
}
ClassDef defClass( argv[1] );
defClass.WriteHpp();
defClass.WriteCpp();
return(0);
}
| [
"[email protected]"
]
| [
[
[
1,
25
]
]
]
|
552ed6017313763eb313997e11c8ab89670dab78 | 4c0c3b9539a84860b1ecec87e0cc89da5a2b8579 | /src/exerb/gui.cpp | 75663cdae3de7b50bf990572387d4e4e618af674 | [
"DOC"
]
| permissive | snaury/exerb-mingw | 8ec9f4f39aead177c91dec3671b49315d300d923 | 577683046e021785e6ac47cf2bd6fe6a8e6951f7 | refs/heads/master | 2016-09-05T11:59:54.922776 | 2009-11-02T14:31:25 | 2009-11-02T14:31:25 | 348,470 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 7,914 | cpp | // $Id: gui.cpp,v 1.15 2008/12/19 12:17:50 arton Exp $
#include <ruby.h>
#include <windowsx.h>
#include "exerb.h"
#include "resource.h"
////////////////////////////////////////////////////////////////////////////////
int exerb_main(int argc, char** argv, void (*on_init)(VALUE, VALUE, VALUE), void (*on_fail)(VALUE)); // exerb.cpp
int WINAPI WinMain(HINSTANCE current_instance, HINSTANCE prev_instance, LPSTR cmd_line, int show_cmd);
static void on_init(VALUE io_stdin, VALUE io_stdout, VALUE io_stderr);
static void on_fail(VALUE errinfo);
static void exerb_replace_io_methods(const VALUE io);
static VALUE rb_exerbio_write(VALUE self, VALUE str);
static VALUE rb_exerbio_return_nil(int argc, VALUE *argv, VALUE self);
static LRESULT CALLBACK dialog_proc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam);
////////////////////////////////////////////////////////////////////////////////
int WINAPI
WinMain(HINSTANCE current_instance, HINSTANCE prev_instance, LPSTR cmd_line, int show_cmd)
{
#ifdef _DEBUG
__asm { int 3 }
#endif
return ::exerb_main(0, NULL, on_init, on_fail);
}
static void
on_init(VALUE io_stdin, VALUE io_stdout, VALUE io_stderr)
{
::exerb_replace_io_methods(io_stdin);
::exerb_replace_io_methods(io_stdout);
::exerb_replace_io_methods(io_stderr);
::rb_define_global_function("gets", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_global_function("readline", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_global_function("getc", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_global_function("readlines", (RUBY_PROC)rb_exerbio_return_nil, -1);
}
static void
on_fail(VALUE errinfo)
{
::DialogBoxParam(::GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_EXCEPTION), NULL, (DLGPROC)dialog_proc, (LPARAM)errinfo);
}
////////////////////////////////////////////////////////////////////////////////
static void
exerb_replace_io_methods(const VALUE io)
{
::rb_define_singleton_method(io, "reopen", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "each", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "each_line", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "each_byte", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "syswrite", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "sysread", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "fileno", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "to_i", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "to_io", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "fsync", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "sync", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "sync=", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "lineno", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "lineno=", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "readlines", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "read", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "write", (RUBY_PROC)rb_exerbio_write, 1);
::rb_define_singleton_method(io, "gets", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "readline", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "getc", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "readchar", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "ungetc", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "flush", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "tell", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "seek", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "rewind", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "pos", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "pos=", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "eof", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "eof?", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "close", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "closed?", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "close_read", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "close_write", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "isatty", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "tty?", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "binmode", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "sysseek", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "ioctl", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "fcntl", (RUBY_PROC)rb_exerbio_return_nil, -1);
::rb_define_singleton_method(io, "pid", (RUBY_PROC)rb_exerbio_return_nil, -1);
}
static VALUE
rb_exerbio_write(VALUE self, VALUE str)
{
::rb_secure(4);
if ( TYPE(str) != T_STRING ) str = ::rb_obj_as_string(str);
if ( RSTRING_LEN(str) > 0 ) ::OutputDebugString(RSTRING_PTR(str));
return Qnil;
}
static VALUE
rb_exerbio_return_nil(int argc, VALUE *argv, VALUE self)
{
return Qnil;
}
////////////////////////////////////////////////////////////////////////////////
static LRESULT CALLBACK
dialog_proc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
static HFONT font = NULL;
switch ( message ) {
case WM_INITDIALOG:
if ( lparam ) {
const VALUE errinfo = (VALUE)lparam;
const VALUE message = ::rb_funcall(errinfo, ::rb_intern("message"), 0);
const VALUE message_str = ::rb_funcall(message, ::rb_intern("gsub"), 2, ::rb_str_new2("\n"), ::rb_str_new2("\r\n"));
const VALUE backtrace = ::rb_funcall(errinfo, ::rb_intern("backtrace"), 0);
const VALUE backtrace_str = ::rb_str_concat(::rb_ary_join(backtrace, ::rb_str_new2("\r\n")), rb_str_new2("\r\n"));
::SetDlgItemText(hwnd, IDC_EDIT_TYPE, ::rb_obj_classname(errinfo));
::SetDlgItemText(hwnd, IDC_EDIT_MESSAGE, STR2CSTR(message_str));
::SetDlgItemText(hwnd, IDC_EDIT_BACKTRACE, STR2CSTR(backtrace_str));
}
{
char self_filename[MAX_PATH] = "";
char window_title_format[MAX_PATH] = "";
char window_title[MAX_PATH] = "";
::GetModuleFileName(NULL, self_filename, sizeof(self_filename));
::GetWindowText(hwnd, window_title_format, sizeof(window_title_format));
::wsprintf(window_title, window_title_format, self_filename);
::SetWindowText(hwnd, window_title);
}
font = ::CreateFont(14, 0, 0, 0, FW_REGULAR, FALSE, FALSE, FALSE, SHIFTJIS_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, PROOF_QUALITY, FIXED_PITCH | FF_MODERN, "Terminal");
SetWindowFont(::GetDlgItem(hwnd, IDC_EDIT_TYPE), font, false);
SetWindowFont(::GetDlgItem(hwnd, IDC_EDIT_MESSAGE), font, false);
SetWindowFont(::GetDlgItem(hwnd, IDC_EDIT_BACKTRACE), font, false);
::MessageBeep(MB_ICONHAND);
return TRUE;
case WM_DESTROY:
::DeleteObject(font);
return TRUE;
case WM_CLOSE:
::EndDialog(hwnd, ID_CLOSE);
return TRUE;
case WM_COMMAND:
if ( LOWORD(wparam) == ID_CLOSE ) {
::EndDialog(hwnd, ID_CLOSE);
return TRUE;
}
break;
}
return FALSE;
}
////////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
]
| [
[
[
1,
171
]
]
]
|
14d8b7982d78a28c5852088afdfe6d19cb5ceee1 | 65da00cc6f20a83dd89098bb22f8f93c2ff7419b | /HabuMath/LPad/Include/AffineTransformTest.hpp | 1a7579cd63531101c8a9bb88267458bb2468a1cd | []
| no_license | skevy/CSC-350-Assignment-5 | 8b7c42257972d71e3d0cd3e9566e88a1fdcce73c | 8091a56694f4b5b8de7e278b64448d4f491aaef5 | refs/heads/master | 2021-01-23T11:49:35.653361 | 2011-04-20T02:20:06 | 2011-04-20T02:20:06 | 1,638,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,854 | hpp |
#ifndef AFFINE_TRANFORM_TEST_HPP
#define AFFINE_TRANFORM_TEST_HPP
#include "HabuMath.hpp"
#include <d3dx9math.h> // for testing
using namespace HabuTech;
#define INTERATIONS 1000000
void TestAffineTransforms()
{
long double fXdiff = 0.0;
long double fYdiff = 0.0;
long double fZdiff = 0.0;
cout << "*************START AFFINE TRANSFORMS TEST************" << endl;
cout << "*****************START ROTATION TEST*****************" << endl;
D3DXMATRIX D3DX_XRotationMatrix;
D3DXMATRIX D3DX_YRotationMatrix;
D3DXMATRIX D3DX_ZRotationMatrix;
Matrix<float, 4> HM_XRotationMatrix;
Matrix<float, 4> HM_YRotationMatrix;
Matrix<float, 4> HM_ZRotationMatrix;
Random<float> oRandomFloat;
for(unsigned long long i = 0; i < INTERATIONS; i++)
{
D3DXMatrixIdentity(&D3DX_XRotationMatrix);
D3DXMatrixIdentity(&D3DX_YRotationMatrix);
D3DXMatrixIdentity(&D3DX_ZRotationMatrix);
HM_XRotationMatrix.Identity();
HM_YRotationMatrix.Identity();
HM_ZRotationMatrix.Identity();
float fXangle = oRandomFloat.Generate(0.0F, 2*3.14F);
float fYangle = oRandomFloat.Generate(0.0F, 2*3.14F);
float fZangle = oRandomFloat.Generate(0.0F, 2*3.14F);
D3DXMatrixRotationX(&D3DX_XRotationMatrix, fXangle);
D3DXMatrixRotationY(&D3DX_YRotationMatrix, fYangle);
D3DXMatrixRotationZ(&D3DX_ZRotationMatrix, fZangle);
HM_XRotationMatrix.RotateAboutX(fXangle);
HM_YRotationMatrix.RotateAboutY(fYangle);
HM_ZRotationMatrix.RotateAboutZ(fZangle);
for(unsigned char r = 0; r < 4; r++)
{
for(unsigned char c = 0; c < 4; c++)
{
fXdiff += (D3DX_XRotationMatrix(r,c) - HM_XRotationMatrix(c,r));
}
}
for(unsigned char r = 0; r < 4; r++)
{
for(unsigned char c = 0; c < 4; c++)
{
fYdiff += (D3DX_YRotationMatrix(r,c) - HM_YRotationMatrix(c,r));
}
}
for(unsigned char r = 0; r < 4; r++)
{
for(unsigned char c = 0; c < 4; c++)
{
fZdiff += (D3DX_ZRotationMatrix(r,c) - HM_ZRotationMatrix(c,r));
}
}
if(!(i%10000))
{
cout << "XDiff Average: " << fXdiff/(float)(INTERATIONS * 16) << endl
<< "YDiff Average: " << fYdiff/(float)(INTERATIONS * 16) << endl
<< "ZDiff Average: " << fZdiff/(float)(INTERATIONS * 16) << endl;
}
}
cout << "Final Result for Rotation Test" << endl
<< "XDiff Average: " << fXdiff/(float)(INTERATIONS * 16) << endl
<< "YDiff Average: " << fYdiff/(float)(INTERATIONS * 16) << endl
<< "ZDiff Average: " << fZdiff/(float)(INTERATIONS * 16) << endl;
cout << "*****************END ROTATION TEST*****************" << endl;
cout << "************END AFFINE TRANSFORMS TEST**********" << endl;
}
#endif AFFINE_TRANFORM_TEST_HPP | [
"[email protected]"
]
| [
[
[
1,
97
]
]
]
|
2c64247f7fa371550dfa38f246fa6767a449ea2a | 6d25f0b33ccaadd65b35f77c442b80097a2fce8e | /gbt/rank_gbtree.h | bf102e2e6eba04e7d9572d19c0ebd795f14cc28f | []
| no_license | zhongyunuestc/felix-academic-project | 8b282d3a783aa48a6b56ff6ca73dc967f13fd6cf | cc71c44fba50a5936b79f7d75b5112d247af17fe | refs/heads/master | 2021-01-24T10:28:38.604955 | 2010-03-20T08:33:59 | 2010-03-20T08:33:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 679 | h | #ifndef __RANK_MODEL__
#define __RANK_MODEL__
#include <string>
#include <tree.h>
#include <cart.h>
#include <rank_common.h>
struct GBTree {
TreeVec treeVec;
double learningRate, b;
doubles_t w;
int nDims;
void train(const Dataset& trainset, int nDims, const Dataset& testset, const Dataset& valset, const MartParam& martParam, const Metric* m=NULL);
void test(const Dataset& ds, doubles_t& res) const;
double getLoss(const Dataset& ds, const doubles_t& res) const;
void save(const std::string& fn) const;
void load(const std::string& fn);
~GBTree() {
for(size_t i=0;i<treeVec.size();i++) delete treeVec[i];
}
};
#endif
| [
"Felix.Guozq@fe1a0076-fbb2-11de-b7cb-b1160b2c2156"
]
| [
[
[
1,
27
]
]
]
|
e33fbdef7cff69ba4e0d5cfa4e992551144b7137 | 1c84fe02ecde4a78fb03d3c28dce6fef38ebaeff | /State_FollowQueen.h | 88cfecc3fe7412a47e5278f92f1b346ffe435166 | []
| no_license | aadarshasubedi/beesiege | c29cb8c3fce910771deec5bb63bcb32e741c1897 | 2128b212c5c5a68e146d3f888bb5a8201c8104f7 | refs/heads/master | 2016-08-12T08:37:10.410041 | 2007-12-16T20:57:33 | 2007-12-16T20:57:33 | 36,995,410 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 566 | h | #ifndef STATEFOLLOWQUEEN_H
#define STATEFOLLOWQUEEN_H
#include "FSMState.h"
class StateFollowQueen: public FSMState
{
public:
// ctor
StateFollowQueen(FSMAIControl* control, int type=FSM_FOLLOW_QUEEN) :
FSMState(control, type)
{}
// see base class
void Enter();
void Exit();
void Update(float fTime);
FSMState* CheckTransitions(float fTime);
private:
enum AIControlType
{
BEE_AI_CONTROL,
HEALER_BEE_AI_CONTROL,
HONEY_BEE_AI_CONTROL
};
AIControlType m_eType;
};
NiSmartPointer(StateFollowQueen);
#endif | [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
8
],
[
15,
16
],
[
30,
34
]
],
[
[
9,
14
],
[
17,
29
]
]
]
|
3d2746db32a0e516440fb646b6370f87f06f382d | 610c7fab24418c124efa4f224f61fee1076c851b | /opensurf/surflib.h | 815873f82b4d3436792aa258b11dc53c73f7b733 | []
| no_license | julapy/ofxOpenSurf | 3c2478729ad05d5fa3612620a8fd78ab8dfd3f27 | 9875b6189360983c6a770bc8a91ed00b0e5c1938 | refs/heads/master | 2016-08-04T04:35:06.588986 | 2011-10-11T09:50:06 | 2011-10-11T09:50:06 | 2,131,676 | 13 | 3 | null | 2015-02-01T14:42:29 | 2011-07-31T08:17:22 | C++ | UTF-8 | C++ | false | false | 3,393 | h | /***********************************************************
* --- OpenSURF --- *
* This library is distributed under the GNU GPL. Please *
* contact [email protected] for more information. *
* *
* C. Evans, Research Into Robust Visual Features, *
* MSc University of Bristol, 2008. *
* *
************************************************************/
#ifndef SURFLIB_H
#define SURFLIB_H
#include "cv.h"
//#include "highgui.h"
#include "integral.h"
#include "fasthessian.h"
#include "surf.h"
#include "ipoint.h"
#include "utils.h"
//! Library function builds vector of described interest points
inline void surfDetDes(IplImage *img, /* image to find Ipoints in */
std::vector<Ipoint> &ipts, /* reference to vector of Ipoints */
bool upright = false, /* run in rotation invariant mode? */
int octaves = OCTAVES, /* number of octaves to calculate */
int intervals = INTERVALS, /* number of intervals per octave */
int init_sample = INIT_SAMPLE, /* initial sampling step */
float thres = THRES /* blob response threshold */)
{
// Create integral-image representation of the image
IplImage *int_img = Integral(img);
// Create Fast Hessian Object
FastHessian fh(int_img, ipts, octaves, intervals, init_sample, thres);
// Extract interest points and store in vector ipts
fh.getIpoints();
// Create Surf Descriptor Object
Surf des(int_img, ipts);
// Extract the descriptors for the ipts
des.getDescriptors(upright);
// Deallocate the integral image
cvReleaseImage(&int_img);
}
//! Library function builds vector of interest points
inline void surfDet(IplImage *img, /* image to find Ipoints in */
std::vector<Ipoint> &ipts, /* reference to vector of Ipoints */
int octaves = OCTAVES, /* number of octaves to calculate */
int intervals = INTERVALS, /* number of intervals per octave */
int init_sample = INIT_SAMPLE, /* initial sampling step */
float thres = THRES /* blob response threshold */)
{
// Create integral image representation of the image
IplImage *int_img = Integral(img);
// Create Fast Hessian Object
FastHessian fh(int_img, ipts, octaves, intervals, init_sample, thres);
// Extract interest points and store in vector ipts
fh.getIpoints();
// Deallocate the integral image
cvReleaseImage(&int_img);
}
//! Library function describes interest points in vector
inline void surfDes(IplImage *img, /* image to find Ipoints in */
std::vector<Ipoint> &ipts, /* reference to vector of Ipoints */
bool upright = false) /* run in rotation invariant mode? */
{
// Create integral image representation of the image
IplImage *int_img = Integral(img);
// Create Surf Descriptor Object
Surf des(int_img, ipts);
// Extract the descriptors for the ipts
des.getDescriptors(upright);
// Deallocate the integral image
cvReleaseImage(&int_img);
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
95
]
]
]
|
fe775589d6dd22e4e65dfb893fda167eeaa8ad80 | 444a151706abb7bbc8abeb1f2194a768ed03f171 | /trunk/CompilerSource/general/string.cpp | 616cd78d05a7b3c8cb8d4fe1652854d679081195 | []
| no_license | amorri40/Enigma-Game-Maker | 9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6 | c6b701201b6037f2eb57c6938c184a5d4ba917cf | refs/heads/master | 2021-01-15T11:48:39.834788 | 2011-11-22T04:09:28 | 2011-11-22T04:09:28 | 1,855,342 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,887 | cpp | /********************************************************************************\
** **
** Copyright (C) 2008 Josh Ventura **
** **
** This file is a part of the ENIGMA Development Environment. **
** **
** **
** ENIGMA 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 3 of the license or any later version. **
** **
** This application and its source code is distributed AS-IS, 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 recieved a copy of the GNU General Public License along **
** with this code. If not, see <http://www.gnu.org/licenses/> **
** **
** ENIGMA is an environment designed to create games and other programs with a **
** high-level, fully compilable language. Developers of ENIGMA or anything **
** associated with ENIGMA are in no way responsible for its users or **
** applications created by its users, or damages caused by the environment **
** or programs made in the environment. **
** **
\********************************************************************************/
#include <string>
#include <cstdio>
using namespace std;
typedef size_t pt;
string tostring(int val)
{
char a[12];
sprintf(a,"%d",val);
return a;
}
string tostringd(double val)
{
char a[24];
sprintf(a,"%f",val);
return a;
}
string tostringv(void* val)
{
char a[24];
sprintf(a,"%p",val);
return a;
}
string arraybounds_as_str(string str)
{
string ret;
for (pt i=0;i<str.length();i++)
{
if (str[i]=='[') ret+="arrayb";
else if (str[i]==')') ret+="eparenth";
else if (str[i]=='(') ret+="fparenth";
}
return ret;
}
int string_count(char c, char* str)
{
int occ = 0;
while (*str) occ+=*(str++)==c;
return occ;
}
/* */
| [
"[email protected]"
]
| [
[
[
1,
71
]
]
]
|
76a09ba033501d6d3dbd0e315f72d33765fb760f | 6c8c4728e608a4badd88de181910a294be56953a | /CommunicationModule/TelepathyIM/VoiceSessionParticipant.cpp | d9f25b7bb272eb5a324e25d9aa86df96e1ab967f | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 819 | cpp | // For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "VoiceSessionParticipant.h"
#include "Contact.h"
#include "MemoryLeakCheck.h"
namespace TelepathyIM
{
VoiceSessionParticipant::VoiceSessionParticipant(Contact *contact): contact_(contact)
{
}
VoiceSessionParticipant::~VoiceSessionParticipant()
{
}
Communication::ContactInterface* VoiceSessionParticipant::GetContact() const
{
return contact_;
}
QString VoiceSessionParticipant::GetID() const
{
return contact_->GetID();
}
QString VoiceSessionParticipant::GetName() const
{
return contact_->GetName();
}
} // end of namespace: TelepathyIM
| [
"jonnenau@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3",
"mattiku@5b2332b8-efa3-11de-8684-7d64432d61a3",
"Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
3
]
],
[
[
4,
4
],
[
6,
6
],
[
8,
9
]
],
[
[
5,
5
],
[
7,
7
],
[
10,
11
],
[
36,
37
]
],
[
[
12,
35
]
]
]
|
a5f709e224335c1cb426021471b93d0232a7c6da | 7acbb1c1941bd6edae0a4217eb5d3513929324c0 | /GLibrary-CPP/sources/GDirectory.cpp | 14bb7cb1f015c66ccf76659bf9badeaa7b6bcccb | []
| no_license | hungconcon/geofreylibrary | a5bfc96e0602298b5a7b53d4afe7395a993498f1 | 3abf3e1c31a245a79fa26b4bcf2e6e86fa258e4d | refs/heads/master | 2021-01-10T10:11:51.535513 | 2009-11-30T15:29:34 | 2009-11-30T15:29:34 | 46,771,895 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,374 | cpp |
#include "GDirectory.h"
GDirectory::GDirectory(void)
{
this->Cd(".");
}
GDirectory::~GDirectory(void)
{
}
bool GDirectory::Exist(void)
{
char *tmp = this->_path.ToChar();
bool ok(true);
#if defined (GWIN)
if (GetFileAttributes(tmp) == INVALID_FILE_ATTRIBUTES)
ok = (false);
#else
struct stat s;
if (lstat(tmp, &s) == -1)
ok = (false);
#endif
delete[] tmp;
return (ok);
}
bool GDirectory::Exist(const GString &Path)
{
bool ok(true);
#if defined (GWIN)
GString tmp(this->_path + "\\" + Path);
if (GetFileAttributes(tmp.ToLPCSTR()) == INVALID_FILE_ATTRIBUTES)
ok = (false);
#else
char *tmp = GString(this->_path + "\\" + Path).ToChar();
struct stat s;
if (lstat(tmp, &s) == -1)
ok = (false);
delete[] tmp;
#endif
return (ok);
}
GFileList GDirectory::Ls(void)
{
GFileList list;
char *tmp;
#if defined (GWIN)
HANDLE hEnt;
WIN32_FIND_DATA ent;
tmp = GString(this->_path + "/" + "*").ToChar();
if ((hEnt = FindFirstFile(tmp, &ent)) != INVALID_HANDLE_VALUE)
{
do
{
GFileInfos t(ent.cFileName);
list.PushBack(t);
}
while (FindNextFile(hEnt, &ent));
FindClose(hEnt);
}
#else
tmp = this->_path.ToChar();
DIR * rep = opendir(tmp);
if (rep != NULL)
{
struct dirent *ent;
while ((ent = readdir(rep)) != NULL)
{
GFileInfos t(ent->d_name);
list.PushBack(t);
}
closedir (rep);
}
#endif
delete[] tmp;
return (list);
}
GFileList GDirectory::Ls(const GString &p)
{
GFileList list;
char *tmp;
#if defined (GWIN)
HANDLE hEnt;
WIN32_FIND_DATA ent;
tmp = GString(p+ "/" + "*").ToChar();
if ((hEnt = FindFirstFile(tmp, &ent)) != INVALID_HANDLE_VALUE)
{
do
{
GFileInfos t(ent.cFileName);
list.PushBack(t);
}
while (FindNextFile(hEnt, &ent));
FindClose(hEnt);
}
#else
tmp = p.ToChar();
DIR * rep = opendir(tmp);
if (rep != NULL)
{
struct dirent *ent;
while ((ent = readdir(rep)) != NULL)
{
GFileInfos t(ent->d_name);
list.PushBack(t);
}
closedir (rep);
}
#endif
delete[] tmp;
return (list);
}
bool GDirectory::Mkdir(const GString &s)
{
char *tmp = s.ToChar();
bool ok(true);
#if defined (GWIN)
if (CreateDirectory(tmp, NULL) == 0)
ok = (false);
#else
if (mkdir(tmp, NULL) == -1)
ok = (false);
#endif
delete[] tmp;
return (ok);
}
bool GDirectory::Mkpath(const GString &s)
{
GString current = this->Pwd();
GStringList list = s.Split("\\");
for (unsigned int i = 0; i < list.Size(); ++i)
{
char *tmp = list[i].ToChar();
#if defined (GWIN)
if (CreateDirectory(tmp, NULL) == 0)
#else
if (mkdir(tmp, NULL) == -1)
#endif
{
delete[] tmp;
this->Cd(current);
return (false);
}
delete[] tmp;
this->Cd(list[i]);
}
this->Cd(current);
return (true);
}
bool GDirectory::Rename(const GString &f1, const GString &f2)
{
bool ok(true);
#if defined (GWIN)
char *tmp1 = f1.ToChar();
char *tmp2 = f2.ToChar();
if (MoveFile(tmp1, tmp2) == 0)
ok = (false);
delete[] tmp1;
delete[] tmp2;
#else
#endif
return (ok);
}
GString GDirectory::Pwd(void)
{
#if defined (GWIN)
TCHAR szPath[1024];
int n;
if ((n = GetCurrentDirectory(1024, szPath)) == 0)
throw GException(G::CANNOT_GET_CURRENT_PATH);
if (n == 0)
return (this->_path);
this->_path = GString(szPath);
#elif defined(GBSD)
char *path = new char[1024];
if (getwd(path) == NULL)
throw GException(G::CANNOT_GET_CURRENT_PATH);
this->_path = path;
delete[] path;
#elif defined(GLINUX)
char *path = get_current_dir_name();
this->_path = path;
delete[] path;
#endif
return (this->_path);
}
bool GDirectory::Cd(const GString &d)
{
char *tmp = d.ToChar();
bool ok(true);
#if defined (GWIN)
if (SetCurrentDirectory(tmp) == 0)
ok = false;
#else
if (chdir(tmp) == -1)
ok = false;
#endif
delete[] tmp;
this->Pwd();
return (ok);
}
bool GDirectory::Rmdir(bool test)
{
if (test == true)
{
GFileList content = GDirectory::Ls(this->_path);
for (unsigned int i = 0; i < content.Size(); i++)
{
if (content[i].FileName() != "." && content[i].FileName() != "..")
{
if (content[i].IsDir())
GDirectory::Rmdir(this->_path + "/" + content[i].FileName());
else
GFile::Rm(this->_path + "/" + content[i].FileName());
}
}
}
char *tmp = this->_path.ToChar();
bool ok(true);
#if defined (GWIN)
if (RemoveDirectory(tmp) == 0)
ok = (false);
#else
if (rmdir(tmp) == -1)
ok = (false);
#endif
delete[] tmp;
return (ok);
}
bool GDirectory::Rmdir(const GString &d, bool test)
{
if (test == true)
{
GFileList content = GDirectory::Ls(d);
for (unsigned int i = 0; i < content.Size(); i++)
{
if (content[i].FileName() != "." && content[i].FileName() != "..")
{
if (content[i].IsDir())
GDirectory::Rmdir(d + "/" + content[i].FileName());
else
GFile::Rm(d + "/" + content[i].FileName());
}
}
}
char *tmp = d.ToChar();
bool ok(true);
#if defined (GWIN)
if (RemoveDirectory(tmp) == 0)
ok = (false);
#else
if (rmdir(tmp) == -1)
ok = (false);
#endif
delete[] tmp;
return (ok);
}
bool GDirectory::Rmpath(const GString &)
{
return (true);
}
GString GDirectory::GetPathDesktop(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("Desktop"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetPathFonts(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("Fonts"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetPathMusic(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("My Music"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetPathVideos(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("My Video"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetPathPictures(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("My Pictures"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetPathCookies(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("Cookies"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetPathDocuments(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("Personal"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetPathHistory(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("History"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetPathStartMenu(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("Start Menu"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetPathProgramsMenu(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("Programs"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetPathFavorites(void)
{
#if defined (GWIN)
GRegistry r;
r.OpenKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
GString t(r.ReadStringValue("Favorites"));
r.CloseKey();
return (t);
#else
return ("");
#endif
}
GString GDirectory::GetRootPath(void)
{
#if defined (GWIN)
const unsigned long BUFSIZE = 255;
unsigned long dwSize = BUFSIZE;
char pbuf[ BUFSIZE + 1];
::GetWindowsDirectory(pbuf, dwSize);
return (pbuf);
#else
return ("\\");
#endif
}
GString GDirectory::GetSystemPath(void)
{
#if defined (GWIN)
const unsigned long BUFSIZE = 255;
unsigned long dwSize = BUFSIZE;
char pbuf[ BUFSIZE + 1];
::GetSystemDirectory(pbuf, dwSize);
return (pbuf);
#else
return ("");
#endif
}
/*
# m_AppData = m_Reg.LireStr("AppData");
# m_Cache = m_Reg.LireStr("Cache");
# m_LocalAppData = m_Reg.LireStr("Local AppData");
# m_LocalSettings = m_Reg.LireStr("Local Settings");
# m_VoisinageReseau = m_Reg.LireStr("NetHood");
# m_VoisinageImpression = m_Reg.LireStr("PrintHood");
# m_Recents = m_Reg.LireStr("Recent");
# m_EnvoyerVers = m_Reg.LireStr("SendTo");
# m_Demarrage = m_Reg.LireStr("Startup");
# m_Modeles = m_Reg.LireStr("Templates");
*/
| [
"mvoirgard@34e8d5ee-a372-11de-889f-a79cef5dd62c",
"tincani.geoffrey@34e8d5ee-a372-11de-889f-a79cef5dd62c",
"[email protected]"
]
| [
[
[
1,
33
],
[
36,
37
],
[
39,
42
],
[
44,
140
],
[
142,
142
],
[
146,
168
],
[
170,
184
],
[
186,
190
],
[
195,
412
],
[
414,
421
],
[
423,
425
],
[
438,
452
]
],
[
[
34,
35
],
[
38,
38
],
[
43,
43
],
[
413,
413
],
[
422,
422
],
[
426,
437
]
],
[
[
141,
141
],
[
143,
145
],
[
169,
169
],
[
185,
185
],
[
191,
194
]
]
]
|
e52135be4bbac478fa8b3ead656664d59617a1bd | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /Sockets/SocketStream.cpp | 10f59e210f2c59124e8eeaf5440dd224cb3989f3 | []
| 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 | 1,989 | cpp | /**
** \file SocketStream.cpp
** \date 2008-12-20
** \author [email protected]
**/
/*
Copyright (C) 2008-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 "SocketStream.h"
#include "ISocketHandler.h"
#include "TcpSocket.h"
#ifdef SOCKETS_NAMESPACE
namespace SOCKETS_NAMESPACE {
#endif
SocketStream::SocketStream(ISocketHandler& h, TcpSocket *sock) : m_handler(h), m_socket(sock)
, m_socket_uid(sock -> UniqueIdentifier())
{
}
size_t SocketStream::IStreamRead(char *buf, size_t max_sz)
{
if (m_handler.Valid(m_socket_uid))
{
return m_socket -> ReadInput(buf, max_sz);
}
return 0;
}
void SocketStream::IStreamWrite(const char *buf, size_t sz)
{
if (m_handler.Valid(m_socket_uid))
{
m_socket -> SendBuf(buf, sz);
}
}
#ifdef SOCKETS_NAMESPACE
} // namespace SOCKETS_NAMESPACE {
#endif
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
69
]
]
]
|
73346280bdb4dcf68fc0b9575b796fa5f1ac4282 | 91e66307c16b7bc5ac09a00e59e22872029d2dfe | /code/ChainApp/system.cpp | c42fda03ef96058f7a2b37930bbcc3e88c0085da | []
| no_license | BackupTheBerlios/artbody-svn | 52a7d0e780b077c9972ab25558916b772b8d8289 | 3dde2231e92d6c53b33021e333da1a434ab10c44 | refs/heads/master | 2016-09-03T01:53:14.446671 | 2008-02-06T16:33:58 | 2008-02-06T16:33:58 | 40,725,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,922 | cpp | //////////////////////////////////////////////////////////////////////////
// system.cpp
//////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <gl/glut.h>
#include "ChainApp.h"
#include "ab_types.h"
#include "ab_adapter.h"
#include "render.h"
#include "timer.h"
#include "processor.h"
#include "camera.h"
#include "inputer.h"
using namespace app;
void Application::_DisplayFunc(void)
{
App._renderer->processRender();
return;
}
void Application::_IdleFunc(void)
{
App._timer->processTimer();
glutPostRedisplay();
return;
}
void Application::_KeyboardFunc(unsigned char c, int x, int y)
{
inp::InputParams inp_params;
int sysKeyModif = glutGetModifiers();
inp::Inputer::MapGLInputToApp(&c, NULL, NULL, &sysKeyModif, &x, &y, inp_params);
App._inputer->processInput(inp_params);
return;
}
void Application::_MouseFunc(int button, int state, int x, int y)
{
inp::InputParams inp_params;
int sysKeyModif = glutGetModifiers();
inp::Inputer::MapGLInputToApp(NULL, &button, &state, &sysKeyModif, &x, &y, inp_params);
App._inputer->processInput(inp_params);
return;
}
void Application::_MotionFunc(int x, int y)
{
inp::InputParams inp_params = App._inputer->getCurParams();
inp::Inputer::MapGLInputToApp(NULL, NULL, NULL, NULL, &x, &y, inp_params);
App._inputer->processInput(inp_params);
return;
}
void Application::_ReshapeFunc(int w, int h)
{
App._processor->getCameraMng().setCameraWindow(w, h);
return;
}
bool Application::_InitSystem(int argc, char * argv[])
{
glutInit(&argc, (char**)&argv);
glutInitDisplayMode (GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(_wSize, _hSize);
_window = glutCreateWindow ("ChainApp");
glClearColor (0.0, 0.0, 0.0, 0.0);
_renderer = new rnd::Renderer(_wSize, _hSize);
_timer = new tmr::Timer;
_inputer = new inp::Inputer;
_processor = new Processor;
_renderer->addHdl(_processor);
_timer->addHdl(_processor);
_inputer->addHdl(_processor);
_processor->getCameraMng().setCamera(_renderer->getCamera());
glutDisplayFunc (_DisplayFunc);
glutIdleFunc (_IdleFunc);
glutReshapeFunc (_ReshapeFunc);
glutKeyboardFunc (_KeyboardFunc);
glutMouseFunc (_MouseFunc);
glutMotionFunc (_MotionFunc);
// glutPassiveMotionFunc(_MotionFunc);
return true;
}
void Application::_TermSystem(void)
{
delete _processor;
_processor = NULL;
delete _inputer;
_inputer = NULL;
delete _timer;
_timer = NULL;
delete _renderer;
_renderer = NULL;
glutDestroyWindow(_window);
return;
}
int Application::MainLoop()
{
glutMainLoop();
return 0;
}
| [
"ilya_p@70fd935d-ab2c-0410-87c7-a1c3f06a4c7f"
]
| [
[
[
1,
119
]
]
]
|
4bb51d23de869e909a3d24ebd29ffd2e6242ed15 | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhnetsdk/Demo/DeviceWorkState.h | 3104193ea5ce23d73a43d046dd75a74c88c27eaf | []
| 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 | 1,564 | h | #if !defined(AFX_DEVICEWORKSTATE_H__7818B4F5_1A0E_4E5B_B37F_B9702C5A8FB7__INCLUDED_)
#define AFX_DEVICEWORKSTATE_H__7818B4F5_1A0E_4E5B_B37F_B9702C5A8FB7__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// DeviceWorkState.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CDeviceWorkState dialog
class CDeviceWorkState : public CDialog
{
// Construction
public:
CDeviceWorkState(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CDeviceWorkState)
enum { IDD = IDD_DEVICE_WORKSTATE };
CComboBox m_disksel;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDeviceWorkState)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CDeviceWorkState)
virtual BOOL OnInitDialog();
afx_msg void OnSelchangeDiskselCombo();
afx_msg void OnSelchangeChanselCombo();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
public:
void SetDevice(DeviceNode *dev);
private:
DeviceNode *m_dev;
// NET_DEV_WORKSTATE m_workState;
NET_CLIENT_STATE m_almState;
char m_shltAlarm[16];
char m_recording[16];
HARD_DISK_STATE m_diskState;
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_DEVICEWORKSTATE_H__7818B4F5_1A0E_4E5B_B37F_B9702C5A8FB7__INCLUDED_)
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
58
]
]
]
|
7514dc7a578616220924ef2397433124be016863 | 5b3221bdc6edd8123287b2ace0a971eb979d8e2d | /Fiew/Layer.h | dec1e028eee0c3fe1fc560e2b43daf3bb227116f | []
| no_license | jackiejohn/fedit-image-editor | 0a4b67b46b88362d45db6a2ba7fa94045ad301e2 | fd6a87ed042e8adf4bf88ddbd13f2e3b475d985a | refs/heads/master | 2021-05-29T23:32:39.749370 | 2009-02-25T21:01:11 | 2009-02-25T21:01:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,672 | h | using namespace Gdiplus;
class ChildCore;
class Cell;
class Layer {
protected:
ChildCore *core;
Image *image, *scali;
int type, fitmode, sidemode;
int x, y, width, height, cwidth, cheight;
int rollHor, rollVer, maxrollHor, maxrollVer, minrollVer, offrollVer;
int offset, menuheight, rot, gifdir;
double zoom;
bool fulldraw, sidedraw, zoomdraw, fullscreen, cancel;
GUID *dimension;
UINT frameCount, frameThat;
SolidBrush *Brush_Back;
SolidBrush *Brush_DarkBack;
SolidBrush *Brush_LiteBack;
Pen *Pen_Border;
Pen *Pen_DarkBorder;
int FontSize;
FontFamily *FontFamily_Arial;
Font *Font_Default;
HANDLE mut_animloop, mut_image, mut_terminator;
HANDLE thrd_anim;
public:
Layer(ChildCore *core, Image *image);
virtual ~Layer();
void loadContent(Image *source,int init = TOP);
virtual void nextImage(int x = FERROR, int y = FERROR);
virtual void prevImage(int x = FERROR, int y = FERROR);
virtual Bitmap *render();
void reset();
virtual void repos();
virtual void scroll(int hor, int ver, bool invalidate = true);
virtual void scrollSet(int x, int y, bool invalidate = true);
virtual void scrollHor(int val);
virtual void scrollVer(int val);
virtual void zoomer(double val = NULL);
virtual void zoomat(double val = ZOOMINIT, bool invalidate = true);
virtual void zoomend(bool invalidate = true);
virtual void rotate(int val = NULL);
virtual void rotateReset(bool novalid = false);
int getX();
int getY();
int getWidth();
int getHeight();
File *getFile();
Image *getImage();
int getImageWidth();
int getImageHeight();
RECT getClientSize();
SCROLLINFO getScrollHor();
SCROLLINFO getScrollVer();
RECT getScrollInfo();
POINT getScrollMax();
int getMaxrollHor();
int getMaxrollVer();
double getZoom();
bool getSidedraw();
int getSidemode();
int getFitmode();
virtual void setFitmode(int mode = DEFAULT);
virtual void unsetFitmode();
virtual void setSidemode(int mode = NULL);
virtual void setSidedraw();
void setMenuheight(int val);
void setGifDir(int dir = DEFAULT);
void setCancel(bool set = true);
bool setWall();
bool isCancel();
bool isContent();
void locate(int init = NULL);
void invalidate(bool full = true);
static void scaleEnlarge(Bitmap *src, Rect srcRect, Bitmap *bmp, double zoom = ZOOMINIT);
static void scaleEnlarge(Bitmap *src, Bitmap *bmp, double zoom = ZOOMINIT);
static void scaleInvert(Bitmap *src, Rect *srcRect, Bitmap *bmp, Rect *bmpRect = NULL, int hatch = NULL, double zoom = ZOOMINIT);
static DWORD WINAPI anim(LPVOID param);
protected:
void init(Image *source);
void afterLoadContent(int init);
bool nextFrame(bool back = false);
bool prevFrame(bool back = false);
void rotate(Image *image);
void zoombegin();
void rotateSet();
void boundRoll();
void boundZoom();
double getZoom(int width, int height);
double getZoom(int width, int height, int cwidth, int cheight);
void animate();
Image *scale(Image *source);
bool isTopmost();
};
class Overlay : public Layer
{
public:
Overlay(ChildCore *core, Image *image);
~Overlay();
virtual void nextImage(int x = FERROR, int y = FERROR);
virtual void prevImage(int x = FERROR, int y = FERROR);
Bitmap *render();
virtual void zoomer(double val = NULL);
virtual void zoomat(double val = ZOOMINIT, bool invalidate = true);
virtual void zoomend(bool invalidate = true);
virtual void rotate(int val = NULL);
virtual void rotateReset(bool novalid = false);
virtual void setFitmode(int mode = DEFAULT);
virtual void unsetFitmode();
virtual void setSidedraw();
virtual void setSidemode(int mode = NULL);
RECT getOverlayRect();
protected:
virtual void hide();
};
class Thumblay : public Overlay
{
private:
Explorer *explorer;
Cacher *cacher;
Core *hardcore;
HWND hOwner;
Cell *lastCell;
int ticker;
int picker;
public:
Thumblay(ChildCore *core, Image *image);
Thumblay(HWND hOwner, Core *core, FwCHAR *path);
~Thumblay();
void update(bool init = false);
void nextImage(int x = FERROR, int y = FERROR);
void prevImage(int x = FERROR, int y = FERROR);
void prevImageDblClk(int x = FERROR, int y = FERROR);
void scroll(int hor, int ver, bool invalidate = true);
void scrollSet(int x, int y, bool invalidate = true);
void scrollHor(int val);
void scrollVer(int val);
void zoomer(double val = NULL);
void zoomat(double val = ZOOMINIT, bool invalidate = true);
void zoomend(bool invalidate = true);
void rotate(int val = NULL);
void rotateReset(bool novalid = false);
void setFitmode(int mode = DEFAULT);
void unsetFitmode();
void setSidedraw();
void setSidemode(int mode = NULL);
Cell *getLastCell();
void hide();
void subrender();
private:
void setPicker(int newpick);
int getPicker(int x, int y);
};
class Listlay : public Overlay
{
private:
Cell *lastCell;
int ticker;
public:
Listlay(ChildCore *core, Image *image);
~Listlay();
void update(bool init = false);
void nextImage(int x = FERROR, int y = FERROR);
void prevImage(int x = FERROR, int y = FERROR);
void scroll(int hor, int ver, bool invalidate = true);
void scrollSet(int x, int y, bool invalidate = true);
void scrollHor(int val);
void scrollVer(int val);
void zoomer(double val = NULL);
void zoomat(double val = ZOOMINIT, bool invalidate = true);
void zoomend(bool invalidate = true);
void rotate(int val = NULL);
void rotateReset(bool novalid = false);
void setFitmode(int mode = DEFAULT);
void unsetFitmode();
void setSidedraw();
void setSidemode(int mode = NULL);
Cell *getLastCell();
private:
void subrender();
};
class Gridlay : public Layer
{
private:
Bitmap *gridblock;
CachedBitmap *pattern;
bool rendered;
int oldx, oldy;
public:
Gridlay(ChildCore *core);
~Gridlay();
Bitmap *render();
bool isRendered();
void preload(RECT client, RECT scrollInfo, int x, int y, int width, int height);
void scroll(int hor, int ver, bool invalidate = true);
void scrollSet(int x, int y, bool invalidate = true);
void scrollHor(int val);
void scrollVer(int val);
void zoomer(double val = NULL);
void zoomat(double val = ZOOMINIT, bool invalidate = true);
void zoomend(bool invalidate = true);
};
class Snaplay : public Layer
{
private:
Pen *penPattern, *penSolid;
int oldWidth, oldHeight;
double oldZoom;
public:
Snaplay(ChildCore *core, Image *image);
~Snaplay();
Bitmap *render();
void preload();
}; | [
"[email protected]"
]
| [
[
[
1,
302
]
]
]
|
9a7af3ac546ba902dc16022016a9d63b20f0ce95 | d425cf21f2066a0cce2d6e804bf3efbf6dd00c00 | /Laptop/BobbyRShipments.cpp | 09479fc4541b1b1b67219e4ef3c77eced396bc87 | []
| no_license | infernuslord/ja2 | d5ac783931044e9b9311fc61629eb671f376d064 | 91f88d470e48e60ebfdb584c23cc9814f620ccee | refs/heads/master | 2021-01-02T23:07:58.941216 | 2011-10-18T09:22:53 | 2011-10-18T09:22:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,478 | cpp | #ifdef PRECOMPILEDHEADERS
#include "Laptop All.h"
#include "BobbyRShipments.h"
#else
#include "laptop.h"
#include "BobbyRShipments.h"
#include "bobbyr.h"
#include "utilities.h"
#include "WCheck.h"
#include "Text.h"
#include "BobbyRGuns.h"
#include "cursors.h"
#include "BobbyRMailOrder.h"
#include "wordwrap.h"
#include "strategic.h"
#include "strategicmap.h"
#include "PostalService.h"
#endif
#define BOBBYR_SHIPMENT_TITLE_TEXT_FONT FONT14ARIAL
#define BOBBYR_SHIPMENT_TITLE_TEXT_COLOR 157
#define BOBBYR_SHIPMENT_STATIC_TEXT_FONT FONT12ARIAL
#define BOBBYR_SHIPMENT_STATIC_TEXT_COLOR 145
#define BOBBYR_BOBBY_RAY_TITLE_X LAPTOP_SCREEN_UL_X + 171
#define BOBBYR_BOBBY_RAY_TITLE_Y LAPTOP_SCREEN_WEB_UL_Y + 3
#define BOBBYR_ORDER_FORM_TITLE_X BOBBYR_BOBBY_RAY_TITLE_X
#define BOBBYR_ORDER_FORM_TITLE_Y BOBBYR_BOBBY_RAY_TITLE_Y + 37
#define BOBBYR_ORDER_FORM_TITLE_WIDTH 159
#define BOBBYR_SHIPMENT_DELIVERY_GRID_X LAPTOP_SCREEN_UL_X + 2
#define BOBBYR_SHIPMENT_DELIVERY_GRID_Y BOBBYR_SHIPMENT_ORDER_GRID_Y
#define BOBBYR_SHIPMENT_DELIVERY_GRID_WIDTH 183
#define BOBBYR_SHIPMENT_ORDER_GRID_X LAPTOP_SCREEN_UL_X + 223
#define BOBBYR_SHIPMENT_ORDER_GRID_Y LAPTOP_SCREEN_WEB_UL_Y + 62
#define BOBBYR_SHIPMENT_BACK_BUTTON_X iScreenWidthOffset + 130
#define BOBBYR_SHIPMENT_BACK_BUTTON_Y iScreenHeightOffset + 400 + LAPTOP_SCREEN_WEB_DELTA_Y + 4
#define BOBBYR_SHIPMENT_HOME_BUTTON_X iScreenWidthOffset + 515
#define BOBBYR_SHIPMENT_HOME_BUTTON_Y BOBBYR_SHIPMENT_BACK_BUTTON_Y
#define BOBBYR_SHIPMENT_NUM_PREVIOUS_SHIPMENTS 13
#define MAX_SHIPMENTS_THAT_FIT_ON_SCREEN 13
#define BOBBYR_SHIPMENT_ORDER_NUM_X iScreenWidthOffset + 116//LAPTOP_SCREEN_UL_X + 9
#define BOBBYR_SHIPMENT_ORDER_NUM_START_Y iScreenHeightOffset + 144
#define BOBBYR_SHIPMENT_ORDER_NUM_WIDTH 64
#define BOBBYR_SHIPMENT_GAP_BTN_LINES 20
#define BOBBYR_SHIPMENT_SHIPMENT_ORDER_NUM_X BOBBYR_SHIPMENT_ORDER_NUM_X
#define BOBBYR_SHIPMENT_SHIPMENT_ORDER_NUM_Y iScreenHeightOffset + 117
#define BOBBYR_SHIPMENT_NUM_ITEMS_X iScreenWidthOffset + 183//BOBBYR_SHIPMENT_ORDER_NUM_X+BOBBYR_SHIPMENT_ORDER_NUM_WIDTH+2
#define BOBBYR_SHIPMENT_NUM_ITEMS_Y BOBBYR_SHIPMENT_SHIPMENT_ORDER_NUM_Y
#define BOBBYR_SHIPMENT_NUM_ITEMS_WIDTH 116
//#define BOBBYR_SHIPMENT_
UINT32 guiBobbyRShipmentGrid;
BOOLEAN gfBobbyRShipmentsDirty = FALSE;
INT32 giBobbyRShipmentSelectedShipment = -1;
//Back Button
void BtnBobbyRShipmentBackCallback(GUI_BUTTON *btn,INT32 reason);
UINT32 guiBobbyRShipmetBack;
INT32 guiBobbyRShipmentBackImage;
//Home Button
void BtnBobbyRShipmentHomeCallback(GUI_BUTTON *btn,INT32 reason);
UINT32 guiBobbyRShipmentHome;
INT32 giBobbyRShipmentHomeImage;
MOUSE_REGION gSelectedPreviousShipmentsRegion[BOBBYR_SHIPMENT_NUM_PREVIOUS_SHIPMENTS];
void SelectPreviousShipmentsRegionCallBack(MOUSE_REGION * pRegion, INT32 iReason );
//
// Function Prototypes
//
void DisplayShipmentGrid();
void DisplayPreviousShipments();
void DisplayShipmentTitles();
void RemovePreviousShipmentsMouseRegions();
void CreatePreviousShipmentsMouseRegions();
INT32 CountNumberValidShipmentForTheShipmentsPage();
//ppp
extern CPostalService gPostalService;
extern vector<PShipmentStruct> gShipmentTable;
//
// Function
//
void GameInitBobbyRShipments()
{
}
BOOLEAN EnterBobbyRShipments()
{
VOBJECT_DESC VObjectDesc;
InitBobbyRWoodBackground();
// load the Order Grid graphic and add it
VObjectDesc.fCreateFlags=VOBJECT_CREATE_FROMFILE;
FilenameForBPP("LAPTOP\\BobbyRay_OnOrder.sti", VObjectDesc.ImageFile);
CHECKF(AddVideoObject(&VObjectDesc, &guiBobbyRShipmentGrid));
guiBobbyRShipmentBackImage = LoadButtonImage("LAPTOP\\CatalogueButton.sti", -1,0,-1,1,-1 );
guiBobbyRShipmetBack = CreateIconAndTextButton( guiBobbyRShipmentBackImage, BobbyROrderFormText[BOBBYR_BACK], BOBBYR_GUNS_BUTTON_FONT,
BOBBYR_GUNS_TEXT_COLOR_ON, BOBBYR_GUNS_SHADOW_COLOR,
BOBBYR_GUNS_TEXT_COLOR_OFF, BOBBYR_GUNS_SHADOW_COLOR,
TEXT_CJUSTIFIED,
BOBBYR_SHIPMENT_BACK_BUTTON_X, BOBBYR_SHIPMENT_BACK_BUTTON_Y, BUTTON_TOGGLE, MSYS_PRIORITY_HIGH,
DEFAULT_MOVE_CALLBACK, BtnBobbyRShipmentBackCallback);
SetButtonCursor( guiBobbyRShipmetBack, CURSOR_LAPTOP_SCREEN);
giBobbyRShipmentHomeImage = UseLoadedButtonImage( guiBobbyRShipmentBackImage, -1,0,-1,1,-1 );
guiBobbyRShipmentHome = CreateIconAndTextButton( giBobbyRShipmentHomeImage, BobbyROrderFormText[BOBBYR_HOME], BOBBYR_GUNS_BUTTON_FONT,
BOBBYR_GUNS_TEXT_COLOR_ON, BOBBYR_GUNS_SHADOW_COLOR,
BOBBYR_GUNS_TEXT_COLOR_OFF, BOBBYR_GUNS_SHADOW_COLOR,
TEXT_CJUSTIFIED,
BOBBYR_SHIPMENT_HOME_BUTTON_X, BOBBYR_SHIPMENT_HOME_BUTTON_Y, BUTTON_TOGGLE, MSYS_PRIORITY_HIGH,
DEFAULT_MOVE_CALLBACK, BtnBobbyRShipmentHomeCallback);
SetButtonCursor( guiBobbyRShipmentHome, CURSOR_LAPTOP_SCREEN);
CreateBobbyRayOrderTitle();
giBobbyRShipmentSelectedShipment = -1;
/*
//if there are shipments
if( giNumberOfNewBobbyRShipment != 0 )
{
INT32 iCnt;
// WDS - If there are more than 13 shipments only show 13 because
// that is all that will fit on the screen. If you show more things
// get corrupted.
INT32 max = giNumberOfNewBobbyRShipment;
if (max > MAX_SHIPMENTS_THAT_FIT_ON_SCREEN)
max = MAX_SHIPMENTS_THAT_FIT_ON_SCREEN;
//get the first shipment #
for( iCnt=0; iCnt<max; iCnt++ )
{
if( gpNewBobbyrShipments[iCnt].fActive )
giBobbyRShipmentSelectedShipment = iCnt;
}
}
*/
//if there are shipments
if( gShipmentTable.size() != 0 )
{
INT32 iCnt=0;
//get the first shipment #
vector<PShipmentStruct>::iterator& psi = gShipmentTable.begin();
while(psi != gShipmentTable.end())
{
if(((PShipmentStruct)*psi)->ShipmentStatus == SHIPMENT_INTRANSIT)
{
giBobbyRShipmentSelectedShipment = iCnt;
}
psi++;
iCnt++;
}
}
CreatePreviousShipmentsMouseRegions();
return( TRUE );
}
void ExitBobbyRShipments()
{
DeleteBobbyRWoodBackground();
DestroyBobbyROrderTitle();
DeleteVideoObjectFromIndex(guiBobbyRShipmentGrid);
UnloadButtonImage( guiBobbyRShipmentBackImage );
UnloadButtonImage( giBobbyRShipmentHomeImage );
RemoveButton( guiBobbyRShipmetBack );
RemoveButton( guiBobbyRShipmentHome );
RemovePreviousShipmentsMouseRegions();
}
void HandleBobbyRShipments()
{
if( gfBobbyRShipmentsDirty )
{
gfBobbyRShipmentsDirty = FALSE;
RenderBobbyRShipments();
}
}
void RenderBobbyRShipments()
{
// HVOBJECT hPixHandle;
// Dealtar: this must be static as this is accessed after this function has returned
static BobbyRayPurchaseStruct brps[MAX_PURCHASE_AMOUNT];
for(int i = 0; i < MAX_PURCHASE_AMOUNT; i++)
{
memset(&brps[i], 0, sizeof(BobbyRayPurchaseStruct));
}
DrawBobbyRWoodBackground();
DrawBobbyROrderTitle();
//Output the title
DrawTextToScreen(gzBobbyRShipmentText[ BOBBYR_SHIPMENT__TITLE ], BOBBYR_ORDER_FORM_TITLE_X, BOBBYR_ORDER_FORM_TITLE_Y, BOBBYR_ORDER_FORM_TITLE_WIDTH, BOBBYR_SHIPMENT_TITLE_TEXT_FONT, BOBBYR_SHIPMENT_TITLE_TEXT_COLOR, FONT_MCOLOR_BLACK, FALSE, CENTER_JUSTIFIED);
DisplayShipmentGrid();
if(giBobbyRShipmentSelectedShipment != -1)
{
RefToShipmentPackageListIterator spli = gShipmentTable[giBobbyRShipmentSelectedShipment]->ShipmentPackages.begin();
int j;
for(unsigned i = 0; i < gShipmentTable[giBobbyRShipmentSelectedShipment]->ShipmentPackages.size(); i++, spli++)
{
brps[i].bItemQuality = ((ShipmentPackageStruct)*spli).bItemQuality;
brps[i].ubNumberPurchased = ((ShipmentPackageStruct)*spli).ubNumber;
brps[i].usItemIndex = ((ShipmentPackageStruct)*spli).usItemIndex;
brps[i].fUsed = (((ShipmentPackageStruct)*spli).bItemQuality < 100);
if(brps[i].fUsed)
{
for(j=0; j < MAXITEMS; j++)
{
if(LaptopSaveInfo.BobbyRayUsedInventory[j].usItemIndex == brps[i].usItemIndex)
{
break;
}
}
brps[i].usBobbyItemIndex = j;
}
else
{
for(j=0; j < MAXITEMS; j++)
{
if(LaptopSaveInfo.BobbyRayInventory[j].usItemIndex == brps[i].usItemIndex)
{
break;
}
}
brps[i].usBobbyItemIndex = j;
}
}
}
/*
if( giBobbyRShipmentSelectedShipment != -1 &&
gpNewBobbyrShipments[ giBobbyRShipmentSelectedShipment ].fActive &&
gpNewBobbyrShipments[ giBobbyRShipmentSelectedShipment ].fDisplayedInShipmentPage )
{
// DisplayPurchasedItems( FALSE, BOBBYR_SHIPMENT_ORDER_GRID_X, BOBBYR_SHIPMENT_ORDER_GRID_Y, &LaptopSaveInfo.BobbyRayOrdersOnDeliveryArray[giBobbyRShipmentSelectedShipment].BobbyRayPurchase[0], FALSE );
DisplayPurchasedItems( FALSE, BOBBYR_SHIPMENT_ORDER_GRID_X, BOBBYR_SHIPMENT_ORDER_GRID_Y, &gpNewBobbyrShipments[giBobbyRShipmentSelectedShipment].BobbyRayPurchase[0], FALSE, giBobbyRShipmentSelectedShipment );
}
else
{
// DisplayPurchasedItems( FALSE, BOBBYR_SHIPMENT_ORDER_GRID_X, BOBBYR_SHIPMENT_ORDER_GRID_Y, &LaptopSaveInfo.BobbyRayOrdersOnDeliveryArray[giBobbyRShipmentSelectedShipment].BobbyRayPurchase[0], TRUE );
DisplayPurchasedItems( FALSE, BOBBYR_SHIPMENT_ORDER_GRID_X, BOBBYR_SHIPMENT_ORDER_GRID_Y, NULL, TRUE, giBobbyRShipmentSelectedShipment );
}
*/
if( giBobbyRShipmentSelectedShipment != -1 &&
gShipmentTable[ giBobbyRShipmentSelectedShipment ]->ShipmentStatus == SHIPMENT_INTRANSIT) // &&
{
DisplayPurchasedItems( FALSE, BOBBYR_SHIPMENT_ORDER_GRID_X, BOBBYR_SHIPMENT_ORDER_GRID_Y,&brps[0], FALSE, giBobbyRShipmentSelectedShipment );
}
else
{
DisplayPurchasedItems( FALSE, BOBBYR_SHIPMENT_ORDER_GRID_X, BOBBYR_SHIPMENT_ORDER_GRID_Y, NULL, TRUE, giBobbyRShipmentSelectedShipment );
}
DisplayShipmentTitles();
DisplayPreviousShipments();
MarkButtonsDirty( );
RenderWWWProgramTitleBar( );
InvalidateRegion(LAPTOP_SCREEN_UL_X,LAPTOP_SCREEN_WEB_UL_Y,LAPTOP_SCREEN_LR_X,LAPTOP_SCREEN_WEB_LR_Y);
}
void BtnBobbyRShipmentBackCallback(GUI_BUTTON *btn,INT32 reason)
{
if(reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
btn->uiFlags |= BUTTON_CLICKED_ON;
InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY);
}
if(reason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
btn->uiFlags &= (~BUTTON_CLICKED_ON );
guiCurrentLaptopMode = LAPTOP_MODE_BOBBY_R_MAILORDER;
InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY);
}
if(reason & MSYS_CALLBACK_REASON_LOST_MOUSE)
{
btn->uiFlags &= (~BUTTON_CLICKED_ON );
InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY);
}
}
void BtnBobbyRShipmentHomeCallback(GUI_BUTTON *btn,INT32 reason)
{
if(reason & MSYS_CALLBACK_REASON_LBUTTON_DWN )
{
btn->uiFlags |= BUTTON_CLICKED_ON;
InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY);
}
if(reason & MSYS_CALLBACK_REASON_LBUTTON_UP )
{
btn->uiFlags &= (~BUTTON_CLICKED_ON );
guiCurrentLaptopMode = LAPTOP_MODE_BOBBY_R;
InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY);
}
if(reason & MSYS_CALLBACK_REASON_LOST_MOUSE)
{
btn->uiFlags &= (~BUTTON_CLICKED_ON );
InvalidateRegion(btn->Area.RegionTopLeftX, btn->Area.RegionTopLeftY, btn->Area.RegionBottomRightX, btn->Area.RegionBottomRightY);
}
}
void DisplayShipmentGrid()
{
HVOBJECT hPixHandle;
GetVideoObject(&hPixHandle, guiBobbyRShipmentGrid);
// Shipment Order Grid
BltVideoObject(FRAME_BUFFER, hPixHandle, 0, BOBBYR_SHIPMENT_DELIVERY_GRID_X, BOBBYR_SHIPMENT_DELIVERY_GRID_Y, VO_BLT_SRCTRANSPARENCY,NULL);
// Order Grid
BltVideoObject(FRAME_BUFFER, hPixHandle, 1, BOBBYR_SHIPMENT_ORDER_GRID_X, BOBBYR_SHIPMENT_ORDER_GRID_Y, VO_BLT_SRCTRANSPARENCY,NULL);
}
void DisplayShipmentTitles()
{
//output the order #
DrawTextToScreen( gzBobbyRShipmentText[BOBBYR_SHIPMENT__ORDERED_ON], BOBBYR_SHIPMENT_SHIPMENT_ORDER_NUM_X, BOBBYR_SHIPMENT_SHIPMENT_ORDER_NUM_Y, BOBBYR_SHIPMENT_ORDER_NUM_WIDTH, BOBBYR_SHIPMENT_STATIC_TEXT_FONT, BOBBYR_SHIPMENT_STATIC_TEXT_COLOR, FONT_MCOLOR_BLACK, FALSE, CENTER_JUSTIFIED );
//Output the # of items
DrawTextToScreen( gzBobbyRShipmentText[BOBBYR_SHIPMENT__NUM_ITEMS], BOBBYR_SHIPMENT_NUM_ITEMS_X, BOBBYR_SHIPMENT_NUM_ITEMS_Y, BOBBYR_SHIPMENT_NUM_ITEMS_WIDTH, BOBBYR_SHIPMENT_STATIC_TEXT_FONT, BOBBYR_SHIPMENT_STATIC_TEXT_COLOR, FONT_MCOLOR_BLACK, FALSE, CENTER_JUSTIFIED );
}
void DisplayPreviousShipments()
{
UINT32 uiCnt;
CHAR16 zText[512];
UINT16 usPosY = BOBBYR_SHIPMENT_ORDER_NUM_START_Y;
UINT32 uiNumItems; // = CountNumberValidShipmentForTheShipmentsPage();
UINT32 uiNumberItemsInShipments = 0;
UINT32 uiItemCnt;
UINT8 ubFontColor = BOBBYR_SHIPMENT_STATIC_TEXT_COLOR;
RefToShipmentListIterator sli = gPostalService.LookupShipmentList().begin();
uiNumItems = (UINT32)gPostalService.LookupShipmentList().size();
if(uiNumItems > BOBBYR_SHIPMENT_NUM_PREVIOUS_SHIPMENTS)
uiNumItems = BOBBYR_SHIPMENT_NUM_PREVIOUS_SHIPMENTS;
//loop through all the shipments
for( uiCnt=0; uiCnt<uiNumItems; uiCnt++ )
{
/*
//if it is a valid shipment, and can be displayed at bobby r
if( gpNewBobbyrShipments[ uiCnt ].fActive &&
gpNewBobbyrShipments[ giBobbyRShipmentSelectedShipment ].fDisplayedInShipmentPage )
*/
// if it is a shipment that is active (= in transit)
if( gShipmentTable[ uiCnt ]->ShipmentStatus == SHIPMENT_INTRANSIT)
{
if( uiCnt == (UINT32)giBobbyRShipmentSelectedShipment )
{
ubFontColor = FONT_MCOLOR_WHITE;
}
else
{
ubFontColor = BOBBYR_SHIPMENT_STATIC_TEXT_COLOR;
}
//Display the "ordered on day num"
//swprintf( zText, L"%s %d", gpGameClockString[0], gpNewBobbyrShipments[ uiCnt ].uiOrderedOnDayNum );
swprintf( zText, L"%s %d", gpGameClockString[0], gShipmentTable[ uiCnt ]->uiOrderDate );
DrawTextToScreen( zText, BOBBYR_SHIPMENT_ORDER_NUM_X, usPosY, BOBBYR_SHIPMENT_ORDER_NUM_WIDTH, BOBBYR_SHIPMENT_STATIC_TEXT_FONT, ubFontColor, 0, FALSE, CENTER_JUSTIFIED );
uiNumberItemsInShipments = 0;
/*
// for( uiItemCnt=0; uiItemCnt<LaptopSaveInfo.BobbyRayOrdersOnDeliveryArray[ uiCnt ].ubNumberPurchases; uiItemCnt++ )
for( uiItemCnt=0; uiItemCnt<gpNewBobbyrShipments[ uiCnt ].ubNumberPurchases; uiItemCnt++ )
{
// uiNumberItemsInShipments += LaptopSaveInfo.BobbyRayOrdersOnDeliveryArray[ uiCnt ].BobbyRayPurchase[uiItemCnt].ubNumberPurchased;
uiNumberItemsInShipments += gpNewBobbyrShipments[ uiCnt ].BobbyRayPurchase[uiItemCnt].ubNumberPurchased;
}
*/
for( uiItemCnt=0; uiItemCnt<gShipmentTable[ uiCnt ]->ShipmentPackages.size(); uiItemCnt++ )
{
uiNumberItemsInShipments += gShipmentTable[ uiCnt ]->ShipmentPackages[uiItemCnt].ubNumber;
}
//Display the # of items
swprintf( zText, L"%d", uiNumberItemsInShipments );
DrawTextToScreen( zText, BOBBYR_SHIPMENT_NUM_ITEMS_X, usPosY, BOBBYR_SHIPMENT_NUM_ITEMS_WIDTH, BOBBYR_SHIPMENT_STATIC_TEXT_FONT, ubFontColor, 0, FALSE, CENTER_JUSTIFIED );
usPosY += BOBBYR_SHIPMENT_GAP_BTN_LINES;
}
}
}
void CreatePreviousShipmentsMouseRegions()
{
UINT32 uiCnt;
UINT16 usPosY = BOBBYR_SHIPMENT_ORDER_NUM_START_Y;
UINT16 usWidth = BOBBYR_SHIPMENT_DELIVERY_GRID_WIDTH;
UINT16 usHeight = GetFontHeight( BOBBYR_SHIPMENT_STATIC_TEXT_FONT );
//UINT32 uiNumItems = CountNumberOfBobbyPurchasesThatAreInTransit();
UINT32 uiNumItems = gPostalService.GetShipmentCount(SHIPMENT_INTRANSIT);
// WDS - If there are more than 13 shipments only show 13 because
// that is all that will fit on the screen. If you show more things
// get corrupted.
UINT32 max = uiNumItems;
if (max > MAX_SHIPMENTS_THAT_FIT_ON_SCREEN)
max = MAX_SHIPMENTS_THAT_FIT_ON_SCREEN;
for( uiCnt=0; uiCnt<max; uiCnt++ )
{
MSYS_DefineRegion( &gSelectedPreviousShipmentsRegion[uiCnt], BOBBYR_SHIPMENT_ORDER_NUM_X, usPosY, (UINT16)(BOBBYR_SHIPMENT_ORDER_NUM_X+usWidth), (UINT16)(usPosY+usHeight), MSYS_PRIORITY_HIGH,
CURSOR_WWW, MSYS_NO_CALLBACK, SelectPreviousShipmentsRegionCallBack );
MSYS_AddRegion(&gSelectedPreviousShipmentsRegion[uiCnt]);
MSYS_SetRegionUserData( &gSelectedPreviousShipmentsRegion[uiCnt], 0, uiCnt);
usPosY += BOBBYR_SHIPMENT_GAP_BTN_LINES;
}
}
void RemovePreviousShipmentsMouseRegions()
{
UINT32 uiCnt;
//UINT32 uiNumItems = CountNumberOfBobbyPurchasesThatAreInTransit();
UINT32 uiNumItems = gPostalService.GetShipmentCount(SHIPMENT_INTRANSIT);
for( uiCnt=0; uiCnt<uiNumItems; uiCnt++ )
{
MSYS_RemoveRegion( &gSelectedPreviousShipmentsRegion[uiCnt] );
}
}
void SelectPreviousShipmentsRegionCallBack(MOUSE_REGION * pRegion, INT32 iReason )
{
if (iReason & MSYS_CALLBACK_REASON_INIT)
{
}
else if(iReason & MSYS_CALLBACK_REASON_LBUTTON_UP)
{
INT32 iSlotID = MSYS_GetRegionUserData( pRegion, 0 );
// if( CountNumberOfBobbyPurchasesThatAreInTransit() > iSlotID )
if( gPostalService.GetShipmentCount(SHIPMENT_INTRANSIT) > iSlotID )
{
INT32 iCnt;
INT32 iValidShipmentCounter=0;
giBobbyRShipmentSelectedShipment = -1;
//loop through and get the "x" iSlotID shipment
// for( iCnt=0; iCnt<giNumberOfNewBobbyRShipment; iCnt++ )
for( iCnt=0; iCnt<gPostalService.GetShipmentCount(SHIPMENT_INTRANSIT); iCnt++ )
{
// if( gpNewBobbyrShipments[iCnt].fActive )
if( gShipmentTable[iCnt]->ShipmentStatus == SHIPMENT_INTRANSIT )
{
if( iValidShipmentCounter == iSlotID )
{
giBobbyRShipmentSelectedShipment = iCnt;
}
iValidShipmentCounter++;
}
}
}
gfBobbyRShipmentsDirty = TRUE;
}
}
//Dealtar's Airport Externalization
/*
* Function no longer used.
INT32 CountNumberValidShipmentForTheShipmentsPage()
{
if( giNumberOfNewBobbyRShipment > BOBBYR_SHIPMENT_NUM_PREVIOUS_SHIPMENTS )
return( BOBBYR_SHIPMENT_NUM_PREVIOUS_SHIPMENTS );
else
return( giNumberOfNewBobbyRShipment );
}
*/
| [
"jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1"
]
| [
[
[
1,
543
]
]
]
|
d671ba7407eafc69e29a84cf67b1b32f31cce504 | 9a6a9d17dde3e8888d8183618a02863e46f072f1 | /SettingsDialog.h | fb24b16b4939ab1abe51b852d9ff0e80358e4f47 | []
| no_license | pritykovskaya/max-visualization | 34266c449fb2c03bed6fd695e0b54f144d78e123 | a3c0879a8030970bb1fee95d2bfc6ccf689972ea | refs/heads/master | 2021-01-21T12:23:01.436525 | 2011-07-06T18:23:38 | 2011-07-06T18:23:38 | 2,006,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 417 | h | #pragma once
// SettingsDialog dialog
class SettingsDialog : public CDialog
{
DECLARE_DYNAMIC(SettingsDialog)
public:
SettingsDialog(CWnd* pParent = NULL); // standard constructor
virtual ~SettingsDialog();
// Dialog Data
enum { IDD = IDD_DIALOG1 };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
int natasha;
};
| [
"[email protected]"
]
| [
[
[
1,
23
]
]
]
|
aa9adec870a7e36bbfab6c7ec5d1e6228d9627c9 | f66e343bd16f5dd4c2652c2f8753efd90fb4e813 | /ext/CapFile.h | aa387f9e65942f5c82d7b37152e7eaefa9d6c43c | []
| no_license | footprint4me/rcapdissector | 7046307f9053fe515a9a0b5c6212a5f4d0e5c1c1 | 399a2da4229f8f371a8c3f4c88fa99ce1985a0eb | refs/heads/master | 2021-01-14T10:28:15.490402 | 2010-11-07T17:47:42 | 2010-11-07T17:47:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,902 | h | #pragma once
#include "RubyAndShit.h"
#include "rcapdissector.h"
#ifdef USE_LOOKASIDE_LIST
#include "RubyAllocator.h"
#include "ProtocolTreeNodeLookasideList.h"
#endif
class CapFile
{
public:
static VALUE createClass();
static void initPacketCapture();
static void deinitPacketCapture();
#ifdef USE_LOOKASIDE_LIST
ProtocolTreeNodeLookasideList& getNodeLookasideList() { return _nodeLookaside; }
#endif
private:
CapFile(void);
virtual ~CapFile(void);
/*@ Packet capture helper methods */
static const char* buildCfOpenErrorMessage(int err,
gchar *err_info,
gboolean for_writing,
int file_type);
/*@ Methods implementing the CapFile Ruby object methods */
static void free(void* p);
static VALUE alloc(VALUE klass);
static VALUE initialize(VALUE self, VALUE capfile);
static VALUE init_copy(VALUE copy, VALUE orig);
static VALUE set_preference(VALUE klass, VALUE name, VALUE value);
static VALUE set_wlan_decryption_key(VALUE klass, VALUE key);
static VALUE set_wlan_decryption_keys(VALUE klass, VALUE keys);
static VALUE set_display_filter(VALUE self, VALUE filter);
static VALUE each_packet(VALUE self);
static VALUE close_capture_file(VALUE self);
static VALUE deinitialize();
/*@ Instance methods that actually perform the CapFile-specific work */
void openCaptureFile(VALUE capFileName);
void closeCaptureFile();
void setDisplayFilter(VALUE filter);
void eachPacket();
static void setPreference(const char* name, const char* value);
static void setWlanDecryptionKey(VALUE key);
static void setWlanDecryptionKeys(VALUE keys);
void setupColumns();
static gint* COLUMNS;
static gint NUM_COLUMNS;
VALUE _self;
capture_file _cf;
#ifdef USE_LOOKASIDE_LIST
RubyAllocator _allocator;
ProtocolTreeNodeLookasideList _nodeLookaside;
#endif
};
| [
"[email protected]"
]
| [
[
[
1,
73
]
]
]
|
bd2dbeed4b5ef0a6f4a0610b2d6c540fc3b7fe21 | 61e4e71a9ad4ac3fdce3c1595c627b9c79a68c29 | /src/cppsqlite3/CppSQLite3U.h | 61268fe5acc9209c0691f45355006d53c4271e06 | []
| no_license | oot/signpost | c2ff81bdb3ab75a5511eedd18798d637cd080526 | 8a8e5c6c693217daf56398e6bb59f89563f9689b | refs/heads/master | 2016-09-05T19:52:41.876837 | 2010-11-19T08:07:48 | 2010-11-19T08:07:48 | 32,301,199 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,707 | h | ////////////////////////////////////////////////////////////////////////////////
// CppSQLite3U is a C++ unicode wrapper around the SQLite3 embedded database library.
//
// Copyright (c) 2006 Tyushkov Nikolay. All Rights Reserved. http://softvoile.com
//
//
// Based on beautiful wrapper written by Rob Groves
// (https://secure.codeproject.com/database/CppSQLite.asp).
// Very good wrapper, but without unicode support unfortunately.
// So, I have reconstructed it for unicode.
//
// CppSQLite3 wrapper:
// Copyright (c) 2004 Rob Groves. All Rights Reserved. [email protected]
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement, is hereby granted, provided that the above copyright notice,
// this paragraph and the following two paragraphs appear in all copies,
// modifications, and distributions.
//
// IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
// INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST
// PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
// EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF
// ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". THE AUTHOR HAS NO OBLIGATION
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
//
// If you want to get some documentation look at
// https://secure.codeproject.com/database/CppSQLite.asp
// Note, not all features from CppSQLite3 were implemented in CppSQLite3U
//
// V1.0 11/06/2006 - Initial Public Version
//
// Noteses :
// I have tested this wrapper only in unicode version, so I have no idea
// about its work in ANSI configuration, I think it doesn't work without modification;)
//
// Home page : http://softvoile.com/development/CppSQLite3U/
// Please send all bug report and comment to [email protected]
//
//
////////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_CPPSQLITE3U_H__1B1BE273_2D1E_439C_946F_3CBD1C0EFD2F__INCLUDED_)
#define AFX_CPPSQLITE3U_H__1B1BE273_2D1E_439C_946F_3CBD1C0EFD2F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// CppSQLite3U.h : header file
//
#ifdef __LIB_SIT_EXPORT__
#define DllExport __declspec(dllexport)
#else
#define DllExport __declspec(dllimport)
#endif /* __LIB_SIT_EXPORT__ */
#include <sqlite3/sqlite3.h>
/////////////////////////////////////////////////////////////////////////////
#define SQL_MAXSIZE 2048
#define CPPSQLITE_ERROR 1000
static const bool DONT_DELETE_MSG=false;
CString DoubleQuotes(CString in);
class CppSQLite3Query;
class CppSQLite3Statement;
class CppSQLite3Exception
{
public:
CppSQLite3Exception(const int nErrCode,
LPTSTR szErrMess,
bool bDeleteMsg=true);
CppSQLite3Exception(const CppSQLite3Exception& e);
virtual ~CppSQLite3Exception();
const int errorCode() { return mnErrCode; }
LPCTSTR errorMessage() { return mpszErrMess; }
static LPCTSTR errorCodeAsString(int nErrCode);
private:
int mnErrCode;
LPTSTR mpszErrMess;
};
class CppSQLite3DB
{
// Construction
public:
CppSQLite3DB();
// Operations
public:
virtual ~CppSQLite3DB();
void open(LPCTSTR szFile);
void close();
bool tableExists(LPCTSTR szTable);
int execDML(LPCTSTR szSQL);
CppSQLite3Query execQuery(LPCTSTR szSQL);
int execScalar(LPCTSTR szSQL);
CString execScalarStr(LPCTSTR szSQL);
CppSQLite3Statement compileStatement(LPCTSTR szSQL);
sqlite_int64 lastRowId();
void interrupt() { sqlite3_interrupt(mpDB); }
void setBusyTimeout(int nMillisecs);
static const char* SQLiteVersion() { return SQLITE_VERSION; }
private:
CppSQLite3DB(const CppSQLite3DB& db);
CppSQLite3DB& operator=(const CppSQLite3DB& db);
sqlite3_stmt* compile(LPCTSTR szSQL);
void checkDB();
public:
sqlite3* mpDB;
int mnBusyTimeoutMs;
};
/////////////////////////////////////////////////////////////////////////////
class CppSQLite3Statement
{
public:
CppSQLite3Statement();
CppSQLite3Statement(const CppSQLite3Statement& rStatement);
CppSQLite3Statement(sqlite3* pDB, sqlite3_stmt* pVM);
virtual ~CppSQLite3Statement();
CppSQLite3Statement& operator=(const CppSQLite3Statement& rStatement);
int execDML();
CppSQLite3Query execQuery();
void bind(int nParam, LPCTSTR szValue);
void bind(int nParam, const int nValue);
void bind(int nParam, const double dwValue);
void bind(int nParam, const unsigned char* blobValue, int nLen);
void bindNull(int nParam);
void reset();
void finalize();
private:
void checkDB();
void checkVM();
sqlite3* mpDB;
sqlite3_stmt* mpVM;
};
///////////////////// CppSQLite3Query //////////////////////////////////////////////////
class CppSQLite3Query
{
public:
CppSQLite3Query();
CppSQLite3Query(const CppSQLite3Query& rQuery);
CppSQLite3Query(sqlite3* pDB,
sqlite3_stmt* pVM,
bool bEof,
bool bOwnVM=true);
CppSQLite3Query& operator=(const CppSQLite3Query& rQuery);
virtual ~CppSQLite3Query();
int numFields();
int fieldIndex(LPCTSTR szField);
LPCTSTR fieldName(int nCol);
LPCTSTR fieldDeclType(int nCol);
int fieldDataType(int nCol);
LPCTSTR fieldValue(int nField);
LPCTSTR fieldValue(LPCTSTR szField);
int getIntField(int nField, int nNullValue=0);
int getIntField(LPCTSTR szField, int nNullValue=0);
double getFloatField(int nField, double fNullValue=0.0);
double getFloatField(LPCTSTR szField, double fNullValue=0.0);
LPCTSTR getStringField(int nField, LPCTSTR szNullValue=_T(""));
LPCTSTR getStringField(LPCTSTR szField, LPCTSTR szNullValue=_T(""));
const unsigned char* getBlobField(int nField, int& nLen);
const unsigned char* getBlobField(LPCTSTR szField, int& nLen);
bool fieldIsNull(int nField);
bool fieldIsNull(LPCTSTR szField);
bool eof();
void nextRow();
void finalize();
private:
void checkVM();
sqlite3* mpDB;
sqlite3_stmt* mpVM;
bool mbEof;
int mnCols;
bool mbOwnVM;
};
/////////////////////////////////////////////////////////////////////////////
//
// TCHAR based sqlite3 function names for Unicode/MCBS builds.
//
#if defined(_UNICODE) || defined(UNICODE)
#pragma message("Unicode Selected")
#define _sqlite3_aggregate_context sqlite3_aggregate_context
#define _sqlite3_aggregate_count sqlite3_aggregate_count
#define _sqlite3_bind_blob sqlite3_bind_blob
#define _sqlite3_bind_double sqlite3_bind_double
#define _sqlite3_bind_int sqlite3_bind_int
#define _sqlite3_bind_int64 sqlite3_bind_int64
#define _sqlite3_bind_null sqlite3_bind_null
#define _sqlite3_bind_parameter_count sqlite3_bind_parameter_count
#define _sqlite3_bind_parameter_index sqlite3_bind_parameter_index
#define _sqlite3_bind_parameter_name sqlite3_bind_parameter_name
#define _sqlite3_bind_text sqlite3_bind_text16
#define _sqlite3_bind_text16 sqlite3_bind_text16
#define _sqlite3_busy_handler sqlite3_busy_handler
#define _sqlite3_busy_timeout sqlite3_busy_timeout
#define _sqlite3_changes sqlite3_changes
#define _sqlite3_close sqlite3_close
#define _sqlite3_collation_needed sqlite3_collation_needed16
#define _sqlite3_collation_needed16 sqlite3_collation_needed16
#define _sqlite3_column_blob sqlite3_column_blob
#define _sqlite3_column_bytes sqlite3_column_bytes16
#define _sqlite3_column_bytes16 sqlite3_column_bytes16
#define _sqlite3_column_count sqlite3_column_count
#define _sqlite3_column_decltype sqlite3_column_decltype16
#define _sqlite3_column_decltype16 sqlite3_column_decltype16
#define _sqlite3_column_double sqlite3_column_double
#define _sqlite3_column_int sqlite3_column_int
#define _sqlite3_column_int64 sqlite3_column_int64
#define _sqlite3_column_name sqlite3_column_name16
#define _sqlite3_column_name16 sqlite3_column_name16
#define _sqlite3_column_text sqlite3_column_text16
#define _sqlite3_column_text16 sqlite3_column_text16
#define _sqlite3_column_type sqlite3_column_type
#define _sqlite3_commit_hook sqlite3_commit_hook
#define _sqlite3_complete sqlite3_complete16
#define _sqlite3_complete16 sqlite3_complete16
#define _sqlite3_create_collation sqlite3_create_collation16
#define _sqlite3_create_collation16 sqlite3_create_collation16
#define _sqlite3_create_function sqlite3_create_function16
#define _sqlite3_create_function16 sqlite3_create_function16
#define _sqlite3_data_count sqlite3_data_count
#define _sqlite3_errcode sqlite3_errcode
#define _sqlite3_errmsg sqlite3_errmsg16
#define _sqlite3_errmsg16 sqlite3_errmsg16
#define _sqlite3_exec sqlite3_exec
#define _sqlite3_finalize sqlite3_finalize
#define _sqlite3_free sqlite3_free
#define _sqlite3_free_table sqlite3_free_table
#define _sqlite3_get_table sqlite3_get_table
#define _sqlite3_interrupt sqlite3_interrupt
#define _sqlite3_last_insert_rowid sqlite3_last_insert_rowid
#define _sqlite3_libversion sqlite3_libversion
#define _sqlite3_mprintf sqlite3_mprintf
#define _sqlite3_open sqlite3_open16
#define _sqlite3_open16 sqlite3_open16
#define _sqlite3_prepare sqlite3_prepare16
#define _sqlite3_prepare16 sqlite3_prepare16
#define _sqlite3_progress_handler sqlite3_progress_handler
#define _sqlite3_reset sqlite3_reset
#define _sqlite3_result_blob sqlite3_result_blob
#define _sqlite3_result_double sqlite3_result_double
#define _sqlite3_result_error sqlite3_result_error16
#define _sqlite3_result_error16 sqlite3_result_error16
#define _sqlite3_result_int sqlite3_result_int
#define _sqlite3_result_int64 sqlite3_result_int64
#define _sqlite3_result_null sqlite3_result_null
#define _sqlite3_result_text sqlite3_result_text16
#define _sqlite3_result_text16 sqlite3_result_text16
#define _sqlite3_result_text16be sqlite3_result_text16be
#define _sqlite3_result_text16le sqlite3_result_text16le
#define _sqlite3_result_value sqlite3_result_value
#define _sqlite3_set_authorizer sqlite3_set_authorizer
#define _sqlite3_step sqlite3_step
#define _sqlite3_total_changes sqlite3_total_changes
#define _sqlite3_trace sqlite3_trace
#define _sqlite3_user_data sqlite3_user_data
#define _sqlite3_value_blob sqlite3_value_blob
#define _sqlite3_value_bytes sqlite3_value_bytes16
#define _sqlite3_value_bytes16 sqlite3_value_bytes16
#define _sqlite3_value_double sqlite3_value_double
#define _sqlite3_value_int sqlite3_value_int
#define _sqlite3_value_int64 sqlite3_value_int64
#define _sqlite3_value_text sqlite3_value_text16
#define _sqlite3_value_text16 sqlite3_value_text16
#define _sqlite3_value_text16be sqlite3_value_text16be
#define _sqlite3_value_text16le sqlite3_value_text16le
#define _sqlite3_value_type sqlite3_value_type
#define _sqlite3_vmprintf sqlite3_vmprintf
#else
#pragma message("MCBS Selected")
#define _sqlite3_aggregate_context sqlite3_aggregate_context
#define _sqlite3_aggregate_count sqlite3_aggregate_count
#define _sqlite3_bind_blob sqlite3_bind_blob
#define _sqlite3_bind_double sqlite3_bind_double
#define _sqlite3_bind_int sqlite3_bind_int
#define _sqlite3_bind_int64 sqlite3_bind_int64
#define _sqlite3_bind_null sqlite3_bind_null
#define _sqlite3_bind_parameter_count sqlite3_bind_parameter_count
#define _sqlite3_bind_parameter_index sqlite3_bind_parameter_index
#define _sqlite3_bind_parameter_name sqlite3_bind_parameter_name
#define _sqlite3_bind_text sqlite3_bind_text
#define _sqlite3_bind_text16 sqlite3_bind_text16
#define _sqlite3_busy_handler sqlite3_busy_handler
#define _sqlite3_busy_timeout sqlite3_busy_timeout
#define _sqlite3_changes sqlite3_changes
#define _sqlite3_close sqlite3_close
#define _sqlite3_collation_needed sqlite3_collation_needed
#define _sqlite3_collation_needed16 sqlite3_collation_needed16
#define _sqlite3_column_blob sqlite3_column_blob
#define _sqlite3_column_bytes sqlite3_column_bytes
#define _sqlite3_column_bytes16 sqlite3_column_bytes16
#define _sqlite3_column_count sqlite3_column_count
#define _sqlite3_column_decltype sqlite3_column_decltype
#define _sqlite3_column_decltype16 sqlite3_column_decltype16
#define _sqlite3_column_double sqlite3_column_double
#define _sqlite3_column_int sqlite3_column_int
#define _sqlite3_column_int64 sqlite3_column_int64
#define _sqlite3_column_name sqlite3_column_name
#define _sqlite3_column_name16 sqlite3_column_name16
#define _sqlite3_column_text sqlite3_column_text
#define _sqlite3_column_text16 sqlite3_column_text16
#define _sqlite3_column_type sqlite3_column_type
#define _sqlite3_commit_hook sqlite3_commit_hook
#define _sqlite3_complete sqlite3_complete
#define _sqlite3_complete16 sqlite3_complete16
#define _sqlite3_create_collation sqlite3_create_collation
#define _sqlite3_create_collation16 sqlite3_create_collation16
#define _sqlite3_create_function sqlite3_create_function
#define _sqlite3_create_function16 sqlite3_create_function16
#define _sqlite3_data_count sqlite3_data_count
#define _sqlite3_errcode sqlite3_errcode
#define _sqlite3_errmsg sqlite3_errmsg
#define _sqlite3_errmsg16 sqlite3_errmsg16
#define _sqlite3_exec sqlite3_exec
#define _sqlite3_finalize sqlite3_finalize
#define _sqlite3_free sqlite3_free
#define _sqlite3_free_table sqlite3_free_table
#define _sqlite3_get_table sqlite3_get_table
#define _sqlite3_interrupt sqlite3_interrupt
#define _sqlite3_last_insert_rowid sqlite3_last_insert_rowid
#define _sqlite3_libversion sqlite3_libversion
#define _sqlite3_mprintf sqlite3_mprintf
#define _sqlite3_open sqlite3_open
#define _sqlite3_open16 sqlite3_open16
#define _sqlite3_prepare sqlite3_prepare
#define _sqlite3_prepare16 sqlite3_prepare16
#define _sqlite3_progress_handler sqlite3_progress_handler
#define _sqlite3_reset sqlite3_reset
#define _sqlite3_result_blob sqlite3_result_blob
#define _sqlite3_result_double sqlite3_result_double
#define _sqlite3_result_error sqlite3_result_error
#define _sqlite3_result_error16 sqlite3_result_error16
#define _sqlite3_result_int sqlite3_result_int
#define _sqlite3_result_int64 sqlite3_result_int64
#define _sqlite3_result_null sqlite3_result_null
#define _sqlite3_result_text sqlite3_result_text
#define _sqlite3_result_text16 sqlite3_result_text16
#define _sqlite3_result_text16be sqlite3_result_text16be
#define _sqlite3_result_text16le sqlite3_result_text16le
#define _sqlite3_result_value sqlite3_result_value
#define _sqlite3_set_authorizer sqlite3_set_authorizer
#define _sqlite3_step sqlite3_step
#define _sqlite3_total_changes sqlite3_total_changes
#define _sqlite3_trace sqlite3_trace
#define _sqlite3_user_data sqlite3_user_data
#define _sqlite3_value_blob sqlite3_value_blob
#define _sqlite3_value_bytes sqlite3_value_bytes
#define _sqlite3_value_bytes16 sqlite3_value_bytes16
#define _sqlite3_value_double sqlite3_value_double
#define _sqlite3_value_int sqlite3_value_int
#define _sqlite3_value_int64 sqlite3_value_int64
#define _sqlite3_value_text sqlite3_value_text
#define _sqlite3_value_text16 sqlite3_value_text16
#define _sqlite3_value_text16be sqlite3_value_text16be
#define _sqlite3_value_text16le sqlite3_value_text16le
#define _sqlite3_value_type sqlite3_value_type
#define _sqlite3_vmprintf sqlite3_vmprintf
#endif
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CPPSQLITE3U_H__1B1BE273_2D1E_439C_946F_3CBD1C0EFD2F__INCLUDED_)
| [
"[email protected]@067241ac-f43e-11dd-9d1a-b59b2e1864b6"
]
| [
[
[
1,
430
]
]
]
|
167b846a3633e6ea115ac47a4d93ca19e252ec3a | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/UnitTests/UnitTest_GraphView/GraphNodeEventController.h | fa10cb6b7844a31bdf118f0cfe6234385ac85744 | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,295 | h | /*!
@file
@author Albert Semenov
@date 08/2009
@module
*/
#ifndef __GRAPH_NODE_EVENT_H__
#define __GRAPH_NODE_EVENT_H__
#include <MyGUI.h>
#include "BaseAnimationNode.h"
#include "EventController.h"
namespace demo
{
class GraphNodeEventController : public BaseAnimationNode
{
public:
GraphNodeEventController(const std::string& _name) :
BaseAnimationNode("GraphNodeEvent.layout", "EventController", _name),
mConnectionOut(nullptr)
{
}
private:
virtual void initialise()
{
mMainWidget->castType<MyGUI::Window>()->setCaption(getName());
assignBase(mConnectionOut, "ConnectionOut");
assignWidget(mButtonEvent, "ButtonEvent");
mButtonEvent->eventMouseButtonClick += MyGUI::newDelegate(this, &GraphNodeEventController::notifyMouseButtonClick);
}
virtual void shutdown()
{
}
void notifyMouseButtonClick(MyGUI::WidgetPtr _sender)
{
onEvent();
}
void onEvent()
{
animation::EventController* controller = dynamic_cast<animation::EventController*>(getAnimationNode());
if (controller)
controller->generateEvent();
}
private:
wraps::BaseGraphConnection* mConnectionOut;
MyGUI::ButtonPtr mButtonEvent;
};
} // namespace demo
#endif // __GRAPH_NODE_EVENT_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
60
]
]
]
|
cb154e7bf8ea58b0a30dc08116a2884052a05a99 | f596200d0a3a98304d8108120bf97a8d4e16319e | /gui/src/eventful.cpp | 55a884286ef9fc606e823f9cf56df164bc1d723b | []
| no_license | justinvh/Rogue-Reborn | 692f8995d21c085bd2290ef22bbd3b2ce737a20c | b4356f3af39e82536c4254a51cc89fa5af0b6452 | refs/heads/master | 2021-01-06T20:38:28.362318 | 2011-01-10T01:07:14 | 2011-01-10T01:07:14 | 952,588 | 13 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 14,070 | cpp | /*
Rogue Reborn GUI "Eventful" source from src/eventful.cpp
Copyright 2010 Justin Bruce Van Horne. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <hat/gui/eventful.hpp>
#include <hat/gui/image.hpp>
#include <hat/gui/gui.hpp>
#include <hat/gui/ui_local.h>
namespace hat {
namespace {
/*
This is a list of accessors made available through the Eventful class.
Any additional elements that are added to the class should be added here.
They will be looped over and added to the accessor list when a template
is constructed.
*/
JS_mapping accessors[] = {
{ NULL, NULL, NULL } // Signals the end of the accessor list
};
/*
This is a list of functions made availabe through the Element class.
Any additional functions that are addeed tot he class should be added here.
They will be looped over and added to the function list when a template
is constructued.
*/
JS_fun_mapping funs[] = {
JS_FUN_MAP(Eventful, mousedown),
JS_FUN_MAP(Eventful, mouseup),
JS_FUN_MAP(Eventful, mousedrag),
JS_FUN_MAP(Eventful, mouseover),
JS_FUN_MAP(Eventful, mouseout),
JS_FUN_MAP(Eventful, scrolldown),
JS_FUN_MAP(Eventful, scrollup),
JS_FUN_MAP(Eventful, keydown),
JS_FUN_MAP(Eventful, keyup),
JS_FUN_MAP(Eventful, keypress),
{ NULL, NULL, NULL } // Signlas the end of the function list
};
}
/*
*/
JS_FUN_CLASS(Eventful, mousedown)
{
JS_BA_FUNCTION(Eventful, eventful_attrs.mouse_down, {
Gui* g = unwrap_global_pointer<Gui>(0);
if (!g) { return v8::Exception::Error(v8::String::New("Gui became detached.")); }
e->mouse_down(g->last_kbm_state.mx, g->last_kbm_state.my, g->last_kbm_state.button);
});
}
/*
*/
JS_FUN_CLASS(Eventful, mouseup)
{
JS_BA_FUNCTION(Eventful, eventful_attrs.mouse_up, {
Gui* g = unwrap_global_pointer<Gui>(0);
if (!g) { return v8::Exception::Error(v8::String::New("Gui became detached.")); }
e->mouse_up(g->last_kbm_state.mx, g->last_kbm_state.my, g->last_kbm_state.button);
});
}
/*
*/
JS_FUN_CLASS(Eventful, mouseover)
{
JS_BA_FUNCTION(Eventful, eventful_attrs.mouse_over, {
Gui* g = unwrap_global_pointer<Gui>(0);
if (!g) { return v8::Exception::Error(v8::String::New("Gui became detached.")); }
e->mouse_over(g->last_kbm_state.mx, g->last_kbm_state.my);
});
}
/*
*/
JS_FUN_CLASS(Eventful, mouseout)
{
JS_BA_FUNCTION(Eventful, eventful_attrs.mouse_out, {
Gui* g = unwrap_global_pointer<Gui>(0);
if (!g) { return v8::Exception::Error(v8::String::New("Gui became detached.")); }
e->mouse_out(g->last_kbm_state.mx, g->last_kbm_state.my);
});
}
/*
*/
JS_FUN_CLASS(Eventful, mousedrag)
{
JS_BA_FUNCTION(Eventful, eventful_attrs.mouse_drag, {
Gui* g = unwrap_global_pointer<Gui>(0);
if (!g) { return v8::Exception::Error(v8::String::New("Gui became detached.")); }
const Gui_kbm& kbm = g->last_kbm_state;
e->mouse_drag(kbm.mx, kbm.my, kbm.button);
});
}
/*
*/
JS_FUN_CLASS(Eventful, scrolldown)
{
JS_BA_FUNCTION(Eventful, eventful_attrs.scroll_down, {
Gui* g = unwrap_global_pointer<Gui>(0);
if (!g) { return v8::Exception::Error(v8::String::New("Gui became detached.")); }
e->scroll_down();
});
}
/*
*/
JS_FUN_CLASS(Eventful, scrollup)
{
JS_BA_FUNCTION(Eventful, eventful_attrs.scroll_up, {
Gui* g = unwrap_global_pointer<Gui>(0);
if (!g) { return v8::Exception::Error(v8::String::New("Gui became detached.")); }
e->scroll_up();
});
}
/*
*/
JS_FUN_CLASS(Eventful, keydown)
{
JS_BA_FUNCTION(Eventful, eventful_attrs.key_down, {
Gui* g = unwrap_global_pointer<Gui>(0);
if (!g) { return v8::Exception::Error(v8::String::New("Gui became detached.")); }
e->key_down(g->last_kbm_state.key);
});
}
/*
*/
JS_FUN_CLASS(Eventful, keyup)
{
JS_BA_FUNCTION(Eventful, eventful_attrs.key_up, {
Gui* g = unwrap_global_pointer<Gui>(0);
if (!g) { return v8::Exception::Error(v8::String::New("Gui became detached.")); }
e->key_up(g->last_kbm_state.key);
});
}
/*
*/
JS_FUN_CLASS(Eventful, keypress)
{
JS_BA_FUNCTION(Eventful, eventful_attrs.key_press, {
Gui* g = unwrap_global_pointer<Gui>(0);
if (!g) { return v8::Exception::Error(v8::String::New("Gui became detached.")); }
e->key_press(g->last_kbm_state.character);
});
}
void Eventful::mouse_down(int mx, int my, int button)
{
eventful_attrs.event_state |= EV_MOUSE_DOWN;
if (!eventful_attrs.mouse_down.size()) return;
v8::HandleScope execution_scope;
v8::Handle<v8::Value> argvs[3] = {
v8::Int32::New(mx), v8::Int32::New(my), v8::Int32::New(button)
};
v8::TryCatch run_try_catch;
for (Function_list::const_iterator tci = eventful_attrs.mouse_down.begin();
tci != eventful_attrs.mouse_down.end();
++tci)
{
(*tci)->Call(self, 3, argvs);
if (run_try_catch.HasCaught()) {
run_try_catch.ReThrow();
return;
}
}
}
void Eventful::mouse_up(int mx, int my, int button)
{
eventful_attrs.event_state |= EV_MOUSE_UP;
set_held_timer(0);
if (!eventful_attrs.mouse_up.size()) return;
v8::HandleScope execution_scope;
v8::Handle<v8::Value> argvs[3] = {
v8::Int32::New(mx), v8::Int32::New(my), v8::Int32::New(button)
};
v8::TryCatch run_try_catch;
for (Function_list::const_iterator tci = eventful_attrs.mouse_up.begin();
tci != eventful_attrs.mouse_up.end();
++tci)
{
(*tci)->Call(self, 3, argvs);
if (run_try_catch.HasCaught()) {
run_try_catch.ReThrow();
return;
}
}
}
bool Eventful::is_draggable(int time)
{
return eventful_attrs.is_mouse_down && eventful_attrs.held_timer > time;
}
void Eventful::update_held_timer(int dt)
{
eventful_attrs.held_timer += dt;
}
void Eventful::set_held_timer(int timer)
{
eventful_attrs.held_timer = timer;
}
void Eventful::mouse_drag(int rx, int ry, int button)
{
eventful_attrs.event_state |= EV_MOUSE_DRAG;
if (!eventful_attrs.mouse_drag.size()) return;
v8::HandleScope execution_scope;
v8::Handle<v8::Value> argvs[3] = {
v8::Int32::New(rx), v8::Int32::New(ry), v8::Int32::New(button)
};
v8::TryCatch run_try_catch;
for (Function_list::const_iterator tci = eventful_attrs.mouse_drag.begin();
tci != eventful_attrs.mouse_drag.end();
++tci)
{
(*tci)->Call(self, 3, argvs);
if (run_try_catch.HasCaught()) {
run_try_catch.ReThrow();
return;
}
}
}
void Eventful::mouse_over(int mx, int my)
{
eventful_attrs.event_state |= EV_MOUSE_OVER;
if (!eventful_attrs.mouse_over.size()) return;
v8::HandleScope execution_scope;
v8::Handle<v8::Value> argvs[2] = {
v8::Int32::New(mx), v8::Int32::New(my)
};
v8::TryCatch run_try_catch;
for (Function_list::const_iterator tci = eventful_attrs.mouse_over.begin();
tci != eventful_attrs.mouse_over.end();
++tci)
{
(*tci)->Call(self, 2, argvs);
if (run_try_catch.HasCaught()) {
run_try_catch.ReThrow();
return;
}
}
}
void Eventful::mouse_out(int mx, int my)
{
eventful_attrs.event_state |= EV_MOUSE_OUT;
if (!eventful_attrs.mouse_out.size()) return;
v8::HandleScope execution_scope;
v8::Handle<v8::Value> argvs[2] = {
v8::Int32::New(mx), v8::Int32::New(my)
};
v8::TryCatch run_try_catch;
for (Function_list::const_iterator tci = eventful_attrs.mouse_out.begin();
tci != eventful_attrs.mouse_out.end();
++tci)
{
(*tci)->Call(self, 2, argvs);
if (run_try_catch.HasCaught()) {
run_try_catch.ReThrow();
return;
}
}
}
void Eventful::key_down(int key)
{
eventful_attrs.event_state |= EV_KEY_DOWN;
if (!eventful_attrs.key_down.size()) return;
v8::HandleScope execution_scope;
v8::Handle<v8::Value> argvs[1] = {
v8::Int32::New(key)
};
v8::TryCatch run_try_catch;
for (Function_list::const_iterator tci = eventful_attrs.key_down.begin();
tci != eventful_attrs.key_down.end();
++tci)
{
(*tci)->Call(self, 1, argvs);
if (run_try_catch.HasCaught()) {
run_try_catch.ReThrow();
return;
}
}
}
void Eventful::key_up(int key)
{
eventful_attrs.event_state |= EV_KEY_UP;
if (!eventful_attrs.key_up.size()) return;
v8::HandleScope execution_scope;
v8::Handle<v8::Value> argvs[1] = {
v8::Int32::New(key)
};
v8::TryCatch run_try_catch;
for (Function_list::const_iterator tci = eventful_attrs.key_up.begin();
tci != eventful_attrs.key_up.end();
++tci)
{
(*tci)->Call(self, 1, argvs);
if (run_try_catch.HasCaught()) {
run_try_catch.ReThrow();
return;
}
}
}
void Eventful::key_press(char character)
{
eventful_attrs.event_state |= EV_KEY_PRESS;
if (!eventful_attrs.key_press.size()) return;
v8::HandleScope execution_scope;
v8::Handle<v8::Value> argvs[1] = {
v8::String::New("" + character)
};
v8::TryCatch run_try_catch;
for (Function_list::const_iterator tci = eventful_attrs.key_press.begin();
tci != eventful_attrs.key_press.end();
++tci)
{
(*tci)->Call(self, 1, argvs);
if (run_try_catch.HasCaught()) {
run_try_catch.ReThrow();
return;
}
}
}
void Eventful::scroll_down()
{
eventful_attrs.event_state |= EV_SCROLL_DOWN;
if (!eventful_attrs.scroll_down.size()) return;
v8::HandleScope execution_scope;
v8::TryCatch run_try_catch;
for (Function_list::const_iterator tci = eventful_attrs.scroll_down.begin();
tci != eventful_attrs.scroll_down.end();
++tci)
{
(*tci)->Call(self, 0, NULL);
if (run_try_catch.HasCaught()) {
run_try_catch.ReThrow();
return;
}
}
}
void Eventful::scroll_up()
{
eventful_attrs.event_state |= EV_SCROLL_UP;
if (!eventful_attrs.scroll_up.size()) return;
v8::HandleScope execution_scope;
v8::TryCatch run_try_catch;
for (Function_list::const_iterator tci = eventful_attrs.scroll_up.begin();
tci != eventful_attrs.scroll_up.end();
++tci)
{
(*tci)->Call(self, 0, NULL);
if (run_try_catch.HasCaught()) {
run_try_catch.ReThrow();
return;
}
}
}
void Eventful::force_state(int state)
{
eventful_attrs.event_state |= state;
}
void Eventful::finish_state()
{
int s = eventful_attrs.event_state;
int p = eventful_attrs.previous_event_state;
eventful_attrs.is_mouse_down = false;
if (s & EV_MOUSE_DOWN) {
eventful_attrs.is_mouse_down = true;
} else if (p & EV_MOUSE_DOWN && !(s & EV_MOUSE_UP)) {
eventful_attrs.is_mouse_down = true;
s |= EV_MOUSE_DOWN;
}
eventful_attrs.is_mouse_up = false;
if (s & EV_MOUSE_UP) {
eventful_attrs.is_mouse_up = true;
eventful_attrs.is_mouse_down = false;
}
eventful_attrs.is_mouse_drag = false;
if (s & EV_MOUSE_DRAG) {
eventful_attrs.is_mouse_drag = true;
}
eventful_attrs.is_mouse_over = false;
if (s & EV_MOUSE_OVER) {
eventful_attrs.is_mouse_over = true;
}
eventful_attrs.is_mouse_out = false;
if (s & EV_MOUSE_OUT) {
eventful_attrs.is_mouse_out = true;
}
eventful_attrs.is_key_down = false;
if (s & EV_KEY_DOWN) {
eventful_attrs.is_key_down = true;
}
eventful_attrs.is_key_up = false;
if (s & EV_KEY_UP) {
eventful_attrs.is_key_up = true;
}
eventful_attrs.is_key_press = false;
if (s & EV_KEY_PRESS) {
eventful_attrs.is_key_press = true;
}
eventful_attrs.is_scroll_up = false;
if (s & EV_SCROLL_UP) {
eventful_attrs.is_scroll_up = true;
}
eventful_attrs.is_scroll_down = false;
if (s & EV_SCROLL_DOWN) {
eventful_attrs.is_scroll_down = true;
}
eventful_attrs.previous_event_state = s;
eventful_attrs.event_state = 0;
}
/*
*/
void Eventful::wrap_extension_list(Extension_list* list)
{
list->push_back(std::make_pair(accessors, funs));
}
}
| [
"[email protected]"
]
| [
[
[
1,
490
]
]
]
|
c61ededc9e4d2354c1d55220eac5af733fcc8a2f | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Scada/Emulation/PLC5/PLC5.cpp | 2d54ffafd033f229c818986d3028cf47682afc3c | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,988 | cpp | // PLC5.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "resource.h"
#include <initguid.h>
#include "PLC5.h"
#include "PLC5Dlg.h"
#include "Dlgs.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//*********************************************************
// FSServer stuff
//#include ".\OpcSrvr\Callback.h" // FSServer callback class
/////////////////////////////////////////////////////////////////////////////
CPLC5Dlg theDlg;//(&m_Plc, &m_Xfer, pOPCCallback);//pOPCCallBack);
/////////////////////////////////////////////////////////////////////////////
// CPLC5App
BEGIN_MESSAGE_MAP(CPLC5App, CWinApp)
//{{AFX_MSG_MAP(CPLC5App)
// NOTE - the ClassWizard will add and remove mapping macros here.
// DO NOT EDIT what you see in these blocks of generated code!
//}}AFX_MSG
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
// ON_MESSAGE( WM_OPCCMD, OnOpcCmd)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CPLC5App construction
CPLC5App::CPLC5App()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
m_UpNAbout=FALSE;
}
/////////////////////////////////////////////////////////////////////////////
// The one and only CPLC5App object
CPLC5App theApp;
//CPLC5Module _Module;
//
//BEGIN_OBJECT_MAP(ObjectMap)
//OBJECT_ENTRY(CLSID_SysCADCmd, CSysCADCmd)
//END_OBJECT_MAP()
/////////////////////////////////////////////////////////////////////////////
// CPLC5App initialization
BOOL CPLC5App::InitInstance()
{
OleInitialize(NULL);
//if( !StartFSServer(m_hInstance, &CLSID_OPCServer) )
// return FALSE;
// COM Command Register
m_ScdCmdIF.Register( WM_COMEVT);
//#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
// HRESULT hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED);
//#else
// HRESULT hRes = CoInitialize(NULL);
//#endif
// _ASSERTE(SUCCEEDED(hRes));
// _Module.Init(ObjectMap, m_hInstance, &LIBID_PLC5Lib);
//_Module.dwThreadID = GetCurrentThreadId();
// TCHAR szTokens[] = _T("-/");
bool Embedding=false;
bool RegoDone=false;
TCHAR szTokens[] = _T("-/ ");
// copy m_lpCmdLine because _tcstok modifies the string
CString tempCmdLine(m_lpCmdLine);
LPTSTR lpszToken = _tcstok(tempCmdLine.GetBuffer(1), szTokens);
while (lpszToken != NULL)
{
if (_tcsicmp(lpszToken, _T("UnregServer"))==0)
{
// SysCADCmd
//_Module.UpdateRegistryFromResource(IDR_PLC5, FALSE);
//if ( FAILED(_Module.UnregisterServer(TRUE)) )
// AfxMessageBox(_T("SysCADCmd UnregisterServer Failed"));
// OPC
if (theDlg.OPCStart())
if (!theDlg.OPCUnregister())
AfxMessageBox(_T("OPC UnregisterServer Failed"));
theDlg.OPCStop();
RegoDone=true;
}
else if (_tcsicmp(lpszToken, _T("RegServer"))==0)
{
// SysCADCmd
HRESULT hr=m_ScdCmdIF.UpdateRegistry(m_hInstance, TRUE);//, OLESTR("AAA"), OLESTR("TTT"));
if( FAILED(hr) )
AfxMessageBox(_T("SysCADCmd RegisterServer Failed"));
// OPC
if (theDlg.OPCStart())
if (!theDlg.OPCRegister())
AfxMessageBox(_T("OPC RegisterServer Failed"));
theDlg.OPCStop();
RegoDone=true;
}
else if (_tcsicmp(lpszToken, _T("Embedding"))==0)
{
Embedding=true;
}
lpszToken = _tcstok(NULL, szTokens);
}
// StopFSServer();
if (RegoDone)
{
Sleep(100);//_Module.Term();
m_ScdCmdIF.UnRegister();
OleUninitialize();
return FALSE;
}
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need.
#ifdef _AFXDLL
// Enable3dControls(); // Call this when using MFC in a shared DLL
#else
Enable3dControlsStatic(); // Call this when linking to MFC statically
#endif
#ifdef _DEBUG
long BreakAlloc = -1; // Use Debugger to set this
_CrtSetBreakAlloc(BreakAlloc); //this sets _crtBreakAlloc
#endif
char ModuleFN[_MAX_PATH];
GetModuleFileName(NULL, ModuleFN, sizeof(ModuleFN));
char cDrv[_MAX_DRIVE];
char cPath[_MAX_PATH];
char cFile[_MAX_FNAME];
char cExt[_MAX_EXT];
_splitpath(ModuleFN, cDrv, cPath, cFile, cExt);
CString sFNRoot=cDrv;
CString sFNPrj;
_strlwr(cPath);
char*pBin=strstr(cPath, "\\bin\\");
if (pBin)
{
*pBin=0; // remove \Bin\ etc
sFNRoot+=cPath;
sFNRoot+="\\MosRef\\";
}
else
sFNRoot+="\\SysCAD82\\MosRef\\";
sFNRoot+="EsdPlc\\";
sFNRoot = GetProfileString("General", "ProjectFolder", (const char*)sFNRoot);
sFNPrj = GetProfileString("General", "ProjectFile", (const char*)sFNPrj);
bool DbgOn = (GetProfileInt("Debug", "On", 1)!=0);
bool GotPrj=0;
if (Embedding)
{
//_splitpath(sFNRoot, cDrv, cPath, NULL, NULL);
//sFNRoot=cDrv;
//sFNRoot+=cPath;
//_splitpath(sFNPrj, NULL, NULL, cFile, cExt);
//sFNPrj=cFile;
//sFNPrj+=cExt;
}
else
{
//not started remotely, ask user to select project folder...
COpenDlg Dlg;
Dlg.m_PrjPath = sFNRoot;
Dlg.m_PrjPath += sFNPrj;
Dlg.m_DbgOn = DbgOn;
if (Dlg.DoModal()==IDOK)
{
_splitpath(Dlg.m_PrjPath, cDrv, cPath, cFile, cExt);
sFNRoot=cDrv;
sFNRoot+=cPath;
sFNPrj=cFile;
sFNPrj+=cExt;
DbgOn = (Dlg.m_DbgOn!=0);
HANDLE H;
WIN32_FIND_DATA fd;
CString Fn;
Fn=sFNRoot+sFNPrj;
if ((H=FindFirstFile(Fn, &fd))!=INVALID_HANDLE_VALUE)
{
GotPrj=true;
FindClose(H);
}
else if (Fn.GetLength()>0)
{
CString Msg;
Msg.Format("File not found: %s", (LPCTSTR)Fn);
MessageBox(NULL, Msg, "PLC5", MB_OK);
}
}
}
//assume folder exists!
//if (sFNRoot[sFNRoot.GetLength()-1]!='\\')
// sFNRoot += '\\';
WriteProfileString("General", "ProjectFolder", (const char*)sFNRoot);
WriteProfileString("General", "ProjectFile", (const char*)sFNPrj);
WriteProfileInt("Debug", "On", DbgOn);
if (DbgOn)
{
char Temp[_MAX_PATH];
if (GetEnvironmentVariable("TEMP", Temp, sizeof(Temp)))
{
char t=Temp[strlen(Temp)-1];
if (t!='/' && t!='\\')
strcat(Temp, "\\");
strcat(Temp, "SysCAD");
::CreateDirectory(Temp, NULL);
strcat(Temp, "\\PLC5_dbg.txt");
dbgf=fopen(Temp, "wt");
}
}
if (GotPrj)
{
theDlg.m_sInitFile=sFNRoot;
theDlg.m_sInitFile+=sFNPrj;
//theDlg.Open(sFNRoot, sFNPrj);
}
// m_Plc.InitTree(m_Tree);
m_UpNAbout=true;
//CPLC5Dlg theDlg;//(&m_Plc, &m_Xfer, pOPCCallback);//pOPCCallBack);
m_pMainWnd = &theDlg;
int nResponse = theDlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
theDlg.OPCStop();
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
//=========================================================================
int CPLC5App::ExitInstance()
{
// TODO: Add your specialized code here and/or call the base class
m_ScdCmdIF.UnRegister();
//StopFSServer();
OleUninitialize();
return CWinApp::ExitInstance();
}
//=========================================================================
void CTransferBlk::DoTransfer()
{
if (m_bOK)
{
if (m_pSrc->IsFlt())
{
for (int i=0; i<m_nLen; i++)
m_pDst->SetFValue(i, m_pSrc->FValue(i));
}
else if (!m_pSrc->IsBit())
{
for (int i=0; i<m_nLen; i++)
m_pDst->SetIValue(i, m_pSrc->IValue(i));
}
else
{
INCOMPLETECODE();
}
}
};
//=========================================================================
void CForceBlk::DoTransfer()
{
if (m_bOK)
{
if (m_pDst->IsFlt())
{
for (int i=0; i<m_nLen; i++)
m_pDst->SetFValue(i, m_Values[i]);
}
else if (!m_pDst->IsBit())
{
for (int i=0; i<m_nLen; i++)
m_pDst->SetIValue(i, short(m_Values[i]));
}
else
{
INCOMPLETECODE();
}
}
};
//=========================================================================
//
//
//
//=========================================================================
| [
"[email protected]"
]
| [
[
[
1,
347
]
]
]
|
1ffec0b1246d4d43dfc68be395e98f6a441c10bb | c2c93fc3fd90bd77764ac3016d816a59b2370891 | /Incomplited/Useful functions 0.1/last/hooks.cpp | 21ce275bac66da2fde5fb47cef36feef2f2b785e | []
| no_license | MsEmiNeko/samp-alex009-projects | a1d880ee3116de95c189ef3f79ce43b163b91603 | 9b9517486b28411c8b747fae460266a88d462e51 | refs/heads/master | 2021-01-10T16:22:34.863725 | 2011-04-30T04:01:15 | 2011-04-30T04:01:15 | 43,719,520 | 0 | 1 | null | 2018-01-19T16:55:45 | 2015-10-05T23:23:37 | SourcePawn | UTF-8 | C++ | false | false | 16,053 | cpp | /*
* Created: 06.03.10
* Author: 009
* Last Modifed: -
*/
// SDK
#include "SDK/amx/amx.h"
#include "SDK/plugincommon.h"
// plugin
#include "os.h"
#include "hooks.h"
#include "main.h"
// samp data
#include "samp address.h"
#include "samp defines.h"
#include "samp structs.h"
// main vars
DWORD c_samp;
DWORD c_mass;
DWORD CSampPointer;
// offsets
DWORD CPlayerPosXOffset;
DWORD CPlayerPosYOffset;
DWORD CPlayerPosZOffset;
DWORD CPlayerHealthOffset;
DWORD CPlayerArmourOffset;
DWORD CPlayerAngleOffset;
DWORD CPlayerStateOffset;
DWORD CPlayerFootSyncOffset;
DWORD CPlayerInCarSyncOffset;
DWORD CPlayerPassangerSyncOffset;
DWORD CPlayerAimSyncOffset;
DWORD CPlayerAimSyncStateOffset;
DWORD CPlayerSyncTypeOffset;
DWORD CPlayerWeaponSkillOffset;
DWORD CPlayerSkinOffset;
DWORD CPlayerInteriorOffset;
DWORD CPlayerIsStreamedOffset;
DWORD CPlayerVehicleIdOffset;
DWORD CPlayerVehicleSeatOffset;
DWORD CVehiclePosXOffset;
DWORD CVehiclePosYOffset;
DWORD CVehiclePosZOffset;
DWORD CVehicleDriverOffset;
DWORD CVehicleHealthOffset;
// core
DWORD PlaybackDirAddr;
DWORD LogFileAddr;
DWORD BadCharsAddr;
DWORD ChangeNameLogAddr;
// callbacks
DWORD OPSP_DisableCheckAdmin1;
DWORD OPSP_DisableCheckAdmin2;
DWORD OPSP_GotoCallback_start;
DWORD OPSP_GotoCallback_end;
extern int SampVersion;
extern AMX* gAMX;
//
// ------------------------------------------------------
//
void HooksInstall(int version)
{
void *temp;
switch(version)
{
case SAMP_VERSION_034:
{
POINTER_TO_MEMBER(CPlayerPosXOffset,(void *)(R4_C_PLAYER_POS_X_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPosYOffset,(void *)(R4_C_PLAYER_POS_Y_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPosZOffset,(void *)(R4_C_PLAYER_POS_Z_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerHealthOffset,(void *)(R4_C_PLAYER_HEALTH_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerArmourOffset,(void *)(R4_C_PLAYER_ARMOUR_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAngleOffset,(void *)(R4_C_PLAYER_ANGLE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerStateOffset,(void *)(R4_C_PLAYER_STATE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerFootSyncOffset,(void *)(R4_C_PLAYER_FOOT_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerInCarSyncOffset,(void *)(R4_C_PLAYER_INCAR_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPassangerSyncOffset,(void *)(R4_C_PLAYER_PASSANGER_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAimSyncOffset,(void *)(R4_C_PLAYER_AIM_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAimSyncStateOffset,(void *)(R4_C_PLAYER_AIM_SYNC_STATE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerSyncTypeOffset,(void *)(R4_C_PLAYER_SYNC_TYPE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerWeaponSkillOffset,(void *)(R4_C_PLAYER_WEAPON_SKILL_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerSkinOffset,(void *)(R4_C_PLAYER_SKIN_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerInteriorOffset,(void *)(R4_C_PLAYER_INTERIOR_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerIsStreamedOffset,(void *)(R4_C_PLAYER_IS_STREAMED_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerVehicleIdOffset,(void *)(R4_C_PLAYER_VEHICLE_ID_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerVehicleSeatOffset,(void *)(R4_C_PLAYER_VEHICLE_SEAT_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosXOffset,(void *)(R4_C_VEHICLE_POS_X_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosYOffset,(void *)(R4_C_VEHICLE_POS_Y_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosZOffset,(void *)(R4_C_VEHICLE_POS_Z_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehicleDriverOffset,(void *)(R4_C_VEHICLE_DRIVER_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehicleHealthOffset,(void *)(R4_C_VEHICLE_HEALTH_OFFSET),DWORD);
POINTER_TO_MEMBER(PlaybackDirAddr,(void *)(R4_PLAYBACK_DIR),DWORD);
POINTER_TO_MEMBER(LogFileAddr,(void *)(R4_LOG_FILE),DWORD);
POINTER_TO_MEMBER(BadCharsAddr,(void *)(R4_BAD_CHARS),DWORD);
POINTER_TO_MEMBER(ChangeNameLogAddr,(void *)(R4_CHANGE_NAME_LOG),DWORD);
POINTER_TO_MEMBER(OPSP_DisableCheckAdmin1,(void *)(R4_OPSP_DISABLE_CHECK_ADMIN_1),DWORD);
POINTER_TO_MEMBER(OPSP_DisableCheckAdmin2,(void *)(R4_OPSP_DISABLE_CHECK_ADMIN_2),DWORD);
POINTER_TO_MEMBER(OPSP_GotoCallback_start,(void *)(R4_OPSP_GOTO_CALLBACK_START),DWORD);
POINTER_TO_MEMBER(OPSP_GotoCallback_end,(void *)(R4_OPSP_GOTO_CALLBACK_END),DWORD);
break;
}
case SAMP_VERSION_0351:
{
POINTER_TO_MEMBER(CPlayerPosXOffset,(void *)(R51_C_PLAYER_POS_X_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPosYOffset,(void *)(R51_C_PLAYER_POS_Y_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPosZOffset,(void *)(R51_C_PLAYER_POS_Z_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerHealthOffset,(void *)(R51_C_PLAYER_HEALTH_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerArmourOffset,(void *)(R51_C_PLAYER_ARMOUR_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAngleOffset,(void *)(R51_C_PLAYER_ANGLE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerStateOffset,(void *)(R51_C_PLAYER_STATE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerFootSyncOffset,(void *)(R51_C_PLAYER_FOOT_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerInCarSyncOffset,(void *)(R51_C_PLAYER_INCAR_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPassangerSyncOffset,(void *)(R51_C_PLAYER_PASSANGER_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAimSyncOffset,(void *)(R51_C_PLAYER_AIM_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAimSyncStateOffset,(void *)(R51_C_PLAYER_AIM_SYNC_STATE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerSyncTypeOffset,(void *)(R51_C_PLAYER_SYNC_TYPE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerWeaponSkillOffset,(void *)(R51_C_PLAYER_WEAPON_SKILL_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerSkinOffset,(void *)(R51_C_PLAYER_SKIN_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerInteriorOffset,(void *)(R51_C_PLAYER_INTERIOR_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerIsStreamedOffset,(void *)(R51_C_PLAYER_IS_STREAMED_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerVehicleIdOffset,(void *)(R51_C_PLAYER_VEHICLE_ID_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerVehicleSeatOffset,(void *)(R51_C_PLAYER_VEHICLE_SEAT_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosXOffset,(void *)(R51_C_VEHICLE_POS_X_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosYOffset,(void *)(R51_C_VEHICLE_POS_Y_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosZOffset,(void *)(R51_C_VEHICLE_POS_Z_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehicleDriverOffset,(void *)(R51_C_VEHICLE_DRIVER_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehicleHealthOffset,(void *)(R51_C_VEHICLE_HEALTH_OFFSET),DWORD);
POINTER_TO_MEMBER(PlaybackDirAddr,(void *)(R51_PLAYBACK_DIR),DWORD);
POINTER_TO_MEMBER(LogFileAddr,(void *)(R51_LOG_FILE),DWORD);
POINTER_TO_MEMBER(BadCharsAddr,(void *)(R51_BAD_CHARS),DWORD);
POINTER_TO_MEMBER(ChangeNameLogAddr,(void *)(R51_CHANGE_NAME_LOG),DWORD);
POINTER_TO_MEMBER(OPSP_DisableCheckAdmin1,(void *)(R51_OPSP_DISABLE_CHECK_ADMIN_1),DWORD);
POINTER_TO_MEMBER(OPSP_DisableCheckAdmin2,(void *)(R51_OPSP_DISABLE_CHECK_ADMIN_2),DWORD);
POINTER_TO_MEMBER(OPSP_GotoCallback_start,(void *)(R51_OPSP_GOTO_CALLBACK_START),DWORD);
POINTER_TO_MEMBER(OPSP_GotoCallback_end,(void *)(R51_OPSP_GOTO_CALLBACK_END),DWORD);
break;
}
case SAMP_VERSION_0352:
{
POINTER_TO_MEMBER(CPlayerPosXOffset,(void *)(R52_C_PLAYER_POS_X_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPosYOffset,(void *)(R52_C_PLAYER_POS_Y_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPosZOffset,(void *)(R52_C_PLAYER_POS_Z_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerHealthOffset,(void *)(R52_C_PLAYER_HEALTH_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerArmourOffset,(void *)(R52_C_PLAYER_ARMOUR_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAngleOffset,(void *)(R52_C_PLAYER_ANGLE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerStateOffset,(void *)(R52_C_PLAYER_STATE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerFootSyncOffset,(void *)(R52_C_PLAYER_FOOT_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerInCarSyncOffset,(void *)(R52_C_PLAYER_INCAR_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPassangerSyncOffset,(void *)(R52_C_PLAYER_PASSANGER_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAimSyncOffset,(void *)(R52_C_PLAYER_AIM_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAimSyncStateOffset,(void *)(R52_C_PLAYER_AIM_SYNC_STATE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerSyncTypeOffset,(void *)(R52_C_PLAYER_SYNC_TYPE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerWeaponSkillOffset,(void *)(R52_C_PLAYER_WEAPON_SKILL_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerSkinOffset,(void *)(R52_C_PLAYER_SKIN_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerInteriorOffset,(void *)(R52_C_PLAYER_INTERIOR_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerIsStreamedOffset,(void *)(R52_C_PLAYER_IS_STREAMED_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerVehicleIdOffset,(void *)(R52_C_PLAYER_VEHICLE_ID_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerVehicleSeatOffset,(void *)(R52_C_PLAYER_VEHICLE_SEAT_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosXOffset,(void *)(R52_C_VEHICLE_POS_X_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosYOffset,(void *)(R52_C_VEHICLE_POS_Y_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosZOffset,(void *)(R52_C_VEHICLE_POS_Z_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehicleDriverOffset,(void *)(R52_C_VEHICLE_DRIVER_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehicleHealthOffset,(void *)(R52_C_VEHICLE_HEALTH_OFFSET),DWORD);
POINTER_TO_MEMBER(PlaybackDirAddr,(void *)(R52_PLAYBACK_DIR),DWORD);
POINTER_TO_MEMBER(LogFileAddr,(void *)(R52_LOG_FILE),DWORD);
POINTER_TO_MEMBER(BadCharsAddr,(void *)(R52_BAD_CHARS),DWORD);
POINTER_TO_MEMBER(ChangeNameLogAddr,(void *)(R52_CHANGE_NAME_LOG),DWORD);
POINTER_TO_MEMBER(OPSP_DisableCheckAdmin1,(void *)(R52_OPSP_DISABLE_CHECK_ADMIN_1),DWORD);
POINTER_TO_MEMBER(OPSP_DisableCheckAdmin2,(void *)(R52_OPSP_DISABLE_CHECK_ADMIN_2),DWORD);
POINTER_TO_MEMBER(OPSP_GotoCallback_start,(void *)(R52_OPSP_GOTO_CALLBACK_START),DWORD);
POINTER_TO_MEMBER(OPSP_GotoCallback_end,(void *)(R52_OPSP_GOTO_CALLBACK_END),DWORD);
break;
}
case SAMP_VERSION_036:
{
POINTER_TO_MEMBER(CPlayerPosXOffset,(void *)(R6_C_PLAYER_POS_X_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPosYOffset,(void *)(R6_C_PLAYER_POS_Y_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPosZOffset,(void *)(R6_C_PLAYER_POS_Z_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerHealthOffset,(void *)(R6_C_PLAYER_HEALTH_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerArmourOffset,(void *)(R6_C_PLAYER_ARMOUR_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAngleOffset,(void *)(R6_C_PLAYER_ANGLE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerStateOffset,(void *)(R6_C_PLAYER_STATE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerFootSyncOffset,(void *)(R6_C_PLAYER_FOOT_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerInCarSyncOffset,(void *)(R6_C_PLAYER_INCAR_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPassangerSyncOffset,(void *)(R6_C_PLAYER_PASSANGER_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAimSyncOffset,(void *)(R6_C_PLAYER_AIM_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAimSyncStateOffset,(void *)(R6_C_PLAYER_AIM_SYNC_STATE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerSyncTypeOffset,(void *)(R6_C_PLAYER_SYNC_TYPE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerWeaponSkillOffset,(void *)(R6_C_PLAYER_WEAPON_SKILL_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerSkinOffset,(void *)(R6_C_PLAYER_SKIN_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerInteriorOffset,(void *)(R6_C_PLAYER_INTERIOR_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerIsStreamedOffset,(void *)(R6_C_PLAYER_IS_STREAMED_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerVehicleIdOffset,(void *)(R6_C_PLAYER_VEHICLE_ID_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerVehicleSeatOffset,(void *)(R6_C_PLAYER_VEHICLE_SEAT_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosXOffset,(void *)(R6_C_VEHICLE_POS_X_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosYOffset,(void *)(R6_C_VEHICLE_POS_Y_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosZOffset,(void *)(R6_C_VEHICLE_POS_Z_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehicleDriverOffset,(void *)(R6_C_VEHICLE_DRIVER_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehicleHealthOffset,(void *)(R6_C_VEHICLE_HEALTH_OFFSET),DWORD);
POINTER_TO_MEMBER(PlaybackDirAddr,(void *)(R6_PLAYBACK_DIR),DWORD);
POINTER_TO_MEMBER(LogFileAddr,(void *)(R6_LOG_FILE),DWORD);
POINTER_TO_MEMBER(BadCharsAddr,(void *)(R6_BAD_CHARS),DWORD);
POINTER_TO_MEMBER(ChangeNameLogAddr,(void *)(R6_CHANGE_NAME_LOG),DWORD);
POINTER_TO_MEMBER(OPSP_DisableCheckAdmin1,(void *)(R6_OPSP_DISABLE_CHECK_ADMIN_1),DWORD);
POINTER_TO_MEMBER(OPSP_DisableCheckAdmin2,(void *)(R6_OPSP_DISABLE_CHECK_ADMIN_2),DWORD);
POINTER_TO_MEMBER(OPSP_GotoCallback_start,(void *)(R6_OPSP_GOTO_CALLBACK_START),DWORD);
POINTER_TO_MEMBER(OPSP_GotoCallback_end,(void *)(R6_OPSP_GOTO_CALLBACK_END),DWORD);
break;
}
case SAMP_VERSION_037:
{
POINTER_TO_MEMBER(CPlayerPosXOffset,(void *)(R7_C_PLAYER_POS_X_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPosYOffset,(void *)(R7_C_PLAYER_POS_Y_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPosZOffset,(void *)(R7_C_PLAYER_POS_Z_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerHealthOffset,(void *)(R7_C_PLAYER_HEALTH_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerArmourOffset,(void *)(R7_C_PLAYER_ARMOUR_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAngleOffset,(void *)(R7_C_PLAYER_ANGLE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerStateOffset,(void *)(R7_C_PLAYER_STATE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerFootSyncOffset,(void *)(R7_C_PLAYER_FOOT_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerInCarSyncOffset,(void *)(R7_C_PLAYER_INCAR_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerPassangerSyncOffset,(void *)(R7_C_PLAYER_PASSANGER_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAimSyncOffset,(void *)(R7_C_PLAYER_AIM_SYNC_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerAimSyncStateOffset,(void *)(R7_C_PLAYER_AIM_SYNC_STATE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerSyncTypeOffset,(void *)(R7_C_PLAYER_SYNC_TYPE_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerWeaponSkillOffset,(void *)(R7_C_PLAYER_WEAPON_SKILL_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerSkinOffset,(void *)(R7_C_PLAYER_SKIN_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerInteriorOffset,(void *)(R7_C_PLAYER_INTERIOR_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerIsStreamedOffset,(void *)(R7_C_PLAYER_IS_STREAMED_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerVehicleIdOffset,(void *)(R7_C_PLAYER_VEHICLE_ID_OFFSET),DWORD);
POINTER_TO_MEMBER(CPlayerVehicleSeatOffset,(void *)(R7_C_PLAYER_VEHICLE_SEAT_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosXOffset,(void *)(R7_C_VEHICLE_POS_X_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosYOffset,(void *)(R7_C_VEHICLE_POS_Y_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehiclePosZOffset,(void *)(R7_C_VEHICLE_POS_Z_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehicleDriverOffset,(void *)(R7_C_VEHICLE_DRIVER_OFFSET),DWORD);
POINTER_TO_MEMBER(CVehicleHealthOffset,(void *)(R7_C_VEHICLE_HEALTH_OFFSET),DWORD);
POINTER_TO_MEMBER(PlaybackDirAddr,(void *)(R7_PLAYBACK_DIR),DWORD);
POINTER_TO_MEMBER(LogFileAddr,(void *)(R7_LOG_FILE),DWORD);
POINTER_TO_MEMBER(BadCharsAddr,(void *)(R7_BAD_CHARS),DWORD);
POINTER_TO_MEMBER(ChangeNameLogAddr,(void *)(R7_CHANGE_NAME_LOG),DWORD);
POINTER_TO_MEMBER(OPSP_DisableCheckAdmin1,(void *)(R7_OPSP_DISABLE_CHECK_ADMIN_1),DWORD);
POINTER_TO_MEMBER(OPSP_DisableCheckAdmin2,(void *)(R7_OPSP_DISABLE_CHECK_ADMIN_2),DWORD);
POINTER_TO_MEMBER(OPSP_GotoCallback_start,(void *)(R7_OPSP_GOTO_CALLBACK_START),DWORD);
POINTER_TO_MEMBER(OPSP_GotoCallback_end,(void *)(R7_OPSP_GOTO_CALLBACK_END),DWORD);
break;
}
}
}
void JmpHook(DWORD from, DWORD to)
{
DWORD oldp;
VirtualProtect((LPVOID)from, 5, PAGE_EXECUTE_READWRITE, &oldp);
BYTE *patch = (BYTE *)from;
*patch = 0xE9; // JMP
*(DWORD *)(patch + 1) = (to - (from + 5));
}
| [
"[email protected]"
]
| [
[
[
1,
276
]
]
]
|
ba2484025ba4bf5a118fc395306bfb2740ceb188 | d752d83f8bd72d9b280a8c70e28e56e502ef096f | /FugueDLL/Virtual Machine/Operations/Operators/CompoundOperator.cpp | 146ee196a3b3a92c527ddc591cbd4c569c5e009d | []
| no_license | apoch/epoch-language.old | f87b4512ec6bb5591bc1610e21210e0ed6a82104 | b09701714d556442202fccb92405e6886064f4af | refs/heads/master | 2021-01-10T20:17:56.774468 | 2010-03-07T09:19:02 | 2010-03-07T09:19:02 | 34,307,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 765 | cpp | //
// The Epoch Language Project
// FUGUE Virtual Machine
//
// Base class for operators that can act on arrays of parameters
//
#include "pch.h"
#include "Virtual Machine/Operations/Operators/CompoundOperator.h"
#include "Virtual Machine/Operations/StackOps.h"
using namespace VM;
using namespace VM::Operations;
namespace
{
Operation* GetRealOperation(Operation* op)
{
PushOperation* pushop = dynamic_cast<PushOperation*>(op);
if(pushop)
return pushop->GetNestedOperation();
return op;
}
}
void CompoundOperator::AddOperation(VM::Operation* op)
{
SubOps.push_back(GetRealOperation(op));
}
void CompoundOperator::AddOperationToFront(VM::Operation* op)
{
SubOps.push_front(GetRealOperation(op));
}
| [
"[email protected]",
"don.apoch@localhost"
]
| [
[
[
1,
4
],
[
6,
41
]
],
[
[
5,
5
]
]
]
|
c2d9fb23091e6293f2141a0d278c16643d2a4a97 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ObjectDLL/ObjectShared/RotatingSwitch.h | 6f4d0551468d6e52c617343cf974c920c3e0906d | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 664 | h | // ----------------------------------------------------------------------- //
//
// MODULE : RotatingSwitch.h
//
// PURPOSE : A RotatingSwitch object
//
// CREATED : 5/29/01
//
// (c) 2001 Monolith Productions, Inc. All Rights Reserved
//
// ----------------------------------------------------------------------- //
#ifndef __ROTATING_SWITCH_H__
#define __ROTATING_SWITCH_H__
//
// Includes...
//
#include "Switch.h"
LINKTO_MODULE( RotatingSwitch );
//
// Structs...
//
class RotatingSwitch : public Switch
{
public: // Methods...
RotatingSwitch( );
virtual ~RotatingSwitch( );
};
#endif // __ROTATING_SWITCH_H__ | [
"[email protected]"
]
| [
[
[
1,
36
]
]
]
|
42f4371abac54d91b469ce7cc2d85c4574880226 | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/common/src/Utilities/ThreadTools.cpp | ca0b8d83b0480e99dfc41d040d51ea825f8720d2 | []
| no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,874 | cpp | /* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 is free software: you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#ifdef __LINUX__
# include <signal.h> // for pthread_kill, which is in pthread.h on w32-pthreads
#endif
#include "PersistentThread.h"
#include "wxBaseTools.h"
#include "ThreadingInternal.h"
#include "EventSource.inl"
using namespace Threading;
template class EventSource< EventListener_Thread >;
// 100ms interval for waitgui (issued from blocking semaphore waits on the main thread,
// to avoid gui deadlock).
const wxTimeSpan Threading::def_yieldgui_interval( 0, 0, 0, 100 );
ConsoleLogSource_Threading::ConsoleLogSource_Threading()
{
static const TraceLogDescriptor myDesc =
{
L"pxThread", L"pxThread",
wxLt("Threading activity: start, detach, sync, deletion, etc.")
};
m_Descriptor = &myDesc;
}
ConsoleLogSource_Threading pxConLog_Thread;
class StaticMutex : public Mutex
{
protected:
bool& m_DeletedFlag;
public:
StaticMutex( bool& deletedFlag )
: m_DeletedFlag( deletedFlag )
{
}
virtual ~StaticMutex() throw()
{
m_DeletedFlag = true;
}
};
static pthread_key_t curthread_key = 0;
static s32 total_key_count = 0;
static bool tkl_destructed = false;
static StaticMutex total_key_lock( tkl_destructed );
static void make_curthread_key( const pxThread* thr )
{
pxAssumeDev( !tkl_destructed, "total_key_lock is destroyed; program is shutting down; cannot create new thread key." );
ScopedLock lock( total_key_lock );
if( total_key_count++ != 0 ) return;
if( 0 != pthread_key_create(&curthread_key, NULL) )
{
pxThreadLog.Error( thr->GetName(), L"Thread key creation failed (probably out of memory >_<)" );
curthread_key = 0;
}
}
static void unmake_curthread_key()
{
ScopedLock lock;
if( !tkl_destructed )
lock.AssignAndLock( total_key_lock );
if( --total_key_count > 0 ) return;
if( curthread_key )
pthread_key_delete( curthread_key );
curthread_key = 0;
}
void Threading::pxTestCancel()
{
pthread_testcancel();
}
// Returns a handle to the current persistent thread. If the current thread does not belong
// to the pxThread table, NULL is returned. Since the main/ui thread is not created
// through pxThread it will also return NULL. Callers can use wxThread::IsMain() to
// test if the NULL thread is the main thread.
pxThread* Threading::pxGetCurrentThread()
{
return !curthread_key ? NULL : (pxThread*)pthread_getspecific( curthread_key );
}
// returns the name of the current thread, or "Unknown" if the thread is neither a pxThread
// nor the Main/UI thread.
wxString Threading::pxGetCurrentThreadName()
{
if( pxThread* thr = pxGetCurrentThread() )
{
return thr->GetName();
}
else if( wxThread::IsMain() )
{
return L"Main/UI";
}
return L"Unknown";
}
void Threading::pxYield( int ms )
{
if( pxThread* thr = pxGetCurrentThread() )
thr->Yield( ms );
else
Sleep( ms );
}
// (intended for internal use only)
// Returns true if the Wait is recursive, or false if the Wait is safe and should be
// handled via normal yielding methods.
bool Threading::_WaitGui_RecursionGuard( const wxChar* name )
{
AffinityAssert_AllowFrom_MainUI();
// In order to avoid deadlock we need to make sure we cut some time to handle messages.
// But this can result in recursive yield calls, which would crash the app. Protect
// against them here and, if recursion is detected, perform a standard blocking wait.
static int __Guard = 0;
RecursionGuard guard( __Guard );
//if( pxAssertDev( !guard.IsReentrant(), "Recursion during UI-bound threading wait object." ) ) return false;
if( !guard.IsReentrant() ) return false;
pxThreadLog.Write( pxGetCurrentThreadName(),
wxsFormat(L"Yield recursion in %s; opening modal dialog.", name)
);
return true;
}
__fi void Threading::Timeslice()
{
sched_yield();
}
void Threading::pxThread::_pt_callback_cleanup( void* handle )
{
((pxThread*)handle)->_ThreadCleanup();
}
Threading::pxThread::pxThread( const wxString& name )
: m_name( name )
{
m_detached = true; // start out with m_thread in detached/invalid state
m_running = false;
m_native_id = 0;
m_native_handle = 0;
}
// This destructor performs basic "last chance" cleanup, which is a blocking join
// against the thread. Extending classes should almost always implement their own
// thread closure process, since any pxThread will, by design, not terminate
// unless it has been properly canceled (resulting in deadlock).
//
// Thread safety: This class must not be deleted from its own thread. That would be
// like marrying your sister, and then cheating on her with your daughter.
Threading::pxThread::~pxThread() throw()
{
try
{
pxThreadLog.Write( GetName(), L"Executing default destructor!" );
if( m_running )
{
pxThreadLog.Write( GetName(), L"Waiting for running thread to end...");
m_mtx_InThread.Wait();
pxThreadLog.Write( GetName(), L"Thread ended gracefully.");
}
Threading::Sleep( 1 );
Detach();
}
DESTRUCTOR_CATCHALL
}
bool Threading::pxThread::AffinityAssert_AllowFromSelf( const DiagnosticOrigin& origin ) const
{
if( IsSelf() ) return true;
if( IsDevBuild )
pxOnAssert( origin, wxsFormat( L"Thread affinity violation: Call allowed from '%s' thread only.", GetName().c_str() ) );
return false;
}
bool Threading::pxThread::AffinityAssert_DisallowFromSelf( const DiagnosticOrigin& origin ) const
{
if( !IsSelf() ) return true;
if( IsDevBuild )
pxOnAssert( origin, wxsFormat( L"Thread affinity violation: Call is *not* allowed from '%s' thread.", GetName().c_str() ) );
return false;
}
void Threading::pxThread::FrankenMutex( Mutex& mutex )
{
if( mutex.RecreateIfLocked() )
{
// Our lock is bupkis, which means the previous thread probably deadlocked.
// Let's create a new mutex lock to replace it.
pxThreadLog.Error( GetName(), L"Possible deadlock detected on restarted mutex!" );
}
}
// Main entry point for starting or e-starting a persistent thread. This function performs necessary
// locks and checks for avoiding race conditions, and then calls OnStart() immediately before
// the actual thread creation. Extending classes should generally not override Start(), and should
// instead override DoPrepStart instead.
//
// This function should not be called from the owner thread.
void Threading::pxThread::Start()
{
// Prevents sudden parallel startup, and or parallel startup + cancel:
ScopedLock startlock( m_mtx_start );
if( m_running )
{
pxThreadLog.Write(GetName(), L"Start() called on running thread; ignorning...");
return;
}
Detach(); // clean up previous thread handle, if one exists.
OnStart();
m_except = NULL;
pxThreadLog.Write(GetName(), L"Calling pthread_create...");
if( pthread_create( &m_thread, NULL, _internal_callback, this ) != 0 )
throw Exception::ThreadCreationError( this );
if( !m_sem_startup.WaitWithoutYield( wxTimeSpan( 0, 0, 3, 0 ) ) )
{
RethrowException();
// And if the thread threw nothing of its own:
throw Exception::ThreadCreationError( this ).SetDiagMsg( L"Thread creation error: %s thread never posted startup semaphore." );
}
// Event Rationale (above): Performing this semaphore wait on the created thread is "slow" in the
// sense that it stalls the calling thread completely until the new thread is created
// (which may not always be desirable). But too bad. In order to safely use 'running' locks
// and detachment management, this *has* to be done. By rule, starting new threads shouldn't
// be done very often anyway, hence the concept of Threadpooling for rapidly rotating tasks.
// (and indeed, this semaphore wait might, in fact, be very swift compared to other kernel
// overhead in starting threads).
// (this could also be done using operating system specific calls, since any threaded OS has
// functions that allow us to see if a thread is running or not, and to block against it even if
// it's been detached -- removing the need for m_mtx_InThread and the semaphore wait above. But
// pthreads kinda lacks that stuff, since pthread_join() has no timeout option making it im-
// possible to safely block against a running thread)
}
// Returns: TRUE if the detachment was performed, or FALSE if the thread was
// already detached or isn't running at all.
// This function should not be called from the owner thread.
bool Threading::pxThread::Detach()
{
AffinityAssert_DisallowFromSelf(pxDiagSpot);
if( _InterlockedExchange( &m_detached, true ) ) return false;
pthread_detach( m_thread );
return true;
}
bool Threading::pxThread::_basecancel()
{
if( !m_running ) return false;
if( m_detached )
{
pxThreadLog.Warn(GetName(), L"Ignoring attempted cancellation of detached thread.");
return false;
}
pthread_cancel( m_thread );
return true;
}
// Remarks:
// Provision of non-blocking Cancel() is probably academic, since destroying a pxThread
// object performs a blocking Cancel regardless of if you explicitly do a non-blocking Cancel()
// prior, since the ExecuteTaskInThread() method requires a valid object state. If you really need
// fire-and-forget behavior on threads, use pthreads directly for now.
//
// This function should not be called from the owner thread.
//
// Parameters:
// isBlocking - indicates if the Cancel action should block for thread completion or not.
//
// Exceptions raised by the blocking thread will be re-thrown into the main thread. If isBlocking
// is false then no exceptions will occur.
//
void Threading::pxThread::Cancel( bool isBlocking )
{
AffinityAssert_DisallowFromSelf( pxDiagSpot );
// Prevent simultaneous startup and cancel, necessary to avoid
ScopedLock startlock( m_mtx_start );
if( !_basecancel() ) return;
if( isBlocking )
{
WaitOnSelf( m_mtx_InThread );
Detach();
}
}
bool Threading::pxThread::Cancel( const wxTimeSpan& timespan )
{
AffinityAssert_DisallowFromSelf( pxDiagSpot );
// Prevent simultaneous startup and cancel:
ScopedLock startlock( m_mtx_start );
if( !_basecancel() ) return true;
if( !WaitOnSelf( m_mtx_InThread, timespan ) ) return false;
Detach();
return true;
}
// Blocks execution of the calling thread until this thread completes its task. The
// caller should make sure to signal the thread to exit, or else blocking may deadlock the
// calling thread. Classes which extend pxThread should override this method
// and signal any necessary thread exit variables prior to blocking.
//
// Returns the return code of the thread.
// This method is roughly the equivalent of pthread_join().
//
// Exceptions raised by the blocking thread will be re-thrown into the main thread.
//
void Threading::pxThread::Block()
{
AffinityAssert_DisallowFromSelf(pxDiagSpot);
WaitOnSelf( m_mtx_InThread );
}
bool Threading::pxThread::Block( const wxTimeSpan& timeout )
{
AffinityAssert_DisallowFromSelf(pxDiagSpot);
return WaitOnSelf( m_mtx_InThread, timeout );
}
bool Threading::pxThread::IsSelf() const
{
// Detached threads may have their pthread handles recycled as newer threads, causing
// false IsSelf reports.
return !m_detached && (pthread_self() == m_thread);
}
bool Threading::pxThread::IsRunning() const
{
return !!m_running;
}
void Threading::pxThread::AddListener( EventListener_Thread& evt )
{
evt.SetThread( this );
m_evtsrc_OnDelete.Add( evt );
}
// Throws an exception if the thread encountered one. Uses the BaseException's Rethrow() method,
// which ensures the exception type remains consistent. Debuggable stacktraces will be lost, since
// the thread will have allowed itself to terminate properly.
void Threading::pxThread::RethrowException() const
{
// Thread safety note: always detach the m_except pointer. If we checked it for NULL, the
// pointer might still be invalid after detachment, so might as well just detach and check
// after.
ScopedPtr<BaseException> ptr( const_cast<pxThread*>(this)->m_except.DetachPtr() );
if( ptr ) ptr->Rethrow();
//m_except->Rethrow();
}
static bool m_BlockDeletions = false;
bool Threading::AllowDeletions()
{
AffinityAssert_AllowFrom_MainUI();
return !m_BlockDeletions;
}
void Threading::YieldToMain()
{
m_BlockDeletions = true;
wxTheApp->Yield( true );
m_BlockDeletions = false;
}
void Threading::pxThread::_selfRunningTest( const wxChar* name ) const
{
if( HasPendingException() )
{
pxThreadLog.Error( GetName(), wxsFormat(L"An exception was thrown while waiting on a %s.", name) );
RethrowException();
}
if( !m_running )
{
throw Exception::CancelEvent( wxsFormat(
L"Blocking thread %s was terminated while another thread was waiting on a %s.",
GetName().c_str(), name )
);
}
// Thread is still alive and kicking (for now) -- yield to other messages and hope
// that impending chaos does not ensue. [it shouldn't since we block pxThread
// objects from being deleted until outside the scope of a mutex/semaphore wait).
if( (wxTheApp != NULL) && wxThread::IsMain() && !_WaitGui_RecursionGuard( L"WaitForSelf" ) )
Threading::YieldToMain();
}
// This helper function is a deadlock-safe method of waiting on a semaphore in a pxThread. If the
// thread is terminated or canceled by another thread or a nested action prior to the semaphore being
// posted, this function will detect that and throw a CancelEvent exception is thrown.
//
// Note: Use of this function only applies to semaphores which are posted by the worker thread. Calling
// this function from the context of the thread itself is an error, and a dev assertion will be generated.
//
// Exceptions:
// This function will rethrow exceptions raised by the persistent thread, if it throws an error
// while the calling thread is blocking (which also means the persistent thread has terminated).
//
void Threading::pxThread::WaitOnSelf( Semaphore& sem ) const
{
if( !AffinityAssert_DisallowFromSelf(pxDiagSpot) ) return;
while( true )
{
if( sem.WaitWithoutYield( wxTimeSpan(0, 0, 0, 333) ) ) return;
_selfRunningTest( L"semaphore" );
}
}
// This helper function is a deadlock-safe method of waiting on a mutex in a pxThread.
// If the thread is terminated or canceled by another thread or a nested action prior to the
// mutex being unlocked, this function will detect that and a CancelEvent exception is thrown.
//
// Note: Use of this function only applies to mutexes which are acquired by a worker thread.
// Calling this function from the context of the thread itself is an error, and a dev assertion
// will be generated.
//
// Exceptions:
// This function will rethrow exceptions raised by the persistent thread, if it throws an
// error while the calling thread is blocking (which also means the persistent thread has
// terminated).
//
void Threading::pxThread::WaitOnSelf( Mutex& mutex ) const
{
if( !AffinityAssert_DisallowFromSelf(pxDiagSpot) ) return;
while( true )
{
if( mutex.WaitWithoutYield( wxTimeSpan(0, 0, 0, 333) ) ) return;
_selfRunningTest( L"mutex" );
}
}
static const wxTimeSpan SelfWaitInterval( 0,0,0,333 );
bool Threading::pxThread::WaitOnSelf( Semaphore& sem, const wxTimeSpan& timeout ) const
{
if( !AffinityAssert_DisallowFromSelf(pxDiagSpot) ) return true;
wxTimeSpan runningout( timeout );
while( runningout.GetMilliseconds() > 0 )
{
const wxTimeSpan interval( (SelfWaitInterval < runningout) ? SelfWaitInterval : runningout );
if( sem.WaitWithoutYield( interval ) ) return true;
_selfRunningTest( L"semaphore" );
runningout -= interval;
}
return false;
}
bool Threading::pxThread::WaitOnSelf( Mutex& mutex, const wxTimeSpan& timeout ) const
{
if( !AffinityAssert_DisallowFromSelf(pxDiagSpot) ) return true;
wxTimeSpan runningout( timeout );
while( runningout.GetMilliseconds() > 0 )
{
const wxTimeSpan interval( (SelfWaitInterval < runningout) ? SelfWaitInterval : runningout );
if( mutex.WaitWithoutYield( interval ) ) return true;
_selfRunningTest( L"mutex" );
runningout -= interval;
}
return false;
}
// Inserts a thread cancellation point. If the thread has received a cancel request, this
// function will throw an SEH exception designed to exit the thread (so make sure to use C++
// object encapsulation for anything that could leak resources, to ensure object unwinding
// and cleanup, or use the DoThreadCleanup() override to perform resource cleanup).
void Threading::pxThread::TestCancel() const
{
AffinityAssert_AllowFromSelf(pxDiagSpot);
pthread_testcancel();
}
// Executes the virtual member method
void Threading::pxThread::_try_virtual_invoke( void (pxThread::*method)() )
{
try {
(this->*method)();
}
// ----------------------------------------------------------------------------
// Neat repackaging for STL Runtime errors...
//
catch( std::runtime_error& ex )
{
m_except = new Exception::RuntimeError( ex, GetName().c_str() );
}
// ----------------------------------------------------------------------------
catch( Exception::RuntimeError& ex )
{
BaseException* woot = ex.Clone();
woot->DiagMsg() += wxsFormat( L"(thread:%s)", GetName().c_str() );
m_except = woot;
}
#ifndef PCSX2_DEVBUILD
// ----------------------------------------------------------------------------
// Bleh... don't bother with std::exception. runtime_error should catch anything
// useful coming out of the core STL libraries anyway, and these are best handled by
// the MSVC debugger (or by silent random annoying fail on debug-less linux).
/*catch( std::logic_error& ex )
{
throw BaseException( wxsFormat( L"STL Logic Error (thread:%s): %s",
GetName().c_str(), fromUTF8( ex.what() ).c_str() )
);
}
catch( std::exception& ex )
{
throw BaseException( wxsFormat( L"STL exception (thread:%s): %s",
GetName().c_str(), fromUTF8( ex.what() ).c_str() )
);
}*/
// ----------------------------------------------------------------------------
// BaseException -- same deal as LogicErrors.
//
catch( BaseException& ex )
{
BaseException* woot = ex.Clone();
woot->DiagMsg() += wxsFormat( L"(thread:%s)", GetName().c_str() );
m_except = woot;
}
#endif
}
// invoked internally when canceling or exiting the thread. Extending classes should implement
// OnCleanupInThread() to extend cleanup functionality.
void Threading::pxThread::_ThreadCleanup()
{
AffinityAssert_AllowFromSelf(pxDiagSpot);
_try_virtual_invoke( &pxThread::OnCleanupInThread );
m_mtx_InThread.Release();
// Must set m_running LAST, as thread destructors depend on this value (it is used
// to avoid destruction of the thread until all internal data use has stopped.
m_running = false;
}
wxString Threading::pxThread::GetName() const
{
ScopedLock lock(m_mtx_ThreadName);
return m_name;
}
void Threading::pxThread::SetName( const wxString& newname )
{
ScopedLock lock(m_mtx_ThreadName);
m_name = newname;
}
// This override is called by PeristentThread when the thread is first created, prior to
// calling ExecuteTaskInThread, and after the initial InThread lock has been claimed.
// This code is also executed within a "safe" environment, where the creating thread is
// blocked against m_sem_event. Make sure to do any necessary variable setup here, without
// worry that the calling thread might attempt to test the status of those variables
// before initialization has completed.
//
void Threading::pxThread::OnStartInThread()
{
m_detached = false;
m_running = true;
_platform_specific_OnStartInThread();
}
void Threading::pxThread::_internal_execute()
{
m_mtx_InThread.Acquire();
_DoSetThreadName( GetName() );
make_curthread_key(this);
if( curthread_key )
pthread_setspecific( curthread_key, this );
OnStartInThread();
m_sem_startup.Post();
_try_virtual_invoke( &pxThread::ExecuteTaskInThread );
}
// Called by Start, prior to actual starting of the thread, and after any previous
// running thread has been canceled or detached.
void Threading::pxThread::OnStart()
{
m_native_handle = 0;
m_native_id = 0;
FrankenMutex( m_mtx_InThread );
m_sem_event.Reset();
m_sem_startup.Reset();
}
// Extending classes that override this method should always call it last from their
// personal implementations.
void Threading::pxThread::OnCleanupInThread()
{
if( curthread_key )
pthread_setspecific( curthread_key, NULL );
unmake_curthread_key();
_platform_specific_OnCleanupInThread();
m_native_handle = 0;
m_native_id = 0;
m_evtsrc_OnDelete.Dispatch( 0 );
}
// passed into pthread_create, and is used to dispatch the thread's object oriented
// callback function
void* Threading::pxThread::_internal_callback( void* itsme )
{
if( !pxAssertDev( itsme != NULL, wxNullChar ) ) return NULL;
pxThread& owner = *((pxThread*)itsme);
pthread_cleanup_push( _pt_callback_cleanup, itsme );
owner._internal_execute();
pthread_cleanup_pop( true );
return NULL;
}
void Threading::pxThread::_DoSetThreadName( const wxString& name )
{
_DoSetThreadName( name.ToUTF8() );
}
// --------------------------------------------------------------------------------------
// BaseTaskThread Implementations
// --------------------------------------------------------------------------------------
// Tells the thread to exit and then waits for thread termination.
void Threading::BaseTaskThread::Block()
{
if( !IsRunning() ) return;
m_Done = true;
m_sem_event.Post();
pxThread::Block();
}
// Initiates the new task. This should be called after your own StartTask has
// initialized internal variables / preparations for task execution.
void Threading::BaseTaskThread::PostTask()
{
pxAssert( !m_detached );
ScopedLock locker( m_lock_TaskComplete );
m_TaskPending = true;
m_post_TaskComplete.Reset();
m_sem_event.Post();
}
// Blocks current thread execution pending the completion of the parallel task.
void Threading::BaseTaskThread::WaitForResult()
{
if( m_detached || !m_running ) return;
if( m_TaskPending )
#if wxUSE_GUI
m_post_TaskComplete.Wait();
#else
m_post_TaskComplete.WaitWithoutYield();
#endif
m_post_TaskComplete.Reset();
}
void Threading::BaseTaskThread::ExecuteTaskInThread()
{
while( !m_Done )
{
// Wait for a job -- or get a pthread_cancel. I'm easy.
m_sem_event.WaitWithoutYield();
Task();
m_lock_TaskComplete.Acquire();
m_TaskPending = false;
m_post_TaskComplete.Post();
m_lock_TaskComplete.Release();
};
return;
}
// --------------------------------------------------------------------------------------
// pthread Cond is an evil api that is not suited for Pcsx2 needs.
// Let's not use it. (Air)
// --------------------------------------------------------------------------------------
#if 0
Threading::WaitEvent::WaitEvent()
{
int err = 0;
err = pthread_cond_init(&cond, NULL);
err = pthread_mutex_init(&mutex, NULL);
}
Threading::WaitEvent::~WaitEvent() throw()
{
pthread_cond_destroy( &cond );
pthread_mutex_destroy( &mutex );
}
void Threading::WaitEvent::Set()
{
pthread_mutex_lock( &mutex );
pthread_cond_signal( &cond );
pthread_mutex_unlock( &mutex );
}
void Threading::WaitEvent::Wait()
{
pthread_mutex_lock( &mutex );
pthread_cond_wait( &cond, &mutex );
pthread_mutex_unlock( &mutex );
}
#endif
// --------------------------------------------------------------------------------------
// InterlockedExchanges / AtomicExchanges (PCSX2's Helper versions)
// --------------------------------------------------------------------------------------
// define some overloads for InterlockedExchanges for commonly used types, like u32 and s32.
__fi bool Threading::AtomicBitTestAndReset( volatile u32& bitset, u8 bit )
{
return _interlockedbittestandreset( (volatile long*)& bitset, bit ) != 0;
}
__fi u32 Threading::AtomicExchange( volatile u32& Target, u32 value )
{
return _InterlockedExchange( (volatile long*)&Target, value );
}
__fi u32 Threading::AtomicExchangeAdd( volatile u32& Target, u32 value )
{
return _InterlockedExchangeAdd( (volatile long*)&Target, value );
}
__fi u32 Threading::AtomicIncrement( volatile u32& Target )
{
return _InterlockedExchangeAdd( (volatile long*)&Target, 1 );
}
__fi u32 Threading::AtomicDecrement( volatile u32& Target )
{
return _InterlockedExchangeAdd( (volatile long*)&Target, -1 );
}
__fi s32 Threading::AtomicExchange( volatile s32& Target, s32 value )
{
return _InterlockedExchange( (volatile long*)&Target, value );
}
__fi s32 Threading::AtomicExchangeAdd( volatile s32& Target, s32 value )
{
return _InterlockedExchangeAdd( (volatile long*)&Target, value );
}
__fi s32 Threading::AtomicExchangeSub( volatile s32& Target, s32 value )
{
return _InterlockedExchangeAdd( (volatile long*)&Target, -value );
}
__fi s32 Threading::AtomicIncrement( volatile s32& Target )
{
return _InterlockedExchangeAdd( (volatile long*)&Target, 1 );
}
__fi s32 Threading::AtomicDecrement( volatile s32& Target )
{
return _InterlockedExchangeAdd( (volatile long*)&Target, -1 );
}
__fi void* Threading::_AtomicExchangePointer( volatile uptr& target, uptr value )
{
#ifdef _M_AMD64 // high-level atomic ops, please leave these 64 bit checks in place.
return (void*)_InterlockedExchange64( &(volatile s64&)target, value );
#else
return (void*)_InterlockedExchange( (volatile long*)&target, value );
#endif
}
__fi void* Threading::_AtomicCompareExchangePointer( volatile uptr& target, uptr value, uptr comparand )
{
#ifdef _M_AMD64 // high-level atomic ops, please leave these 64 bit checks in place.
return (void*)_InterlockedCompareExchange64( &(volatile s64&)target, value );
#else
return (void*)_InterlockedCompareExchange( &(volatile long&)target, value, comparand );
#endif
}
// --------------------------------------------------------------------------------------
// BaseThreadError
// --------------------------------------------------------------------------------------
wxString Exception::BaseThreadError::FormatDiagnosticMessage() const
{
return wxsFormat( m_message_diag, (m_thread==NULL) ? L"Null Thread Object" : m_thread->GetName().c_str());
}
wxString Exception::BaseThreadError::FormatDisplayMessage() const
{
return wxsFormat( m_message_user, (m_thread==NULL) ? L"Null Thread Object" : m_thread->GetName().c_str());
}
pxThread& Exception::BaseThreadError::Thread()
{
pxAssertDev( m_thread != NULL, "NULL thread object on ThreadError exception." );
return *m_thread;
}
const pxThread& Exception::BaseThreadError::Thread() const
{
pxAssertDev( m_thread != NULL, "NULL thread object on ThreadError exception." );
return *m_thread;
}
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
]
| [
[
[
1,
882
]
]
]
|
b3c1f075c97523a13efd704ab97ba574eec7c442 | 6e4f9952ef7a3a47330a707aa993247afde65597 | /PROJECTS_ROOT/WireKeys/WP_TimeSync/Sntp.cpp | 4709145d60fbd5ef3f69f909b4fb8bae9b9988d1 | []
| no_license | meiercn/wiredplane-wintools | b35422570e2c4b486c3aa6e73200ea7035e9b232 | 134db644e4271079d631776cffcedc51b5456442 | refs/heads/master | 2021-01-19T07:50:42.622687 | 2009-07-07T03:34:11 | 2009-07-07T03:34:11 | 34,017,037 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 26,817 | cpp | /*
Module : SNTP.CPP
Purpose: implementation for a MFC class to encapsulate the SNTP protocol
Created: PJN / 05-08-1998
History: PJN / 16-11-1998 1. m_nOriginateTime was getting set incorrectly in the SNTP response
2. GetLastError now works when a timeout occurs.
PJN / 25-06-2000 1. Fixed an issue where the packing order of the NtpBasicInfo
struct was causing problems. Now packing is set to 1 byte for this
struct
AR / 22-07-2000 Windows CE 2.11 compatibility
PJN / 29-03-2001 1. Updated copyright message
2. Fixed a handle leak RevertSetTimePriviledge where the process
token was not been closed
PJN / 13-03-2003 1. Fixed a bug in CNtpSocket::IsReadible in the setup of the timeval
structure. Thanks to "InBloom Support" for reporting this.
PJN / 20-09-2003 1. Class now uses CWSocket class to provide sockets capability. This
now allows the class to support connecting via a Socks 5 proxy.
Copyright (c) 1998 - 2003 by PJ Naughter. (Web: www.naughter.com, Email: [email protected])
All rights reserved.
Copyright / Usage Details:
You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
when your product is released in binary form. You are allowed to modify the source code in any way you want
except you cannot modify the copyright details at the top of each module. If you want to distribute source
code with your application, then you are only allowed to distribute versions released by the author. This is
to maintain a single distribution point for the source code.
*/
///////////////////////////////// Includes //////////////////////////////////
#include "stdafx.h"
#ifndef _INC_MATH
#pragma message("To avoid this message, please put math.h in your pre compiled header (normally stdafx.h)")
#include <math.h>
#endif
#include "sntp.h"
#include "SocMFC.h" //If you get a compilation error about this missing header file, then you need to download my CWSocket wrapper classes from http://www.naughter.com/w3mfc.html
///////////////////////////////// Macros / Locals ///////////////////////////
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
const double NTP_FRACTIONAL_TO_MS = (((double)1000.0)/0xFFFFFFFF);
const double NTP_TO_SECOND = (((double)1.0)/0xFFFFFFFF);
const long JAN_1ST_1900 = 2415021;
//Lookup table to convert from Milliseconds (hence 1000 Entries)
//to fractions of a second expressed as a DWORD
DWORD CNtpTime::m_MsToNTP[1000] =
{
0x00000000, 0x00418937, 0x0083126f, 0x00c49ba6, 0x010624dd, 0x0147ae14,
0x0189374c, 0x01cac083, 0x020c49ba, 0x024dd2f2, 0x028f5c29, 0x02d0e560,
0x03126e98, 0x0353f7cf, 0x03958106, 0x03d70a3d, 0x04189375, 0x045a1cac,
0x049ba5e3, 0x04dd2f1b, 0x051eb852, 0x05604189, 0x05a1cac1, 0x05e353f8,
0x0624dd2f, 0x06666666, 0x06a7ef9e, 0x06e978d5, 0x072b020c, 0x076c8b44,
0x07ae147b, 0x07ef9db2, 0x083126e9, 0x0872b021, 0x08b43958, 0x08f5c28f,
0x09374bc7, 0x0978d4fe, 0x09ba5e35, 0x09fbe76d, 0x0a3d70a4, 0x0a7ef9db,
0x0ac08312, 0x0b020c4a, 0x0b439581, 0x0b851eb8, 0x0bc6a7f0, 0x0c083127,
0x0c49ba5e, 0x0c8b4396, 0x0ccccccd, 0x0d0e5604, 0x0d4fdf3b, 0x0d916873,
0x0dd2f1aa, 0x0e147ae1, 0x0e560419, 0x0e978d50, 0x0ed91687, 0x0f1a9fbe,
0x0f5c28f6, 0x0f9db22d, 0x0fdf3b64, 0x1020c49c, 0x10624dd3, 0x10a3d70a,
0x10e56042, 0x1126e979, 0x116872b0, 0x11a9fbe7, 0x11eb851f, 0x122d0e56,
0x126e978d, 0x12b020c5, 0x12f1a9fc, 0x13333333, 0x1374bc6a, 0x13b645a2,
0x13f7ced9, 0x14395810, 0x147ae148, 0x14bc6a7f, 0x14fdf3b6, 0x153f7cee,
0x15810625, 0x15c28f5c, 0x16041893, 0x1645a1cb, 0x16872b02, 0x16c8b439,
0x170a3d71, 0x174bc6a8, 0x178d4fdf, 0x17ced917, 0x1810624e, 0x1851eb85,
0x189374bc, 0x18d4fdf4, 0x1916872b, 0x19581062, 0x1999999a, 0x19db22d1,
0x1a1cac08, 0x1a5e353f, 0x1a9fbe77, 0x1ae147ae, 0x1b22d0e5, 0x1b645a1d,
0x1ba5e354, 0x1be76c8b, 0x1c28f5c3, 0x1c6a7efa, 0x1cac0831, 0x1ced9168,
0x1d2f1aa0, 0x1d70a3d7, 0x1db22d0e, 0x1df3b646, 0x1e353f7d, 0x1e76c8b4,
0x1eb851ec, 0x1ef9db23, 0x1f3b645a, 0x1f7ced91, 0x1fbe76c9, 0x20000000,
0x20418937, 0x2083126f, 0x20c49ba6, 0x210624dd, 0x2147ae14, 0x2189374c,
0x21cac083, 0x220c49ba, 0x224dd2f2, 0x228f5c29, 0x22d0e560, 0x23126e98,
0x2353f7cf, 0x23958106, 0x23d70a3d, 0x24189375, 0x245a1cac, 0x249ba5e3,
0x24dd2f1b, 0x251eb852, 0x25604189, 0x25a1cac1, 0x25e353f8, 0x2624dd2f,
0x26666666, 0x26a7ef9e, 0x26e978d5, 0x272b020c, 0x276c8b44, 0x27ae147b,
0x27ef9db2, 0x283126e9, 0x2872b021, 0x28b43958, 0x28f5c28f, 0x29374bc7,
0x2978d4fe, 0x29ba5e35, 0x29fbe76d, 0x2a3d70a4, 0x2a7ef9db, 0x2ac08312,
0x2b020c4a, 0x2b439581, 0x2b851eb8, 0x2bc6a7f0, 0x2c083127, 0x2c49ba5e,
0x2c8b4396, 0x2ccccccd, 0x2d0e5604, 0x2d4fdf3b, 0x2d916873, 0x2dd2f1aa,
0x2e147ae1, 0x2e560419, 0x2e978d50, 0x2ed91687, 0x2f1a9fbe, 0x2f5c28f6,
0x2f9db22d, 0x2fdf3b64, 0x3020c49c, 0x30624dd3, 0x30a3d70a, 0x30e56042,
0x3126e979, 0x316872b0, 0x31a9fbe7, 0x31eb851f, 0x322d0e56, 0x326e978d,
0x32b020c5, 0x32f1a9fc, 0x33333333, 0x3374bc6a, 0x33b645a2, 0x33f7ced9,
0x34395810, 0x347ae148, 0x34bc6a7f, 0x34fdf3b6, 0x353f7cee, 0x35810625,
0x35c28f5c, 0x36041893, 0x3645a1cb, 0x36872b02, 0x36c8b439, 0x370a3d71,
0x374bc6a8, 0x378d4fdf, 0x37ced917, 0x3810624e, 0x3851eb85, 0x389374bc,
0x38d4fdf4, 0x3916872b, 0x39581062, 0x3999999a, 0x39db22d1, 0x3a1cac08,
0x3a5e353f, 0x3a9fbe77, 0x3ae147ae, 0x3b22d0e5, 0x3b645a1d, 0x3ba5e354,
0x3be76c8b, 0x3c28f5c3, 0x3c6a7efa, 0x3cac0831, 0x3ced9168, 0x3d2f1aa0,
0x3d70a3d7, 0x3db22d0e, 0x3df3b646, 0x3e353f7d, 0x3e76c8b4, 0x3eb851ec,
0x3ef9db23, 0x3f3b645a, 0x3f7ced91, 0x3fbe76c9, 0x40000000, 0x40418937,
0x4083126f, 0x40c49ba6, 0x410624dd, 0x4147ae14, 0x4189374c, 0x41cac083,
0x420c49ba, 0x424dd2f2, 0x428f5c29, 0x42d0e560, 0x43126e98, 0x4353f7cf,
0x43958106, 0x43d70a3d, 0x44189375, 0x445a1cac, 0x449ba5e3, 0x44dd2f1b,
0x451eb852, 0x45604189, 0x45a1cac1, 0x45e353f8, 0x4624dd2f, 0x46666666,
0x46a7ef9e, 0x46e978d5, 0x472b020c, 0x476c8b44, 0x47ae147b, 0x47ef9db2,
0x483126e9, 0x4872b021, 0x48b43958, 0x48f5c28f, 0x49374bc7, 0x4978d4fe,
0x49ba5e35, 0x49fbe76d, 0x4a3d70a4, 0x4a7ef9db, 0x4ac08312, 0x4b020c4a,
0x4b439581, 0x4b851eb8, 0x4bc6a7f0, 0x4c083127, 0x4c49ba5e, 0x4c8b4396,
0x4ccccccd, 0x4d0e5604, 0x4d4fdf3b, 0x4d916873, 0x4dd2f1aa, 0x4e147ae1,
0x4e560419, 0x4e978d50, 0x4ed91687, 0x4f1a9fbe, 0x4f5c28f6, 0x4f9db22d,
0x4fdf3b64, 0x5020c49c, 0x50624dd3, 0x50a3d70a, 0x50e56042, 0x5126e979,
0x516872b0, 0x51a9fbe7, 0x51eb851f, 0x522d0e56, 0x526e978d, 0x52b020c5,
0x52f1a9fc, 0x53333333, 0x5374bc6a, 0x53b645a2, 0x53f7ced9, 0x54395810,
0x547ae148, 0x54bc6a7f, 0x54fdf3b6, 0x553f7cee, 0x55810625, 0x55c28f5c,
0x56041893, 0x5645a1cb, 0x56872b02, 0x56c8b439, 0x570a3d71, 0x574bc6a8,
0x578d4fdf, 0x57ced917, 0x5810624e, 0x5851eb85, 0x589374bc, 0x58d4fdf4,
0x5916872b, 0x59581062, 0x5999999a, 0x59db22d1, 0x5a1cac08, 0x5a5e353f,
0x5a9fbe77, 0x5ae147ae, 0x5b22d0e5, 0x5b645a1d, 0x5ba5e354, 0x5be76c8b,
0x5c28f5c3, 0x5c6a7efa, 0x5cac0831, 0x5ced9168, 0x5d2f1aa0, 0x5d70a3d7,
0x5db22d0e, 0x5df3b646, 0x5e353f7d, 0x5e76c8b4, 0x5eb851ec, 0x5ef9db23,
0x5f3b645a, 0x5f7ced91, 0x5fbe76c9, 0x60000000, 0x60418937, 0x6083126f,
0x60c49ba6, 0x610624dd, 0x6147ae14, 0x6189374c, 0x61cac083, 0x620c49ba,
0x624dd2f2, 0x628f5c29, 0x62d0e560, 0x63126e98, 0x6353f7cf, 0x63958106,
0x63d70a3d, 0x64189375, 0x645a1cac, 0x649ba5e3, 0x64dd2f1b, 0x651eb852,
0x65604189, 0x65a1cac1, 0x65e353f8, 0x6624dd2f, 0x66666666, 0x66a7ef9e,
0x66e978d5, 0x672b020c, 0x676c8b44, 0x67ae147b, 0x67ef9db2, 0x683126e9,
0x6872b021, 0x68b43958, 0x68f5c28f, 0x69374bc7, 0x6978d4fe, 0x69ba5e35,
0x69fbe76d, 0x6a3d70a4, 0x6a7ef9db, 0x6ac08312, 0x6b020c4a, 0x6b439581,
0x6b851eb8, 0x6bc6a7f0, 0x6c083127, 0x6c49ba5e, 0x6c8b4396, 0x6ccccccd,
0x6d0e5604, 0x6d4fdf3b, 0x6d916873, 0x6dd2f1aa, 0x6e147ae1, 0x6e560419,
0x6e978d50, 0x6ed91687, 0x6f1a9fbe, 0x6f5c28f6, 0x6f9db22d, 0x6fdf3b64,
0x7020c49c, 0x70624dd3, 0x70a3d70a, 0x70e56042, 0x7126e979, 0x716872b0,
0x71a9fbe7, 0x71eb851f, 0x722d0e56, 0x726e978d, 0x72b020c5, 0x72f1a9fc,
0x73333333, 0x7374bc6a, 0x73b645a2, 0x73f7ced9, 0x74395810, 0x747ae148,
0x74bc6a7f, 0x74fdf3b6, 0x753f7cee, 0x75810625, 0x75c28f5c, 0x76041893,
0x7645a1cb, 0x76872b02, 0x76c8b439, 0x770a3d71, 0x774bc6a8, 0x778d4fdf,
0x77ced917, 0x7810624e, 0x7851eb85, 0x789374bc, 0x78d4fdf4, 0x7916872b,
0x79581062, 0x7999999a, 0x79db22d1, 0x7a1cac08, 0x7a5e353f, 0x7a9fbe77,
0x7ae147ae, 0x7b22d0e5, 0x7b645a1d, 0x7ba5e354, 0x7be76c8b, 0x7c28f5c3,
0x7c6a7efa, 0x7cac0831, 0x7ced9168, 0x7d2f1aa0, 0x7d70a3d7, 0x7db22d0e,
0x7df3b646, 0x7e353f7d, 0x7e76c8b4, 0x7eb851ec, 0x7ef9db23, 0x7f3b645a,
0x7f7ced91, 0x7fbe76c9, 0x80000000, 0x80418937, 0x8083126f, 0x80c49ba6,
0x810624dd, 0x8147ae14, 0x8189374c, 0x81cac083, 0x820c49ba, 0x824dd2f2,
0x828f5c29, 0x82d0e560, 0x83126e98, 0x8353f7cf, 0x83958106, 0x83d70a3d,
0x84189375, 0x845a1cac, 0x849ba5e3, 0x84dd2f1b, 0x851eb852, 0x85604189,
0x85a1cac1, 0x85e353f8, 0x8624dd2f, 0x86666666, 0x86a7ef9e, 0x86e978d5,
0x872b020c, 0x876c8b44, 0x87ae147b, 0x87ef9db2, 0x883126e9, 0x8872b021,
0x88b43958, 0x88f5c28f, 0x89374bc7, 0x8978d4fe, 0x89ba5e35, 0x89fbe76d,
0x8a3d70a4, 0x8a7ef9db, 0x8ac08312, 0x8b020c4a, 0x8b439581, 0x8b851eb8,
0x8bc6a7f0, 0x8c083127, 0x8c49ba5e, 0x8c8b4396, 0x8ccccccd, 0x8d0e5604,
0x8d4fdf3b, 0x8d916873, 0x8dd2f1aa, 0x8e147ae1, 0x8e560419, 0x8e978d50,
0x8ed91687, 0x8f1a9fbe, 0x8f5c28f6, 0x8f9db22d, 0x8fdf3b64, 0x9020c49c,
0x90624dd3, 0x90a3d70a, 0x90e56042, 0x9126e979, 0x916872b0, 0x91a9fbe7,
0x91eb851f, 0x922d0e56, 0x926e978d, 0x92b020c5, 0x92f1a9fc, 0x93333333,
0x9374bc6a, 0x93b645a2, 0x93f7ced9, 0x94395810, 0x947ae148, 0x94bc6a7f,
0x94fdf3b6, 0x953f7cee, 0x95810625, 0x95c28f5c, 0x96041893, 0x9645a1cb,
0x96872b02, 0x96c8b439, 0x970a3d71, 0x974bc6a8, 0x978d4fdf, 0x97ced917,
0x9810624e, 0x9851eb85, 0x989374bc, 0x98d4fdf4, 0x9916872b, 0x99581062,
0x9999999a, 0x99db22d1, 0x9a1cac08, 0x9a5e353f, 0x9a9fbe77, 0x9ae147ae,
0x9b22d0e5, 0x9b645a1d, 0x9ba5e354, 0x9be76c8b, 0x9c28f5c3, 0x9c6a7efa,
0x9cac0831, 0x9ced9168, 0x9d2f1aa0, 0x9d70a3d7, 0x9db22d0e, 0x9df3b646,
0x9e353f7d, 0x9e76c8b4, 0x9eb851ec, 0x9ef9db23, 0x9f3b645a, 0x9f7ced91,
0x9fbe76c9, 0xa0000000, 0xa0418937, 0xa083126f, 0xa0c49ba6, 0xa10624dd,
0xa147ae14, 0xa189374c, 0xa1cac083, 0xa20c49ba, 0xa24dd2f2, 0xa28f5c29,
0xa2d0e560, 0xa3126e98, 0xa353f7cf, 0xa3958106, 0xa3d70a3d, 0xa4189375,
0xa45a1cac, 0xa49ba5e3, 0xa4dd2f1b, 0xa51eb852, 0xa5604189, 0xa5a1cac1,
0xa5e353f8, 0xa624dd2f, 0xa6666666, 0xa6a7ef9e, 0xa6e978d5, 0xa72b020c,
0xa76c8b44, 0xa7ae147b, 0xa7ef9db2, 0xa83126e9, 0xa872b021, 0xa8b43958,
0xa8f5c28f, 0xa9374bc7, 0xa978d4fe, 0xa9ba5e35, 0xa9fbe76d, 0xaa3d70a4,
0xaa7ef9db, 0xaac08312, 0xab020c4a, 0xab439581, 0xab851eb8, 0xabc6a7f0,
0xac083127, 0xac49ba5e, 0xac8b4396, 0xaccccccd, 0xad0e5604, 0xad4fdf3b,
0xad916873, 0xadd2f1aa, 0xae147ae1, 0xae560419, 0xae978d50, 0xaed91687,
0xaf1a9fbe, 0xaf5c28f6, 0xaf9db22d, 0xafdf3b64, 0xb020c49c, 0xb0624dd3,
0xb0a3d70a, 0xb0e56042, 0xb126e979, 0xb16872b0, 0xb1a9fbe7, 0xb1eb851f,
0xb22d0e56, 0xb26e978d, 0xb2b020c5, 0xb2f1a9fc, 0xb3333333, 0xb374bc6a,
0xb3b645a2, 0xb3f7ced9, 0xb4395810, 0xb47ae148, 0xb4bc6a7f, 0xb4fdf3b6,
0xb53f7cee, 0xb5810625, 0xb5c28f5c, 0xb6041893, 0xb645a1cb, 0xb6872b02,
0xb6c8b439, 0xb70a3d71, 0xb74bc6a8, 0xb78d4fdf, 0xb7ced917, 0xb810624e,
0xb851eb85, 0xb89374bc, 0xb8d4fdf4, 0xb916872b, 0xb9581062, 0xb999999a,
0xb9db22d1, 0xba1cac08, 0xba5e353f, 0xba9fbe77, 0xbae147ae, 0xbb22d0e5,
0xbb645a1d, 0xbba5e354, 0xbbe76c8b, 0xbc28f5c3, 0xbc6a7efa, 0xbcac0831,
0xbced9168, 0xbd2f1aa0, 0xbd70a3d7, 0xbdb22d0e, 0xbdf3b646, 0xbe353f7d,
0xbe76c8b4, 0xbeb851ec, 0xbef9db23, 0xbf3b645a, 0xbf7ced91, 0xbfbe76c9,
0xc0000000, 0xc0418937, 0xc083126f, 0xc0c49ba6, 0xc10624dd, 0xc147ae14,
0xc189374c, 0xc1cac083, 0xc20c49ba, 0xc24dd2f2, 0xc28f5c29, 0xc2d0e560,
0xc3126e98, 0xc353f7cf, 0xc3958106, 0xc3d70a3d, 0xc4189375, 0xc45a1cac,
0xc49ba5e3, 0xc4dd2f1b, 0xc51eb852, 0xc5604189, 0xc5a1cac1, 0xc5e353f8,
0xc624dd2f, 0xc6666666, 0xc6a7ef9e, 0xc6e978d5, 0xc72b020c, 0xc76c8b44,
0xc7ae147b, 0xc7ef9db2, 0xc83126e9, 0xc872b021, 0xc8b43958, 0xc8f5c28f,
0xc9374bc7, 0xc978d4fe, 0xc9ba5e35, 0xc9fbe76d, 0xca3d70a4, 0xca7ef9db,
0xcac08312, 0xcb020c4a, 0xcb439581, 0xcb851eb8, 0xcbc6a7f0, 0xcc083127,
0xcc49ba5e, 0xcc8b4396, 0xcccccccd, 0xcd0e5604, 0xcd4fdf3b, 0xcd916873,
0xcdd2f1aa, 0xce147ae1, 0xce560419, 0xce978d50, 0xced91687, 0xcf1a9fbe,
0xcf5c28f6, 0xcf9db22d, 0xcfdf3b64, 0xd020c49c, 0xd0624dd3, 0xd0a3d70a,
0xd0e56042, 0xd126e979, 0xd16872b0, 0xd1a9fbe7, 0xd1eb851f, 0xd22d0e56,
0xd26e978d, 0xd2b020c5, 0xd2f1a9fc, 0xd3333333, 0xd374bc6a, 0xd3b645a2,
0xd3f7ced9, 0xd4395810, 0xd47ae148, 0xd4bc6a7f, 0xd4fdf3b6, 0xd53f7cee,
0xd5810625, 0xd5c28f5c, 0xd6041893, 0xd645a1cb, 0xd6872b02, 0xd6c8b439,
0xd70a3d71, 0xd74bc6a8, 0xd78d4fdf, 0xd7ced917, 0xd810624e, 0xd851eb85,
0xd89374bc, 0xd8d4fdf4, 0xd916872b, 0xd9581062, 0xd999999a, 0xd9db22d1,
0xda1cac08, 0xda5e353f, 0xda9fbe77, 0xdae147ae, 0xdb22d0e5, 0xdb645a1d,
0xdba5e354, 0xdbe76c8b, 0xdc28f5c3, 0xdc6a7efa, 0xdcac0831, 0xdced9168,
0xdd2f1aa0, 0xdd70a3d7, 0xddb22d0e, 0xddf3b646, 0xde353f7d, 0xde76c8b4,
0xdeb851ec, 0xdef9db23, 0xdf3b645a, 0xdf7ced91, 0xdfbe76c9, 0xe0000000,
0xe0418937, 0xe083126f, 0xe0c49ba6, 0xe10624dd, 0xe147ae14, 0xe189374c,
0xe1cac083, 0xe20c49ba, 0xe24dd2f2, 0xe28f5c29, 0xe2d0e560, 0xe3126e98,
0xe353f7cf, 0xe3958106, 0xe3d70a3d, 0xe4189375, 0xe45a1cac, 0xe49ba5e3,
0xe4dd2f1b, 0xe51eb852, 0xe5604189, 0xe5a1cac1, 0xe5e353f8, 0xe624dd2f,
0xe6666666, 0xe6a7ef9e, 0xe6e978d5, 0xe72b020c, 0xe76c8b44, 0xe7ae147b,
0xe7ef9db2, 0xe83126e9, 0xe872b021, 0xe8b43958, 0xe8f5c28f, 0xe9374bc7,
0xe978d4fe, 0xe9ba5e35, 0xe9fbe76d, 0xea3d70a4, 0xea7ef9db, 0xeac08312,
0xeb020c4a, 0xeb439581, 0xeb851eb8, 0xebc6a7f0, 0xec083127, 0xec49ba5e,
0xec8b4396, 0xeccccccd, 0xed0e5604, 0xed4fdf3b, 0xed916873, 0xedd2f1aa,
0xee147ae1, 0xee560419, 0xee978d50, 0xeed91687, 0xef1a9fbe, 0xef5c28f6,
0xef9db22d, 0xefdf3b64, 0xf020c49c, 0xf0624dd3, 0xf0a3d70a, 0xf0e56042,
0xf126e979, 0xf16872b0, 0xf1a9fbe7, 0xf1eb851f, 0xf22d0e56, 0xf26e978d,
0xf2b020c5, 0xf2f1a9fc, 0xf3333333, 0xf374bc6a, 0xf3b645a2, 0xf3f7ced9,
0xf4395810, 0xf47ae148, 0xf4bc6a7f, 0xf4fdf3b6, 0xf53f7cee, 0xf5810625,
0xf5c28f5c, 0xf6041893, 0xf645a1cb, 0xf6872b02, 0xf6c8b439, 0xf70a3d71,
0xf74bc6a8, 0xf78d4fdf, 0xf7ced917, 0xf810624e, 0xf851eb85, 0xf89374bc,
0xf8d4fdf4, 0xf916872b, 0xf9581062, 0xf999999a, 0xf9db22d1, 0xfa1cac08,
0xfa5e353f, 0xfa9fbe77, 0xfae147ae, 0xfb22d0e5, 0xfb645a1d, 0xfba5e354,
0xfbe76c8b, 0xfc28f5c3, 0xfc6a7efa, 0xfcac0831, 0xfced9168, 0xfd2f1aa0,
0xfd70a3d7, 0xfdb22d0e, 0xfdf3b646, 0xfe353f7d, 0xfe76c8b4, 0xfeb851ec,
0xfef9db23, 0xff3b645a, 0xff7ced91, 0xffbe76c9
};
//The mandatory part of an NTP packet
#pragma pack(push, 1)
struct NtpBasicInfo
{
BYTE m_LiVnMode;
BYTE m_Stratum;
char m_Poll;
char m_Precision;
long m_RootDelay;
long m_RootDispersion;
char m_ReferenceID[4];
CNtpTimePacket m_ReferenceTimestamp;
CNtpTimePacket m_OriginateTimestamp;
CNtpTimePacket m_ReceiveTimestamp;
CNtpTimePacket m_TransmitTimestamp;
};
#pragma pack(pop)
//The optional part of an NTP packet
struct NtpAuthenticationInfo
{
unsigned long m_KeyID;
BYTE m_MessageDigest[16];
};
//The Full NTP packet
struct NtpFullPacket
{
NtpBasicInfo m_Basic;
NtpAuthenticationInfo m_Auth;
};
///////////////////////////////// Implementation //////////////////////////////
CNtpTime::CNtpTime()
{
m_Time = 0;
}
CNtpTime::CNtpTime(const CNtpTime& time)
{
*this = time;
}
CNtpTime::CNtpTime(CNtpTimePacket& packet)
{
DWORD dwLow = ntohl(packet.m_dwFractional);
DWORD dwHigh = ntohl(packet.m_dwInteger);
m_Time = ((unsigned __int64) dwHigh) << 32;
m_Time += dwLow;
}
CNtpTime::CNtpTime(const SYSTEMTIME& st)
{
//Currently this function only operates correctly in
//the 1900 - 2036 primary epoch defined by NTP
long JD = GetJulianDay(st.wYear, st.wMonth, st.wDay);
JD -= JAN_1ST_1900;
ASSERT(JD >= 0); //NTP only supports dates greater than 1900
unsigned __int64 Seconds = JD;
Seconds = (Seconds * 24) + st.wHour;
Seconds = (Seconds * 60) + st.wMinute;
Seconds = (Seconds * 60) + st.wSecond;
ASSERT(Seconds <= 0xFFFFFFFF); //NTP Only supports up to 2036
m_Time = (Seconds << 32) + MsToNtpFraction(st.wMilliseconds);
}
long CNtpTime::GetJulianDay(WORD Year, WORD Month, WORD Day)
{
long y = (long) Year;
long m = (long) Month;
long d = (long) Day;
if (m > 2)
m = m - 3;
else
{
m = m + 9;
y = y - 1;
}
long c = y / 100;
long ya = y - 100 * c;
long j = (146097L * c) / 4 + (1461L * ya) / 4 + (153L * m + 2) / 5 + d + 1721119L;
return j;
}
void CNtpTime::GetGregorianDate(long JD, WORD& Year, WORD& Month, WORD& Day)
{
long j = JD - 1721119;
long y = (4 * j - 1) / 146097;
j = 4 * j - 1 - 146097 * y;
long d = j / 4;
j = (4 * d + 3) / 1461;
d = 4 * d + 3 - 1461 * j;
d = (d + 4) / 4;
long m = (5 * d - 3) / 153;
d = 5 * d - 3 - 153 * m;
d = (d + 5) / 5;
y = 100 * y + j;
if (m < 10)
m = m + 3;
else
{
m = m - 9;
y = y + 1;
}
Year = (WORD) y;
Month = (WORD) m;
Day = (WORD) d;
}
CNtpTime& CNtpTime::operator=(const CNtpTime& time)
{
m_Time = time.m_Time;
return *this;
}
double CNtpTime::operator-(const CNtpTime& time) const
{
if (m_Time >= time.m_Time)
{
CNtpTime diff;
diff.m_Time = m_Time - time.m_Time;
return diff.Seconds() + NtpFractionToSecond(diff.Fraction());
}
else
{
CNtpTime diff;
diff.m_Time = time.m_Time - m_Time;
return -(diff.Seconds() + NtpFractionToSecond(diff.Fraction()));
}
}
CNtpTime CNtpTime::operator+(const double& timespan) const
{
CNtpTime rVal;
rVal.m_Time = m_Time;
if (timespan >= 0)
{
unsigned __int64 diff = ((unsigned __int64) timespan) << 32;
double intpart;
double frac = modf(timespan, &intpart);
diff += (unsigned __int64) (frac * 0xFFFFFFFF);
rVal.m_Time += diff;
}
else
{
double d = -timespan;
unsigned __int64 diff = ((unsigned __int64) d) << 32;
double intpart;
double frac = modf(d, &intpart);
diff += (unsigned __int64) (frac * 0xFFFFFFFF);
rVal.m_Time -= diff;
}
return rVal;
}
CNtpTime::operator SYSTEMTIME() const
{
//Currently this function only operates correctly in
//the 1900 - 2036 primary epoch defined by NTP
SYSTEMTIME st;
DWORD s = Seconds();
st.wSecond = (WORD)(s % 60);
s /= 60;
st.wMinute = (WORD)(s % 60);
s /= 60;
st.wHour = (WORD)(s % 24);
s /= 24;
long JD = s + JAN_1ST_1900;
st.wDayOfWeek = (WORD)((JD + 1) % 7);
GetGregorianDate(JD, st.wYear, st.wMonth, st.wDay);
st.wMilliseconds = NtpFractionToMs(Fraction());
return st;
}
DWORD CNtpTime::Seconds() const
{
return (DWORD) ((m_Time & 0xFFFFFFFF00000000) >> 32);
}
DWORD CNtpTime::Fraction() const
{
return (DWORD) (m_Time & 0xFFFFFFFF);
}
CNtpTime::operator CNtpTimePacket() const
{
CNtpTimePacket ntp;
ntp.m_dwInteger = htonl(Seconds());
ntp.m_dwFractional = htonl(Fraction());
return ntp;
}
CNtpTime CNtpTime::GetCurrentTime()
{
SYSTEMTIME st;
GetSystemTime(&st);
CNtpTime t(st);
return t;
}
DWORD CNtpTime::MsToNtpFraction(WORD wMilliSeconds)
{
ASSERT(wMilliSeconds < 1000);
return m_MsToNTP[wMilliSeconds];
}
WORD CNtpTime::NtpFractionToMs(DWORD dwFraction)
{
return (WORD)((((double)dwFraction) * NTP_FRACTIONAL_TO_MS) + 0.5);
}
double CNtpTime::NtpFractionToSecond(DWORD dwFraction)
{
double d = (double)dwFraction;
d *= NTP_TO_SECOND;
return ((double)dwFraction) * NTP_TO_SECOND;
}
CSNTPClient::CSNTPClient()
{
m_dwTimeout = 5000; //Default timeout of 5 seconds
m_nProxyPort = 1080;
m_bProxy = FALSE;
}
BOOL CSNTPClient::GetServerTime(LPCTSTR pszHostName, NtpServerResponse& response, int nPort)
{
//For correct operation of the T2A macro, see MFC Tech Note 59
USES_CONVERSION;
//paramater validity checking
ASSERT(pszHostName);
//Create the socket, Allocated of the heap so we can control
//the time when it's destructor is called. This means that
//we can call SetLastError after its destructor
CWSocket* pSocket = new CWSocket();
try
{
if (m_bProxy)
pSocket->Create(FALSE); //TCP if going thro a proxy
else
pSocket->Create(TRUE); //UDP otherwise
}
catch(CWSocketException* pEx)
{
pEx->Delete();
TRACE(_T("Failed to create client socket, GetLastError returns: %d\n"), GetLastError());
return FALSE;
}
//Connect to the SNTP server (or Socks Proxy)
try
{
if (m_bProxy)
{
/*
if (m_sLocalBoundAddress.GetLength())
{
if (m_sProxyUserName.GetLength())
pSocket->ConnectViaSocks5(pszHostName, nPort, m_sProxyServer, m_nProxyPort, m_sProxyUserName, m_sProxyPassword, m_sLocalBoundAddress, m_dwTimeout, TRUE);
else
pSocket->ConnectViaSocks5(pszHostName, nPort, m_sProxyServer, m_nProxyPort, NULL, NULL, m_sLocalBoundAddress, m_dwTimeout, TRUE);
}
else
*/
{
if (m_sProxyUserName.GetLength()){
//pSocket->ConnectViaSocks5(pszHostName, nPort, m_sProxyServer, m_nProxyPort, m_sProxyUserName, m_sProxyPassword, NULL, m_dwTimeout, TRUE);
pSocket->ConnectViaSocks5(pszHostName, nPort, m_sProxyServer, m_nProxyPort, m_sProxyUserName, m_sProxyPassword, m_dwTimeout, TRUE);
}else{
pSocket->ConnectViaSocks5(pszHostName, nPort, m_sProxyServer, m_nProxyPort, NULL, NULL, m_dwTimeout, TRUE);
//pSocket->ConnectViaSocks5(pszHostName, nPort, m_sProxyServer, m_nProxyPort, NULL, NULL, NULL, m_dwTimeout, TRUE);
}
}
}
else
{
/*
if (m_sLocalBoundAddress.GetLength())
pSocket->Connect(pszHostName, nPort, m_sLocalBoundAddress);
else
*/
pSocket->Connect(pszHostName, nPort);
}
}
catch(CWSocketException* pEx)
{
TRACE(_T("Could not connect to the SNTP server %s on port %d, GetLastError returns: %d\n"), pszHostName, nPort, pEx->m_nError);
//Tidy up prior to returning
delete pSocket;
SetLastError(pEx->m_nError);
pEx->Delete();
return FALSE;
}
//Initialise the NtpBasicInfo packet
NtpBasicInfo nbi;
int nSendSize = sizeof(NtpBasicInfo);
memset(&nbi, 0, nSendSize);
nbi.m_LiVnMode = 27; //Encoded representation which represents NTP Client Request & NTP version 3.0 (i.e. LI=0, VN=3, Mode=3)
nbi.m_TransmitTimestamp = CNtpTime::GetCurrentTime();
//Send off the NtpBasicInfo packet
try
{
pSocket->Send(&nbi, nSendSize);
}
catch(CWSocketException* pEx)
{
TRACE(_T("Failed in call to send NTP request to the SNTP server, GetLastError returns %d\n"), pEx->m_nError);
//Tidy up prior to returning
delete pSocket;
SetLastError(pEx->m_nError);
pEx->Delete();
return FALSE;
}
//Need to use select to determine readibilty of socket
BOOL bReadable = FALSE;
try
{
bReadable = pSocket->IsReadible(m_dwTimeout);
}
catch(CWSocketException* pEx)
{
pEx->Delete();
bReadable = FALSE;
}
if (!bReadable)
{
TRACE(_T("Unable to wait for NTP reply from the SNTP server, GetLastError returns %d\n"), WSAETIMEDOUT);
//Tidy up prior to returning
delete pSocket;
SetLastError(WSAETIMEDOUT);
return FALSE;
}
response.m_DestinationTime = CNtpTime::GetCurrentTime();
//read back the response into the NtpFullPacket struct
NtpFullPacket nfp;
int nReceiveSize = sizeof(NtpFullPacket);
memset(&nfp, 0, nReceiveSize);
try
{
pSocket->Receive(&nfp, nReceiveSize);
}
catch(CWSocketException* pEx)
{
TRACE(_T("Unable to read reply from the SNTP server, Error returns %d\n"), pEx->m_nError);
//Tidy up prior to returning
DWORD dwError = GetLastError();
delete pSocket;
SetLastError(pEx->m_nError);
pEx->Delete();
return FALSE;
}
//Transfer all the useful info into the response structure
response.m_nStratum = nfp.m_Basic.m_Stratum;
response.m_nLeapIndicator = (nfp.m_Basic.m_LiVnMode & 0xC0) >> 6;
response.m_OriginateTime = nfp.m_Basic.m_OriginateTimestamp;
response.m_ReceiveTime = nfp.m_Basic.m_ReceiveTimestamp;
response.m_TransmitTime = nfp.m_Basic.m_TransmitTimestamp;
response.m_RoundTripDelay = (response.m_DestinationTime - response.m_OriginateTime) - (response.m_ReceiveTime - response.m_TransmitTime);
response.m_LocalClockOffset = ((response.m_ReceiveTime - response.m_OriginateTime) + (response.m_TransmitTime - response.m_DestinationTime)) / 2;
//Tidy up prior to returning
delete pSocket;
return TRUE;
}
//AR 22-07-2000
#ifndef _WIN32_WCE
BOOL CSNTPClient::EnableSetTimePriviledge()
{
BOOL bOpenToken = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES |
TOKEN_QUERY, &m_hToken);
m_bTakenPriviledge = FALSE;
if (!bOpenToken)
{
if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
//Must be running on 95 or 98 not NT. In that case just ignore the error
SetLastError(ERROR_SUCCESS);
return TRUE;
}
TRACE(_T("Failed to get Adjust priviledge token\n"));
return FALSE;
}
ZeroMemory(&m_TokenPriv, sizeof(TOKEN_PRIVILEGES));
if (!LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &m_TokenPriv.Privileges[0].Luid))
{
TRACE(_T("Failed in callup to lookup priviledge\n"));
return FALSE;
}
m_TokenPriv.PrivilegeCount = 1;
m_TokenPriv.Privileges[0].Attributes |= SE_PRIVILEGE_ENABLED;
m_bTakenPriviledge = TRUE;
BOOL bSuccess = AdjustTokenPrivileges(m_hToken, FALSE, &m_TokenPriv, 0, NULL, 0);
if (!bSuccess)
TRACE(_T("Failed to adjust SetTime priviledge\n"));
return bSuccess;
}
#endif
//AR 22-07-2000
#ifndef _WIN32_WCE
void CSNTPClient::RevertSetTimePriviledge()
{
if (m_bTakenPriviledge)
{
m_TokenPriv.Privileges[0].Attributes &= (~SE_PRIVILEGE_ENABLED);
if (!AdjustTokenPrivileges(m_hToken, FALSE, &m_TokenPriv, 0, NULL, 0))
TRACE(_T("Failed to reset SetTime priviledge\n"));
CloseHandle(m_hToken);
}
}
#endif
BOOL CSNTPClient::SetClientTime(const CNtpTime& NewTime)
{
BOOL bSuccess = FALSE;
//AR 22-07-2000
#ifndef _WIN32_WCE
if (EnableSetTimePriviledge())
{
#endif
SYSTEMTIME st = NewTime;
bSuccess = SetSystemTime(&st);
if (!bSuccess)
TRACE(_T("Failed in call to set the system time\n"));
//AR 22-07-2000
#ifndef _WIN32_WCE
}
RevertSetTimePriviledge();
#endif
return bSuccess;
}
| [
"wplabs@3fb49600-69e0-11de-a8c1-9da277d31688"
]
| [
[
[
1,
700
]
]
]
|
413f0d4af59b7f77953f1947f3c6583b9076d7cf | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctesteh/src/bctestehcontainer.cpp | 3a32e90755cb3f928605b226d6f83b7caec55fd3 | []
| 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 | 3,441 | cpp | /*
* Copyright (c) 2006 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: container
*
*/
#include "bctestehcontainer.h"
// ======== MEMBER FUNCTIONS ========
// ---------------------------------------------------------------------------
// C++ default Constructor
// ---------------------------------------------------------------------------
//
CBCTestEHContainer::CBCTestEHContainer()
{
}
// ---------------------------------------------------------------------------
// Destructor
// ---------------------------------------------------------------------------
//
CBCTestEHContainer::~CBCTestEHContainer()
{
ResetControl();
}
// ---------------------------------------------------------------------------
// Symbian 2nd Constructor
// ---------------------------------------------------------------------------
//
void CBCTestEHContainer::ConstructL( const TRect& aRect )
{
CreateWindowL();
SetRect( aRect );
ActivateL();
}
// ----------------------------------------------------------------------------
// CBCTestEHContainer::Draw
// Fills the window's rectangle.
// ----------------------------------------------------------------------------
//
void CBCTestEHContainer::Draw( const TRect& aRect ) const
{
CWindowGc& gc = SystemGc();
gc.SetPenStyle( CGraphicsContext::ENullPen );
gc.SetBrushColor( KRgbGray );
gc.SetBrushStyle( CGraphicsContext::ESolidBrush );
gc.DrawRect( aRect );
}
// ---------------------------------------------------------------------------
// CBCTestEHContainer::CountComponentControls
// ---------------------------------------------------------------------------
//
TInt CBCTestEHContainer::CountComponentControls() const
{
if ( iControl )
{
return 1;
}
else
{
return 0;
}
}
// ---------------------------------------------------------------------------
// CBCTestEHContainer::ComponentControl
// ---------------------------------------------------------------------------
//
CCoeControl* CBCTestEHContainer::ComponentControl( TInt ) const
{
return iControl;
}
// ---------------------------------------------------------------------------
// CBCTestEHContainer::SetControl
// ---------------------------------------------------------------------------
//
void CBCTestEHContainer::SetControl( CCoeControl* aControl )
{
iControl = aControl;
if ( iControl )
{
// You can change the position and size
iControl->SetExtent( Rect().iTl, Rect().Size() );
DrawNow();
}
}
// ---------------------------------------------------------------------------
// CBCTestEHContainer::ResetControl
// ---------------------------------------------------------------------------
//
void CBCTestEHContainer::ResetControl()
{
delete iControl;
iControl = NULL;
}
//end of file
| [
"none@none"
]
| [
[
[
1,
117
]
]
]
|
9b09069bd6344b7216ff5ec44d92827d1c91e297 | 3ec3b97044e4e6a87125470cfa7eef535f26e376 | /victor_and_andre-sourcegod/include/test.h | c6bd30929f031aef6dec092fd4dd4b2f0263fb34 | []
| no_license | strategist922/TINS-Is-not-speedhack-2010 | 6d7a43ebb9ab3b24208b3a22cbcbb7452dae48af | 718b9d037606f0dbd9eb6c0b0e021eeb38c011f9 | refs/heads/master | 2021-01-18T14:14:38.724957 | 2010-10-17T14:04:40 | 2010-10-17T14:04:40 | null | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 367 | h | /*
* TINS 2010 - The source god
* Authors: Victor Williams Stafusa da Silva
* André Luiz Pereira Álvares
*/
#ifndef __SENTINELA_TEST
#define __SENTINELA_TEST
#define RUN_TEST 1
#if RUN_TEST
#include <iostream>
#include <fstream>
void pathfind_test();
void readsource_test();
#endif /* RUN_TEST */
#endif /* __SENTINELA_TEST */ | [
"[email protected]"
]
| [
[
[
1,
21
]
]
]
|
0b68b83f1f88c8570121ef134aed59879f1a589c | 7d5bde00c1d3f3e03a0f35ed895068f0451849b2 | /treethread.cpp | ca7f2aff936db0edfeda5017f88f456499140514 | []
| no_license | jkackley/jeremykackley-dfjobs-improvment | 6638af16515d140e9d68c7872b11b47d4f6d7587 | 73f53a26daa7f66143f35956150c8fe2b922c2e2 | refs/heads/master | 2021-01-16T01:01:38.642050 | 2011-05-16T18:03:23 | 2011-05-16T18:03:23 | 32,128,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,698 | cpp | /*-
* Copyright (c) 2011, Derek Young
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
//#include <QString>
//#include <QFutureSynchronizer>
//#include <QtConcurrentRun>
//#include <QDebug>
//#include <math.h>
//#include <algorithm>
#include "treethread.h"
//#include "dwarfforeman.h"
using namespace std;
//extern dfsettings settings;
//extern dfitem dfitems[];
//extern uint32_t x_max,y_max,z_max, tx_max, ty_max;
//vector<cords *> busy;
void TreeThread::run() {
// When a tree is being cut, it isn't designated. If you redesignate it, it throws an annoying invalid dig error.
//uint32_t cvector = meminfo->getAddress ("creature_vector");
//uint32_t race_offset = meminfo->getOffset ("creature_race");
//uint32_t job_type_offset = meminfo->getOffset("job_type");
//uint32_t current_job_offset = meminfo->getOffset("creature_current_job");
//DFHack::t_creature creature;
/*
DFHack::DfVector <uint32_t> p_cre (p, cvector);
for(uint32_t i = 0; i < p_cre.size(); i++)
{ */
/*
creature.race = p->readDWord(p_cre[i] + race_offset);
creature.current_job.occupationPtr = p->readDWord(p_cre[i] + current_job_offset);
if(creature.current_job.occupationPtr > 0)
{
creature.current_job.active = true;
creature.current_job.jobType = p->readByte (creature.current_job.occupationPtr + job_type_offset);
}
else
{
creature.current_job.active = false;
creature.current_job.jobType = 0;
}*/ /*
uint32_t occupation = p->readDWord(p_cre[i] + current_job_offset);
if ((p->readDWord(p_cre[i] + race_offset) == 200) && (occupation))
{
uint8_t jobType = p->readByte (occupation + job_type_offset);
if ((jobType == 9) || (jobType == 10))
{
cords *cord = new cords;
cord->x = p->readWord(occupation+16);
cord->y = p->readWord(occupation+18);
cord->z = p->readWord(occupation+20);
busy.push_back(cord);
}
} */
/*
if((creature.race == 200) && creature.current_job.active && ((creature.current_job.jobType == 9) || (creature.current_job.jobType == 10)))
{
cords *hrm = new cords;
hrm->x = p->readWord(creature.current_job.occupationPtr+16);
hrm->y = p->readWord(creature.current_job.occupationPtr+18);
hrm->z = p->readWord(creature.current_job.occupationPtr+20);
busy.push_back(hrm);
} */ /*
}
settings.logpending = 0;
uint32_t numTrees;
v->Start(numTrees);
//////////////
QFutureSynchronizer<void> synchronizer;
const int MAXS = 600;
for (uint32_t i = 0 ; i < numTrees; i += MAXS)
synchronizer.addFuture(QtConcurrent::run(this,&TreeThread::cutTree,i,((i+MAXS)<numTrees) ? (i+MAXS) : numTrees));
synchronizer.waitForFinished();
//////////////////
v->Finish();
for (uint32_t i = 0; i < busy.size(); i++)
{
delete busy[i];
}
busy.clear();
*/
}
void TreeThread::cutTree(uint32_t start, uint32_t end)
{
/*
//uint32_t desOff = meminfo->getOffset ("map_data_designation");
//uint32_t tileOff = meminfo->getOffset ("map_data_type");
vector<uint32_t> dirty;
uint32_t pending = 0;
for (uint32_t i = start; i < end; i++)
{
DFHack::t_tree tree;
v->Read(i,tree);
// make sure we are not wasting our time
if ((tree.type == 0 || tree.type == 1) && !settings.logenabled) continue;
if ((tree.type == 2 || tree.type == 3) && !settings.gatherallplants) continue;
// Make sure tree isn't on the boundary. why?
//if(tree.x == 0 || tree.x == tx_max - 1 || tree.y == 0 || tree.y == ty_max - 1) continue;
uint32_t blockPtr = Maps->getBlockPtr(floor(tree.x/16),floor(tree.y/16),tree.z);
qDebug(QString::number(blockPtr,16).toAscii());
uint32_t designation = p->readDWord(blockPtr + desOff + ((((tree.x%16) * 16) + (tree.y%16))*4));
// Make sure it isn't hiden.
if ((designation & 512) == 512)
{ // Clean up the mess if the stupid fucking user tried this with reveal on.
if((designation & 16) == 16)
{
designation = (designation & ~16) | (-false & 16);
p->writeDWord(blockPtr + desOff + ((((tree.x%16) * 16) + (tree.y%16))*4), designation);
dirty.push_back(blockPtr);
}
continue;
}
// Make sure it is not already designated.
if ((designation & 16) == 16)
{
if (tree.type == 0 || tree.type == 1)
pending++;
continue;
}
// Don't waste time
if ((tree.type == 0 || tree.type == 1) && !settings.cutalltrees) continue;
//Make sure it isn't a sapling... (or dead)
uint16_t tileType = p->readWord(blockPtr + tileOff + ((((tree.x%16) * 16) + (tree.y%16))*2));
if((tileType != 24) && (tileType != 34)) continue;
// Make sure none of the dwarfs are about to cut this down
int abort = 0;
for (uint32_t i = 0; i < busy.size(); i++)
{
if ((busy[i]->x == tree.x) && (busy[i]->y == tree.y) && (busy[i]->z == tree.z))
{
abort = 1;
break;
}
} if (abort == 1) continue;
// Chop chop chop, suck it elves!
designation = (designation & ~16) | (-true & 16);
p->writeDWord(blockPtr + desOff + ((((tree.x%16) * 16) + (tree.y%16))*4), designation);
dirty.push_back(blockPtr);
if (tree.type == 0 || tree.type == 1) pending++;
}
settings.logpending += pending;
std::sort(dirty.begin(),dirty.end());
dirty.erase(std::unique(dirty.begin(), dirty.end()), dirty.end());
for (uint32_t i = 0; i < dirty.size(); i++)
{
uint32_t addr_of_struct = p->readDWord(dirty[i]);
uint32_t dirtydword = p->readDWord(addr_of_struct);
dirtydword &= 0xFFFFFFFE;
dirtydword |= (uint32_t) true;
p->writeDWord (addr_of_struct, dirtydword);
}
*/
}
| [
"Devek@localhost"
]
| [
[
[
1,
192
]
]
]
|
0f650bbc3b4b2f46da94054794eb48a87ae68346 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/Models/MDLBASE/RL_BASIC.CPP | 9e408b95195337f7ec864f0fef3d181a3928761f | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,985 | cpp | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
// SysCAD Copyright Kenwalt (Pty) Ltd 1992
#include "stdafx.h"
#include <string.h>
#include <math.h>
#include <stdio.h>
#define __RL_BASIC_CPP
#include "rl_basic.h"
//===========================================================================
//
//
//
//===========================================================================
/*#D:#T:Simple Regulation Logic
#X:#h<General Description>#nThis is a regulation logic equation. Simple... ???
#n#n
#n#h<Variables to be supplied by the user>#n
#i<Y> : ???#n
#n
#n#h<Other>#n
Short name:RL_Basic#n
Model type:Regulation Logic#n
#G:Regulation Logic
*/
IMPLEMENT_REGLTNLOGIC(RL_Basic, "RL_Basic", "", TOC_SYSTEM, "Simple", "Simple Regulation Logic")
RL_Basic::RL_Basic(pTagObjClass pClass_, pchar pTag, pTaggedObject pAttach, TagObjAttachment eAttach) :
CIO_Logic(pClass_, pTag, pAttach, eAttach)
{
//bOn=1;
dOut=1.0;
dMin=0.0;
dMax=1.0;
//Initialise(pAttach);
};
//---------------------------------------------------------------------------
RL_Basic::~RL_Basic()
{
};
//---------------------------------------------------------------------------
void RL_Basic::BuildDataDefn(DataDefnBlk & DDB)
{
//DDBAdd_OnOff(DDB, "State", &bOn);
DDB.Double("", "Y", DC_Frac, "%", &dOut, this, isParm);
}
//---------------------------------------------------------------------------
flag RL_Basic::DataXchg(DataChangeBlk & DCB)
{
return False;
}
//---------------------------------------------------------------------------
flag RL_Basic::CopyFrom(CIO_Logic * pOther)
{
RL_Basic * pO=dynamic_cast<RL_Basic*>(pOther);
if (pO)
{
dOut = pO->dOut;
dMin = pO->dMin;
dMax = pO->dMax;
return true;
}
return false;
};
//---------------------------------------------------------------------------
//void RL_Basic::EvalCtrlActions(pFlwNode pFNode)
// {
// };
//---------------------------------------------------------------------------
void RL_Basic::SetOutput(double O)
{
dOut = Range(dMin, O, dMax);
};
//---------------------------------------------------------------------------
double RL_Basic::Output()
{
dOut=Range(dMin, dOut, dMax);
return dOut;//bOn ? dOut : 0.0;
};
//---------------------------------------------------------------------------
void RL_Basic::SetRange(double Min, double Max)
{
dMin=Min;
dMax=Max;
};
//---------------------------------------------------------------------------
double RL_Basic::RangeMin()
{
return dMin;
};
//---------------------------------------------------------------------------
double RL_Basic::RangeMax()
{
return dMax;
};
//===========================================================================
//
//
//
//===========================================================================
/*#D:#T:Simple Regulation Logic
#X:#h<General Description>#nThis is a regulation logic equation. Simple... ???
#n#n
#n#h<Variables to be supplied by the user>#n
#i<Y> : ???#n
#n
#n#h<Other>#n
Short name:RL_Basic#n
Model type:Regulation Logic#n
#G:Regulation Logic
*/
IMPLEMENT_REGLTNLOGIC(RL_Stroke, "RL_Stroke", "", TOC_SYSTEM, "Stroking", "Stroking Regulation Logic")
RL_Stroke::RL_Stroke(pTagObjClass pClass_, pchar pTag, pTaggedObject pAttach, TagObjAttachment eAttach) :
RL_Basic(pClass_, pTag, pAttach, eAttach)
{
//bOn=1;
dOut=1.0;
dOutRqd=1.0;
dMin=0.0;
dMax=1.0;
dStrkUp=10.0;
dStrkDn=10.0;
//Initialise(pAttach);
};
//---------------------------------------------------------------------------
RL_Stroke::~RL_Stroke()
{
};
//---------------------------------------------------------------------------
void RL_Stroke::BuildDataDefn(DataDefnBlk & DDB)
{
//DDBAdd_OnOff(DDB, "State", &bOn);
DDB.Double("", "Y", DC_Frac, "%", &dOut, this, isResult|0);
DDB.Double("", "YReqd", DC_Frac, "%", &dOutRqd, this, isParm);
DDB.Double("", "StokeUp", DC_T, "s", &dStrkUp, this, isParm);
DDB.Double("", "StokeDn", DC_T, "s", &dStrkDn, this, isParm);
}
//---------------------------------------------------------------------------
flag RL_Stroke::DataXchg(DataChangeBlk & DCB)
{
return False;
}
//---------------------------------------------------------------------------
void RL_Stroke::EvalCtrlActions(pFlwNode pFNode)
{
double dDiff = dOutRqd-dOut;
// limit the diff by the stroketime
// dDiff = Sign(dDiff)*Min(fabs(dDiff),(ICGetTimeInc()/GTZ(dDiff>0.0 ? dStrkUp : dStrkDn)));
double D=dMax-dMin;
if (dDiff>0)
dDiff = Min(dDiff, D*ICGetTimeInc()/GTZ(dStrkUp));
else
dDiff = Max(dDiff, -D*ICGetTimeInc()/GTZ(dStrkDn));
// apply it;
dOut+=dDiff;
};
//---------------------------------------------------------------------------
void RL_Stroke::SetOutput(double O)
{
dOut = Range(dMin, O, dMax);
};
//---------------------------------------------------------------------------
double RL_Stroke::Output()
{
dOut=Range(dMin, dOut, dMax);
return dOut;//bOn ? dOut : 0.0;
};
//---------------------------------------------------------------------------
void RL_Stroke::SetRange(double Min, double Max)
{
dMin=Min;
dMax=Max;
};
//---------------------------------------------------------------------------
double RL_Stroke::RangeMin()
{
return dMin;
};
//---------------------------------------------------------------------------
double RL_Stroke::RangeMax()
{
return dMax;
};
//===========================================================================
| [
"[email protected]"
]
| [
[
[
1,
235
]
]
]
|
f7f7e0211ff86c4d9cbd0f679bb208e50c4372e2 | d609fb08e21c8583e5ad1453df04a70573fdd531 | /trunk/OpenXP/下载组件/library/DownLoadMTR.cpp | f8287ca7527190477e24791fdbc2a4d52e54a7c6 | []
| 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 | 29,843 | cpp | #include "StdAfx.h"
#include "DownLoadMTR.h"
#include <io.h>
#include "PublicFunc.h"
void DownloadNotify(int nIndex, UINT nNotityType, LPVOID lpNotifyData, LPVOID pDownloadMTR);
DownLoadMTR::DownLoadMTR() : m_nThreadCount(DEFAULT_THREAD_COUNT)
, m_pDownloadPub_MTR(NULL)
, m_pDownloadPub_Info(NULL)
, m_pDownloadCellInfo(NULL)
, m_hThread(NULL)
, m_bForceDownload(FALSE)
, m_nTotalDownloadedSize_ThisTimes(0)
{
memset(&m_BaseDownInfo,0,sizeof(BaseDownInfo));
m_hEvtEndModule = ::CreateEvent(NULL, TRUE, FALSE, NULL);
m_dwDownloadStartTime = GetTickCount();
}
DownLoadMTR::~DownLoadMTR()
{
StopDownload ();
}
//
// 设置下载的线程数
//
BOOL DownLoadMTR::SetThreadCount(int nThreadCount)
{
if (nThreadCount <= 0 || nThreadCount > MAX_DOWNLOAD_THREAD_COUNT)
{
HWriteLog("Thread count %d is invalid. Rang [%d-%d]", nThreadCount, 1, MAX_DOWNLOAD_THREAD_COUNT);
return FALSE;
}
if (nThreadCount == m_nThreadCount)
return TRUE;
m_nThreadCount = nThreadCount;
return TRUE;
}
//
// 下载任务的线程函数
//
DWORD WINAPI ThreadProcDownloadMTR(LPVOID lpParameter // thread data
)
{
DownLoadMTR *pDownloadMTR = (DownLoadMTR*)lpParameter;
ASSERT(pDownloadMTR);
pDownloadMTR->ThreadProcDownloadMTR();
TRACE("下载任务的线程函数 执行完毕\n");
HWriteLog("下载任务的线程函数 执行完毕\n");
return TRUE;
}
BOOL DownLoadMTR::ThreadProcDownloadMTR()
{
// 启动多线程下载任务
int nRet = StartMTRDownload();
if (nRet == 2) return HandleDownloadFinished(ENUM_DOWNLOAD_RESULT_SUCCESS);
if (nRet == 0) return HandleDownloadFinished(ENUM_DOWNLOAD_RESULT_FAILED);
// 等待所有线程下载完成
ENUM_DOWNLOAD_RESULT eDownloadResult = WaitForDownloadFinished ();
if (eDownloadResult == ENUM_DOWNLOAD_RESULT_SUCCESS && !GetDownloadResult())
{
eDownloadResult = ENUM_DOWNLOAD_RESULT_FAILED;
}
return HandleDownloadFinished(eDownloadResult);
}
BOOL DownLoadMTR::StartDownload()
{
return Download(m_strDownloadURL, m_strSavePath, m_strSaveOnlyFileName);
}
//
// 多线程断点续传下载一个文件
//
BOOL DownLoadMTR::Download (
LPCTSTR lpszDownloadURL,
LPCTSTR lpszSavePath,
LPCTSTR lpszSaveOnlyFileName,
LPCTSTR lpszUsername/*=NULL*/,
LPCTSTR lpszPassword/*=NULL*/,
BOOL bForceDownload/*=FALSE*/ // 如果为 TRUE 表示强制性重新下载,以下载的部分将会被删除,FALSE 表示断点续传
)
{
if (!HANDLE_IS_VALID(m_hEvtEndModule))
return FALSE;
if (!lpszSavePath || strlen(lpszSavePath) < 1)
return FALSE;
m_strSavePath = lpszSavePath;
m_strSaveOnlyFileName = GET_SAFE_STRING(lpszSaveOnlyFileName);
m_bForceDownload = bForceDownload;
CString strServer, strObject;
USHORT nPort = 0;
if (!ParseTrueURL (lpszDownloadURL, strServer, strObject, nPort, m_strProtocolType))
{
HWriteLog("Download URL [%s] invalid", lpszDownloadURL);
return FALSE;
}
m_strDownloadURL = lpszDownloadURL;
// 创建取站点信息对象
if (!(m_pDownloadPub_Info = CreateDownloadObject()))
{
HWriteLog("Create download object failed");
return HandleDownloadFinished(ENUM_DOWNLOAD_RESULT_FAILED);
}
// 设置取站点信息对象的参数
m_pDownloadPub_Info->SetAuthorization(lpszUsername, lpszPassword);
m_pDownloadPub_Info->m_pDownloadMTR = this;
m_pDownloadPub_Info->SetDownloadUrl(lpszDownloadURL);
// 创建一个下载线程
DWORD dwThreadId = 0;
m_hThread = CreateThread(NULL,0,::ThreadProcDownloadMTR,LPVOID(this),0,&dwThreadId);
if (!HANDLE_IS_VALID(m_hThread))
{
HWriteLog("Create download thread failed");
return FALSE;
}
return TRUE;
}
//
// 创建下载对象
//
DownLoadPublic* DownLoadMTR::CreateDownloadObject ( int nCount/*=1*/ )
{
if (nCount < 1) return NULL;
DownLoadPublic *pDownloadPub = NULL;
if (m_strProtocolType.CompareNoCase ("http") == 0)
{
pDownloadPub = (DownLoadPublic*)new DownLoadHTTP[nCount];
}
else if (m_strProtocolType.CompareNoCase ("ftp") == 0)
{
pDownloadPub = (DownLoadPublic*)new DownLoadFTP[nCount];
}
else
return NULL;
return pDownloadPub;
}
//
// 删除下载对象
//
void DownLoadMTR::DeleteDownloadObject ( DownLoadPublic *pDownloadPub )
{
if ( m_strProtocolType.CompareNoCase ("http") == 0 )
{
delete[] ((DownLoadHTTP*)pDownloadPub);
}
else if (m_strProtocolType.CompareNoCase ("ftp") == 0)
{
delete[] ((DownLoadFTP*)pDownloadPub);
}
else delete[] pDownloadPub;
}
void Callback_SaveDownloadInfo ( int nIndex, int nDownloadedSize, int nSimpleSaveSize, WPARAM wParam )
{
DownLoadMTR *pDownloadMTR = (DownLoadMTR*)wParam;
ASSERT ( pDownloadMTR );
pDownloadMTR->CallbackSaveDownloadInfo(nIndex, nDownloadedSize, nSimpleSaveSize);
}
void DownLoadMTR::CallbackSaveDownloadInfo( int nIndex, int nDownloadedSize, int nSimpleSaveSize )
{
if (nIndex >= 0 && nIndex < m_nThreadCount)
{
m_pDownloadCellInfo[nIndex].nDownloadedSize = nDownloadedSize;
if (nDownloadedSize > 0)
{
m_csDownloadedData.Lock();
m_nTotalDownloadedSize_ThisTimes += nSimpleSaveSize;
m_csDownloadedData.Unlock();
}
}
}
//
// 创建多线程下载使用的对象和数据缓冲
//
BOOL DownLoadMTR::CreateDownloadObjectAndDataMTR()
{
DeleteDownloadObjectAndDataMTR();
ASSERT(!m_pDownloadPub_MTR && m_pDownloadPub_Info);
m_pDownloadPub_MTR = CreateDownloadObject(m_nThreadCount);
// 设置多线程下载使用的对象的参数
if (m_pDownloadPub_MTR)
{
for (int nIndex=0; nIndex<m_nThreadCount; nIndex++)
{
m_pDownloadPub_MTR[nIndex].m_nIndex = nIndex;
m_pDownloadPub_MTR[nIndex].m_pDownloadMTR = this;
m_pDownloadPub_MTR[nIndex].SetSaveDownloadInfoCallback(::Callback_SaveDownloadInfo, WPARAM(this) );
m_pDownloadPub_MTR[nIndex].SetAuthorization(m_pDownloadPub_Info->GetUserName(), m_pDownloadPub_Info->GetPassword() );
m_pDownloadPub_MTR[nIndex].SetDownloadUrl(m_strDownloadURL);
if (!m_pDownloadPub_MTR[nIndex].SetSaveFileName (GetTempFilePath()))
return FALSE;
}
}
// 创建多线程下载使用的数据缓冲
ASSERT (!m_pDownloadCellInfo);
m_pDownloadCellInfo = new DownLoadCellInfo[m_nThreadCount];
if (m_pDownloadCellInfo)
memset(m_pDownloadCellInfo, 0, m_nThreadCount*sizeof(DownLoadCellInfo));
if (m_pDownloadPub_MTR != NULL && m_pDownloadCellInfo != NULL)
return TRUE;
HWriteLog("Create MTR download object or buffer failed");
return FALSE;
}
//
// 删除多线程下载使用的对象和数据缓冲
//
void DownLoadMTR::DeleteDownloadObjectAndDataMTR()
{
if (m_pDownloadPub_MTR)
{
DeleteDownloadObject(m_pDownloadPub_MTR);
m_pDownloadPub_MTR = NULL;
}
if (m_pDownloadCellInfo)
{
delete[] m_pDownloadCellInfo;
m_pDownloadCellInfo = NULL;
}
}
//
// 删除取站点信息的下载对象
//
void DownLoadMTR::DeleteDownloadObjectInfo()
{
if (m_pDownloadPub_Info)
{
DeleteDownloadObject(m_pDownloadPub_Info);
m_pDownloadPub_Info = NULL;
}
}
//
// 启动多线程下载,返回 0 表示失败,1表示成功,2表示不用下载了,因为该文件已经下载过了
//
int DownLoadMTR::StartMTRDownload()
{
m_dwDownloadStartTime = GetTickCount();
DownloadNotify(-1, NOTIFY_TYPE_START_DOWNLOAD, (LPVOID)NULL, this);
// 先获取站点信息
ASSERT(m_pDownloadPub_Info);
if (!m_pDownloadPub_Info->GetRemoteSiteInfo())
return 0;
TRACE("要下载的文件大小是: %d 字节\n", m_pDownloadPub_Info->GetFileTotalSize());
HWriteLog("要下载的文件大小是: %d 字节\n", m_pDownloadPub_Info->GetFileTotalSize());
StandardSaveFileName();
CFileStatus fileStatus;
if (m_bForceDownload)
{
// 需要重新下载
::DeleteFile(m_strSavePathFileName);
::DeleteFile(GetTempFilePath());
}
else
{
// 要保存的文件是否已经存在,且大小和创建时间一致,如果不是强制性下载,则不需要再下载了。
if (CFile::GetStatus(m_strSavePathFileName,fileStatus))
{
if (
(
fileStatus.m_mtime.GetTime() - m_pDownloadPub_Info->GetTimeLastModified() <=2 &&
m_pDownloadPub_Info->GetTimeLastModified()-fileStatus.m_mtime.GetTime() <=2
)
&&
fileStatus.m_size == m_pDownloadPub_Info->GetFileTotalSize()
&&
!m_bForceDownload
)
{
return 2;
}
}
}
BOOL bMustCreateNullFile = TRUE;
// 读取下载信息,如果能读到说明上次下载尚未完成
if (!m_bForceDownload && m_pDownloadPub_Info->IsSupportResume())
{
if (CFile::GetStatus(GetTempFilePath(),fileStatus) &&
fileStatus.m_size == m_pDownloadPub_Info->GetFileTotalSize()+GetDownloadInfoWholeSize())
{
if (ReadDownloadInfo())
bMustCreateNullFile = FALSE;
}
}
if (bMustCreateNullFile)
{
int nFileSize = m_pDownloadPub_Info->GetFileTotalSize();
int nTempFileSize = nFileSize+GetDownloadInfoWholeSize();
if (nFileSize < 0 || !m_pDownloadPub_Info->IsSupportResume())
nTempFileSize = 0;
// 创建一个用来保存下载数据的空文件
if (!CreateNullFile(GetTempFilePath(), nTempFileSize ))
return FALSE;
}
// 分配下载任务
if (!AssignDownloadTask())
{
HWriteLog("Assign task failed");
return 0;
}
m_dwDownloadStartTime = GetTickCount();
return 1;
}
//
// 得到临时数据保存的路径文件名
//
CString DownLoadMTR::GetTempFilePath()
{
ASSERT(!m_strSavePathFileName.IsEmpty());
CString strTempFileName;
strTempFileName.Format("%s.lj", m_strSavePathFileName);
//::SetFileAttributes(strTempFileName,FILE_ATTRIBUTE_HIDDEN);
return strTempFileName;
}
//
// 分配下载任务
//
BOOL DownLoadMTR::AssignDownloadTask()
{
ASSERT ( m_pDownloadPub_Info );
if (!m_pDownloadPub_Info->IsSupportResume())
{
DeleteDownloadObjectAndDataMTR ();
HWriteLog("Site [%s] not support resume download", m_pDownloadPub_Info->GetServerName());
}
// 文件大小未知,采用单线程
if (m_pDownloadPub_Info->GetFileTotalSize () <= 0 || !m_pDownloadPub_Info->IsSupportResume())
{
if (m_nThreadCount != 1)
{
DeleteDownloadObjectAndDataMTR();
SetThreadCount(1);
}
}
if (!DownloadInfoIsValid() || !m_pDownloadPub_MTR || !m_pDownloadCellInfo)
{
if (!CreateDownloadObjectAndDataMTR())
return FALSE;
}
ASSERT (m_pDownloadPub_MTR && m_pDownloadCellInfo);
// 下载任务尚未分配
if (!DownloadInfoIsValid())
{
int nWillDownloadSize = -1, nWillDownloadStartPos = 0, nNoAssignSize = 0;
if (m_pDownloadPub_Info->GetFileTotalSize() > 0)
{
nWillDownloadSize = m_pDownloadPub_Info->GetFileTotalSize () / m_nThreadCount;
// 均分后剩下的部分,让第一个线程来承担下载
nNoAssignSize = m_pDownloadPub_Info->GetFileTotalSize () % m_nThreadCount;
}
TRACE("任务分配如下:--------------------\n");
HWriteLog("任务分配如下:--------------------\n");
for (int nIndex = 0; nIndex < m_nThreadCount; nIndex++)
{
m_pDownloadCellInfo[nIndex].nWillDownloadStartPos = nWillDownloadStartPos;
m_pDownloadCellInfo[nIndex].nWillDownloadSize = nWillDownloadSize;
if (nIndex == 0 && m_pDownloadPub_Info->GetFileTotalSize () > 0)
{
m_pDownloadCellInfo[nIndex].nWillDownloadSize += nNoAssignSize;
}
TRACE("线程.%d 从 %d(0x%08x) 下载到 %d(0x%08x) 共 %d(0x%08x) 字节\n", nIndex,
m_pDownloadCellInfo[nIndex].nWillDownloadStartPos, m_pDownloadCellInfo[nIndex].nWillDownloadStartPos,
m_pDownloadCellInfo[nIndex].nWillDownloadStartPos+m_pDownloadCellInfo[nIndex].nWillDownloadSize,
m_pDownloadCellInfo[nIndex].nWillDownloadStartPos+m_pDownloadCellInfo[nIndex].nWillDownloadSize,
m_pDownloadCellInfo[nIndex].nWillDownloadSize, m_pDownloadCellInfo[nIndex].nWillDownloadSize);
HWriteLog("线程.%d 从 %d(0x%08x) 下载到 %d(0x%08x) 共 %d(0x%08x) 字节\n", nIndex,
m_pDownloadCellInfo[nIndex].nWillDownloadStartPos, m_pDownloadCellInfo[nIndex].nWillDownloadStartPos,
m_pDownloadCellInfo[nIndex].nWillDownloadStartPos+m_pDownloadCellInfo[nIndex].nWillDownloadSize,
m_pDownloadCellInfo[nIndex].nWillDownloadStartPos+m_pDownloadCellInfo[nIndex].nWillDownloadSize,
m_pDownloadCellInfo[nIndex].nWillDownloadSize, m_pDownloadCellInfo[nIndex].nWillDownloadSize);
nWillDownloadStartPos += m_pDownloadCellInfo[nIndex].nWillDownloadSize;
}
}
// 启动下载任务
for (int nIndex = 0; nIndex < m_nThreadCount; nIndex++)
{
if (!m_pDownloadPub_MTR[nIndex].Download(m_pDownloadCellInfo[nIndex].nWillDownloadStartPos,
m_pDownloadCellInfo[nIndex].nWillDownloadSize, m_pDownloadCellInfo[nIndex].nDownloadedSize))
return FALSE;
}
m_BaseDownInfo.dwThreadCount = m_nThreadCount;
return TRUE;
}
//
// 从下载信息文件中读取下载信息
//
BOOL DownLoadMTR::ReadDownloadInfo()
{
CString strTempFileName = GetTempFilePath();
BOOL bRet = FALSE;
CFile file;
TRY
{
if (file.Open(strTempFileName, CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite|CFile::typeBinary|CFile::shareDenyNone ))
{
if ( file.Seek(-(int)sizeof(BaseDownInfo), CFile::end) == (int)(file.GetLength() - sizeof(BaseDownInfo)))
{
if ((UINT)file.Read ( &m_BaseDownInfo, sizeof(BaseDownInfo) ) == sizeof(BaseDownInfo))
{
if ((m_BaseDownInfo.dwThreadCount > 0 && m_BaseDownInfo.dwThreadCount <= MAX_DOWNLOAD_THREAD_COUNT)&&
SetThreadCount ( m_BaseDownInfo.dwThreadCount ))
{
if (CreateDownloadObjectAndDataMTR())
{
if (file.Seek(-GetDownloadInfoWholeSize(), CFile::end ) == int(file.GetLength() - GetDownloadInfoWholeSize()))
{
if (file.Read(m_pDownloadCellInfo, sizeof(DownLoadCellInfo)*m_nThreadCount ) == sizeof(DownLoadCellInfo)*m_nThreadCount)
{
bRet = TRUE;
}
else
{
memset(m_pDownloadCellInfo, 0, sizeof(DownLoadCellInfo)*m_nThreadCount);
}
}
}
}
}
}
}
}
CATCH(CFileException, e)
{
e->Delete ();
bRet = FALSE;
}
END_CATCH
if (HANDLE_IS_VALID(file.m_hFile))
file.Close();
return bRet;
}
BOOL DownLoadMTR::SaveDownloadInfo ()
{
if (!m_pDownloadPub_Info->IsSupportResume())
return TRUE;
CString strTempFileName = GetTempFilePath();
BOOL bRet = FALSE;
CFile file;
TRY
{
if (file.Open(strTempFileName, CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite|CFile::typeBinary|CFile::shareDenyNone))
{
if (file.Seek ( -(int)sizeof(BaseDownInfo), CFile::end ) == (int)(file.GetLength() - sizeof(BaseDownInfo)))
{
file.Write ( &m_BaseDownInfo, sizeof(BaseDownInfo) );
if (file.Seek ( -GetDownloadInfoWholeSize(), CFile::end ) == int(file.GetLength() - GetDownloadInfoWholeSize()))
{
file.Write(m_pDownloadCellInfo, m_nThreadCount*sizeof(DownLoadCellInfo));
bRet = TRUE;
}
}
}
}
CATCH(CFileException, e)
{
e->Delete();
bRet = FALSE;
}
END_CATCH
if (HANDLE_IS_VALID(file.m_hFile))
file.Close();
if (!bRet)
HWriteLog("Save download info failed. %s", ErrorCodeFormatMessage(GetLastError()));
return bRet;
}
BOOL DownLoadMTR::HandleDownloadFinished(ENUM_DOWNLOAD_RESULT eDownloadResult)
{
CString strTempFileName;
CFileStatus fileStatus;
BOOL bRet = FALSE;
CFile file;
if (eDownloadResult != ENUM_DOWNLOAD_RESULT_SUCCESS)
{
SaveDownloadInfo();
goto Finished;
}
strTempFileName = GetTempFilePath();
// 设置文件大小
if (m_pDownloadPub_Info->IsSupportResume() && m_pDownloadPub_Info->GetFileTotalSize() > 0)
{
TRY
{
file.Open(strTempFileName, CFile::modeCreate|CFile::modeNoTruncate|CFile::modeReadWrite|CFile::typeBinary|CFile::shareDenyNone);
file.SetLength(m_pDownloadPub_Info->GetFileTotalSize ());
bRet = TRUE;
}
CATCH(CFileException, e)
{
e->Delete();
bRet = FALSE;
}
END_CATCH
if (HANDLE_IS_VALID(file.m_hFile))
file.Close();
if (!bRet)
{
HWriteLog("Set [%s] length failed", strTempFileName);
eDownloadResult = ENUM_DOWNLOAD_RESULT_FAILED;
goto Finished;
}
}
if (_access(strTempFileName,04) == 0)
{
// 将文件改名
bRet = FALSE;
DeleteFile(m_strSavePathFileName);
TRY
{
CFile::Rename(strTempFileName, m_strSavePathFileName);
bRet = TRUE;
}
CATCH(CFileException, e)
{
e->Delete();
bRet = FALSE;
}
END_CATCH
if (!bRet)
{
HWriteLog("Rename [%s] failed. %s", strTempFileName, ErrorCodeFormatMessage(GetLastError()));
eDownloadResult = ENUM_DOWNLOAD_RESULT_FAILED;
goto Finished;
}
// 设置文件属性,时间设置和服务器一致
bRet = FALSE;
if (CFile::GetStatus(m_strSavePathFileName,fileStatus))
{
fileStatus.m_mtime = m_pDownloadPub_Info->GetTimeLastModified();
fileStatus.m_attribute = CFile::normal;
CFile::SetStatus (m_strSavePathFileName, fileStatus);
bRet = TRUE;
}
if ( !bRet )
{
HWriteLog("Set file [%s] status failed. %s", strTempFileName, ErrorCodeFormatMessage(GetLastError()));
eDownloadResult = ENUM_DOWNLOAD_RESULT_FAILED;
goto Finished;
}
}
Finished:
DownloadNotify(-1, NOTIFY_TYPE_END_DOWNLOAD, (LPVOID)eDownloadResult, this);
return bRet;
}
BOOL DownLoadMTR::GetDownloadResult()
{
for (int nIndex=0; nIndex<m_nThreadCount; nIndex++)
{
if (!m_pDownloadPub_MTR[nIndex].IsDownloadSuccess())
return FALSE;
}
return TRUE;
}
//
// 下载信息是否有效
//
BOOL DownLoadMTR::DownloadInfoIsValid()
{
BOOL bValid = FALSE;
int nIndex = 0;
if (!m_pDownloadCellInfo)
goto Invalid;
if (m_BaseDownInfo.dwThreadCount < 1 || m_BaseDownInfo.dwThreadCount > MAX_DOWNLOAD_THREAD_COUNT)
goto Invalid;
for (nIndex=0; nIndex<m_nThreadCount; nIndex++)
{
if (m_pDownloadCellInfo[nIndex].nWillDownloadSize > 0)
{
bValid = TRUE;
break;
}
}
if (!bValid) goto Invalid;
return TRUE;
Invalid:
if (m_pDownloadCellInfo)
memset(m_pDownloadCellInfo, 0, m_nThreadCount*sizeof(DownLoadCellInfo));
memset(&m_BaseDownInfo, 0, sizeof(BaseDownInfo));
return FALSE;
}
//
// 找到剩余未下载的数量最大的那个对象编号
//
int DownLoadMTR::GetUndownloadMaxBytes( int &nUndownloadBytes )
{
nUndownloadBytes = 0;
int nMaxIndex = -1;
for (int nIndex=0; nIndex<m_nThreadCount; nIndex++)
{
int nTempBytes = m_pDownloadPub_MTR[nIndex].GetUndownloadBytes();
if (nUndownloadBytes < nTempBytes)
{
nUndownloadBytes = nTempBytes;
nMaxIndex = nIndex;
}
}
return nMaxIndex;
}
//
// 编号为 nIndex 的对象调度任务,为下载任务最繁重的对象减轻负担
//
BOOL DownLoadMTR::AttemperDownloadTask(int nIndex)
{
ASSERT(m_pDownloadPub_MTR && m_pDownloadCellInfo);
if (m_nThreadCount <= 1 || m_pDownloadCellInfo[nIndex].nWillDownloadSize == -1)
return FALSE;
int nUndownloadBytes = 0;
int nIndex_Heavy = GetUndownloadMaxBytes(nUndownloadBytes);
if (nIndex_Heavy == -1 || nIndex_Heavy == nIndex)
return FALSE;
if (m_pDownloadPub_MTR[nIndex_Heavy].ThreadIsRunning() && nUndownloadBytes < 100*1024)
return FALSE;
ASSERT(nIndex_Heavy >= 0 && nIndex_Heavy < m_nThreadCount);
ASSERT(m_pDownloadPub_MTR[nIndex_Heavy].GetWillDownloadStartPos() == m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadStartPos);
TRACE("下载对象.%d 帮 %d (%s) 减轻负担\n", nIndex, nIndex_Heavy, m_pDownloadPub_MTR[nIndex_Heavy].ThreadIsRunning()?"运行":"停止");
HWriteLog("下载对象.%d 帮 %d (%s) 减轻负担\n", nIndex, nIndex_Heavy, m_pDownloadPub_MTR[nIndex_Heavy].ThreadIsRunning()?"运行":"停止");
// 给空闲下载对象分配新任务
m_pDownloadCellInfo[nIndex].nWillDownloadSize = ( m_pDownloadPub_MTR[nIndex_Heavy].ThreadIsRunning()?(nUndownloadBytes/2) : nUndownloadBytes );
m_pDownloadCellInfo[nIndex].nWillDownloadStartPos = m_pDownloadPub_MTR[nIndex_Heavy].GetWillDownloadStartPos() +
m_pDownloadPub_MTR[nIndex_Heavy].GetWillDownloadSize() - m_pDownloadCellInfo[nIndex].nWillDownloadSize;
m_pDownloadCellInfo[nIndex].nDownloadedSize = 0;
TRACE("空闲下载对象.%d 分配新任务: %d(0x%08x) - %d(0x%08x) 共 %d(0x%08x)\n", nIndex, m_pDownloadCellInfo[nIndex].nWillDownloadStartPos, m_pDownloadCellInfo[nIndex].nWillDownloadStartPos,
m_pDownloadCellInfo[nIndex].nWillDownloadStartPos + m_pDownloadCellInfo[nIndex].nWillDownloadSize, m_pDownloadCellInfo[nIndex].nWillDownloadStartPos + m_pDownloadCellInfo[nIndex].nWillDownloadSize,
m_pDownloadCellInfo[nIndex].nWillDownloadSize, m_pDownloadCellInfo[nIndex].nWillDownloadSize);
HWriteLog("空闲下载对象.%d 分配新任务: %d(0x%08x) - %d(0x%08x) 共 %d(0x%08x)\n", nIndex, m_pDownloadCellInfo[nIndex].nWillDownloadStartPos, m_pDownloadCellInfo[nIndex].nWillDownloadStartPos,
m_pDownloadCellInfo[nIndex].nWillDownloadStartPos + m_pDownloadCellInfo[nIndex].nWillDownloadSize, m_pDownloadCellInfo[nIndex].nWillDownloadStartPos + m_pDownloadCellInfo[nIndex].nWillDownloadSize,
m_pDownloadCellInfo[nIndex].nWillDownloadSize, m_pDownloadCellInfo[nIndex].nWillDownloadSize);
// 启动空闲下载对象的下载任务
if (m_pDownloadCellInfo[nIndex].nWillDownloadSize == 0)
return FALSE;
m_pDownloadPub_MTR[nIndex].ResetVar();
if (!m_pDownloadPub_MTR[nIndex].Download(m_pDownloadCellInfo[nIndex].nWillDownloadStartPos,
m_pDownloadCellInfo[nIndex].nWillDownloadSize, m_pDownloadCellInfo[nIndex].nDownloadedSize))
return FALSE;
// 减轻繁忙下载对象的任务
m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadSize -= m_pDownloadCellInfo[nIndex].nWillDownloadSize;
m_pDownloadPub_MTR[nIndex_Heavy].SetWillDownloadSize(m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadSize);
TRACE("繁忙下载对象.%d 下载了 %d(0x%08x) 未完 %d(0x%08x) 字节,调整任务为: %d(0x%08x) - %d(0x%08x) 共 %d(0x%08x)\n",
nIndex_Heavy, m_pDownloadPub_MTR[nIndex_Heavy].GetDownloadedSize(), m_pDownloadPub_MTR[nIndex_Heavy].GetDownloadedSize(),
nUndownloadBytes, nUndownloadBytes,
m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadStartPos, m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadStartPos,
m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadStartPos + m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadSize, m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadStartPos + m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadSize,
m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadSize, m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadSize);
HWriteLog("繁忙下载对象.%d 下载了 %d(0x%08x) 未完 %d(0x%08x) 字节,调整任务为: %d(0x%08x) - %d(0x%08x) 共 %d(0x%08x)\n",
nIndex_Heavy, m_pDownloadPub_MTR[nIndex_Heavy].GetDownloadedSize(), m_pDownloadPub_MTR[nIndex_Heavy].GetDownloadedSize(),
nUndownloadBytes, nUndownloadBytes,
m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadStartPos, m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadStartPos,
m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadStartPos + m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadSize, m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadStartPos + m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadSize,
m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadSize, m_pDownloadCellInfo[nIndex_Heavy].nWillDownloadSize);
return TRUE;
}
//
// 等待下载结束
//
ENUM_DOWNLOAD_RESULT DownLoadMTR::WaitForDownloadFinished()
{
ASSERT(HANDLE_IS_VALID(m_hEvtEndModule));
int nCount = m_nThreadCount + 1;
ENUM_DOWNLOAD_RESULT eDownloadResult = ENUM_DOWNLOAD_RESULT_FAILED;
HANDLE *lpHandles = new HANDLE[nCount];
if (!lpHandles)
goto End;
while (TRUE)
{
nCount = 0;
for (int nIndex=0; nIndex<m_nThreadCount; nIndex++)
{
HANDLE hThread = m_pDownloadPub_MTR[nIndex].GetThreadHandle();
if (HANDLE_IS_VALID(hThread))
lpHandles[nCount++] = hThread;
}
lpHandles[nCount++] = m_hEvtEndModule;
if (nCount == 1)
{
if (GetTotalDownloadedSize() >= m_pDownloadPub_Info->GetFileTotalSize())
{
ASSERT(GetTotalDownloadedSize() == m_pDownloadPub_Info->GetFileTotalSize());
eDownloadResult = ENUM_DOWNLOAD_RESULT_SUCCESS;
}
else
eDownloadResult = ENUM_DOWNLOAD_RESULT_FAILED;
goto End;
}
int nRet = (int)WaitForMultipleObjects(nCount, lpHandles, FALSE, INFINITE ) - WAIT_OBJECT_0;
// 某下载对象完成任务了
if (nRet >= 0 && nRet < nCount-1)
{
int nIndex = FindIndexByThreadHandle(lpHandles[nRet]);
if ((nIndex >= 0 && nIndex < m_nThreadCount ))
{
if (!m_pDownloadPub_MTR[nIndex].IsDownloadSuccess() ||
!AttemperDownloadTask (nIndex))
{
m_pDownloadPub_MTR[nIndex].ClearThreadHandle();
}
}
else
{
eDownloadResult = ENUM_DOWNLOAD_RESULT_CANCEL;
goto End;
}
}
// 模块结束
else
{
eDownloadResult = ENUM_DOWNLOAD_RESULT_CANCEL;
goto End;
}
}
End:
// 等待所有下载线程结束
if (eDownloadResult != ENUM_DOWNLOAD_RESULT_SUCCESS)
{
nCount = 0;
for (int nIndex=0; nIndex<m_nThreadCount; nIndex++)
{
HANDLE hThread = m_pDownloadPub_MTR[nIndex].GetThreadHandle();
if (HANDLE_IS_VALID(hThread))
lpHandles[nCount++] = hThread;
}
WaitForMultipleObjects(nCount, lpHandles, TRUE, 500*1000);
}
if (lpHandles)
delete[] lpHandles;
return eDownloadResult;
}
int DownLoadMTR::FindIndexByThreadHandle(HANDLE hThread)
{
for (int nIndex = 0; nIndex < m_nThreadCount; nIndex++)
{
HANDLE hThread_Temp = m_pDownloadPub_MTR[nIndex].GetThreadHandle();
if (HANDLE_IS_VALID(hThread_Temp) && hThread_Temp == hThread)
return nIndex;
}
return -1;
}
int DownLoadMTR::GetDownloadInfoWholeSize()
{
return ( sizeof(DownLoadCellInfo)*m_nThreadCount + sizeof(BaseDownInfo));
}
//
// 获取下载所消耗的时间(毫秒),可用来计算下载速度和推算剩余时间
//
DWORD DownLoadMTR::GetDownloadElapsedTime()
{
return (GetTickCount()-m_dwDownloadStartTime);
}
//
// 停止下载。将所有下载线程关闭,将下载对象删除,文件关闭
//
void DownLoadMTR::StopDownload()
{
if (HANDLE_IS_VALID(m_hEvtEndModule))
{
::SetEvent(m_hEvtEndModule);
}
// 设置多线程下载使用的对象的参数
if (m_pDownloadPub_MTR)
{
for (int nIndex = 0; nIndex < m_nThreadCount; nIndex++)
{
m_pDownloadPub_MTR[nIndex].StopDownload();
}
}
if (m_pDownloadPub_Info)
{
m_pDownloadPub_Info->StopDownload();
}
if (HANDLE_IS_VALID(m_hThread))
{
WaitForThreadEnd(m_hThread,100*1000);
CLOSE_HANDLE(m_hThread)
}
DeleteDownloadObjectAndDataMTR();
DeleteDownloadObjectInfo();
CLOSE_HANDLE(m_hEvtEndModule);
}
void DownLoadMTR::StandardSaveFileName()
{
ASSERT(m_strSavePath.GetLength() > 0);
ASSERT(m_strSavePath.GetAt(m_strSavePath.GetLength() - 1) == '\\');
/*
StandardizationPathBuffer ( m_strSavePath.GetBuffer(MAX_PATH), MAX_PATH );
m_strSavePath.ReleaseBuffer ();
MakeSureDirectory ( m_strSavePath );
*/
char szOnlyFileName_NoExt_User[MAX_PATH] = {0};
char szExtensionName_User[MAX_PATH] = {0};
// 如果用户指定了新的保存文件名,就用新的。
if (m_strSaveOnlyFileName.GetLength() > 0)
{
CString strFileNameByURL = GetLocalFileNameByURL (m_strDownloadURL);
if (strFileNameByURL.CompareNoCase(m_strSaveOnlyFileName) != 0)
{
PartFileAndExtensionName(m_strSaveOnlyFileName, szOnlyFileName_NoExt_User, MAX_PATH, szExtensionName_User, MAX_PATH);
}
}
CString strExtensionName_Remote;
CString strFileName_Remote = m_pDownloadPub_Info->GetDownloadObjectFileName(&strExtensionName_Remote);
if (strlen(szOnlyFileName_NoExt_User) > 0)
{
if (strlen(szExtensionName_User) < 1)
{
//#define STRNCPY_CS(sz,str) strncpy((char*)(sz),(str).GetBuffer((str).GetLength()),sizeof(sz))
STRNCPY_CS(szExtensionName_User, strExtensionName_Remote);
strExtensionName_Remote.ReleaseBuffer();
}
m_strSavePathFileName.Format ("%s%s.%s", StandardizationFileForPathName(m_strSavePath,FALSE),
StandardizationFileForPathName(szOnlyFileName_NoExt_User,TRUE), StandardizationFileForPathName(szExtensionName_User,TRUE) );
}
else
{
m_strSavePathFileName.Format ("%s%s", StandardizationFileForPathName(m_strSavePath,FALSE), StandardizationFileForPathName(strFileName_Remote,TRUE));
}
}
//
// 根据 URL 来获取本地保存的文件名
//
CString DownLoadMTR::GetLocalFileNameByURL ( LPCTSTR lpszDownloadURL )
{
if (!lpszDownloadURL || strlen(lpszDownloadURL) < 1)
return "";
char szOnlyPath[MAX_PATH] = {0};
char szOnlyFileName[MAX_PATH] = {0};
if (!PartFileAndPathByFullPath(lpszDownloadURL, szOnlyFileName, MAX_PATH, szOnlyPath, MAX_PATH))
return "";
return szOnlyFileName;
}
//
// 获取文件大小
//
int DownLoadMTR::GetFileTotaleSize()
{
if (!m_pDownloadPub_Info) return -1;
return m_pDownloadPub_Info->GetFileTotalSize ();
}
//
// 获取已下载的字节数,包括以前下载的和本次下载的
//
int DownLoadMTR::GetTotalDownloadedSize()
{
if (!m_pDownloadPub_Info) return -1;
int nTotalUndownloadBytes = 0;
for (int nIndex = 0; nIndex < m_nThreadCount; nIndex++)
{
nTotalUndownloadBytes += m_pDownloadPub_MTR[nIndex].GetUndownloadBytes();
}
int nFileSize = m_pDownloadPub_Info->GetFileTotalSize();
if (nFileSize < 1) return -1;
// 文件大小减去未完成的,就是已下载的
return (nFileSize - nTotalUndownloadBytes);
}
int DownLoadMTR::GetTotalDownloadedSize_ThisTimes()
{
m_csDownloadedData.Lock();
int nTotalDownloadedSize_ThisTimes = m_nTotalDownloadedSize_ThisTimes;
m_csDownloadedData.Unlock();
return nTotalDownloadedSize_ThisTimes;
}
| [
"[email protected]@f92b348d-55a1-4afa-8193-148a6675784b"
]
| [
[
[
1,
941
]
]
]
|
448624836a6b9f609cb1bb6acade7c1cc240089b | 974a20e0f85d6ac74c6d7e16be463565c637d135 | /trunk/applications/newtonDemos/sdkDemos/PhysicsUtils.cpp | 91b7693d257144f600622b21f70e8b1c7aa1241d | []
| no_license | Naddiseo/Newton-Dynamics-fork | cb0b8429943b9faca9a83126280aa4f2e6944f7f | 91ac59c9687258c3e653f592c32a57b61dc62fb6 | refs/heads/master | 2021-01-15T13:45:04.651163 | 2011-11-12T04:02:33 | 2011-11-12T04:02:33 | 2,759,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,696 | cpp | /* Copyright (c) <2009> <Newton Game Dynamics>
*
* 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.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely
*/
#include <toolbox_stdafx.h>
#include "DemoMesh.h"
#include "DemoEntity.h"
#include "PhysicsUtils.h"
#include "DemoEntityManager.h"
#include "toolBox/OpenGlUtil.h"
#include "toolBox/DebugDisplay.h"
static int showContacts;
#ifdef USE_TEST_SERIALIZATION
//static char* MAGIC_NUMBER = "serialize data";
static void SerializeFile (void* serializeHandle, const void* buffer, int size)
{
fwrite (buffer, size, 1, (FILE*) serializeHandle);
}
static void DeSerializeFile (void* serializeHandle, void* buffer, int size)
{
fread (buffer, size, 1, (FILE*) serializeHandle);
}
#endif
dVector ForceBetweenBody (NewtonBody* const body0, NewtonBody* const body1)
{
dVector reactionforce (0.0f, 0.0f, 0.0f, 0.0f);
for (NewtonJoint* joint = NewtonBodyGetFirstContactJoint(body0); joint; joint = NewtonBodyGetNextContactJoint(body0, joint)) {
if ((NewtonJointGetBody0(joint) == body0) || (NewtonJointGetBody0(joint) == body1)) {
for (void* contact = NewtonContactJointGetFirstContact (joint); contact; contact = NewtonContactJointGetNextContact (joint, contact)) {
dVector point;
dVector normal;
dVector contactForce;
NewtonMaterial* const material = NewtonContactGetMaterial (contact);
NewtonMaterialGetContactPositionAndNormal (material, body0, &point.m_x, &normal.m_x);
NewtonMaterialGetContactForce(material, body0, &contactForce[0]);
//forceAcc += normal.Scale (forceMag);
reactionforce += contactForce;
}
break;
}
}
return reactionforce;
}
static dFloat RayCastPlacement (const NewtonBody* body, const dFloat* normal, int collisionID, void* userData, dFloat intersetParam)
{
dFloat* paramPtr;
paramPtr = (dFloat*)userData;
if (intersetParam < paramPtr[0]) {
paramPtr[0] = intersetParam;
}
return paramPtr[0];
}
dFloat FindFloor (const NewtonWorld* world, dFloat x, dFloat z)
{
dFloat parameter;
//parameter = 1.2f;
//float q0[] = {8.07129, -1.66341 - 1.5, 0};
//float q1[] = {8.04629, -3.1684 - 1.5, 0};
//NewtonWorldRayCast(world, q0, q1, RayCastPlacement, ¶meter, NULL);
// shot a vertical ray from a high altitude and collect the intersection parameter.
dVector p0 (x, 1000.0f, z);
dVector p1 (x, -1000.0f, z);
parameter = 1.2f;
NewtonWorldRayCast (world, &p0[0], &p1[0], RayCastPlacement, ¶meter, NULL);
//_ASSERTE (parameter < 1.0f);
// the intersection is the interpolated value
return 1000.0f - 2000.0f * parameter;
//return 0.0f;
}
#if 0
#include "SceneManager.h"
#include "toolBox/MousePick.h"
#include "toolBox/OpenGlUtil.h"
#include "toolBox/RenderPrimitive.h"
#include "NewtonCustomJoint.h"
#include "OGLMesh.h"
dFloat rollAngle = 0.0f;
dFloat yawAngle = 0.0f;
dVector cameraDir (1.0f, 0.0f, 0.0f, 0.0f);
dVector cameraEyepoint (-40.0f, 10.0f, 0.0f, 0.0f);
static int showIslans;
static unsigned ConvexCastCallback (const NewtonBody* body, const NewtonCollision* collision, void* userData)
{
NewtonBody* me = (NewtonBody*) userData;
return (me == body) ? 0 : 1;
}
void ConvexCastPlacement (NewtonBody* body)
{
dFloat param;
dMatrix matrix;
NewtonWorld* world;
NewtonCollision* collision;
NewtonWorldConvexCastReturnInfo info[16];
NewtonBodyGetMatrix (body, &matrix[0][0]);
matrix.m_posit.m_y += 40.0f;
dVector p (matrix.m_posit);
p.m_y -= 80.0f;
world = NewtonBodyGetWorld(body);
collision = NewtonBodyGetCollision(body);
NewtonWorldConvexCast (world, &matrix[0][0], &p[0], collision, ¶m, body, ConvexCastCallback, info, 16, 0);
_ASSERTE (param < 1.0f);
matrix.m_posit.m_y += (p.m_y - matrix.m_posit.m_y) * param;
NewtonBodySetMatrix(body, &matrix[0][0]);
}
void SetShowContacts (SceneManager& me, int mode)
{
showContacts = mode;
}
void AutoSleep (SceneManager& me, int mode)
{
mode = mode ? 0 : 1;
for (const NewtonBody* body = NewtonWorldGetFirstBody (me.m_world); body; body = NewtonWorldGetNextBody (me.m_world, body)) {
NewtonBodySetAutoSleep (body, mode);
}
}
void ShowJointInfo(const NewtonCustomJoint* joint)
{
NewtonJointRecord info;
if (showContacts) {
joint->GetInfo (&info);
dMatrix bodyMatrix0;
NewtonBodyGetMatrix (info.m_attachBody_0, &bodyMatrix0[0][0]);
dMatrix matrix0 (*((dMatrix*) &info.m_attachmenMatrix_0[0]));
matrix0 = matrix0 * bodyMatrix0;
DebugDrawLine (matrix0.m_posit, matrix0.m_posit + matrix0.m_front, dVector (1, 0, 0));
DebugDrawLine (matrix0.m_posit, matrix0.m_posit + matrix0.m_up, dVector (0, 1, 0));
DebugDrawLine (matrix0.m_posit, matrix0.m_posit + matrix0.m_right, dVector (0, 0, 1));
dMatrix bodyMatrix1;
NewtonBodyGetMatrix (info.m_attachBody_1, &bodyMatrix1[0][0]);
dMatrix matrix1 (*((dMatrix*) &info.m_attachmenMatrix_1[0]));
matrix1 = matrix1 * bodyMatrix1;
DebugDrawLine (matrix1.m_posit, matrix1.m_posit + matrix1.m_front, dVector (1, 0, 0));
DebugDrawLine (matrix1.m_posit, matrix1.m_posit + matrix1.m_up, dVector (0, 1, 0));
DebugDrawLine (matrix1.m_posit, matrix1.m_posit + matrix1.m_right, dVector (0, 0, 1));
}
}
static void ShowMeshCollidingFaces (
const NewtonBody* bodyWithTreeCollision,
const NewtonBody* body,
int faceID,
int vertexCount,
const dFloat* vertex,
int vertexstrideInBytes)
{
// we are copieng data to and array of memory, anothe call back may be doing the same thong
// her fore we nee to avopid race coditions
NewtonWorldCriticalSectionLock (NewtonBodyGetWorld (bodyWithTreeCollision));
dVector face[64];
int stride = vertexstrideInBytes / sizeof (dFloat);
for (int j = 0; j < vertexCount; j ++) {
face [j] = dVector (vertex[j * stride + 0], vertex[j * stride + 1] , vertex[j * stride + 2]);
}
DebugDrawPolygon (vertexCount, face);
// unlock the critical section
NewtonWorldCriticalSectionUnlock (NewtonBodyGetWorld (bodyWithTreeCollision));
}
void SetShowMeshCollision (SceneManager& me, int mode)
{
NewtonTreeCollisionCallback showFaceCallback;
showFaceCallback = NULL;
if (mode) {
showFaceCallback = ShowMeshCollidingFaces;
}
// iterate the world
for (const NewtonBody* body = NewtonWorldGetFirstBody (me.m_world); body; body = NewtonWorldGetNextBody (me.m_world, body)) {
NewtonCollision* collision;
NewtonCollisionInfoRecord info;
collision = NewtonBodyGetCollision (body);
NewtonCollisionGetInfo (collision, &info);
switch (info.m_collisionType)
{
case SERIALIZE_ID_TREE:
case SERIALIZE_ID_SCENE:
case SERIALIZE_ID_USERMESH:
case SERIALIZE_ID_HEIGHTFIELD:
{
NewtonStaticCollisionSetDebugCallback (collision, showFaceCallback);
break;
}
default:
break;
}
}
}
void SetShowIslands (SceneManager& me, int mode)
{
showIslans = mode;
}
//static void CalculateAABB (const NewtonBody* body, dVector& minP, dVector& maxP)
void CalculateAABB (const NewtonCollision* collision, const dMatrix& matrix, dVector& minP, dVector& maxP)
{
// NewtonCollision *collision;
// show an exact AABB
// collision = NewtonBodyGetCollision (body) ;
// dMatrix matrix;
// NewtonBodyGetMatrix (body, &matrix[0][0]);
for (int i = 0; i < 3; i ++) {
dVector support;
dVector dir (0.0f, 0.0f, 0.0f, 0.0f);
dir[i] = 1.0f;
dVector localDir (matrix.UnrotateVector (dir));
NewtonCollisionSupportVertex (collision, &localDir[0], &support[0]);
support = matrix.TransformVector (support);
maxP[i] = support[i];
localDir = localDir.Scale (-1.0f);
NewtonCollisionSupportVertex (collision, &localDir[0], &support[0]);
support = matrix.TransformVector (support);
minP[i] = support[i];
}
}
int PhysicsIslandUpdate (const NewtonWorld* world, const void* islandHandle, int bodyCount)
{
if (showIslans) {
dVector minAABB ( 1.0e10f, 1.0e10f, 1.0e10f, 0.0f);
dVector maxAABB (-1.0e10f, -1.0e10f, -1.0e10f, 0.0f);
for (int i = 0; i < bodyCount; i ++) {
dVector p0;
dVector p1;
#if 0
// show the engine loose aabb
NewtonIslandGetBodyAABB (islandHandle, i, &p0[0], &p1[0]);
#else
// calculate the shape aabb
dMatrix matrix;
NewtonBody* body;
NewtonCollision *collision;
body = NewtonIslandGetBody (islandHandle, i);
collision = NewtonBodyGetCollision (body);
NewtonBodyGetMatrix (body, &matrix[0][0]);
CalculateAABB (collision, matrix, p0, p1);
#endif
for (int j = 0; j < 3; j ++ ) {
minAABB[j] = p0[j] < minAABB[j] ? p0[j] : minAABB[j];
maxAABB[j] = p1[j] > maxAABB[j] ? p1[j] : maxAABB[j];
}
}
DebugDrawAABB (minAABB, maxAABB);
}
// g_activeBodies += bodyCount;
return 1;
}
NewtonBody* CreateGenericSolid (NewtonWorld* world, SceneManager* scene, const char* meshName, dFloat mass, const dMatrix& matrix, const dVector& size, PrimitiveType type, int materialID)
{
_ASSERTE (0);
return NULL;
/*
// create some boxes too
NewtonCollision* collision = CreateConvexCollision (world, GetIdentityMatrix(), size, type, 0);
OGLMesh* mesh = new OGLMesh (meshName, collision, "wood_0.tga", "wood_0.tga", "wood_1.tga");
NewtonBody* body = CreateSimpleSolid (world, scene, mesh, mass, matrix, collision, materialID);
mesh->Release();
NewtonReleaseCollision(world, collision);
return body;
*/
}
void InitEyePoint (const dVector& dir, const dVector& origin)
{
cameraDir = dir;
cameraEyepoint = origin;
rollAngle = dAsin (dir.m_y);
yawAngle = dAtan2 (-dir.m_z, dir.m_x);
dMatrix cameraDirMat (dRollMatrix(rollAngle) * dYawMatrix(yawAngle));
}
// Keyboard handler.
void Keyboard(SceneManager& me)
{
NewtonWorld* world;
world = me.m_world;
// read the mouse position and set the camera direction
dMOUSE_POINT mouse1;
dInt32 mouseLeftKey;
static dMOUSE_POINT mouse0;
GetCursorPos(mouse1);
// this section control the camera object picking
mouseLeftKey = dGetKeyState (KeyCode_L_BUTTON);
if (!MousePick (world, mouse1, mouseLeftKey, 0.125f, 1.0f)) {
// we are not in mouse pick mode, then we are in camera tracking mode
if (mouseLeftKey) {
// when click left mouse button the first time, we reset the camera
// convert the mouse x position to delta yaw angle
if (mouse1.x > (mouse0.x + 1)) {
yawAngle += 1.0f * 3.141592f / 180.0f;
if (yawAngle > (360.0f * 3.141592f / 180.0f)) {
yawAngle -= (360.0f * 3.141592f / 180.0f);
}
} else if (mouse1.x < (mouse0.x - 1)) {
yawAngle -= 1.0f * 3.141592f / 180.0f;
if (yawAngle < 0.0f) {
yawAngle += (360.0f * 3.141592f / 180.0f);
}
}
if (mouse1.y > (mouse0.y + 1)) {
rollAngle += 1.0f * 3.141592f / 180.0f;
if (rollAngle > (80.0f * 3.141592f / 180.0f)) {
rollAngle = 80.0f * 3.141592f / 180.0f;
}
} else if (mouse1.y < (mouse0.y - 1)) {
rollAngle -= 1.0f * 3.141592f / 180.0f;
if (rollAngle < -(80.0f * 3.141592f / 180.0f)) {
rollAngle = -80.0f * 3.141592f / 180.0f;
}
}
dMatrix cameraDirMat (dRollMatrix(rollAngle) * dYawMatrix(yawAngle));
cameraDir = cameraDirMat.m_front;
}
}
// save mouse position and left mouse key state for next frame
mouse0 = mouse1;
// camera control
if (dGetKeyState ('W')) {
cameraEyepoint += cameraDir.Scale (CAMERA_SPEED / 60.0f);
} else if (dGetKeyState ('S')) {
cameraEyepoint -= cameraDir.Scale (CAMERA_SPEED / 60.0f);
}
if (dGetKeyState ('D')) {
dVector up (0.0f, 1.0f, 0.0f);
dVector right (cameraDir * up);
cameraEyepoint += right.Scale (CAMERA_SPEED / 60.0f);
} else if (dGetKeyState ('A')) {
dVector up (0.0f, 1.0f, 0.0f);
dVector right (cameraDir * up);
cameraEyepoint -= right.Scale (CAMERA_SPEED / 60.0f);
}
dVector target (cameraEyepoint + cameraDir);
SetCamera (cameraEyepoint, target);
}
int OnAABBOverlap (const NewtonMaterial* material, const NewtonBody* body0, const NewtonBody* body1, int threadIndex)
{
_ASSERTE (body0);
_ASSERTE (body1);
_ASSERTE (NewtonBodyGetUserData(body0));
_ASSERTE (NewtonBodyGetUserData(body1));
return 1;
}
// this callback is called for every contact between the two bodies
//int GenericContactProcess (const NewtonMaterial* material, const NewtonBody* body0, const NewtonBody* body1, dFloat timestep, int threadIndex)
/*
void GenericContactProcess (const NewtonJoint* contactJoint, dFloat timestep, int threadIndex)
{
int isHightField;
NewtonBody* body;
NewtonCollision* collision;
NewtonCollisionInfoRecord info;
isHightField = 1;
body = NewtonJointGetBody0 (contactJoint);
collision = NewtonBodyGetCollision(body);
NewtonCollisionGetInfo(collision, &info);
if (info.m_collisionType != SERIALIZE_ID_HEIGHTFIELD) {
body = NewtonJointGetBody1 (contactJoint);
collision = NewtonBodyGetCollision(body);
NewtonCollisionGetInfo(collision, &info);
isHightField = (info.m_collisionType == SERIALIZE_ID_HEIGHTFIELD);
}
#define HOLE_INTERRAIN 10
if (isHightField) {
void* nextContact;
for (void* contact = NewtonContactJointGetFirstContact (contactJoint); contact; contact = nextContact) {
int faceID;
NewtonMaterial* material;
nextContact = NewtonContactJointGetNextContact (contactJoint, contact);
material = NewtonContactGetMaterial (contact);
faceID = NewtonMaterialGetContactFaceAttribute (material);
if (faceID == HOLE_INTERRAIN) {
NewtonContactJointRemoveContact (contactJoint, contact);
}
}
}
}
*/
void GetForceOnStaticBody (NewtonBody* body, NewtonBody* staticBody)
{
for (NewtonJoint* joint = NewtonBodyGetFirstContactJoint (body); joint; joint = NewtonBodyGetNextContactJoint (body, joint)) {
NewtonBody* body0;
NewtonBody* body1;
body0 = NewtonJointGetBody0(joint);
body1 = NewtonJointGetBody1(joint);
if ((body0 == staticBody) || (body1 == staticBody)) {
for (void* contact = NewtonContactJointGetFirstContact (joint); contact; contact = NewtonContactJointGetNextContact (joint, contact)) {
float forceMag;
dVector point;
dVector normal;
NewtonMaterial* material;
material = NewtonContactGetMaterial (contact);
NewtonMaterialGetContactForce (material, &forceMag);
NewtonMaterialGetContactPositionAndNormal (material, &point.m_x, &normal.m_x);
dVector force (normal.Scale (-forceMag));
// do wherever you want withteh force
}
}
}
}
static void ExtrudeFaces (void* userData, int vertexCount, const dFloat* faceVertec, int id)
{
float OFFSET = 0.1f;
float face[32][10];
NewtonMesh* mesh = (NewtonMesh*) userData;
// calculate the face normal
dVector normal (0, 0, 0);
dVector p0 (faceVertec[0 * 3 + 0], faceVertec[0 * 3 + 1], faceVertec[0 * 3 + 2]);
dVector p1 (faceVertec[1 * 3 + 0], faceVertec[1 * 3 + 1], faceVertec[1 * 3 + 2]);
dVector e0 (p1 - p0);
for (int i = 2; i < vertexCount; i ++) {
dVector p2 (faceVertec[i * 3 + 0], faceVertec[i * 3 + 1], faceVertec[i * 3 + 2]);
dVector e1 (p2 - p0);
normal += e0 * e1;
e0 = e1;
}
normal = normal.Scale (1.0f / dSqrt (normal % normal));
dVector displacemnet (normal.Scale (OFFSET));
// add the face displace by some offset
for (int i = 0; i < vertexCount; i ++) {
dVector p1 (faceVertec[i * 3 + 0], faceVertec[i * 3 + 1], faceVertec[i * 3 + 2]);
p1 += displacemnet;
face[i][0] = p1.m_x;
face[i][1] = p1.m_y;
face[i][2] = p1.m_z;
face[i][3] = normal.m_x;
face[i][4] = normal.m_y;
face[i][5] = normal.m_z;
face[i][6] = 0.0f;
face[i][7] = 0.0f;
face[i][8] = 0.0f;
face[i][9] = 0.0f;
}
// add the face
NewtonMeshAddFace (mesh, vertexCount, &face[0][0], 10 * sizeof (float), id);
// now add on face walk the perimeter and add a rivet face
dVector q0 (faceVertec[(vertexCount - 1) * 3 + 0], faceVertec[(vertexCount - 1) * 3 + 1], faceVertec[(vertexCount - 1) * 3 + 2]);
q0 += displacemnet;
for (int i = 0; i < vertexCount; i ++) {
dVector q1 (faceVertec[i * 3 + 0], faceVertec[i * 3 + 1], faceVertec[i * 3 + 2]);
q1 += displacemnet;
// calculate the river normal
dVector edge (q1 - q0);
dVector n (edge * normal);
n = n.Scale (1.0f / sqrtf (n % n));
// build a quad to serve a the face between the two parellel faces
face[0][0] = q0.m_x;
face[0][1] = q0.m_y;
face[0][2] = q0.m_z;
face[0][3] = n.m_x;
face[0][4] = n.m_y;
face[0][5] = n.m_z;
face[0][6] = 0.0f;
face[0][7] = 0.0f;
face[0][8] = 0.0f;
face[0][9] = 0.0f;
face[1][0] = q1.m_x;
face[1][1] = q1.m_y;
face[1][2] = q1.m_z;
face[1][3] = n.m_x;
face[1][4] = n.m_y;
face[1][5] = n.m_z;
face[1][6] = 0.0f;
face[1][7] = 0.0f;
face[1][8] = 0.0f;
face[1][9] = 0.0f;
face[2][0] = q1.m_x - displacemnet.m_x;
face[2][1] = q1.m_y - displacemnet.m_y;
face[2][2] = q1.m_z - displacemnet.m_z;
face[2][3] = n.m_x;
face[2][4] = n.m_y;
face[2][5] = n.m_z;
face[2][6] = 0.0f;
face[2][7] = 0.0f;
face[2][8] = 0.0f;
face[2][9] = 0.0f;
face[3][0] = q0.m_x - displacemnet.m_x;
face[3][1] = q0.m_y - displacemnet.m_y;
face[3][2] = q0.m_z - displacemnet.m_z;
face[3][3] = n.m_x;
face[3][4] = n.m_y;
face[3][5] = n.m_z;
face[3][6] = 0.0f;
face[3][7] = 0.0f;
face[3][8] = 0.0f;
face[3][9] = 0.0f;
// save the first point for the next rivet
q0 = q1;
// add this face to the mesh
NewtonMeshAddFace (mesh, 4, &face[0][0], 10 * sizeof (float), id);
}
}
NewtonMesh* CreateCollisionTreeDoubleFaces (NewtonWorld* world, NewtonCollision* optimizedDoubelFacesTree)
{
NewtonMesh* mesh = NewtonMeshCreate(world);
dMatrix matrix (GetIdentityMatrix());
NewtonMeshBeginFace(mesh);
NewtonCollisionForEachPolygonDo (optimizedDoubelFacesTree, &matrix[0][0], ExtrudeFaces, mesh);
NewtonMeshEndFace(mesh);
return mesh;
}
/*
// return the collision joint, if the body collide
NewtonJoint* CheckIfBodiesCollide (NewtonBody* body0, NewtonBody* body1)
{
for (NewtonJoint* joint = NewtonBodyGetFirstContactJoint (body0); joint; joint = NewtonBodyGetNextContactJoint (body0, joint)) {
if ((NewtonJointGetBody0(joint) == body1) || (NewtonJointGetBody1(joint) == body1)) {
return joint;
}
}
return NULL;
}
//to get teh collision points
void HandlecollisionPoints (NewtonJoint* contactjoint)
{
NewtonBody* body0 = NewtonJointGetBody0(contactjoint);
NewtonBody* body1 = NewtonJointGetBody1(contactjoint);
for (void* contact = NewtonContactJointGetFirstContact (contactjoint); contact; contact = NewtonContactJointGetNextContact (contactjoint, contact)) {
float forceMag;
dVector point;
dVector normal;
NewtonMaterial* material = NewtonContactGetMaterial (contact);
// do whatever you want here
//NewtonMaterialGetContactForce (material, &forceMag);
// NewtonMaterialGetContactPositionAndNormal (material, &point.m_x, &normal.m_x);
// do whatever you want with the force
}
}
void GetContactOnBody (NewtonBody* body)
{
for (NewtonJoint* joint = NewtonBodyGetFirstContactJoint (body); joint; joint = NewtonBodyGetNextContactJoint (body, joint)) {
for (void* contact = NewtonContactJointGetFirstContact (joint); contact; contact = NewtonContactJointGetNextContact (joint, contact)) {
float forceMag;
dVector point;
dVector normal;
NewtonBody* body0 = NewtonJointGetBody0(joint);
NewtonBody* body1 = NewtonJointGetBody1(joint);
NewtonMaterial* material = NewtonContactGetMaterial (contact);
//NewtonMaterialGetContactForce (material, &forceMag);
NewtonMaterialGetContactPositionAndNormal (material, &point.m_x, &normal.m_x);
// do whatever you want with the force
}
}
}
*/
#endif
dFloat RandomVariable(dFloat amp)
{
unsigned val;
val = dRand() + dRand();
return amp * (dFloat (val) / dFloat(dRAND_MAX) - 1.0f) * 0.5f;
}
// rigid body destructor
void PhysicsBodyDestructor (const NewtonBody* body)
{
// RenderPrimitive* primitive;
// get the graphic object form the rigid body
// primitive = (RenderPrimitive*) NewtonBodyGetUserData (body);
// destroy the graphic object
// delete primitive;
}
// add force and torque to rigid body
void PhysicsApplyGravityForce (const NewtonBody* body, dFloat timestep, int threadIndex)
{
dFloat Ixx;
dFloat Iyy;
dFloat Izz;
dFloat mass;
NewtonBodyGetMassMatrix (body, &mass, &Ixx, &Iyy, &Izz);
dVector force (0.0f, mass * DEMO_GRAVITY, 0.0f);
NewtonBodySetForce (body, &force.m_x);
}
void GenericContactProcess (const NewtonJoint* contactJoint, dFloat timestep, int threadIndex)
{
#if 0
dFloat speed0;
dFloat speed1;
SpecialEffectStruct* currectEffect;
// get the pointer to the special effect structure
currectEffect = (SpecialEffectStruct *)NewtonMaterialGetMaterialPairUserData (material);
// save the contact information
NewtonMaterialGetContactPositionAndNormal (material, &currectEffect->m_position.m_x, &currectEffect->m_normal.m_x);
NewtonMaterialGetContactTangentDirections (material, &currectEffect->m_tangentDir0.m_x, &currectEffect->m_tangentDir1.m_x);
// Get the maximum normal speed of this impact. this can be used for positioning collision sound
speed0 = NewtonMaterialGetContactNormalSpeed (material);
if (speed0 > currectEffect->m_contactMaxNormalSpeed) {
// save the position of the contact (for 3d sound of particles effects)
currectEffect->m_contactMaxNormalSpeed = speed0;
}
// get the maximum of the two sliding contact speed
speed0 = NewtonMaterialGetContactTangentSpeed (material, 0);
speed1 = NewtonMaterialGetContactTangentSpeed (material, 1);
if (speed1 > speed0) {
speed0 = speed1;
}
// Get the maximum tangent speed of this contact. this can be used for particles(sparks) of playing scratch sounds
if (speed0 > currectEffect->m_contactMaxTangentSpeed) {
// save the position of the contact (for 3d sound of particles effects)
currectEffect->m_contactMaxTangentSpeed = speed0;
}
#endif
// read the table direction
// dVector dir (tableDir);
// // table verical dir
// dVector updir (TableDir);
// NewtonBody* const body = NewtonJointGetBody0(contactJoint);
// for (void* contact = NewtonContactJointGetFirstContact (contactJoint); contact; contact = NewtonContactJointGetNextContact (contactJoint, contact)) {
// dFloat speed;
// dVector point;
// dVector normal;
// dVector dir0;
// dVector dir1;
// dVector force;
// NewtonMaterial* material;
//
// material = NewtonContactGetMaterial (contact);
// NewtonMaterialGetContactPositionAndNormal (material, body, &point.m_x, &normal.m_x);
//
// // if the normal is vertical is large the say 40 degrees
// if (fabsf (normal % upDir) > 0.7f) {
// // rotate the normal to be aligned with the table direction
// NewtonMaterialContactRotateTangentDirections (material, dir);
// }
// }
NewtonBody* const body = NewtonJointGetBody0(contactJoint);
for (void* contact = NewtonContactJointGetFirstContact (contactJoint); contact; contact = NewtonContactJointGetNextContact (contactJoint, contact)) {
dFloat speed;
dVector point;
dVector normal;
dVector dir0;
dVector dir1;
dVector force;
NewtonMaterial* material;
material = NewtonContactGetMaterial (contact);
NewtonMaterialGetContactForce (material, body, &force.m_x);
NewtonMaterialGetContactPositionAndNormal (material, body, &point.m_x, &normal.m_x);
NewtonMaterialGetContactTangentDirections (material, body, &dir0.m_x, &dir1.m_x);
speed = NewtonMaterialGetContactNormalSpeed(material);
//speed = NewtonMaterialGetContactNormalSpeed(material);
// play sound base of the contact speed.
//
}
}
NewtonCollision* CreateConvexCollision (NewtonWorld* world, const dMatrix& srcMatrix, const dVector& originalSize, PrimitiveType type, int materialID)
{
dMatrix matrix (srcMatrix);
matrix.m_front = matrix.m_front.Scale (1.0f / dSqrt (matrix.m_front % matrix.m_front));
matrix.m_right = matrix.m_front * matrix.m_up;
matrix.m_right = matrix.m_right.Scale (1.0f / dSqrt (matrix.m_right % matrix.m_right));
matrix.m_up = matrix.m_right * matrix.m_front;
dVector size (originalSize);
NewtonCollision* collision = NULL;
switch (type)
{
case _SPHERE_PRIMITIVE:
{
// create the collision
collision = NewtonCreateSphere (world, size.m_x * 0.5f, size.m_y * 0.5f, size.m_z * 0.5f, 0, NULL);
break;
}
case _BOX_PRIMITIVE:
{
// create the collision
collision = NewtonCreateBox (world, size.m_x, size.m_y, size.m_z, 0, NULL);
break;
}
case _CONE_PRIMITIVE:
{
dFloat r = size.m_x * 0.5f;
dFloat h = size.m_y;
// create the collision
collision = NewtonCreateCone (world, r, h, 0, NULL);
break;
}
case _CYLINDER_PRIMITIVE:
{
// create the collision
collision = NewtonCreateCylinder (world, size.m_x * 0.5f, size.m_y, 0, NULL);
break;
}
case _CAPSULE_PRIMITIVE:
{
// create the collision
collision = NewtonCreateCapsule (world, size.m_x * 0.5f, size.m_y, 0, NULL);
//NewtonCollision* collision1;
//collision1 = NewtonCreateCapsule (world, size.m_y, size.m_x, NULL);
//collision = NewtonCreateConvexHullModifier( world, collision1 );
//float my_matrix[16] = { 1,0,0,0,
// 0,1,0,0,
// 0,0,1,0,
// 0,0,0,1 };
//NewtonConvexHullModifierSetMatrix( collision, my_matrix );
//NewtonReleaseCollision (world, collision1);
break;
}
case _CHAMFER_CYLINDER_PRIMITIVE:
{
// create the collision
collision = NewtonCreateChamferCylinder (world, size.m_x * 0.5f, size.m_y, 0, NULL);
break;
}
case _RANDOM_CONVEX_HULL_PRIMITIVE:
{
// Create a clouds of random point around the origin
#define SAMPLE_COUNT 5000
dVector cloud [SAMPLE_COUNT];
// make sure that at least the top and bottom are present
cloud [0] = dVector ( size.m_x * 0.5f, -0.3f, 0.0f);
cloud [1] = dVector ( size.m_x * 0.5f, 0.3f, 0.3f);
cloud [2] = dVector ( size.m_x * 0.5f, 0.3f, -0.3f);
cloud [3] = dVector (-size.m_x * 0.5f, -0.3f, 0.0f);
cloud [4] = dVector (-size.m_x * 0.5f, 0.3f, 0.3f);
cloud [5] = dVector (-size.m_x * 0.5f, 0.3f, -0.3f);
int count = 5;
// populate the cloud with pseudo Gaussian random points
for (int i = 6; i < SAMPLE_COUNT; i ++) {
cloud [i].m_x = RandomVariable(size.m_x);
cloud [i].m_y = RandomVariable(size.m_y);
cloud [i].m_z = RandomVariable(size.m_z);
count ++;
}
collision = NewtonCreateConvexHull (world, count, &cloud[0].m_x, sizeof (dVector), 0.01f, 0, NULL);
break;
}
case _REGULAR_CONVEX_HULL_PRIMITIVE:
{
// Create a clouds of random point around the origin
#define STEPS_HULL 6
//#define STEPS_HULL 3
dVector cloud [STEPS_HULL * 4 + 256];
int count = 0;
dFloat radius = size.m_y;
dFloat height = size.m_x * 0.999f;
dFloat x = - height * 0.5f;
dMatrix rotation (dPitchMatrix(2.0f * 3.141592f / STEPS_HULL));
for (int i = 0; i < 4; i ++) {
dFloat pad;
pad = ((i == 1) || (i == 2)) * 0.25f * radius;
dVector p (x, 0.0f, radius + pad);
x += 0.3333f * height;
dMatrix acc (GetIdentityMatrix());
for (int j = 0; j < STEPS_HULL; j ++) {
cloud[count] = acc.RotateVector(p);
acc = acc * rotation;
count ++;
}
}
collision = NewtonCreateConvexHull (world, count, &cloud[0].m_x, sizeof (dVector), 0.02f, 0, NULL);
break;
}
default: _ASSERTE (0);
}
#ifdef USE_TEST_SERIALIZATION
FILE* file;
char fullPathName[2048];
// save the collision file
GetWorkingFileName ("collisiontest.bin", fullPathName);
file = fopen (fullPathName, "wb");
// SerializeFile (file, MAGIC_NUMBER, strlen (MAGIC_NUMBER) + 1);
NewtonCollisionSerialize (world, collision, SerializeFile, file);
fclose (file);
// load the collision file
NewtonReleaseCollision (world, collision);
file = fopen (fullPathName, "rb");
// DeSerializeFile (file, magicNumber, strlen (MAGIC_NUMBER) + 1);
collision = NewtonCreateCollisionFromSerialization (world, DeSerializeFile, file);
fclose (file);
NewtonCollisionInfoRecord collisionInfo;
NewtonCollisionGetInfo (collision, &collisionInfo);
#endif
return collision;
}
NewtonBody* CreateSimpleSolid (DemoEntityManager* const scene, DemoMesh* const mesh, dFloat mass, const dMatrix& matrix, NewtonCollision* const collision, int materialId)
{
_ASSERTE (collision);
_ASSERTE (mesh);
// add an new entity to the world
DemoEntity* const entity = new DemoEntity(NULL);
scene->Append (entity);
entity->SetMesh(mesh);
/*
// create a visual effect for fracture
primitive->CreateVisualEffect (world);
// save the collision volume, (this si all tweaked by trial and error heuristic)
#define CONTROL_VOLUME 0.1f
dFloat randomizeDnsdity = 1.0f + ((RandomVariable(0.4f) + RandomVariable(0.4f)) - 0.1f);
dFloat volume = 0.5f * NewtonConvexCollisionCalculateVolume (collision);
primitive->m_density = randomizeDnsdity * mass / volume;
// primitive->m_controlVolume = NewtonConvexCollisionCalculateVolume (collision) * (CONTROL_VOLUME * CONTROL_VOLUME * CONTROL_VOLUME);
*/
// calculate the moment of inertia and the relative center of mass of the solid
dVector origin;
dVector inertia;
NewtonConvexCollisionCalculateInertialMatrix (collision, &inertia[0], &origin[0]);
dFloat Ixx = mass * inertia[0];
dFloat Iyy = mass * inertia[1];
dFloat Izz = mass * inertia[2];
//create the rigid body
NewtonWorld* const world = scene->GetNewton();
NewtonBody* const rigidBody = NewtonCreateBody (world, collision, &matrix[0][0]);
// set the correct center of gravity for this body
NewtonBodySetCentreOfMass (rigidBody, &origin[0]);
// set the mass matrix
NewtonBodySetMassMatrix (rigidBody, mass, Ixx, Iyy, Izz);
// activate
// NewtonBodyCoriolisForcesMode (blockBoxBody, 1);
// save the pointer to the graphic object with the body.
NewtonBodySetUserData (rigidBody, entity);
// assign the wood id
NewtonBodySetMaterialGroupID (rigidBody, materialId);
// set continue collision mode
// NewtonBodySetContinuousCollisionMode (rigidBody, continueCollisionMode);
// set a destructor for this rigid body
NewtonBodySetDestructorCallback (rigidBody, PhysicsBodyDestructor);
// set the transform call back function
NewtonBodySetTransformCallback (rigidBody, DemoEntity::SetTransformCallback);
// set the force and torque call back function
NewtonBodySetForceAndTorqueCallback (rigidBody, PhysicsApplyGravityForce);
// set the matrix for both the rigid body and the graphic body
//NewtonBodySetMatrix (rigidBody, &matrix[0][0]);
//PhysicsSetTransform (rigidBody, &matrix[0][0], 0);
//dVector xxx (0, -9.8f * mass, 0.0f, 0.0f);
//NewtonBodySetForce (rigidBody, &xxx[0]);
// force the body to be active of inactive
// NewtonBodySetAutoSleep (rigidBody, sleepMode);
return rigidBody;
}
void AddPrimitiveArray (DemoEntityManager* const scene, dFloat mass, const dVector& origin, const dVector& size, int xCount, int zCount, dFloat spacing, PrimitiveType type, int materialID)
{
dMatrix matrix (GetIdentityMatrix());
// create the shape and visual mesh as a common data to be re used
NewtonWorld* const world = scene->GetNewton();
NewtonCollision* const collision = CreateConvexCollision (world, GetIdentityMatrix(), size, type, materialID);
// DemoMesh* const geometry = new DemoMesh("cylinder_1", collision, "wood_0.tga", "wood_0.tga", "wood_1.tga");
DemoMesh* const geometry = new DemoMesh("cylinder_1", collision, "smilli.tga", "smilli.tga", "smilli.tga");
for (int i = 0; i < xCount; i ++) {
dFloat x = origin.m_x + (i - xCount / 2) * spacing;
for (int j = 0; j < zCount; j ++) {
dFloat z = origin.m_z + (j - zCount / 2) * spacing;
matrix.m_posit.m_x = x;
matrix.m_posit.m_z = z;
matrix.m_posit.m_y = FindFloor (world, x, z) + 4.0f;
CreateSimpleSolid (scene, geometry, mass, matrix, collision, materialID);
}
}
// do not forget to release the assets
geometry->Release();
NewtonReleaseCollision(world, collision);
}
static void CreateLevelMeshBody (NewtonWorld* const world, DemoEntity* const ent, bool optimization)
{
// measure the time to build a collision tree
unsigned64 timer0 = dGetTimeInMicrosenconds();
// create the collision tree geometry
NewtonCollision* const collision = NewtonCreateTreeCollision(world, 0);
// set the application level callback
#ifdef USE_STATIC_MESHES_DEBUG_COLLISION
// NewtonStaticCollisionSetDebugCallback (collision, DebugCallback);
#endif
// prepare to create collision geometry
NewtonTreeCollisionBeginBuild(collision);
int faceCount = 0;
// iterate the entire geometry an build the collision
for (DemoEntity* model = ent->GetFirst(); model; model = model->GetNext()) {
dMatrix matrix (model->CalculateGlobalMatrix(ent));
DemoMesh* const mesh = model->GetMesh();
dFloat* const vertex = mesh->m_vertex;
for (DemoMesh::dListNode* nodes = mesh->GetFirst(); nodes; nodes = nodes->GetNext()) {
DemoSubMesh& segment = nodes->GetInfo();
for (int i = 0; i < segment.m_indexCount; i += 3) {
int index;
int matID;
dVector face[3];
index = segment.m_indexes[i + 0] * 3;
face[0] = dVector (vertex[index + 0], vertex[index + 1], vertex[index + 2]);
index = segment.m_indexes[i + 1] * 3;
face[1] = dVector (vertex[index + 0], vertex[index + 1], vertex[index + 2]);
index = segment.m_indexes[i + 2] * 3;
face[2] = dVector (vertex[index + 0], vertex[index + 1], vertex[index + 2]);
matrix.TransformTriplex (&face[0].m_x, sizeof (dVector), &face[0].m_x, sizeof (dVector), 3);
// stress test the collision builder
// matID = matID == 2 ? 1 : 2 ;
matID = 0;
faceCount ++;
NewtonTreeCollisionAddFace(collision, 3, &face[0].m_x, sizeof (dVector), matID);
}
}
}
NewtonTreeCollisionEndBuild(collision, optimization ? 1 : 0);
// measure the time to build a collision tree
timer0 = (dGetTimeInMicrosenconds() - timer0) / 1000;
// Get the root Matrix
dMatrix matrix (ent->CalculateGlobalMatrix(NULL));
// create the level rigid body
NewtonBody* const level = NewtonCreateBody(world, collision, &matrix[0][0]);
// set the global position of this body
//NewtonBodySetMatrix (level, &matrix[0][0]);
// save the pointer to the graphic object with the body.
NewtonBodySetUserData (level, ent);
// set a destructor for this rigid body
//NewtonBodySetDestructorCallback (m_level, Destructor);
dVector boxP0;
dVector boxP1;
// get the position of the aabb of this geometry
NewtonCollisionCalculateAABB (collision, &matrix[0][0], &boxP0.m_x, &boxP1.m_x);
// add some extra padding the world size
boxP0.m_x -= 50.0f;
boxP0.m_y -= 50.0f;
boxP0.m_z -= 50.0f;
boxP1.m_x += 50.0f;
boxP1.m_y += 500.0f;
boxP1.m_z += 50.0f;
// set the world size
NewtonSetWorldSize (world, &boxP0.m_x, &boxP1.m_x);
// release the collision tree (this way the application does not have to do book keeping of Newton objects
NewtonReleaseCollision (world, collision);
}
void CreateLevelMesh (DemoEntityManager* const scene, const char* name, bool optimized)
{
// load the scene from and alchemedia file format
char fileName[2048];
GetWorkingFileName (name, fileName);
scene->LoadScene (fileName);
NewtonWorld* const world = scene->GetNewton();
for (DemoEntityManager::dListNode* node = scene->GetFirst(); node; node = node->GetNext()) {
DemoEntity* const ent = node->GetInfo();
DemoMesh* const mesh = ent->GetMesh();
if (mesh) {
char name[2048];
mesh->GetName(name);
if (!strcmp (name, "levelGeometry_mesh")) {
CreateLevelMeshBody (world, ent, optimized);
break;
}
}
}
} | [
"[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692"
]
| [
[
[
1,
1213
]
]
]
|
59131cbff97a46663bea6c2b884a5cd82cfccd4f | 01fa6f43ad536f4c9656be0f2c7da69c6fc9dc1c | /bufferlist.h | 3ccffacdd2d62e2185b7531aaca60fb396efca2f | []
| no_license | akavel/wed-editor | 76a22b7ff1bb4b109cfe5f3cc630e18ebb91cd51 | 6a10c167e46bfcb65adb514a1278634dfcb384c1 | refs/heads/master | 2021-01-19T19:33:18.124144 | 2010-04-16T20:32:17 | 2010-04-16T20:32:17 | 10,511,499 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,446 | h | #if !defined(AFX_BUFFERLIST_H__F71BD6A0_DFE4_11D2_BEED_002078105E2C__INCLUDED_)
#define AFX_BUFFERLIST_H__F71BD6A0_DFE4_11D2_BEED_002078105E2C__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// BufferList.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// BufferList dialog
class BufferList : public CDialog
{
// Construction
public:
long m_cv;
BufferList(CWnd* pParent = NULL); // standard constructor
void Fill();
// Dialog Data
//{{AFX_DATA(BufferList)
enum { IDD = IDD_DIALOG1 };
CEdit m_edit1;
CListBox m_list;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(BufferList)
public:
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(BufferList)
afx_msg void OnShowWindow(BOOL bShow, UINT nStatus);
virtual void OnOK();
afx_msg void OnButton1();
afx_msg void OnButton2();
afx_msg void OnButton3();
virtual BOOL OnInitDialog();
afx_msg void OnDblclkList1();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BUFFERLIST_H__F71BD6A0_DFE4_11D2_BEED_002078105E2C__INCLUDED_)
| [
"none@none"
]
| [
[
[
1,
56
]
]
]
|
83899a899cb639476589640aaf3a98f265ad36d0 | 7ee1bcc17310b9f51c1a6be0ff324b6e297b6c8d | /AppData/Sources/VS 6.0 Win32 MFC 6.0 SDI/Source/$PROJECT$App.cpp | 5cae34cfb61dfcdec156c8956ecf468e4daf4470 | []
| no_license | SchweinDeBurg/afx-scratch | 895585e98910f79127338bdca5b19c5e36921453 | 3181b779b4bb36ef431e5ce39e297cece1ca9cca | refs/heads/master | 2021-01-19T04:50:48.770595 | 2011-06-18T05:14:22 | 2011-06-18T05:14:22 | 32,185,218 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,430 | cpp | // $PROJECT$ application.
// Copyright (c) $YEAR$ by $AUTHOR$,
// All rights reserved.
// $PROJECT$App.cpp - implementation of the C$PROJECT$App class
// initially generated by $GENERATOR$ on $DATE$ at $TIME$
// visit http://zarezky.spb.ru/projects/afx_scratch.html for more info
//////////////////////////////////////////////////////////////////////////////////////////////
// PCH includes
#include "stdafx.h"
//////////////////////////////////////////////////////////////////////////////////////////////
// resource includes
#include "Resource.h"
//////////////////////////////////////////////////////////////////////////////////////////////
// other includes
#include "$PROJECT$App.h"
#include "MainFrame.h"
//////////////////////////////////////////////////////////////////////////////////////////////
// debugging support
#if defined(_DEBUG)
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#define new DEBUG_NEW
#endif // _DEBUG
//////////////////////////////////////////////////////////////////////////////////////////////
// object model
IMPLEMENT_DYNAMIC(C$PROJECT$App, CWinApp)
//////////////////////////////////////////////////////////////////////////////////////////////
// message map
BEGIN_MESSAGE_MAP(C$PROJECT$App, CWinApp)
END_MESSAGE_MAP()
//////////////////////////////////////////////////////////////////////////////////////////////
// construction/destruction
C$PROJECT$App::C$PROJECT$App(void)
{
}
C$PROJECT$App::~C$PROJECT$App(void)
{
}
//////////////////////////////////////////////////////////////////////////////////////////////
// overridables
BOOL C$PROJECT$App::InitInstance(void)
{
CMainFrame* pMainFrame = new CMainFrame();
if (pMainFrame != NULL)
{
// try to create and show main window
if (pMainFrame->Create(NULL, AfxGetAppName()))
{
ASSERT(::IsWindow(pMainFrame->GetSafeHwnd()));
pMainFrame->SetIcon(LoadIcon(IDI_APP_ICON), TRUE);
pMainFrame->SetIcon(LoadSmIcon(MAKEINTRESOURCE(IDI_APP_ICON)), FALSE);
pMainFrame->ShowWindow(m_nCmdShow);
pMainFrame->UpdateWindow();
m_pMainWnd = pMainFrame;
// succeeded
return (TRUE);
}
}
// failed to create main window
return (FALSE);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// diagnostic services
#if defined(_DEBUG)
void C$PROJECT$App::AssertValid(void) const
{
// first perform inherited validity check...
CWinApp::AssertValid();
// ...and then verify our own state as well
}
void C$PROJECT$App::Dump(CDumpContext& dumpCtx) const
{
try
{
// first invoke inherited dumper...
CWinApp::Dump(dumpCtx);
// ...and then dump own unique members
}
catch (CFileException* pXcpt)
{
pXcpt->ReportError();
pXcpt->Delete();
}
}
#endif // _DEBUG
//////////////////////////////////////////////////////////////////////////////////////////////
// implementation helpers
HICON C$PROJECT$App::LoadSmIcon(LPCTSTR pszResName)
{
HINSTANCE hInstRes = AfxGetResourceHandle();
int cxSmIcon = ::GetSystemMetrics(SM_CXSMICON);
int cySmIcon = ::GetSystemMetrics(SM_CYSMICON);
HANDLE hSmIcon = ::LoadImage(hInstRes, pszResName, IMAGE_ICON, cxSmIcon, cySmIcon, 0);
return (static_cast<HICON>(hSmIcon));
}
// the one and only application object
static C$PROJECT$App g_app$PROJECT$;
// end of file
| [
"Elijah Zarezky@9edebcd1-9b41-0410-8d36-53a5787adf6b"
]
| [
[
[
1,
131
]
]
]
|
ebfc5cde34d27ad157a4c1b596dd1a34d214f4b8 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/wheel/NewWheelController/include/WheelClockListener.h | fbc741e46324b99d2e24d756c48e53b521657d30 | []
| 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 | 304 | h | #ifndef __Orz_WheelClockListener_h__
#define __Orz_WheelClockListener_h__
#include "WheelControllerConfig.h"
namespace Orz
{
class _OrzNewWheelControlleExport WheelClockListener
{
public:
virtual ~WheelClockListener(void){}
virtual void clockChanged(int second) = 0;
};
}
#endif | [
"[email protected]"
]
| [
[
[
1,
18
]
]
]
|
95b250219d17a2bd3df879e781374ffe305728c9 | a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561 | /SlonEngine/extensions/PythonBindings/physics/src/PyCollisionObject.cpp | d016f0cd8e4ae0b1d8eda20dc28334a9d30806a5 | []
| no_license | BackupTheBerlios/slon | e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6 | dc10b00c8499b5b3966492e3d2260fa658fee2f3 | refs/heads/master | 2016-08-05T09:45:23.467442 | 2011-10-28T16:19:31 | 2011-10-28T16:19:31 | 39,895,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | cpp | #include "stdafx.h"
#include "PyCollisionObject.h"
#include "Physics/CollisionObject.h"
using namespace boost::python;
using namespace slon::physics;
boost::shared_ptr<math::Matrix4r> CollisionObjectGetTransform(const CollisionObject* co)
{
return boost::shared_ptr<math::Matrix4r>( new math::Matrix4r(co->getTransform()) );
}
void exportCollisionObject()
{
scope coScope =
class_<CollisionObject, boost::intrusive_ptr<CollisionObject>, boost::noncopyable>("CollisionObject", no_init)
.add_property("name", make_function(&CollisionObject::getName, return_internal_reference<>()))
.add_property("type", &CollisionObject::getType)
.def("getTransform", CollisionObjectGetTransform, with_custodian_and_ward_postcall<1,0>())
.def("setTransform", &CollisionObject::setTransform);
enum_<CollisionObject::COLLISION_TYPE>("COLLISION_TYPE")
.value("GHOST", CollisionObject::CT_GHOST)
.value("RIGID_BODY", CollisionObject::CT_RIGID_BODY);
} | [
"devnull@localhost"
]
| [
[
[
1,
25
]
]
]
|
7ae6dfb11fd1f01ce3e51fdd96484669ccb0aae6 | 5ed707de9f3de6044543886ea91bde39879bfae6 | /ASBaseball/Shared/Source/ASBaseballBuildSchedule.cpp | 6254ee44bfcfd84b358071786d4d1fb17c7b668d | []
| no_license | grtvd/asifantasysports | 9e472632bedeec0f2d734aa798b7ff00148e7f19 | 76df32c77c76a76078152c77e582faa097f127a8 | refs/heads/master | 2020-03-19T02:25:23.901618 | 1999-12-31T16:00:00 | 2018-05-31T19:48:19 | 135,627,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,370 | cpp | /* ASBaseballBuildSchedule.cpp */
/******************************************************************************/
/******************************************************************************/
#include "CBldVCL.h"
#pragma hdrstop
#include "ASBaseballBuildSchedule.h"
namespace asbaseball
{
/******************************************************************************/
static StaticBuildScheduleGame gEightTeamStaticScheduleGameList[] =
{
{ 0, 1 },
{ 2, 3 },
{ 4, 5 },
{ 6, 7 },
{ 1, 0 },
{ 3, 2 },
{ 5, 4 },
{ 7, 6 },
{ 0, 4 },
{ 1, 5 },
{ 2, 6 },
{ 3, 7 },
{ 0, 5 },
{ 1, 6 },
{ 7, 2 },
{ 4, 3 },
{ 1, 0 },
{ 3, 2 },
{ 5, 4 },
{ 7, 6 },
{ 1, 0 },
{ 4, 2 },
{ 5, 3 },
{ 7, 6 },
{ 0, 6 },
{ 1, 7 },
{ 5, 2 },
{ 3, 4 },
{ 0, 7 },
{ 1, 2 },
{ 3, 6 },
{ 5, 4 },
{ 6, 7 },
{ 2, 4 },
{ 3, 0 },
{ 5, 1 },
{ 4, 1 },
{ 7, 3 },
{ 6, 0 },
{ 2, 5 },
{ 6, 3 },
{ 4, 5 },
{ 7, 1 },
{ 0, 2 },
{ 3, 5 },
{ 2, 7 },
{ 0, 1 },
{ 6, 4 },
{ 6, 7 },
{ 2, 3 },
{ 1, 4 },
{ 5, 0 },
{ 5, 7 },
{ 4, 6 },
{ 3, 2 },
{ 0, 1 },
{ 2, 0 },
{ 3, 1 },
{ 4, 6 },
{ 7, 5 },
{ 5, 6 },
{ 7, 4 },
{ 3, 0 },
{ 1, 2 },
{ 2, 1 },
{ 0, 3 },
{ 4, 6 },
{ 5, 7 },
{ 3, 0 },
{ 2, 1 },
{ 4, 7 },
{ 6, 5 },
{ 6, 4 },
{ 1, 3 },
{ 2, 0 },
{ 7, 5 },
{ 6, 2 },
{ 3, 1 },
{ 7, 0 },
{ 4, 5 },
{ 5, 6 },
{ 7, 4 },
{ 0, 2 },
{ 1, 3 },
{ 1, 2 },
{ 0, 3 },
{ 5, 7 },
{ 6, 4 },
{ 4, 7 },
{ 6, 5 },
{ 2, 0 },
{ 3, 1 },
{ 1, 3 },
{ 7, 4 },
{ 0, 2 },
{ 5, 6 },
{ 4, 0 },
{ 2, 3 },
{ 6, 1 },
{ 7, 5 },
{ 0, 3 },
{ 2, 1 },
{ 4, 7 },
{ 6, 5 },
};
static int gEightTeamStaticScheduleGameListCount =
sizeof(gEightTeamStaticScheduleGameList)/sizeof(*gEightTeamStaticScheduleGameList);
/******************************************************************************/
static StaticBuildScheduleGame gTenTeamStaticScheduleGameList[] =
{
//Game: 1
{ 2, 0 }, { 3, 1 }, { 8, 4 }, { 7, 5 }, { 9, 6 },
//Game: 2
{ 9, 0 }, { 8, 1 }, { 7, 2 }, { 4, 3 }, { 6, 5 },
//Game: 3
{ 0, 3 }, { 1, 4 }, { 2, 5 }, { 6, 8 }, { 7, 9 },
//Game: 4
{ 0, 8 }, { 5, 9 }, { 3, 6 }, { 1, 7 }, { 2, 4 },
//Game: 5
{ 6, 0 }, { 4, 1 }, { 9, 2 }, { 5, 3 }, { 8, 7 },
//Game: 6
{ 0, 3 }, { 1, 2 }, { 4, 9 }, { 5, 8 }, { 6, 7 },
//Game: 7
{ 4, 0 }, { 9, 1 }, { 8, 2 }, { 7, 3 }, { 6, 5 },
//Game: 8
{ 0, 5 }, { 1, 2 }, { 3, 4 }, { 6, 8 }, { 7, 9 },
//Game: 9
{ 7, 0 }, { 6, 1 }, { 4, 2 }, { 8, 3 }, { 9, 5 },
//Game: 10
{ 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 9 }, { 7, 8 },
//Game: 11
{ 2, 0 }, { 3, 1 }, { 7, 4 }, { 8, 5 }, { 9, 6 },
//Game: 12
{ 8, 0 }, { 9, 5 }, { 6, 3 }, { 7, 1 }, { 4, 2 },
//Game: 13
{ 0, 4 }, { 1, 9 }, { 2, 8 }, { 3, 7 }, { 5, 6 },
//Game: 14
{ 3, 0 }, { 4, 1 }, { 5, 2 }, { 8, 6 }, { 9, 7 },
//Game: 15
{ 0, 2 }, { 1, 3 }, { 4, 7 }, { 5, 8 }, { 6, 9 },
//Game: 16
{ 0, 1 }, { 2, 3 }, { 4, 5 }, { 6, 7 }, { 8, 9 },
//Game: 17
{ 0, 9 }, { 1, 8 }, { 2, 7 }, { 3, 4 }, { 5, 6 },
//Game: 18
{ 0, 1 }, { 2, 3 }, { 4, 6 }, { 5, 7 }, { 8, 9 },
//Game: 19
{ 3, 0 }, { 2, 1 }, { 9, 4 }, { 8, 5 }, { 7, 6 },
//Game: 20
{ 4, 0 }, { 5, 1 }, { 6, 2 }, { 9, 3 }, { 8, 7 },
//Game: 21
{ 5, 0 }, { 2, 1 }, { 4, 3 }, { 8, 6 }, { 9, 7 },
//Game: 22
{ 0, 2 }, { 1, 3 }, { 4, 8 }, { 5, 7 }, { 6, 9 },
//Game: 23
{ 1, 0 }, { 3, 2 }, { 5, 4 }, { 7, 6 }, { 9, 8 },
//Game: 24
{ 0, 7 }, { 1, 6 }, { 2, 4 }, { 3, 8 }, { 5, 9 },
//Game: 25
{ 1, 0 }, { 3, 2 }, { 6, 4 }, { 7, 5 }, { 9, 8 },
//Game: 26
{ 0, 6 }, { 1, 4 }, { 2, 9 }, { 3, 5 }, { 7, 8 },
/*
{ 0, 1 },
{ 2, 3 },
{ 4, 5 },
{ 6, 7 },
{ 8, 9 },
{ 1, 0 },
{ 3, 2 },
{ 5, 4 },
{ 7, 6 },
{ 9, 8 },
{ 0, 1 },
{ 2, 3 },
{ 4, 6 },
{ 5, 7 },
{ 8, 9 },
{ 1, 0 },
{ 3, 2 },
{ 6, 4 },
{ 7, 5 },
{ 9, 8 },
{ 0, 2 },
{ 1, 3 },
{ 4, 7 },
{ 5, 8 },
{ 6, 9 },
{ 2, 0 },
{ 3, 1 },
{ 7, 4 },
{ 8, 5 },
{ 9, 6 },
{ 0, 2 },
{ 1, 3 },
{ 4, 8 },
{ 5, 7 },
{ 6, 9 },
{ 2, 0 },
{ 3, 1 },
{ 8, 4 },
{ 7, 5 },
{ 9, 6 },
{ 0, 3 },
{ 1, 2 },
{ 4, 9 },
{ 5, 8 },
{ 6, 7 },
{ 3, 0 },
{ 2, 1 },
{ 9, 4 },
{ 8, 5 },
{ 7, 6 },
{ 0, 3 },
{ 1, 4 },
{ 2, 5 },
{ 6, 8 },
{ 7, 9 },
{ 3, 0 },
{ 4, 1 },
{ 5, 2 },
{ 8, 6 },
{ 9, 7 },
{ 0, 4 },
{ 1, 9 },
{ 2, 8 },
{ 3, 7 },
{ 5, 6 },
{ 4, 0 },
{ 9, 1 },
{ 8, 2 },
{ 7, 3 },
{ 6, 5 },
{ 0, 4 },
{ 1, 5 },
{ 2, 6 },
{ 3, 9 },
{ 7, 8 },
{ 4, 0 },
{ 5, 1 },
{ 6, 2 },
{ 9, 3 },
{ 8, 7 },
{ 0, 5 },
{ 1, 2 },
{ 3, 4 },
{ 6, 8 },
{ 7, 9 },
{ 5, 0 },
{ 2, 1 },
{ 4, 3 },
{ 8, 6 },
{ 9, 7 },
{ 0, 6 },
{ 1, 4 },
{ 2, 9 },
{ 3, 5 },
{ 7, 8 },
{ 6, 0 },
{ 4, 1 },
{ 9, 2 },
{ 5, 3 },
{ 8, 7 },
{ 0, 7 },
{ 1, 6 },
{ 2, 4 },
{ 3, 8 },
{ 5, 9 },
{ 7, 0 },
{ 6, 1 },
{ 4, 2 },
{ 8, 3 },
{ 9, 5 },
{ 0, 8 },
{ 5, 9 },
{ 3, 6 },
{ 1, 7 },
{ 2, 4 },
{ 8, 0 },
{ 9, 5 },
{ 6, 3 },
{ 7, 1 },
{ 4, 2 },
{ 0, 9 },
{ 1, 8 },
{ 2, 7 },
{ 3, 4 },
{ 5, 6 },
{ 9, 0 },
{ 8, 1 },
{ 7, 2 },
{ 4, 3 },
{ 6, 5 },
*/
};
static int gTenTeamStaticScheduleGameListCount =
sizeof(gTenTeamStaticScheduleGameList)/sizeof(*gTenTeamStaticScheduleGameList);
/******************************************************************************/
/******************************************************************************/
StaticBuildScheduleGame* ASBaseballBuildSchedule::getStaticScheduleGameList(
int numTeams,int& numGames)
{
StaticBuildScheduleGame* gameList;
if(numTeams == 8)
{
gameList = gEightTeamStaticScheduleGameList;
numGames = gEightTeamStaticScheduleGameListCount;
}
else if(numTeams == 10)
{
gameList = gTenTeamStaticScheduleGameList;
numGames = gTenTeamStaticScheduleGameListCount;
}
else
throw ASIException("ASBaseballBuildSchedule::getStaticScheduleGameList: "
"unsupported number of teams");
return(gameList);
}
/******************************************************************************/
}; //asbaseball
/******************************************************************************/
/******************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
351
]
]
]
|
48e66ad574b24f20bc1755a9d61d9f70a328534c | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhnetsdk/netsdk/AutoRegister.h | 2606ca41da1c75bcc1f313ac43a6450da516a332 | []
| 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 | GB18030 | C++ | false | false | 1,373 | h | // AutoRegister.h: interface for the CAutoRegister class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_AUTOREGISTER_H__55EF1893_48EB_442C_A58F_7F4BCCAD48D6__INCLUDED_)
#define AFX_AUTOREGISTER_H__55EF1893_48EB_442C_A58F_7F4BCCAD48D6__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "netsdk.h"
class CManager;
class CAutoRegister
{
public:
CAutoRegister(CManager *pManager);
virtual ~CAutoRegister();
public:
/* 初始化 */
int Init(void);
/* 清理 */
int Uninit(void);
/* 关闭一个设备的所有通道 */
int CloseChannelOfDevice(afk_device_s* device);
/* 主动注册重定向功能*/
// 使设备定向主动连接服务器
LONG ConnectRegServer(LONG lLoginID, char* RegServerIP, WORD RegServerPort, int TimeOut);
// 使设备主动注册接服务器
int ControlRegister(LONG lLoginID, LONG ConnectionID, int waittime);
// 使设备断开主动注册服务机器
int DisConnectRegServer(LONG lLoginID, LONG ConnectionID);
// 查询设备主动注册服务器的信息
int QueryRegServerInfo(LONG lLoginID, LPDEV_SERVER_AUTOREGISTER lpRegServerInfo, int waittime);
private:
CManager* m_pManager;
};
#endif // !defined(AFX_AUTOREGISTER_H__55EF1893_48EB_442C_A58F_7F4BCCAD48D6__INCLUDED_)
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
49
]
]
]
|
bcb584d0f00d963da5c5d9d2e1d4399171692e65 | 971b000b9e6c4bf91d28f3723923a678520f5bcf | /QTextPanel/qtextpanelimage.h | d0dff34390da41d977eae8bb14da56c3910825ee | []
| no_license | google-code-export/fop-miniscribus | 14ce53d21893ce1821386a94d42485ee0465121f | 966a9ca7097268c18e690aa0ea4b24b308475af9 | refs/heads/master | 2020-12-24T17:08:51.551987 | 2011-09-02T07:55:05 | 2011-09-02T07:55:05 | 32,133,292 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,961 | h | #ifndef QTEXTPANELIMAGE_H
#define QTEXTPANELIMAGE_H
#include <QPair>
#include <QtGui>
#include <QtCore>
#include <QPixmap>
#include <QMetaType>
#define _IMAGE_PICS_ITEM_ 100
#define _LINK_COLOR_ \
QColor("#dc0000")
class SPics
{
public:
enum { MAGICNUMBER = 0xFFAAFFAA, VERSION = 1 };
SPics();
SPics& operator=(const SPics& d);
bool operator!=(const SPics& d);
operator QVariant() const
{
return QVariant::fromValue(*this);
}
QPixmap erno_pix();
QString web();
QPixmap pix();
QString FileName();
void SavePixThread(QString dir = QString());
void set_pics(const QPixmap * barcode);
void set_pics(QPixmap barcode);
inline int picskilo()
{
return data.size();
}
QUrl indoc();
/* vars permanent to put on stream */
QString name;
QString info;
QByteArray extension;
QByteArray data; /* qCompress */
};
Q_DECLARE_METATYPE(SPics);
inline QDebug operator<<(QDebug debug, SPics& udoc)
{
debug.nospace() << "SPics(name."
<< udoc.name << ","
<< udoc.info << ",size()"
<< udoc.data.size() << ",type()"
<< udoc.extension << ")";
return debug.space();
}
inline QDataStream& operator<<(QDataStream& out, const SPics& udoc)
{
out << udoc.name;
out << udoc.info;
out << udoc.extension;
out << udoc.data;
return out;
}
inline QDataStream& operator>>(QDataStream& in, SPics& udoc)
{
in >> udoc.name;
in >> udoc.info;
in >> udoc.extension;
in >> udoc.data;
return in;
}
class RichDoc
{
public:
enum { MAGICNUMBER = 0xFFAAFFAA, VERSION = 2 };
RichDoc()
{
html = QByteArray("<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Your text</p>");
style = QString("min-height:300px;padding:0px 0px 0px 0px;background-color:#ffffff;");
nullmargin = false;
}
void margin(bool e)
{
nullmargin = e;
}
RichDoc& operator=(const RichDoc& d)
{
resource.clear();
resource = d.resource;
html = d.html;
style = d.style;
return *this;
}
operator QVariant() const
{
return QVariant::fromValue(*this);
}
void Register(QTextDocument *doc , QMap<QString,SPics> list , QString s)
{
style = s;
html.clear();
html.append(doc->clone()->toHtml("utf-8"));
resource.clear();
if (list.size() > 0)
{
resource = list;
}
}
void Register(const QString xhtml , QMap<QString,SPics> list , QString s)
{
style = s;
html.clear();
html.append(xhtml);
resource.clear();
if (list.size() > 0)
{
resource = list;
}
}
QString Hxtml()
{
return QString(html.constData());
}
bool isAbsolute()
{
return style.contains("position:absolute;");
}
QTextDocument *todoc()
{
QTextCursor helper;
QTextDocument *d = new QTextDocument();
d->setHtml(QString(html));
helper = QTextCursor(d);
QMapIterator<QString,SPics> i(resource);
while (i.hasNext())
{
i.next();
SPics record = i.value();
d->addResource(QTextDocument::ImageResource,QUrl(record.name),record.pix());
}
QTextFrame *Tframe = d->rootFrame();
if (nullmargin)
{
QTextFrameFormat Ftf = Tframe->frameFormat();
Ftf.setLeftMargin(0);
Ftf.setBottomMargin(0);
Ftf.setTopMargin(0);
Ftf.setRightMargin(0);
Tframe->setFrameFormat(Ftf);
}
QTextFrame::iterator it;
for (it = Tframe->begin(); !(it.atEnd()); ++it)
{
QTextBlock para = it.currentBlock();
if (para.isValid())
{
QTextBlockFormat Parformat = para.blockFormat();
if (Parformat.bottomMargin() == 12 && Parformat.topMargin() == 12 || nullmargin)
{
Parformat.setBottomMargin(0);
Parformat.setTopMargin(0);
Parformat.setRightMargin(0);
Parformat.setLeftMargin(0);
helper.setPosition(para.position(),QTextCursor::MoveAnchor);
helper.setBlockFormat(Parformat);
}
QTextBlock::iterator de;
for (de = para.begin(); !(de.atEnd()); ++de)
{
QTextFragment fr = de.fragment();
if (fr.isValid())
{
QTextCharFormat base = fr.charFormat();
QTextImageFormat pico = base.toImageFormat();
if (base.isAnchor())
{
//////////////qDebug() << "### link found..... ";
base.setForeground(QBrush(_LINK_COLOR_));
base.setUnderlineStyle(QTextCharFormat::SingleUnderline);
helper.setPosition(fr.position());
helper.setPosition(fr.position() + fr.length(),QTextCursor::KeepAnchor);
helper.setCharFormat(base);
}
if (pico.isValid())
{
const QString hrefadress = pico.name();
SPics spico = resource[hrefadress];
////////////qDebug() << "### from RichDoc add resource " << hrefadress;
////////////////qDebug() << "### from RichDoc info " << spico.info;
pico.setToolTip(spico.info);
pico.setProperty(_IMAGE_PICS_ITEM_,spico);
helper.setPosition(fr.position());
helper.setPosition(fr.position() + fr.length(),QTextCursor::KeepAnchor);
helper.setCharFormat(pico);
}
}
}
}
}
return d;
}
bool nullmargin;
QString style;
QMap<QString,SPics> resource;
QByteArray html; /* qCompress */
};
inline QDataStream& operator<<(QDataStream& out, RichDoc& e)
{
out << e.html;
out << e.style;
QMapIterator<QString,SPics> i(e.resource);
while (i.hasNext())
{
i.next();
SPics record = i.value();
out << record;
}
return out;
}
inline QDataStream& operator>>(QDataStream& in, RichDoc& e)
{
in >> e.html;
in >> e.style;
while (!in.atEnd())
{
SPics appoint;
in >> appoint;
e.resource.insert(appoint.name,appoint);
}
return in;
}
Q_DECLARE_METATYPE(RichDoc);
typedef QMap<int,RichDoc> LayerList;
typedef QList<RichDoc> QLayerList;
Q_DECLARE_METATYPE(LayerList)
Q_DECLARE_METATYPE(QLayerList)
/* save pics list stream */
QString SaveImageGroup(QList<SPics> li);
/* decoded base64 stream to put on mysql row , file or network streams */
QList<SPics> OpenImageGroup(const QString datastream_base64);
/* save a doc to stream */
QString SaveRichDoc(RichDoc e);
/* decoded base64 stream to put on mysql row , file or network streams */
RichDoc OpenRichDoc(const QString datastream_base64);
/* inline stream from page format */
QByteArray HeSaveLayer(RichDoc e , const int position);
QPair<int,RichDoc> HeOpenLayer(const QByteArray stream);
class PageDoc
{
public:
enum { MAGICNUMBER = 0xFFFAFFAA, VERSION = 1 };
PageDoc()
{
Listening.clear();
binformat.clear();
modus = 1;
}
operator QVariant() const
{
return QVariant::fromValue(*this);
}
int size()
{
return Listening.size();
}
QByteArray save()
{
QString line("\n\n");
QByteArray bytes;
QByteArray signature("PAGE\n");
binformat.clear();
QMapIterator<int,RichDoc> o(Listening);
while (o.hasNext())
{
o.next();
RichDoc record = o.value();
QByteArray dat = HeSaveLayer(record,o.key());
binformat.append(dat);
}
QBuffer buffer(&bytes);
if (!buffer.open(QIODevice::WriteOnly))
{
return QByteArray();
}
QDataStream ds(&buffer);
/* place header */
ds.setVersion(QDataStream::Qt_4_2);
ds << signature;
ds << (quint32)MAGICNUMBER;
ds << (quint32)VERSION;
ds << rect;
ds << line;
for (int i = 0; i < binformat.size(); ++i)
{
ds << binformat.at(i);
}
buffer.close();
QCryptographicHash formats(QCryptographicHash::Md5);
formats.addData(bytes);
smd5 = formats.result();
return bytes;
}
void open(QByteArray stream)
{
QCryptographicHash formats(QCryptographicHash::Md5);
formats.addData(stream);
smd5 = formats.result();
QBuffer buffer(&stream);
if (!buffer.open(QIODevice::ReadOnly))
{
return;
}
QString infostream;
quint32 magic, version;
QByteArray signer;
QDataStream ds(&buffer);
ds.setVersion(QDataStream::Qt_4_2);
ds >> signer;
if (!signer.contains(QByteArray("PAGE")))
{
buffer.close();
return;
}
ds >> magic;
if ((quint32)MAGICNUMBER != magic)
{
qWarning() << "######## PageDoc::MAGICNUMBER not ok " << magic;
buffer.close();
return;
}
ds >> version;
if ((quint32)VERSION != version)
{
qWarning() << "######## PageDoc::VERSION not ok " << version;
buffer.close();
return;
}
ds >> rect;
ds >> infostream;
QByteArray daten;
Listening.clear();
while (!ds.atEnd())
{
ds >> daten;
QPair<int,RichDoc> Layers = HeOpenLayer(daten);
Listening.insert(Layers.first,Layers.second);
}
buffer.close();
}
QRectF rect;
QByteArray smd5;
int modus;
QMap<int,RichDoc> Listening; /* QMap<int,RichDoc> */
QList<QByteArray> binformat;
};
Q_DECLARE_METATYPE(PageDoc);
#endif // IMAGE_PAGE_MIME_H
| [
"[email protected]@9af58faf-7e3e-0410-b956-55d145112073"
]
| [
[
[
1,
431
]
]
]
|
c7d1c3d0a75374681970f8ebbbbd7db8209bec84 | 0e060b1066f5e8524677189cdb017905b265bb29 | /lib/TinyXml/tinyxml.h | 5f20261fef1c985d67892feed4df7a07d6e21bf1 | []
| no_license | TheAks999/BlockBuilder | 2f9de1f36a23fd247782db1b1c3dad4f3ce5078f | db6d9b7c25e6cb4a33a36da18da362996c5223d0 | refs/heads/master | 2016-09-05T22:52:05.287555 | 2011-09-28T18:35:44 | 2011-09-28T18:35:44 | 2,476,607 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 64,258 | h | /*
www.sourceforge.net/projects/tinyxml
Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com)
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.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef TINYXML_INCLUDED
#define TINYXML_INCLUDED
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4530 )
#pragma warning( disable : 4786 )
#endif
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
// Help out windows:
#if defined( _DEBUG ) && !defined( DEBUG )
#define DEBUG
#endif
#define TIXML_USE_STL
#ifdef TIXML_USE_STL
#include <string>
#include <iostream>
#include <sstream>
#define TIXML_STRING std::string
#else
#include "tinystr.h"
#define TIXML_STRING TiXmlString
#endif
// Deprecated library function hell. Compilers want to use the
// new safe versions. This probably doesn't fully address the problem,
// but it gets closer. There are too many compilers for me to fully
// test. If you get compilation troubles, undefine TIXML_SAFE
#define TIXML_SAFE
#ifdef TIXML_SAFE
#if defined(_MSC_VER) && (_MSC_VER >= 1400 )
// Microsoft visual studio, version 2005 and higher.
#define TIXML_SNPRINTF _snprintf_s
#define TIXML_SSCANF sscanf_s
#elif defined(_MSC_VER) && (_MSC_VER >= 1200 )
// Microsoft visual studio, version 6 and higher.
//#pragma message( "Using _sn* functions." )
#define TIXML_SNPRINTF _snprintf
#define TIXML_SSCANF sscanf
#elif defined(__GNUC__) && (__GNUC__ >= 3 )
// GCC version 3 and higher.s
//#warning( "Using sn* functions." )
#define TIXML_SNPRINTF snprintf
#define TIXML_SSCANF sscanf
#else
#define TIXML_SNPRINTF snprintf
#define TIXML_SSCANF sscanf
#endif
#endif
class TiXmlDocument;
class TiXmlElement;
class TiXmlComment;
class TiXmlUnknown;
class TiXmlAttribute;
class TiXmlText;
class TiXmlDeclaration;
class TiXmlParsingData;
const int TIXML_MAJOR_VERSION = 2;
const int TIXML_MINOR_VERSION = 6;
const int TIXML_PATCH_VERSION = 1;
/* Internal structure for tracking location of items
in the XML file.
*/
struct TiXmlCursor
{
TiXmlCursor() { Clear(); }
void Clear() { row = col = -1; }
int row; // 0 based.
int col; // 0 based.
};
/**
Implements the interface to the "Visitor pattern" (see the Accept() method.)
If you call the Accept() method, it requires being passed a TiXmlVisitor
class to handle callbacks. For nodes that contain other nodes (Document, Element)
you will get called with a VisitEnter/VisitExit pair. Nodes that are always leaves
are simply called with Visit().
If you return 'true' from a Visit method, recursive parsing will continue. If you return
false, <b>no children of this node or its sibilings</b> will be Visited.
All flavors of Visit methods have a default implementation that returns 'true' (continue
visiting). You need to only override methods that are interesting to you.
Generally Accept() is called on the TiXmlDocument, although all nodes suppert Visiting.
You should never change the document from a callback.
@sa TiXmlNode::Accept()
*/
class TiXmlVisitor
{
public:
virtual ~TiXmlVisitor() {}
/// Visit a document.
virtual bool VisitEnter( const TiXmlDocument& /*doc*/ ) { return true; }
/// Visit a document.
virtual bool VisitExit( const TiXmlDocument& /*doc*/ ) { return true; }
/// Visit an element.
virtual bool VisitEnter( const TiXmlElement& /*element*/, const TiXmlAttribute* /*firstAttribute*/ ) { return true; }
/// Visit an element.
virtual bool VisitExit( const TiXmlElement& /*element*/ ) { return true; }
/// Visit a declaration
virtual bool Visit( const TiXmlDeclaration& /*declaration*/ ) { return true; }
/// Visit a text node
virtual bool Visit( const TiXmlText& /*text*/ ) { return true; }
/// Visit a comment node
virtual bool Visit( const TiXmlComment& /*comment*/ ) { return true; }
/// Visit an unknow node
virtual bool Visit( const TiXmlUnknown& /*unknown*/ ) { return true; }
};
// Only used by Attribute::Query functions
enum
{
TIXML_SUCCESS,
TIXML_NO_ATTRIBUTE,
TIXML_WRONG_TYPE
};
// Used by the parsing routines.
enum TiXmlEncoding
{
TIXML_ENCODING_UNKNOWN,
TIXML_ENCODING_UTF8,
TIXML_ENCODING_LEGACY
};
const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN;
/** TiXmlBase is a base class for every class in TinyXml.
It does little except to establish that TinyXml classes
can be printed and provide some utility functions.
In XML, the document and elements can contain
other elements and other types of nodes.
@verbatim
A Document can contain: Element (container or leaf)
Comment (leaf)
Unknown (leaf)
Declaration( leaf )
An Element can contain: Element (container or leaf)
Text (leaf)
Attributes (not on tree)
Comment (leaf)
Unknown (leaf)
A Decleration contains: Attributes (not on tree)
@endverbatim
*/
class TiXmlBase
{
friend class TiXmlNode;
friend class TiXmlElement;
friend class TiXmlDocument;
public:
TiXmlBase() : userData(0) {}
virtual ~TiXmlBase() {}
/** All TinyXml classes can print themselves to a filestream
or the string class (TiXmlString in non-STL mode, std::string
in STL mode.) Either or both cfile and str can be null.
This is a formatted print, and will insert
tabs and newlines.
(For an unformatted stream, use the << operator.)
*/
virtual void Print( FILE* cfile, int depth ) const = 0;
/** The world does not agree on whether white space should be kept or
not. In order to make everyone happy, these global, static functions
are provided to set whether or not TinyXml will condense all white space
into a single space or not. The default is to condense. Note changing this
value is not thread safe.
*/
static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; }
/// Return the current white space setting.
static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; }
/** Return the position, in the original source file, of this node or attribute.
The row and column are 1-based. (That is the first row and first column is
1,1). If the returns values are 0 or less, then the parser does not have
a row and column value.
Generally, the row and column value will be set when the TiXmlDocument::Load(),
TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set
when the DOM was created from operator>>.
The values reflect the initial load. Once the DOM is modified programmatically
(by adding or changing nodes and attributes) the new values will NOT update to
reflect changes in the document.
There is a minor performance cost to computing the row and column. Computation
can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value.
@sa TiXmlDocument::SetTabSize()
*/
int Row() const { return location.row + 1; }
int Column() const { return location.col + 1; } ///< See Row()
void SetUserData( void* user ) { userData = user; } ///< Set a pointer to arbitrary user data.
void* GetUserData() { return userData; } ///< Get a pointer to arbitrary user data.
const void* GetUserData() const { return userData; } ///< Get a pointer to arbitrary user data.
// Table that returs, for a given lead byte, the total number of bytes
// in the UTF-8 sequence.
static const int utf8ByteTable[256];
virtual const char* Parse( const char* p,
TiXmlParsingData* data,
TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0;
/** Expands entities in a string. Note this should not contian the tag's '<', '>', etc,
or they will be transformed into entities!
*/
static void EncodeString( const TIXML_STRING& str, TIXML_STRING* out );
enum
{
TIXML_NO_ERROR = 0,
TIXML_ERROR,
TIXML_ERROR_OPENING_FILE,
TIXML_ERROR_PARSING_ELEMENT,
TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME,
TIXML_ERROR_READING_ELEMENT_VALUE,
TIXML_ERROR_READING_ATTRIBUTES,
TIXML_ERROR_PARSING_EMPTY,
TIXML_ERROR_READING_END_TAG,
TIXML_ERROR_PARSING_UNKNOWN,
TIXML_ERROR_PARSING_COMMENT,
TIXML_ERROR_PARSING_DECLARATION,
TIXML_ERROR_DOCUMENT_EMPTY,
TIXML_ERROR_EMBEDDED_NULL,
TIXML_ERROR_PARSING_CDATA,
TIXML_ERROR_DOCUMENT_TOP_ONLY,
TIXML_ERROR_STRING_COUNT
};
protected:
static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding );
inline static bool IsWhiteSpace( char c )
{
return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' );
}
inline static bool IsWhiteSpace( int c )
{
if ( c < 256 )
return IsWhiteSpace( (char) c );
return false; // Again, only truly correct for English/Latin...but usually works.
}
#ifdef TIXML_USE_STL
static bool StreamWhiteSpace( std::istream * in, TIXML_STRING * tag );
static bool StreamTo( std::istream * in, int character, TIXML_STRING * tag );
#endif
/* Reads an XML name into the string provided. Returns
a pointer just past the last character of the name,
or 0 if the function has an error.
*/
static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding );
/* Reads text. Returns a pointer past the given end tag.
Wickedly complex options, but it keeps the (sensitive) code in one place.
*/
static const char* ReadText( const char* in, // where to start
TIXML_STRING* text, // the string read
bool ignoreWhiteSpace, // whether to keep the white space
const char* endTag, // what ends this text
bool ignoreCase, // whether to ignore case in the end tag
TiXmlEncoding encoding ); // the current encoding
// If an entity has been found, transform it into a character.
static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding );
// Get a character, while interpreting entities.
// The length can be from 0 to 4 bytes.
inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding )
{
assert( p );
if ( encoding == TIXML_ENCODING_UTF8 )
{
*length = utf8ByteTable[ *((const unsigned char*)p) ];
assert( *length >= 0 && *length < 5 );
}
else
{
*length = 1;
}
if ( *length == 1 )
{
if ( *p == '&' )
return GetEntity( p, _value, length, encoding );
*_value = *p;
return p+1;
}
else if ( *length )
{
//strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe),
// and the null terminator isn't needed
for( int i=0; p[i] && i<*length; ++i ) {
_value[i] = p[i];
}
return p + (*length);
}
else
{
// Not valid text.
return 0;
}
}
// Return true if the next characters in the stream are any of the endTag sequences.
// Ignore case only works for english, and should only be relied on when comparing
// to English words: StringEqual( p, "version", true ) is fine.
static bool StringEqual( const char* p,
const char* endTag,
bool ignoreCase,
TiXmlEncoding encoding );
static const char* errorString[ TIXML_ERROR_STRING_COUNT ];
TiXmlCursor location;
/// Field containing a generic user pointer
void* userData;
// None of these methods are reliable for any language except English.
// Good for approximation, not great for accuracy.
static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding );
static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding );
inline static int ToLower( int v, TiXmlEncoding encoding )
{
if ( encoding == TIXML_ENCODING_UTF8 )
{
if ( v < 128 ) return tolower( v );
return v;
}
else
{
return tolower( v );
}
}
static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length );
private:
TiXmlBase( const TiXmlBase& ); // not implemented.
void operator=( const TiXmlBase& base ); // not allowed.
struct Entity
{
const char* str;
unsigned int strLength;
char chr;
};
enum
{
NUM_ENTITY = 5,
MAX_ENTITY_LENGTH = 6
};
static Entity entity[ NUM_ENTITY ];
static bool condenseWhiteSpace;
};
/** The parent class for everything in the Document Object Model.
(Except for attributes).
Nodes have siblings, a parent, and children. A node can be
in a document, or stand on its own. The type of a TiXmlNode
can be queried, and it can be cast to its more defined type.
*/
class TiXmlNode : public TiXmlBase
{
friend class TiXmlDocument;
friend class TiXmlElement;
public:
#ifdef TIXML_USE_STL
/** An input stream operator, for every class. Tolerant of newlines and
formatting, but doesn't expect them.
*/
friend std::istream& operator >> (std::istream& in, TiXmlNode& base);
/** An output stream operator, for every class. Note that this outputs
without any newlines or formatting, as opposed to Print(), which
includes tabs and new lines.
The operator<< and operator>> are not completely symmetric. Writing
a node to a stream is very well defined. You'll get a nice stream
of output, without any extra whitespace or newlines.
But reading is not as well defined. (As it always is.) If you create
a TiXmlElement (for example) and read that from an input stream,
the text needs to define an element or junk will result. This is
true of all input streams, but it's worth keeping in mind.
A TiXmlDocument will read nodes until it reads a root element, and
all the children of that root element.
*/
friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base);
/// Appends the XML node or attribute to a std::string.
friend std::string& operator<< (std::string& out, const TiXmlNode& base );
#endif
/** The types of XML nodes supported by TinyXml. (All the
unsupported types are picked up by UNKNOWN.)
*/
enum NodeType
{
TINYXML_DOCUMENT,
TINYXML_ELEMENT,
TINYXML_COMMENT,
TINYXML_UNKNOWN,
TINYXML_TEXT,
TINYXML_DECLARATION,
TINYXML_TYPECOUNT
};
virtual ~TiXmlNode();
/** The meaning of 'value' changes for the specific type of
TiXmlNode.
@verbatim
Document: filename of the xml file
Element: name of the element
Comment: the comment text
Unknown: the tag contents
Text: the text string
@endverbatim
The subclasses will wrap this function.
*/
const char *Value() const { return value.c_str (); }
#ifdef TIXML_USE_STL
/** Return Value() as a std::string. If you only use STL,
this is more efficient than calling Value().
Only available in STL mode.
*/
const std::string& ValueStr() const { return value; }
#endif
const TIXML_STRING& ValueTStr() const { return value; }
/** Changes the value of the node. Defined as:
@verbatim
Document: filename of the xml file
Element: name of the element
Comment: the comment text
Unknown: the tag contents
Text: the text string
@endverbatim
*/
void SetValue(const char * _value) { value = _value;}
#ifdef TIXML_USE_STL
/// STL std::string form.
void SetValue( const std::string& _value ) { value = _value; }
#endif
/// Delete all the children of this node. Does not affect 'this'.
void Clear();
/// One step up the DOM.
TiXmlNode* Parent() { return parent; }
const TiXmlNode* Parent() const { return parent; }
const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children.
TiXmlNode* FirstChild() { return firstChild; }
const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found.
/// The first child of this node with the matching 'value'. Will be null if none found.
TiXmlNode* FirstChild( const char * _value ) {
// Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe)
// call the method, cast the return back to non-const.
return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->FirstChild( _value ));
}
const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children.
TiXmlNode* LastChild() { return lastChild; }
const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children.
TiXmlNode* LastChild( const char * _value ) {
return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value ));
}
#ifdef TIXML_USE_STL
const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form.
TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form.
const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form.
TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form.
#endif
/** An alternate way to walk the children of a node.
One way to iterate over nodes is:
@verbatim
for( child = parent->FirstChild(); child; child = child->NextSibling() )
@endverbatim
IterateChildren does the same thing with the syntax:
@verbatim
child = 0;
while( child = parent->IterateChildren( child ) )
@endverbatim
IterateChildren takes the previous child as input and finds
the next one. If the previous child is null, it returns the
first. IterateChildren will return null when done.
*/
const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const;
TiXmlNode* IterateChildren( const TiXmlNode* previous ) {
return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( previous ) );
}
/// This flavor of IterateChildren searches for children with a particular 'value'
const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const;
TiXmlNode* IterateChildren( const char * _value, const TiXmlNode* previous ) {
return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( _value, previous ) );
}
#ifdef TIXML_USE_STL
const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form.
TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form.
#endif
/** Add a new node related to this. Adds a child past the LastChild.
Returns a pointer to the new object or NULL if an error occured.
*/
TiXmlNode* InsertEndChild( const TiXmlNode& addThis );
/** Add a new node related to this. Adds a child past the LastChild.
NOTE: the node to be added is passed by pointer, and will be
henceforth owned (and deleted) by tinyXml. This method is efficient
and avoids an extra copy, but should be used with care as it
uses a different memory model than the other insert functions.
@sa InsertEndChild
*/
TiXmlNode* LinkEndChild( TiXmlNode* addThis );
/** Add a new node related to this. Adds a child before the specified child.
Returns a pointer to the new object or NULL if an error occured.
*/
TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis );
/** Add a new node related to this. Adds a child after the specified child.
Returns a pointer to the new object or NULL if an error occured.
*/
TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis );
/** Replace a child of this node.
Returns a pointer to the new object or NULL if an error occured.
*/
TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis );
/// Delete a child of this node.
bool RemoveChild( TiXmlNode* removeThis );
/// Navigate to a sibling node.
const TiXmlNode* PreviousSibling() const { return prev; }
TiXmlNode* PreviousSibling() { return prev; }
/// Navigate to a sibling node.
const TiXmlNode* PreviousSibling( const char * ) const;
TiXmlNode* PreviousSibling( const char *_prev ) {
return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->PreviousSibling( _prev ) );
}
#ifdef TIXML_USE_STL
const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form.
TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form.
const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form.
TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form.
#endif
/// Navigate to a sibling node.
const TiXmlNode* NextSibling() const { return next; }
TiXmlNode* NextSibling() { return next; }
/// Navigate to a sibling node with the given 'value'.
const TiXmlNode* NextSibling( const char * ) const;
TiXmlNode* NextSibling( const char* _next ) {
return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->NextSibling( _next ) );
}
/** Convenience function to get through elements.
Calls NextSibling and ToElement. Will skip all non-Element
nodes. Returns 0 if there is not another element.
*/
const TiXmlElement* NextSiblingElement() const;
TiXmlElement* NextSiblingElement() {
return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement() );
}
/** Convenience function to get through elements.
Calls NextSibling and ToElement. Will skip all non-Element
nodes. Returns 0 if there is not another element.
*/
const TiXmlElement* NextSiblingElement( const char * ) const;
TiXmlElement* NextSiblingElement( const char *_next ) {
return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement( _next ) );
}
#ifdef TIXML_USE_STL
const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form.
TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form.
#endif
/// Convenience function to get through elements.
const TiXmlElement* FirstChildElement() const;
TiXmlElement* FirstChildElement() {
return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement() );
}
/// Convenience function to get through elements.
const TiXmlElement* FirstChildElement( const char * _value ) const;
TiXmlElement* FirstChildElement( const char * _value ) {
return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement( _value ) );
}
#ifdef TIXML_USE_STL
const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form.
TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form.
#endif
/** Query the type (as an enumerated value, above) of this node.
The possible types are: DOCUMENT, ELEMENT, COMMENT,
UNKNOWN, TEXT, and DECLARATION.
*/
int Type() const { return type; }
/** Return a pointer to the Document this node lives in.
Returns null if not in a document.
*/
const TiXmlDocument* GetDocument() const;
TiXmlDocument* GetDocument() {
return const_cast< TiXmlDocument* >( (const_cast< const TiXmlNode* >(this))->GetDocument() );
}
/// Returns true if this node has no children.
bool NoChildren() const { return !firstChild; }
virtual const TiXmlDocument* ToDocument() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual const TiXmlElement* ToElement() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual const TiXmlComment* ToComment() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual const TiXmlUnknown* ToUnknown() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual const TiXmlText* ToText() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual const TiXmlDeclaration* ToDeclaration() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual TiXmlDocument* ToDocument() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual TiXmlElement* ToElement() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual TiXmlComment* ToComment() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual TiXmlUnknown* ToUnknown() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual TiXmlText* ToText() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
virtual TiXmlDeclaration* ToDeclaration() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type.
/** Create an exact duplicate of this node and return it. The memory must be deleted
by the caller.
*/
virtual TiXmlNode* Clone() const = 0;
/** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the
XML tree will be conditionally visited and the host will be called back
via the TiXmlVisitor interface.
This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse
the XML for the callbacks, so the performance of TinyXML is unchanged by using this
interface versus any other.)
The interface has been based on ideas from:
- http://www.saxproject.org/
- http://c2.com/cgi/wiki?HierarchicalVisitorPattern
Which are both good references for "visiting".
An example of using Accept():
@verbatim
TiXmlPrinter printer;
tinyxmlDoc.Accept( &printer );
const char* xmlcstr = printer.CStr();
@endverbatim
*/
virtual bool Accept( TiXmlVisitor* visitor ) const = 0;
protected:
TiXmlNode( NodeType _type );
// Copy to the allocated object. Shared functionality between Clone, Copy constructor,
// and the assignment operator.
void CopyTo( TiXmlNode* target ) const;
#ifdef TIXML_USE_STL
// The real work of the input operator.
virtual void StreamIn( std::istream* in, TIXML_STRING* tag ) = 0;
#endif
// Figure out what is at *p, and parse it. Returns null if it is not an xml node.
TiXmlNode* Identify( const char* start, TiXmlEncoding encoding );
TiXmlNode* parent;
NodeType type;
TiXmlNode* firstChild;
TiXmlNode* lastChild;
TIXML_STRING value;
TiXmlNode* prev;
TiXmlNode* next;
private:
TiXmlNode( const TiXmlNode& ); // not implemented.
void operator=( const TiXmlNode& base ); // not allowed.
};
/** An attribute is a name-value pair. Elements have an arbitrary
number of attributes, each with a unique name.
@note The attributes are not TiXmlNodes, since they are not
part of the tinyXML document object model. There are other
suggested ways to look at this problem.
*/
class TiXmlAttribute : public TiXmlBase
{
friend class TiXmlAttributeSet;
public:
/// Construct an empty attribute.
TiXmlAttribute() : TiXmlBase()
{
document = 0;
prev = next = 0;
}
#ifdef TIXML_USE_STL
/// std::string constructor.
TiXmlAttribute( const std::string& _name, const std::string& _value )
{
name = _name;
value = _value;
document = 0;
prev = next = 0;
}
#endif
/// Construct an attribute with a name and value.
TiXmlAttribute( const char * _name, const char * _value )
{
name = _name;
value = _value;
document = 0;
prev = next = 0;
}
const char* Name() const { return name.c_str(); } ///< Return the name of this attribute.
const char* Value() const { return value.c_str(); } ///< Return the value of this attribute.
#ifdef TIXML_USE_STL
const std::string& ValueStr() const { return value; } ///< Return the value of this attribute.
#endif
int IntValue() const; ///< Return the value of this attribute, converted to an integer.
double DoubleValue() const; ///< Return the value of this attribute, converted to a double.
// Get the tinyxml string representation
const TIXML_STRING& NameTStr() const { return name; }
/** QueryIntValue examines the value string. It is an alternative to the
IntValue() method with richer error checking.
If the value is an integer, it is stored in 'value' and
the call returns TIXML_SUCCESS. If it is not
an integer, it returns TIXML_WRONG_TYPE.
A specialized but useful call. Note that for success it returns 0,
which is the opposite of almost all other TinyXml calls.
*/
int QueryIntValue( int* _value ) const;
/// QueryDoubleValue examines the value string. See QueryIntValue().
int QueryDoubleValue( double* _value ) const;
void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute.
void SetValue( const char* _value ) { value = _value; } ///< Set the value.
void SetIntValue( int _value ); ///< Set the value from an integer.
void SetDoubleValue( double _value ); ///< Set the value from a double.
#ifdef TIXML_USE_STL
/// STL std::string form.
void SetName( const std::string& _name ) { name = _name; }
/// STL std::string form.
void SetValue( const std::string& _value ) { value = _value; }
#endif
/// Get the next sibling attribute in the DOM. Returns null at end.
const TiXmlAttribute* Next() const;
TiXmlAttribute* Next() {
return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Next() );
}
/// Get the previous sibling attribute in the DOM. Returns null at beginning.
const TiXmlAttribute* Previous() const;
TiXmlAttribute* Previous() {
return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Previous() );
}
bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; }
bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; }
bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; }
/* Attribute parsing starts: first letter of the name
returns: the next char after the value end quote
*/
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
// Prints this Attribute to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const {
Print( cfile, depth, 0 );
}
void Print( FILE* cfile, int depth, TIXML_STRING* str ) const;
// [internal use]
// Set the document pointer so the attribute can report errors.
void SetDocument( TiXmlDocument* doc ) { document = doc; }
private:
TiXmlAttribute( const TiXmlAttribute& ); // not implemented.
void operator=( const TiXmlAttribute& base ); // not allowed.
TiXmlDocument* document; // A pointer back to a document, for error reporting.
TIXML_STRING name;
TIXML_STRING value;
TiXmlAttribute* prev;
TiXmlAttribute* next;
};
/* A class used to manage a group of attributes.
It is only used internally, both by the ELEMENT and the DECLARATION.
The set can be changed transparent to the Element and Declaration
classes that use it, but NOT transparent to the Attribute
which has to implement a next() and previous() method. Which makes
it a bit problematic and prevents the use of STL.
This version is implemented with circular lists because:
- I like circular lists
- it demonstrates some independence from the (typical) doubly linked list.
*/
class TiXmlAttributeSet
{
public:
TiXmlAttributeSet();
~TiXmlAttributeSet();
void Add( TiXmlAttribute* attribute );
void Remove( TiXmlAttribute* attribute );
const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; }
TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; }
const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; }
TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; }
TiXmlAttribute* Find( const char* _name ) const;
TiXmlAttribute* FindOrCreate( const char* _name );
# ifdef TIXML_USE_STL
TiXmlAttribute* Find( const std::string& _name ) const;
TiXmlAttribute* FindOrCreate( const std::string& _name );
# endif
private:
//*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element),
//*ME: this class must be also use a hidden/disabled copy-constructor !!!
TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed
void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute)
TiXmlAttribute sentinel;
};
/** The element is a container class. It has a value, the element name,
and can contain other elements, text, comments, and unknowns.
Elements also contain an arbitrary number of attributes.
*/
class TiXmlElement : public TiXmlNode
{
public:
/// Construct an element.
TiXmlElement (const char * in_value);
#ifdef TIXML_USE_STL
/// std::string constructor.
TiXmlElement( const std::string& _value );
#endif
TiXmlElement( const TiXmlElement& );
void operator=( const TiXmlElement& base );
virtual ~TiXmlElement();
/** Given an attribute name, Attribute() returns the value
for the attribute of that name, or null if none exists.
*/
const char* Attribute( const char* name ) const;
/** Given an attribute name, Attribute() returns the value
for the attribute of that name, or null if none exists.
If the attribute exists and can be converted to an integer,
the integer value will be put in the return 'i', if 'i'
is non-null.
*/
const char* Attribute( const char* name, int* i ) const;
/** Given an attribute name, Attribute() returns the value
for the attribute of that name, or null if none exists.
If the attribute exists and can be converted to an double,
the double value will be put in the return 'd', if 'd'
is non-null.
*/
const char* Attribute( const char* name, double* d ) const;
/** QueryIntAttribute examines the attribute - it is an alternative to the
Attribute() method with richer error checking.
If the attribute is an integer, it is stored in 'value' and
the call returns TIXML_SUCCESS. If it is not
an integer, it returns TIXML_WRONG_TYPE. If the attribute
does not exist, then TIXML_NO_ATTRIBUTE is returned.
*/
int QueryIntAttribute( const char* name, int* _value ) const;
/// QueryDoubleAttribute examines the attribute - see QueryIntAttribute().
int QueryDoubleAttribute( const char* name, double* _value ) const;
/// QueryFloatAttribute examines the attribute - see QueryIntAttribute().
int QueryFloatAttribute( const char* name, float* _value ) const {
double d;
int result = QueryDoubleAttribute( name, &d );
if ( result == TIXML_SUCCESS ) {
*_value = (float)d;
}
return result;
}
#ifdef TIXML_USE_STL
/// QueryStringAttribute examines the attribute - see QueryIntAttribute().
int QueryStringAttribute( const char* name, std::string* _value ) const {
const char* cstr = Attribute( name );
if ( cstr ) {
*_value = std::string( cstr );
return TIXML_SUCCESS;
}
return TIXML_NO_ATTRIBUTE;
}
/** Template form of the attribute query which will try to read the
attribute into the specified type. Very easy, very powerful, but
be careful to make sure to call this with the correct type.
NOTE: This method doesn't work correctly for 'string' types that contain spaces.
@return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE
*/
template< typename T > int QueryValueAttribute( const std::string& name, T* outValue ) const
{
const TiXmlAttribute* node = attributeSet.Find( name );
if ( !node )
return TIXML_NO_ATTRIBUTE;
std::stringstream sstream( node->ValueStr() );
sstream >> *outValue;
if ( !sstream.fail() )
return TIXML_SUCCESS;
return TIXML_WRONG_TYPE;
}
int QueryValueAttribute( const std::string& name, std::string* outValue ) const
{
const TiXmlAttribute* node = attributeSet.Find( name );
if ( !node )
return TIXML_NO_ATTRIBUTE;
*outValue = node->ValueStr();
return TIXML_SUCCESS;
}
#endif
/** Sets an attribute of name to a given value. The attribute
will be created if it does not exist, or changed if it does.
*/
void SetAttribute( const char* name, const char * _value );
#ifdef TIXML_USE_STL
const std::string* Attribute( const std::string& name ) const;
const std::string* Attribute( const std::string& name, int* i ) const;
const std::string* Attribute( const std::string& name, double* d ) const;
int QueryIntAttribute( const std::string& name, int* _value ) const;
int QueryDoubleAttribute( const std::string& name, double* _value ) const;
/// STL std::string form.
void SetAttribute( const std::string& name, const std::string& _value );
///< STL std::string form.
void SetAttribute( const std::string& name, int _value );
///< STL std::string form.
void SetDoubleAttribute( const std::string& name, double value );
#endif
/** Sets an attribute of name to a given value. The attribute
will be created if it does not exist, or changed if it does.
*/
void SetAttribute( const char * name, int value );
/** Sets an attribute of name to a given value. The attribute
will be created if it does not exist, or changed if it does.
*/
void SetDoubleAttribute( const char * name, double value );
/** Deletes an attribute with the given name.
*/
void RemoveAttribute( const char * name );
#ifdef TIXML_USE_STL
void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form.
#endif
const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element.
TiXmlAttribute* FirstAttribute() { return attributeSet.First(); }
const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element.
TiXmlAttribute* LastAttribute() { return attributeSet.Last(); }
/** Convenience function for easy access to the text inside an element. Although easy
and concise, GetText() is limited compared to getting the TiXmlText child
and accessing it directly.
If the first child of 'this' is a TiXmlText, the GetText()
returns the character string of the Text node, else null is returned.
This is a convenient method for getting the text of simple contained text:
@verbatim
<foo>This is text</foo>
const char* str = fooElement->GetText();
@endverbatim
'str' will be a pointer to "This is text".
Note that this function can be misleading. If the element foo was created from
this XML:
@verbatim
<foo><b>This is text</b></foo>
@endverbatim
then the value of str would be null. The first child node isn't a text node, it is
another element. From this XML:
@verbatim
<foo>This is <b>text</b></foo>
@endverbatim
GetText() will return "This is ".
WARNING: GetText() accesses a child node - don't become confused with the
similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are
safe type casts on the referenced node.
*/
const char* GetText() const;
/// Creates a new Element and returns it - the returned element is a copy.
virtual TiXmlNode* Clone() const;
// Print the Element to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const;
/* Attribtue parsing starts: next char past '<'
returns: next char past '>'
*/
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
virtual const TiXmlElement* ToElement() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
virtual TiXmlElement* ToElement() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
/** Walk the XML tree visiting this node and all of its children.
*/
virtual bool Accept( TiXmlVisitor* visitor ) const;
protected:
void CopyTo( TiXmlElement* target ) const;
void ClearThis(); // like clear, but initializes 'this' object as well
// Used to be public [internal use]
#ifdef TIXML_USE_STL
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
#endif
/* [internal use]
Reads the "value" of the element -- another element, or text.
This should terminate with the current end tag.
*/
const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding );
private:
TiXmlAttributeSet attributeSet;
};
/** An XML comment.
*/
class TiXmlComment : public TiXmlNode
{
public:
/// Constructs an empty comment.
TiXmlComment() : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) {}
/// Construct a comment from text.
TiXmlComment( const char* _value ) : TiXmlNode( TiXmlNode::TINYXML_COMMENT ) {
SetValue( _value );
}
TiXmlComment( const TiXmlComment& );
void operator=( const TiXmlComment& base );
virtual ~TiXmlComment() {}
/// Returns a copy of this Comment.
virtual TiXmlNode* Clone() const;
// Write this Comment to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const;
/* Attribtue parsing starts: at the ! of the !--
returns: next char past '>'
*/
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
virtual const TiXmlComment* ToComment() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
virtual TiXmlComment* ToComment() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
/** Walk the XML tree visiting this node and all of its children.
*/
virtual bool Accept( TiXmlVisitor* visitor ) const;
protected:
void CopyTo( TiXmlComment* target ) const;
// used to be public
#ifdef TIXML_USE_STL
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
#endif
// virtual void StreamOut( TIXML_OSTREAM * out ) const;
private:
};
/** XML text. A text node can have 2 ways to output the next. "normal" output
and CDATA. It will default to the mode it was parsed from the XML file and
you generally want to leave it alone, but you can change the output mode with
SetCDATA() and query it with CDATA().
*/
class TiXmlText : public TiXmlNode
{
friend class TiXmlElement;
public:
/** Constructor for text element. By default, it is treated as
normal, encoded text. If you want it be output as a CDATA text
element, set the parameter _cdata to 'true'
*/
TiXmlText (const char * initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT)
{
SetValue( initValue );
cdata = false;
}
virtual ~TiXmlText() {}
#ifdef TIXML_USE_STL
/// Constructor.
TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TINYXML_TEXT)
{
SetValue( initValue );
cdata = false;
}
#endif
TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TINYXML_TEXT ) { copy.CopyTo( this ); }
void operator=( const TiXmlText& base ) { base.CopyTo( this ); }
// Write this text object to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const;
/// Queries whether this represents text using a CDATA section.
bool CDATA() const { return cdata; }
/// Turns on or off a CDATA representation of text.
void SetCDATA( bool _cdata ) { cdata = _cdata; }
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
virtual const TiXmlText* ToText() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
virtual TiXmlText* ToText() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
/** Walk the XML tree visiting this node and all of its children.
*/
virtual bool Accept( TiXmlVisitor* content ) const;
protected :
/// [internal use] Creates a new Element and returns it.
virtual TiXmlNode* Clone() const;
void CopyTo( TiXmlText* target ) const;
bool Blank() const; // returns true if all white space and new lines
// [internal use]
#ifdef TIXML_USE_STL
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
#endif
private:
bool cdata; // true if this should be input and output as a CDATA style text element
};
/** In correct XML the declaration is the first entry in the file.
@verbatim
<?xml version="1.0" standalone="yes"?>
@endverbatim
TinyXml will happily read or write files without a declaration,
however. There are 3 possible attributes to the declaration:
version, encoding, and standalone.
Note: In this version of the code, the attributes are
handled as special cases, not generic attributes, simply
because there can only be at most 3 and they are always the same.
*/
class TiXmlDeclaration : public TiXmlNode
{
public:
/// Construct an empty declaration.
TiXmlDeclaration() : TiXmlNode( TiXmlNode::TINYXML_DECLARATION ) {}
#ifdef TIXML_USE_STL
/// Constructor.
TiXmlDeclaration( const std::string& _version,
const std::string& _encoding,
const std::string& _standalone );
#endif
/// Construct.
TiXmlDeclaration( const char* _version,
const char* _encoding,
const char* _standalone );
TiXmlDeclaration( const TiXmlDeclaration& copy );
void operator=( const TiXmlDeclaration& copy );
virtual ~TiXmlDeclaration() {}
/// Version. Will return an empty string if none was found.
const char *Version() const { return version.c_str (); }
/// Encoding. Will return an empty string if none was found.
const char *Encoding() const { return encoding.c_str (); }
/// Is this a standalone document?
const char *Standalone() const { return standalone.c_str (); }
/// Creates a copy of this Declaration and returns it.
virtual TiXmlNode* Clone() const;
// Print this declaration to a FILE stream.
virtual void Print( FILE* cfile, int depth, TIXML_STRING* str ) const;
virtual void Print( FILE* cfile, int depth ) const {
Print( cfile, depth, 0 );
}
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
virtual const TiXmlDeclaration* ToDeclaration() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
virtual TiXmlDeclaration* ToDeclaration() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
/** Walk the XML tree visiting this node and all of its children.
*/
virtual bool Accept( TiXmlVisitor* visitor ) const;
protected:
void CopyTo( TiXmlDeclaration* target ) const;
// used to be public
#ifdef TIXML_USE_STL
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
#endif
private:
TIXML_STRING version;
TIXML_STRING encoding;
TIXML_STRING standalone;
};
/** Any tag that tinyXml doesn't recognize is saved as an
unknown. It is a tag of text, but should not be modified.
It will be written back to the XML, unchanged, when the file
is saved.
DTD tags get thrown into TiXmlUnknowns.
*/
class TiXmlUnknown : public TiXmlNode
{
public:
TiXmlUnknown() : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) {}
virtual ~TiXmlUnknown() {}
TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::TINYXML_UNKNOWN ) { copy.CopyTo( this ); }
void operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); }
/// Creates a copy of this Unknown and returns it.
virtual TiXmlNode* Clone() const;
// Print this Unknown to a FILE stream.
virtual void Print( FILE* cfile, int depth ) const;
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
virtual const TiXmlUnknown* ToUnknown() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
virtual TiXmlUnknown* ToUnknown() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
/** Walk the XML tree visiting this node and all of its children.
*/
virtual bool Accept( TiXmlVisitor* content ) const;
protected:
void CopyTo( TiXmlUnknown* target ) const;
#ifdef TIXML_USE_STL
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
#endif
private:
};
/** Always the top level node. A document binds together all the
XML pieces. It can be saved, loaded, and printed to the screen.
The 'value' of a document node is the xml file name.
*/
class TiXmlDocument : public TiXmlNode
{
public:
/// Create an empty document, that has no name.
TiXmlDocument();
/// Create a document with a name. The name of the document is also the filename of the xml.
TiXmlDocument( const char * documentName );
#ifdef TIXML_USE_STL
/// Constructor.
TiXmlDocument( const std::string& documentName );
#endif
TiXmlDocument( const TiXmlDocument& copy );
void operator=( const TiXmlDocument& copy );
virtual ~TiXmlDocument() {}
/** Load a file using the current document value.
Returns true if successful. Will delete any existing
document data before loading.
*/
bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/// Save a file using the current document value. Returns true if successful.
bool SaveFile() const;
/// Load a file using the given filename. Returns true if successful.
bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/// Save a file using the given filename. Returns true if successful.
bool SaveFile( const char * filename ) const;
/** Load a file using the given FILE*. Returns true if successful. Note that this method
doesn't stream - the entire object pointed at by the FILE*
will be interpreted as an XML file. TinyXML doesn't stream in XML from the current
file location. Streaming may be added in the future.
*/
bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/// Save a file using the given FILE*. Returns true if successful.
bool SaveFile( FILE* ) const;
#ifdef TIXML_USE_STL
bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version.
{
return LoadFile( filename.c_str(), encoding );
}
bool SaveFile( const std::string& filename ) const ///< STL std::string version.
{
return SaveFile( filename.c_str() );
}
#endif
/** Parse the given null terminated block of xml data. Passing in an encoding to this
method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml
to use that encoding, regardless of what TinyXml might otherwise try to detect.
*/
virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/** Get the root element -- the only top level element -- of the document.
In well formed XML, there should only be one. TinyXml is tolerant of
multiple elements at the document level.
*/
const TiXmlElement* RootElement() const { return FirstChildElement(); }
TiXmlElement* RootElement() { return FirstChildElement(); }
/** If an error occurs, Error will be set to true. Also,
- The ErrorId() will contain the integer identifier of the error (not generally useful)
- The ErrorDesc() method will return the name of the error. (very useful)
- The ErrorRow() and ErrorCol() will return the location of the error (if known)
*/
bool Error() const { return error; }
/// Contains a textual (english) description of the error if one occurs.
const char * ErrorDesc() const { return errorDesc.c_str (); }
/** Generally, you probably want the error string ( ErrorDesc() ). But if you
prefer the ErrorId, this function will fetch it.
*/
int ErrorId() const { return errorId; }
/** Returns the location (if known) of the error. The first column is column 1,
and the first row is row 1. A value of 0 means the row and column wasn't applicable
(memory errors, for example, have no row/column) or the parser lost the error. (An
error in the error reporting, in that case.)
@sa SetTabSize, Row, Column
*/
int ErrorRow() const { return errorLocation.row+1; }
int ErrorCol() const { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow()
/** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol())
to report the correct values for row and column. It does not change the output
or input in any way.
By calling this method, with a tab size
greater than 0, the row and column of each node and attribute is stored
when the file is loaded. Very useful for tracking the DOM back in to
the source file.
The tab size is required for calculating the location of nodes. If not
set, the default of 4 is used. The tabsize is set per document. Setting
the tabsize to 0 disables row/column tracking.
Note that row and column tracking is not supported when using operator>>.
The tab size needs to be enabled before the parse or load. Correct usage:
@verbatim
TiXmlDocument doc;
doc.SetTabSize( 8 );
doc.Load( "myfile.xml" );
@endverbatim
@sa Row, Column
*/
void SetTabSize( int _tabsize ) { tabsize = _tabsize; }
int TabSize() const { return tabsize; }
/** If you have handled the error, it can be reset with this call. The error
state is automatically cleared if you Parse a new XML block.
*/
void ClearError() { error = false;
errorId = 0;
errorDesc = "";
errorLocation.row = errorLocation.col = 0;
//errorLocation.last = 0;
}
/** Write the document to standard out using formatted printing ("pretty print"). */
void Print() const { Print( stdout, 0 ); }
/* Write the document to a string using formatted printing ("pretty print"). This
will allocate a character array (new char[]) and return it as a pointer. The
calling code pust call delete[] on the return char* to avoid a memory leak.
*/
//char* PrintToMemory() const;
/// Print this Document to a FILE stream.
virtual void Print( FILE* cfile, int depth = 0 ) const;
// [internal use]
void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding );
virtual const TiXmlDocument* ToDocument() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
virtual TiXmlDocument* ToDocument() { return this; } ///< Cast to a more defined type. Will return null not of the requested type.
/** Walk the XML tree visiting this node and all of its children.
*/
virtual bool Accept( TiXmlVisitor* content ) const;
protected :
// [internal use]
virtual TiXmlNode* Clone() const;
#ifdef TIXML_USE_STL
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
#endif
private:
void CopyTo( TiXmlDocument* target ) const;
bool error;
int errorId;
TIXML_STRING errorDesc;
int tabsize;
TiXmlCursor errorLocation;
bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write.
};
/**
A TiXmlHandle is a class that wraps a node pointer with null checks; this is
an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml
DOM structure. It is a separate utility class.
Take an example:
@verbatim
<Document>
<Element attributeA = "valueA">
<Child attributeB = "value1" />
<Child attributeB = "value2" />
</Element>
<Document>
@endverbatim
Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very
easy to write a *lot* of code that looks like:
@verbatim
TiXmlElement* root = document.FirstChildElement( "Document" );
if ( root )
{
TiXmlElement* element = root->FirstChildElement( "Element" );
if ( element )
{
TiXmlElement* child = element->FirstChildElement( "Child" );
if ( child )
{
TiXmlElement* child2 = child->NextSiblingElement( "Child" );
if ( child2 )
{
// Finally do something useful.
@endverbatim
And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity
of such code. A TiXmlHandle checks for null pointers so it is perfectly safe
and correct to use:
@verbatim
TiXmlHandle docHandle( &document );
TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).ToElement();
if ( child2 )
{
// do something useful
@endverbatim
Which is MUCH more concise and useful.
It is also safe to copy handles - internally they are nothing more than node pointers.
@verbatim
TiXmlHandle handleCopy = handle;
@endverbatim
What they should not be used for is iteration:
@verbatim
int i=0;
while ( true )
{
TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).ToElement();
if ( !child )
break;
// do something
++i;
}
@endverbatim
It seems reasonable, but it is in fact two embedded while loops. The Child method is
a linear walk to find the element, so this code would iterate much more than it needs
to. Instead, prefer:
@verbatim
TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).ToElement();
for( child; child; child=child->NextSiblingElement() )
{
// do something
}
@endverbatim
*/
class TiXmlHandle
{
public:
/// Create a handle from any node (at any depth of the tree.) This can be a null pointer.
TiXmlHandle( TiXmlNode* _node ) { this->node = _node; }
/// Copy constructor
TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; }
TiXmlHandle operator=( const TiXmlHandle& ref ) { this->node = ref.node; return *this; }
/// Return a handle to the first child node.
TiXmlHandle FirstChild() const;
/// Return a handle to the first child node with the given name.
TiXmlHandle FirstChild( const char * value ) const;
/// Return a handle to the first child element.
TiXmlHandle FirstChildElement() const;
/// Return a handle to the first child element with the given name.
TiXmlHandle FirstChildElement( const char * value ) const;
/** Return a handle to the "index" child with the given name.
The first child is 0, the second 1, etc.
*/
TiXmlHandle Child( const char* value, int index ) const;
/** Return a handle to the "index" child.
The first child is 0, the second 1, etc.
*/
TiXmlHandle Child( int index ) const;
/** Return a handle to the "index" child element with the given name.
The first child element is 0, the second 1, etc. Note that only TiXmlElements
are indexed: other types are not counted.
*/
TiXmlHandle ChildElement( const char* value, int index ) const;
/** Return a handle to the "index" child element.
The first child element is 0, the second 1, etc. Note that only TiXmlElements
are indexed: other types are not counted.
*/
TiXmlHandle ChildElement( int index ) const;
#ifdef TIXML_USE_STL
TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); }
TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); }
TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); }
TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); }
#endif
/** Return the handle as a TiXmlNode. This may return null.
*/
TiXmlNode* ToNode() const { return node; }
/** Return the handle as a TiXmlElement. This may return null.
*/
TiXmlElement* ToElement() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); }
/** Return the handle as a TiXmlText. This may return null.
*/
TiXmlText* ToText() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); }
/** Return the handle as a TiXmlUnknown. This may return null.
*/
TiXmlUnknown* ToUnknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); }
/** @deprecated use ToNode.
Return the handle as a TiXmlNode. This may return null.
*/
TiXmlNode* Node() const { return ToNode(); }
/** @deprecated use ToElement.
Return the handle as a TiXmlElement. This may return null.
*/
TiXmlElement* Element() const { return ToElement(); }
/** @deprecated use ToText()
Return the handle as a TiXmlText. This may return null.
*/
TiXmlText* Text() const { return ToText(); }
/** @deprecated use ToUnknown()
Return the handle as a TiXmlUnknown. This may return null.
*/
TiXmlUnknown* Unknown() const { return ToUnknown(); }
private:
TiXmlNode* node;
};
/** Print to memory functionality. The TiXmlPrinter is useful when you need to:
-# Print to memory (especially in non-STL mode)
-# Control formatting (line endings, etc.)
When constructed, the TiXmlPrinter is in its default "pretty printing" mode.
Before calling Accept() you can call methods to control the printing
of the XML document. After TiXmlNode::Accept() is called, the printed document can
be accessed via the CStr(), Str(), and Size() methods.
TiXmlPrinter uses the Visitor API.
@verbatim
TiXmlPrinter printer;
printer.SetIndent( "\t" );
doc.Accept( &printer );
fprintf( stdout, "%s", printer.CStr() );
@endverbatim
*/
class TiXmlPrinter : public TiXmlVisitor
{
public:
TiXmlPrinter() : depth( 0 ), simpleTextPrint( false ),
buffer(), indent( " " ), lineBreak( "\n" ) {}
virtual bool VisitEnter( const TiXmlDocument& doc );
virtual bool VisitExit( const TiXmlDocument& doc );
virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute );
virtual bool VisitExit( const TiXmlElement& element );
virtual bool Visit( const TiXmlDeclaration& declaration );
virtual bool Visit( const TiXmlText& text );
virtual bool Visit( const TiXmlComment& comment );
virtual bool Visit( const TiXmlUnknown& unknown );
/** Set the indent characters for printing. By default 4 spaces
but tab (\t) is also useful, or null/empty string for no indentation.
*/
void SetIndent( const char* _indent ) { indent = _indent ? _indent : "" ; }
/// Query the indention string.
const char* Indent() { return indent.c_str(); }
/** Set the line breaking string. By default set to newline (\n).
Some operating systems prefer other characters, or can be
set to the null/empty string for no indenation.
*/
void SetLineBreak( const char* _lineBreak ) { lineBreak = _lineBreak ? _lineBreak : ""; }
/// Query the current line breaking string.
const char* LineBreak() { return lineBreak.c_str(); }
/** Switch over to "stream printing" which is the most dense formatting without
linebreaks. Common when the XML is needed for network transmission.
*/
void SetStreamPrinting() { indent = "";
lineBreak = "";
}
/// Return the result.
const char* CStr() { return buffer.c_str(); }
/// Return the length of the result string.
size_t Size() { return buffer.size(); }
#ifdef TIXML_USE_STL
/// Return the result.
const std::string& Str() { return buffer; }
#endif
private:
void DoIndent() {
for( int i=0; i<depth; ++i )
buffer += indent;
}
void DoLineBreak() {
buffer += lineBreak;
}
int depth;
bool simpleTextPrint;
TIXML_STRING buffer;
TIXML_STRING indent;
TIXML_STRING lineBreak;
};
#ifdef _MSC_VER
#pragma warning( pop )
#endif
#endif
| [
"[email protected]"
]
| [
[
[
1,
1801
]
]
]
|
0fb4729970871baf304e8f9151907fbd69c3b3a8 | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Engine/Graphics/include/EffectManager.h | cb62fd38e5c744f5f1756f5bc3e8189645b8f3f7 | []
| no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,663 | h | #pragma once
#ifndef __EFFECT_MANAGER_H__
#define __EFFECT_MANAGER_H__
#include "base.h"
#include "Effect.h"
#include "Utils/MapManager.h"
#include "params.h"
#define MAX_LIGHTS_BY_SHADER 4
//forward declarations ----------------------------------------------
class CLightManager;
class CalSkeleton;
class CalHardwareModel;
class CLight;
//-------------------------------------------------------------------
class CEffectManager:
public CMapManager<CEffect>
{
private:
typedef map<int,string> TDefaultEffectMap;
public:
CEffectManager(): m_pLightManager(0),
m_pEffectPool(0),
m_szFileName(""),
m_vCameraEye(0.0f),
m_pCalSkeleton(0),
m_pCalHardwareModel(0),
m_iTextureWidth(0),
m_iTextureHeight(0),
m_iViewportX(0),
m_iViewportY(0),
m_iViewportWidth(0),
m_iViewportHeight(0),
m_bWorldMatrixUpdated(false),
m_bProjectionMatrixUpdated(false),
m_bViewMatrixUpdated(false),
m_bLightViewMatrixUpdated(false),
m_bViewProjectionMatrixUpdated(false),
m_bWorldViewMatrixUpdated(false),
m_bWorldViewProjectionMatrixUpdated(false),
m_bCameraEyeUpdated(false),
m_bCameraUpUpdated(false),
m_bCameraRightUpdated(false),
m_bViewProjectionUpdated(false),
m_bWorldViewUpdated(false),
m_bWorldViewProjectionUpdated(false),
m_bLightsUpdated(false),
m_bLightUpdated(false),
m_bSkeletonUpdated(false),
m_bTextureWidthHeightUpdated(false),
m_bAlphaFactorUpdated(false),
m_bPoissonBlurKernelUpdated(true),
m_bSpecularParamsUpdated(true),
m_bGlowUpdated(false),
m_bSpecularUpdated(false),
m_bSpecularActive(false),
m_bEnvironmentUpdated(false),
m_bTimeUpdated(false),
m_bSpriteSizeUpdated(false),
m_bHDRParamsUpdated(true),
m_bViewportUpdated(true),
m_bCenterUpdated(false),
m_bBlurParamsUpdated(true),
m_fTime(0.0f),
m_fEnvironmentIntensity(0.f),
m_fGlossiness(0.f),
m_fSpecularLevel(0.f),
m_fBrightPassThreshold(.8f),
m_fExposure(.5f),
m_fGaussMultiplier(.4f),
m_fMaxLuminanceLowerLimit (0.25f), m_fMaxLuminanceUpperLimit (2.f),
m_fSceneLuminanceLowerLimit(0.25f), m_fSceneLuminanceUpperLimit(1.f),
m_fBloomFinalScale(0.25f),
m_fGlowToBloom(1.f),
m_fGlowLuminanceScale(0.5f),
m_fMaxGlowLuminance(4.f),
m_fGlowFinalScale(1.f),
m_fBlurRadius(10.f),
m_fNearBlurDepth(-15.f),
m_fFarBlurDepth(25.f),
m_fNearFocalPlaneDepth(.5f),
m_fFarFocalPlaneDepth(15.f)
{SetOk(true);};
~CEffectManager() {Done();};
void SetWorldMatrix(const Mat44f& _mMatrix)
{
m_mWorldMatrix = _mMatrix;
m_bWorldMatrixUpdated=
m_bWorldViewMatrixUpdated=
m_bWorldViewProjectionMatrixUpdated=
m_bWorldViewUpdated=
m_bWorldViewProjectionUpdated=true;
};
void SetProjectionMatrix(const Mat44f& _mMatrix)
{
m_mProjectionMatrix = _mMatrix;
m_bProjectionMatrixUpdated=
m_bViewProjectionMatrixUpdated=
m_bWorldViewProjectionMatrixUpdated=
m_bViewProjectionUpdated=
m_bWorldViewUpdated=
m_bWorldViewProjectionUpdated=true;
};
void SetViewMatrix(const Mat44f& _mMatrix)
{
m_mViewMatrix = _mMatrix;
m_bLightViewMatrixUpdated =
m_bViewMatrixUpdated =
m_bViewProjectionMatrixUpdated =
m_bWorldViewMatrixUpdated =
m_bWorldViewProjectionMatrixUpdated =
m_bViewProjectionUpdated=
m_bWorldViewProjectionUpdated=true;
};
void SetLightViewMatrix(const Mat44f& _mMatrix)
{
m_mLightViewMatrix = _mMatrix;
m_bLightViewMatrixUpdated=true;
};
void SetShadowProjectionMatrix(const Mat44f& _mMatrix)
{
m_mShadowProjectionMatrix = _mMatrix;
m_bLightViewMatrixUpdated=true;
};
void SetCameraEye(const Vect3f& _vCameraEye)
{
m_vCameraEye = _vCameraEye;
m_bCameraEyeUpdated=true;
};
void SetCameraUp(const Vect3f& _vCameraUp)
{
m_vCameraUp = _vCameraUp;
m_bCameraUpUpdated=true;
};
void SetCameraRight(const Vect3f& _vCameraRight)
{
m_vCameraRight = _vCameraRight;
m_bCameraRightUpdated=true;
};
void SetSpecular(bool _bSpecular)
{
m_bSpecularActive = _bSpecular;
m_bSpecularUpdated = true;
};
void SetLight(CLight* _pLight);
void SetSpecularParams(float _fGlossiness, float _fSpecularLevel);
const Mat44f& GetWorldMatrix() const {return m_mWorldMatrix;};
const Mat44f& GetProjectionMatrix() const {return m_mProjectionMatrix;};
const Mat44f& GetViewMatrix() const {return m_mViewMatrix;};
const Mat44f& GetLightViewMatrix() const {return m_mLightViewMatrix;};
const Mat44f& GetShadowProjectionMatrix() {return m_mShadowProjectionMatrix;};
//Compostes
//const Mat44f& GetInverseProjectionMatrix();
//const Mat44f& GetInverseViewMatrix();
//const Mat44f& GetInverseWorldMatrix();
const Mat44f& GetViewProjectionMatrix();
const Mat44f& GetWorldViewMatrix();
const Mat44f& GetWorldViewProjectionMatrix();
//non matrix
const Vect3f& GetCameraEye() {return m_vCameraEye;};
size_t GetMaxLights() const { return MAX_LIGHTS_BY_SHADER; };
CEffect* GetEffect(const string& _szName) {return GetResource(_szName);};
void SetSkeleton(CalSkeleton* _pSkeleton, CalHardwareModel* _pCalHardwareModel) {m_pCalSkeleton = _pSkeleton; m_pCalHardwareModel = _pCalHardwareModel; m_bSkeletonUpdated = true;};
void SetTextureWidthHeight(int _iWidth, int _iHeight) {m_iTextureWidth = _iWidth; m_iTextureHeight = _iHeight; m_bTextureWidthHeightUpdated = true;};
void GetTextureWidthHeight(int& _iWidth, int& _iHeight) {_iWidth = m_iTextureWidth; _iHeight = m_iTextureHeight;};
void SetViewport(int _iX, int _iY, int _iWidth, int _iHeight) {m_iViewportX = _iX; m_iViewportY = _iY; m_iViewportWidth = _iWidth; m_iViewportHeight = _iHeight; m_bViewportUpdated = true;};
void GetViewport(int& _iX, int& _iY, int& _iWidth, int& _iHeight) {_iX = m_iViewportX; _iY = m_iViewportY; _iWidth = m_iViewportWidth; _iHeight = m_iViewportHeight;};
void SetAlphaFactor(float _fAlphaFactor) {m_fAlphaFactor = _fAlphaFactor; m_bAlphaFactorUpdated = true;};
void SetTime(float _bTime) {m_fTime = _bTime; m_bTimeUpdated = true;};
void SetGlow(bool _bGlow) {m_bGlowActive = _bGlow; m_bGlowUpdated = true;};
void SetGlowIntensity(float _fGlowIntensity) {m_fGlowIntensity = _fGlowIntensity; m_bGlowUpdated = true;};
void SetEnvironmentIntensity(float _fEnvironmentIntensity) {if(_fEnvironmentIntensity != m_fEnvironmentIntensity) {m_fEnvironmentIntensity = _fEnvironmentIntensity; m_bEnvironmentUpdated = true;}};
void SetSpriteSize(const Vect2f _vSpriteSize) {if(_vSpriteSize != m_vSpriteSize) { m_vSpriteSize = _vSpriteSize; m_bSpriteSizeUpdated = true; } };
void SetCenterXY(float _fX, float _fY) {m_fCenterX = _fX; m_fCenterY = _fY; m_bCenterUpdated = true;};
void SetBrightPassThreshold (float _fBrightPassThreshold);
void SetExposure (float _fExposure);
void SetGaussMultiplier (float _fGaussMultiplier);
void SetMaxLuminanceLimits (float _fMaxLuminanceLowerLimit, float _fMaxLuminanceUpperLimit);
void SetSceneLuminanceLimits(float _fSceneLuminanceLowerLimit, float _fSceneLuminanceUpperLimit);
void SetBloomFinalScale (float _fBloomFinalScale );
void SetGlowToBloom (float _fGlowToBloom );
void SetGlowLuminanceScale (float _fGlowLuminanceScale );
void SetMaxGlowLuminance (float _fMaxGlowLuminance );
void SetGlowFinalScale (float _fGlowFinalScale );
float GetBrightPassThreshold () const { return m_fBrightPassThreshold;};
float GetExposure () const { return m_fExposure ;};
float GetGaussMultiplier () const { return m_fGaussMultiplier ;};
float GetBloomFinalScale () const { return m_fBloomFinalScale ;};
float GetGlowToBloom () const { return m_fGlowToBloom ;};
float GetGlowLuminanceScale () const { return m_fGlowLuminanceScale ;};
float GetMaxGlowLuminance () const { return m_fMaxGlowLuminance ;};
float GetGlowFinalScale () const { return m_fGlowFinalScale ;};
void GetMaxLuminanceLimits (float &fMaxLuminanceLowerLimit_ , float &fMaxLuminanceUpperLimit_) {fMaxLuminanceLowerLimit_ = m_fMaxLuminanceLowerLimit ; fMaxLuminanceUpperLimit_ = m_fMaxLuminanceUpperLimit; };
void GetSceneLuminanceLimits(float &fSceneLuminanceLowerLimit_, float &fSceneLuminanceUpperLimit_) {fSceneLuminanceLowerLimit_ = m_fSceneLuminanceLowerLimit; fSceneLuminanceUpperLimit_ = m_fSceneLuminanceUpperLimit;};
void PrintHDRParams() const;
void SetBlurRadius (float _fBlurRadius ) { if(_fBlurRadius != m_fBlurRadius ) { m_fBlurRadius = _fBlurRadius ; m_bBlurParamsUpdated = true; }};
void SetNearBlurDepth (float _fNearBlurDepth ) { if(_fNearBlurDepth != m_fNearBlurDepth ) { m_fNearBlurDepth = _fNearBlurDepth ; m_bBlurParamsUpdated = true; }};
void SetFarBlurDepth (float _fFarBlurDepth ) { if(_fFarBlurDepth != m_fFarBlurDepth ) { m_fFarBlurDepth = _fFarBlurDepth ; m_bBlurParamsUpdated = true; }};
void SetNearFocalPlaneDepth(float _fNearFocalPlaneDepth) { if(_fNearFocalPlaneDepth != m_fNearFocalPlaneDepth) { m_fNearFocalPlaneDepth = _fNearFocalPlaneDepth; m_bBlurParamsUpdated = true; }};
void SetFarFocalPlaneDepth(float _fFarFocalPlaneDepth) { if(_fFarFocalPlaneDepth != m_fFarFocalPlaneDepth) { m_fFarFocalPlaneDepth = _fFarFocalPlaneDepth ; m_bBlurParamsUpdated = true; }};
float GetBlurRadius () const { return m_fBlurRadius ;};
float GetNearBlurDepth () const { return m_fNearBlurDepth ;};
float GetFarBlurDepth () const { return m_fFarBlurDepth ;};
float GetNearFocalPlaneDepth() const { return m_fNearFocalPlaneDepth;};
float GetFarFocalPlaneDepth() const { return m_fFarFocalPlaneDepth;};
void ActivateCamera(const Mat44f& _mViewMatrix, const Mat44f& _mProjectionMatrix, const Vect3f& _vCameraEye, const Vect3f& _vCameraUp, const Vect3f& _vCameraRight);
void Begin(void) {m_bLightsUpdated = true; ActivateDefaultRendering();};
void ActivateDefaultRendering(void);
void ActivateAlphaRendering(void);
void ActivateInstancedRendering(void);
void LoadShaderData(CEffect* _pEffect);
bool Load(const SEffectManagerParams& _params);
void Reload();
void CleanUp() { Release(); };
protected:
void Release();
private:
bool Load(bool _bReload);
CLightManager* m_pLightManager;
LPD3DXEFFECTPOOL m_pEffectPool;
CalSkeleton* m_pCalSkeleton;
CalHardwareModel* m_pCalHardwareModel;
string m_szFileName;
Mat44f m_mWorldMatrix;
Mat44f m_mProjectionMatrix;
Mat44f m_mViewMatrix;
Mat44f m_mLightViewMatrix;
Mat44f m_mShadowProjectionMatrix;
Mat44f m_mViewProjectionMatrix;
Mat44f m_mWorldViewMatrix;
Mat44f m_mWorldViewProjectionMatrix;
Vect3f m_vCameraEye;
Vect3f m_vCameraUp;
Vect3f m_vCameraRight;
int m_iTextureWidth;
int m_iTextureHeight;
int m_iViewportX;
int m_iViewportY;
int m_iViewportWidth;
int m_iViewportHeight;
float m_fAlphaFactor;
float m_pfPoissonBlurKernel[32];
float m_fBlurRadius ;
float m_fNearBlurDepth ;
float m_fFarBlurDepth ;
float m_fNearFocalPlaneDepth;
float m_fFarFocalPlaneDepth ;
//Variables actualitzadeds al shader
bool m_bWorldMatrixUpdated;
bool m_bProjectionMatrixUpdated;
bool m_bViewMatrixUpdated;
bool m_bLightViewMatrixUpdated;
//bool m_bShadowProjectionMatrixUpdated;
bool m_bViewProjectionMatrixUpdated;
bool m_bWorldViewMatrixUpdated;
bool m_bWorldViewProjectionMatrixUpdated;
bool m_bCameraEyeUpdated;
bool m_bCameraUpUpdated;
bool m_bCameraRightUpdated;
bool m_bSkeletonUpdated;
bool m_bTextureWidthHeightUpdated;
bool m_bViewportUpdated;
bool m_bAlphaFactorUpdated;
bool m_bPoissonBlurKernelUpdated;
bool m_bSpecularParamsUpdated;
bool m_bGlowUpdated;
bool m_bSpecularUpdated;
bool m_bEnvironmentUpdated;
bool m_bHDRParamsUpdated;
bool m_bBlurParamsUpdated;
//Matrius compostes recalculades
bool m_bViewProjectionUpdated;
bool m_bWorldViewUpdated;
bool m_bWorldViewProjectionUpdated;
bool m_bLightsUpdated;
bool m_bLightUpdated;
bool m_bSpriteSizeUpdated;
bool m_bTimeUpdated;
bool m_bCenterUpdated;
//Parametres
float m_fGlossiness;
float m_fSpecularLevel;
bool m_bSpecularActive;
bool m_bGlowActive;
float m_fGlowIntensity;
float m_fEnvironmentIntensity;
float m_fTime;
Vect2f m_vSpriteSize;
float m_fBrightPassThreshold;
float m_fExposure;
float m_fGaussMultiplier;
float m_fMaxLuminanceLowerLimit, m_fMaxLuminanceUpperLimit;
float m_fSceneLuminanceLowerLimit, m_fSceneLuminanceUpperLimit;
float m_fBloomFinalScale;
float m_fGlowToBloom;
float m_fGlowLuminanceScale;
float m_fMaxGlowLuminance;
float m_fGlowFinalScale;
float m_fCenterX;
float m_fCenterY;
bool m_bLightEnabled;
int m_iLightType;
Vect3f m_vLightPosition;
Vect3f m_vLightDirection;
CColor m_cLightColor;
float m_fLightAngleCos;
float m_fLightFallOffCos;
float m_fLightStartRangeSQ;
float m_fLightEndRangeSQ;
bool m_bLightShadowEnabled;
bool m_bLightDynamicOnly;
//bool m_bInverseProjectionUpdated, m_bInverseViewUpdated, m_bInverseWorldUpdated;
//Mat44f m_mInverseProjectionMatrix, m_mInverseViewMatrix, m_mInverseWorldMatrix;
};
#endif
| [
"mudarra@576ee6d0-068d-96d9-bff2-16229cd70485",
"sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485",
"atridas87@576ee6d0-068d-96d9-bff2-16229cd70485",
"Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485"
]
| [
[
[
1,
7
],
[
9,
9
],
[
18,
20
],
[
22,
23
],
[
25,
26
],
[
90,
91
],
[
164,
168
],
[
176,
177
],
[
242,
248
],
[
268,
268
],
[
365,
367
]
],
[
[
8,
8
],
[
10,
17
],
[
21,
21
],
[
24,
24
],
[
27,
28
],
[
30,
34
],
[
39,
46
],
[
49,
49
],
[
51,
57
],
[
59,
61
],
[
63,
63
],
[
67,
67
],
[
69,
69
],
[
80,
81
],
[
84,
86
],
[
88,
89
],
[
92,
135
],
[
137,
162
],
[
170,
172
],
[
178,
178
],
[
180,
180
],
[
182,
184
],
[
187,
190
],
[
193,
193
],
[
203,
204
],
[
222,
223
],
[
225,
229
],
[
239,
241
],
[
249,
267
],
[
272,
273
],
[
278,
286
],
[
288,
297
],
[
300,
301
],
[
303,
307
],
[
311,
318
],
[
320,
324
],
[
328,
330
],
[
332,
332
],
[
342,
343
],
[
345,
361
],
[
363,
364
]
],
[
[
29,
29
],
[
47,
48
],
[
50,
50
],
[
58,
58
],
[
71,
71
],
[
87,
87
],
[
136,
136
],
[
163,
163
],
[
169,
169
],
[
173,
175
],
[
179,
179
],
[
181,
181
],
[
224,
224
],
[
231,
238
],
[
269,
271
],
[
298,
299
],
[
325,
327
],
[
344,
344
],
[
362,
362
]
],
[
[
35,
38
],
[
62,
62
],
[
64,
66
],
[
68,
68
],
[
70,
70
],
[
72,
79
],
[
82,
83
],
[
185,
186
],
[
191,
192
],
[
194,
202
],
[
205,
221
],
[
230,
230
],
[
274,
277
],
[
287,
287
],
[
302,
302
],
[
308,
310
],
[
319,
319
],
[
331,
331
],
[
333,
341
]
]
]
|
15e3e60bffa76de0e59428d6e0bd7b6bef687c11 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-19/pcbnew/class_edge_mod.h | 240b0263d015aa64fd8ae2239176f065101edca5 | []
| 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 | ISO-8859-1 | C++ | false | false | 1,449 | h | /**************************************************************/
/* class_edge_module.h : description des contours d'un module */
/**************************************************************/
class Pcb3D_GLCanvas;
/* description des contours (empreintes ) et TYPES des CONTOURS : */
class EDGE_MODULE: public EDA_BaseLineStruct
{
public:
int m_Shape ; // voir "enum Track_Shapes"
wxPoint m_Start0; // coord relatives a l'ancre du point de depart(Orient 0)
wxPoint m_End0; // coord relatives a l'ancre du point de fin (Orient 0)
int m_Angle; // pour les arcs de cercle: longueur de l'arc en 0,1 degres
int m_PolyCount; // For polygons : number of points (> 2)
int * m_PolyList; // For polygons: coord list (1 point = 2 coord)
// Coord are relative to Origine, orient 0
public:
EDGE_MODULE(MODULE * parent );
EDGE_MODULE(EDGE_MODULE * edge );
~EDGE_MODULE();
/* supprime du chainage la structure Struct */
void UnLink( void );
void Copy(EDGE_MODULE * source); // copy structure
/* Readind and writing data on files */
int WriteDescr( FILE * File );
int ReadDescr( char * Line, FILE * File, int * LineNum = NULL);
// Mise a jour des coordonées pour l'affichage
void SetDrawCoord(void);
/* drawing functions */
void Draw(WinEDA_DrawPanel * panel, wxDC * DC, const wxPoint & offset,
int draw_mode);
void Draw3D(Pcb3D_GLCanvas * glcanvas);
};
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
43
]
]
]
|
d75b719356fc22a37696d621e42e5812ba6fe303 | 3276915b349aec4d26b466d48d9c8022a909ec16 | /c++/数据类型以及语句/浮点数的比较.cpp | 22b3c087d372dce05b674cdcc4cbfe7da7cdcb99 | []
| no_license | flyskyosg/3dvc | c10720b1a7abf9cf4fa1a66ef9fc583d23e54b82 | 0279b1a7ae097b9028cc7e4aa2dcb67025f096b9 | refs/heads/master | 2021-01-10T11:39:45.352471 | 2009-07-31T13:13:50 | 2009-07-31T13:13:50 | 48,670,844 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 483 | cpp | #include<iostream> //浮点数的比较
#include<string>
//#include<iomanip>
#include<sstream>
#include<fstream>
#include<vector>
using namespace std;
void main()
{
double f1=1.23456789123456779,f2=1.23456789123456789; //10进制double浮点数取16位有效数字,只要前16位有效数字相同,就相同
cout<<(f1==f2)<<endl; //而float则取9位有效数字
}
| [
"[email protected]"
]
| [
[
[
1,
30
]
]
]
|
9d3bbf7476dd2187ff91aacf536db768461ea05f | 640a36607eb5b185eceb733643dda918221a40a4 | /Sever/lib/IOCPFramework/IOCP.cpp | 8941be524bd4f149ac9511909d6564211d247b33 | []
| no_license | degravata/simple-flash-mmorpg | 13cc97665e89dc8a0c6218a9a6ebc5c44217fc7d | 71138defc786ce757eae8d6fc6bd53d16bf44e63 | refs/heads/master | 2016-09-12T10:38:44.046533 | 2011-01-25T07:51:25 | 2011-01-25T07:51:25 | 56,880,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,510 | cpp | #include "IOCP.h"
#include "BehaviorCreateMainThread.h"
#include "BehaviorDefaultMsgDeal.h"
#include "BehaviorDefaultMsgDealManage.h"
namespace SevenSmile{
namespace Net{
namespace IOCPFramework{
IOCP::IOCP(void)
{
this->_strIPAddr="127.0.0.1";
this->_intPort=5555;
this->_intExecuteThreadNumOfIOCPTaskList=10;
this->_lpBaseBehaviorMainThread=new Behavior::BehaviorCreateMainThread();
this->_lpBaseBehaviorMsgDeal=NULL;
this->_lpIBMsgDealManage=NULL;
//this->_lpBaseBehaviorMainThread=NULL;
//this->_lpBaseBehaviorMsgSend=NULL;
//this->_lpBaseBehaviorQuit=NULL;
}
IOCP::IOCP(char* i_strIPAddr, int i_intPort, int i_intExecuteThreadNumOfIOCPTaskList){
IOCP();
this->_strIPAddr=i_strIPAddr;
this->_intPort=i_intPort;
this->_intExecuteThreadNumOfIOCPTaskList=i_intExecuteThreadNumOfIOCPTaskList;
}
IOCP::~IOCP(void)
{
if (NULL!=_lpBaseBehaviorMainThread){
delete this->_lpBaseBehaviorMainThread;
this->_lpBaseBehaviorMainThread=NULL;
}
if (NULL!=_lpBaseBehaviorMsgDeal){
delete this->_lpBaseBehaviorMsgDeal;
this->_lpBaseBehaviorMsgDeal=NULL;
}
if (NULL!=_lpIBMsgDealManage){
delete this->_lpIBMsgDealManage;
this->_lpIBMsgDealManage=NULL;
}
}
void IOCP::SetIpAddress(const char* i_strAddr){
this->_strIPAddr=i_strAddr;
}
void IOCP::MyIOCPSetPort(int i_intPort){
this->_intPort=i_intPort;
}
void IOCP::SetPort(int i_intPort){
this->_intPort=i_intPort;
}
void IOCP::SetExecuteThreadNumOfIOCPTaskList(int i_intExecuteThreadNumOfIOCPTaskList){
this->_intExecuteThreadNumOfIOCPTaskList=i_intExecuteThreadNumOfIOCPTaskList;
}
void IOCP::SetBehaviorMainThread(BaseBehavior::BaseBehaviorMainThread* i_lpBaseBehaviorMainThread){
if (NULL!=this->_lpBaseBehaviorMainThread){
delete this->_lpBaseBehaviorMainThread;
this->_lpBaseBehaviorMainThread=NULL;
}
this->_lpBaseBehaviorMainThread=i_lpBaseBehaviorMainThread;
}
void IOCP::SetBehaviorMsgDeal(BaseBehavior::BaseBehaviorMsgDeal* i_lpBaseBehaviorMsgDeal){
if (NULL!=this->_lpBaseBehaviorMsgDeal){
delete this->_lpBaseBehaviorMsgDeal;
this->_lpBaseBehaviorMsgDeal=NULL;
}
this->_lpBaseBehaviorMainThread->SetBehaviorMsgDeal(i_lpBaseBehaviorMsgDeal);
}
void IOCP::SetBehaviorMsgDealManage( BaseBehavior::IBMsgDealManage* i_lpIBMsgDealManage )
{
if (NULL!=this->_lpIBMsgDealManage){
delete this->_lpIBMsgDealManage;
this->_lpIBMsgDealManage=NULL;
}
this->_lpBaseBehaviorMainThread->SetIBMsgDealManage(i_lpIBMsgDealManage);
}
//void IOCP::SetBehaviorMsgSend(BaseBehavior::BaseBehaviorMsgSend* i_lpBaseBehaviorMsgSend){
// this->_lpBaseBehaviorMainThread->SetBehaviorMsgSend(i_lpBaseBehaviorMsgSend);
//}
//void IOCP::SetBehaviorQuit(BaseBehavior::BaseBehaviorQuit* i_lpBaseBehaviorBehaviorQuit){
// this->_lpBaseBehaviorMainThread->SetBehaviorQuit(i_lpBaseBehaviorBehaviorQuit);
//}
int IOCP::Start(){
//if (NULL==this->_lpBaseBehaviorMainThread){
// this->SetBehaviorMainThread(new Behavior::BehaviorCreateMainThread());
//}
if (NULL==this->_lpBaseBehaviorMainThread->_lpBaseBehaviorMsgDeal){
this->SetBehaviorMsgDeal(new Behavior::BehaviorDefaultMsgDeal());
}
if (NULL==this->_lpBaseBehaviorMainThread->_lpIBMsgDealManage){
this->SetBehaviorMsgDealManage(new Behavior::BehaviorDefaultMsgDealManage());
}
this->_lpBaseBehaviorMainThread->SetListenSoketIPAddr(this->_strIPAddr);
this->_lpBaseBehaviorMainThread->SetListenSoketPort(this->_intPort);
this->_lpBaseBehaviorMainThread->SetExecuteThreadNum(this->_intExecuteThreadNumOfIOCPTaskList);
_intErrRes=this->_lpBaseBehaviorMainThread->Start(0);
return _intErrRes;
}
const char* IOCP::GetErrorStr()
{
if(_intErrRes==0)
{
return "It's OK";
}
if(_intErrRes==1)
{
return "WSAStartup fail!";
}
if(_intErrRes==2)
{
return "CreateIoCompletionPort fail!";
}
if(_intErrRes==3)
{
return "Init sociket fail!";
}
if(_intErrRes==4)
{
return "start thread fail!";
}
if(_intErrRes==5)
{
return "BindAndListenSocket fail!";
}
if(_intErrRes==6)
{
return "GetFunPointer fail!";
}
if(_intErrRes==7)
{
return "PostAcceptEx fail!";
}
if(_intErrRes==8)
{
return "RegAcceptEvent fail!";
}
return "UnKnow Result!";
}
//bool IOCP::MsgDeal(SOCKET i_soket,char* i_lpChar,int i_charArrLength){
// this->_lpBaseBehaviorMsgDeal->MsgDeal(i_soket,i_lpChar,i_charArrLength);
// return true;
//}
//bool IOCP::MsgSend(SOCKET i_soket,char* i_lpChar,int i_charArrLength){
// //this->_lpBaseBehaviorMsgSend->Send(i_soket,i_lpChar,i_charArrLength);
// this->_lpBaseBehaviorMsgDeal->Send(i_soket,i_lpChar,i_charArrLength);
// return true;
//}
//bool IOCP::Quit(SOCKET i_soket){
// this->_lpBaseBehaviorQuit->Quit(i_soket);
// return true;
//}
string IOCP::GetIpAddress(void){
return this->_strIPAddr;
}
int IOCP::GetPort(void){
return this->_intPort;
}
int IOCP::GetExecuteThreadNumOfIOCPTaskList(){
return this->_intExecuteThreadNumOfIOCPTaskList;
}
}
}
} | [
"fangtong8752@60e69123-55e6-9807-5f38-cd17b4386222"
]
| [
[
[
1,
191
]
]
]
|
2ea265c6b320a52a482be104b6048c29d9740355 | c70941413b8f7bf90173533115c148411c868bad | /core/src/vtxOpSysHelper.cpp | 456707511a1c158dd5404a6298f136cd16786681 | []
| no_license | cnsuhao/vektrix | ac6e028dca066aad4f942b8d9eb73665853fbbbe | 9b8c5fa7119ff7f3dc80fb05b7cdba335cf02c1a | refs/heads/master | 2021-06-23T11:28:34.907098 | 2011-03-27T17:39:37 | 2011-03-27T17:39:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,995 | cpp | /*
-----------------------------------------------------------------------------
This source file is part of "vektrix"
(the rich media and vector graphics rendering library)
For the latest info, see http://www.fuse-software.com/
Copyright (c) 2009-2010 Fuse-Software (tm)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "vtxOpSysHelper.h"
namespace vtx
{
//-----------------------------------------------------------------------
String OpSysHelper::getSystemTime()
{
time_t rawtime;
struct tm* timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
std::stringstream result;
result << std::setfill('0') <<
std::setw(2) <<
timeinfo->tm_hour << ":" <<
std::setw(2) <<
timeinfo->tm_min << ":" <<
std::setw(2) <<
timeinfo->tm_sec;
return result.str();
}
//-----------------------------------------------------------------------
}
| [
"stonecold_@9773a11d-1121-4470-82d2-da89bd4a628a"
]
| [
[
[
1,
54
]
]
]
|
6b17a463f94bf00a17406162eba53496d4a9527c | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/testsemtrywait/src/tsemtrywait.cpp | 5d9f5398ecedeed182ae00e2cfea321a4fce345a | []
| 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 | 2,426 | cpp | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#include "tsemtrywait.h"
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <e32std.h>
#include <stdlib.h>
#include <string.h>
CTestSemtrywait::~CTestSemtrywait()
{
}
CTestSemtrywait::CTestSemtrywait(const TDesC& aStepName)
{
// MANDATORY Call to base class method to set up the human readable name for logging.
SetTestStepName(aStepName);
}
TVerdict CTestSemtrywait::doTestStepPreambleL()
{
__UHEAP_MARK;
SetTestStepResult(EPass);
return TestStepResult();
}
TVerdict CTestSemtrywait::doTestStepPostambleL()
{
__UHEAP_MARKEND;
return TestStepResult();
}
TVerdict CTestSemtrywait::doTestStepL()
{
int err;
if(TestStepName() == KTestSem388)
{
INFO_PRINTF1(_L("TestSem388():"));
err = TestSem388();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestSem389)
{
INFO_PRINTF1(_L("TestSem389():"));
err = TestSem389();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestSem390)
{
INFO_PRINTF1(_L("TestSem390():"));
err = TestSem390();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestSem391)
{
INFO_PRINTF1(_L("TestSem391():"));
err = TestSem391();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestSem392)
{
INFO_PRINTF1(_L("TestSem392():"));
err = TestSem392();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == KTestSem700)
{
INFO_PRINTF1(_L("TestSem700():"));
err = TestSem700();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
return TestStepResult();
}
| [
"none@none"
]
| [
[
[
1,
99
]
]
]
|
00c2b2bdf6c0d0ae1f6e1bb11512b23913c73853 | 4323418f83efdc8b9f8b8bb1cc15680ba66e1fa8 | /Trunk/Battle Cars/Battle Cars/Source/CPrintFont.h | 0feab72d07c71f4516c89fa21c2a42ec8236ca5f | []
| no_license | FiveFourFive/battle-cars | 5f2046e7afe5ac50eeeb9129b87fcb4b2893386c | 1809cce27a975376b0b087a96835347069fe2d4c | refs/heads/master | 2021-05-29T19:52:25.782568 | 2011-07-28T17:48:39 | 2011-07-28T17:48:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,187 | h |
#ifndef _CPRINTFONT_H
#define _CPRINTFONT_H
#include <Windows.h>
#include "CSGD_TextureManager.h"
class CPrintFont
{
private:
CSGD_TextureManager* m_pTM;
// Cell Algorithm
int m_nCharWidth;
int m_nCharHeight;
char m_cStartChar;
int m_nImageID;
RECT CellAlgorithm(int id);
public:
CPrintFont(int imageid);
void SetImageID(int nImageID) { m_nImageID = nImageID; }
void Print(const char* szText, int x, int y, float scale, DWORD color)
{
m_pTM = CSGD_TextureManager::GetInstance();
// loop through text one char at a time
int len = strlen(szText);
int xorig = x;
for(int i = 0; i < len; i++)
{
// get letter
char ch = szText[i];
if(ch == ' ')
{
x += (int)(m_nCharWidth * scale);
continue;
}
else if(ch == '\n')
{
x = xorig;
y += (int)(m_nCharHeight * scale);
continue;
}
// get image id
int id = ch - m_cStartChar;
// get rect of letter
RECT rLetter = CellAlgorithm(id);
// draw to screen
if(ch=='p' || ch=='j' || ch=='y' || ch=='g')
m_pTM->Draw(m_nImageID,x,y+3,scale,scale,&rLetter,0,0,0,color);
else
m_pTM->Draw(m_nImageID,x,y,scale,scale,&rLetter,0,0,0,color);
x += (int)(m_nCharWidth * scale);
}
}
void PrintCentered(const char* szTextToPrint, int nPosX, int nPosY, float fScale, DWORD dwColor)
{
int nOffsetX = 0;
//loop through the string 1 char at a time
int len = strlen(szTextToPrint);
for(int i=0; i < len ; i++)
{
//char /find the id by offsetting the startchar
char ch=szTextToPrint[i];
nOffsetX = (int)(m_nCharWidth*i*fScale);
if(ch == ' ')
{
nOffsetX = (int)(m_nCharWidth*i*fScale);
continue;
}
else if (ch=='\n')
{
nOffsetX = 0;
nPosY+= (int)(m_nCharHeight *fScale);
continue;
}
int id = (int)(ch - m_cStartChar);
//use CellAlgorithm to get RECT for Letter
RECT rLetter = CellAlgorithm(id);
//Draw to the screen
CSGD_TextureManager::GetInstance()->Draw(m_nImageID, (nPosX-(((int)(m_nCharWidth*fScale)*len)/2))+nOffsetX, nPosY, fScale, fScale, &rLetter, 0,0,0, dwColor);
}
}
};
#endif | [
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330",
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330",
"[email protected]@598269ab-7e8a-4bc4-b06e-4a1e7ae79330"
]
| [
[
[
1,
51
],
[
56,
58
],
[
94,
99
]
],
[
[
52,
55
],
[
59,
69
],
[
71,
72
],
[
74,
78
],
[
80,
90
],
[
92,
93
]
],
[
[
70,
70
],
[
73,
73
],
[
79,
79
],
[
91,
91
]
]
]
|
7c7667982e6548d7e9592bb56eb9b7e663928d75 | d752d83f8bd72d9b280a8c70e28e56e502ef096f | /Shared/User Interface/Input.h | 1763b05a14fecfd03a49523f0c1613552f28a009 | []
| no_license | apoch/epoch-language.old | f87b4512ec6bb5591bc1610e21210e0ed6a82104 | b09701714d556442202fccb92405e6886064f4af | refs/heads/master | 2021-01-10T20:17:56.774468 | 2010-03-07T09:19:02 | 2010-03-07T09:19:02 | 34,307,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | h | //
// The Epoch Language Project
// FUGUE Virtual Machine
//
// User interface input routines. This structure is designed to decouple
// the bulk of the application from the actual type of user interface.
// This should make it trivial to port the code from one UI framework to
// another, between console and GUI formats, etc.
//
#pragma once
namespace UI
{
//
// Wrapper class for acquiring input from the user
//
class Input
{
// Read operations
public:
std::wstring BlockingRead();
};
}
| [
"[email protected]"
]
| [
[
[
1,
27
]
]
]
|
72c653738f6cb7b407abbb3799973e5b47b6de19 | 95a3e8914ddc6be5098ff5bc380305f3c5bcecb2 | /src/FusionForever_lib/Triangulate.cpp | f7dd181e7d229345ab4f5c5cfe7ff3a1e4098041 | []
| no_license | danishcake/FusionForever | 8fc3b1a33ac47177666e6ada9d9d19df9fc13784 | 186d1426fe6b3732a49dfc8b60eb946d62aa0e3b | refs/heads/master | 2016-09-05T16:16:02.040635 | 2010-04-24T11:05:10 | 2010-04-24T11:05:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,354 | cpp | #include "StdAfx.h"
#include "Triangulate.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
float Triangulate::Area(const Vector2dVector_ptr contour)
{
int n = static_cast<int>(contour->size());
float A=0.0f;
for(int p=n-1,q=0; q<n; p=q++)
{
A+= (*contour)[p].x * (*contour)[q].y - (*contour)[q].x * (*contour)[p].y;
}
return A*0.5f;
}
/*
InsideTriangle decides if a point P is Inside of the triangle
defined by A, B, C.
*/
bool Triangulate::InsideTriangle(float Ax, float Ay,
float Bx, float By,
float Cx, float Cy,
float Px, float Py)
{
float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy;
float cCROSSap, bCROSScp, aCROSSbp;
ax = Cx - Bx; ay = Cy - By;
bx = Ax - Cx; by = Ay - Cy;
cx = Bx - Ax; cy = By - Ay;
apx= Px - Ax; apy= Py - Ay;
bpx= Px - Bx; bpy= Py - By;
cpx= Px - Cx; cpy= Py - Cy;
aCROSSbp = ax*bpy - ay*bpx;
cCROSSap = cx*apy - cy*apx;
bCROSScp = bx*cpy - by*cpx;
return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f));
};
bool Triangulate::Snip(const Vector2dVector_ptr contour,int u,int v,int w,int n,int *V)
{
int p;
float Ax, Ay, Bx, By, Cx, Cy, Px, Py;
Ax = (*contour)[V[u]].x;
Ay = (*contour)[V[u]].y;
Bx = (*contour)[V[v]].x;
By = (*contour)[V[v]].y;
Cx = (*contour)[V[w]].x;
Cy = (*contour)[V[w]].y;
if ( EPSILON > (((Bx-Ax)*(Cy-Ay)) - ((By-Ay)*(Cx-Ax))) )
return false;
for (p=0;p<n;p++)
{
if( (p == u) || (p == v) || (p == w) ) continue;
Px = (*contour)[V[p]].x;
Py = (*contour)[V[p]].y;
if (InsideTriangle(Ax,Ay,Bx,By,Cx,Cy,Px,Py)) return false;
}
return true;
}
bool Triangulate::Process(const Vector2dVector_ptr contour, Vector2dVector_ptr result)
{
/* allocate and initialize list of Vertices in polygon */
int n = static_cast<int>(contour->size());
if ( n < 3 ) return false;
int *V = new int[n];
/* we want a counter-clockwise polygon in V */
if ( 0.0f < Area(contour) )
for (int v=0; v<n; v++) V[v] = v;
else
for(int v=0; v<n; v++) V[v] = (n-1)-v;
int nv = n;
/* remove nv-2 Vertices, creating 1 triangle every time */
int count = 2*nv; /* error detection */
for(int m=0, v=nv-1; nv>2; )
{
/* if we loop, it is probably a non-simple polygon */
if (0 >= (count--))
{
//** Triangulate: ERROR - probable bad polygon!
return false;
}
/* three consecutive vertices in current polygon, <u,v,w> */
int u = v ; if (nv <= u) u = 0; /* previous */
v = u+1; if (nv <= v) v = 0; /* new v */
int w = v+1; if (nv <= w) w = 0; /* next */
if ( Snip(contour,u,v,w,nv,V) )
{
int a,b,c,s,t;
/* true names of the vertices */
a = V[u]; b = V[v]; c = V[w];
/* output Triangle */
result->push_back( (*contour)[a] );
result->push_back( (*contour)[b] );
result->push_back( (*contour)[c] );
m++;
/* remove v from remaining polygon */
for(s=v,t=v+1;t<nv;s++,t++) V[s] = V[t]; nv--;
/* resest error detection counter */
count = 2*nv;
}
}
delete V;
return true;
}
| [
"Edward Woolhouse@e6f1df29-e57c-d74d-9e6e-27e3b006b1a7",
"[email protected]"
]
| [
[
[
1,
62
],
[
65,
130
],
[
132,
137
]
],
[
[
63,
64
],
[
131,
131
]
]
]
|
c1f4c1dfc2f4a80a686a5b212556208cf1b9b9ea | 96b4d383b517e578d44f9beab0814bdf18797fce | /src/luanode_crypto.cpp | 51900219aece58d3bde1bb1f3aa481f03d60941d | [
"MIT"
]
| permissive | mkottman/LuaNode | e675f2199acfaa8190cf6c9b09f85bb9f9196f36 | b059225855939477147c5d4a6e8df3350c0a25fb | refs/heads/master | 2021-01-16T19:19:29.942269 | 2011-01-30T00:09:50 | 2011-01-30T00:09:50 | 1,234,094 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,021 | cpp | #include "stdafx.h"
#include "LuaNode.h"
#include "luanode_crypto.h"
#include "luanode_net.h"
#include "blogger.h"
#include <boost/asio/read_until.hpp>
#include <boost/bind.hpp>
#include "shared_const_buffer.h"
using namespace LuaNode::Crypto;
//////////////////////////////////////////////////////////////////////////
/// Register this module's classes
void LuaNode::Crypto::Register(lua_State* L) {
OpenSSL_add_all_digests();
OpenSSL_add_all_ciphers();
Socket::Register(L, NULL, true);
SecureContext::Register(L, NULL, true);
Hash::Register(L, true);
Hmac::Register(L, true);
Signer::Register(L, true);
Verifier::Register(L, true);
Cipher::Register(L, true);
Decipher::Register(L, true);
}
static unsigned long s_nextSocketId = 0;
static unsigned long s_socketCount = 0;
const char* Socket::className = "SecureSocket";
const Socket::RegType Socket::methods[] = {
{"setoption", &Socket::SetOption},
{"verifyPeer", &Socket::VerifyPeer},
{"getPeerCertificate", &Socket::GetPeerCertificate},
{"close", &Socket::Close},
{"shutdown", &Socket::Shutdown},
{"write", &Socket::Write},
{"read", &Socket::Read},
{"doHandShake", &Socket::DoHandShake},
{0}
};
const Socket::RegType Socket::setters[] = {
{0}
};
const Socket::RegType Socket::getters[] = {
{0}
};
static int verify_callback(int ok, X509_STORE_CTX *ctx) {
assert(ok);
return(1); // Ignore errors by now. VerifyPeer will catch them by using SSL_get_verify_result.
}
Socket::Socket(lua_State* L) :
m_L(L),
m_socketId(++s_nextSocketId),
m_shutdown_pending(false),
m_close_pending(false),
m_pending_writes(0),
m_pending_reads(0)
{
s_socketCount++;
LogDebug("Constructing Crypto::Socket (%p) (id:%d). Current socket count = %d", this, m_socketId, s_socketCount);
LuaNode::Net::Socket* pSocket = LuaNode::Net::Socket::check(L, 1);
SecureContext* ctx = Crypto::SecureContext::check(L, 2);
if(lua_toboolean(L, 3)) {
m_handshake_type = boost::asio::ssl::stream_base::server;
}
else {
m_handshake_type = boost::asio::ssl::stream_base::client;
}
if(lua_toboolean(L, 4)) {
m_should_verify = true;
}
else {
m_should_verify = false;
}
m_ssl_socket = new boost::asio::ssl::stream<boost::asio::ip::tcp::socket&>(pSocket->GetSocketRef(), ctx->GetContextRef());
if(m_should_verify) {
SSL_set_verify(m_ssl_socket->impl()->ssl, SSL_VERIFY_PEER, verify_callback);
}
}
Socket::~Socket(void)
{
s_socketCount--;
LogDebug("Destructing Crypto::Socket (%p) (id:%d). Current socket count = %d", this, m_socketId, s_socketCount);
}
//////////////////////////////////////////////////////////////////////////
///
/*static*/ int Socket::tostring_T(lua_State* L) {
userdataType* ud = static_cast<userdataType*>(lua_touserdata(L, 1));
Socket* obj = ud->pT;
lua_pushfstring(L, "%s (%p) (id=%d)", className, obj, obj->m_socketId);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int Socket::SetOption(lua_State* L) {
return 0;
}
//////////////////////////////////////////////////////////////////////////
///
int Socket::VerifyPeer(lua_State* L) {
//lua_getfield(L, 1, "_ssl_context");
/*SecureContext* ctx = Crypto::SecureContext::check(L, 2);*/
//boost::asio::ssl::context& context = ctx->GetContextRef();
/*boost::system::error_code ec;
ctx->GetContextRef().set_verify_mode(boost::asio::ssl::context_base::verify_peer, ec);
if(ec) {
return BoostErrorCodeToLua(L, ec);
}
lua_pushboolean(L, true);
return 1;*/
/*if (ss->ssl_ == NULL) return False();
if (!ss->should_verify_) return False();*/
X509* peer_cert = SSL_get_peer_certificate( m_ssl_socket->impl()->ssl );
if(peer_cert == NULL) {
lua_pushboolean(L, false);
return 1;
}
X509_free(peer_cert);
long x509_verify_error = SSL_get_verify_result( m_ssl_socket->impl()->ssl );
// Can also check for:
// X509_V_ERR_CERT_HAS_EXPIRED
// X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
// X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
// X509_V_ERR_INVALID_CA
// X509_V_ERR_PATH_LENGTH_EXCEEDED
// X509_V_ERR_INVALID_PURPOSE
// X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
// printf("%s\n", X509_verify_cert_error_string(x509_verify_error));
if (!x509_verify_error) {
lua_pushboolean(L, true);
}
else {
lua_pushboolean(L, false);
}
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int Socket::GetPeerCertificate(lua_State* L) {
const SSL* ssl = m_ssl_socket->impl()->ssl;
X509* peer_cert = SSL_get_peer_certificate(ssl);
if(peer_cert == NULL) {
lua_pushnil(L);
return 1;
}
lua_newtable(L);
int table = lua_gettop(L);
char* subject = X509_NAME_oneline(X509_get_subject_name(peer_cert), 0, 0);
if (subject != NULL) {
lua_pushstring(L, subject);
lua_setfield(L, table, "subject");
OPENSSL_free(subject);
}
char* issuer = X509_NAME_oneline(X509_get_issuer_name(peer_cert), 0, 0);
if (issuer != NULL) {
lua_pushstring(L, issuer);
lua_setfield(L, table, "issuer");
OPENSSL_free(issuer);
}
char buf[256];
BIO* bio = BIO_new(BIO_s_mem());
ASN1_TIME_print(bio, X509_get_notBefore(peer_cert));
memset(buf, 0, sizeof(buf));
BIO_read(bio, buf, sizeof(buf) - 1);
lua_pushstring(L, buf);
lua_setfield(L, table, "valid_from");
ASN1_TIME_print(bio, X509_get_notAfter(peer_cert));
memset(buf, 0, sizeof(buf));
BIO_read(bio, buf, sizeof(buf) - 1);
BIO_free(bio);
lua_pushstring(L, buf);
lua_setfield(L, table, "valid_to");
unsigned int md_size, i;
unsigned char md[EVP_MAX_MD_SIZE];
if (X509_digest(peer_cert, EVP_sha1(), md, &md_size)) {
const char hex[] = "0123456789ABCDEF";
char fingerprint[EVP_MAX_MD_SIZE * 3];
for (i=0; i<md_size; i++) {
fingerprint[3*i] = hex[(md[i] & 0xf0) >> 4];
fingerprint[(3*i)+1] = hex[(md[i] & 0x0f)];
fingerprint[(3*i)+2] = ':';
}
if (md_size > 0) {
fingerprint[(3*(md_size-1))+2] = '\0';
}
else {
fingerprint[0] = '\0';
}
lua_pushstring(L, fingerprint);
lua_setfield(L, table, "fingerprint");
}
X509_free(peer_cert);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int Socket::DoHandShake(lua_State* L) {
LogDebug("SecureSocket::DoHandShake (%p) (id:%d)", this, m_socketId);
// store a reference in the registry
lua_pushvalue(L, 1);
int reference = luaL_ref(L, LUA_REGISTRYINDEX);
m_ssl_socket->async_handshake(m_handshake_type,
boost::bind(&Socket::HandleHandshake, this,
reference, boost::asio::placeholders::error)
);
return 0;
}
//////////////////////////////////////////////////////////////////////////
///
void Socket::HandleHandshake(int reference, const boost::system::error_code& error) {
lua_State* L = m_L;
lua_rawgeti(L, LUA_REGISTRYINDEX, reference);
luaL_unref(L, LUA_REGISTRYINDEX, reference);
if(!error) {
LogInfo("SecureSocket::HandleHandshake (%p) (id:%d)", this, m_socketId);
lua_getfield(L, 1, "handshake_callback");
if(lua_type(L, 2) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
LuaNode::GetLuaVM().call(1, LUA_MULTRET);
}
else {
// do nothing?
}
}
else {
LogDebug("SecureSocket::HandleHandshake with error (%p) (id:%d) - %s", this, m_socketId, error.message().c_str());
lua_getfield(L, 1, "handshake_callback");
if(lua_type(L, 2) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
lua_pushnil(L);
switch(error.value()) {
case boost::asio::error::eof:
lua_pushliteral(L, "eof");
break;
#ifdef _WIN32
case ERROR_CONNECTION_ABORTED:
#endif
case boost::asio::error::connection_aborted:
lua_pushliteral(L, "aborted");
break;
case boost::asio::error::operation_aborted:
lua_pushliteral(L, "aborted");
break;
case boost::asio::error::connection_reset:
lua_pushliteral(L, "reset");
break;
default:
lua_pushstring(L, error.message().c_str());
break;
}
LuaNode::GetLuaVM().call(3, LUA_MULTRET);
m_inputBuffer.consume(m_inputBuffer.size());
}
else {
LogError("SecureSocket::HandleWrite with error (%p) - %s", this, m_socketId, error.message().c_str());
}
}
lua_settop(L, 0);
}
//////////////////////////////////////////////////////////////////////////
///
int Socket::Write(lua_State* L) {
/*if(m_shutdown_pending) {
LogDebug("SecureSocket::Write (%p) ignoring because shutdown was signaled", this);
return 0;
}*/
if(m_pending_writes > 0) {
lua_pushboolean(L, false);
return 1;
}
// store a reference in the registry
lua_pushvalue(L, 1);
int reference = luaL_ref(L, LUA_REGISTRYINDEX);
if(lua_type(L, 2) == LUA_TSTRING) {
const char* data = lua_tostring(L, 2);
size_t length = lua_objlen(L, 2);
std::string d(data, length);
shared_const_buffer buffer(d);
LogDebug("SecureSocket::Write (%p) (id:%d) - Length=%d, \r\n'%s'", this, m_socketId, length, data);
m_pending_writes++;
boost::asio::async_write(*m_ssl_socket, buffer,
boost::bind(&Socket::HandleWrite, this, reference, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)
);
}
else {
luaL_error(L, "SecureSocket::Write (%p) (id:%d), unhandled type '%s'", this, m_socketId, luaL_typename(L, 2));
}
lua_pushboolean(L, true);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
void Socket::HandleWrite(int reference, const boost::system::error_code& error, size_t bytes_transferred) {
lua_State* L = m_L;
lua_rawgeti(L, LUA_REGISTRYINDEX, reference);
luaL_unref(L, LUA_REGISTRYINDEX, reference);
m_pending_writes--;
if(!error) {
LogInfo("SecureSocket::HandleWrite (%p) (id:%d) - Bytes Transferred (%d)", this, m_socketId, bytes_transferred);
lua_getfield(L, 1, "write_callback");
if(lua_type(L, 2) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
LuaNode::GetLuaVM().call(1, LUA_MULTRET);
}
else {
// do nothing?
}
}
else {
LogDebug("SecureSocket::HandleWrite with error (%p) (id:%d) - %s", this, m_socketId, error.message().c_str());
lua_getfield(L, 1, "write_callback");
if(lua_type(L, 2) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
lua_pushnil(L);
switch(error.value()) {
case boost::asio::error::eof:
lua_pushliteral(L, "eof");
break;
#ifdef _WIN32
case ERROR_CONNECTION_ABORTED:
#endif
case boost::asio::error::connection_aborted:
lua_pushliteral(L, "aborted");
break;
case boost::asio::error::operation_aborted:
lua_pushliteral(L, "aborted");
break;
case boost::asio::error::connection_reset:
lua_pushliteral(L, "reset");
break;
default:
lua_pushstring(L, error.message().c_str());
break;
}
LuaNode::GetLuaVM().call(3, LUA_MULTRET);
m_inputBuffer.consume(m_inputBuffer.size());
}
else {
LogError("SecureSocket::HandleWrite with error (%p) (id:%d) - %s", this, m_socketId, error.message().c_str());
}
}
boost::system::error_code ec;
if(m_pending_writes == 0 && m_shutdown_pending) {
boost::system::error_code ec;
/*m_ssl_socket->async_shutdown(
boost::bind(&Socket::HandleShutdown, this,
reference, boost::asio::placeholders::error)
);*/
if(ec) {
luaL_error(L, ec.message().c_str());
}
//m_ssl_socket->lowest_layer().shutdown(boost::asio::socket_base::shutdown_both, ec);
if(m_shutdown_send) {
m_ssl_socket->lowest_layer().shutdown(boost::asio::socket_base::shutdown_send, ec);
}
else {
m_ssl_socket->lowest_layer().shutdown(boost::asio::socket_base::shutdown_receive, ec);
}
if(ec) {
LogWarning("Error en shutdown (%p) (id:%d) '%s'", this, m_socketId, ec.message().c_str());
}
}
/*boost::system::error_code ec;
if(m_pending_writes == 0 && m_shutdown_pending) {
LogDebug("Socket::HandleWrite (%p) async_shutdown", this);
// store a reference in the registry
lua_pushvalue(L, 1);
int reference = luaL_ref(L, LUA_REGISTRYINDEX);
m_ssl_socket->async_shutdown(
boost::bind(&Socket::HandleShutdown, this,
reference, boost::asio::placeholders::error)
);*/
/*if(m_handshake_type == boost::asio::ssl::stream_base::server) {
LogDebug("Socket::HandleWrite (%p) async_shutdown (shutdown send)", this);
m_ssl_socket->lowest_layer().shutdown(boost::asio::socket_base::shutdown_send, ec);
}*/
/*else {
LogWarning("Socket::HandleWrite (%p) async_shutdown (shutdown send)", this);
m_ssl_socket->lowest_layer().shutdown(boost::asio::socket_base::shutdown_receive, ec);
}*/
//}
if(m_close_pending && m_pending_writes == 0 && m_pending_reads == 0) {
boost::system::error_code ec;
m_ssl_socket->lowest_layer().close(ec);
if(ec) {
LogError("SecureSocket::HandleWrite - Error closing socket (%p) (id=%d) - %s", this, m_socketId, ec.message().c_str());
}
}
lua_settop(L, 0);
}
//////////////////////////////////////////////////////////////////////////
///
int Socket::Read(lua_State* L) {
/*if(m_shutdown_pending) {
LogDebug("SecureSocket::Read (%p) ignoring because shutdown was signaled", this);
return 0;
}*/
// store a reference in the registry
lua_pushvalue(L, 1);
int reference = luaL_ref(L, LUA_REGISTRYINDEX);
m_pending_reads++;
if(lua_isnoneornil(L, 2)) {
m_ssl_socket->async_read_some(
boost::asio::buffer(m_inputArray),
boost::bind(&Socket::HandleReadSome, this, reference, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)
);
}
else if(!lua_isnumber(L, 2)) {
//const char* p = luaL_optstring(L, 2, "*l");
std::string delimiter = "\r\n";
boost::asio::async_read_until(
*m_ssl_socket,
m_inputBuffer,
delimiter,
boost::bind(&Socket::HandleRead, this, reference, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)
);
}
/*boost::asio::async_read(*m_socket, buffer,
boost::bind(&Socket::HandleWrite, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)
);*/
return 0;
}
//////////////////////////////////////////////////////////////////////////
///
void Socket::HandleRead(int reference, const boost::system::error_code& error, size_t bytes_transferred) {
lua_State* L = m_L;
lua_rawgeti(L, LUA_REGISTRYINDEX, reference);
luaL_unref(L, LUA_REGISTRYINDEX, reference);
m_pending_reads--;
if(!error) {
LogInfo("SecureSocket::HandleRead (%p) (id:%d) - Bytes Transferred (%d)", this, m_socketId, bytes_transferred);
lua_getfield(L, 1, "read_callback");
if(lua_type(L, 2) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
const char* data = (const char*)boost::asio::detail::buffer_cast_helper(m_inputBuffer.data());
lua_pushlstring(L, data, m_inputBuffer.size());
m_inputBuffer.consume(m_inputBuffer.size()); // its safe to consume, the string has already been interned
LuaNode::GetLuaVM().call(2, LUA_MULTRET);
}
else {
// do nothing?
}
}
else {
if(m_shutdown_pending) {
// ignore error when we're shutting down (FIXME!)
return;
}
LogDebug("SecureSocket::HandleRead with error (%p) (id:%d) - %s", this, m_socketId, error.message().c_str());
lua_getfield(L, 1, "read_callback");
if(lua_type(L, 2) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
lua_pushnil(L);
switch(error.value()) {
case boost::asio::error::eof:
lua_pushliteral(L, "eof");
break;
#ifdef _WIN32
case ERROR_CONNECTION_ABORTED:
#endif
case boost::asio::error::connection_aborted:
lua_pushliteral(L, "aborted");
break;
case boost::asio::error::operation_aborted:
lua_pushliteral(L, "aborted");
break;
case boost::asio::error::connection_reset:
lua_pushliteral(L, "reset");
break;
default:
lua_pushstring(L, error.message().c_str());
break;
}
LuaNode::GetLuaVM().call(3, LUA_MULTRET);
m_inputBuffer.consume(m_inputBuffer.size());
}
else {
LogError("SecureSocket::HandleRead with error (%p) (id:%d) - %s", this, m_socketId, error.message().c_str());
}
}
/*boost::system::error_code ec;
if(m_pending_writes == 0 && m_shutdown_pending) {
boost::system::error_code ec;
m_ssl_socket->async_shutdown(
boost::bind(&Socket::HandleShutdown, this,
reference, boost::asio::placeholders::error)
);
if(ec) {
luaL_error(L, ec.message().c_str());
}
}*/
if(m_close_pending && m_pending_writes == 0 && m_pending_reads == 0) {
boost::system::error_code ec;
m_ssl_socket->lowest_layer().close(ec);
if(ec) {
LogError("Socket::HandleRead - Error closing socket (%p) (id=%d) - %s", this, m_socketId, ec.message().c_str());
}
}
lua_settop(L, 0);
}
//////////////////////////////////////////////////////////////////////////
///
void Socket::HandleReadSome(int reference, const boost::system::error_code& error, size_t bytes_transferred) {
lua_State* L = m_L;
lua_rawgeti(L, LUA_REGISTRYINDEX, reference);
luaL_unref(L, LUA_REGISTRYINDEX, reference);
m_pending_reads--;
if(!error) {
LogInfo("SecureSocket::HandleReadSome (%p) (id:%d) - Bytes Transferred (%d)", this, m_socketId, bytes_transferred);
lua_getfield(L, 1, "read_callback");
if(lua_type(L, 2) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
const char* data = m_inputArray.c_array();
lua_pushlstring(L, data, bytes_transferred);
LuaNode::GetLuaVM().call(2, LUA_MULTRET);
}
else {
// do nothing?
}
}
else {
if(m_shutdown_pending) {
// ignore error when we're shutting down (FIXME!)
//return;
}
lua_getfield(L, 1, "read_callback");
if(lua_type(L, 2) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
lua_pushnil(L);
switch(error.value()) {
case boost::asio::error::eof:
lua_pushliteral(L, "eof");
break;
#ifdef _WIN32
case ERROR_CONNECTION_ABORTED:
#endif
case boost::asio::error::connection_aborted:
lua_pushliteral(L, "aborted");
break;
case boost::asio::error::operation_aborted:
lua_pushliteral(L, "aborted");
break;
case boost::asio::error::connection_reset:
lua_pushliteral(L, "reset");
break;
default:
lua_pushstring(L, error.message().c_str());
break;
}
LuaNode::GetLuaVM().call(3, LUA_MULTRET);
m_inputBuffer.consume(m_inputBuffer.size());
}
else {
LogError("SecureSocket::HandleRead with error (%p) (id:%d) - %s", this, m_socketId, error.message().c_str());
}
}
/*boost::system::error_code ec;
if(m_pending_reads == 0 && m_shutdown_pending) {
boost::system::error_code ec;
m_ssl_socket->async_shutdown(
boost::bind(&Socket::HandleShutdown, this,
reference, boost::asio::placeholders::error)
);
if(ec) {
luaL_error(L, ec.message().c_str());
}
}*/
if(m_close_pending && m_pending_writes == 0 && m_pending_reads == 0) {
boost::system::error_code ec;
m_ssl_socket->lowest_layer().close(ec);
if(ec) {
LogError("Socket::HandleReadSome - Error closing socket (%p) (id=%d) - %s", this, m_socketId, ec.message().c_str());
}
}
lua_settop(L, 0);
}
//////////////////////////////////////////////////////////////////////////
///
int Socket::Close(lua_State* L) {
// Q: should I do the same when there are pending reads? probably not. One tends to have always a pending read.
if(m_pending_writes) {
LogDebug("SecureSocket::Close - Socket (%p) (id=%d) marked for closing", this, m_socketId);
// can't close the socket right away, just flag it and close it when there are no more queued ops
m_close_pending = true;
lua_pushboolean(L, true);
return 1;
}
// nothing is waiting, just close the socket right away
LogDebug("SecureSocket::Close - Socket (%p) (id=%d) closing now", this, m_socketId);
boost::system::error_code ec;
m_ssl_socket->lowest_layer().close(ec);
return BoostErrorCodeToLua(L, ec);
}
//////////////////////////////////////////////////////////////////////////
///
int Socket::Shutdown(lua_State* L) {
LogDebug("SecureSocket::Shutdown (%p) (id:%d)", this, m_socketId);
m_shutdown_pending = true;
/*m_ssl_socket->async_shutdown(
boost::bind(&Socket::HandleShutdown, this,
reference, boost::asio::placeholders::error)
);
if(ec) {
luaL_error(L, ec.message().c_str());
}*/
if(strcmp(luaL_checkstring(L, 2), "write") == 0) {
m_shutdown_send = true;
//m_ssl_socket->lowest_layer().shutdown(boost::asio::socket_base::shutdown_send, ec);
}
return 0;
}
//////////////////////////////////////////////////////////////////////////
///
void Socket::HandleShutdown(int reference, const boost::system::error_code& error) {
lua_State* L = m_L;
lua_rawgeti(L, LUA_REGISTRYINDEX, reference);
luaL_unref(L, LUA_REGISTRYINDEX, reference);
// No encontre mejor forma de hacer esto que llamar al read_handler con un error 'eof'
if(!error) {
LogInfo("SecureSocket::HandleShutdown (%p) (id:%d)", this, m_socketId);
lua_getfield(L, 1, "read_callback");
//lua_getfield(L, 1, "shutdown_callback");
if(lua_type(L, 2) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
lua_pushnil(L);
lua_pushliteral(L, "eof");
LuaNode::GetLuaVM().call(3, LUA_MULTRET);
}
else {
// do nothing?
}
}
else {
LogDebug("SecureSocket::HandleShutdown with error (%p) (id:%d) - %s", this, m_socketId, error.message().c_str());
//lua_getfield(L, 1, "shutdown_callback");
lua_getfield(L, 1, "read_callback");
if(lua_type(L, 2) == LUA_TFUNCTION) {
lua_pushvalue(L, 1);
lua_pushnil(L);
lua_pushliteral(L, "eof");
LuaNode::GetLuaVM().call(3, LUA_MULTRET);
m_inputBuffer.consume(m_inputBuffer.size());
}
else {
LogError("SecureSocket::HandleShutdown with error (%p) (id:%d) - %s", this, m_socketId, error.message().c_str());
}
}
lua_settop(L, 0);
}
//////////////////////////////////////////////////////////////////////////
///
const char* SecureContext::className = "SecureContext";
const SecureContext::RegType SecureContext::methods[] = {
{"setKey", &SecureContext::SetKey},
{"setCert", &SecureContext::SetCert},
{"addCACert", &SecureContext::AddCACert},
{0}
};
const SecureContext::RegType SecureContext::setters[] = {
{0}
};
const SecureContext::RegType SecureContext::getters[] = {
{0}
};
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> ssl_socket;
SecureContext::SecureContext(lua_State* L) :
m_L(L)
{
// TODO: handle other ssl types
m_context.reset( new boost::asio::ssl::context( GetIoService(), boost::asio::ssl::context::sslv23) );
m_context->set_options(boost::asio::ssl::context::default_workarounds);
//boost::system::error_code ec;
//m_context->set_verify_mode(boost::asio::ssl::context_base::verify_peer, ec);
m_ca_store = X509_STORE_new();
SSL_CTX_set_cert_store(m_context->impl(), m_ca_store);
}
SecureContext::~SecureContext(void)
{
}
//////////////////////////////////////////////////////////////////////////
///
int SecureContext::SetKey(lua_State* L) {
const char* key_pem = luaL_checkstring(L, 2);
size_t key_pem_len = lua_objlen(L, 2);
BIO *bp = BIO_new(BIO_s_mem());
if (!BIO_write(bp, key_pem, key_pem_len)) {
BIO_free(bp);
lua_pushboolean(L, false);
return 1;
}
EVP_PKEY* pkey = PEM_read_bio_PrivateKey(bp, NULL, NULL, NULL);
if (pkey == NULL) {
BIO_free(bp);
lua_pushboolean(L, false);
return 1;
}
SSL_CTX_use_PrivateKey( m_context->impl(), pkey);
BIO_free(bp);
// XXX Free pkey?
lua_pushboolean(L, true);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int SecureContext::SetCert(lua_State* L) {
const char* cert_pem = luaL_checkstring(L, 2);
size_t cert_pem_len = lua_objlen(L, 2);
BIO *bp = BIO_new(BIO_s_mem());
if (!BIO_write(bp, cert_pem, cert_pem_len)) {
BIO_free(bp);
lua_pushboolean(L, false);
return 1;
}
X509* x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL);
if (x509 == NULL) {
BIO_free(bp);
lua_pushboolean(L, false);
return 1;
}
SSL_CTX_use_certificate(m_context->impl(), x509);
BIO_free(bp);
X509_free(x509);
lua_pushboolean(L, true);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int SecureContext::AddCACert(lua_State* L) {
const char* cert_pem = luaL_checkstring(L, 2);
size_t cert_pem_len = lua_objlen(L, 2);
BIO *bp = BIO_new(BIO_s_mem());
if (!BIO_write(bp, cert_pem, cert_pem_len)) {
BIO_free(bp);
lua_pushboolean(L, false);
return 1;
}
X509 *x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL);
if (x509 == NULL) {
BIO_free(bp);
lua_pushboolean(L, false);
return 1;
}
X509_STORE_add_cert(m_ca_store, x509);
BIO_free(bp);
X509_free(x509);
lua_pushboolean(L, true);
return 1;
}
// TODO: Split these classes to a different file
//////////////////////////////////////////////////////////////////////////
///
static inline void tohex(unsigned char c, char* buffer) {
buffer[0] = ((c >> 4) > 9) ? (c >> 4) + ('a' - 10) : (c >> 4) + '0';
buffer[1] = ((c & 15) > 9) ? (c & 15) + ('a' - 10) : (c & 15) + '0';
}
/////////////////////////////////////////////////////////////////////////
///
static void crypto_error(lua_State* L) {
char buf[120];
unsigned long e = ERR_get_error();
ERR_load_crypto_strings();
luaL_error(L, ERR_error_string(e, buf));
}
static int push_crypto_error(lua_State* L) {
char buf[120];
unsigned long e = ERR_get_error();
ERR_load_crypto_strings();
lua_pushnil(L);
lua_pushstring(L, ERR_error_string(e, buf));
return 2;
}
//////////////////////////////////////////////////////////////////////////
///
static void encode_output(lua_State* L, unsigned char output_type, const unsigned char* data, size_t length) {
switch(output_type) {
case 0: // binary
lua_pushlstring(L, (const char*)data, length);
break;
case 1:{ // hex
char hex[2];
luaL_Buffer buffer;
luaL_buffinit(L, &buffer);
for(unsigned int i = 0; i < length; i++) {
tohex(data[i], hex);
luaL_addlstring(&buffer, hex, 2);
}
luaL_pushresult(&buffer);
break;}
}
}
static const char* encoding_options[] = {
"binary",
"hex",
NULL
};
//////////////////////////////////////////////////////////////////////////
///
const char* Hash::className = "Hash";
const Hash::RegType Hash::methods[] = {
{"update", &Hash::Update},
{"final", &Hash::Final},
{0}
};
Hash::Hash(lua_State* L)
{
const char* digest_name = luaL_checkstring(L, 1);
const EVP_MD* digest = EVP_get_digestbyname(digest_name);
if(digest == NULL) {
luaL_argerror(L, 1, "invalid digest/cipher type");
}
else {
EVP_MD_CTX_init(&m_context);
EVP_DigestInit_ex(&m_context, digest, NULL);
}
}
Hash::~Hash(void)
{
EVP_MD_CTX_cleanup(&m_context);
}
//////////////////////////////////////////////////////////////////////////
///
int Hash::Update(lua_State* L) {
const char* data = luaL_checkstring(L, 2);
EVP_DigestUpdate(&m_context, data, lua_objlen(L, 2));
lua_settop(L, 1);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int Hash::Final(lua_State* L) {
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int written = 0;
EVP_MD_CTX* d = EVP_MD_CTX_create();
EVP_MD_CTX_copy_ex(d, &m_context);
EVP_DigestFinal_ex(d, digest, &written);
EVP_MD_CTX_destroy(d);
int chosen_option = luaL_checkoption(L, 2, "hex", encoding_options);
encode_output(L, chosen_option, digest, written);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
const char* Hmac::className = "Hmac";
const Hmac::RegType Hmac::methods[] = {
{"update", &Hmac::Update},
{"final", &Hmac::Final},
{0}
};
Hmac::Hmac(lua_State* L)
{
const char* algorithm_name = luaL_checkstring(L, 1);
const char* key = luaL_checkstring(L, 2);
const EVP_MD* digest = EVP_get_digestbyname(algorithm_name);
if(digest == NULL) {
luaL_argerror(L, 1, "invalid digest type");
}
else {
HMAC_CTX_init(&m_context);
HMAC_Init_ex(&m_context, key, lua_objlen(L, 2), digest, NULL);
}
}
Hmac::~Hmac(void)
{
HMAC_CTX_cleanup(&m_context);
}
//////////////////////////////////////////////////////////////////////////
///
int Hmac::Update(lua_State* L) {
const char* data = luaL_checkstring(L, 2);
HMAC_Update(&m_context, (unsigned char*)data, lua_objlen(L, 2));
lua_settop(L, 1);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int Hmac::Final(lua_State* L) {
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int written = 0;
HMAC_Final(&m_context, digest, &written);
int chosen_option = luaL_checkoption(L, 2, "hex", encoding_options);
encode_output(L, chosen_option, digest, written);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
const char* Signer::className = "Signer";
const Signer::RegType Signer::methods[] = {
{"update", &Signer::Update},
{"sign", &Signer::Sign},
{0}
};
Signer::Signer(lua_State* L)
{
const char* algorithm_name = luaL_checkstring(L, 1);
const EVP_MD* digest = EVP_get_digestbyname(algorithm_name);
if(digest == NULL) {
luaL_argerror(L, 1, "invalid digest type");
}
else {
EVP_MD_CTX_init(&m_context);
EVP_SignInit_ex(&m_context, digest, NULL);
}
}
Signer::~Signer(void)
{
EVP_MD_CTX_cleanup(&m_context);
}
//////////////////////////////////////////////////////////////////////////
///
int Signer::Update(lua_State* L) {
const char* data = luaL_checkstring(L, 2);
EVP_SignUpdate(&m_context, data, lua_objlen(L, 2));
lua_settop(L, 1);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int Signer::Sign(lua_State* L) {
const unsigned char* key_pem = (const unsigned char*)luaL_checkstring(L, 2);
BIO* bp = BIO_new(BIO_s_mem());
if(!BIO_write(bp, key_pem, lua_objlen(L, 2))) {
return push_crypto_error(L);
}
EVP_PKEY* pkey = PEM_read_bio_PrivateKey( bp, NULL, NULL, NULL );
if(pkey == NULL) {
BIO_free(bp);
return push_crypto_error(L);
}
unsigned int output_len = 0;
unsigned char* buffer = (unsigned char*)malloc(EVP_PKEY_size(pkey));
if(!EVP_SignFinal(&m_context, buffer, &output_len, pkey)) {
free(buffer);
EVP_PKEY_free(pkey);
BIO_free(bp);
return push_crypto_error(L);
}
lua_pushlstring(L, (char*)buffer, output_len);
free(buffer);
EVP_PKEY_free(pkey);
BIO_free(bp);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
const char* Verifier::className = "Verifier";
const Verifier::RegType Verifier::methods[] = {
{"update", &Verifier::Update},
{"verify", &Verifier::Verify},
{0}
};
Verifier::Verifier(lua_State* L)
{
const char* algorithm_name = luaL_checkstring(L, 1);
const EVP_MD* digest = EVP_get_digestbyname(algorithm_name);
if(digest == NULL) {
luaL_argerror(L, 1, "invalid digest type");
}
else {
EVP_MD_CTX_init(&m_context);
EVP_VerifyInit_ex(&m_context, digest, NULL);
}
}
Verifier::~Verifier(void)
{
EVP_MD_CTX_cleanup(&m_context);
}
//////////////////////////////////////////////////////////////////////////
///
int Verifier::Update(lua_State* L) {
const char* data = luaL_checkstring(L, 2);
EVP_VerifyUpdate(&m_context, data, lua_objlen(L, 2));
lua_settop(L, 1);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int Verifier::Verify(lua_State* L) {
const unsigned char* key_pem = (const unsigned char*)luaL_checkstring(L, 2);
const unsigned char* signature = (const unsigned char*)luaL_checkstring(L, 3);
BIO* bp = BIO_new(BIO_s_mem());
if(!BIO_write(bp, key_pem, lua_objlen(L, 2))) {
return push_crypto_error(L);
}
X509* x509 = PEM_read_bio_X509(bp, NULL, NULL, NULL);
if(x509 == NULL) {
BIO_free(bp);
return 0;
}
EVP_PKEY* pkey = X509_get_pubkey(x509);
if(pkey == NULL) {
X509_free(x509);
BIO_free(bp);
return push_crypto_error(L);
}
int result = EVP_VerifyFinal(&m_context, signature, lua_objlen(L, 3), pkey);
EVP_PKEY_free(pkey);
X509_free(x509);
BIO_free(bp);
if(result != 1) {
//ERR_print_errors_fp(stderr);
lua_pushboolean(L, false);
push_crypto_error(L);
}
else {
lua_pushboolean(L, true);
}
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
const char* Cipher::className = "Cipher";
const Cipher::RegType Cipher::methods[] = {
{"update", &Cipher::Update},
{"final", &Cipher::Final},
{0}
};
Cipher::Cipher(lua_State* L)
{
const char* algorithm_name = luaL_checkstring(L, 1);
const EVP_CIPHER* cipher = EVP_get_cipherbyname(algorithm_name);
if(cipher == NULL) {
luaL_argerror(L, 1, "invalid cipher type");
}
size_t key_len = 0;
const char* key = luaL_checklstring(L, 2, &key_len);
m_outputMode = (unsigned char)luaL_checkoption(L, 3, "binary", encoding_options); /* 0 = binary, 1 = hexadecimal */
unsigned char evp_key[EVP_MAX_KEY_LENGTH] = {0};
size_t iv_len = 0;
const char *iv = lua_tolstring(L, 4, &iv_len); /* can be NULL */
unsigned char evp_iv[EVP_MAX_IV_LENGTH] = {0};
memcpy(evp_key, key, key_len);
if (iv) {
memcpy(evp_iv, iv, iv_len);
}
EVP_CIPHER_CTX_init(&m_context);
EVP_EncryptInit_ex(&m_context, cipher, NULL, evp_key, iv ? evp_iv : NULL);
}
Cipher::~Cipher(void)
{
EVP_CIPHER_CTX_cleanup(&m_context);
}
//////////////////////////////////////////////////////////////////////////
///
int Cipher::Update(lua_State* L) {
size_t input_len = 0;
const unsigned char* input = (const unsigned char*)luaL_checklstring(L, 2, &input_len);
unsigned char* buffer = (unsigned char*)malloc(input_len + EVP_CIPHER_CTX_block_size(&m_context));
int output_len = 0;
if(!EVP_EncryptUpdate(&m_context, buffer, &output_len, input, input_len)) {
free(buffer);
crypto_error(L);
}
encode_output(L, m_outputMode, buffer, output_len);
free(buffer);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int Cipher::Final(lua_State* L) {
int output_len = 0;
unsigned char buffer[EVP_MAX_BLOCK_LENGTH];
if(!EVP_EncryptFinal(&m_context, buffer, &output_len)) {
crypto_error(L);
}
encode_output(L, m_outputMode, buffer, output_len);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
const char* Decipher::className = "Decipher";
const Decipher::RegType Decipher::methods[] = {
{"update", &Decipher::Update},
{"final", &Decipher::Final},
{0}
};
Decipher::Decipher(lua_State* L)
{
const char* algorithm_name = luaL_checkstring(L, 1);
const EVP_CIPHER* cipher = EVP_get_cipherbyname(algorithm_name);
if(cipher == NULL) {
luaL_argerror(L, 1, "invalid cipher type");
}
size_t key_len = 0;
const char* key = luaL_checklstring(L, 2, &key_len);
unsigned char evp_key[EVP_MAX_KEY_LENGTH] = {0};
m_outputMode = (unsigned char)luaL_checkoption(L, 3, "binary", encoding_options); /* 0 = binary, 1 = hexadecimal */
size_t iv_len = 0;
const char *iv = lua_tolstring(L, 4, &iv_len); /* can be NULL */
unsigned char evp_iv[EVP_MAX_IV_LENGTH] = {0};
memcpy(evp_key, key, key_len);
if (iv) {
memcpy(evp_iv, iv, iv_len);
}
EVP_CIPHER_CTX_init(&m_context);
EVP_DecryptInit_ex(&m_context, cipher, NULL, evp_key, iv ? evp_iv : NULL);
}
Decipher::~Decipher(void)
{
EVP_CIPHER_CTX_cleanup(&m_context);
}
//////////////////////////////////////////////////////////////////////////
///
int Decipher::Update(lua_State* L) {
size_t input_len = 0;
const unsigned char* input = (const unsigned char*)luaL_checklstring(L, 2, &input_len);
unsigned char* buffer = (unsigned char*)malloc(input_len + EVP_CIPHER_CTX_block_size(&m_context));
int output_len = 0;
if(!EVP_DecryptUpdate(&m_context, buffer, &output_len, input, input_len)) {
free(buffer);
crypto_error(L);
}
encode_output(L, m_outputMode, buffer, output_len);
free(buffer);
return 1;
}
//////////////////////////////////////////////////////////////////////////
///
int Decipher::Final(lua_State* L) {
int output_len = 0;
unsigned char buffer[EVP_MAX_BLOCK_LENGTH];
if(!EVP_DecryptFinal(&m_context, buffer, &output_len)) {
crypto_error(L);
}
encode_output(L, m_outputMode, buffer, output_len);
return 1;
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
2
],
[
899,
899
],
[
1012,
1012
],
[
1384,
1384
]
],
[
[
3,
898
],
[
900,
1011
],
[
1013,
1383
]
]
]
|
7cd98f0b9b0992dec1d1817d9d47b9d2157fbee0 | be78c6c17e74febd81d3f89e88347a0d009f4c99 | /src/GoIO_cpp/GUSBDirectTempDevice.cpp | 73e83ad5a772c7018d5c2aaa1992236b1dd410ac | []
| no_license | concord-consortium/goio_sdk | 87b3f816199e0bc3bd03cf754e0daf2b6a10f792 | e371fd14b8962748e853f76a3a1b472063d12284 | refs/heads/master | 2021-01-22T09:41:53.246014 | 2011-07-14T21:33:34 | 2011-07-14T21:33:34 | 851,663 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,904 | cpp | // GUSBDirectTempDevice.cpp
#include "stdafx.h"
#include "GUSBDirectTempDevice.h"
#include "GUtils.h"
#ifdef _DEBUG
#include "GPlatformDebug.h" // for DEBUG_NEW definition
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static const unsigned long kUSBDirectTempMaxLocalNonVolatileMemAddr = 127;
static const unsigned long kUSBDirectTempMaxRemoteNonVolatileMemAddr = 0;
StringVector GUSBDirectTempDevice::m_snapshotOfAvailableDevices;
static const real kDegreesCelsiusPerBit = 0.0078125;
GUSBDirectTempDevice::GUSBDirectTempDevice(GPortRef *pPortRef)
: TBaseClass(pPortRef)
{
if (!OSInitialize())
GUtils::Trace(GSTD_S("Error - GUSBDirectTempDevice constructor, OSInitialize() returned false."));
}
GUSBDirectTempDevice::~GUSBDirectTempDevice()
{
}
unsigned long GUSBDirectTempDevice::GetMaxLocalNonVolatileMemAddr(void)
{
return kUSBDirectTempMaxLocalNonVolatileMemAddr;
}
unsigned long GUSBDirectTempDevice::GetMaxRemoteNonVolatileMemAddr(void)
{
return kUSBDirectTempMaxRemoteNonVolatileMemAddr;
}
long GUSBDirectTempDevice::ReadSensorDDSMemory(
unsigned char *pBuf,
unsigned long ddsAddr,
unsigned long nBytesToRead,
long nTimeoutMs /* = 1000 */,
bool *pExitFlag /* = NULL */)
{
return ReadNonVolatileMemory(true, pBuf, ddsAddr, nBytesToRead, nTimeoutMs, pExitFlag);
}
long GUSBDirectTempDevice::WriteSensorDDSMemory(
unsigned char *pBuf,
unsigned long ddsAddr,
unsigned long nBytesToWrite,
long nTimeoutMs /* = 1000 */,
bool *pExitFlag /* = NULL */)
{
return WriteNonVolatileMemory(true, pBuf, ddsAddr, nBytesToWrite, nTimeoutMs, pExitFlag);
}
real GUSBDirectTempDevice::ConvertToVoltage(int raw, EProbeType /* eProbeType */, bool /* bCalibrateADCReading = true */)
{
return (GSkipBaseDevice::kVoltsPerBit_ProbeTypeAnalog5V*raw + GSkipBaseDevice::kVoltsOffset_ProbeTypeAnalog5V);
}
| [
"[email protected]"
]
| [
[
[
1,
67
]
]
]
|
87270997559af7814ea14e86ba0ec8c79333ff33 | 061348a6be0e0e602d4a5b3e0af28e9eee2d257f | /Examples/Tutorial/Animation/04ShaderAnimation.cpp | 8bc76a7d7a2049301ede71aa8779861359534d58 | []
| no_license | passthefist/OpenSGToolbox | 4a76b8e6b87245685619bdc3a0fa737e61a57291 | d836853d6e0647628a7dd7bb7a729726750c6d28 | refs/heads/master | 2023-06-09T22:44:20.711657 | 2010-07-26T00:43:13 | 2010-07-26T00:43:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,252 | cpp | //
// OpenSGToolbox Tutorial: 04ShaderAnimation
//
// Demonstrates a simple animation.
//
// General OpenSG configuration, needed everywhere
#include "OSGConfig.h"
// A little helper to simplify scene management and interaction
#include "OSGSimpleSceneManager.h"
#include "OSGNode.h"
#include "OSGGroup.h"
#include "OSGViewport.h"
#include "OSGSimpleGeometry.h"
#include "OSGLineChunk.h"
#include "OSGBlendChunk.h"
#include "OSGChunkMaterial.h"
#include "OSGMaterialChunk.h"
#include "OSGSimpleSHLChunk.h"
#include "OSGSHLParameterChunk.h"
#include "OSGShaderVariableVec4f.h"
// Input
#include "OSGKeyListener.h"
#include "OSGWindowAdapter.h"
#include "OSGWindowUtils.h"
#include <sstream>
//Animation
#include "OSGKeyframeSequences.h"
#include "OSGKeyframeAnimator.h"
#include "OSGFieldAnimation.h"
// Activate the OpenSG namespace
OSG_USING_NAMESPACE
// The SimpleSceneManager to manage simple applications
SimpleSceneManager *mgr;
WindowEventProducerUnrecPtr TutorialWindow;
AnimationUnrecPtr TheAnimation;
// Forward declaration so we can have the interesting stuff upfront
void display(void);
void reshape(Vec2f Size);
std::string createSHLVertexProg(void);
std::string createSHLFragProg(void);
void initAnimations(FieldContainerUnrecPtr AnimatedObject, std::string AnimatedField);
AnimationUnrecPtr createColorAnimation(FieldContainerUnrecPtr AnimatedObject, std::string AnimatedField);
// Create a class to allow for the use of the keyboard shortcuts
class TutorialKeyListener : public KeyListener
{
public:
virtual void keyPressed(const KeyEventUnrecPtr e)
{
if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND)
{
TutorialWindow->closeWindow();
}
}
virtual void keyReleased(const KeyEventUnrecPtr e)
{
}
virtual void keyTyped(const KeyEventUnrecPtr e)
{
}
};
class TutorialMouseListener : public MouseListener
{
public:
virtual void mouseClicked(const MouseEventUnrecPtr e)
{
}
virtual void mouseEntered(const MouseEventUnrecPtr e)
{
}
virtual void mouseExited(const MouseEventUnrecPtr e)
{
}
virtual void mousePressed(const MouseEventUnrecPtr e)
{
mgr->mouseButtonPress(e->getButton(), e->getLocation().x(), e->getLocation().y());
}
virtual void mouseReleased(const MouseEventUnrecPtr e)
{
mgr->mouseButtonRelease(e->getButton(), e->getLocation().x(), e->getLocation().y());
}
};
class TutorialMouseMotionListener : public MouseMotionListener
{
public:
virtual void mouseMoved(const MouseEventUnrecPtr e)
{
mgr->mouseMove(e->getLocation().x(), e->getLocation().y());
}
virtual void mouseDragged(const MouseEventUnrecPtr e)
{
mgr->mouseMove(e->getLocation().x(), e->getLocation().y());
}
};
int main(int argc, char **argv)
{
// OSG init
osgInit(argc,argv);
// Set up Window
TutorialWindow = createNativeWindow();
TutorialWindow->initWindow();
TutorialWindow->setDisplayCallback(display);
TutorialWindow->setReshapeCallback(reshape);
//Add Window Listener
TutorialKeyListener TheKeyListener;
TutorialWindow->addKeyListener(&TheKeyListener);
TutorialMouseListener TheTutorialMouseListener;
TutorialMouseMotionListener TheTutorialMouseMotionListener;
TutorialWindow->addMouseListener(&TheTutorialMouseListener);
TutorialWindow->addMouseMotionListener(&TheTutorialMouseMotionListener);
// Create the SimpleSceneManager helper
mgr = new SimpleSceneManager;
// Tell the Manager what to manage
mgr->setWindow(TutorialWindow);
//Shader Material
BlendChunkUnrecPtr ExampleBlendChunk = BlendChunk::create();
ExampleBlendChunk->setSrcFactor(GL_SRC_ALPHA);
ExampleBlendChunk->setDestFactor(GL_ONE_MINUS_SRC_ALPHA);
//Material Chunk
MaterialChunkUnrecPtr ShaderMaterialChunk = MaterialChunk::create();
ShaderMaterialChunk->setAmbient(Color4f(0.4f,0.4f,0.4f,1.0f));
ShaderMaterialChunk->setDiffuse(Color4f(0.7f,0.7f,0.7f,1.0f));
ShaderMaterialChunk->setSpecular(Color4f(1.0f,1.0f,1.0f,1.0f));
//Shader Chunk
SimpleSHLChunkUnrecPtr TheSHLChunk = SimpleSHLChunk::create();
TheSHLChunk->setVertexProgram(createSHLVertexProg());
TheSHLChunk->setFragmentProgram(createSHLFragProg());
//Color Parameter
ShaderVariableVec4fUnrecPtr Color1Parameter = ShaderVariableVec4f::create();
Color1Parameter->setName("Color1");
Color1Parameter->setValue(Vec4f(0.0f,1.0f,0.0f,1.0f));
ShaderVariableVec4fUnrecPtr Color2Parameter = ShaderVariableVec4f::create();
Color2Parameter->setName("Color2");
Color2Parameter->setValue(Vec4f(1.0f,1.0f,1.0f,1.0f));
//Shader Parameter Chunk
SHLParameterChunkUnrecPtr SHLParameters = SHLParameterChunk::create();
SHLParameters->getParameters().push_back(Color1Parameter);
SHLParameters->getParameters().push_back(Color2Parameter);
SHLParameters->setSHLChunk(TheSHLChunk);
ChunkMaterialUnrecPtr ShaderMaterial = ChunkMaterial::create();
ShaderMaterial->addChunk(ShaderMaterialChunk);
ShaderMaterial->addChunk(TheSHLChunk);
ShaderMaterial->addChunk(SHLParameters);
//Torus Node
GeometryUnrecPtr TorusGeometry = makeTorusGeo(5.0f,20.0f, 32,32);
TorusGeometry->setMaterial(ShaderMaterial);
NodeUnrecPtr TorusNode = Node::create();
TorusNode->setCore(TorusGeometry);
// Make Main Scene Node
NodeUnrecPtr scene = Node::create();
scene->setCore(Group::create());
scene->addChild(TorusNode);
mgr->setRoot(scene);
// Show the whole Scene
mgr->showAll();
//Create the Animations
initAnimations(Color1Parameter, "value");
//Open Window
Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
TutorialWindow->openWindow(WinPos,
WinSize,
"04ShaderAnimation");
//Main Loop
TutorialWindow->mainLoop();
osgExit();
return 0;
}
// Callback functions
// Redraw the window
void display(void)
{
mgr->redraw();
}
// React to size changes
void reshape(Vec2f Size)
{
mgr->resize(Size.x(), Size.y());
}
std::string createSHLVertexProg(void)
{
std::string Result("");
return Result;
}
std::string createSHLFragProg(void)
{
std::ostringstream FragCodeStream;
FragCodeStream
<< "//Fragment Shader\n"
<< "uniform vec4 Color1;\n"
<< "uniform vec4 Color2;\n"
<< "void main()\n"
<< "{\n"
<< " gl_FragColor = mix(Color1,Color2,1.0-(0.3*gl_Color.r + 0.59*gl_Color.g + 0.11*gl_Color.b));\n"
<< "}\n";
return FragCodeStream.str();
}
AnimationUnrecPtr createColorAnimation(FieldContainerUnrecPtr AnimatedObject, std::string AnimatedField)
{
//Color Keyframe Sequence
KeyframeVectorSequenceUnrecPtr ColorKeyframes = KeyframeVectorSequenceVec4f::create();
ColorKeyframes->addKeyframe(Vec4f(1.0f,0.0f,0.0f,1.0f),0.0f);
ColorKeyframes->addKeyframe(Vec4f(0.0f,1.0f,0.0f,1.0f),2.0f);
ColorKeyframes->addKeyframe(Vec4f(0.0f,0.0f,1.0f,1.0f),4.0f);
ColorKeyframes->addKeyframe(Vec4f(1.0f,0.0f,0.0f,1.0f),6.0f);
//Animator
AnimatorUnrecPtr Animator = KeyframeAnimator::create();
dynamic_pointer_cast<KeyframeAnimator>(Animator)->setKeyframeSequence(ColorKeyframes);
//Animation
FieldAnimationUnrecPtr ColorAnimation = FieldAnimation::create();
dynamic_pointer_cast<FieldAnimation>(ColorAnimation)->setInterpolationType(Animator::LINEAR_INTERPOLATION);
dynamic_pointer_cast<FieldAnimation>(ColorAnimation)->setCycling(-1);
ColorAnimation->setAnimatedField(AnimatedObject, AnimatedField);
return ColorAnimation;
}
void initAnimations(FieldContainerUnrecPtr AnimatedObject, std::string AnimatedField)
{
//Main Animation
TheAnimation = createColorAnimation(AnimatedObject, AnimatedField);
TheAnimation->attachUpdateProducer(TutorialWindow->editEventProducer());
TheAnimation->start();
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
60
],
[
62,
283
]
],
[
[
61,
61
]
]
]
|
76b091302bcfa2be72d43ee5bbcfce5ead552386 | 545c50f3a7928e445f74802e9c42a0ac2c8f57c4 | /Socket.cpp | 21d61ad94e77a30e9bd40ed33e302f7109e763fa | []
| no_license | zcm/WVU-VectorDesign | f0094046988c839df098d669d24d789b871d9d42 | 5fcf9b622db7b10775e6f25faa598791de4909ec | refs/heads/master | 2021-07-09T19:21:05.684565 | 2010-04-23T18:47:23 | 2010-04-23T18:47:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | #include "Socket.h"
Socket::Socket()
{ int result = WSAStartup(MAKEWORD(2,2), &wsaData);
if(result != 0) throw NetworkException("WSAStartup failed!");
}
Socket::Socket(string const ip, string const port)
{ int result = WSAStartup(MAKEWORD(2,2), &wsaData);
if(result != 0) throw NetworkException("WSAStartup failed!");
connectTo(ip, port);
}
void Socket::connectTo(string const ip, string const port)
{ setIp(ip);
setPort(port);
}
void Socket::setIp(string const ip)
{ _ip = ip;
}
const string Socket::getIp()
{ return _ip;
}
void Socket::setPort(string const port)
{ _port = port;
}
const string Socket::getPort()
{ return _port;
}
| [
"ben@580bed88-caa2-44de-b298-61e134d9bb2a"
]
| [
[
[
1,
34
]
]
]
|
cdd9731498280405b6dc31f8ad5f05d05c2cdc73 | 5e72c94a4ea92b1037217e31a66e9bfee67f71dd | /old/src/main.cpp | fcfa3c561a15057d618304c81f6e1048099aed6c | []
| no_license | stein1/bbk | 1070d2c145e43af02a6df14b6d06d9e8ed85fc8a | 2380fc7a2f5bcc9cb2b54f61e38411468e1a1aa8 | refs/heads/master | 2021-01-17T23:57:37.689787 | 2011-05-04T14:50:01 | 2011-05-04T14:50:01 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,824 | cpp | #include "includes.h"
#include "main.h"
#include "MainFrame.h"
// the application icon
#if defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXMAC__)
#include "rc/appicon.xpm"
#endif
// ----------------------------------------------------------------------------
// private classes
// ----------------------------------------------------------------------------
IMPLEMENT_APP(TheApp)
ServerList *g_ServerList;
// 'Main program' equivalent: the program execution "starts" here
bool TheApp::OnInit()
{
wxImage::AddHandler(new wxPNGHandler());
wxImage::AddHandler(new wxJPEGHandler());
g_ServerList = new ServerList();
g_ServerList->DeleteContents( true );
m_conf = AppConfig::GetInstance();
#ifdef MACOSX
wxApp::s_macHelpMenuTitleName = wxT("&Hjälp");
wxApp::s_macPreferencesMenuItemId = wxID_MENU_PREFERENCES;
#endif
this->m_mframe = new MainFrame(this);
this->m_mframe->Show(true);
// Do this so that the window is fully painted before we start the slow
// process of loading the remote serverlist.
this->m_mframe->Refresh();
this->m_mframe->Update();
if( !GetConfig()->RemoteLoadServerList() )
{
wxMessageBox( wxT("Kunde inte hämta serverlistan från referensservern") );
}
GetConfig()->LoadServerList();
this->m_mframe->RefreshPanels();
return true;
}
int TheApp::OnExit()
{
ResultLog *rlog = ResultLog::GetInstance();
// We need to save results because the user might have removed some manually
// The results are saved after each successfully completed test.
rlog->SaveResults();
delete rlog;
m_conf->SaveServerList();
g_ServerList->Clear();
wxTheClipboard->Flush();
delete m_conf;
delete g_ServerList;
return 0;
}
AppConfig* TheApp::GetConfig()
{
return m_conf;
}
| [
"[email protected]"
]
| [
[
[
1,
82
]
]
]
|
164a77658e74d9b44b6e87996c5844c947ca1e5a | 6bdb3508ed5a220c0d11193df174d8c215eb1fce | /Codes/Halak/Internal/IntersectShapes2D.cpp | 189b7a3ba561a3b110e925ed2c8988c201e68dfd | []
| no_license | halak/halak-plusplus | d09ba78640c36c42c30343fb10572c37197cfa46 | fea02a5ae52c09ff9da1a491059082a34191cd64 | refs/heads/master | 2020-07-14T09:57:49.519431 | 2011-07-09T14:48:07 | 2011-07-09T14:48:07 | 66,716,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,180 | cpp | #include <Halak/PCH.h>
#include <Halak/Internal/IntersectShapes2D.h>
#include <Halak/AxisAlignedBoxShape2D.h>
#include <Halak/BoxShape2D.h>
#include <Halak/Geom2D.h>
#include <Halak/Math.h>
#include <Halak/PointShape2D.h>
#include <Halak/SegmentShape2D.h>
#include <Halak/Shape2D.h>
#include <Halak/SphereShape2D.h>
#include <Halak/UserShape2D.h>
namespace Halak
{
typedef bool (*F)(Shape2D*, Shape2D*);
static const F IntersectFunctionTable[6][6] =
{
{ (F)IntersectShapes2D::PointPoint, (F)IntersectShapes2D::PointSegment, (F)IntersectShapes2D::PointSphere, (F)IntersectShapes2D::PointAxisAlignedBox, (F)IntersectShapes2D::PointBox, (F)IntersectShapes2D::PointUserShape },
{ nullptr, (F)IntersectShapes2D::SegmentSegment, (F)IntersectShapes2D::SegmentSphere, (F)IntersectShapes2D::SegmentAxisAlignedBox, (F)IntersectShapes2D::SegmentBox, (F)IntersectShapes2D::SegmentUserShape },
{ nullptr, nullptr, (F)IntersectShapes2D::SphereSphere, (F)IntersectShapes2D::SphereAxisAlignedBox, (F)IntersectShapes2D::SphereBox, (F)IntersectShapes2D::SphereUserShape },
{ nullptr, nullptr, nullptr, (F)IntersectShapes2D::AxisAlignedBoxAxisAlignedBox, (F)IntersectShapes2D::AxisAlignedBoxBox, (F)IntersectShapes2D::AxisAlignedBoxUserShape },
{ nullptr, nullptr, nullptr, nullptr, (F)IntersectShapes2D::BoxBox, (F)IntersectShapes2D::BoxUserShape },
{ nullptr, nullptr, nullptr, nullptr, nullptr, (F)IntersectShapes2D::UserShapeUserShape },
};
bool IntersectShapes2D::Test(Shape2D* left, Shape2D* right)
{
if (left == nullptr || right == nullptr)
return false;
if (static_cast<int>(left->GetType()) < static_cast<int>(right->GetType()))
return IntersectFunctionTable[left->GetType()][right->GetType()](left, right);
else
return IntersectFunctionTable[right->GetType()][left->GetType()](right, left);
}
bool IntersectShapes2D::PointPoint(PointShape2D* left, PointShape2D* right)
{
return Math::Equals(left->GetPosition(), right->GetPosition());
}
bool IntersectShapes2D::PointSegment(PointShape2D* left, SegmentShape2D* right)
{
return Geom2D::IntersectPointSegment(left->GetPosition(), right->GetStartPoint(), right->GetEndPoint());
}
bool IntersectShapes2D::PointSphere(PointShape2D* left, SphereShape2D* right)
{
return Vector2::GetDistanceSquared(left->GetPosition(), right->GetPosition()) <= right->GetScaledRadiusSquared();
}
bool IntersectShapes2D::PointAxisAlignedBox(PointShape2D* left, AxisAlignedBoxShape2D* right)
{
const Vector2 point = left->GetPosition();
const Vector2 min = right->GetScaledMin();
const Vector2 max = right->GetScaledMax();
return min.X <= point.X && point.X <= max.X &&
min.Y <= point.Y && point.Y <= max.Y;
}
bool IntersectShapes2D::PointBox(PointShape2D* left, BoxShape2D* right)
{
return Geom2D::IntersectPointBox(left->GetPosition(), right->GetCenter(), right->GetRotatedOrientation(), right->GetRotatedUp(), right->GetScaledExtension());
}
bool IntersectShapes2D::PointUserShape(PointShape2D* left, UserShape2D* right)
{
if (right->GetUserShape())
return right->GetUserShape()->IntersectPoint(right, left->GetPosition());
else
return false;
}
bool IntersectShapes2D::SegmentSegment(SegmentShape2D* left, SegmentShape2D* right)
{
return Geom2D::IntersectSegmentSegment(left->GetStartPoint(), left->GetEndPoint(), right->GetStartPoint(), right->GetEndPoint());
}
bool IntersectShapes2D::SegmentSphere(SegmentShape2D* left, SphereShape2D* right)
{
return Geom2D::GetPointSegmentDistanceSquared(right->GetPosition(), left->GetStartPoint(), left->GetEndPoint()) <= right->GetScaledRadiusSquared();
}
bool IntersectShapes2D::SegmentAxisAlignedBox(SegmentShape2D* left, AxisAlignedBoxShape2D* right)
{
return Geom2D::IntersectSegmentAxisAlignedBox(left->GetStartPoint(), left->GetEndPoint(), right->GetScaledMin(), right->GetScaledMax());
}
bool IntersectShapes2D::SegmentBox(SegmentShape2D* /*left*/, BoxShape2D* /*right*/)
{
return false;
}
bool IntersectShapes2D::SegmentUserShape(SegmentShape2D* left, UserShape2D* right)
{
if (right->GetUserShape())
return right->GetUserShape()->IntersectSegment(right, left->GetStartPoint(), left->GetEndPoint());
else
return false;
}
bool IntersectShapes2D::SphereSphere(SphereShape2D* left, SphereShape2D* right)
{
const float scaledRadiusSum = left->GetScaledRadius() + right->GetScaledRadius();
return Vector2::GetDistanceSquared(left->GetPosition(), right->GetPosition()) <= (scaledRadiusSum * scaledRadiusSum);
}
bool IntersectShapes2D::SphereAxisAlignedBox(SphereShape2D* left, AxisAlignedBoxShape2D* right)
{
return Geom2D::GetPointAxisAlignedBoxDistanceSquared(left->GetPosition(), right->GetScaledMin(), right->GetScaledMax()) <= left->GetScaledRadiusSquared();
}
bool IntersectShapes2D::SphereBox(SphereShape2D* left, BoxShape2D* right)
{
const Vector2 closestPoint = Geom2D::GetPointBoxClosestPoint(left->GetPosition(), right->GetCenter(), right->GetRotatedOrientation(), right->GetRotatedUp(), right->GetScaledExtension());
return Vector2::GetDistanceSquared(closestPoint, left->GetPosition()) <= left->GetScaledRadiusSquared();
}
bool IntersectShapes2D::SphereUserShape(SphereShape2D* left, UserShape2D* right)
{
if (right->GetUserShape())
return right->GetUserShape()->IntersectSphere(right, left->GetPosition(), left->GetScaledRadius());
else
return false;
}
bool IntersectShapes2D::AxisAlignedBoxAxisAlignedBox(AxisAlignedBoxShape2D* left, AxisAlignedBoxShape2D* right)
{
return Geom2D::IntersectAxisAlignedBoxAxisAlignedBox(left->GetScaledMin(), left->GetScaledMax(), right->GetScaledMax(), right->GetScaledMax());
}
bool IntersectShapes2D::AxisAlignedBoxBox(AxisAlignedBoxShape2D* /*left*/, BoxShape2D* /*right*/)
{
return false;
}
bool IntersectShapes2D::AxisAlignedBoxUserShape(AxisAlignedBoxShape2D* left, UserShape2D* right)
{
if (right->GetUserShape())
return right->GetUserShape()->IntersectAxisAlignedBox(right, left->GetScaledMin(), left->GetScaledMax());
else
return false;
}
bool IntersectShapes2D::BoxBox(BoxShape2D* left, BoxShape2D* right)
{
return Geom2D::IntersectBoxBox(left->GetCenter(), left->GetRotatedOrientation(), left->GetScaledExtension(), right->GetCenter(), right->GetRotatedOrientation(), right->GetScaledExtension());;
}
bool IntersectShapes2D::BoxUserShape(BoxShape2D* left, UserShape2D* right)
{
if (right->GetUserShape())
return right->GetUserShape()->IntersectBox(right, left->GetCenter(), left->GetRotatedOrientation(), left->GetRotatedUp(), left->GetExtension());
else
return false;
}
bool IntersectShapes2D::UserShapeUserShape(UserShape2D* left, UserShape2D* right)
{
if (left->GetUserShape() && right->GetUserShape())
return left->GetUserShape()->IntersectUserShape(left, right->GetUserShape().GetPointee());
else
return false;
}
} | [
"[email protected]"
]
| [
[
[
1,
166
]
]
]
|
8fc538610e1e5f24e5b5edf1e207e0c725ca2ca0 | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /shared/src/win_io.cpp | b1607b499dfa079229d5c499ccf3950162a823b6 | [
"LicenseRef-scancode-public-domain"
]
| permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,017 | cpp | #define NOMINMAX
#include "win_io.h"
#include <iostream>
#include <stdexcept>
using namespace std;
#ifndef NO_MCC
#include <cbw.h>
void InitMCC_once()
{
static int nCalls = 0;
if(!nCalls)
{
float RevLevel = (float)CURRENTREVNUM;
/* Declare UL Revision Level */
cbDeclareRevision(&RevLevel);
/* Initiate error handling
Parameters:
PRINTALL :all warnings and errors encountered will be printed
DONTSTOP :program will continue even if error occurs.
Note that STOPALL and STOPFATAL are only effective in
Windows applications, not Console applications.
*/
cbErrHandling (PRINTALL, DONTSTOP);
nCalls++;
}
}
MCC_analog_in::MCC_analog_in(int BoardNum) :
analog_in(4),
BoardNum(BoardNum),
data(4)
{
InitMCC_once();
}
void MCC_analog_in::getData()
{
// int cbAInScan(int BoardNum, int LowChan, int HighChan, long Count, long *Rate, int Range, int MemHandle, int Options)
long Rate = 1200;
int ULstat = cbAInScan(BoardNum, 0, data.size()-1, data.size(), &Rate, BIP5VOLTS, &(data[0]), FOREGROUND);
if(ULstat != 0)
cout << "[MCC_analog_in::getData] cbAInScan ERROR: " << ULstat << endl;
for(unsigned i=0; i<data.size(); i++)
values[i] = 5.0 * (data[i] / 2048.0 - 1);
}
MCC_analog_digital_out::MCC_analog_digital_out(int BoardNum) : BoardNum(BoardNum)
{
InitMCC_once();
//confiog digital output
int PortNum = FIRSTPORTA;
int Direction = DIGITALOUT;
cbDConfigPort (BoardNum, PortNum, Direction);
}
void MCC_analog_digital_out::setOutputs(const std::valarray<double>& analog, unsigned digital)
{
// int cbAOutScan(int BoardNum, int LowChan, int HighChan,
// long NumPoints, long *Rate, int Range, int MemHandle, int Options)
int ULstat = cbDOut(BoardNum, FIRSTPORTA, (unsigned char)(digital & 0xFF));
if(ULstat != 0)
cout << "[MCC_analog_in::setOutputs] cbDOut ERROR" << endl;
valarray<short> DAData(analog.size());
for(unsigned i=0; i<analog.size(); i++)
DAData[i] = (short)(0.5 + (2.5+analog[i]) * 0.2 * 1024);
long Rate = 1000; /* sampling rate (samples per second) */
int Options = FOREGROUND | SINGLEEXEC; /* data collection options */
ULstat = cbAOutScan(BoardNum, 0, 1, 2, &Rate, BIP5VOLTS, &(DAData[0]), Options);
if(ULstat != 0)
cout << "[MCC_analog_in::setOutputs] cbAOutScan ERROR" << endl;
}
#endif
#ifndef NO_NIDAQ
void DAQmxErrChk(int e)
{
if( DAQmxFailed(e) )
{
char errBuff[2048];
DAQmxGetExtendedErrorInfo(errBuff,2048);
cout << "DAQmx Error: " << errBuff << endl;
throw runtime_error(errBuff);
}
}
NI_analog_in::NI_analog_in(const std::string& channels, double minV, double maxV) :
analog_in(4),
taskHandleAI(0),
data(0.0, 10000)
{
try
{
DAQmxErrChk (DAQmxCreateTask("",&taskHandleAI));
DAQmxErrChk (DAQmxCreateAIVoltageChan(taskHandleAI,channels.c_str(),"",DAQmx_Val_Cfg_Default,minV,maxV,DAQmx_Val_Volts,NULL));
DAQmxErrChk (DAQmxCfgSampClkTiming(taskHandleAI,NULL,1250,DAQmx_Val_Rising,DAQmx_Val_ContSamps,data.size()/4));
DAQmxErrChk (DAQmxSetRealTimeReportMissedSamp(taskHandleAI, false)); //don't report an error for missed input samples
}
catch(runtime_error e) {}
}
int NI_analog_in::getData()
{
int32 read = 0;
try
{
//read in all available new data
DAQmxErrChk (DAQmxReadAnalogF64(taskHandleAI,-1,10.0,DAQmx_Val_GroupByScanNumber,&(data[0]),data.size(),&read,NULL));
for(unsigned i=0; i<values.size(); i++)
values[i] = data[i];
}
catch(runtime_error e)
{
//restart task on error
// stop();
// start();
// ignore errors
}
return read;
}
void NI_analog_in::start()
{
try
{
DAQmxErrChk (DAQmxStartTask(taskHandleAI));
}
catch(runtime_error e) {}
}
void NI_analog_in::stop()
{
try
{
DAQmxErrChk (DAQmxStopTask(taskHandleAI));
}
catch(runtime_error e) {}
}
NI_analog_out::NI_analog_out(const std::string& Achannels, unsigned numAO,
double minV, double maxV, double offset) :
analog_out(numAO),
minV(minV),
maxV(maxV),
offset(offset)
{
try
{
DAQmxErrChk (DAQmxCreateTask("",&taskHandleAO));
DAQmxErrChk (DAQmxCreateAOVoltageChan(taskHandleAO,Achannels.c_str(),"",minV,maxV,DAQmx_Val_Volts,""));
DAQmxErrChk (DAQmxStartTask(taskHandleAO));
}
catch(runtime_error e) {}
}
void NI_analog_out::updateAnalogOutputs()
{
//do analog update if values have changed
valarray<bool> check_equalAO(new_aOut.size());
check_equalAO = (new_aOut == old_aOut);
if(check_equalAO.min() == false)
{
old_aOut = new_aOut;
valarray<int32> written(new_aOut.size());
valarray<double> a_o(new_aOut.size());
//shift range from -2.5 ... 2.5 to 0 ... 5 V (for NI USB6008)
for(unsigned i=0; i<new_aOut.size(); i++)
a_o[i] = offset+new_aOut[i];
try
{
DAQmxErrChk (DAQmxWriteAnalogF64(taskHandleAO,1,0,10.0,DAQmx_Val_GroupByChannel,&(a_o[0]),&(written[0]),NULL));
}
catch(runtime_error e) {}
}
}
NI_digital_out::NI_digital_out(const std::string& Dchannels, unsigned numDO) :
digital_out(numDO)
{
try
{
DAQmxErrChk (DAQmxCreateTask("",&taskHandleDO));
DAQmxErrChk (DAQmxCreateDOChan(taskHandleDO,Dchannels.c_str(),"",DAQmx_Val_ChanForAllLines));
DAQmxErrChk (DAQmxStartTask(taskHandleDO));
}
catch(runtime_error e) {}
}
bool NI_digital_out::updateDigitalOutputs()
{
bool bDifferent = false;
unsigned dOut = 0;
for(unsigned i=0; i<new_dOut.size(); i++)
{
if(new_dOut[i])
dOut |= (1 << i);
if(old_dOut[i] != new_dOut[i])
{
bDifferent = true;
old_dOut[i] = new_dOut[i];
}
}
//do digital update if values have changed
if(bDifferent)
{
uInt8 d_o = (unsigned char)(dOut & 0xFF);
try
{
DAQmxErrChk (DAQmxWriteDigitalU8(taskHandleDO,1,1,10.0,DAQmx_Val_GroupByChannel,&d_o,NULL,NULL));
}
catch(runtime_error e) {}
return true;
}
return false;
}
#endif // NO_NIDAQ
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
]
| [
[
[
1,
256
]
]
]
|
dc58d8ef54011d94f5efd2d910e16557f6b5c7b0 | 6477cf9ac119fe17d2c410ff3d8da60656179e3b | /Projects/openredalert/src/ui/RA_Label.cpp | 5fb54ad2916584129c7173904d47a89925bdf23d | []
| 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 | 7,172 | cpp | // RA_Label.cpp
// 1.5
// 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 "RA_Label.h"
#include <string>
#include "video/GraphicsEngine.h"
#include "Font.h"
#include "RaWindow.h"
using std::string;
namespace pc {
extern GraphicsEngine * gfxeng;
}
RA_Label::RA_Label() :
LabelFont("type.fnt")
{
// Setup some vars
Checked = false;
Width = 20,
Heigth = 20;
LabelSurface = 0;
LabelText = "Uninitialize";
DrawingSurface = 0;
DrawingWindow = 0;
BackgroundBackup = 0;
// Initialize the display surface pointer
// SetDrawingSurface (pc::gfxeng->get_SDL_ScreenSurface());
// Initialize the checkbox color
LabelFontColor.r = 0;
LabelFontColor.g = 0;
LabelFontColor.b = 0xff;
ColorKeyColor.r = ColorKeyColor.g = ColorKeyColor.b = 0;
LabelDest.x = 0;
LabelDest.y = 0;
}
/**
*
*/
RA_Label::~RA_Label()
{
if (LabelSurface != 0)
{
SDL_FreeSurface(LabelSurface);
}
if (BackgroundBackup != 0)
{
SDL_FreeSurface(BackgroundBackup);
}
LabelSurface = 0;
}
Uint32 RA_Label::getHeight()
{
return LabelFont.getHeight();
}
Uint32 RA_Label::getWidth()
{
return LabelFont.calcTextWidth(LabelText);
}
Uint32 RA_Label::getWidth(const string text){
return LabelFont.calcTextWidth(text);
}
string RA_Label::getText(){
return LabelText;
}
void RA_Label::setColor(SDL_Color RGBcolor)
{
if (BackgroundBackup != 0 && DrawingWindow != 0)
{
SDL_BlitSurface(BackgroundBackup, NULL, DrawingWindow->GetWindowSurface (), &LabelDest);
SDL_FreeSurface(BackgroundBackup);
BackgroundBackup = NULL;
}
if ( RGBcolor.r != LabelFontColor.r || RGBcolor.g != LabelFontColor.g || RGBcolor.b != LabelFontColor.b ){
memcpy (&LabelFontColor, &RGBcolor, sizeof (SDL_Color));
recreate = true;
}
}
void RA_Label::setColor(Uint32 color)
{
SDL_Color RGBcolor;
if (LabelSurface != NULL){
SDL_GetRGB(color, pc::gfxeng->get_SDL_ScreenSurface()->format, &RGBcolor.r, &RGBcolor.g, &RGBcolor.b );
setColor(RGBcolor);
}
}
void RA_Label::setColor (Uint8 r, Uint8 g, Uint8 b)
{
SDL_Color RGBcolor;
RGBcolor.r = r;
RGBcolor.g = g;
RGBcolor.b = b;
setColor(RGBcolor);
}
void RA_Label::SetDrawingSurface (SDL_Surface *DwgSurface)
{
if (DrawingSurface != DwgSurface){
DrawingWindow = NULL;
DrawingSurface = DwgSurface;
recreate = true;
}
}
void RA_Label::SetDrawingWindow(RaWindow* window)
{
if (DrawingWindow != window)
{
DrawingWindow = window;
DrawingSurface = 0;
recreate = true;
}
}
void RA_Label::UseAntiAliasing(bool status)
{
LabelFont.UseAntiAliasing(status);
recreate = true;
}
void RA_Label::underline(bool status)
{
LabelFont.underline(status);
recreate = true;
}
void RA_Label::Draw(int X, int Y)
{
SDL_Rect BackupDest;
// Recreate the text if we draw it somewhere else
if (LabelDest.x != X || LabelDest.y != Y)
recreate = true;
// Init LabelDest
LabelDest.x = X;
LabelDest.y = Y;
LabelDest.w = Width;
LabelDest.h = Heigth;
// Recreate the Label surface if needed
if (recreate)
Create();
if (LabelSurface == 0)
return;
if (DrawingSurface == 0 && DrawingWindow == 0)
return;
if (DrawingSurface != NULL){
SDL_BlitSurface(LabelSurface, NULL, DrawingSurface, &LabelDest);
}
else if (DrawingWindow != NULL)
{
if (BackgroundBackup == NULL){
BackgroundBackup = SDL_CreateRGBSurface(SDL_SWSURFACE|SDL_SRCCOLORKEY, LabelDest.w, LabelFont.getHeight(), 16, 0, 0, 0, 0);
BackupDest.x = 0; BackupDest.y = 0; BackupDest.w = LabelDest.w; BackupDest.h = LabelDest.h;
SDL_BlitSurface(DrawingWindow->GetWindowSurface (), &LabelDest, BackgroundBackup, &BackupDest);
SDL_BlitSurface(LabelSurface, NULL, DrawingWindow->GetWindowSurface (), &LabelDest);
} else {
SDL_BlitSurface(BackgroundBackup, NULL, DrawingWindow->GetWindowSurface (), &LabelDest);
SDL_BlitSurface(LabelSurface, NULL, DrawingWindow->GetWindowSurface (), &LabelDest);
}
}
}
void RA_Label::Draw(SDL_Surface *DrawingSurface, int X, int Y)
{
SetDrawingSurface(DrawingSurface);
Draw(X, Y);
}
void RA_Label::Draw(const string& text, SDL_Surface *DrawingSurface, int X, int Y)
{
setText(text);
SetDrawingSurface(DrawingSurface);
Draw(X, Y);
}
void RA_Label::Draw(const string& text, SDL_Surface *DrawingSurface, SDL_Color Fcolor, int X, int Y)
{
setText(text);
setColor(Fcolor);
SetDrawingSurface(DrawingSurface);
Draw(X, Y);
}
void RA_Label::Redraw()
{
Draw(LabelDest.x, LabelDest.y);
}
void RA_Label::Create()
{
SDL_Rect dest;
SDL_Surface *tmp;
if (LabelSurface != NULL)
SDL_FreeSurface(LabelSurface);
if (BackgroundBackup != NULL && DrawingWindow != NULL){
SDL_BlitSurface(BackgroundBackup, NULL, DrawingWindow->GetWindowSurface (), &LabelDest);
SDL_FreeSurface(BackgroundBackup);
BackgroundBackup = NULL;
}
LabelSurface = NULL;
if (LabelText.length() == 0)
return;
Width = LabelFont.calcTextWidth(LabelText) + 4;
Heigth = LabelFont.getHeight()+4;
LabelSurface = SDL_CreateRGBSurface(SDL_SWSURFACE|SDL_SRCCOLORKEY, Width, Heigth, 16, 0, 0, 0, 0);
// this is the destination as needed for the new surface
dest.x = 0;
dest.y = 0;
dest.w = Width;
dest.h = Heigth;
// Fill the surface with the correct color
SDL_FillRect(LabelSurface, &dest, SDL_MapRGB( LabelSurface->format, ColorKeyColor.r, ColorKeyColor.g, ColorKeyColor.b ));
if (DrawingSurface != NULL)
LabelFont.drawText(LabelText, DrawingSurface, LabelDest.x, LabelDest.y, LabelSurface, LabelFontColor, 0, 0);
else if (DrawingWindow != NULL){
LabelFont.drawText(LabelText, DrawingWindow->GetWindowSurface(), LabelDest.x, LabelDest.y, LabelSurface, LabelFontColor, 0, 0);
}
SDL_SetColorKey(LabelSurface, SDL_SRCCOLORKEY, 0);
// SDL_SetAlpha(LabelSurface, SDL_SRCALPHA, 150);
tmp = SDL_DisplayFormat(LabelSurface);
SDL_FreeSurface(LabelSurface);
LabelSurface = tmp;
recreate = false;
}
void RA_Label::setText(const string text)
{
if (LabelText != text)
{
if (BackgroundBackup != NULL && DrawingWindow != NULL)
{
SDL_BlitSurface(BackgroundBackup, NULL, DrawingWindow->GetWindowSurface (), &LabelDest);
SDL_FreeSurface(BackgroundBackup);
BackgroundBackup = NULL;
}
LabelText = text;
recreate = true;
}
}
/**
* Set the font of the Label
*/
void RA_Label::SetFont(const string FontName)
{
LabelFont.Load(FontName);
recreate = true;
}
| [
"[email protected]"
]
| [
[
[
1,
300
]
]
]
|
a6f096d4b731ce837dff13559548cd87ac28b6c7 | 7f30cb109e574560873a5eb8bb398c027f85eeee | /src/infoFilter.cxx | 223a44c91ab41ad704fa4a24c41629b069a8dd70 | []
| no_license | svn2github/MITO | e8fd0e0b6eebf26f2382f62660c06726419a9043 | 71d1269d7666151df52d6b5a98765676d992349a | refs/heads/master | 2021-01-10T03:13:55.083371 | 2011-10-14T15:40:14 | 2011-10-14T15:40:14 | 47,415,786 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,610 | cxx | /**
* \file infoFilter.cxx
* \brief File per la gestione delle informazioni sulle immagini
* \author ICAR-CNR Napoli
*/
#include "infoFilter.h"
infoFilter::infoFilter(unsigned int idData, dataHandler *dataHandler, int sliceNumber) : itkVtkFilter(idData, dataHandler) {
_sliceNumber = sliceNumber;
}
infoFilter::~infoFilter() {
}
ImageType::PointType infoFilter::getImageOrigin() {
if (isValidData()) {
if(!getItkVtkData()->getRgb()) return getItkVtkData()->getItkImage()->GetOrigin();
else return getItkVtkData()->getItkRgbImage()->GetOrigin();
}
return NULL;
}
ImageType::SpacingType infoFilter::getSpacingType() {
if(!getItkVtkData()->getRgb()) return getItkVtkData()->getItkImage()->GetSpacing();
else return getItkVtkData()->getItkRgbImage()->GetSpacing();
}
double infoFilter::getCurrentX(double xPos) {
if (isValidData()) {
return (xPos - getImageOrigin()[0])/getSpacingType()[0];
}
return 0;
}
double infoFilter::getCurrentY(double yPos) {
if (isValidData()) {
return (yPos - getImageOrigin()[1])/getSpacingType()[1];
}
return 0;
}
PixelType infoFilter::getPixelValue(double x, double y) {
if (isValidData()) {
ImageType::IndexType pixelIndex;
pixelIndex[0] = x;
pixelIndex[1] = y;
ImageType::SizeType size = getItkVtkData()->getItkImage()->GetLargestPossibleRegion().GetSize();
if (size[2] == 1)
pixelIndex[2] = 0;
else
pixelIndex[2] = _sliceNumber;
PixelType pixelValue = 0;
if (x >= 0 && x < size[0] && y >= 0 && y < size[1])
pixelValue = getItkVtkData()->getItkImage()->GetPixel(pixelIndex);
return pixelValue;
}
return NULL;
}
RGBPixelType infoFilter::getPixelValueRgb(double x, double y) {
RGBPixelType pixelValueRgb;
if (isValidData()) {
RGBImageType::IndexType pixelIndex;
pixelIndex[0] = x;
pixelIndex[1] = y;
RGBImageType::SizeType size = getItkVtkData()->getItkRgbImage()->GetLargestPossibleRegion().GetSize();
if (size[2] == 1)
pixelIndex[2] = 0;
else
pixelIndex[2] = _sliceNumber;
if (x >= 0 && x <= size[0] && y >= 0 && y <= size[1])
pixelValueRgb = getItkVtkData()->getItkRgbImage()->GetPixel(pixelIndex);
return pixelValueRgb;
}
else {
pixelValueRgb.SetRed(0);
pixelValueRgb.SetGreen(0);
pixelValueRgb.SetBlue(0);
}
return pixelValueRgb;
}
ImageType::IndexType infoFilter::getXY(double x, double y) {
ImageType::IndexType seed;
seed[0] = 0;
seed[1] = 0;
seed[2] = 0;
if (isValidData()) {
seed[0] = (long)x;
seed[1] = (long)y;
seed[2] = _sliceNumber;
}
return seed;
} | [
"kg_dexterp37@fde90bc1-0431-4138-8110-3f8199bc04de"
]
| [
[
[
1,
101
]
]
]
|
77a0283cac62eb2d430a805daec8c8b6ee12f1eb | 96e96a73920734376fd5c90eb8979509a2da25c0 | /C3DE/ShadowSurface.h | 786ee61e11e47fa883359f73be4cb0b44dc615f3 | []
| no_license | lianlab/c3de | 9be416cfbf44f106e2393f60a32c1bcd22aa852d | a2a6625549552806562901a9fdc083c2cacc19de | refs/heads/master | 2020-04-29T18:07:16.973449 | 2009-11-15T10:49:36 | 2009-11-15T10:49:36 | 32,124,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 245 | h | #ifndef SHADOW_SURFACE_H
#define SHADOW_SURFACE_H
#include "Mesh.h"
class ShadowSurface
{
public:
ShadowSurface(Mesh *);
virtual ~ShadowSurface();
Mesh * GetMesh(){return m_mesh;}
protected:
Mesh *m_mesh;
};
#endif
| [
"caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158"
]
| [
[
[
1,
19
]
]
]
|
2db93efd45159bd3b16df9b97398d2da26ad079f | 09ea547305ed8be9f8aa0dc6a9d74752d660d05d | /Tests/SmfMusicEventsnService/SmfMusicEventsnService.h | 5f58c89fcae17d1019bc543a1ed3e62bedf34f80 | []
| no_license | SymbianSource/oss.FCL.sf.mw.socialmobilefw | 3c49e1d1ae2db8703e7c6b79a4c951216c9c5019 | 7020b195cf8d1aad30732868c2ed177e5459b8a8 | refs/heads/master | 2021-01-13T13:17:24.426946 | 2010-10-12T09:53:52 | 2010-10-12T09:53:52 | 72,676,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,770 | h | /****************************************************************************
**
** Trolltech hereby grants a license to use the Qt/Eclipse Integration
** plug-in (the software contained herein), in binary form, solely for the
** purpose of creating code to be used with Trolltech's Qt software.
**
** Qt Designer is licensed under the terms of the GNU General Public
** License versions 2.0 and 3.0 ("GPL License"). Trolltech offers users the
** right to use certain no GPL licensed software under the terms of its GPL
** Exception version 1.2 (http://trolltech.com/products/qt/gplexception).
**
** THIS SOFTWARE IS PROVIDED BY TROLLTECH AND ITS CONTRIBUTORS (IF ANY) "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."
**
** Since we now have the GPL exception I think that the "special exception
** is no longer needed. The license text proposed above (other than the
** special exception portion of it) is the BSD license and we have added
** the BSD license as a permissible license under the exception.
**
****************************************************************************/
#ifndef SMFTESTAPP_H
#define SMFTESTAPP_H
#include <QtGui/QWidget>
#include <smfprovider.h>
#include <smfcontact.h>
#include <smfglobal.h>
#include <qcontactguid.h>
#include "ui_SmfMusicEventsnService.h"
#include <smfactivityfetcher.h>
#include <smfmusic.h>
class SmfContactFetcher;
class SmfTestApp : public QWidget
{
Q_OBJECT
public:
SmfTestApp(QWidget *parent = 0);
~SmfTestApp();
void getFacebookFriends();
void getTracksOfArtists();
void FacebookFiltered();
void lastFm();
void FacebookActivities();
private slots:
void friendsListAvailable ( SmfContactList* list, SmfError error, SmfResultPage resultPage );
void resultsAvailableSlot(SmfActivityEntryList * _t1, SmfError _t2, SmfResultPage _t3);
void userMusicInfoAvlbl(SmfMusicProfile*,SmfError);
private:
Ui::SmfTestApp ui;
SmfContactFetcher *m_contactFetcher;
SmfProviderList *m_providerList;
};
#endif // SMFTESTAPP_H
| [
"none@none"
]
| [
[
[
1,
70
]
]
]
|
fbce1a47e7790e82b500481febb1ced5cbda15af | dda0d7bb4153bcd98ad5e32e4eac22dc974b8c9d | /thirdparty/udtEx/app/sendfile.cpp | 28dc1a9ec5f5fe7badff701cb29b06a7fb35d0a7 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | systembugtj/crash-report | abd45ceedc08419a3465414ad9b3b6a5d6c6729a | 205b087e79eb8ed7a9b6a7c9f4ac580707e9cb7e | refs/heads/master | 2021-01-19T07:08:04.878028 | 2011-04-05T04:03:54 | 2011-04-05T04:03:54 | 35,228,814 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,128 | cpp | #ifndef WIN32
#include <cstdlib>
#else
#include <winsock2.h>
#include <ws2tcpip.h>
#endif
#include <fstream>
#include <iostream>
#include <cstring>
#include <udt.h>
#include <sys/types.h>//_stat ,_stat64
#include <sys/stat.h>
using namespace std;
int main( )
{
// use this function to initialize the UDT library
UDT::startup();
UDTSOCKET serv = UDT::socket(AF_INET, SOCK_STREAM, 0);
// Windows UDP issue
// For better performance, modify HKLM\System\CurrentControlSet\Services\Afd\Parameters\FastSendDatagramThreshold
#ifdef WIN32
int mss = 1052;
UDT::setsockopt(serv, 0, UDT_MSS, &mss, sizeof(int));
#endif
int port = 9000;
sockaddr_in my_addr;
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(port);
my_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(my_addr.sin_zero), '\0', 8);
if (UDT::ERROR == UDT::bind(serv, (sockaddr*)&my_addr, sizeof(my_addr)))
{
cout << "bind: " << UDT::getlasterror().getErrorMessage() << endl;
return 0;
}
cout << "server is ready at port: " << port << endl;
UDT::listen(serv, 1);
sockaddr_in their_addr;
int namelen = sizeof(their_addr);
UDTSOCKET fhandle;
if (UDT::INVALID_SOCK == (fhandle = UDT::accept(serv, (sockaddr*)&their_addr, &namelen)))
{
cout << "accept: " << UDT::getlasterror().getErrorMessage() << endl;
return 0;
}
UDT::close(serv);
// aquiring file name information from client
char file[1024];
int len;
if (UDT::ERROR == UDT::recv(fhandle, (char*)&len, sizeof(int), 0))
{
cout << "recv: " << UDT::getlasterror().getErrorMessage() << endl;
return 0;
}
if (UDT::ERROR == UDT::recv(fhandle, file, len, 0))
{
cout << "recv: " << UDT::getlasterror().getErrorMessage() << endl;
return 0;
}
file[len] = '\0';
// open the file
//fstream ifs(file, ios::in | ios::binary);
FILE* fp =fopen(file ,"r+");
if (fp==NULL)
{
cout<<"fail to open file "<<endl;
return -1;
}
//以下代码不能处理超过2G的文件大小
//ifs.seekg(0, ios::end);
//int64_t size = ifs.tellg();//这里出现问题
//cout<<"size = "<<size<<endl;
//system("pause");
//ifs.seekg(0, ios::beg);
struct __stat64 filestat;
_stat64(file ,&filestat );
int64_t size=filestat.st_size;
// send file size information
if (UDT::ERROR == UDT::send(fhandle, (char*)&size, sizeof(int64_t), 0))
{
cout << "send: " << UDT::getlasterror().getErrorMessage() << endl;
return 0;
}
int64_t sendsize;
int64_t leftsize=size;
const int64_t block_size=1024*1024*10;//10M/per time
int64_t offset=0;
while (leftsize>0)
{
int64_t thisblock=(leftsize> block_size)? block_size:leftsize;
// send the file
if (UDT::ERROR ==(sendsize= UDT::mysendfile(fhandle, fp, offset, thisblock)) )
{
cout << "sendfile: " << UDT::getlasterror().getErrorMessage() << endl;
return 0;
}
leftsize -= sendsize;
offset += sendsize;
cout<<".";//代表进度
}
UDT::close(fhandle);
fclose(fp);
//ifs.close();
// use this function to release the UDT library
UDT::cleanup();
return 1;
}
| [
"[email protected]@9307afbf-8b4c-5d34-949b-c69a0924eb0b"
]
| [
[
[
1,
138
]
]
]
|
4125f07a3d03cf14817cebe96576c69e50f850b0 | 5750620062af54ed24792c39d0bf19a6f8f1e3bf | /src/uint256.h | 11128d56c6630bf78b40d54b4b286a9ece1fbb12 | []
| no_license | makomk/soldcoin | 4088e49928efe7436eee8bae40b0b1b9ce9e2720 | f964acdd1a76d58f7e27e386fffbed22a1916307 | refs/heads/master | 2021-01-17T22:18:53.603480 | 2011-09-04T19:29:57 | 2011-09-04T19:29:57 | 2,344,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,560 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2011 The SolidCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef SOLIDCOIN_UINT256_H
#define SOLIDCOIN_UINT256_H
#include "serialize.h"
#include <limits.h>
#include <string>
#include <vector>
#if defined(_MSC_VER) || defined(__BORLANDC__)
typedef __int64 int64;
typedef unsigned __int64 uint64;
#else
typedef long long int64;
typedef unsigned long long uint64;
#endif
#if defined(_MSC_VER) && _MSC_VER < 1300
#define for if (false) ; else for
#endif
inline int Testuint256AdHoc(std::vector<std::string> vArg);
// We have to keep a separate base class without constructors
// so the compiler will let us use it in a union
template<unsigned int BITS>
class base_uint
{
protected:
enum { WIDTH=BITS/32 };
unsigned int pn[WIDTH];
public:
bool operator!() const
{
for (int i = 0; i < WIDTH; i++)
if (pn[i] != 0)
return false;
return true;
}
const base_uint operator~() const
{
base_uint ret;
for (int i = 0; i < WIDTH; i++)
ret.pn[i] = ~pn[i];
return ret;
}
const base_uint operator-() const
{
base_uint ret;
for (int i = 0; i < WIDTH; i++)
ret.pn[i] = ~pn[i];
ret++;
return ret;
}
base_uint& operator=(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator^=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] ^= b.pn[i];
return *this;
}
base_uint& operator&=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] &= b.pn[i];
return *this;
}
base_uint& operator|=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] |= b.pn[i];
return *this;
}
base_uint& operator^=(uint64 b)
{
pn[0] ^= (unsigned int)b;
pn[1] ^= (unsigned int)(b >> 32);
return *this;
}
base_uint& operator&=(uint64 b)
{
pn[0] &= (unsigned int)b;
pn[1] &= (unsigned int)(b >> 32);
return *this;
}
base_uint& operator|=(uint64 b)
{
pn[0] |= (unsigned int)b;
pn[1] |= (unsigned int)(b >> 32);
return *this;
}
base_uint& operator<<=(unsigned int shift)
{
base_uint a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++)
{
if (i+k+1 < WIDTH && shift != 0)
pn[i+k+1] |= (a.pn[i] >> (32-shift));
if (i+k < WIDTH)
pn[i+k] |= (a.pn[i] << shift);
}
return *this;
}
base_uint& operator>>=(unsigned int shift)
{
base_uint a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++)
{
if (i-k-1 >= 0 && shift != 0)
pn[i-k-1] |= (a.pn[i] << (32-shift));
if (i-k >= 0)
pn[i-k] |= (a.pn[i] >> shift);
}
return *this;
}
base_uint& operator+=(const base_uint& b)
{
uint64 carry = 0;
for (int i = 0; i < WIDTH; i++)
{
uint64 n = carry + pn[i] + b.pn[i];
pn[i] = n & 0xffffffff;
carry = n >> 32;
}
return *this;
}
base_uint& operator-=(const base_uint& b)
{
*this += -b;
return *this;
}
base_uint& operator+=(uint64 b64)
{
base_uint b;
b = b64;
*this += b;
return *this;
}
base_uint& operator-=(uint64 b64)
{
base_uint b;
b = b64;
*this += -b;
return *this;
}
base_uint& operator++()
{
// prefix operator
int i = 0;
while (++pn[i] == 0 && i < WIDTH-1)
i++;
return *this;
}
const base_uint operator++(int)
{
// postfix operator
const base_uint ret = *this;
++(*this);
return ret;
}
base_uint& operator--()
{
// prefix operator
int i = 0;
while (--pn[i] == -1 && i < WIDTH-1)
i++;
return *this;
}
const base_uint operator--(int)
{
// postfix operator
const base_uint ret = *this;
--(*this);
return ret;
}
friend inline bool operator<(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH-1; i >= 0; i--)
{
if (a.pn[i] < b.pn[i])
return true;
else if (a.pn[i] > b.pn[i])
return false;
}
return false;
}
friend inline bool operator<=(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH-1; i >= 0; i--)
{
if (a.pn[i] < b.pn[i])
return true;
else if (a.pn[i] > b.pn[i])
return false;
}
return true;
}
friend inline bool operator>(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH-1; i >= 0; i--)
{
if (a.pn[i] > b.pn[i])
return true;
else if (a.pn[i] < b.pn[i])
return false;
}
return false;
}
friend inline bool operator>=(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH-1; i >= 0; i--)
{
if (a.pn[i] > b.pn[i])
return true;
else if (a.pn[i] < b.pn[i])
return false;
}
return true;
}
friend inline bool operator==(const base_uint& a, const base_uint& b)
{
for (int i = 0; i < base_uint::WIDTH; i++)
if (a.pn[i] != b.pn[i])
return false;
return true;
}
friend inline bool operator==(const base_uint& a, uint64 b)
{
if (a.pn[0] != (unsigned int)b)
return false;
if (a.pn[1] != (unsigned int)(b >> 32))
return false;
for (int i = 2; i < base_uint::WIDTH; i++)
if (a.pn[i] != 0)
return false;
return true;
}
friend inline bool operator!=(const base_uint& a, const base_uint& b)
{
return (!(a == b));
}
friend inline bool operator!=(const base_uint& a, uint64 b)
{
return (!(a == b));
}
std::string GetHex() const
{
char psz[sizeof(pn)*2 + 1];
for (int i = 0; i < sizeof(pn); i++)
sprintf(psz + i*2, "%02x", ((unsigned char*)pn)[sizeof(pn) - i - 1]);
return std::string(psz, psz + sizeof(pn)*2);
}
void SetHex(const char* psz)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
// skip leading spaces
while (isspace(*psz))
psz++;
// skip 0x
if (psz[0] == '0' && tolower(psz[1]) == 'x')
psz += 2;
// hex string to uint
static char phexdigit[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0, 0,0xa,0xb,0xc,0xd,0xe,0xf,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0xa,0xb,0xc,0xd,0xe,0xf,0,0,0,0,0,0,0,0,0 };
const char* pbegin = psz;
while (phexdigit[*psz] || *psz == '0')
psz++;
psz--;
unsigned char* p1 = (unsigned char*)pn;
unsigned char* pend = p1 + WIDTH * 4;
while (psz >= pbegin && p1 < pend)
{
*p1 = phexdigit[(unsigned char)*psz--];
if (psz >= pbegin)
{
*p1 |= (phexdigit[(unsigned char)*psz--] << 4);
p1++;
}
}
}
void SetHex(const std::string& str)
{
SetHex(str.c_str());
}
std::string ToString() const
{
return (GetHex());
}
unsigned char* begin()
{
return (unsigned char*)&pn[0];
}
unsigned char* end()
{
return (unsigned char*)&pn[WIDTH];
}
unsigned int size()
{
return sizeof(pn);
}
unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const
{
return sizeof(pn);
}
template<typename Stream>
void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const
{
s.write((char*)pn, sizeof(pn));
}
template<typename Stream>
void Unserialize(Stream& s, int nType=0, int nVersion=VERSION)
{
s.read((char*)pn, sizeof(pn));
}
friend class uint160;
friend class uint256;
friend inline int Testuint256AdHoc(std::vector<std::string> vArg);
};
typedef base_uint<160> base_uint160;
typedef base_uint<256> base_uint256;
//
// uint160 and uint256 could be implemented as templates, but to keep
// compile errors and debugging cleaner, they're copy and pasted.
//
//////////////////////////////////////////////////////////////////////////////
//
// uint160
//
class uint160 : public base_uint160
{
public:
typedef base_uint160 basetype;
uint160()
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
uint160(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint160& operator=(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
return *this;
}
uint160(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint160& operator=(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
explicit uint160(const std::string& str)
{
SetHex(str);
}
explicit uint160(const std::vector<unsigned char>& vch)
{
if (vch.size() == sizeof(pn))
memcpy(pn, &vch[0], sizeof(pn));
else
*this = 0;
}
};
inline bool operator==(const uint160& a, uint64 b) { return (base_uint160)a == b; }
inline bool operator!=(const uint160& a, uint64 b) { return (base_uint160)a != b; }
inline const uint160 operator<<(const base_uint160& a, unsigned int shift) { return uint160(a) <<= shift; }
inline const uint160 operator>>(const base_uint160& a, unsigned int shift) { return uint160(a) >>= shift; }
inline const uint160 operator<<(const uint160& a, unsigned int shift) { return uint160(a) <<= shift; }
inline const uint160 operator>>(const uint160& a, unsigned int shift) { return uint160(a) >>= shift; }
inline const uint160 operator^(const base_uint160& a, const base_uint160& b) { return uint160(a) ^= b; }
inline const uint160 operator&(const base_uint160& a, const base_uint160& b) { return uint160(a) &= b; }
inline const uint160 operator|(const base_uint160& a, const base_uint160& b) { return uint160(a) |= b; }
inline const uint160 operator+(const base_uint160& a, const base_uint160& b) { return uint160(a) += b; }
inline const uint160 operator-(const base_uint160& a, const base_uint160& b) { return uint160(a) -= b; }
inline bool operator<(const base_uint160& a, const uint160& b) { return (base_uint160)a < (base_uint160)b; }
inline bool operator<=(const base_uint160& a, const uint160& b) { return (base_uint160)a <= (base_uint160)b; }
inline bool operator>(const base_uint160& a, const uint160& b) { return (base_uint160)a > (base_uint160)b; }
inline bool operator>=(const base_uint160& a, const uint160& b) { return (base_uint160)a >= (base_uint160)b; }
inline bool operator==(const base_uint160& a, const uint160& b) { return (base_uint160)a == (base_uint160)b; }
inline bool operator!=(const base_uint160& a, const uint160& b) { return (base_uint160)a != (base_uint160)b; }
inline const uint160 operator^(const base_uint160& a, const uint160& b) { return (base_uint160)a ^ (base_uint160)b; }
inline const uint160 operator&(const base_uint160& a, const uint160& b) { return (base_uint160)a & (base_uint160)b; }
inline const uint160 operator|(const base_uint160& a, const uint160& b) { return (base_uint160)a | (base_uint160)b; }
inline const uint160 operator+(const base_uint160& a, const uint160& b) { return (base_uint160)a + (base_uint160)b; }
inline const uint160 operator-(const base_uint160& a, const uint160& b) { return (base_uint160)a - (base_uint160)b; }
inline bool operator<(const uint160& a, const base_uint160& b) { return (base_uint160)a < (base_uint160)b; }
inline bool operator<=(const uint160& a, const base_uint160& b) { return (base_uint160)a <= (base_uint160)b; }
inline bool operator>(const uint160& a, const base_uint160& b) { return (base_uint160)a > (base_uint160)b; }
inline bool operator>=(const uint160& a, const base_uint160& b) { return (base_uint160)a >= (base_uint160)b; }
inline bool operator==(const uint160& a, const base_uint160& b) { return (base_uint160)a == (base_uint160)b; }
inline bool operator!=(const uint160& a, const base_uint160& b) { return (base_uint160)a != (base_uint160)b; }
inline const uint160 operator^(const uint160& a, const base_uint160& b) { return (base_uint160)a ^ (base_uint160)b; }
inline const uint160 operator&(const uint160& a, const base_uint160& b) { return (base_uint160)a & (base_uint160)b; }
inline const uint160 operator|(const uint160& a, const base_uint160& b) { return (base_uint160)a | (base_uint160)b; }
inline const uint160 operator+(const uint160& a, const base_uint160& b) { return (base_uint160)a + (base_uint160)b; }
inline const uint160 operator-(const uint160& a, const base_uint160& b) { return (base_uint160)a - (base_uint160)b; }
inline bool operator<(const uint160& a, const uint160& b) { return (base_uint160)a < (base_uint160)b; }
inline bool operator<=(const uint160& a, const uint160& b) { return (base_uint160)a <= (base_uint160)b; }
inline bool operator>(const uint160& a, const uint160& b) { return (base_uint160)a > (base_uint160)b; }
inline bool operator>=(const uint160& a, const uint160& b) { return (base_uint160)a >= (base_uint160)b; }
inline bool operator==(const uint160& a, const uint160& b) { return (base_uint160)a == (base_uint160)b; }
inline bool operator!=(const uint160& a, const uint160& b) { return (base_uint160)a != (base_uint160)b; }
inline const uint160 operator^(const uint160& a, const uint160& b) { return (base_uint160)a ^ (base_uint160)b; }
inline const uint160 operator&(const uint160& a, const uint160& b) { return (base_uint160)a & (base_uint160)b; }
inline const uint160 operator|(const uint160& a, const uint160& b) { return (base_uint160)a | (base_uint160)b; }
inline const uint160 operator+(const uint160& a, const uint160& b) { return (base_uint160)a + (base_uint160)b; }
inline const uint160 operator-(const uint160& a, const uint160& b) { return (base_uint160)a - (base_uint160)b; }
//////////////////////////////////////////////////////////////////////////////
//
// uint256
//
class uint256 : public base_uint256
{
public:
typedef base_uint256 basetype;
uint256()
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint256& operator=(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
return *this;
}
uint256(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint256& operator=(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
explicit uint256(const std::string& str)
{
SetHex(str);
}
explicit uint256(const std::vector<unsigned char>& vch)
{
if (vch.size() == sizeof(pn))
memcpy(pn, &vch[0], sizeof(pn));
else
*this = 0;
}
};
inline bool operator==(const uint256& a, uint64 b) { return (base_uint256)a == b; }
inline bool operator!=(const uint256& a, uint64 b) { return (base_uint256)a != b; }
inline const uint256 operator<<(const base_uint256& a, unsigned int shift) { return uint256(a) <<= shift; }
inline const uint256 operator>>(const base_uint256& a, unsigned int shift) { return uint256(a) >>= shift; }
inline const uint256 operator<<(const uint256& a, unsigned int shift) { return uint256(a) <<= shift; }
inline const uint256 operator>>(const uint256& a, unsigned int shift) { return uint256(a) >>= shift; }
inline const uint256 operator^(const base_uint256& a, const base_uint256& b) { return uint256(a) ^= b; }
inline const uint256 operator&(const base_uint256& a, const base_uint256& b) { return uint256(a) &= b; }
inline const uint256 operator|(const base_uint256& a, const base_uint256& b) { return uint256(a) |= b; }
inline const uint256 operator+(const base_uint256& a, const base_uint256& b) { return uint256(a) += b; }
inline const uint256 operator-(const base_uint256& a, const base_uint256& b) { return uint256(a) -= b; }
inline bool operator<(const base_uint256& a, const uint256& b) { return (base_uint256)a < (base_uint256)b; }
inline bool operator<=(const base_uint256& a, const uint256& b) { return (base_uint256)a <= (base_uint256)b; }
inline bool operator>(const base_uint256& a, const uint256& b) { return (base_uint256)a > (base_uint256)b; }
inline bool operator>=(const base_uint256& a, const uint256& b) { return (base_uint256)a >= (base_uint256)b; }
inline bool operator==(const base_uint256& a, const uint256& b) { return (base_uint256)a == (base_uint256)b; }
inline bool operator!=(const base_uint256& a, const uint256& b) { return (base_uint256)a != (base_uint256)b; }
inline const uint256 operator^(const base_uint256& a, const uint256& b) { return (base_uint256)a ^ (base_uint256)b; }
inline const uint256 operator&(const base_uint256& a, const uint256& b) { return (base_uint256)a & (base_uint256)b; }
inline const uint256 operator|(const base_uint256& a, const uint256& b) { return (base_uint256)a | (base_uint256)b; }
inline const uint256 operator+(const base_uint256& a, const uint256& b) { return (base_uint256)a + (base_uint256)b; }
inline const uint256 operator-(const base_uint256& a, const uint256& b) { return (base_uint256)a - (base_uint256)b; }
inline bool operator<(const uint256& a, const base_uint256& b) { return (base_uint256)a < (base_uint256)b; }
inline bool operator<=(const uint256& a, const base_uint256& b) { return (base_uint256)a <= (base_uint256)b; }
inline bool operator>(const uint256& a, const base_uint256& b) { return (base_uint256)a > (base_uint256)b; }
inline bool operator>=(const uint256& a, const base_uint256& b) { return (base_uint256)a >= (base_uint256)b; }
inline bool operator==(const uint256& a, const base_uint256& b) { return (base_uint256)a == (base_uint256)b; }
inline bool operator!=(const uint256& a, const base_uint256& b) { return (base_uint256)a != (base_uint256)b; }
inline const uint256 operator^(const uint256& a, const base_uint256& b) { return (base_uint256)a ^ (base_uint256)b; }
inline const uint256 operator&(const uint256& a, const base_uint256& b) { return (base_uint256)a & (base_uint256)b; }
inline const uint256 operator|(const uint256& a, const base_uint256& b) { return (base_uint256)a | (base_uint256)b; }
inline const uint256 operator+(const uint256& a, const base_uint256& b) { return (base_uint256)a + (base_uint256)b; }
inline const uint256 operator-(const uint256& a, const base_uint256& b) { return (base_uint256)a - (base_uint256)b; }
inline bool operator<(const uint256& a, const uint256& b) { return (base_uint256)a < (base_uint256)b; }
inline bool operator<=(const uint256& a, const uint256& b) { return (base_uint256)a <= (base_uint256)b; }
inline bool operator>(const uint256& a, const uint256& b) { return (base_uint256)a > (base_uint256)b; }
inline bool operator>=(const uint256& a, const uint256& b) { return (base_uint256)a >= (base_uint256)b; }
inline bool operator==(const uint256& a, const uint256& b) { return (base_uint256)a == (base_uint256)b; }
inline bool operator!=(const uint256& a, const uint256& b) { return (base_uint256)a != (base_uint256)b; }
inline const uint256 operator^(const uint256& a, const uint256& b) { return (base_uint256)a ^ (base_uint256)b; }
inline const uint256 operator&(const uint256& a, const uint256& b) { return (base_uint256)a & (base_uint256)b; }
inline const uint256 operator|(const uint256& a, const uint256& b) { return (base_uint256)a | (base_uint256)b; }
inline const uint256 operator+(const uint256& a, const uint256& b) { return (base_uint256)a + (base_uint256)b; }
inline const uint256 operator-(const uint256& a, const uint256& b) { return (base_uint256)a - (base_uint256)b; }
inline int Testuint256AdHoc(std::vector<std::string> vArg)
{
uint256 g(0);
printf("%s\n", g.ToString().c_str());
g--; printf("g--\n");
printf("%s\n", g.ToString().c_str());
g--; printf("g--\n");
printf("%s\n", g.ToString().c_str());
g++; printf("g++\n");
printf("%s\n", g.ToString().c_str());
g++; printf("g++\n");
printf("%s\n", g.ToString().c_str());
g++; printf("g++\n");
printf("%s\n", g.ToString().c_str());
g++; printf("g++\n");
printf("%s\n", g.ToString().c_str());
uint256 a(7);
printf("a=7\n");
printf("%s\n", a.ToString().c_str());
uint256 b;
printf("b undefined\n");
printf("%s\n", b.ToString().c_str());
int c = 3;
a = c;
a.pn[3] = 15;
printf("%s\n", a.ToString().c_str());
uint256 k(c);
a = 5;
a.pn[3] = 15;
printf("%s\n", a.ToString().c_str());
b = 1;
b <<= 52;
a |= b;
a ^= 0x500;
printf("a %s\n", a.ToString().c_str());
a = a | b | (uint256)0x1000;
printf("a %s\n", a.ToString().c_str());
printf("b %s\n", b.ToString().c_str());
a = 0xfffffffe;
a.pn[4] = 9;
printf("%s\n", a.ToString().c_str());
a++;
printf("%s\n", a.ToString().c_str());
a++;
printf("%s\n", a.ToString().c_str());
a++;
printf("%s\n", a.ToString().c_str());
a++;
printf("%s\n", a.ToString().c_str());
a--;
printf("%s\n", a.ToString().c_str());
a--;
printf("%s\n", a.ToString().c_str());
a--;
printf("%s\n", a.ToString().c_str());
uint256 d = a--;
printf("%s\n", d.ToString().c_str());
printf("%s\n", a.ToString().c_str());
a--;
printf("%s\n", a.ToString().c_str());
a--;
printf("%s\n", a.ToString().c_str());
d = a;
printf("%s\n", d.ToString().c_str());
for (int i = uint256::WIDTH-1; i >= 0; i--) printf("%08x", d.pn[i]); printf("\n");
uint256 neg = d;
neg = ~neg;
printf("%s\n", neg.ToString().c_str());
uint256 e = uint256("0xABCDEF123abcdef12345678909832180000011111111");
printf("\n");
printf("%s\n", e.ToString().c_str());
printf("\n");
uint256 x1 = uint256("0xABCDEF123abcdef12345678909832180000011111111");
uint256 x2;
printf("%s\n", x1.ToString().c_str());
for (int i = 0; i < 270; i += 4)
{
x2 = x1 << i;
printf("%s\n", x2.ToString().c_str());
}
printf("\n");
printf("%s\n", x1.ToString().c_str());
for (int i = 0; i < 270; i += 4)
{
x2 = x1;
x2 >>= i;
printf("%s\n", x2.ToString().c_str());
}
for (int i = 0; i < 100; i++)
{
uint256 k = (~uint256(0) >> i);
printf("%s\n", k.ToString().c_str());
}
for (int i = 0; i < 100; i++)
{
uint256 k = (~uint256(0) << i);
printf("%s\n", k.ToString().c_str());
}
return (0);
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
766
]
]
]
|
e5bfdab9b9b452cfe8882c55f163efe1c234969b | 2b32433353652d705e5558e7c2d5de8b9fbf8fc3 | /Dm_new_idz/Mlita/Exam/Query.h | dc92dd3bb397fd8549da652c235e8183ffff7b78 | []
| no_license | smarthaert/d-edit | 70865143db2946dd29a4ff52cb36e85d18965be3 | 41d069236748c6e77a5a457280846a300d38e080 | refs/heads/master | 2020-04-23T12:21:51.180517 | 2011-01-30T00:37:18 | 2011-01-30T00:37:18 | 35,532,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | h | // Query.h: interface for the CQuery class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_QUERY_H__8212A288_BE62_4F26_B679_75E998F2A3FE__INCLUDED_)
#define AFX_QUERY_H__8212A288_BE62_4F26_B679_75E998F2A3FE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CQueryElement;
class CQuery
{
public:
BOOL IsEmpty();
int Pop();
void Push(int V);
CQueryElement* Last;
CQueryElement* Top;
void FreeMemory();
CQuery();
virtual ~CQuery();
};
#endif // !defined(AFX_QUERY_H__8212A288_BE62_4F26_B679_75E998F2A3FE__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
27
]
]
]
|
cf66c04c0d0f2412b37fdd8ecc6466e9b292208c | 41c264ec05b297caa2a6e05e4476ce0576a8d7a9 | /OpenScrape/MainFrm.h | ebbec754708a6c11d9380c317d587cca39a87a54 | []
| no_license | seawei/openholdem | cf19a90911903d7f4d07f956756bd7e521609af3 | ba408c835b71dc1a9d674eee32958b69090fb86c | refs/heads/master | 2020-12-25T05:40:09.628277 | 2009-01-25T01:17:10 | 2009-01-25T01:17:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,197 | h | // MainFrm.h : interface of the CMainFrame class
//
#pragma once
#define BLINKER_TIMER 1
class CMainFrame : public CFrameWnd
{
protected: // create from serialization only
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnViewRefresh();
afx_msg void OnViewShowregionboxes();
afx_msg void OnEditUpdatehashes();
afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg void OnUpdateViewShowregionboxes(CCmdUI *pCmdUI);
afx_msg void OnUpdateViewCurrentwindowsize(CCmdUI *pCmdUI);
void SaveBmpPbits(void);
DECLARE_MESSAGE_MAP()
CStatusBar m_wndStatusBar;
CToolBar m_wndToolBar;
public:
virtual BOOL DestroyWindow();
afx_msg void OnViewConnecttowindow();
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual ~CMainFrame();
// Flag indicating whether red regions are shown or not
bool show_regions;
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
};
// used by EnumProcTopLevelWindowList function
extern CArray <STableList, STableList> g_tlist;
BOOL CALLBACK EnumProcTopLevelWindowList(HWND hwnd, LPARAM lparam);
| [
"[email protected]"
]
| [
[
[
1,
44
]
]
]
|
ac83d29ba8c9392a00905fcc5d773ae788b20e41 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian-r6/MyAccountContainer.cpp | 700536f37edd4f9526b01278b81dac94dff76249 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,853 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// S60 includes
#include <barsread.h>
#include <stringloader.h>
#include <eiklabel.h>
#include <eikenv.h>
#include <gdi.h>
#include <eikseced.h>
#include <aknviewappui.h>
#include <eikappui.h>
#include <aknutils.h>
#include <aknsdrawutils.h>// add this include file skin
#include <aknsbasicbackgroundcontrolcontext.h> //add this include file skin
#include <wayfinder8_s60v5.rsg>
#include "wayfinder.hrh"
#include "WayFinderConstants.h"
#include "MyAccountView.h"
#include "MyAccountContainer.h"
const TInt kXMargin = 10;
/**
* First phase of Symbian two-phase construction. Should not
* contain any code that could leave.
*/
CMyAccountContainer::CMyAccountContainer(RBuf& aUsername) :
iUsername(aUsername)
{
iInstructionsLabel = NULL;
iUserNameLabel = NULL;
iSecretEditor = NULL;
iPasswordLabel = NULL;
}
/**
* Destroy child controls.
*/
CMyAccountContainer::~CMyAccountContainer()
{
delete iInstructionsLabel;
iInstructionsLabel = NULL;
delete iUserNameLabel;
iUserNameLabel = NULL;
delete iSecretEditor;
iSecretEditor = NULL;
delete iPasswordLabel;
iPasswordLabel = NULL;
iUserNameAndLabel.Close();
delete iBackground;
}
/**
* Construct the control (first phase).
*/
CMyAccountContainer*
CMyAccountContainer::NewL(const TRect& aRect, const CCoeControl* aParent,
MEikCommandObserver* aCommandObserver,
RBuf& aUsername)
{
CMyAccountContainer* self = CMyAccountContainer::NewLC(aRect, aParent,
aCommandObserver, aUsername);
CleanupStack::Pop(self);
return self;
}
/**
* Construct the control (first phase).
*/
CMyAccountContainer*
CMyAccountContainer::NewLC(const TRect& aRect, const CCoeControl* aParent,
MEikCommandObserver* aCommandObserver,
RBuf& aUsername)
{
CMyAccountContainer* self = new (ELeave) CMyAccountContainer(aUsername);
CleanupStack::PushL(self);
self->ConstructL(aRect, aParent, aCommandObserver);
return self;
}
/**
* Construct the control (second phase).
*/
void
CMyAccountContainer::ConstructL(const TRect& aRect, const CCoeControl* aParent,
MEikCommandObserver* aCommandObserver)
{
if (aParent == NULL) {
CreateWindowL();
} else {
SetContainerWindowL(*aParent);
}
iFocusControl = NULL;
iCommandObserver = aCommandObserver;
InitializeControlsL();
SetRect(aRect);
iBackground = CAknsBasicBackgroundControlContext::NewL(
KAknsIIDQsnBgAreaMain, Rect(), EFalse);// new a background
ActivateL();
}
/**
* Return the number of controls in the container (override)
* @return count
*/
TInt
CMyAccountContainer::CountComponentControls() const
{
return (int) ELastControl;
}
/**
* Get the control with the given index (override)
* @param aIndex Control index [0...n) (limited by #CountComponentControls)
* @return Pointer to control
*/
CCoeControl*
CMyAccountContainer::ComponentControl(TInt aIndex) const
{
switch (aIndex) {
case EInstructionsLabel:
return iInstructionsLabel;
case EUserNameLabel:
return iUserNameLabel;
case ESecretEditor:
return iSecretEditor;
case EPasswordLabel:
return iPasswordLabel;
}
return NULL;
}
/**
* Handle resizing of the container. This implementation will lay out
* full-sized controls like list boxes for any screen size, and will layout
* labels, editors, etc. to the size they were given in the UI designer.
* This code will need to be modified to adjust arbitrary controls to
* any screen size.
*/
void
CMyAccountContainer::SizeChanged()
{
CCoeControl::SizeChanged();
LayoutControls();
}
/**
* Layout components as specified in the UI Designer
*/
void
CMyAccountContainer::LayoutControls()
{
if (iBackground) {
iBackground->SetRect(Rect());
}
TRect screenRect;
AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EMainPane, screenRect);
// find the x values
TInt Xstart = kXMargin;
TInt width = screenRect.Width() - kXMargin - kXMargin;
// find the y values by spliting the heigth into 15 lines
TInt h = screenRect.Height() / 15;
RBuf instructionStringBuf;
TInt noLines = 0;
// for smaller screens the instructions need to be in a smaller font
if (screenRect.Height() < 400 )
{
// small font for FP2 type devices
const CFont* legendFont = iEikonEnv->LegendFont();
iInstructionsLabel->SetFont(legendFont);
noLines = LayoutInstructions(instructionStringBuf, iInstructionsLabel->Font());
iInstructionsLabel->SetTextL(instructionStringBuf);
iUserNameLabel->SetFont(legendFont);
iPasswordLabel->SetFont(legendFont);
iSecretEditor->SetExtent(TPoint(Xstart, (noLines + 5) * h), TSize(width, 2 * h));
iPasswordLabel->SetExtent(TPoint(Xstart, ((noLines + 4) * h)-(h/2)), TSize(width, (2 * h) -5));
}
else {
// Normal font on edition 5 type devices
const CFont* normalFont = CCoeEnv::Static()->NormalFont();
iInstructionsLabel->SetFont(normalFont);
noLines = LayoutInstructions(instructionStringBuf, iInstructionsLabel->Font());
iInstructionsLabel->SetTextL(instructionStringBuf);
iUserNameLabel->SetFont(normalFont);
iPasswordLabel->SetFont(normalFont);
iSecretEditor->SetExtent(TPoint(Xstart, (noLines + 5) * h), TSize(width, 2 * h));
iPasswordLabel->SetExtent(TPoint(Xstart, ((noLines + 4) * h)-(h/2)), TSize(width, (2 * h) -5));
}
instructionStringBuf.Close();
iInstructionsLabel->SetExtent(TPoint(Xstart, 0), TSize(width, 8 * h));
iUserNameLabel->SetExtent(TPoint(Xstart, (noLines + 1) * h), TSize(width, 3 * h));
}
/**
* Handle key events.
*/
TKeyResponse
CMyAccountContainer::OfferKeyEventL(const TKeyEvent& aKeyEvent,
TEventCode aType)
{
if (iFocusControl != NULL && iFocusControl->OfferKeyEventL(aKeyEvent, aType)
== EKeyWasConsumed) {
// a key event has gone to the editor so if password length >0 enable update LSK
TBuf<KBuf64Length> passordText;
iSecretEditor->GetText(passordText);
CEikButtonGroupContainer* buttonGroupContainer=CEikButtonGroupContainer::Current();
if (passordText.Length()) {
buttonGroupContainer->MakeCommandVisible(EAknSoftkeyOk,ETrue);
}
else {
buttonGroupContainer->MakeCommandVisible(EAknSoftkeyOk,EFalse);
}
return EKeyWasConsumed;
}
return CCoeControl::OfferKeyEventL(aKeyEvent, aType);
}
/**
* Initialize each control upon creation.
*/
void
CMyAccountContainer::InitializeControlsL()
{
// Get the current text color for the current skin
MAknsSkinInstance* skin = AknsUtils::SkinInstance();
TRgb txtColor;
AknsUtils::GetCachedColor(skin, txtColor, KAknsIIDQsnTextColors,
EAknsCIQsnTextColorsCG6);
// block of text containing instructions
iInstructionsLabel = new (ELeave) CEikLabel;
iInstructionsLabel->SetContainerWindowL(*this);
{
TResourceReader reader;
iEikonEnv->CreateResourceReaderLC(reader,
R_MY_ACCOUNT_VIEW_INSTRUCTIONS_LABEL);
iInstructionsLabel->ConstructFromResourceL(reader);
CleanupStack::PopAndDestroy(); // reader internal state
}
iInstructionsLabel->OverrideColorL(EColorLabelText, txtColor);
iUserNameLabel = new (ELeave) CEikLabel;
iUserNameLabel->SetContainerWindowL(*this);
{
TResourceReader reader;
iEikonEnv->CreateResourceReaderLC(reader,
R_MY_ACCOUNT_VIEW_USER_NAME_LABEL);
iUserNameLabel->ConstructFromResourceL(reader);
CleanupStack::PopAndDestroy(); // reader internal state
// Read the "Username" string resource
HBufC* buf = CCoeEnv::Static()->AllocReadResourceLC(R_S60_USER_NAME_TXT);
iUserNameAndLabel.Create(buf->Length() + 2 + KBuf64Length);
iUserNameAndLabel.Copy(*buf);
CleanupStack::PopAndDestroy(buf);
// add the real username eg "fred" to "Username:" to make "User name:Fred"
iUserNameAndLabel.Append(_L("\n"));
iUserNameAndLabel.Append(iUsername);
iUserNameLabel->SetTextL(iUserNameAndLabel);
}
iUserNameLabel->OverrideColorL(EColorLabelText, txtColor);
// secret editor
iSecretEditor = new (ELeave) CEikSecretEditor;
iSecretEditor->SetContainerWindowL(*this);
{
TResourceReader reader;
iEikonEnv->CreateResourceReaderLC(reader, R_MY_ACCOUNT_VIEW_SECRET_EDITOR);
iSecretEditor->ConstructFromResourceL(reader);
CleanupStack::PopAndDestroy(); // reader internal state
}
iSecretEditor->SetMaxLength(KBuf64Length);
iSecretEditor->SetText(_L(""));
iSecretEditor->AknSetAlignment(CGraphicsContext::ECenter);
iSecretEditor->SetBorder( TGulBorder::ESingleBlack );
iSecretEditor->OverrideColorL(EColorControlText, txtColor);
iSecretEditor->SetFocus(ETrue);
iFocusControl = iSecretEditor;
// Password label
iPasswordLabel = new (ELeave) CEikLabel;
iPasswordLabel->SetContainerWindowL(*this);
{
TResourceReader reader;
iEikonEnv->CreateResourceReaderLC(reader,
R_MY_ACCOUNT_VIEW_PASSWORD_LABEL);
iPasswordLabel->ConstructFromResourceL(reader);
CleanupStack::PopAndDestroy(); // reader internal state
}
iPasswordLabel->OverrideColorL(EColorLabelText, txtColor);
}
/**
* Handle global resource changes, such as scalable UI or skin events (override)
*/
void
CMyAccountContainer::HandleResourceChange(TInt aType)
{
CCoeControl::HandleResourceChange(aType);
SetRect(iAvkonViewAppUi->View(KMyAccountViewId)->ClientRect());
}
/**
* Draw container contents.
*/
void
CMyAccountContainer::Draw(const TRect& aRect) const
{
// draw background
CWindowGc& gc = SystemGc();
MAknsSkinInstance* skin = AknsUtils::SkinInstance();
MAknsControlContext* cc = AknsDrawUtils::ControlContext(this);
AknsDrawUtils::Background(skin, cc, this, gc, aRect);
/* add a 1 pixel border around the secret editor */
TRect border = iSecretEditor->Rect();
border.iTl.iX -=1;
border.iTl.iY -=1;
border.iBr.iX +=1;
border.iBr.iY +=1;
gc.SetPenStyle(CGraphicsContext::ESolidPen);
TRgb txtColor;
AknsUtils::GetCachedColor(skin, txtColor, KAknsIIDQsnTextColors,
EAknsCIQsnTextColorsCG6);
gc.SetPenColor(txtColor);
gc.DrawRect(border);
}
TTypeUid::Ptr
CMyAccountContainer::MopSupplyObject(TTypeUid aId)
{
if (aId.iUid == MAknsControlContext::ETypeId && iBackground) {
return MAknsControlContext::SupplyMopObject(aId, iBackground);
}
return CCoeControl::MopSupplyObject(aId);
}
TInt CMyAccountContainer::LayoutInstructions(RBuf& aInstructionStringBuf,
const CFont* aFont)
{
// Read the instruction string from resource into RBuf
HBufC* txt = CCoeEnv::Static()->AllocReadResourceLC(R_S60_INSTRUCTION_TXT);
// Find the screen width
TRect screenRect;
AknLayoutUtils::LayoutMetricsRect(AknLayoutUtils::EMainPane, screenRect);
TInt screenWidth = screenRect.Width() - kXMargin - kXMargin;
// Wrap the text to fit
CArrayFix<TPtrC16>* textArray = new (ELeave) CArrayFixFlat<TPtrC> (10);
CleanupStack::PushL(textArray);
AknTextUtils::WrapToArrayL(*txt, screenWidth, *aFont, *textArray);
// add newline to every line and pack back together into aInstructionStringBuf
aInstructionStringBuf.Close();
aInstructionStringBuf.Create(txt->Length() + 10);
for (TInt i = 0; i < textArray->Count(); i++) {
aInstructionStringBuf.Append(textArray->At(i));
aInstructionStringBuf.Append(_L("\n"));
}
TInt noLines = textArray->Count();
CleanupStack::PopAndDestroy(textArray);
CleanupStack::PopAndDestroy(txt);
// return the number of lines needed
return noLines;
}
void CMyAccountContainer::GetPassword(RBuf& aPassword)
{
iSecretEditor->GetText(aPassword);
}
| [
"[email protected]"
]
| [
[
[
1,
406
]
]
]
|
45287cfe741e39fad1fe459417ead83f44dfb574 | 2d22825193eacf3669ac8bd7a857791745a9ead4 | /HairSimulation/HairSimulation/DynamicsLib/mesh1.cpp | 089733ab129a1eb39a434a04d9d134216dd79cb7 | []
| no_license | dtbinh/com-animation-classprojects | 557ba550b575c3d4efc248f7984a3faac8f052fd | 37dc800a6f2bac13f5aa4fc7e0e96aa8e9cec29e | refs/heads/master | 2021-01-06T20:45:42.613604 | 2009-01-20T00:23:11 | 2009-01-20T00:23:11 | 41,496,905 | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 13,253 | cpp | //////////////////////////////////////////////////////////////////////
//
// 修改了 mesh.cpp 11/01
//
// mesh.cpp: implementation of the mesh class.
//
//////////////////////////////////////////////////////////////////////
#include "mesh.h"
#include <iostream>
#include <cassert>
#include <cmath>
#include <Ogre.h>
using namespace Ogre;
const char* obj_database = ""; // 定義 mesh 的預設目錄
#pragma warning(disable:4786) // microsoft stupid bug!!
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
mesh::mesh(const char* obj_file)
{
matTotal = 0; // mat[0] reserved for default meterial
vTotal = tTotal = nTotal = fTotal = 0;
fnList = 0;
vAdjFList = 0;
Init(obj_file);
}
mesh::mesh(CMesh* sourceMesh)
{
matTotal = 0;
vTotal = tTotal = nTotal = fTotal = 0;
fnList = 0;
vAdjFList = 0;
Init(sourceMesh);
}
mesh::~mesh()
{
if( fnList != 0 )
delete[] fnList;
if( vAdjFList != 0 )
delete[] vAdjFList;
}
void mesh::LoadMesh(string obj_file)
{
char token[100], buf[100], v[5][100]; // v[5] 表示一個 polygon 可以有 5個 vertex
float vec[3];
int n_vertex, n_texture, n_normal;
int cur_tex = 0; // state variable: 目前所使用的 material
scene = fopen(obj_file.c_str(),"r");
s_file = obj_file;
if (!scene)
{
cout<< string("Can not open object File \"") << obj_file << "\" !" << endl;
return;
}
cout<<endl<<obj_file<<endl;
while(!feof(scene))
{
token[0] = NULL;
fscanf(scene,"%s", token); // 讀 token
if (!strcmp(token,"g"))
{
fscanf(scene,"%s",buf);
}
else if (!strcmp(token,"mtllib"))
{
fscanf(scene,"%s", mat_file);
LoadTex(string(obj_database) + string(mat_file));
}
else if (!strcmp(token,"usemtl"))
{
fscanf(scene,"%s",buf);
cur_tex = matMap[s_file+string("_")+string(buf)];
}
else if (!strcmp(token,"v"))
{
fscanf(scene,"%f %f %f",&vec[0],&vec[1],&vec[2]);
vList.push_back(Vector3(vec));
}
else if (!strcmp(token,"vn"))
{
fscanf(scene,"%f %f %f",&vec[0],&vec[1],&vec[2]);
nList.push_back(Vector3(vec));
}
else if (!strcmp(token,"vt"))
{
fscanf(scene,"%f %f",&vec[0],&vec[1]);
tList.push_back(Vector3(vec));
}
else if (!strcmp(token,"f"))
{
int i;
for (i=0;i<3;i++) // face 預設為 3,假設一個 polygon 都只有 3 個 vertex
{
fscanf(scene,"%s",v[i]);
//printf("[%s]",v[i]);
}
//printf("\n");
Vertex tmp_vertex[3]; // for faceList structure
for (i=0;i<3;i++) // for each vertex of this face
{
char str[20], ch;
int base,offset;
base = offset = 0;
// calculate vertex-list index
while( (ch=v[i][base+offset]) != '/' && (ch=v[i][base+offset]) != '\0')
{
str[offset] = ch;
offset++;
}
str[offset] = '\0';
n_vertex = atoi(str);
base += (ch == '\0')? offset : offset+1;
offset = 0;
// calculate texture-list index
while( (ch=v[i][base+offset]) != '/' && (ch=v[i][base+offset]) != '\0')
{
str[offset] = ch;
offset++;
}
str[offset] = '\0';
n_texture = atoi(str); // case: xxx//zzz,texture 設為 0 (tList 從 1 開始)
base += (ch == '\0')? offset : offset+1;
offset = 0;
// calculate normal-list index
while( (ch=v[i][base+offset]) != '\0')
{
str[offset] = ch;
offset++;
}
str[offset] = '\0';
n_normal = atoi(str); // case: xxx/yyy,normal 設為 0 (nList 從 1 開始)
tmp_vertex[i].v = n_vertex;
tmp_vertex[i].t = n_texture;
tmp_vertex[i].n = n_normal;
tmp_vertex[i].m = cur_tex;
}
faceList.push_back(FACE(tmp_vertex[0],tmp_vertex[1],tmp_vertex[2]));
}
else if (!strcmp(token,"#")) // 註解
fgets(buf,100,scene);
// printf("[%s]\n",token);
}
if (scene) fclose(scene);
vTotal = int( vList.size());
nTotal = int( nList.size());
tTotal = int(tList.size());
fTotal = int(faceList.size());
printf("vetex: %d, normal: %d, texture: %d, triangles: %d\n",vTotal, nTotal, tTotal, fTotal);
}
void mesh::LoadMesh(CMesh* srcMesh)
{
int srcVertexCount, srcFaceCount;
Ogre::Vector3* srcVertices;
unsigned long* srcIndices;
Vertex tmp_vertex[3];
int i, j;
int vIndex;
srcVertexCount = (int)srcMesh->getVertexCount();
srcVertices = srcMesh->getVertices();
srcFaceCount = (int)srcMesh->getTriCount();
srcIndices = srcMesh->getIndices();
//Set vertex position
for (i = 0; i < srcVertexCount; i++)
{
vList.push_back(srcVertices[i]);
}
for (i = 0; i < srcFaceCount; i++)
{
vIndex = i*3;
for (j = 0; j < 3; j++)
{
tmp_vertex[j].v = (int)srcIndices[vIndex+j];
}
faceList.push_back(FACE(tmp_vertex[0], tmp_vertex[1], tmp_vertex[2]));
}
vTotal = (int)vList.size();
nTotal = (int)nList.size();
tTotal = (int)tList.size();
fTotal = (int)faceList.size();
printf("vetex: %d, normal: %d, texture: %d, triangles: %d\n",vTotal, nTotal, tTotal, fTotal);
}
void mesh::LoadTex(string tex_file)
{
//char token[100], buf[100], v1[100], v2[100], v3[100];
char token[100], buf[100];
//float x,y,z,r,g,b;
float r,g,b;
//int n_vertex, n_texture, n_normal; // temp 的 current data
//int cur_tex; // 儲存接著下去的 polygon 是用哪個 texture
texture = fopen(tex_file.c_str(),"r");
t_file = tex_file;
if (!texture)
{
cout << "Can't open material file \"" << tex_file << "\"!" << endl;
return;
}
cout<<tex_file<<endl;
int cur_mat;
while(!feof(texture))
{
token[0] = NULL;
fscanf(texture,"%s", token); // 讀 token
if (!strcmp(token,"newmtl"))
{
fscanf(texture,"%s",buf);
cur_mat = matTotal++; // 從 mat[1] 開始,mat[0] 空下來給 default material 用
matMap[s_file+string("_")+string(buf)] = cur_mat; // matMap["material_name"] = material_id;
}
else if (!strcmp(token,"Ka"))
{
fscanf(texture,"%f %f %f",&r,&g,&b);
mat[cur_mat].Ka[0] = r;
mat[cur_mat].Ka[1] = g;
mat[cur_mat].Ka[2] = b;
mat[cur_mat].Ka[3] = 1;
}
else if (!strcmp(token,"Kd"))
{
fscanf(texture,"%f %f %f",&r,&g,&b);
mat[cur_mat].Kd[0] = r;
mat[cur_mat].Kd[1] = g;
mat[cur_mat].Kd[2] = b;
mat[cur_mat].Kd[3] = 1;
}
else if (!strcmp(token,"Ks"))
{
fscanf(texture,"%f %f %f",&r,&g,&b);
mat[cur_mat].Ks[0] = r;
mat[cur_mat].Ks[1] = g;
mat[cur_mat].Ks[2] = b;
mat[cur_mat].Ks[3] = 1;
}
else if (!strcmp(token,"Ns"))
{
fscanf(texture,"%f",&r);
mat[cur_mat].Ns = r;
}
else if (!strcmp(token,"#")) // 註解
fgets(buf,100,texture);
// printf("[%s]\n",token);
}
printf("total material:%d\n",matMap.size());
if (texture) fclose(texture);
}
void mesh::Init(const char* obj_file)
{
float default_value[3] = {1,1,1};
vList.push_back(Vector3(default_value)); // 因為 *.obj 的 index 是從 1 開始
nList.push_back(Vector3(default_value)); // 所以要先 push 一個 default value 到 vList[0],nList[0],tList[0]
tList.push_back(Vector3(default_value));
// 定義 default meterial: mat[0]
mat[0].Ka[0] = 0.0f; mat[0].Ka[1] = 0.0f; mat[0].Ka[2] = 0.0f; mat[0].Ka[3] = 1.0f;
mat[0].Kd[0] = 1.0f; mat[0].Kd[1] = 1.0f; mat[0].Kd[2] = 1.0f; mat[0].Kd[3] = 1.0f;
mat[0].Ks[0] = 0.8f; mat[0].Ks[1] = 0.8f; mat[0].Ks[2] = 0.8f; mat[0].Ks[3] = 1.0f;
mat[0].Ns = 32;
matTotal++;
LoadMesh(string(obj_file)); // 讀入 .obj 檔 (可處理 Material)
//算vertex的平均normal (facet normal)
CalculateFn();
//create myFaceList
buildMyFaceList();
}
void mesh::Init(CMesh* sourceMesh)
{
float default_value[3] = {1,1,1};
vList.push_back(Vector3(default_value)); // 因為 *.obj 的 index 是從 1 開始
nList.push_back(Vector3(default_value)); // 所以要先 push 一個 default value 到 vList[0],nList[0],tList[0]
tList.push_back(Vector3(default_value));
// 定義 default meterial: mat[0]
mat[0].Ka[0] = 0.0f; mat[0].Ka[1] = 0.0f; mat[0].Ka[2] = 0.0f; mat[0].Ka[3] = 1.0f;
mat[0].Kd[0] = 1.0f; mat[0].Kd[1] = 1.0f; mat[0].Kd[2] = 1.0f; mat[0].Kd[3] = 1.0f;
mat[0].Ks[0] = 0.8f; mat[0].Ks[1] = 0.8f; mat[0].Ks[2] = 0.8f; mat[0].Ks[3] = 1.0f;
mat[0].Ns = 32;
matTotal++;
LoadMesh(sourceMesh);
//算vertex的平均normal (facet normal)
CalculateFn();
//create myFaceList
buildMyFaceList_simple();
}
//建myFaceList
void mesh::buildMyFaceList()
{
assert( vTotal > 0 );
assert( fTotal > 0 );
assert( fnList != 0 );
for( int i = 0; i < fTotal; i++ ){
Face f;
f.materialPtr = &mat[ faceList[i][0].m ];
for( int w = 0; w < 3; w++ ){
f.vPtr[w] = &vList[ faceList[i][w].v ];
f.nPtr[w] = &nList[ faceList[i][w].n ];
f.tPtr[w] = &tList[ faceList[i][w].t ];
}
f.fnPtr = &fnList[i];
f.cPtr = &triCList[i];
myFaceList.push_back( f );
}
//build bv-tree
m_bvTree.buildTree( myFaceList, fTotal );
}
//建myFaceList
void mesh::buildMyFaceList_simple()
{
assert( vTotal > 0 );
assert( fTotal > 0 );
assert( fnList != 0 );
for( int i = 0; i < fTotal; i++ ){
Face f;
//f.materialPtr = &mat[ faceList[i][0].m ];
for( int w = 0; w < 3; w++ ){
f.vPtr[w] = &vList[ faceList[i][w].v ];
//f.nPtr[w] = &nList[ faceList[i][w].n ];
//f.tPtr[w] = &tList[ faceList[i][w].t ];
}
f.fnPtr = &fnList[i];
//f.cPtr = &triCList[i];
myFaceList.push_back( f );
}
//build bv-tree
m_bvTree.buildTree( myFaceList, fTotal );
}
/** 2009-01-12 另有用途 */
void mesh::CalculateFn()
{
assert( vTotal > 0 );
assert( fTotal > 0 );
if( fnList != 0 ){
delete[] fnList;
}
if( vAdjFList != 0 ){
delete[] vAdjFList;
}
//if( triCList != 0 ){
// delete[] triCList;
//}
//triCList = new Vector3[ fTotal ];
fnList = new Vector3[ fTotal ];
assert( fnList );
//assert( triCList );
for( int f = 0; f < fTotal; f++ ){
Vector3 a = vList[ faceList[f][1].v ] - vList[ faceList[f][0].v ];
Vector3 b = vList[ faceList[f][2].v ] - vList[ faceList[f][0].v ];
// 注意外積的方向要和平面相同
Vector3 n = a.crossProduct( b);
n.normalise();
fnList[f] = n;
//triCList[f] = (vList[ faceList[f][0].v ] + vList[ faceList[f][0].v ] + vList[ faceList[f][0].v ] )/3;
}
}//close function: calculateFn
/***********************************************
函式
算出每個頂點的 facet noraml (多面體法向量)
也就是一個頂點所有相鄰的三角形平面法向量的平均
放置在
Vec3 fnList[ vTotal ] 中
fnList[v] 就是第 v 的頂點的法向量
例如
v: vertex index
glNormal3fv( fnList[v] );
glVertex3fv( vList[v] );
call 之前 mesh 的 vList, faceList 已經建好了
*************************************************/
#if 0
void mesh::CalculateFn()
{
assert( vTotal > 0 );
assert( fTotal > 0 );
if( fnList != 0 ){
delete[] fnList;
}
if( vAdjFList != 0 ){
delete[] vAdjFList;
}
fnList = new Vector3[ vTotal ];
vAdjFList = new vector<int> [ vTotal ];
// vList 編號從1開始
for( int i = 0; i < fTotal; i++ ){
for( int j = 0; j < 3; j++ ){
vAdjFList[ faceList[i][j].v ].push_back( i );
}
}
#ifdef DEBUG_1
for( int i = 1; i < vTotal; i++ ){
printf( "%d adj f:", i );
for( int j = 0; j < vAdjFList[i].size(); j++ ){
printf( " %d", vAdjFList[i][j] );
}
printf("\n");
}
#endif
Vector3 *faceNormal = new Vector3[ fTotal ];
for( int f = 0; f < fTotal; f++ ){
Vector3 a, b, n;
VecSub( vList[ faceList[f][1].v ], vList[ faceList[f][0].v ], a );
VecSub( vList[ faceList[f][2].v ], vList[ faceList[f][0].v ], b );
// 注意外積的方向要和平面相同
VecCross( a, b, n );
NormalizeVec( n );
faceNormal[f] = n;
}
#ifdef DEBUG_1
for( int f = 0; f < fTotal; f++ ){
printf( "%g,%g,%g \n", faceNormal[f][0], faceNormal[f][1], faceNormal[f][2] );
}
for( int v = 1; v < vTotal; v++ ){
printf( "v: " );
for( int i = 0; i < vAdjFList[v].size(); i++ ){
printf( "%g,%g,%g \n", faceNormal[ vAdjFList[v][i] ][0], faceNormal[ vAdjFList[v][i] ][1], faceNormal[ vAdjFList[v][i] ][2] );
}
printf( "\n" );
}
#endif
// calculate facet normal: average of all adjacent face's normal
for( int v = 1; v < vTotal; v++ ){
Vector3 n( 0.0, 0.0, 0.0 );
for( unsigned int i = 0; i < vAdjFList[v].size(); i++ ){
VecAdd( n, faceNormal[ vAdjFList[v][i] ], n );
}
NormalizeVec( n );
fnList[v] = n;
#ifdef DEBUG_1
printf( "%g,%g,%g \n", fnList[v][0], fnList[v][1], fnList[v][2] );
#endif
}
if( faceNormal != 0 )
delete[] faceNormal;
}//close function: calculateFn
#endif
Face::Face()
:materialPtr(0), fnPtr(0)
{
for( int i = 0; i < 3; i++ ){
vPtr[i] = nPtr[i] = tPtr[i] = NULL;
}
}
Face::Face( const Face & face )
{
for( int i = 0; i < 3; i++ ){
vPtr[i] = face.vPtr[i];
nPtr[i] = face.nPtr[i];
tPtr[i] = face.tPtr[i];
}
fnPtr = face.fnPtr;
cPtr = face.cPtr;
materialPtr = face.materialPtr;
} | [
"grahamhuang@73147322-a748-11dd-a8c6-677c70d10fe4"
]
| [
[
[
1,
545
]
]
]
|
b4f2c14c2f282698890027ebd8a429a51e3365a2 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/inc/util/nbitstream.h | 51fb3d5f7149b4705203f1a87ade1460c4ca0b2f | []
| 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 | 16,162 | h | #ifndef N_BITSTREAM_H
#define N_BITSTREAM_H
//------------------------------------------------------------------------------
// network/nbitstream.h
// author: mark
// (C) 2000 Radon Labs GmbH
//------------------------------------------------------------------------------
#include <memory.h>
#ifndef N_TYPES_H
#include "kernel/ntypes.h"
#endif
#ifndef N_NODE_H
#include "util/nnode.h"
#endif
#undef N_DEFINES
#define N_DEFINES nBitStream
#include "kernel/ndefdllclass.h"
//------------------------------------------------------------------------------
class N_PUBLIC nBitStream : public nNode
{
public:
/// standard constructor, requires separate SetSize()
nBitStream();
/// constructor, expects stream size in bytes
nBitStream(int size);
/// the destructor
virtual ~nBitStream();
/// directly set contents of stream
void Set(const uchar* s, int size);
/// directly get contents of stream
const uchar* Get() const;
/// Set size of stream.
void SetSize(int size);
/// get the byte size of the stream
int GetSize() const;
/// set the current bit position in the stream
void SetPos(int pos);
/// return the current bit position in the stream
int GetPos() const;
/// return the number of bits left in the stream
int BitsLeft() const;
/// write a bool to the stream
void WriteBool(bool flag);
/// read a bool from the stream
bool ReadBool();
/// write a compressed integer to the stream
void WriteInt(int value, int numBits);
/// read a compressed integer from the stream
int ReadInt(int numBits);
/// write a float to the stream
void WriteFloat(float value);
/// read a float from the stream
float ReadFloat();
/// write a custom byte array to the stream
void WriteCustom(const void* ptr, int size);
/// read a custom byte array from the stream
void ReadCustom(void* ptr, int size);
/// write bitstream
void WriteBitStream(nBitStream& stream);
/// read bitstream
void ReadBitStream(nBitStream& stream);
/// copy data from source stream into this stream
void Copy(const nBitStream& source);
/// Lock for writing.
void BeginWrite();
/// Unlock for writing.
void EndWrite();
/// Lock for reading.
void BeginRead();
/// Unlock for reading.
void EndRead();
/// Writeable?
bool IsWriteable() const;
/// Readable?
bool IsReadable() const;
/// Assignment operator.
nBitStream& operator = (const nBitStream& s);
/// Equality operator.
bool operator == (const nBitStream& s) const;
/// Inequality operator.
bool operator != (const nBitStream& s) const;
// output
void Print(int lines);
protected:
/// clear stream contents, do not rewind bit pointer
void Clear();
/// Write bit at current position to stream.
void WriteBit(bool bit);
/// Read bit at currernt position from stream.
bool ReadBit();
private:
unsigned char* stream;
int streamSize;
int currentByte; /// Current index in the stream buffer.
int currentBit; /// Current bit offset int currentByte.
bool writeable;
bool readable;
};
//------------------------------------------------------------------------------
/**
*/
inline
nBitStream::nBitStream()
{
streamSize = 0;
currentByte = 0;
currentBit = 0;
writeable = false;
readable = false;
stream = 0;
}
//------------------------------------------------------------------------------
/**
@param size the byte size of the bit stream (rounded up)
*/
inline
nBitStream::nBitStream(int size)
{
// require
n_assert(size > 0);
streamSize = size;
currentByte = 0;
currentBit = 0;
writeable = false;
readable = false;
stream = n_new unsigned char[size];
if (stream != 0)
{
memset(stream, 0, streamSize);
}
// ensure
n_assert(stream != 0);
}
//------------------------------------------------------------------------------
/**
*/
inline
nBitStream::~nBitStream()
{
if (stream != 0)
{
n_delete[] stream;
}
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::Clear()
{
// require
n_assert( stream != 0 );
n_assert( streamSize > 0 );
memset(stream, 0, streamSize);
}
//------------------------------------------------------------------------------
/**
Write a bool value (always encoded into 1 bit) to the current
stream position.
@param flag the bool value
*/
inline
void
nBitStream::WriteBool(bool flag)
{
n_assert(writeable);
WriteBit(flag);
}
//------------------------------------------------------------------------------
/**
Reads a bool value (always encoded into 1 bit) from the current
stream position.
@return the bool value
*/
inline
bool
nBitStream::ReadBool()
{
n_assert(readable);
return ReadBit();
}
//------------------------------------------------------------------------------
/**
Write a signed integer clamped to numBits bits.
@param value the integer value to write
@param numBits number of bits to write
*/
inline
void
nBitStream::WriteInt(int value, int numBits)
{
n_assert(writeable);
n_assert((1 < numBits) && (numBits <= 32));
n_assert(BitsLeft() >= numBits);
// Write sign
int tmp = (1 << 31);
int tmp2 = (value & tmp);
WriteBit(tmp2 != 0);
numBits -= 2; // I use numBits for shifting
// 1 Bit less for sign
// 1 Bit less for shifting
// Make absolute value;
// write sign and value separate
value = n_abs(value);
// Write value
while (numBits >= 0)
{
tmp = (1 << numBits);
tmp2 = (value & tmp);
WriteBit(tmp2 != 0);
numBits--;
}
n_assert(numBits == -1);
}
//------------------------------------------------------------------------------
/**
Read a signed integer clamped to numBits bits, the rest of the
32 bytes will be filled with the correct sign bit.
@param numBits number of bits to read
@return the integer, correclty expanded to 32 bits
*/
inline
int
nBitStream::ReadInt(int numBits)
{
n_assert(readable);
n_assert((1 < numBits) && (numBits <= 32));
n_assert(BitsLeft() >= numBits);
int value = 0;
// Read sign
bool sign = ReadBit();
numBits -= 2; // I use numBits for shifting
// 1 Bit less for sign
// 1 Bit less for shifting
// Read data
while (numBits >= 0)
{
int v = ReadBit() ? 1 : 0;
value |= (v << numBits);
numBits--;
}
n_assert(numBits == -1);
// set sign
if (sign)
{
value = -value;
}
return value;
}
//------------------------------------------------------------------------------
/**
Write a float value into the stream, the float value will always be
encoded into 32 bits.
@param value the float value to write
*/
inline
void
nBitStream::WriteFloat(float value)
{
n_assert(writeable);
n_assert(BitsLeft() >= 32);
int tmp;
memcpy(&tmp, &value, 4);
WriteInt(tmp, 32); // Write floats as ints; use 32 BITS
}
//------------------------------------------------------------------------------
/**
Read a float value (encoded in 32 bit) from the stream.
@param the float value
*/
inline
float
nBitStream::ReadFloat()
{
n_assert(readable);
n_assert(BitsLeft() >= 32);
int tmp = ReadInt(32); // Read floats as int; use 32 BITS
float value;
memcpy(&value, &tmp, 4);
return value;
}
//------------------------------------------------------------------------------
/**
Write a custom byte array to the stream.
@param ptr pointer to byte array to write to the stream
@param size number of bytes to write
*/
inline
void
nBitStream::WriteCustom(const void* ptr, int size)
{
n_assert(writeable);
n_assert(ptr != 0);
n_assert(size > 0);
n_assert(BitsLeft() >= size * 8);
// advance to next byte in stream
// if current bit offset is greater 0
if (currentBit > 0)
{
currentByte++;
currentBit = 0;
}
memcpy(&stream[currentByte], ptr, size);
currentByte += size;
}
//------------------------------------------------------------------------------
/**
Read a custom byte array from the stream.
@param ptr pointer to byte array
@param size size in bytes to read
*/
inline
void
nBitStream::ReadCustom(void* ptr, int size)
{
n_assert(readable);
n_assert(ptr != 0);
n_assert(size > 0);
n_assert(BitsLeft() >= size * 8);
// advance to next byte in stream
// if current bit offset is greater 0
if (currentBit > 0)
{
currentByte++;
currentBit = 0;
}
memcpy(ptr, &stream[currentByte], size);
currentByte += size;
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::ReadBitStream(nBitStream& stream)
{
n_assert(stream.streamSize <= (BitsLeft() * 8));
ReadCustom(stream.stream, stream.streamSize);
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::WriteBitStream(nBitStream& stream)
{
n_assert(stream.streamSize <= (BitsLeft() * 8));
WriteCustom(stream.stream, stream.streamSize);
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::Set(const uchar* s, int size)
{
// require
n_assert(s != 0);
n_assert(size > 0);
// delete old stream, if exits
if (stream != 0) n_delete[] stream;
// create and copy stream
stream = n_new unsigned char[size];
n_assert(stream != 0);
streamSize = size;
memcpy(stream, s, size);
}
//------------------------------------------------------------------------------
/**
*/
inline
const uchar*
nBitStream::Get() const
{
return stream;
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::SetSize(int size)
{
n_assert(size > 0);
if (stream != 0)
{
n_delete stream;
}
stream = n_new unsigned char[size];
n_assert(stream != 0);
streamSize = size;
Clear();
n_assert(streamSize == size);
}
//------------------------------------------------------------------------------
/**
*/
inline
int
nBitStream::GetSize() const
{
return streamSize;
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::SetPos(int pos)
{
n_assert(!writeable); // Can't change bit pos while writing!!!
n_assert((0 <= pos) && (pos <= streamSize * 8));
currentByte = pos / 8;
currentBit = pos % 8;
}
//------------------------------------------------------------------------------
/**
*/
inline
int
nBitStream::GetPos() const
{
return (currentByte * 8) + currentBit;
}
//------------------------------------------------------------------------------
/**
*/
inline
int
nBitStream::BitsLeft() const
{
return (GetSize() * 8) - GetPos();
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::Copy(const nBitStream& source)
{
n_assert(source.streamSize > 0);
n_assert(source.streamSize == streamSize);
n_assert(stream != 0);
n_assert(source.stream != 0);
memcpy(stream, source.stream, source.streamSize);
currentBit = streamSize * 8;
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::BeginWrite()
{
n_assert(!writeable);
n_assert(!readable);
Clear();
SetPos(0);
writeable = true;
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::EndWrite()
{
n_assert(writeable);
n_assert(!readable);
writeable = false;
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::BeginRead()
{
n_assert(!readable);
n_assert(!writeable);
SetPos(0);
readable = true;
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::EndRead()
{
n_assert(readable);
n_assert(!writeable);
readable = false;
}
//------------------------------------------------------------------------------
/**
*/
inline
bool
nBitStream::IsWriteable() const
{
return writeable;
}
//------------------------------------------------------------------------------
/**
*/
inline
bool
nBitStream::IsReadable() const
{
return readable;
}
//------------------------------------------------------------------------------
/**
Print debug data to stdout.
*/
inline
void
nBitStream::Print(int lines)
{
// require
n_assert(stream != 0);
// print out the first bits
for (int i = 0; i < lines; i++)
{
n_printf("%4.d: ", i + 1);
char ch = stream[i];
for (int j = 0; j < 8; j++)
{
if ( ch & ( 1 << ( 7 - j ) ) )
{
n_printf( "%d", 1 );
}
else
{
n_printf( "%d", 0 );
}
}
n_printf( "\n" );
}
}
//------------------------------------------------------------------------------
/**
Assignment operator.
*/
inline
nBitStream&
nBitStream::operator = (const nBitStream& s)
{
n_assert(s.streamSize > 0);
n_assert(s.streamSize == streamSize);
n_assert(stream != 0);
n_assert(s.stream != 0);
Copy(s);
return *this;
}
//------------------------------------------------------------------------------
/**
Equality operator.
*/
inline
bool
nBitStream::operator == (const nBitStream& s) const
{
if (streamSize != s.streamSize) return false;
return (memcmp(stream, s.stream, streamSize) == 0);
}
//------------------------------------------------------------------------------
/**
Inequality operator.
*/
inline
bool
nBitStream::operator != (const nBitStream& s) const
{
if (streamSize != s.streamSize) return true;
return (memcmp(stream, s.stream, streamSize) != 0);
}
//------------------------------------------------------------------------------
/**
*/
inline
void
nBitStream::WriteBit(bool bit)
{
n_assert(stream != 0);
n_assert(BitsLeft() >= 1);
n_assert(IsWriteable());
// Set bit at current bit in current byte;
// assume that all upcomming bits are cleared
if (bit)
{
int v = (bit) ? 1 : 0;
stream[currentByte] |= (v << (7 - currentBit));
}
// Advance to next byte if current bit is 8!
if (++currentBit == 8)
{
currentByte++;
currentBit = 0;
}
}
//------------------------------------------------------------------------------
/**
*/
inline
bool
nBitStream::ReadBit()
{
n_assert(stream != 0);
n_assert(BitsLeft() >= 1);
n_assert(IsReadable());
// Read current bit
bool flag = ((stream[currentByte] & (1 << (7 - currentBit))) != 0);
// Advance to next byte if current bit is 8!
if (++currentBit == 8)
{
currentByte++;
currentBit = 0;
}
return flag;
}
#endif
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
717
]
]
]
|
d7d63c89bc3c212a0f6e50ccb95f43301fd9cd1c | 5b2b0e9131a27043573107bf42d8ca7641ba511a | /PropsSounds.h | 05aea4c736cbf7820a868cf0ddbc1362eea59e4a | [
"MIT"
]
| permissive | acastroy/pumpkin | 0b1932e9c1fe7672a707cc04f092d98cfcecbd4e | 6e7e413ca364d79673e523c09767c18e7cff1bec | refs/heads/master | 2023-03-15T20:43:59.544227 | 2011-04-27T16:24:42 | 2011-04-27T16:24:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,352 | h | // PropsSounds.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CPropsSounds dialog
class CPropsSounds : public CPropertyPage
{
DECLARE_DYNCREATE(CPropsSounds)
// Construction
public:
void Play(CComboBox& ctl);
void Browse(CComboBox& ctl);
CBellsNWhistles* m_bnw;
CPropsSounds();
~CPropsSounds();
// Dialog Data
//{{AFX_DATA(CPropsSounds)
enum { IDD = IDD_PROPS_SOUNDS };
CButton m_RequestPlayCtl;
CButton m_RequestBrowseCtl;
CComboBox m_RequestCtl;
CButton m_SuccessPlayCtl;
CButton m_SuccessBrowseCtl;
CComboBox m_SuccessCtl;
CButton m_AbortPlayCtl;
CButton m_AbortBrowseCtl;
CComboBox m_AbortCtl;
CString m_Abort;
CString m_Success;
CString m_Request;
//}}AFX_DATA
// Overrides
// ClassWizard generate virtual function overrides
//{{AFX_VIRTUAL(CPropsSounds)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CPropsSounds)
virtual BOOL OnInitDialog();
afx_msg void OnAbortedBrowse();
afx_msg void OnFinishedBrowse();
afx_msg void OnRingBrowse();
afx_msg void OnAbortedPlay();
afx_msg void OnFinishedPlay();
afx_msg void OnRingPlay();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]"
]
| [
[
[
1,
58
]
]
]
|
7699839505392a09eba13ffc87a50ff934285f37 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/kernelhwsrv/base/validation/f32/sfsrv/inc/T_SfSrvServer.h | 03acbea20f215c3fcc31501ac44dda6c7d7e66df | []
| 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 | 1,359 | h | /*
* Copyright (c) 2007-2008 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:
*
*/
/**
@test
@internalComponent
This contains CT_SfSrvServer
*/
#ifndef __T_SFSRV_SERVER_H__
#define __T_SFSRV_SERVER_H__
#include <testblockcontroller.h>
#include <testserver2.h>
#include "T_FsData.h"
#include "T_FileData.h"
#include "T_FormatData.h"
#include "T_FileManData.h"
_LIT(KRFs, "RFs");
_LIT(KRFile, "RFile");
_LIT(KRFormat, "RFormat");
_LIT(KCFileMan, "CFileMan");
class CT_SfSrvServer : public CTestServer2
{
private:
class CT_SfSrvBlock : public CTestBlockController
{
public:
inline CT_SfSrvBlock();
inline ~CT_SfSrvBlock();
inline CDataWrapper* CreateDataL(const TDesC& aData);
};
public:
static CT_SfSrvServer* NewL();
inline ~CT_SfSrvServer();
inline CTestBlockController* CreateTestBlock();
protected:
inline CT_SfSrvServer();
};
#include "T_SfSrvServer.inl"
#endif // __T_SFSRV_SERVER_H__
| [
"none@none"
]
| [
[
[
1,
66
]
]
]
|
f9b3add955c9110039c31b34d3ae38106cd85947 | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /libs/lith/lithsimparystat.cpp | cf9280bc2447295599a662b4e7748c1ad5386eb8 | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34 | cpp |
#include "lithsimparystat.h"
| [
"[email protected]"
]
| [
[
[
1,
3
]
]
]
|
fc1682a3c215cc38b377cda01a5e923e375305e9 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Geometry/WmlConvexPolyhedron3.cpp | 40705713a98127fd2b3f7bec5e5c95e35ec02054 | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,372 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlConvexPolyhedron3.h"
#include "WmlConvexClipper.h"
#include <fstream>
#include <map>
#include <set>
using namespace Wml;
using namespace std;
//----------------------------------------------------------------------------
template <class Real>
ConvexPolyhedron3<Real>::ConvexPolyhedron3 ()
{
}
//----------------------------------------------------------------------------
template <class Real>
ConvexPolyhedron3<Real>::ConvexPolyhedron3 (const V3Array& rakPoint,
const IArray& raiConnect)
{
Create(rakPoint,raiConnect);
}
//----------------------------------------------------------------------------
template <class Real>
ConvexPolyhedron3<Real>::ConvexPolyhedron3 (const V3Array& rakPoint,
const IArray& raiConnect, const PArray& rakPlane)
{
Create(rakPoint,raiConnect,rakPlane);
}
//----------------------------------------------------------------------------
template <class Real>
ConvexPolyhedron3<Real>::ConvexPolyhedron3 (const ConvexPolyhedron3& rkPoly)
:
MTMesh(rkPoly),
m_akPoint(rkPoly.m_akPoint),
m_akPlane(rkPoly.m_akPlane)
{
}
//----------------------------------------------------------------------------
template <class Real>
void ConvexPolyhedron3<Real>::Create (const V3Array& rakPoint,
const IArray& raiConnect)
{
assert( rakPoint.size() >= 4 && raiConnect.size() >= 4 );
int iVQuantity = (int)rakPoint.size();
int iTQuantity = (int)raiConnect.size()/3;
int iEQuantity = iVQuantity + iTQuantity - 2;
Reset(iVQuantity,iEQuantity,iTQuantity);
m_akPoint = rakPoint;
// Copy polyhedron points into vertex array. Compute centroid for use in
// making sure the triangles are counterclockwise oriented when viewed
// from the outside.
ComputeCentroid();
// get polyhedron edge and triangle information
for (int iT = 0, iIndex = 0; iT < iTQuantity; iT++)
{
// get vertex indices for triangle
int iV0 = raiConnect[iIndex++];
int iV1 = raiConnect[iIndex++];
int iV2 = raiConnect[iIndex++];
// make sure triangle is counterclockwise
Vector3<Real>& rkV0 = m_akPoint[iV0];
Vector3<Real>& rkV1 = m_akPoint[iV1];
Vector3<Real>& rkV2 = m_akPoint[iV2];
Vector3<Real> kDiff = m_kCentroid - rkV0;
Vector3<Real> kE1 = rkV1 - rkV0;
Vector3<Real> kE2 = rkV2 - rkV0;
Vector3<Real> kNormal = kE1.Cross(kE2);
Real fLength = kNormal.Length();
if ( fLength > Math<Real>::EPSILON )
{
kNormal /= fLength;
}
else
{
kNormal = kDiff;
kNormal.Normalize();
}
Real fDistance = kNormal.Dot(kDiff);
if ( fDistance < (Real)0.0 )
{
// triangle is counterclockwise
Insert(iV0,iV1,iV2);
}
else
{
// triangle is clockwise
Insert(iV0,iV2,iV1);
}
}
UpdatePlanes();
}
//----------------------------------------------------------------------------
template <class Real>
void ConvexPolyhedron3<Real>::Create (const V3Array& rakPoint,
const IArray& raiConnect, const PArray& rakPlane)
{
assert( rakPoint.size() >= 4 && raiConnect.size() >= 4 );
int iVQuantity = (int)rakPoint.size();
int iTQuantity = (int)raiConnect.size()/3;
int iEQuantity = iVQuantity + iTQuantity - 2;
Reset(iVQuantity,iEQuantity,iTQuantity);
m_akPoint = rakPoint;
m_akPlane = rakPlane;
// Copy polyhedron points into vertex array. Compute centroid for use in
// making sure the triangles are counterclockwise oriented when viewed
// from the outside.
ComputeCentroid();
// get polyhedron edge and triangle information
for (int iT = 0, iIndex = 0; iT < iTQuantity; iT++)
{
// get vertex indices for triangle
int iV0 = raiConnect[iIndex++];
int iV1 = raiConnect[iIndex++];
int iV2 = raiConnect[iIndex++];
Real fDistance = m_akPlane[iT].DistanceTo(m_kCentroid);
if ( fDistance > (Real)0.0 )
{
// triangle is counterclockwise
Insert(iV0,iV1,iV2);
}
else
{
// triangle is clockwise
Insert(iV0,iV2,iV1);
}
}
}
//----------------------------------------------------------------------------
template <class Real>
const typename ConvexPolyhedron3<Real>::V3Array&
ConvexPolyhedron3<Real>::GetPoints () const
{
return m_akPoint;
}
//----------------------------------------------------------------------------
template <class Real>
const Vector3<Real>& ConvexPolyhedron3<Real>::GetPoint (int iV) const
{
assert( 0 <= iV && iV < (int)m_akPoint.size() );
return m_akPoint[iV];
}
//----------------------------------------------------------------------------
template <class Real>
int ConvexPolyhedron3<Real>::AddPoint (const Vector3<Real>& rkPoint)
{
int iLocation = (int)m_akPoint.size();
m_akPoint.push_back(rkPoint);
return iLocation;
}
//----------------------------------------------------------------------------
template <class Real>
typename ConvexPolyhedron3<Real>::V3Array& ConvexPolyhedron3<Real>::Points ()
{
return m_akPoint;
}
//----------------------------------------------------------------------------
template <class Real>
Vector3<Real>& ConvexPolyhedron3<Real>::Point (int iV)
{
assert( 0 <= iV && iV < (int)m_akPoint.size() );
return m_akPoint[iV];
}
//----------------------------------------------------------------------------
template <class Real>
const typename ConvexPolyhedron3<Real>::PArray&
ConvexPolyhedron3<Real>::GetPlanes () const
{
return m_akPlane;
}
//----------------------------------------------------------------------------
template <class Real>
const Plane3<Real>& ConvexPolyhedron3<Real>::GetPlane (int iT) const
{
assert( 0 <= iT && iT < (int)m_akPlane.size() );
return m_akPlane[iT];
}
//----------------------------------------------------------------------------
template <class Real>
const Vector3<Real>& ConvexPolyhedron3<Real>::GetCentroid () const
{
return m_kCentroid;
}
//----------------------------------------------------------------------------
template <class Real>
ConvexPolyhedron3<Real>& ConvexPolyhedron3<Real>::operator= (
const ConvexPolyhedron3& rkPoly)
{
MTMesh::operator=(rkPoly);
m_akPoint = rkPoly.m_akPoint;
m_akPlane = rkPoly.m_akPlane;
return *this;
}
//----------------------------------------------------------------------------
template <class Real>
void ConvexPolyhedron3<Real>::UpdatePlanes ()
{
// The planes are constructed to have *inner pointing* normals. This
// supports my Wild Magic software clipping code that was based on a view
// frustum having inner pointing normals.
ComputeCentroid();
int iTQuantity = m_akTriangle.GetQuantity();
m_akPlane.resize(iTQuantity);
for (int iT = 0; iT < iTQuantity; iT++)
{
MTTriangle& rkT = m_akTriangle[iT];
int iV0 = GetVLabel(rkT.Vertex(0));
int iV1 = GetVLabel(rkT.Vertex(1));
int iV2 = GetVLabel(rkT.Vertex(2));
Vector3<Real>& rkV0 = m_akPoint[iV0];
Vector3<Real>& rkV1 = m_akPoint[iV1];
Vector3<Real>& rkV2 = m_akPoint[iV2];
Vector3<Real> kDiff = m_kCentroid - rkV0;
Vector3<Real> kE1 = rkV1 - rkV0;
Vector3<Real> kE2 = rkV2 - rkV0;
Vector3<Real> kNormal = kE2.Cross(kE1);
Real fLength = kNormal.Length();
if ( fLength > Math<Real>::EPSILON )
{
kNormal /= fLength;
Real fDot = kNormal.Dot(kDiff);
if ( fDot < (Real)0.0 )
kNormal = -kNormal;
}
else
{
// triangle is degenerate, use "normal" that points towards
// centroid
kNormal = kDiff;
kNormal.Normalize();
}
// inner pointing normal
m_akPlane[iT] = Plane3<Real>(kNormal,kNormal.Dot(rkV0));
}
}
//----------------------------------------------------------------------------
template <class Real>
bool ConvexPolyhedron3<Real>::ValidateHalfSpaceProperty (Real fThreshold)
const
{
Real fMax = -Math<Real>::MAX_REAL, fMin = Math<Real>::MAX_REAL;
for (int iT = 0; iT < m_akTriangle.GetQuantity(); iT++)
{
const Plane3<Real>& rkPlane = m_akPlane[iT];
for (int i = 0; i < (int)m_akPoint.size(); i++)
{
Real fDistance = rkPlane.DistanceTo(m_akPoint[i]);
if ( fDistance < fMin )
fMin = fDistance;
if ( fDistance > fMax )
fMax = fDistance;
if ( fDistance < fThreshold )
return false;
}
}
return true;
}
//----------------------------------------------------------------------------
template <class Real>
void ConvexPolyhedron3<Real>::ComputeCentroid ()
{
m_kCentroid = Vector3<Real>::ZERO;
for (int iV = 0; iV < (int)m_akPoint.size(); iV++)
m_kCentroid += m_akPoint[iV];
m_kCentroid /= (Real)m_akPoint.size();
}
//----------------------------------------------------------------------------
template <class Real>
bool ConvexPolyhedron3<Real>::Clip (const Plane3<Real>& rkPlane,
ConvexPolyhedron3& rkIntr) const
{
ConvexClipper<Real> kClipper(*this);
int iSide = kClipper.Clip(rkPlane);
if ( iSide == Plane3<Real>::POSITIVE_SIDE )
{
rkIntr = *this;
return true;
}
if ( iSide == Plane3<Real>::NEGATIVE_SIDE )
return false;
kClipper.Convert(rkIntr);
return true;
}
//----------------------------------------------------------------------------
template <class Real>
bool ConvexPolyhedron3<Real>::FindIntersection (
const ConvexPolyhedron3& rkPoly, ConvexPolyhedron3& rkIntr) const
{
ConvexClipper<Real> kClipper(*this);
const PArray& rakPlane = rkPoly.GetPlanes();
for (int i = 0; i < (int)rakPlane.size(); i++)
{
if ( kClipper.Clip(rakPlane[i]) == Plane3<Real>::NEGATIVE_SIDE )
return false;
}
kClipper.Convert(rkIntr);
return true;
}
//----------------------------------------------------------------------------
template <class Real>
void ConvexPolyhedron3<Real>::FindAllIntersections (int iQuantity,
ConvexPolyhedron3* akPoly, int& riCombos, ConvexPolyhedron3**& rapkIntr)
{
// Only 2^16 possible combinations for intersections are currently
// supported. If you need more, then GetHighBit(int) must be modified
// to handle more than 16-bit inputs.
if ( iQuantity <= 0 || iQuantity > 16 )
{
riCombos = 0;
rapkIntr = NULL;
return;
}
riCombos = (1 << iQuantity);
bool* abNeedsTesting = new bool[riCombos];
rapkIntr = new ConvexPolyhedron3*[riCombos];
int i;
for (i = 0; i < riCombos; i++)
{
abNeedsTesting[i] = true;
rapkIntr[i] = NULL;
}
// trivial cases, zero or one polyhedron--already the intersection
abNeedsTesting[0] = false;
for (i = 0; i < iQuantity; i++)
{
int j = (1 << i);
abNeedsTesting[j] = false;
rapkIntr[j] = new ConvexPolyhedron3(akPoly[i]);
}
for (i = 3; i < riCombos; i++)
{
if ( abNeedsTesting[i] )
{
// In binary, i = b[m]...b[0] where b[m] is not zero (the
// high-order bit. Also, i1 = b[m-1]...b[0] is not zero
// since, if it were, we would have ruled out the combination
// by the j-loop below. Therefore, i0 = b[m]0...0 and
// i1 correspond to already existing polyhedra. The
// intersection finding just needs to look at the intersection
// of the two polyhedra.
int i0 = GetHighBit(i);
int i1 = i & ~i0;
rapkIntr[i] = FindSolidIntersection(*rapkIntr[i0],
*rapkIntr[i1]);
if ( !rapkIntr[i] )
{
// No intersection for this combination. No need to test
// other combinations that include this one.
for (int j = 0; j < riCombos; j++)
{
if ( (i & j) == i )
abNeedsTesting[j] = false;
}
}
#ifdef _DEBUG
else // test if well-formed convex polyhedron
{
Vector3<Real> kCentroid = rapkIntr[i]->GetCentroid();
bool bContains = rapkIntr[i]->ContainsPoint(kCentroid);
assert( bContains );
}
#endif
}
}
delete[] abNeedsTesting;
}
//----------------------------------------------------------------------------
template <class Real>
ConvexPolyhedron3<Real>* ConvexPolyhedron3<Real>::FindSolidIntersection (
const ConvexPolyhedron3& rkPoly0, const ConvexPolyhedron3& rkPoly1)
{
ConvexPolyhedron3* pkIntr = new ConvexPolyhedron3;
if ( rkPoly0.FindIntersection(rkPoly1,*pkIntr) )
return pkIntr;
// As surfaces, the polyhedra do not intersect. However, as solids,
// one polyhedron might be fully contained in the other.
if ( rkPoly0.ContainsPoint(rkPoly1.GetCentroid()) )
{
*pkIntr = rkPoly1;
return pkIntr;
}
if ( rkPoly1.ContainsPoint(rkPoly0.GetCentroid()) )
{
*pkIntr = rkPoly0;
return pkIntr;
}
delete pkIntr;
return NULL;
}
//----------------------------------------------------------------------------
template <class Real>
int ConvexPolyhedron3<Real>::GetHighBit (int i)
{
// assert: i in [1,2^16]. That is, (i>0) && (0xFFFF0000&i)==0.
// This is a binary search for the high-order bit of i.
if ( (i & 0xFF00) != 0 )
{
if ( (i & 0xF000) != 0 )
{
if ( (i & 0xC000) != 0 )
{
if ( (i & 0x8000) != 0 )
return 0x8000;
else // (i & 0x4000) != 0
return 0x4000;
}
else // (i & 0x3000) != 0
{
if ( (i & 0x2000) != 0 )
return 0x2000;
else // (i & 0x1000) != 0
return 0x1000;
}
}
else // (i & 0x0F00) != 0
{
if ( (i & 0x0C00) != 0 )
{
if ( (i & 0x0800) != 0 )
return 0x0800;
else // (i & 0x0400) != 0
return 0x0400;
}
else // (i & 0x0300) != 0
{
if ( (i & 0x0200) != 0 )
return 0x0200;
else // (i & 0x0100) != 0
return 0x0100;
}
}
}
else // (i & 0x00FF)
{
if ( (i & 0x00F0) != 0 )
{
if ( (i & 0x00C0) != 0 )
{
if ( (i & 0x0080) != 0 )
return 0x0080;
else // (i & 0x0040) != 0
return 0x0040;
}
else // (i & 0x0030) != 0
{
if ( (i & 0x0020) != 0 )
return 0x0020;
else // (i & 0x0010) != 0
return 0x0010;
}
}
else // (i & 0x000F) != 0
{
if ( (i & 0x000C) != 0 )
{
if ( (i & 0x0008) != 0 )
return 0x0008;
else // (i & 0x0004) != 0
return 0x0004;
}
else // (i & 0x0003) != 0
{
if ( (i & 0x0002) != 0 )
return 0x0002;
else // (i & 0x0001) != 0
return 0x0001;
}
}
}
}
//----------------------------------------------------------------------------
template <class Real>
Real ConvexPolyhedron3<Real>::GetTriangleArea (const Vector3<Real>& rkN,
const Vector3<Real>& rkV0, const Vector3<Real>& rkV1,
const Vector3<Real>& rkV2) const
{
// compute maximum absolute component of normal vector
int iMax = 0;
Real fMax = Math<Real>::FAbs(rkN.X());
Real fAbs = Math<Real>::FAbs(rkN.Y());
if ( fAbs > fMax )
{
iMax = 1;
fMax = fAbs;
}
fAbs = Math<Real>::FAbs(rkN.Z());
if ( fAbs > fMax )
{
iMax = 2;
fMax = fAbs;
}
// catch degenerate triangles
if ( fMax == (Real)0.0 )
return (Real)0.0;
// compute area of projected triangle
Real fD0, fD1, fD2, fArea;
if ( iMax == 0 )
{
fD0 = rkV1.Z() - rkV2.Z();
fD1 = rkV2.Z() - rkV0.Z();
fD2 = rkV0.Z() - rkV1.Z();
fArea = Math<Real>::FAbs(rkV0.Y()*fD0 + rkV1.Y()*fD1 + rkV2.Y()*fD2);
}
else if ( iMax == 1 )
{
fD0 = rkV1.X() - rkV2.X();
fD1 = rkV2.X() - rkV0.X();
fD2 = rkV0.X() - rkV1.X();
fArea = Math<Real>::FAbs(rkV0.Z()*fD0 + rkV1.Z()*fD1 + rkV2.Z()*fD2);
}
else
{
fD0 = rkV1.Y() - rkV2.Y();
fD1 = rkV2.Y() - rkV0.Y();
fD2 = rkV0.Y() - rkV1.Y();
fArea = Math<Real>::FAbs(rkV0.X()*fD0 + rkV1.X()*fD1 + rkV2.X()*fD2);
}
fArea *= ((Real)0.5)/fMax;
return fArea;
}
//----------------------------------------------------------------------------
template <class Real>
Real ConvexPolyhedron3<Real>::GetSurfaceArea () const
{
Real fSurfaceArea = (Real)0.0;
for (int iT = 0; iT < m_akTriangle.GetQuantity(); iT++)
{
const MTTriangle& rkT = m_akTriangle.Get(iT);
int iV0 = GetVLabel(rkT.GetVertex(0));
int iV1 = GetVLabel(rkT.GetVertex(1));
int iV2 = GetVLabel(rkT.GetVertex(2));
const Vector3<Real>& rkV0 = m_akPoint[iV0];
const Vector3<Real>& rkV1 = m_akPoint[iV1];
const Vector3<Real>& rkV2 = m_akPoint[iV2];
const Vector3<Real>& rkN = m_akPlane[iT].GetNormal();
fSurfaceArea += GetTriangleArea(rkN,rkV0,rkV1,rkV2);
}
return fSurfaceArea;
}
//----------------------------------------------------------------------------
template <class Real>
Real ConvexPolyhedron3<Real>::GetVolume () const
{
Real fVolume = (Real)0.0;
for (int iT = 0; iT < m_akTriangle.GetQuantity(); iT++)
{
const MTTriangle& rkT = m_akTriangle.Get(iT);
int iV0 = GetVLabel(rkT.GetVertex(0));
int iV1 = GetVLabel(rkT.GetVertex(1));
int iV2 = GetVLabel(rkT.GetVertex(2));
const Vector3<Real>& rkV0 = m_akPoint[iV0];
const Vector3<Real>& rkV1 = m_akPoint[iV1];
const Vector3<Real>& rkV2 = m_akPoint[iV2];
fVolume += rkV0.Dot(rkV1.Cross(rkV2));
}
fVolume /= (Real)6.0;
return fVolume;
}
//----------------------------------------------------------------------------
template <class Real>
bool ConvexPolyhedron3<Real>::ContainsPoint (const Vector3<Real>& rkP) const
{
for (int iT = 0; iT < m_akTriangle.GetQuantity(); iT++)
{
Real fDistance = m_akPlane[iT].DistanceTo(rkP);
if ( fDistance < (Real)0.0 )
return false;
}
return true;
}
//----------------------------------------------------------------------------
template <class Real>
Real ConvexPolyhedron3<Real>::GetDistance (const Vector3<Real>& rkEye, int iT,
vector<Real>& rafDistance) const
{
// Signed distance from eye to plane of triangle. When distance is
// positive, triangle is visible from eye (front-facing). When distance
// is negative, triangle is not visible from eye (back-facing). When
// distance is zero, triangle is visible "on-edge" from eye.
if ( rafDistance[iT] == Math<Real>::MAX_REAL )
{
rafDistance[iT] = -m_akPlane[iT].DistanceTo(rkEye);
if ( Math<Real>::FAbs(rafDistance[iT]) < Math<Real>::EPSILON )
rafDistance[iT] = (Real)0.0;
}
return rafDistance[iT];
}
//----------------------------------------------------------------------------
template <class Real>
bool ConvexPolyhedron3<Real>::IsNegativeProduct (Real fDist0, Real fDist1)
{
return (fDist0 != (Real)0.0 ? (fDist0*fDist1 <= (Real)0.0) :
(fDist1 != (Real)0.0));
}
//----------------------------------------------------------------------------
template <class Real>
void ConvexPolyhedron3<Real>::ComputeTerminator (const Vector3<Real>& rkEye,
V3Array& rkTerminator)
{
// temporary storage for signed distances from eye to triangles
int iTQuantity = m_akTriangle.GetQuantity();
vector<Real> afDistance(iTQuantity);
int i, j;
for (i = 0; i < iTQuantity; i++)
afDistance[i] = Math<Real>::MAX_REAL;
// Start a search for a front-facing triangle that has an adjacent
// back-facing triangle or for a back-facing triangle that has an
// adjacent front-facing triangle.
int iTCurrent = 0;
MTTriangle* pkTCurrent = &m_akTriangle[iTCurrent];
Real fTriDist = GetDistance(rkEye,iTCurrent,afDistance);
int iEFirst = -1;
for (i = 0; i < iTQuantity; i++)
{
// Check adjacent neighbors for edge of terminator. Such an
// edge occurs if the signed distance changes sign.
int iMinIndex = -1;
Real fMinAbsDist = Math<Real>::MAX_REAL;
Real afAdjDist[3];
for (j = 0; j < 3; j++)
{
afAdjDist[j] = GetDistance(rkEye,pkTCurrent->Adjacent(j),
afDistance);
if ( IsNegativeProduct(fTriDist,afAdjDist[j]) )
{
iEFirst = pkTCurrent->Edge(j);
break;
}
Real fAbsDist = Math<Real>::FAbs(afAdjDist[j]);
if ( fAbsDist < fMinAbsDist )
{
fMinAbsDist = fAbsDist;
iMinIndex = j;
}
}
if ( j < 3 )
break;
// First edge not found during this iteration. Move to adjacent
// triangle whose distance is smallest of all adjacent triangles.
iTCurrent = pkTCurrent->Adjacent(iMinIndex);
pkTCurrent = &m_akTriangle[iTCurrent];
fTriDist = afAdjDist[iMinIndex];
}
assert( i < iTQuantity );
MTEdge& rkEFirst = m_akEdge[iEFirst];
rkTerminator.push_back(m_akPoint[GetVLabel(rkEFirst.Vertex(0))]);
rkTerminator.push_back(m_akPoint[GetVLabel(rkEFirst.Vertex(1))]);
// walk along the terminator
int iVFirst = rkEFirst.Vertex(0);
int iV = rkEFirst.Vertex(1);
int iE = iEFirst;
int iEQuantity = m_akEdge.GetQuantity();
for (i = 0; i < iEQuantity; i++)
{
// search all edges sharing the vertex for another terminator edge
int j, jMax = m_akVertex[iV].GetEdgeQuantity();
for (j = 0; j < m_akVertex[iV].GetEdgeQuantity(); j++)
{
int iENext = m_akVertex[iV].GetEdge(j);
if ( iENext == iE )
continue;
Real fDist0 = GetDistance(rkEye,m_akEdge[iENext].GetTriangle(0),
afDistance);
Real fDist1 = GetDistance(rkEye,m_akEdge[iENext].GetTriangle(1),
afDistance);
if ( IsNegativeProduct(fDist0,fDist1) )
{
if ( m_akEdge[iENext].GetVertex(0) == iV )
{
iV = m_akEdge[iENext].GetVertex(1);
rkTerminator.push_back(m_akPoint[GetVLabel(iV)]);
if ( iV == iVFirst )
return;
}
else
{
iV = m_akEdge[iENext].GetVertex(0);
rkTerminator.push_back(m_akPoint[GetVLabel(iV)]);
if ( iV == iVFirst )
return;
}
iE = iENext;
break;
}
}
assert( j < jMax );
}
assert( i < iEQuantity );
}
//----------------------------------------------------------------------------
template <class Real>
bool ConvexPolyhedron3<Real>::ComputeSilhouette (const Vector3<Real>& rkEye,
const Plane3<Real>& rkPlane, const Vector3<Real>& rkU,
const Vector3<Real>& rkV, V2Array& rkSilhouette)
{
V3Array kTerminator;
ComputeTerminator(rkEye,kTerminator);
return ComputeSilhouette(kTerminator,rkEye,rkPlane,rkU,rkV,rkSilhouette);
}
//----------------------------------------------------------------------------
template <class Real>
bool ConvexPolyhedron3<Real>::ComputeSilhouette (V3Array& rkTerminator,
const Vector3<Real>& rkEye, const Plane3<Real>& rkPlane,
const Vector3<Real>& rkU, const Vector3<Real>& rkV,
V2Array& rkSilhouette)
{
Real fEDist = rkPlane.DistanceTo(rkEye); // assert: fEDist > 0
// closest planar point to E is K = E-dist*N
Vector3<Real> kClosest = rkEye - fEDist*rkPlane.GetNormal();
// project polyhedron points onto plane
for (int i = 0; i < (int)rkTerminator.size(); i++)
{
Vector3<Real>& rkPoint = rkTerminator[i];
Real fVDist = rkPlane.DistanceTo(rkPoint);
if ( fVDist >= fEDist )
{
// cannot project vertex onto plane
return false;
}
// compute projected point Q
Real fRatio = fEDist/(fEDist-fVDist);
Vector3<Real> kProjected = rkEye + fRatio*(rkPoint - rkEye);
// compute (x,y) so that Q = K+x*U+y*V+z*N
Vector3<Real> kDiff = kProjected - kClosest;
rkSilhouette.push_back(Vector2<Real>(rkU.Dot(kDiff),rkV.Dot(kDiff)));
}
return true;
}
//----------------------------------------------------------------------------
template <class Real>
void ConvexPolyhedron3<Real>::CreateEggShape (const Vector3<Real>& rkCenter,
Real fX0, Real fX1, Real fY0, Real fY1, Real fZ0, Real fZ1,
int iMaxSteps, ConvexPolyhedron3& rkEgg)
{
assert( fX0 > (Real)0.0 && fX1 > (Real)0.0 );
assert( fY0 > (Real)0.0 && fY1 > (Real)0.0 );
assert( fZ0 > (Real)0.0 && fZ1 > (Real)0.0 );
assert( iMaxSteps >= 0 );
// Start with an octahedron whose 6 vertices are (-x0,0,0), (x1,0,0),
// (0,-y0,0), (0,y1,0), (0,0,-z0), (0,0,z1). The center point will be
// added later.
V3Array akPoint(6);
akPoint[0] = Vector3<Real>(-fX0,(Real)0.0,(Real)0.0);
akPoint[1] = Vector3<Real>(fX1,(Real)0.0,(Real)0.0);
akPoint[2] = Vector3<Real>((Real)0.0,-fY0,(Real)0.0);
akPoint[3] = Vector3<Real>((Real)0.0,fY1,(Real)0.0);
akPoint[4] = Vector3<Real>((Real)0.0,(Real)0.0,-fZ0);
akPoint[5] = Vector3<Real>((Real)0.0,(Real)0.0,fZ1);
IArray aiConnect(24);
aiConnect[ 0] = 1; aiConnect[ 1] = 3; aiConnect[ 2] = 5;
aiConnect[ 3] = 3; aiConnect[ 4] = 0; aiConnect[ 5] = 5;
aiConnect[ 6] = 0; aiConnect[ 7] = 2; aiConnect[ 8] = 5;
aiConnect[ 9] = 2; aiConnect[10] = 1; aiConnect[11] = 5;
aiConnect[12] = 3; aiConnect[13] = 1; aiConnect[14] = 4;
aiConnect[15] = 0; aiConnect[16] = 3; aiConnect[17] = 4;
aiConnect[18] = 2; aiConnect[19] = 0; aiConnect[20] = 4;
aiConnect[21] = 1; aiConnect[22] = 2; aiConnect[23] = 4;
rkEgg.InitialELabel() = 0;
rkEgg.Create(akPoint,aiConnect);
// Subdivide the triangles. The midpoints of the edges are computed.
// The triangle is replaced by four sub triangles using the original 3
// vertices and the 3 new edge midpoints.
int i;
for (int iStep = 1; iStep <= iMaxSteps; iStep++)
{
int iVQuantity = rkEgg.GetVQuantity();
int iEQuantity = rkEgg.GetEQuantity();
int iTQuantity = rkEgg.GetTQuantity();
// compute lifted edge midpoints
for (i = 0; i < iEQuantity; i++)
{
// get edge
const MTEdge& rkE = rkEgg.GetEdge(i);
int iV0 = rkEgg.GetVLabel(rkE.GetVertex(0));
int iV1 = rkEgg.GetVLabel(rkE.GetVertex(1));
// compute "lifted" centroid to points
Vector3<Real> kCen = rkEgg.Point(iV0)+rkEgg.Point(iV1);
Real fXR = (kCen.X() > (Real)0.0 ? kCen.X()/fX1 : kCen.X()/fX0);
Real fYR = (kCen.Y() > (Real)0.0 ? kCen.Y()/fY1 : kCen.Y()/fY0);
Real fZR = (kCen.Z() > (Real)0.0 ? kCen.Z()/fZ1 : kCen.Z()/fZ0);
kCen *= Math<Real>::InvSqrt(fXR*fXR+fYR*fYR+fZR*fZR);
// Add the point to the array. Store the point index in the edge
// label for support in adding new triangles.
rkEgg.ELabel(i) = iVQuantity++;
rkEgg.AddPoint(kCen);
}
// Add the new triangles and remove the old triangle. The removal
// in slot i will cause the last added triangle to be moved to that
// slot. This side effect will not interfere with the iteration
// and removal of the triangles.
for (i = 0; i < iTQuantity; i++)
{
const MTTriangle& rkT = rkEgg.GetTriangle(i);
int iV0 = rkEgg.GetVLabel(rkT.GetVertex(0));
int iV1 = rkEgg.GetVLabel(rkT.GetVertex(1));
int iV2 = rkEgg.GetVLabel(rkT.GetVertex(2));
int iV01 = rkEgg.GetELabel(rkT.GetEdge(0));
int iV12 = rkEgg.GetELabel(rkT.GetEdge(1));
int iV20 = rkEgg.GetELabel(rkT.GetEdge(2));
rkEgg.Insert(iV0,iV01,iV20);
rkEgg.Insert(iV01,iV1,iV12);
rkEgg.Insert(iV20,iV12,iV2);
rkEgg.Insert(iV01,iV12,iV20);
rkEgg.Remove(iV0,iV1,iV2);
}
}
// add center
for (i = 0; i < (int)rkEgg.m_akPoint.size(); i++)
rkEgg.m_akPoint[i] += rkCenter;
rkEgg.UpdatePlanes();
}
//----------------------------------------------------------------------------
template <class Real>
void ConvexPolyhedron3<Real>::Print (ofstream& rkOStr) const
{
MTMesh::Print(rkOStr);
int i;
char acMsg[512];
rkOStr << "points:" << endl;
for (i = 0; i < (int)m_akPoint.size(); i++)
{
const Vector3<Real>& rkV = m_akPoint[i];
sprintf(acMsg,"point<%d> = (%+8.4f,%+8.4f,%+8.4f)",i,rkV.X(),rkV.Y(),
rkV.Z());
rkOStr << acMsg << endl;
}
rkOStr << endl;
rkOStr << "planes:" << endl;
for (i = 0; i < (int)m_akPlane.size(); i++)
{
const Plane3<Real>& rkP = m_akPlane[i];
sprintf(acMsg,"plane<%d> = (%+8.6f,%+8.6f,%+8.6f;%+8.4f)",i,
rkP.GetNormal().X(),rkP.GetNormal().Y(),rkP.GetNormal().Z(),
rkP.GetConstant());
rkOStr << acMsg << endl;
}
rkOStr << endl;
}
//----------------------------------------------------------------------------
template <class Real>
bool ConvexPolyhedron3<Real>::Print (const char* acFilename) const
{
ofstream kOStr(acFilename);
if ( !kOStr )
return false;
Print(kOStr);
return true;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template class WML_ITEM ConvexPolyhedron3<float>;
template class WML_ITEM ConvexPolyhedron3<double>;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
936
]
]
]
|
73bfa638b47f78aa4f3e6b4b60c483d9f6538d7f | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /WallPaper/WallPaperSplashUIThread.cpp | c557a029fe061d1d8e5fbbc0239acb7e5279f247 | []
| no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10T13:11:23.176481 | 2011-04-14T11:04:17 | 2011-04-14T11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,156 | cpp | /*
WallPaperSplashUIThread.cpp
Classe derivata per il thread d'interfaccia utente utilizzata per il dialogo a scomparsa.
Luca Piergentili, 09/06/03
[email protected]
WallPaper (alias crawlpaper) - the hardcore of Windows desktop
http://www.crawlpaper.com/
copyright © 1998-2004 Luca Piergentili, all rights reserved
crawlpaper is a registered name, all rights reserved
This is a free software, released under the terms of the BSD license. Do not
attempt to use it in any form which violates the license or you will be persecuted
and charged for this.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
- Neither the name of "crawlpaper" nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "env.h"
#include "pragma.h"
#include "macro.h"
#include "window.h"
#include "WallPaperSplashScreenDlg.h"
#include "WallPaperSplashUIThread.h"
#include "traceexpr.h"
//#define _TRACE_FLAG _TRFLAG_TRACEOUTPUT
//#define _TRACE_FLAG _TRFLAG_NOTRACE
#define _TRACE_FLAG _TRFLAG_NOTRACE
#define _TRACE_FLAG_INFO _TRFLAG_NOTRACE
#define _TRACE_FLAG_WARN _TRFLAG_NOTRACE
#define _TRACE_FLAG_ERR _TRFLAG_NOTRACE
#if (defined(_DEBUG) && defined(_WINDOWS)) && (defined(_AFX) || defined(_AFXDLL))
#ifdef PRAGMA_MESSAGE_VERBOSE
#pragma message("\t\t\t"__FILE__"("STR(__LINE__)"): using DEBUG_NEW macro")
#endif
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNCREATE(CWallPaperSplashUIThread,CWinThread)
/*
InitInstance()
*/
BOOL CWallPaperSplashUIThread::InitInstance(void)
{
// il thread si elimina automaticamente
CWinThread::m_bAutoDelete = TRUE;
// lancia il dialogo
CWallPaperSplashScreenDlg dlg(NULL);
dlg.DoModal();
// thread basato sul dialogo, non deve creare l'istanza
return(FALSE);
}
| [
"[email protected]"
]
| [
[
[
1,
81
]
]
]
|
735a590400198d068eb80c4c71b24dbd647759fe | 61a1444517cf2b76d273ff90243f8a8d7e627e6a | /util/stabi/adapter/stlIterator2stabiIterator.hxx | 12c9a3340e0da475ab43cafb19d2e35155661f78 | []
| no_license | DayBreakZhang/stabi | eeea80792a3d2501732d19d5a7c8593e497f43a4 | 0d50868bf384a25840a31af87bebb3989d3b350c | refs/heads/master | 2020-05-20T07:29:06.875021 | 2010-06-22T09:40:45 | 2010-06-22T09:40:45 | 33,292,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,883 | hxx | // Copyright (c) 2010 Yu-Li Lin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <assert.h>
#include "algorithm/iterator.h"
namespace util
{
namespace stabi
{
namespace adapter
{
template<typename CollectionType>
stlIterator2stabiIterator<CollectionType>::stlIterator2stabiIterator(iteratorImplType &iteratorImpl, CollectionType *pCollectionImpl) throw () :
m_iteratorImpl(iteratorImpl),
m_pCollectionImpl(pCollectionImpl)
{
}
template<typename CollectionType>
stlIterator2stabiIterator<CollectionType>::~stlIterator2stabiIterator() throw ()
{
}
template<typename CollectionType>
void stlIterator2stabiIterator<CollectionType>::Destroy() throw ()
{
delete this;
}
// Collection
template<typename CollectionType>
bool stlIterator2stabiIterator<CollectionType>::HasNext() const throw ()
{
assert(m_pCollectionImpl != NULL);
if (m_pCollectionImpl == NULL)
{
return false;
}
if (m_iteratorImpl == m_pCollectionImpl->end())
{
return false;
}
iteratorImplType iteratorTest = m_iteratorImpl;
return ++iteratorTest != m_pCollectionImpl->end();
}
template<typename CollectionType>
bool stlIterator2stabiIterator<CollectionType>::HasPrevious() const throw ()
{
assert(m_pCollectionImpl != NULL);
if (m_pCollectionImpl == NULL)
{
return false;
}
return m_iteratorImpl != m_pCollectionImpl->begin();
}
template<typename CollectionType>
typename stlIterator2stabiIterator<CollectionType>::DataType * stlIterator2stabiIterator<CollectionType>::Get() throw ()
{
return const_cast<DataType *>(const_cast<const stlIterator2stabiIterator<CollectionType> *>(this)->Get());
}
template<typename CollectionType>
const typename stlIterator2stabiIterator<CollectionType>::DataType * stlIterator2stabiIterator<CollectionType>::Get() const throw ()
{
assert(m_pCollectionImpl != NULL);
if (m_pCollectionImpl == NULL)
{
return NULL;
}
if (m_iteratorImpl == m_pCollectionImpl->end())
{
return NULL;
}
return &(*m_iteratorImpl);
}
template<typename CollectionType>
ptrdiff_t stlIterator2stabiIterator<CollectionType>::Move(ptrdiff_t offSet) throw ()
{
assert(m_pCollectionImpl != NULL);
if (m_pCollectionImpl == NULL)
{
return NULL;
}
return algorithm::checkedAdvance(m_iteratorImpl, offSet, m_pCollectionImpl->begin(), m_pCollectionImpl->end());
}
template<typename CollectionType>
bool stlIterator2stabiIterator<CollectionType>::Erase() throw ()
{
assert(m_pCollectionImpl != NULL);
if (m_pCollectionImpl == NULL)
{
return false;
}
if (m_iteratorImpl == m_pCollectionImpl->end())
{
return false;
}
m_iteratorImpl = m_pCollectionImpl->erase(m_iteratorImpl);
return true;
}
} // namespace adapter
} // namespace stabi
} // namespace util | [
"yuli.lin@c77a587f-fc48-8b61-66aa-f312bb63b7e1"
]
| [
[
[
1,
134
]
]
]
|
ac01b1f3fe558b7a9180366afc3073899506e5a0 | e3e5243690bd626c79678fdf287ef23c99060263 | /steering/source/exercicio2.cpp | f30197dfcd0669a6ab46de6097cd164761aeb555 | []
| no_license | Shulander/steeringfluid | a6e6c62b719cdfe2f071eec33dfec2f32e3095a1 | 3712b0fc4f00b7c0da563ee887f55229af50d741 | refs/heads/master | 2021-01-25T08:38:09.460551 | 2009-05-27T02:14:24 | 2009-05-27T02:14:24 | 40,906,080 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 9,462 | cpp | #include <windows.h> // Header File For Windows
#include <math.h> // Header File For Windows Math Library
#include <stdio.h> // Header File For Standard Input/Output
#include <time.h>
#include <stdarg.h>
#include <GL/gl.h>
#include <GL/glut.h>
#include "base/Frames.h"
#include "base/GLFont.h"
GLFont * font;
Frames * frames;
float fps = 100;
clock_t t1, t2;
int posicaoluz = 0;
void mudaModoDisplayList(void);
#define X .525731112119133606
#define Z .850650808352039932
static GLfloat vdata[12][3] = {
{-X, 0.0, Z}, {X, 0.0, Z}, {-X, 0.0, -Z}, {X, 0.0, -Z},
{0.0, Z, X}, {0.0, Z, -X}, {0.0, -Z, X}, {0.0, -Z, -X},
{Z, X, 0.0}, {-Z, X, 0.0}, {Z, -X, 0.0}, {-Z, -X, 0.0}
};
static GLuint tindices[20][3] = {
{0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1},
{8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3},
{7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6},
{6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11}
};
int ligacor = 0;
int resolucao = 0;
#define RESOLUCOES 7
GLuint dLEsfera[RESOLUCOES];
void init(void)
{
/* Cria as matrizes responsáveis pelo
controle de luzes na cena */
GLfloat ambiente[] = { 0.2, 0.2, 0.2, 1.0 };
GLfloat difusa[] = { 0.7, 0.7, 0.7, 1.0 };
GLfloat especular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat posicao[] = { 0.0, 3.0, 2.0, 0.0 };
GLfloat lmodelo_ambiente[] = { 0.2, 0.2, 0.2, 1.0 };
glClearColor(0.0, 0.0, 0.0, 1.0);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
/* Cria e configura a Luz para a cena */
glLightfv(GL_LIGHT0, GL_AMBIENT, ambiente);
glLightfv(GL_LIGHT0, GL_DIFFUSE, difusa);
glLightfv(GL_LIGHT0, GL_POSITION, posicao);
glLightfv(GL_LIGHT0, GL_SPECULAR, especular);
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodelo_ambiente);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
mudaModoDisplayList();
frames = new Frames();
font = new GLFont();
t1 = clock();
}
void error(char * str){
printf("%s\n", str);
}
void normalize(float v[3]) {
GLfloat d = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
if (d == 0.0) {
error("zero length vector");
return;
}
v[0] /= d; v[1] /= d; v[2] /= d;
}
void normcrossprod(float v1[3], float v2[3], float out[3])
{
GLint i, j;
GLfloat length;
out[0] = v1[1]*v2[2] - v1[2]*v2[1];
out[1] = v1[2]*v2[0] - v1[0]*v2[2];
out[2] = v1[0]*v2[1] - v1[1]*v2[0];
normalize(out);
}
void drawtriangle(float *v1, float *v2, float *v3)
{
glBegin(GL_TRIANGLES);
//glBegin(GL_LINE_LOOP);
glNormal3fv(v1); glVertex3fv(v1);
glNormal3fv(v2); glVertex3fv(v2);
glNormal3fv(v3); glVertex3fv(v3);
glEnd();
}
void subdivide(float *v1, float *v2, float *v3)
{
GLfloat v12[3], v23[3], v31[3];
GLint i;
for (i = 0; i < 3; i++) {
v12[i] = v1[i]+v2[i];
v23[i] = v2[i]+v3[i];
v31[i] = v3[i]+v1[i];
}
normalize(v12);
normalize(v23);
normalize(v31);
drawtriangle(v1, v12, v31);
drawtriangle(v2, v23, v12);
drawtriangle(v3, v31, v23);
drawtriangle(v12, v23, v31);
}
void subdivide2(float *v1, float *v2, float *v3, long depth)
{
GLfloat v12[3], v23[3], v31[3];
GLint i;
if (depth == 0) {
drawtriangle(v1, v2, v3);
return;
}
for (i = 0; i < 3; i++) {
v12[i] = v1[i]+v2[i];
v23[i] = v2[i]+v3[i];
v31[i] = v3[i]+v1[i];
}
normalize(v12);
normalize(v23);
normalize(v31);
subdivide2(v1, v12, v31, depth-1);
subdivide2(v2, v23, v12, depth-1);
subdivide2(v3, v31, v23, depth-1);
subdivide2(v12, v23, v31, depth-1);
}
/*
Função responsável pelo desenho das esferas.
Nesta função também serão aplicadas as tranformações
necessárias para o efeito desejado.
*/
long rotaciona=0l;
void display(void)
{
int i, j;
float frame_time;
t2 = clock();
frame_time = (double)(t2 - t1) / CLOCKS_PER_SEC;
t1 = t2;
fps = frames->getFrames();
/* Variáveis para definição da capacidade de brilho do material */
GLfloat especular[] = { 1.0, 1.0, 1.0, 1.0 };
/* Posição da luz */
GLfloat posicao[] = { 0.0, 3.0, 2.0, 0.0 };
/*
Limpa o buffer de pixels e
determina a cor padrão dos objetos.
*/
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
/* Armazena o estado anterior para
rotação da posição da luz */
glPushMatrix () ;
glRotated ((GLdouble) posicaoluz, 1.0, 0.0, 0.0);
glLightfv (GL_LIGHT0, GL_POSITION, posicao);
glPopMatrix(); // Posição da Luz
rotaciona+= 90* frame_time;
for(int i=0; i<1000; i++) {
glPushMatrix();
glColor3f ((i*12347%255)/255.0, (i*6541243%255)/255.0,(i*9899543%255)/255.0);
glRotatef(rotaciona, 1.0, 1.0, 1.0);
glTranslatef((i*12347%250)/50.0, (i*6541243%250)/50.0,(i*9899543%250)/50.0);
//glTranslatef(i%8-4, i%9-4.5, i%10-5);
glScalef(0.3f,0.3f,0.3f);
glCallList(dLEsfera[resolucao]);
glPopMatrix();
}
glPushMatrix();
glBegin (GL_LINE_STRIP);
glColor3f (1.0, 1.0, 1.0);
glVertex3f (-200.0, 0.0, 0.0);
glColor3f (1.0, 0.0, 0.0);
glVertex3f (0.0, 0.0, 0.0);
glColor3f (1.0, 1.0, 1.0);
glVertex3f (200.0, 0.0, 0.0);
glEnd ();
glBegin (GL_LINE_STRIP);
glColor3f (1.0, 1.0, 1.0);
glVertex3f ( 0.0, -200.0,0.0);
glColor3f (0.0, 1.0, 0.0);
glVertex3f (0.0, 0.0, 0.0);
glColor3f (1.0, 1.0, 1.0);
glVertex3f ( 0.0, 200.0,0.0);
glEnd ();
glBegin (GL_LINE_STRIP);
glColor3f (1.0, 1.0, 1.0);
glVertex3f ( 0.0,0.0, -200.0);
glColor3f (0.0, 0.0, 1.0);
glVertex3f (0.0, 0.0, 0.0);
glColor3f (1.0, 1.0, 1.0);
glVertex3f ( 0.0,0.0, 200.0);
glEnd ();
glPopMatrix();
glPushMatrix();
glBegin (GL_LINE_STRIP);
glColor3f (1.0, 1.0, 1.0);
glVertex3f (-200.0, 0.0, 0.0);
glColor3f (1.0, 0.0, 0.0);
glVertex3f (0.0, 0.0, 0.0);
glColor3f (1.0, 1.0, 1.0);
glVertex3f (200.0, 0.0, 0.0);
glEnd ();
glBegin (GL_LINE_STRIP);
glColor3f (1.0, 1.0, 1.0);
glVertex3f ( 0.0, -200.0,0.0);
glColor3f (0.0, 1.0, 0.0);
glVertex3f (0.0, 0.0, 0.0);
glColor3f (1.0, 1.0, 1.0);
glVertex3f ( 0.0, 200.0,0.0);
glEnd ();
glBegin (GL_LINE_STRIP);
glColor3f (1.0, 1.0, 1.0);
glVertex3f ( 0.0,0.0, -200.0);
glColor3f (0.0, 0.0, 1.0);
glVertex3f (0.0, 0.0, 0.0);
glColor3f (1.0, 1.0, 1.0);
glVertex3f ( 0.0,0.0, 200.0);
glEnd ();
glPopMatrix();
printf(" \r", fps);
printf("FPS: %.0f\r", fps);
//static char text[50];
//font->startText();
//glColor3f(1,1,1);
//
//sprintf(text, "FPS: %.0f", fps);
//font->print(20, 460, text);
//font->endText();
// Executa os comandos
glutSwapBuffers();
glutPostRedisplay();
}
void mudaModoDisplayList(void)
{
GLuint tempIndice = glGenLists(RESOLUCOES);
GLfloat semespecular[4]={0.0,0.0,0.0,1.0};
for(int j=0; j<RESOLUCOES; j++) {
dLEsfera[j] = tempIndice+j;
glNewList(tempIndice+j, GL_COMPILE);
//comandos de desenho do objeto
//vértices, transformações, etc.
/* Define a propriedade do material */
//refletância do material
glMaterialfv(GL_FRONT,GL_SPECULAR, semespecular);
// Define a concentração do brilho
glMateriali(GL_FRONT,GL_SHININESS,100);
for (int i = 0; i < 20; i++) {
subdivide2(&vdata[tindices[i][0]][0], &vdata[tindices[i][1]][0], &vdata[tindices[i][2]][0], j);
}
glEndList();
}
}
/*
Função responsável pelo desenho da tela
Nesta função são determinados o tipo de Projeção
o modelo de Matrizes e
a posição da câmera
Quando a tela é redimensionada os valores
da visão perspectiva são recalculados com base no novo tamanho da tela
assim como o Viewport
*/
void reshape (int w, int h)
{
glViewport (0, 0, (GLsizei) w, (GLsizei) h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 200.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
gluLookAt (10.0, 10.0, 10.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
/* Função responsável pelo controle de teclado
quando pressionada a tecla d, será executada uma rotação no
próprio eixo da esfera menor. Quando pressionada a tecla y
a esfera menor irá rotacionar em torno da esfera maior, em uma
órbida determinada na translação na função display()
A tecla w é responsável por determinar se as esferas serão sólidas
ou aramadas (wire)
*/
void keyboard (unsigned char key, int x, int y)
{
switch (key) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
resolucao = (key-'0'<RESOLUCOES?key-'0':RESOLUCOES-1);
glutPostRedisplay();
break;
case 27:
exit(0);
break;
default:
break;
}
}
void mouse(int button, int state, int x, int y)
{
switch (button) {
case GLUT_LEFT_BUTTON:
if (state == GLUT_DOWN)
glutIdleFunc(NULL);
break;
case GLUT_RIGHT_BUTTON:
posicaoluz = (posicaoluz + 1) % 360;
glutPostRedisplay();
break;
default:
break;
}
}
/*
Função principal do programa.
*/
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Exemplo 2");
init ();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}
| [
"shulander@85a90f13-b34b-0410-994f-f76cd5410383"
]
| [
[
[
1,
391
]
]
]
|
0597403459bb0ebf61722286ceb45fe197aaa992 | f77f105963cd6447d0f392b9ee7d923315a82ac6 | /Box2DandOgre/include/ParkerStateMachine.h | 5c33f62bd262545d3ca0ef1a87fde8e83a8d6f46 | []
| 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 | 3,686 | h | /*=============================================================================
ParkerStateMachine.h
Author: Matt King
Finite State Machine
=============================================================================*/
#ifndef PARKERSTATEMACHINE_H
#define PARKERSTATEMACHINE_H
#include "Parker.h"
#include "ParkerState.h"
class CharacterParker;
/// Finite state machines have two states at a time, a global state and a
/// current state, both are updated every cycle if they exist.
class ParkerStateMachine<CharacterParker> : FSMStateMachine<T>
{
public:
ParkerStateMachine(CharacterParker* driver);
/// Delete the current state and global state if they exist.
virtual ~ParkerStateMachine(){};
void PostSolve(b2Contact* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture, const b2ContactImpulse* impulse){};
/// Update the FSM
bool Update()
{
// If a global state exists update it.
if(globalState_)
{
globalState_->Update();
}
// If a current state exists update it.
if (currentState_)
{
return currentState_->Update();
}
return true;
}
/// Change current state to newState.
/// This calls the exit method of the current state before calling the
/// enter method of the new state.
void ChangeState(ParkerState* newState)
{
previousState_ = currentState_;
currentState_->Exit();
currentState_ = newState;
currentState_->Enter();
}
/// Change the current state back to the previous state. This calls
/// ChangeState to change the state.
void RevertToPreviousState()
{
ChangeState(previousState_);
}
/// Returns true if the current state's type is equal to the type of the
/// class passed as a parameter.
bool IsInState(const ParkerState& state )const
{
return typeid(*currentState_) == typeid(state);
}
/// Send a message to the FSM
bool HandleMessage(const KGBMessage message)
{
// If a global state exists hand it the message.
if(globalState_)
{
globalState_->HandleMessage(message);
}
// If a current state exists hand it the message.
if (currentState_)
{
return currentState_->HandleMessage(message);
}
return true;
}
/// Called when two fixtures begin to touch.
void BeginContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture)
{
currentState_->BeginContact(contact,contactFixture, collidedFixture);
}
/// Called when two fixtures cease to touch.
void EndContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture)
{
currentState_->EndContact(contact,contactFixture, collidedFixture);
}
/*=============================================================================
Getter / Setter methods
=============================================================================*/
void SetCurrentState(ParkerState* state) { currentState_ = state;}
void SetGlobalState(ParkerState* state) { globalState_ = state;}
void SetPreviousState(ParkerState* state) { previousState_ = state;}
ParkerState* GetCurrentState() const { return currentState_;}
ParkerState* GetGlobalState() const { return globalState_;}
ParkerState* GetPreviousState() const { return previousState_;}
protected:
/// A pointer to the object that drives the state machine.
T* driver_;
FSMState<T>* currentState_;
/// The previous state the machien was in.
FSMState<T>* previousState_;
/// The global state is updated all of the time and regularly does not change.
FSMState<T>* globalState_;
};
#endif
| [
"mapeki@34afb35a-be5b-11de-bb5c-85734917f5ce"
]
| [
[
[
1,
151
]
]
]
|
1c49ec42a06edceb1529089d611ae3f7d4abd492 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/renaissance/rnsgameplay/src/rnsgameplay/ncgpweaponmeleeclass_cmds.cc | 1d9376c1106f0faff0b7221208058ab17ae51f4a | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,535 | cc | //------------------------------------------------------------------------------
// ncgpweaponmeleeclass_cmds.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "precompiled/pchrnsgameplay.h"
#include "rnsgameplay/ncgpweaponmeleeclass.h"
//-----------------------------------------------------------------------------
NSCRIPT_INITCMDS_BEGIN(ncGPWeaponMeleeClass)
NSCRIPT_ADDCMD_COMPCLASS('LSEE', void, SetDamageMelee, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('LGEE', float, GetDamageMelee , 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('LSMT', void, SetMeleeDamageType, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('LGMT', int, GetMeleeDamageType , 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('LGGI', float, GetMeleeRange , 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('LSGI', void, SetMeleeRange, 1, (float), 0, ());
NSCRIPT_INITCMDS_END()
//------------------------------------------------------------------------------
/**
@param ps the persist Server to save the commands
@retval true if save is ok
*/
bool
ncGPWeaponMeleeClass::SaveCmds( nPersistServer * ps )
{
if( ! nComponentClass::SaveCmds(ps) )
{
return false;
}
ps->Put( this->GetEntityClass(), 'LSEE', this->GetDamageMelee() );
ps->Put( this->GetEntityClass(), 'LSMT', this->GetMeleeDamageType() );
return true;
}
//------------------------------------------------------------------------------
| [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
39
]
]
]
|
ba4d7008e8e7ad4f40e0f9b0e02b57ba7ccbdd5b | 40b507c2dde13d14bb75ee1b3c16b4f3f82912d1 | /core/sm_simple_prioqueue.h | a30ca25492d046e7ab15c0b4c8fe55154bc1ce41 | []
| 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 | 2,127 | 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$
*/
#include "sm_queue.h"
#include <IDBDriver.h>
template <class T>
class PrioQueue
{
private:
Queue<T> m_HighQueue;
Queue<T> m_NormalQueue;
Queue<T> m_LowQueue;
public:
inline Queue<T> & GetQueue(PrioQueueLevel level)
{
if (level == PrioQueue_High)
{
return m_HighQueue;
} else if (level == PrioQueue_Normal) {
return m_NormalQueue;
} else {
return m_LowQueue;
}
}
inline Queue<T> & GetLikelyQueue()
{
if (!m_HighQueue.empty())
{
return m_HighQueue;
}
if (!m_NormalQueue.empty())
{
return m_NormalQueue;
}
return m_LowQueue;
}
};
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
2
],
[
4,
5
],
[
7,
7
],
[
11,
11
],
[
16,
16
],
[
19,
19
],
[
28,
66
]
],
[
[
3,
3
],
[
6,
6
],
[
8,
10
],
[
12,
15
],
[
17,
18
],
[
20,
27
]
]
]
|
a1a3d16622fcf7923330d447da0f8918dee35c2d | 4aedb4f2fba771b4a2f1b6ba85001fff23f16d09 | /icfpc_gui/operations.cpp | a070ee114cb83f84cded8cadfba57bd05513b6a8 | []
| no_license | orfest/codingmonkeys-icfpc | 9eacf6b51f03ed271505235e65e53a44ae4addd0 | 8ee42d89261c62ecaddf853edd4e5bb9b097b10b | refs/heads/master | 2020-12-24T16:50:44.419429 | 2009-06-29T17:52:44 | 2009-06-29T17:52:44 | 32,205,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,845 | cpp | #include "brain.h"
#include "operations.h"
#include <exception>
#include <iostream>
#include <assert.h>
#include "vector.h"
#include "vm.h"
#include "executer.h"
using namespace std;
PortMapping Hohman::step(const PortMapping& output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
Vector curEarth(output.find(EARTH_X)->second, output.find(EARTH_Y)->second);
if (timestep == 0) {
state = RUNNING;
r1 = target.minR.length();// sqrt(pow(target.minR.x, 2) + pow(target.minR.y, 2));
r2 = target.maxR.length();// sqrt(pow(target.maxR.x, 2) + pow(target.maxR.y, 2));
transferTime = M_PI * sqrt(pow(r1 + r2, 3) / (8 * MU_CONST));
double delta_v1 = sqrt(MU_CONST / r1) * (sqrt(2 * r2 / (r1 + r2)) - 1);
Vector prevEarth(Brain::prevInput.find(EARTH_X)->second, Brain::prevInput.find(EARTH_Y)->second);
Vector moveDir = prevEarth - curEarth;
Vector tangent(curEarth.y, -curEarth.x);
tangent.normalize();
clockwise = ( Vector::dotProduct(moveDir, tangent) > 0.0 );
if (!clockwise)
tangent = -tangent;
Vector delta = tangent * delta_v1;
res[VX_PORT] = delta.x;
res[VY_PORT] = delta.y;
}
if (timestep == ceil(transferTime)) {
assert(ceil(transferTime) > 1);
double delta_v2 = sqrt(MU_CONST / r2) * (1 - sqrt(2 * r1 / (r1 + r2)));
Vector curEarth(output.find(EARTH_X)->second, output.find(EARTH_Y)->second);
Vector tangent(curEarth.y, -curEarth.x);
tangent.normalize();
if (!clockwise)
tangent = -tangent;
Vector delta = tangent * delta_v2;
res[VX_PORT] = delta.x;
res[VY_PORT] = delta.y;
state = COMPLETE;
}
timestep++;
return res;
}
PortMapping CircleToElliptic::step(const PortMapping& output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
if (timestep == 0) {
std::cout << "Circle To Elliptic" << target.minR.length() << " : " << target.maxR.length() << endl;
state = RUNNING;
r1 = sqrt(pow(target.minR.x, 2) + pow(target.minR.y, 2));
r2 = sqrt(pow(target.maxR.x, 2) + pow(target.maxR.y, 2));
transferTime = M_PI * sqrt(pow(r1 + r2, 3) / (8 * MU_CONST));
double delta_v1 = sqrt(MU_CONST / r1) * (sqrt(2 * r2 / (r1 + r2)) - 1);
Vector prevEarth(Brain::prevInput.find(EARTH_X)->second, Brain::prevInput.find(EARTH_Y)->second);
Vector curEarth(output.find(EARTH_X)->second, output.find(EARTH_Y)->second);
Vector moveDir = prevEarth - curEarth;
Vector tangent(curEarth.y, -curEarth.x);
tangent.normalize();
clockwise = ( Vector::dotProduct(moveDir, tangent) > 0.0 );
if (!clockwise)
tangent = -tangent;
Vector delta = tangent * delta_v1;
res[VX_PORT] = delta.x;
res[VY_PORT] = delta.y;
}
if (timestep == ceil(transferTime)) {
assert(ceil(transferTime) > 1);
state = COMPLETE;
}
timestep++;
return res;
}
PortMapping CircleToEllipticFast::step(const PortMapping& output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
if (timestep == 0) {
state = RUNNING;
r1 = sqrt(pow(target.minR.x, 2) + pow(target.minR.y, 2));
r2 = sqrt(pow(target.maxR.x, 2) + pow(target.maxR.y, 2));
transferTime = M_PI * sqrt(pow(r1 + r2, 3) / (8 * MU_CONST));
double delta_v1 = sqrt(MU_CONST / r1) * (sqrt(2 * r2 / (r1 + r2)) - 1);
Vector prevEarth(Brain::prevInput.find(EARTH_X)->second, Brain::prevInput.find(EARTH_Y)->second);
Vector curEarth(output.find(EARTH_X)->second, output.find(EARTH_Y)->second);
Vector moveDir = prevEarth - curEarth;
Vector tangent(curEarth.y, -curEarth.x);
tangent.normalize();
clockwise = ( Vector::dotProduct(moveDir, tangent) > 0.0 );
if (!clockwise)
tangent = -tangent;
Vector delta = tangent * delta_v1;
res[VX_PORT] = delta.x;
res[VY_PORT] = delta.y;
state = COMPLETE;
}
timestep++;
return res;
}
double CircleToElliptic::GetTransferTime()
{
r1 = sqrt(pow(target.minR.x, 2) + pow(target.minR.y, 2));
r2 = sqrt(pow(target.maxR.x, 2) + pow(target.maxR.y, 2));
return M_PI * sqrt(pow(r1 + r2, 3) / (8 * MU_CONST));
}
PortMapping EllipticToCircle::step(const PortMapping& output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
if (timestep == 0) {
std::cout << "Elliptic to Circle : " << target.minR.length() << " : " << target.maxR.length() << endl;
state = RUNNING;
r2 = target.minR.length();
r1 = target.maxR.length();//sqrt(pow(target.maxR.x, 2) + pow(target.maxR.y, 2));
double delta_v2 = sqrt(MU_CONST / r2) * (1 - sqrt(2 * r1 / (r1 + r2)));
Vector prevEarth(Brain::prevInput.find(EARTH_X)->second, Brain::prevInput.find(EARTH_Y)->second);
Vector curEarth(output.find(EARTH_X)->second, output.find(EARTH_Y)->second);
Vector moveDir = prevEarth - curEarth;
Vector tangent(curEarth.y, -curEarth.x);
tangent.normalize();
clockwise = ( Vector::dotProduct(moveDir, tangent) > 0.0 );
if (!clockwise)
tangent = -tangent;
Vector delta = tangent * delta_v2;
res[VX_PORT] = delta.x;
res[VY_PORT] = delta.y;
transferTime = M_PI * sqrt(pow(r1 + r2, 3) / (8 * MU_CONST));
state = COMPLETE;
}
if (timestep == ceil(transferTime)) {
assert(ceil(transferTime) > 1);
state = COMPLETE;
}
timestep++;
return res;
}
PortMapping FreeFly::step(const PortMapping& output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
if (timestep == 0){
std::cout << "Free Fly for " << transferTime << endl;
}
if (timestep == ceil(transferTime)) {
assert(ceil(transferTime) > 1);
state = COMPLETE;
}
timestep++;
return res;
}
PortMapping FlipDirection::step(const PortMapping& output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
if (timestep == 0){
state = RUNNING;
std::cout << "Flip Direction" << endl;
prev = Vector(
-output.find(EARTH_X)->second,
-output.find(EARTH_Y)->second
);
} else {
Vector cur(
-output.find(EARTH_X)->second,
-output.find(EARTH_Y)->second
);
Vector move(cur);
move -= prev;
res[VX_PORT] = -2*move.x;
res[VY_PORT] = -2*move.y;
state = COMPLETE;
}
timestep++;
return res;
}
PortMapping Accelerate::step(const PortMapping& output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
if (timestep == 0){
state = RUNNING;
std::cout << "Accelerate: delta: " << delta << endl;
prev = Vector(
-output.find(EARTH_X)->second,
-output.find(EARTH_Y)->second
);
} else {
Vector cur(
-output.find(EARTH_X)->second,
-output.find(EARTH_Y)->second
);
Vector move(cur);
move -= prev;
move.normalize();
move *= delta;
res[VX_PORT] = move.x;
res[VY_PORT] = move.y;
state = COMPLETE;
}
timestep++;
return res;
}
PortMapping FreeFlyToOpositPoint::step(const PortMapping& output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
Vector position(-output.find(EARTH_X)->second,-output.find(EARTH_Y)->second);
Vector tar = target.minR;
tar.normalize();
position.normalize();
double dot = Vector::dotProduct(tar,position);
if (abs(dot+1.0) < 0.0000001){
state = COMPLETE;
}
return res;
}
PortMapping FreeFlyToCertainPoint::step(const PortMapping& output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
Vector position(-output.find(EARTH_X)->second,-output.find(EARTH_Y)->second);
double dist = (position-point).length();
if (timestep == 0){
state = RUNNING;
std::cout << "Free Fly to Certain Point: X: " << point.x << " Y: " << point.y << endl;
} else if (timestep > 1){
if (dist < 1000){
state = COMPLETE;
} else if (dist > curDistance && curDistance < prevDistance){
state = COMPLETE;
}
}
prevDistance = curDistance;
curDistance = dist;
timestep++;
return res;
}
PortMapping MeetShip::step(const PortMapping& output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
if (timestep == 0){
std::cout << "Meet Ship " << ship << endl;
state = RUNNING;
}
Vector pos(-output.find(EARTH_X)->second, -output.find(EARTH_Y)->second);
Vector toShip(output.find(TARGETN_X(ship))->second, output.find(TARGETN_Y(ship))->second);
Vector move(pos-prev);
double dist = toShip.length();
if (dist < 1000){
state = COMPLETE;
searchSuccessful = true;
}
if (!searchSuccessful && (timestep % 50) == 3 && dist < 50000000 &&
Vector::dotProduct(toShip, move) > 0 && output.find(FUEL_PORT)->second > 1000){
cout << "Searching, dist " << dist << endl;
Vector move(pos - prev);
//double r = output.find(FUEL_PORT)->second;
//l = r;
//if (l > move.length()){
// l = move.length();
//}
//l = -l;
double l = move.length()*(-0.5);
double r = move.length()*(5.0);
bool found = false;
double veryMinDist = 1e20;
while (r - l > 1 && !found){
VM* vm = Executer::getCloneCurrentVM();
PortMapping in;
in[SCENARIO_PORT] = 0;
double m = (r+l)*0.5;
in[VX_PORT] = (move.normalize()*m).x;
in[VY_PORT] = (move.normalize()*m).y;
PortMapping out = vm->step(in);
if (out.find(SCORE_PORT)->second != 0) {
if (out.find(SCORE_PORT)->second < 0){
r = m;
continue;
} else {
assert(0);
}
}
in[VX_PORT] = 0;
in[VY_PORT] = 0;
bool good = false;
double prevDist = 0;
double curDist = 0;
Vector minPos;
Vector minSPos;
double minDist = 1e20;
for (int t = 0; t < 2000000; t++){
out = vm->step(in);
if (out.find(SCORE_PORT)->second != 0) break;
Vector toShipD(out.find(TARGETN_X(ship))->second, out.find(TARGETN_Y(ship))->second);
double dist = toShipD.length();
if (t > 3){
if (dist < 1000){
found = true;
good = true;
break;
}
if (dist > curDist && curDist < prevDist){
good = true;
break;
}
if (dist < minDist){
Vector pos(-out.find(EARTH_X)->second, -out.find(EARTH_Y)->second);
minDist = dist;
minPos = pos;
minSPos = pos+toShipD;
}
}
prevDist = curDist;
curDist = dist;
}
veryMinDist = min(minDist, veryMinDist);
if (!found && good){
double r1 = minPos.length();
double r2 = minSPos.length();
if (r1 < r2){
l = m;
} else {
r = m;
}
} else if (!found){
l = m;
}
delete vm;
}
if (found){
double m = (r+l)*0.5;
Vector move(pos - prev);
Vector acc(move);
acc.normalize();
acc *= m;
res[VX_PORT] = acc.x;
res[VY_PORT] = acc.y;
searchSuccessful = true;
} else {
cout << "Not found\nMin distance: " << veryMinDist << endl;
//startSearching++;
}
int i = 1;
}
prev = pos;
timestep++;
return res;
}
const double Pursuit::MAX_BURST_RATIO = 500.0;
PortMapping Pursuit::step(const PortMapping & output){
PortMapping res;
res[SCENARIO_PORT] = 0;
res[VX_PORT] = 0;
res[VY_PORT] = 0;
Vector curEarth(output.find(EARTH_X)->second, output.find(EARTH_Y)->second);
if (timestep == 0) {
Operation::state = RUNNING;
state = following;
} else {
bool skipOtherStateChanges = false;
Vector curMeEarth = Vector(output.find(EARTH_X)->second, output.find(EARTH_Y)->second);
Vector curTargEarth = curMeEarth -
Vector(output.find(targXSensor)->second, output.find(targYSensor)->second);
if (state == following && (curMeEarth - curTargEarth).length() > 1000) {
// steer to the target
Vector prevMeEarth(prevInput.find(EARTH_X)->second, prevInput.find(EARTH_Y)->second);
Vector prevTargEarth = prevMeEarth -
Vector(prevInput.find(targXSensor)->second, prevInput.find(targYSensor)->second);
Vector curTargVel = prevTargEarth - curTargEarth;
Vector curMeVel = prevMeEarth - curMeEarth;
Vector dirMeTarg = curMeEarth - curTargEarth;
Vector deltaV = dirMeTarg / MAX_STEERING_STEPS + (curTargVel - curMeVel);
if (deltaV.length() > output.find(FUEL_PORT)->second / MAX_BURST_RATIO)
deltaV = deltaV.normalize() * output.find(FUEL_PORT)->second / MAX_BURST_RATIO;
res[VX_PORT] = deltaV.x;
res[VY_PORT] = deltaV.y;
state = steering;
steeringSteps = 0;
skipOtherStateChanges = true;
}
if (state == steering && !skipOtherStateChanges) {
// if we steer away - return to the pursuit
if (steeringSteps++ > MAX_STEERING_STEPS && (curMeEarth - curTargEarth).length() > 1000)
state = following;
}
if (state == steering && !skipOtherStateChanges &&
(curMeEarth - curTargEarth).length() < 500) {
// remove steering velocity component and continue pursuit
Vector prevMeEarth(prevInput.find(EARTH_X)->second, prevInput.find(EARTH_Y)->second);
Vector curMyVel = prevMeEarth - curMeEarth;
Vector prevTargEarth = prevMeEarth -
Vector(prevInput.find(targXSensor)->second, prevInput.find(targYSensor)->second);
Vector curTargVel = prevTargEarth - curTargEarth;
Vector deltaV = curTargVel - curMyVel;
res[VX_PORT] = deltaV.x;
res[VY_PORT] = deltaV.y;
state = following;
skipOtherStateChanges = true;
}
}
prevInput = output;
timestep++;
return res;
}
double estimateTimeToPerihelionFormula(const Vector& point, const Orbit& orbit) {
long double a = (orbit.maxR - orbit.minR).length()*0.5;
long double ea = (orbit.maxR + orbit.minR).length()*0.5;
long double e = ea / a;
long double bb_aa = 1 - e*e;
long double bb = bb_aa * a*a;
long double b = sqrt(bb);
long double p = a*(1-e*e);//b*b/a;
long double bb_a = bb_aa*a;
long double r = point.length();
long double r1 = orbit.maxR.length();
long double r2 = orbit.minR.length();
long double total_time = 2*M_PI*sqrt( pow(r1+r2,3) / (8*MU_CONST) );
long double A,cosphi,pre_1;
bool f = false;
if (r > a){
cosphi = (r-p) / (r*e);
A = ((1-e)/(1+e));
pre_1 = pow((1+e),2);
f = true;
} else {
cosphi = (p-r) / (r*e);
A = ((1+e)/(1-e));
pre_1 = pow((1-e),2);
}
if (cosphi > 1.0) cosphi = 1.0;
if (cosphi < -1.0) cosphi = -1.0;
long double phi = acos(cosphi);
long double cosphi2 = pow(cos(phi*0.5),2);
long double cosb2 = A*cosphi2 / (1 + (A-1)*cosphi2);
long double beta = acos(sqrt(cosb2));
// long double tnp2 = tan(phi*0.5);
// long double beta = tnp2 / sqrt(A);
long double pre = 2 / (pre_1 * sqrt(A));
long double sum1 = (-1+(1/A))*0.25*sin(2*beta);
long double sum2 = beta * ( ((1/A) - 1)*0.5 + 1 );
long double area = pre * (sum1 + sum2) * p * p * 0.5;
long double total_area = M_PI * a * b;
//1927709481952258.5
long double res_time = total_time * area / total_area;
long double fixed_time = res_time;
if (f){
fixed_time = total_time * 0.5 - fixed_time;
}
//long double fixed_time = /*total_time * 0.5 - */res_time;
Vector3D to_p(point);
Vector3D to_apo(orbit.minR);
Vector3D to_p_apo = Vector3D::crossProduct(to_apo, to_p);
if ((to_p_apo.z > 0 && !orbit.clockwise) || (to_p_apo.z < 0 && orbit.clockwise)){
fixed_time = total_time - fixed_time;
}
return (double)fixed_time;
}
| [
"gorodilovm@6cd8edf8-6250-11de-81d0-cf1ed2c911a4",
"nkurtov@6cd8edf8-6250-11de-81d0-cf1ed2c911a4",
"vizovitin@6cd8edf8-6250-11de-81d0-cf1ed2c911a4"
]
| [
[
[
1,
7
],
[
10,
10
],
[
13,
21
],
[
24,
66
],
[
69,
145
],
[
147,
147
],
[
150,
182
],
[
187,
195
],
[
256,
270
]
],
[
[
8,
9
],
[
11,
12
],
[
22,
23
],
[
67,
68
],
[
146,
146
],
[
148,
149
],
[
183,
186
],
[
196,
255
],
[
271,
417
],
[
487,
547
]
],
[
[
418,
486
]
]
]
|
efc13f34798498d4c449ccbe4aa2627db1e2e40b | 097c5ec89727bca9c69964fdb0125174bd535387 | /src/menu.hpp | d06e04b6848c610b74fb1566bc767815d0735fc1 | []
| no_license | jsj2008/Captain | 280501d3bc2dbd778519fddac3afe1d1fb14ebe8 | 099ee3f7cdd5e81ac741a7e6c69a131fcbccc7c6 | refs/heads/master | 2020-12-25T15:40:53.390224 | 2011-11-28T07:36:05 | 2011-11-28T07:36:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 607 | hpp | #ifndef __MENU_HPP_
#define __MENU_HPP_
#include "text.hpp"
#include "stars.hpp"
#include <vector>
#include <boost/shared_ptr.hpp>
class Menu
{
private:
std::vector<boost::shared_ptr<Text> > items;
std::vector<boost::shared_ptr<Text> > additionalTexts;
boost::shared_ptr<Text> cursor;
int currentSelection;
int step;
boost::shared_ptr<Stars> backgroundStarsPtr;
public:
Menu();
Menu(std::vector<std::string> entries, bool useStars);
~Menu();
void update();
void createMenuStars();
void render();
void moveup();
void movedown();
void select();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
32
]
]
]
|
f61c4d3000cf02bbe9b3dc2b692d3e9411a834bd | d0ae9c74f91979b9a99c122e8a40de4a5d955bae | /AstroVis2/CVector.h | dbe3b007ef7156d55c33ed6194b4472d5fd9b6d8 | []
| no_license | RyanDuToit/AstroVis | fe36bedb4f6fa628578de26c2173f9fe155483b0 | a8864f20553e0a824bbf0c309cb9d76617ba5aad | refs/heads/master | 2021-01-17T08:08:58.780711 | 2011-07-06T19:01:24 | 2011-07-06T19:01:24 | 2,008,297 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,152 | h | #ifndef CVector_H
#define CVector_H
#define USE_GLVERTEX
#ifdef USE_GLVERTEX
//#include <windows.h>
#include <GLUT/glut.h>
#endif
class CVector
{
public:
private:
double texcoord_[3];
double color_[4];
public:
double value_[4];
CVector(
);
CVector(
const CVector& vector_in
);
CVector(
const double& a_in,
const double& b_in,
const double& c_in,
const double& d_in = 1.0
);
CVector(
const double& a_in,
const double& b_in,
const double& c_in,
const double& d_in,
const double& s_in,
const double& t_in,
const double& r_in
);
CVector(
const double& a_in,
const double& b_in,
const double& c_in,
const double& d_in,
const double& s_in,
const double& t_in,
const double& r_in,
const double& R_in,
const double& G_in,
const double& B_in,
const double& A_in
);
CVector(
const double& a_in,
const double& b_in,
const double& c_in,
const double& d_in,
const double& R_in,
const double& G_in,
const double& B_in,
const double& A_in
);
CVector&
operator=(
const CVector& vector_in
);
double&
operator[](
const unsigned short index_in
);
double
operator[](
const unsigned short index_in
) const;
double&
operator()(
const unsigned short index_in
);
double
operator()(
const unsigned short index_in
) const;
void
set(
const double& a_in,
const double& b_in,
const double& c_in,
const double& d_in
);
void
get(
double& a_out,
double& b_out,
double& c_out,
double& d_out
) const;
bool
operator==(
const CVector& vector_in
) const;
bool
operator!=(
const CVector& vector_in
) const;
CVector
operator-(
) const;
friend CVector
operator-(
const CVector& vector0_in,
const CVector& vector1_in
);
friend CVector
operator+(
const CVector& vector0_in,
const CVector& vector1_in
);
friend double
operator*(
const CVector& vector0_in,
const CVector& vector1_in
);
double
getInnerProduct(
const CVector& vector_in
) const;
friend CVector
operator*(
const double& scalar_in,
const CVector& vector_in
);
friend CVector
operator*(
const CVector& vector_in,
const double& scalar_in
);
friend CVector
operator/(
const CVector& vector_in,
const double& scalar_in
);
CVector&
operator+=(
const CVector& vector_in
);
CVector&
operator-=(
const CVector& vector_in
);
CVector&
operator*=(
const double& scalar_in
);
CVector&
operator/=(
const double& scalar_in
);
double
getLength(
) const;
void
normalize(
);
bool
isNormalized(
) const;
bool
isNil(
) const;
#ifdef USE_GLVERTEX
inline void
glVertex(bool bColor = true, bool bTexCoord = true) const{
if (bColor) glColor4d(color_[0], color_[1], color_[2], color_[3]);
if (bTexCoord) glTexCoord3d(texcoord_[0], texcoord_[1], texcoord_[2]);
glVertex4d(value_[0],value_[1],value_[2],value_[3]);
}
#endif
};
#endif // CVector_H
| [
"[email protected]"
]
| [
[
[
1,
211
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.