blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
sequencelengths
1
16
author_lines
sequencelengths
1
16
982be92e9193796767fde625b2b4b26d0e329038
14a00dfaf0619eb57f1f04bb784edd3126e10658
/lab5/GUI.cpp
1c0564bd6848c073b478f5bfe092b5faf9a55af2
[]
no_license
SHINOTECH/modanimation
89f842262b1f552f1044d4aafb3d5a2ce4b587bd
43d0fde55cf75df9d9a28a7681eddeb77460f97c
refs/heads/master
2021-01-21T09:34:18.032922
2010-04-07T12:23:13
2010-04-07T12:23:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,247
cpp
/************************************************************************************************* * * Modeling and animation (TNM079) 2007 * Code base for lab assignments. Copyright: * Gunnar Johansson ([email protected]) * Ken Museth ([email protected]) * Michael Bang Nielsen ([email protected]) * Ola Nilsson ([email protected]) * Andreas Sderstrm ([email protected]) * *************************************************************************************************/ #include "GUI.h" #include <cstdlib> #include <fstream> #include <cmath> #include "LevelSetOperator.h" #include "OperatorDilateErode.h" #include "OperatorReinitialize.h" #include "OperatorAdvect.h" #include "OperatorMeanCurvatureFlow.h" #include "SignedDistanceSphere.h" #include "ImplicitGradientField.h" #include "ImplicitValueField.h" #include "IsoContourColorMap.h" #include "ConstantVectorField.h" //GUI defines #define DEFAULT_WINDOW_HEIGHT 768 #define DEFAULT_WINDOW_WIDTH 1024 #define X 0 #define Y 1 #define Z 2 #define NEAR_PLANE 0.05f #define FAR_PLANE 100.0f using namespace std; //----------------------------------------------------------------------------- GUI::GUI() { mPlayback = false; mPlaybackIndex = 0; mDrawWireframe = false; mDrawXZPlane = true; mCurrentFPS = 0.0; mTimeSinceLastFPS = 0.0; mFramecounter = 0; // Starting global clock mClockArray[GLOBAL_CLOCK].start(); mClockArray[ANIMATION_CLOCK].highPrecision(true); mClockArray[ANIMATION_CLOCK].start(); mFrameTimestamp = mClockArray[ANIMATION_CLOCK].read(); mCam = Camera(Vector3<float>(2, 1, -.1)); mMousePos[X] = -1; mMousePos[Y] = -1; mWindowWidth = DEFAULT_WINDOW_WIDTH; mWindowHeight = DEFAULT_WINDOW_HEIGHT; } //----------------------------------------------------------------------------- GUI::~GUI() { std::vector<Object>::iterator iter = mGeometryList.begin(); std::vector<Object>::iterator iend = mGeometryList.end(); while (iter != iend) { delete (*iter).geometry; iter++; } } //----------------------------------------------------------------------------- void GUI::init() { unsigned int winPosX, winPosY; winPosX = 100;//mScreenWidth/2 - mWindowWidth/2; winPosY = 100;//mScreenHeight/2 - mWindowHeight/2; // Init glut and GL glutInitDisplayMode ( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); // creating rendering window glutInitWindowPosition(100,100); glutInitWindowSize(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT); glutCreateWindow("Mesh Viewer"); glutSetCursor(GLUT_CURSOR_CROSSHAIR); // initializing openGL glClearColor (0.53515625, 0.75390625f, 0.9609375f, 0.0); glEnable(GL_NORMALIZE); // Set default material GLfloat specular [] = { 0.5, 0.5, 0.5, 0.5 }; GLfloat shininess [] = { 10.0 }; glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular); glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, shininess); glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); //glShadeModel(GL_FLAT); glShadeModel(GL_SMOOTH); glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really nice perspective calculations glCullFace(GL_BACK); glEnable(GL_CULL_FACE); glViewport(0,0,DEFAULT_WINDOW_WIDTH,DEFAULT_WINDOW_HEIGHT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f, (GLfloat)(DEFAULT_WINDOW_WIDTH)/(GLfloat)(DEFAULT_WINDOW_HEIGHT),NEAR_PLANE, FAR_PLANE); glMatrixMode(GL_MODELVIEW); glutPositionWindow(winPosX, winPosY); } //----------------------------------------------------------------------------- void GUI::update() { // Force redraw graphics glutPostRedisplay(); } //----------------------------------------------------------------------------- void GUI::displayFunc() { // Time stuff Real timestamp = mClockArray[ANIMATION_CLOCK].read(); Real dt = timestamp - mFrameTimestamp; mFrameTimestamp = timestamp; float drawFPSTime = timestamp - mTimeSinceLastFPS; static const float timelimit = 0.5; // How often do we update the FPS count? if (drawFPSTime > timelimit){ mCurrentFPS = mFramecounter/timelimit; mFramecounter = 0; mTimeSinceLastFPS = timestamp; } // initializing draw glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // light source GLfloat position [] = { 1.0, 1.0, 1.0, 1.0 }; glLightfv(GL_LIGHT0, GL_POSITION, position); glEnable(GL_LIGHT0); // Drawing XZ plane glDisable(GL_LIGHTING); if (mDrawXZPlane){ drawXZplane(200,2.0,10); } glEnable(GL_LIGHTING); // Draw rotating cube //Real angle = 5*2*M_PI*mClockArray[ANIMATION_CLOCK].read(); //drawCube(angle); // if fluid sim playback.. if (mPlayback){ float time = mClockArray[PLAYBACK_CLOCK].read()/3.0; for (unsigned int i = mPlaybackIndex; i+1 < mPlaybackMeshArray.size(); i++){ if (mPlaybackMeshArray[i+1].timestamp >= time){ mPlaybackIndex = i; break; } } if (mPlaybackMeshArray.size() != 0){ mPlaybackMeshArray[mPlaybackIndex].mesh.draw(); } if (mPlaybackMeshArray.size() == 1){ mPlayback = false; mPlaybackIndex = 0; } // Stop if (mPlaybackIndex + 2 == mPlaybackMeshArray.size()){ mPlayback = false; mPlaybackIndex = 0; } } else{ // Draw geometry object(s) glColor3f(0,0,0.7); std::vector<Object>::iterator iter = mGeometryList.begin(); std::vector<Object>::iterator iend = mGeometryList.end(); while (iter != iend) { if (mDrawWireframe && (*iter).allowWireframe){ glDisable(GL_LIGHTING); glDisable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } else{ glEnable(GL_LIGHTING); glEnable(GL_CULL_FACE); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } if ((*iter).draw){ (*iter).geometry->draw(); } iter++; } } // Draw fps glDisable(GL_LIGHTING); drawFPS(mCurrentFPS); glEnable(GL_LIGHTING); // Move observer glMatrixMode(GL_PROJECTION); glLoadIdentity(); // reset viewport and projection parameters glViewport(0,0,mWindowWidth,mWindowHeight); gluPerspective(45.0f, (GLfloat)(mWindowWidth)/(GLfloat)(mWindowHeight),NEAR_PLANE, FAR_PLANE); //Move observer mCam.advect(dt); gluLookAt(mCam.getPosition().x(), mCam.getPosition().y(), mCam.getPosition().z(), mCam.getLookAtPoint().x(), mCam.getLookAtPoint().y(), mCam.getLookAtPoint().z(), 0,1,0); glMatrixMode(GL_MODELVIEW); mFramecounter++; glFlush(); glutSwapBuffers(); } //----------------------------------------------------------------------------- void GUI::winReshapeFunc(GLint newWidth, GLint newHeight) { mWindowWidth = newWidth; mWindowHeight = newHeight; // reset viewport and projection parameters glViewport(0,0,mWindowWidth,mWindowHeight); if (mWindowHeight != 0){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f, (GLfloat)(mWindowWidth)/(GLfloat)(mWindowHeight),NEAR_PLANE, FAR_PLANE); glMatrixMode(GL_MODELVIEW); } } //----------------------------------------------------------------------------- void GUI::mouseFunc(GLint button, GLint action, GLint mouseX, GLint mouseY) { if (mMousePos[X] == -1 && mMousePos[Y] == -1) { mMousePos[X] = mouseX; mMousePos[Y] = mouseY; mOldMousePos[X] = mouseX; mOldMousePos[Y] = mouseY; } else { mOldMousePos[X] = mMousePos[X]; mOldMousePos[Y] = mMousePos[Y]; mMousePos[X] = mouseX; mMousePos[Y] = mWindowHeight-mouseY; } glutPostRedisplay(); } //----------------------------------------------------------------------------- void GUI::mouseActiveMotionFunc(GLint mouseX, GLint mouseY) { Real mx, my, mOldX, mOldY; if (mMousePos[X] == -1 && mMousePos[Y] == -1) { mMousePos[X] = mouseX; mMousePos[Y] = mouseY; mOldMousePos[X] = mouseX; mOldMousePos[Y] = mouseY; } else { mOldMousePos[X] = mMousePos[X]; mOldMousePos[Y] = mMousePos[Y]; mMousePos[X] = mouseX; mMousePos[Y] = mWindowHeight-mouseY; } //if (button == GLUT_LEFT_BUTTON) { getMouseScreenCoordinates(mOldMousePos[X], mOldMousePos[Y], mOldX,mOldY); getMouseScreenCoordinates(mMousePos[X], mMousePos[Y], mx,my); mCam.rotateXY((mOldX - mx)/2.0, (mOldY - my)/2.0); } glutPostRedisplay(); } //----------------------------------------------------------------------------- void GUI::mousePassiveMotionFunc(GLint mouseX, GLint mouseY) { if (mMousePos[X] == -1 && mMousePos[Y] == -1) { mMousePos[X] = mouseX; mMousePos[Y] = mouseY; mOldMousePos[X] = mouseX; mOldMousePos[Y] = mouseY; } else { mOldMousePos[X] = mMousePos[X]; mOldMousePos[Y] = mMousePos[Y]; mMousePos[X] = mouseX; mMousePos[Y] = mWindowHeight-mouseY; } glutPostRedisplay(); } //----------------------------------------------------------------------------- void GUI::keyboardUpFunc(unsigned char keycode, GLint mouseX, GLint mouseY) { mCam.stopAcc(); } //----------------------------------------------------------------------------- void GUI::keyboardFunc(unsigned char keycode, GLint mouseX, GLint mouseY) { switch(keycode){ case 'q' : case 'Q' : exit(0); break; case 'p' : case 'P' : mDrawXZPlane = !mDrawXZPlane; break; case 'W': { mCam.accUp(); break; } case 'S': { mCam.accDown(); break; } case 'w' : // move forward { mCam.accForward(); break; } case 's' : // move backward { mCam.accBackward(); break; } case 'a' : case 'A' : { mCam.accLeft(); break; } case 'd' : case 'D' : { mCam.accRight(); break; } case 'o' : case 'O' : // center on origin { mCam.lookAtOrigo(); break; } case ' ' : // full stop { mCam.stop(); } break; case 'x' : case 'X' : // return to original position { mCam.reset(); } break; case '.' : { mCam.dolly(.1); } break; case ',' : { mCam.dolly(-.1); } break; case 'm' : case 'M': { // Wireframe rendering mDrawWireframe = true; } break; case 'n' : case 'N': { // Solid face rendering mDrawWireframe = false; } break; case 'b' : case 'B': { // Playback fluid sim mPlayback = true; mPlaybackIndex = 0; mClockArray[PLAYBACK_CLOCK].start(); } break; ////////////////////////////////////////////////////////////////////////////////////// case '1' : { const float dx = 0.02; mSimulationTimeCounter = 0; FluidSimSetup simSetupClass(dx, 6); // Add fluid VolumeLevelSet* volLS = simSetupClass.getFluidBoxFluid(); addGeometry("Fluid LevelSet", volLS); // Disable draw for the solid.. mGeometryList.back().drawAsWireframe(false); // Write initial frame Implicit* impl = dynamic_cast<Implicit*>(mGeometryList.back().geometry); Frame frame; frame.timestamp = 0.0; frame.mesh = impl->getMesh<SimpleMesh>(); mPlaybackMeshArray.push_back(frame); // Add solid LevelSet* ls = simSetupClass.getFluidBoxSolid(); addGeometry("Solid LevelSet", ls, 10); mDrawWireframe = true; } break; case '2' : { const float dx = 0.02; mSimulationTimeCounter = 0; FluidSimSetup simSetupClass(dx, 6); // Add fluid VolumeLevelSet* volLS = simSetupClass.getSimpleFluid(); addGeometry("Fluid LevelSet", volLS); // Write initial frame Implicit* impl = dynamic_cast<Implicit*>(mGeometryList.back().geometry); Frame frame; frame.timestamp = 0.0; frame.mesh = impl->getMesh<SimpleMesh>(); mPlaybackMeshArray.push_back(frame); // Add solid LevelSet* ls = simSetupClass.getSimpleSolid(); addGeometry("Solid LevelSet", ls, 10); } break; case '3' : { const float dx = 0.02; mSimulationTimeCounter = 0; FluidSimSetup simSetupClass(dx, 6); // Add fluid VolumeLevelSet* volLS = simSetupClass.getComplexFluid(); addGeometry("Fluid LevelSet", volLS); // Write initial frame Implicit* impl = dynamic_cast<Implicit*>(mGeometryList.back().geometry); Frame frame; frame.timestamp = 0.0; frame.mesh = impl->getMesh<SimpleMesh>(); mPlaybackMeshArray.push_back(frame); // Add solid LevelSet* ls = simSetupClass.getComplexSolid(); addGeometry("Solid LevelSet", ls, 10); } break; case '4' : { } break; case '5' : { } break; case '6' : { } break; case '7' : { } break; case '8' : { } break; case '9' : { } break; case '-' : { } break; case 'k' : case 'K' : { VolumeLevelSet * LS = getGeometry<VolumeLevelSet>("Fluid LevelSet"); float timeCounter = 0; { // Advect fluid level set one step float dt = mNSSolver.getTimestep(); // Get latest dt max from the solver timeCounter += dt; mSimulationTimeCounter += dt; NavierStokesVectorField* advectionField = LS->getAdvectionField(); OperatorAdvect opAdvect(LS, advectionField); opAdvect.propagate(dt); // Re-initialize OperatorReinitialize opReInit(LS); opReInit.propagate(2*LS->getDx()); // Rebuild LS->setNarrowBandWidth(6); delete advectionField; // Create list of geometry to pass to the solver vector<Geometry*> geometryList; for (unsigned int i = 0; i < mGeometryList.size(); i++){ geometryList.push_back(mGeometryList[i].geometry); } mNSSolver.solve(geometryList, dt); // Triangulate and calculate face normals LS->triangulate<SimpleMesh>(0.02); LS->getMesh<SimpleMesh>().calculateFaceNormals(); // Write frame for playback Frame frame; frame.timestamp = mSimulationTimeCounter; frame.mesh = LS->getMesh<SimpleMesh>(); mPlaybackMeshArray.push_back(frame); } } break; case 'l' : case 'L' : { VolumeLevelSet * LS = getGeometry<VolumeLevelSet>("Fluid LevelSet"); float maxTime = 1.0f/25.0f; float timeCounter = 0; while (timeCounter < maxTime) { // Advect fluid level set one step float dt = mNSSolver.getTimestep(); // Get latest dt max from the solver timeCounter += dt; mSimulationTimeCounter += dt; NavierStokesVectorField* advectionField = LS->getAdvectionField(); OperatorAdvect opAdvect(LS, advectionField); opAdvect.propagate(dt); // Re-initialize OperatorReinitialize opReInit(LS); opReInit.propagate(2*LS->getDx()); // Rebuild LS->setNarrowBandWidth(6); delete advectionField; // Create list of geometry to pass to the solver vector<Geometry*> geometryList; for (unsigned int i = 0; i < mGeometryList.size(); i++){ geometryList.push_back(mGeometryList[i].geometry); } mNSSolver.solve(geometryList, dt); // Triangulate and calculate face normals LS->triangulate<SimpleMesh>(0.02); LS->getMesh<SimpleMesh>().calculateFaceNormals(); // Write frame for playback Frame frame; frame.timestamp = mSimulationTimeCounter; frame.mesh = LS->getMesh<SimpleMesh>(); mPlaybackMeshArray.push_back(frame); } } break; } // Updating graphics glutPostRedisplay(); } //----------------------------------------------------------------------------- void GUI::specialFunc(GLint keycode, GLint mouseX, GLint mouseY) { } //----------------------------------------------------------------------------- void GUI::getMouseScreenCoordinates(int mouseX, int mouseY, Real &x, Real &y) { // screen width = 4.0, screen height = 3.0, lower left corner = (0,0) x = 4.0*((Real)mouseX/(mWindowWidth)); y = 3.0*((Real)mouseY/(mWindowHeight)); } //----------------------------------------------------------------------------- void GUI::drawXZplane(int nrOfGridCells, Real width, int subGridLines) { Real spacing = width/(Real)nrOfGridCells; int counter; glBegin(GL_LINES); glColor3f(0.7f,0.7f,0.7f); // x sweep counter = 0; for (Real x = -width/2.0; x < width/2.0; x += spacing){ if (counter >= subGridLines){ glColor3f(0.3f,0.3f,0.3f); counter = 0; } else{ glColor3f(0.7f,0.7f,0.7f); } glVertex3f(x,0.0f,-width/2.0); glVertex3f(x,0.0f,width/2.0); counter++; } // z sweep counter = 0; for (Real z = -width/2.0; z < width/2.0; z += spacing){ if (counter >= subGridLines){ glColor3f(0.3f,0.3f,0.3f); counter = 0; } else{ glColor3f(0.7f,0.7f,0.7f); } glVertex3f(-width/2.0, 0.0f, z); glVertex3f(width/2.0, 0.0f, z); counter++; } // draw coordinate system //X-Axis glColor3f(1.0f,0.0f,0.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(width/2.0, 0.0f, 0.0f); //Y-axis glColor3f(0.0f,1.0f,0.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, width/2.0, 0.0f); //Z-axis glColor3f(0.0f,0.0f,1.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, width/2.0); glEnd(); // Write axis info static const float distance = 0.1; glColor3f(1.0f,0.0f,0.0f); glRasterPos3f(distance,0,0); glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,'X'); glColor3f(0.0f,1.0f,0.0f); glRasterPos3f(0,distance,0); glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,'Y'); glColor3f(0.0f,0.0f,1.0f); glRasterPos3f(0,0,distance); glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,'Z'); } //----------------------------------------------------------------------------- void GUI::drawCube(Real angle) { static const GLfloat vertices[][3] = {{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0}, {1.0,1.0,-1.0}, {-1.0,1.0,-1.0}, {-1.0,-1.0,1.0}, {1.0,-1.0,1.0}, {1.0,1.0,1.0}, {-1.0,1.0,1.0}}; static const GLfloat normals[][3] = {{-1.0,-1.0,-1.0},{1.0,-1.0,-1.0}, {1.0,1.0,-1.0}, {-1.0,1.0,-1.0}, {-1.0,-1.0,1.0}, {1.0,-1.0,1.0}, {1.0,1.0,1.0}, {-1.0,1.0,1.0}}; static const GLfloat colors[][3] = {{0.0,0.0,0.0},{1.0,0.0,0.0}, {1.0,1.0,0.0}, {0.0,1.0,0.0}, {0.0,0.0,1.0}, {1.0,0.0,1.0}, {1.0,1.0,1.0}, {0.0,1.0,1.0}}; static const int polyList[][4] = { {0,3,2,1}, {2,3,7,6}, {0,4,7,3}, {1,2,6,5}, {4,5,6,7}, {0,1,5,4} }; glPushMatrix(); glScalef(0.1f,0.1f,0.1f); glTranslatef(0.0f, 5.0f,0.0f); glRotatef(angle,0.0f,1.0f,0.0f); glRotatef(angle,1.0f,1.0f,1.0f); // Draw the cube.. for (int i = 0; i < 6; i++){ const int a = polyList[i][0]; const int b = polyList[i][1]; const int c = polyList[i][2]; const int d = polyList[i][3]; glBegin(GL_POLYGON); glColor3fv(colors[a]); glNormal3fv(normals[a]); glVertex3fv(vertices[a]); glColor3fv(colors[b]); glNormal3fv(normals[b]); glVertex3fv(vertices[b]); glColor3fv(colors[c]); glNormal3fv(normals[c]); glVertex3fv(vertices[c]); glColor3fv(colors[d]); glNormal3fv(normals[d]); glVertex3fv(vertices[d]); glEnd(); } glPopMatrix(); } //----------------------------------------------------------------------------- void GUI::drawFPS(float fps) { const float pixelsPerLine = 48.0; float pixelsizeH = 1.0/mWindowHeight; //float pixelsizeW = 1.0/mWindowWidth; // Save matrices GLfloat modelview[16]; GLfloat projection[16]; glGetFloatv(GL_MODELVIEW_MATRIX, modelview); glGetFloatv(GL_PROJECTION_MATRIX, projection); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //std::stringify FPS char buffer[10]; sprintf(buffer, "%.0f", fps); std::string fpsStr(buffer); std::string result = std::string("FPS: ") + fpsStr; if (fps < 20){ glColor3f(0.7,0,0.0); } else if (fps < 50){ glColor3f(0.7,0.7,0.0); } else{ glColor3f(0,0.5,0.0); } glRasterPos2f(-1,1.0-1*pixelsPerLine*pixelsizeH); for (unsigned int i = 0; i < result.length(); i++){ glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,(result.c_str())[i]); } // Restore matrices glLoadMatrixf(projection); glMatrixMode(GL_MODELVIEW); glLoadMatrixf(modelview); } void GUI::drawText(const Vector3<float> & pos, const char * str) { glRasterPos3f(pos[0], pos[1], pos[2]); for (unsigned int i = 0; str[i] != '\n'; i++) glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, str[i]); } void GUI::addGeometry(const std::string & name, Geometry * geometry, int order) { mGeometryList.push_back(Object(name, geometry, order)); std::sort(mGeometryList.begin(), mGeometryList.end()); } template <class T> T * GUI::getGeometry(const std::string & name) { std::vector<Object>::iterator iter = mGeometryList.begin(); std::vector<Object>::iterator iend = mGeometryList.end(); while (iter != iend) { if ((*iter).name == name) return dynamic_cast<T *>((*iter).geometry); iter++; } std::cerr << "Warning: cannot find '" << name << "' in geometry list!" << std::endl; return NULL; }
[ "onnepoika@da195381-492e-0410-b4d9-ef7979db4686" ]
[ [ [ 1, 860 ] ] ]
e7efbf2e5731f79f859eeeb4b0d90ead03a37726
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/simon/Source/UAB Videojocs.cpp
8fa3907335cf4289acc179842cfb990dead7d137
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
2,478
cpp
#include <Windows.h> #include "ApplicationDX.h" #define APPLICATION_NAME "UAB Videojocs" //---------PARA DETECTAR MEMORY LEAKS--------// #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> //-------------------------------------------// //----------------------------------------------------------------------------- // Name: MsgProc() // Desc: The window's message handler //----------------------------------------------------------------------------- LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { switch( msg ) { case WM_DESTROY: PostQuitMessage( 0 ); return 0; case WM_KEYDOWN: { switch( wParam ) { case VK_ESCAPE: //Cleanup(); PostQuitMessage( 0 ); return 0; break; } } } return DefWindowProc( hWnd, msg, wParam, lParam ); } //----------------------------------------------------------------------------- // Name: WinMain() // Desc: The application's entry point //----------------------------------------------------------------------------- INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT ) { //-----------Para detectar Memory Leaks------------------------- _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); //_CrtSetBreakAlloc (55); //---------------------------------------------------------------// // Register the window class WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, APPLICATION_NAME, NULL }; RegisterClassEx( &wc ); // Create the application's window HWND hWnd = CreateWindow( APPLICATION_NAME, APPLICATION_NAME, WS_OVERLAPPEDWINDOW, 100, 100, 800, 640, NULL, NULL, wc.hInstance, NULL ); CApplicationDX l_ApplicationDX; l_ApplicationDX.InitAndLoad(hWnd); ShowWindow( hWnd, SW_SHOWDEFAULT ); UpdateWindow( hWnd ); MSG msg; ZeroMemory( &msg, sizeof(msg) ); while( msg.message!=WM_QUIT ) { if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { l_ApplicationDX.Update(); l_ApplicationDX.Render(); } } UnregisterClass( APPLICATION_NAME, wc.hInstance ); return 0; }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 90 ] ] ]
254e29141438e9afeee48e49a5e7423a52323b8f
26867688a923573593770ef4c25de34e975ff7cb
/mmokit/cpp/common/inc/netUtils.h
d613ecb81cdb4fe74d297fe9eb95007a40fe3ae8
[]
no_license
JeffM2501/mmokit
2c2b873202324bd37d0bb2c46911dc254501e32b
9212bf548dc6818b364cf421778f6a36f037395c
refs/heads/master
2016-09-06T10:02:07.796899
2010-07-25T22:12:15
2010-07-25T22:12:15
32,234,709
1
0
null
null
null
null
UTF-8
C++
false
false
4,286
h
//netUtils.h // common utils for TCP networking that does an unsigned short as a message // followed by an unsigned short for message lenght #ifndef _NET_UTILS_H_ #define _NET_UTILS_H_ #include "tcpConnection.h" #include <vector> class ShortShortNetworkPeer { protected: typedef struct { unsigned short code; unsigned short len; char* data; }PendingMessage; std::vector<PendingMessage> pendingMessages; unsigned int size; char *data; public: virtual ~ShortShortNetworkPeer() { flushPendingMessages(); } // called when a full message is received, if the derived class clears the message // return true and it won't be added to the pending messages virtual bool messagePending ( unsigned short code, unsigned short len, char *data ) { return false; } // Add more data to our list of pending data void receive ( unsigned int newSize, char* newData ) { // add this new data to our existing data we had left over from last time if (newData && newSize) { char *temp = (char*)malloc(newSize+size); if (data) memcpy(temp,data,size); memcpy(temp+size,newData,newSize); if(data) delete(data); data = temp; size += newSize; } // walk this data and see what we can parse out if ( data ) { char* pos = data; char* end = data+size; bool done = false; while ( !done ) { if (end-pos >4) // is there even enough left for a message of 0 size { PendingMessage message; message.code = net_Read16(pos); message.len = net_Read16(pos+2); if ( end-pos >= 4 + message.len ) { pos += 4; message.data = (char*)malloc(message.len); memcpy(message.data,pos,message.len); pos += message.len; if (messagePending (message.code,message.len,message.data)) // see if our children want to handle it right now free(message.data); else pendingMessages.push_back(message); // if they don't then we'll keep it till somone does } else done = true; } else done = true; } if (end-pos == 0) { free(data); data = NULL; size = 0; } else { // there was data left over, so lets just keep the // part we didnt' read; char* temp = data; size = (unsigned int)(end-pos); data = (char*)malloc(size); memcpy(data,pos,size); free(temp); } } } // returns the number of unhandled pending messags unsigned int getPendingMessageCount( void ) { return (unsigned int)pendingMessages.size(); } // returns the data pointer for a pending message const char* getPendingMessageData ( unsigned int index ) { if ( index >= pendingMessages.size() ) return NULL; return pendingMessages[index].data; } // returns the size fof a pending message unsigned short getPendingMessageSize ( unsigned int index ) { if ( index >= pendingMessages.size() ) return 0; return pendingMessages[index].len; } // returns the code for a pending message unsigned short getPendingMessageCode ( unsigned int index ) { if ( index >= pendingMessages.size() ) return 0; return pendingMessages[index].code; } // returns all the info for a pending message bool getPendingMessage ( unsigned int index, const char **d, unsigned short &c, unsigned short &s ) { if ( index >= pendingMessages.size() ) return false; *d = pendingMessages[index].data; c = pendingMessages[index].code; s = pendingMessages[index].len; return *d != NULL; } // clears all the pending messages we have left over // call this after all messages are handled void flushPendingMessages ( void ) { for ( unsigned int i = 0; i < pendingMessages.size(); i++ ) free(pendingMessages[i].data); pendingMessages.clear(); } }; unsigned int readStringFromData ( std::string &str, const char *data, unsigned int len ) { str = ""; unsigned short strLen = net_Read16(data); if ( (unsigned short)len < strLen+2 ) return 0; char* temp = (char*)malloc(strLen+1); temp[strLen] = 0; memcpy(temp,data+2,strLen); str = temp; free(temp); return strLen+2; } #endif //_NET_UTILS_H_
[ "JeffM2501@b8188ba6-572f-0410-9fd0-1f3cfbbf368d" ]
[ [ [ 1, 183 ] ] ]
62388e66d8a045655077cbf90e914fab071b3740
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Src/DharaniDev/DharaniDev/DharaniDev.h
8d114c6a318efe41a8c56d2e19f6a44f16716d0c
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UTF-8
C++
false
false
528
h
// DharaniDev.h : main header file for the PROJECT_NAME application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CDharaniDevApp: // See DharaniDev.cpp for the implementation of this class // class CDharaniDevApp : public CWinApp { public: CDharaniDevApp(); // Overrides public: virtual BOOL InitInstance(); // Implementation DECLARE_MESSAGE_MAP() }; extern CDharaniDevApp theApp;
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 31 ] ] ]
e7cd68c38b9da7ea185769e62955c327acda0e1c
677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f
/SolidSBCSrvSvc/SolidSBCResultStack.cpp
20522535b4439d683b9259f3fc50b75bd827603f
[]
no_license
M0WA/SolidSBC
0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419
3e9682e90a22650e12338785c368ed69a9cac18b
refs/heads/master
2020-04-19T14:40:36.625222
2011-12-02T01:50:05
2011-12-02T01:50:05
168,250,374
0
0
null
null
null
null
UTF-8
C++
false
false
7,573
cpp
#include "StdAfx.h" #include "SolidSBCResultStack.h" /* CResultStack::CResultStack(void) : m_lNextHDResultID(0) , m_lNextCPUMeasureResultID(0) { } CResultStack::~CResultStack(void) { Flush(); } int CResultStack::Flush(void) { FlushHD(); FlushCPUMeasure(); return 0; } int CResultStack::FlushHD(void) { CString strHDCVSFile; if ( ( theApp.m_cConfigFile.GetParamStr( VMPERFORMER_CFGFILE_SRV_HD_RESULT_CSVFILE, &strHDCVSFile) != 0 ) ) strHDCVSFile = VMPERFORMER_CFGFILE_SRV_HD_RESULT_CSVFILE_DEFAULT; if ( strHDCVSFile == _T("") ){ m_vHDTestResult.clear(); return 1;} CString strCSVCellSeparator = _T(""); if ( theApp.m_cConfigFile.GetParamStr( VMPERFORMER_CFGFILE_SRV_CSV_CELL_SEPARATOR, &strCSVCellSeparator ) != 0 ){ strCSVCellSeparator = VMPERFORMER_CFGFILE_SRV_CSV_CELL_SEPARATOR_DEFAULT;} strCSVCellSeparator.Replace(_T("\\t"),_T("\t")); CString strCSVRowSeparator = _T(""); if ( theApp.m_cConfigFile.GetParamStr( VMPERFORMER_CFGFILE_SRV_CSV_ROW_SEPARATOR, &strCSVRowSeparator ) != 0 ){ strCSVRowSeparator = VMPERFORMER_CFGFILE_SRV_CSV_ROW_SEPARATOR_DEFAULT;} strCSVRowSeparator.Replace(_T("\\n"),_T("\n")); strCSVRowSeparator.Replace(_T("\\r"),_T("\r")); //assemble csv string CString strCompleteLog; for ( std::vector<VMPERFSRV_HD_TESTRESULT>::iterator i = m_vHDTestResult.begin(); i < m_vHDTestResult.end(); i++){ CString strLogLine; strLogLine.Format(_T("%d%s%d%s%f%s%d%s%d%s") , (*i).nResultID, strCSVCellSeparator , (*i).nClientID, strCSVCellSeparator , (*i).hdResult.dSeconds, strCSVCellSeparator , (*i).hdResult.ulBytes, strCSVCellSeparator , (*i).hdResult.nType, strCSVRowSeparator ); strCompleteLog += strLogLine; } m_vHDTestResult.clear(); //write to log FlushFile(strCompleteLog,strHDCVSFile); return 0; } int CResultStack::FlushFile(CString strCompleteLog, CString strFileName) { //fix decimal seperators CString strCSVDecimalSeparator = _T(""); if ( theApp.m_cConfigFile.GetParamStr( VMPERFORMER_CFGFILE_SRV_CSV_DECIMAL_SEPARATOR, &strCSVDecimalSeparator ) != 0 ){ strCSVDecimalSeparator = VMPERFORMER_CFGFILE_SRV_CSV_DECIMAL_SEPARATOR_DEFAULT;} strCompleteLog.Replace( _T("."),strCSVDecimalSeparator); int length = strCompleteLog.GetLength() * sizeof(TCHAR); TRY { CFile csvFile; csvFile.Open(strFileName,CFile::modeWrite|CFile::modeCreate|CFile::modeNoTruncate); csvFile.SeekToEnd(); csvFile.Write( strCompleteLog.GetBuffer(length), length ); strCompleteLog.ReleaseBuffer(); csvFile.Close(); } CATCH(CException, e) { e->ReportError(); } END_CATCH return 0; } int CResultStack::AddHDResult(PVMPERFSRV_HD_TESTRESULT pResult) { pResult->nResultID = m_lNextHDResultID; m_vHDTestResult.push_back( *pResult ); m_lNextHDResultID++; int nMaxHDEntries = 0; if ( theApp.m_cConfigFile.GetParamInt(VMPERFORMER_CFGFILE_SRV_MAX_HD_RES, &nMaxHDEntries) != 0 ){ nMaxHDEntries = VMPERFORMER_CFGFILE_SRV_MAX_HD_RES_DEFAULT;} if (m_vHDTestResult.size() == nMaxHDEntries){ FlushHD();} #ifdef VMPERFORMER_SRV_ENABLE_LOGGING int nDebug = 0; if (theApp.m_cConfigFile.GetParamInt(VMPERFORMER_CFGFILE_SRV_LOG_DEBUG,&nDebug) != 0) nDebug = VMPERFORMER_CFGFILE_SRV_LOG_DEBUG_DEFAULT; if (nDebug) { CString strLogLine; strLogLine.Format(_T("DEBUG: hd-result received:\n ResultID:%d\n ClientID:%d\n Seconds:%f\n Bytes:%d\n Read(0)/Write(1): %d") , pResult->nResultID , pResult->nClientID , pResult->hdResult.dSeconds , pResult->hdResult.ulBytes , pResult->hdResult.nType ); theApp.WriteToVMPerfSrvLog( strLogLine ); } #endif return 0; } int CResultStack::AddCPUMeasureResult(PVMPERF_CPUMEASURE_TESTRESULT pResult) { pResult->nResultID = m_lNextCPUMeasureResultID; m_vCPUMeasureResult.push_back( *pResult ); m_lNextCPUMeasureResultID++; int nMaxCPUMeasureEntries = 0; if ( theApp.m_cConfigFile.GetParamInt(VMPERFORMER_CFGFILE_SRV_MAX_CPUMEASURE_RES, &nMaxCPUMeasureEntries) != 0 ){ nMaxCPUMeasureEntries = VMPERFORMER_CFGFILE_SRV_MAX_CPUMEASURE_RES_DEFAULT;} if (m_vCPUMeasureResult.size() == nMaxCPUMeasureEntries){ FlushCPUMeasure();} #ifdef VMPERFORMER_SRV_ENABLE_LOGGING int nDebug = 0; if (theApp.m_cConfigFile.GetParamInt(VMPERFORMER_CFGFILE_SRV_LOG_DEBUG,&nDebug) != 0) nDebug = VMPERFORMER_CFGFILE_SRV_LOG_DEBUG_DEFAULT; if (nDebug) { CString strLogLine; strLogLine.Format(_T("DEBUG: cpumeasure-result received:\n ResultID:%d\n ClientID:%d\n AddDuration:%f\n DivDuration:%f\n OverallDuration: %f\n AddMultiplier: %u\n DivMultiplier: %u") , pResult->nResultID , pResult->nClientID , pResult->cpuMeasure.dAddDuration , pResult->cpuMeasure.dDivDuration , pResult->cpuMeasure.dOverallDuration , pResult->cpuMeasure.ullAddMultiplier , pResult->cpuMeasure.ullDivMultiplier ); theApp.WriteToVMPerfSrvLog( strLogLine ); } #endif return 0; } int CResultStack::FlushCPUMeasure(void) { CString strCPUMeasureCVSFile; if ( theApp.m_cConfigFile.GetParamStr( VMPERFORMER_CFGFILE_SRV_CPUMEASURE_RESULT_CSVFILE, &strCPUMeasureCVSFile) != 0 ) strCPUMeasureCVSFile = VMPERFORMER_CFGFILE_SRV_CPUMEASURE_RESULT_CSVFILE_DEFAULT; if ( strCPUMeasureCVSFile == _T("") ){ m_vCPUMeasureResult.clear(); return 1;} CString strCSVCellSeparator = _T(""); if ( theApp.m_cConfigFile.GetParamStr( VMPERFORMER_CFGFILE_SRV_CSV_CELL_SEPARATOR, &strCSVCellSeparator ) != 0 ){ strCSVCellSeparator = VMPERFORMER_CFGFILE_SRV_CSV_CELL_SEPARATOR_DEFAULT;} strCSVCellSeparator.Replace(_T("\\t"),_T("\t")); CString strCSVRowSeparator = _T(""); if ( theApp.m_cConfigFile.GetParamStr( VMPERFORMER_CFGFILE_SRV_CSV_ROW_SEPARATOR, &strCSVRowSeparator ) != 0 ){ strCSVRowSeparator = VMPERFORMER_CFGFILE_SRV_CSV_ROW_SEPARATOR_DEFAULT;} strCSVRowSeparator.Replace(_T("\\n"),_T("\n")); strCSVRowSeparator.Replace(_T("\\r"),_T("\r")); //assemble csv string CString strCompleteLog; for ( std::vector<VMPERF_CPUMEASURE_TESTRESULT>::iterator i = m_vCPUMeasureResult.begin(); i < m_vCPUMeasureResult.end(); i++){ CString strLogLine; strLogLine.Format( _T("%d%s%d%s%f%s%f%s%f%s%I64u%s%I64u%s") , (*i).nResultID , strCSVCellSeparator , (*i).nClientID , strCSVCellSeparator , (*i).cpuMeasure.dAddDuration, strCSVCellSeparator , (*i).cpuMeasure.dDivDuration, strCSVCellSeparator , (*i).cpuMeasure.dOverallDuration, strCSVCellSeparator , (*i).cpuMeasure.ullAddMultiplier, strCSVCellSeparator , (*i).cpuMeasure.ullDivMultiplier, strCSVRowSeparator ); strCompleteLog += strLogLine; } m_vCPUMeasureResult.clear(); //write to log FlushFile(strCompleteLog,strCPUMeasureCVSFile); return 0; } int CResultStack::AddMemResult(PVMPERF_MEM_TESTRESULT pResult) { pResult->nResultID = m_lNextHDResultID; m_lNextHDResultID++; //TODO: add mem result to csv file return 0; } int CResultStack::AddNetPingResult(PVMPERF_NET_PING_TESTRESULT pResult) { pResult->nResultID = m_lNextHDResultID; m_lNextHDResultID++; return 0; } int CResultStack::AddNetTCPConResult(PVMPERF_NET_TCPCON_TESTRESULT pResult) { pResult->nResultID = m_lNextHDResultID; m_lNextHDResultID++; return 0; } int CResultStack::AddClientHistoryResult(CClientResultInfo* pResult, VMPERF_CLIENT_HISTORY_ACTION nAction, UINT nActionParam) { //TODO: add client history to csv file return 0; } */
[ "admin@bd7e3521-35e9-406e-9279-390287f868d3" ]
[ [ [ 1, 239 ] ] ]
4f0f07e4a9db771a55bafb1e6e7d661bcd4fc2ac
bdb8fc8eb5edc84cf92ba80b8541ba2b6c2b0918
/TPs CPOO/Gareth & Maxime/Projet/Wrapper/test2/mWrapper4/mWrapper4/mWrapper4.cpp
3f2385fee03514bb5d19aa85063606d21d99acdf
[]
no_license
Issam-Engineer/tp4infoinsa
3538644b40d19375b6bb25f030580004ed4a056d
1576c31862ffbc048890e72a81efa11dba16338b
refs/heads/master
2021-01-10T17:53:31.102683
2011-01-27T07:46:51
2011-01-27T07:46:51
55,446,817
0
0
null
null
null
null
UTF-8
C++
false
false
91
cpp
// Il s'agit du fichier DLL principal. #include "stdafx.h" #include "mWrapper4.h"
[ "havez.maxime.01@9f3b02c3-fd90-5378-97a3-836ae78947c6" ]
[ [ [ 1, 6 ] ] ]
9b7127755ee5252edd680b854dcd44fb687b634b
502efe97b985c69d6378d9c428c715641719ee03
/src/moaicore/MOAIDeckRemapper.cpp
ac3ce21197e10eb49aae0c6b24f225235cb66dae
[]
no_license
neojjang/moai-beta
c3933bca2625bca4f4da26341de6b855e41b9beb
6bc96412d35192246e35bff91df101bd7c7e41e1
refs/heads/master
2021-01-16T20:33:59.443558
2011-09-19T23:45:06
2011-09-19T23:45:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,971
cpp
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved. // http://getmoai.com #include "pch.h" #include <moaicore/MOAILogMessages.h> #include <moaicore/MOAIDeckRemapper.h> #include <moaicore/MOAITileFlags.h> //================================================================// // local //================================================================// //----------------------------------------------------------------// /** @name reserve @text The total number of indices to remap. Index remaps will be initialized from 1 to N. @in MOAIDeckRemapper self @opt number size Default value is 0. @out nil */ int MOAIDeckRemapper::_reserve ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIDeckRemapper, "U" ) u32 size = state.GetValue < u32 >( 2, 0 ); self->mRemap.Init ( size ); for ( u32 i = 0; i < size; ++i ) { self->mRemap [ i ] = i + 1; } return 0; } //----------------------------------------------------------------// /** @name setBase @text Set the base offset for the range of indices to remap. Used when remapping only a portion of the indices in the original deck. @in MOAIDeckRemapper self @opt number base Default value is 0. @out nil */ int MOAIDeckRemapper::_setBase ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIDeckRemapper, "U" ) self->mBase = state.GetValue < u32 >( 2, 0 ); return 0; } //----------------------------------------------------------------// /** @name setRemap @text Remap a single index to a new value. @in MOAIDeckRemapper self @in number index Index to remap. @opt number remap New value for index. Default value is index (i.e. remove the remap). @out nil */ int MOAIDeckRemapper::_setRemap ( lua_State* L ) { MOAI_LUA_SETUP ( MOAIDeckRemapper, "UN" ) u32 idx = state.GetValue < u32 >( 2, 1 ) - 1; u32 remap = state.GetValue < u32 >( 3, idx ); if ( idx < self->mRemap.Size ()) { self->mRemap [ idx ] = remap; } return 0; } //================================================================// // MOAIDeckRemapper //================================================================// //----------------------------------------------------------------// bool MOAIDeckRemapper::ApplyAttrOp ( u32 attrID, USAttrOp& attrOp ) { UNUSED ( attrID ); UNUSED ( attrOp ); attrID -=1; if (( attrID >= this->mBase ) && ( attrID < this->mRemap.Size ())) { this->mRemap [ attrID ] = attrOp.Op ( this->mRemap [ attrID ]); return true; } return false; } //----------------------------------------------------------------// MOAIDeckRemapper::MOAIDeckRemapper () : mBase ( 0 ) { RTTI_BEGIN RTTI_EXTEND ( MOAINode ) RTTI_END } //----------------------------------------------------------------// MOAIDeckRemapper::~MOAIDeckRemapper () { } //----------------------------------------------------------------// void MOAIDeckRemapper::RegisterLuaClass ( USLuaState& state ) { MOAINode::RegisterLuaClass ( state ); } //----------------------------------------------------------------// void MOAIDeckRemapper::RegisterLuaFuncs ( USLuaState& state ) { MOAINode::RegisterLuaFuncs ( state ); luaL_Reg regTable [] = { { "reserve", _reserve }, { "setBase", _setBase }, { "setRemap", _setRemap }, { NULL, NULL } }; luaL_register ( state, 0, regTable ); } //----------------------------------------------------------------// u32 MOAIDeckRemapper::Remap ( u32 idx ) { u32 code = ( idx & MOAITileFlags::CODE_MASK ) - 1; if (( code >= this->mBase ) && ( code < this->mRemap.Size ())) { u32 flags = idx & MOAITileFlags::FLAGS_MASK; return ( this->mRemap [ code ] ^ ( flags & MOAITileFlags::FLIP_MASK )) | ( flags & MOAITileFlags::HIDDEN ); } return idx; } //----------------------------------------------------------------// STLString MOAIDeckRemapper::ToString () { STLString repr; return repr; }
[ "Patrick@agile.(none)", "[email protected]" ]
[ [ [ 1, 6 ], [ 8, 126 ], [ 128, 130 ], [ 133, 143 ] ], [ [ 7, 7 ], [ 127, 127 ], [ 131, 132 ] ] ]
ede7229de903b813a68e9e8ccffe5f253936318a
cfa6cdfaba310a2fd5f89326690b5c48c6872a2a
/References/My SQL/tutorialSQL/Tutorial/sql_02/sql_02.cpp
783a4ea3302aa084e8ffffd2d9d0224eb404811a
[]
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
1,828
cpp
// sql_01.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <conio.h> #include <mysql++.h> using namespace std; using namespace mysqlpp; #pragma comment(lib,"libmysql") #pragma comment(lib,"mysqlpp") int _tmain(int argc, _TCHAR* argv[]) { Connection con("mmuser", "127.0.0.1", "root", "1124"); // ------------------------------------------------------- //Query query = con.query(); /*query << "show databases"; cout << "Query: " << query.preview() << endl; Result res = query.store(); cout << "Databases found: " << res.size() << endl; Row row; cout.setf(ios::left); Result::iterator i; for (i = res.begin(); i != res.end(); ++i) { row = *i; cout << '\t' << setw(17) << row.raw_data(0) << endl ; } // ------------------------------------------------------- con.select_db("gamedata"); query.reset(); query << "show tables"; cout << "Query: " << query.preview() << endl; res = query.store(); cout << "Tables found: " << res.size() << endl; cout.setf(ios::left); for (i = res.begin(); i != res.end(); ++i) { row = *i; cout << '\t' << setw(17) << (string)row.raw_data(0) << endl; } // ------------------------------------------------------- query.reset(); query << "select * from playerinfo"; res = query.store(); int columns = res.num_fields(); cout << "fields = " << res.num_fields() << ", rows = " << res.size() << endl; volatile MYSQL_RES* ress = res.raw_result(); if (!ress) return -1; for (i = res.begin(); i != res.end(); ++i) { for (int counter = 0; counter < columns; counter++) { cout << string( (*i).at(counter)) << " "; } cout << endl; }*/ // ------------------------------------------------------- getch(); return 0; }
[ [ [ 1, 4 ], [ 6, 17 ], [ 19, 21 ], [ 24, 72 ], [ 74, 76 ], [ 78, 79 ] ], [ [ 5, 5 ], [ 18, 18 ], [ 22, 23 ], [ 73, 73 ], [ 77, 77 ] ] ]
eea3d08bd0f90691ce18ca71a1e3bd1152d2164f
de0881d85df3a3a01924510134feba2fbff5b7c3
/apps/dev/neuralNetworkDemo/src/ofxNeuralNetwork/src/Connection.cpp
2ef3d5fd5a97e3fcbe87f9bd9d2527385b83e7dc
[]
no_license
peterkrenn/ofx-dev
6091def69a1148c05354e55636887d11e29d6073
e08e08a06be6ea080ecd252bc89c1662cf3e37f0
refs/heads/master
2021-01-21T00:32:49.065810
2009-06-26T19:13:29
2009-06-26T19:13:29
146,543
1
1
null
null
null
null
UTF-8
C++
false
false
557
cpp
#include "Connection.h" float Connection::maxInitWeight = 0.1f; float Connection::learningRate = 0.001f; Connection::Connection(Neuron* a, Neuron* b) { weight = randomWeight(); a->addOut(this); b->addIn(this); } void Connection::forwardPropagate() { target->activate(source->activation * weight); } void Connection::changeWeight() { weight += learningRate * target->delta * source->activation; } float Connection::randomWeight() { float one = (float) rand() / (1 << 15); one = one * 2 - 1; return one * maxInitWeight; }
[ [ [ 1, 24 ] ] ]
07423d37217576b1c3538b5397bc34906d864486
e31046aee3ad2d4600c7f35aaeeba76ee2b99039
/trunk/libs/bullet/includes/BulletCollision/CollisionShapes/btBoxShape.h
3f8daa09c4f2c63dd132895f40a0bd9d3b672275
[]
no_license
BackupTheBerlios/trinitas-svn
ddea265cf47aff3e8853bf6d46861e0ed3031ea1
7d3ff64a7d0e5ba37febda38e6ce0b2d0a4b6cca
refs/heads/master
2021-01-23T08:14:44.215249
2009-02-18T19:37:51
2009-02-18T19:37:51
40,749,519
0
0
null
null
null
null
UTF-8
C++
false
false
8,881
h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/ 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 OBB_BOX_MINKOWSKI_H #define OBB_BOX_MINKOWSKI_H #include "btPolyhedralConvexShape.h" #include "btCollisionMargin.h" #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h" #include "LinearMath/btPoint3.h" #include "LinearMath/btMinMax.h" ///The btBoxShape is a box primitive around the origin, its sides axis aligned with length specified by half extents, in local shape coordinates. When used as part of a btCollisionObject or btRigidBody it will be an oriented box in world space. class btBoxShape: public btPolyhedralConvexShape { //btVector3 m_boxHalfExtents1; //use m_implicitShapeDimensions instead public: btVector3 getHalfExtentsWithMargin() const { btVector3 halfExtents = getHalfExtentsWithoutMargin(); btVector3 margin(getMargin(),getMargin(),getMargin()); halfExtents += margin; return halfExtents; } const btVector3& getHalfExtentsWithoutMargin() const { return m_implicitShapeDimensions;//changed in Bullet 2.63: assume the scaling and margin are included } virtual btVector3 localGetSupportingVertex(const btVector3& vec) const { btVector3 halfExtents = getHalfExtentsWithoutMargin(); btVector3 margin(getMargin(),getMargin(),getMargin()); halfExtents += margin; return btVector3(btFsels(vec.x(), halfExtents.x(), -halfExtents.x()), btFsels(vec.y(), halfExtents.y(), -halfExtents.y()), btFsels(vec.z(), halfExtents.z(), -halfExtents.z())); } SIMD_FORCE_INLINE btVector3 localGetSupportingVertexWithoutMargin(const btVector3& vec)const { const btVector3& halfExtents = getHalfExtentsWithoutMargin(); return btVector3(btFsels(vec.x(), halfExtents.x(), -halfExtents.x()), btFsels(vec.y(), halfExtents.y(), -halfExtents.y()), btFsels(vec.z(), halfExtents.z(), -halfExtents.z())); } virtual void batchedUnitVectorGetSupportingVertexWithoutMargin(const btVector3* vectors,btVector3* supportVerticesOut,int numVectors) const { const btVector3& halfExtents = getHalfExtentsWithoutMargin(); for (int i=0;i<numVectors;i++) { const btVector3& vec = vectors[i]; supportVerticesOut[i].setValue(btFsels(vec.x(), halfExtents.x(), -halfExtents.x()), btFsels(vec.y(), halfExtents.y(), -halfExtents.y()), btFsels(vec.z(), halfExtents.z(), -halfExtents.z())); } } btBoxShape( const btVector3& boxHalfExtents) : btPolyhedralConvexShape() { m_shapeType = BOX_SHAPE_PROXYTYPE; btVector3 margin(getMargin(),getMargin(),getMargin()); m_implicitShapeDimensions = (boxHalfExtents * m_localScaling) - margin; }; virtual void setMargin(btScalar collisionMargin) { //correct the m_implicitShapeDimensions for the margin btVector3 oldMargin(getMargin(),getMargin(),getMargin()); btVector3 implicitShapeDimensionsWithMargin = m_implicitShapeDimensions+oldMargin; btConvexInternalShape::setMargin(collisionMargin); btVector3 newMargin(getMargin(),getMargin(),getMargin()); m_implicitShapeDimensions = implicitShapeDimensionsWithMargin - newMargin; } virtual void setLocalScaling(const btVector3& scaling) { btVector3 oldMargin(getMargin(),getMargin(),getMargin()); btVector3 implicitShapeDimensionsWithMargin = m_implicitShapeDimensions+oldMargin; btVector3 unScaledImplicitShapeDimensionsWithMargin = implicitShapeDimensionsWithMargin / m_localScaling; btConvexInternalShape::setLocalScaling(scaling); m_implicitShapeDimensions = (unScaledImplicitShapeDimensionsWithMargin * m_localScaling) - oldMargin; } virtual void getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const; virtual void calculateLocalInertia(btScalar mass,btVector3& inertia) const; virtual void getPlane(btVector3& planeNormal,btPoint3& planeSupport,int i ) const { //this plane might not be aligned... btVector4 plane ; getPlaneEquation(plane,i); planeNormal = btVector3(plane.getX(),plane.getY(),plane.getZ()); planeSupport = localGetSupportingVertex(-planeNormal); } virtual int getNumPlanes() const { return 6; } virtual int getNumVertices() const { return 8; } virtual int getNumEdges() const { return 12; } virtual void getVertex(int i,btVector3& vtx) const { btVector3 halfExtents = getHalfExtentsWithoutMargin(); vtx = btVector3( halfExtents.x() * (1-(i&1)) - halfExtents.x() * (i&1), halfExtents.y() * (1-((i&2)>>1)) - halfExtents.y() * ((i&2)>>1), halfExtents.z() * (1-((i&4)>>2)) - halfExtents.z() * ((i&4)>>2)); } virtual void getPlaneEquation(btVector4& plane,int i) const { btVector3 halfExtents = getHalfExtentsWithoutMargin(); switch (i) { case 0: plane.setValue(btScalar(1.),btScalar(0.),btScalar(0.)); plane[3] = -halfExtents.x(); break; case 1: plane.setValue(btScalar(-1.),btScalar(0.),btScalar(0.)); plane[3] = -halfExtents.x(); break; case 2: plane.setValue(btScalar(0.),btScalar(1.),btScalar(0.)); plane[3] = -halfExtents.y(); break; case 3: plane.setValue(btScalar(0.),btScalar(-1.),btScalar(0.)); plane[3] = -halfExtents.y(); break; case 4: plane.setValue(btScalar(0.),btScalar(0.),btScalar(1.)); plane[3] = -halfExtents.z(); break; case 5: plane.setValue(btScalar(0.),btScalar(0.),btScalar(-1.)); plane[3] = -halfExtents.z(); break; default: assert(0); } } virtual void getEdge(int i,btPoint3& pa,btPoint3& pb) const //virtual void getEdge(int i,Edge& edge) const { int edgeVert0 = 0; int edgeVert1 = 0; switch (i) { case 0: edgeVert0 = 0; edgeVert1 = 1; break; case 1: edgeVert0 = 0; edgeVert1 = 2; break; case 2: edgeVert0 = 1; edgeVert1 = 3; break; case 3: edgeVert0 = 2; edgeVert1 = 3; break; case 4: edgeVert0 = 0; edgeVert1 = 4; break; case 5: edgeVert0 = 1; edgeVert1 = 5; break; case 6: edgeVert0 = 2; edgeVert1 = 6; break; case 7: edgeVert0 = 3; edgeVert1 = 7; break; case 8: edgeVert0 = 4; edgeVert1 = 5; break; case 9: edgeVert0 = 4; edgeVert1 = 6; break; case 10: edgeVert0 = 5; edgeVert1 = 7; break; case 11: edgeVert0 = 6; edgeVert1 = 7; break; default: btAssert(0); } getVertex(edgeVert0,pa ); getVertex(edgeVert1,pb ); } virtual bool isInside(const btPoint3& pt,btScalar tolerance) const { btVector3 halfExtents = getHalfExtentsWithoutMargin(); //btScalar minDist = 2*tolerance; bool result = (pt.x() <= (halfExtents.x()+tolerance)) && (pt.x() >= (-halfExtents.x()-tolerance)) && (pt.y() <= (halfExtents.y()+tolerance)) && (pt.y() >= (-halfExtents.y()-tolerance)) && (pt.z() <= (halfExtents.z()+tolerance)) && (pt.z() >= (-halfExtents.z()-tolerance)); return result; } //debugging virtual const char* getName()const { return "Box"; } virtual int getNumPreferredPenetrationDirections() const { return 6; } virtual void getPreferredPenetrationDirection(int index, btVector3& penetrationVector) const { switch (index) { case 0: penetrationVector.setValue(btScalar(1.),btScalar(0.),btScalar(0.)); break; case 1: penetrationVector.setValue(btScalar(-1.),btScalar(0.),btScalar(0.)); break; case 2: penetrationVector.setValue(btScalar(0.),btScalar(1.),btScalar(0.)); break; case 3: penetrationVector.setValue(btScalar(0.),btScalar(-1.),btScalar(0.)); break; case 4: penetrationVector.setValue(btScalar(0.),btScalar(0.),btScalar(1.)); break; case 5: penetrationVector.setValue(btScalar(0.),btScalar(0.),btScalar(-1.)); break; default: assert(0); } } }; #endif //OBB_BOX_MINKOWSKI_H
[ "paradoxon@ab3bda7c-5b37-0410-9911-e7f4556ba333" ]
[ [ [ 1, 323 ] ] ]
d24cc9a8dacde40475deb008a7b95185ac4ffe51
ad33a51b7d45d8bf1aa900022564495bc08e0096
/DES/DES_GOBSTG/Header/Bullet.h
468056ee13aba99ebb2a32a7d58510edde9da350
[]
no_license
CBE7F1F65/e20671a6add96e9aa3551d07edee6bd4
31aff43df2571d334672929c88dfd41315a4098a
f33d52bbb59dfb758b24c0651449322ecd1b56b7
refs/heads/master
2016-09-11T02:42:42.116248
2011-09-26T04:30:32
2011-09-26T04:30:32
32,192,691
0
0
null
null
null
null
UTF-8
C++
false
false
3,614
h
#ifndef _BULLET_H #define _BULLET_H #include "BObject.h" #include "BulletListActionConst.h" #include "Effectsys.h" #define BULLETMAX 0x1000 #define BULLETCOLORMAX 0x10 #define BULLETTYPECOLORMAX (BULLETTYPEMAX * BULLETCOLORMAX) #define BULLETACTIONMAX 0x20 #define BULLETIZELISTMAX 0x04 #define BULLET_FADEINTYPE (BULLETTYPEMAX - 3) #define BULLET_FADEOUTTYPE (BULLETTYPEMAX - 2) #define BULLET_BONUSTYPE (BULLETTYPEMAX - 1) #define BULLET_ANGLEOFFSET 9000 #define BULLET_FADECOLOR_16 160 #define BULLET_FADECOLOR_8 80 #define BULLET_COLLISION_NONE 0 #define BULLET_COLLISION_CIRCLE 1 #define BULLET_COLLISION_ELLIPSE 2 #define BULLET_COLLISION_RECT 3 #define BULLET_COLLISION_SQURE 4 #define BULLET_ANIMATIONSPEED 4 #define BULLET_FADEINTIME 8 #define BULLET_TYPECHANGETIME 16 #define BULLETZONE_ERASE 0 #define BULLETZONE_SEND 1 #define BULLETZONE_EVENT 2 #define BULLET_EVENTMAX 4 #define BULLETACT_FLOATSCALE 100.0f #define BULLETACT_ANGLECHANGESE 3000 typedef struct tagRenderDepth{ int startIndex; int endIndex; bool haveType; }RenderDepth; class Bullet : public BObject { public: Bullet(); ~Bullet(); static void Init(HTEXTURE tex); static void Release(); static void ClearItem(); static void Action(); static void RenderAll(BYTE playerindex); void Render(); void action(); void actionInStop(); int DoIze(); bool DoCollision(); void DoGraze(); void DoUpdateRenderDepth(); bool HaveGray(); BYTE getRenderDepth(); bool isInRect(float aimx, float aimy, float r, int nextstep=0); bool valueSet(BYTE playerindex, WORD ID, float x, float y, int angle, float speed, BYTE type, BYTE color, int fadeinTime, float avoid = 0, BYTE tarID = 0xff); static int Build(BYTE playerindex, float x, float y, int angle, float speed, BYTE type, BYTE color, int fadeinTime=BULLET_FADEINTIME, float avoid=0, BYTE tarID=0xff); static void BuildCircle(BYTE playerindex, int num, int baseangle, float baser, float x, float y, float speed, BYTE type, BYTE color, int fadeinTime=BULLET_FADEINTIME, float avoid=0); static void BuildLine(BYTE playerindex, int num, int baseangle, float space, int baseindex, float x, float y, int angle, float anglefactor, float speed, float speedfactor, BYTE type, BYTE color, int fadeinTime=BULLET_FADEINTIME, float avoid=0); void matchFadeInColorType(); void matchFadeOutColorType(); static void SendBullet(BYTE playerindex, float x, float y, BYTE setID, BYTE * sendtime=NULL, float * speed = NULL, int sendbonus=1); void AddSendInfo(BYTE sendsetID, BYTE _sendtime); bool passedEvent(DWORD eventID); void passEvent(DWORD eventID); bool ChangeAction(int nextstep=0); void changeType(BYTE totype); public: int actionList[BULLETACTIONMAX]; DWORD eventID[BULLET_EVENTMAX]; float xplus; float yplus; float lastx; float lasty; float lastspeed; int lastangle; int fadeinTime; bool fadeout; bool able; bool grazed; bool remain; bool cancelable; BYTE type; BYTE oldtype; BYTE color; BYTE oldcolor; BYTE playerindex; BYTE typechangetimer; BYTE sendtime; BYTE sendsetID; int sendbonus; BYTE bouncetime; BYTE renderflag; Effectsys eff; static int _actionList[M_PL_MATCHMAXPLAYER][BULLETACTIONMAX]; static RenderDepth renderDepth[M_PL_MATCHMAXPLAYER][BULLETTYPEMAX]; static hgeSprite * sprite[BULLETTYPECOLORMAX]; static HTEXTURE tex; static WORD index; static VectorList<Bullet>bu[M_PL_MATCHMAXPLAYER]; static int rendercount[M_PL_MATCHMAXPLAYER]; }; #endif
[ "CBE7F1F65@b503aa94-de59-8b24-8582-4b2cb17628fa" ]
[ [ [ 1, 141 ] ] ]
045cdc4d005f6463cce4337a7bb5570a9b0792c2
f744f8897adce6654cdfe6466eaf4d0fad4ba661
/src/view/glInfo.cpp
955c600a947a7252b597af37988b42c06095e5ba
[]
no_license
pizibing/bones-animation
37919ab3750683a5da0cc849f80d1e0f5b37c89c
92ce438e28e3020c0e8987299c11c4b74ff98ed5
refs/heads/master
2016-08-03T05:34:19.294712
2009-09-16T14:59:32
2009-09-16T14:59:32
33,969,248
0
0
null
null
null
null
UTF-8
C++
false
false
5,549
cpp
/////////////////////////////////////////////////////////////////////////////// // glInfo.cpp // ========== // get GL vendor, version, supported extensions and other states using glGet* // functions and store them glInfo struct variable // // To get valid OpenGL infos, OpenGL rendering context (RC) must be opened // before calling glInfo::getInfo(). Otherwise it returns false. // /////////////////////////////////////////////////////////////////////////////// #include <GL/glut.h> #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include "glInfo.h" using std::string; using std::stringstream; using std::vector; using std::cout; using std::endl; /////////////////////////////////////////////////////////////////////////////// // extract openGL info // This function must be called after GL rendering context opened. /////////////////////////////////////////////////////////////////////////////// bool glInfo::getInfo() { char* str = 0; char* tok = 0; // get vendor string str = (char*)glGetString(GL_VENDOR); if(str) this->vendor = str; // check NULL return value else return false; // get renderer string str = (char*)glGetString(GL_RENDERER); if(str) this->renderer = str; // check NULL return value else return false; // get version string str = (char*)glGetString(GL_VERSION); if(str) this->version = str; // check NULL return value else return false; // get all extensions as a string str = (char*)glGetString(GL_EXTENSIONS); // split extensions if(str) { tok = strtok((char*)str, " "); while(tok) { this->extensions.push_back(tok); // put a extension into struct tok = strtok(0, " "); // next token } } else { return false; } // sort extension by alphabetical order std::sort(this->extensions.begin(), this->extensions.end()); // get number of color bits glGetIntegerv(GL_RED_BITS, &this->redBits); glGetIntegerv(GL_GREEN_BITS, &this->greenBits); glGetIntegerv(GL_BLUE_BITS, &this->blueBits); glGetIntegerv(GL_ALPHA_BITS, &this->alphaBits); // get depth bits glGetIntegerv(GL_DEPTH_BITS, &this->depthBits); // get stecil bits glGetIntegerv(GL_STENCIL_BITS, &this->stencilBits); // get max number of lights allowed glGetIntegerv(GL_MAX_LIGHTS, &this->maxLights); // get max texture resolution glGetIntegerv(GL_MAX_TEXTURE_SIZE, &this->maxTextureSize); // get max number of clipping planes glGetIntegerv(GL_MAX_CLIP_PLANES, &this->maxClipPlanes); // get max modelview and projection matrix stacks glGetIntegerv(GL_MAX_MODELVIEW_STACK_DEPTH, &this->maxModelViewStacks); glGetIntegerv(GL_MAX_PROJECTION_STACK_DEPTH, &this->maxProjectionStacks); glGetIntegerv(GL_MAX_ATTRIB_STACK_DEPTH, &this->maxAttribStacks); // get max texture stacks glGetIntegerv(GL_MAX_TEXTURE_STACK_DEPTH, &this->maxTextureStacks); return true; } /////////////////////////////////////////////////////////////////////////////// // check if the video card support a certain extension /////////////////////////////////////////////////////////////////////////////// bool glInfo::isExtensionSupported(const char* ext) { // search corresponding extension std::vector< string >::const_iterator iter = this->extensions.begin(); std::vector< string >::const_iterator endIter = this->extensions.end(); while(iter != endIter) { if(ext == *iter) return true; else ++iter; } return false; } /////////////////////////////////////////////////////////////////////////////// // print OpenGL info to screen and save to a file /////////////////////////////////////////////////////////////////////////////// void glInfo::printSelf() { stringstream ss; ss << endl; // blank line ss << "OpenGL Driver Info" << endl; ss << "==================" << endl; ss << "Vendor: " << this->vendor << endl; ss << "Version: " << this->version << endl; ss << "Renderer: " << this->renderer << endl; ss << endl; ss << "Color Bits(R,G,B,A): (" << this->redBits << ", " << this->greenBits << ", " << this->blueBits << ", " << this->alphaBits << ")\n"; ss << "Depth Bits: " << this->depthBits << endl; ss << "Stencil Bits: " << this->stencilBits << endl; ss << endl; ss << "Max Texture Size: " << this->maxTextureSize << "x" << this->maxTextureSize << endl; ss << "Max Lights: " << this->maxLights << endl; ss << "Max Clip Planes: " << this->maxClipPlanes << endl; ss << "Max Modelview Matrix Stacks: " << this->maxModelViewStacks << endl; ss << "Max Projection Matrix Stacks: " << this->maxProjectionStacks << endl; ss << "Max Attribute Stacks: " << this->maxAttribStacks << endl; ss << "Max Texture Stacks: " << this->maxTextureStacks << endl; ss << endl; ss << "Total Number of Extensions: " << this->extensions.size() << endl; ss << "==============================" << endl; for(unsigned int i = 0; i < this->extensions.size(); ++i) ss << this->extensions.at(i) << endl; ss << "======================================================================" << endl; cout << ss.str() << endl; }
[ [ [ 1, 164 ] ] ]
922b5571311ddb7607132b9dff1c576f5e0095b9
55196303f36aa20da255031a8f115b6af83e7d11
/private/external/gameswf/gameswf/gameswf_avm2.h
4975c5cae9eaba359c3cba1f6342ac014677479d
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
2,879
h
// gameswf_avm2.h -- Vitaly Alexeev <[email protected]> 2008 // This source code has been donated to the Public Domain. Do // whatever you want with it. // AVM2 implementation #ifndef GAMESWF_AVM2_H #define GAMESWF_AVM2_H #include "gameswf/gameswf_function.h" #include "gameswf/gameswf_jit.h" namespace gameswf { struct abc_def; struct option_detail { int m_value; Uint8 m_kind; }; struct traits_info : public ref_counted { enum kind { Trait_Slot = 0, Trait_Method = 1, Trait_Getter = 2, Trait_Setter = 3, Trait_Class = 4, Trait_Function = 5, Trait_Const = 6 }; enum attr { ATTR_Final = 0x1, ATTR_Override = 0x2, ATTR_Metadata = 0x4 }; int m_name; Uint8 m_kind; Uint8 m_attr; // data union { struct { int m_slot_id; int m_type_name; int m_vindex; Uint8 m_vkind; } trait_slot; struct { int m_slot_id; int m_classi; } trait_class; struct { int m_slot_id; int m_function; } trait_function; struct { int m_disp_id; int m_method; } trait_method; }; array<int> m_metadata; void read(stream* in, abc_def* abc); }; struct except_info : public ref_counted { int m_from; int m_to; int m_target; int m_exc_type; int m_var_name; void read(stream* in, abc_def* abc); }; struct as_3_function : public as_function { // Unique id of a gameswf resource enum { m_class_id = AS_3_FUNCTION }; virtual bool is(int class_id) const { if (m_class_id == class_id) return true; else return as_function::is(class_id); } enum flags { NEED_ARGUMENTS = 0x01, NEED_ACTIVATION = 0x02, NEED_REST = 0x04, HAS_OPTIONAL = 0x08, SET_DXNS = 0x40, HAS_PARAM_NAMES = 0x80 }; weak_ptr<as_object> m_target; smart_ptr<abc_def> m_abc; // method_info int m_return_type; array<int> m_param_type; int m_name; Uint8 m_flags; array<option_detail> m_options; int m_method; // index in method_info // body_info int m_max_stack; // this is the index of the highest-numbered local register plus one. int m_local_count; int m_init_scope_depth; int m_max_scope_depth; membuf m_code; array< smart_ptr<except_info> > m_exception; array< smart_ptr<traits_info> > m_trait; jit_function m_compiled_code; as_3_function(abc_def* abc, int method, player* player); ~as_3_function(); // Dispatch. virtual void operator()(const fn_call& fn); void execute(array<as_value>& lregister, array<as_value>& stack, array<as_value>& scope, as_value* result); void compile(); void compile_stack_resize( int count ); void read(stream* in); void read_body(stream* in); }; } #endif
[ "viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587" ]
[ [ [ 1, 163 ] ] ]
5fb7919f977c90afc1c4471b3365e7a86577276a
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-shared/Threading/Condition.h
331b9f91149d9fb7c6522722fcf71034ff327e3b
[]
no_license
miklasiak/projekt
df37fa82cf2d4a91c2073f41609bec8b2f23cf66
064402da950555bf88609e98b7256d4dc0af248a
refs/heads/master
2021-01-01T19:29:49.778109
2008-11-10T17:14:14
2008-11-10T17:14:14
34,016,391
2
0
null
null
null
null
UTF-8
C++
false
false
12,897
h
/* * ArcEmu MMORPG Server * Copyright (C) 2008 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef CONDITION_H #define CONDITION_H #ifdef WIN32 //#include <windows.h> #define MAX_AWAITING_THREADS 10 struct list_entry { HANDLE semaphore; long count; bool notified; }; /*class Condition { public: Condition(Mutex*m) { external_mutex=m; wake_sem=NULL; memset(generations,0,sizeof(generations)); } ~Condition() { for(unsigned int i=0;i<MAX_AWAITING_THREADS;++i) dispose_entry(generations[i]); CloseHandle(wake_sem); } void Signal() { internal_mutex.Acquire(); if(wake_sem) { ReleaseSemaphore(wake_sem,1,NULL); for(unsigned int generation=MAX_AWAITING_THREADS;generation!=0;--generation) { list_entry& entry=generations[generation-1]; if(entry.count) { entry.notified=true; ReleaseSemaphore(entry.semaphore,1,NULL); if(!--entry.count) { dispose_entry(entry); } } } } internal_mutex.Release(); } void Broadcast() { internal_mutex.Acquire(); if(wake_sem) { for(unsigned int generation=MAX_AWAITING_THREADS;generation!=0;--generation) { list_entry& entry=generations[generation-1]; if(entry.count) broadcast_entry(entry); } } internal_mutex.Release(); } bool Wait() { HANDLE local_wake_sem; HANDLE sem; internal_mutex.Acquire(); external_mutex->Release(); if(!wake_sem) { wake_sem=create_anonymous_semaphore(0,LONG_MAX); ASSERT(wake_sem); } local_wake_sem=duplicate_handle(wake_sem); if(generations[0].notified) { shift_generations_down(); } if(!generations[0].semaphore) { generations[0].semaphore=create_anonymous_semaphore(0,LONG_MAX); ASSERT(generations[0].semaphore); } ++generations[0].count; sem=duplicate_handle(generations[0].semaphore); internal_mutex.Release(); ASSERT(WaitForSingleObject(sem,INFINITE)==0); ASSERT(CloseHandle(sem)); WaitForSingleObject(local_wake_sem,0); ASSERT(CloseHandle(local_wake_sem)); external_mutex->Acquire();//Must be acquire but it does not work with it return true; } protected: HANDLE create_anonymous_semaphore(long cur,long max) { SECURITY_ATTRIBUTES attr; attr.nLength=sizeof(SECURITY_ATTRIBUTES); attr.lpSecurityDescriptor=NULL; attr.bInheritHandle=false; return CreateSemaphore(&attr,cur,max,NULL); } static bool no_waiters(list_entry const& entry) { return entry.count==0; } ARCEMU_INLINE void shift_generations_down() { if(std::remove_if(generations,generations+MAX_AWAITING_THREADS,no_waiters)==generations+MAX_AWAITING_THREADS) { broadcast_entry(generations[MAX_AWAITING_THREADS-1]); } std::copy_backward(generations,generations+MAX_AWAITING_THREADS,generations+MAX_AWAITING_THREADS); generations[0].semaphore=0; generations[0].count=0; generations[0].notified=false; } void broadcast_entry(list_entry& entry) { ReleaseSemaphore(wake_sem,entry.count,NULL); ReleaseSemaphore(entry.semaphore,entry.count,NULL); entry.count=0; dispose_entry(entry); } ARCEMU_INLINE void dispose_entry(list_entry& entry) { ASSERT(entry.count==0); if(entry.semaphore) { ASSERT(CloseHandle(entry.semaphore)); } entry.semaphore=0; entry.notified=false; } ARCEMU_INLINE HANDLE duplicate_handle(HANDLE source) { HANDLE const current_process=GetCurrentProcess(); HANDLE new_handle=0; ASSERT(DuplicateHandle( current_process, source,current_process,&new_handle,0,false,DUPLICATE_SAME_ACCESS)) return new_handle; } Mutex internal_mutex; Mutex *external_mutex; list_entry generations[MAX_AWAITING_THREADS]; HANDLE wake_sem; };*/ class Condition { public: ARCEMU_INLINE Condition(Mutex * mutex) : m_nLockCount(0), m_externalMutex(mutex) { ::InitializeCriticalSection(&m_critsecWaitSetProtection); } ~Condition() { ::DeleteCriticalSection(&m_critsecWaitSetProtection); assert(m_deqWaitSet.empty()); } ARCEMU_INLINE void BeginSynchronized() { m_externalMutex->Acquire(); ++m_nLockCount; } ARCEMU_INLINE void EndSynchronized() { assert(LockHeldByCallingThread()); --m_nLockCount; m_externalMutex->Release(); } DWORD Wait(time_t timeout) { DWORD dwMillisecondsTimeout = (DWORD)timeout * 1000; BOOL bAlertable = FALSE; ASSERT(LockHeldByCallingThread()); // Enter a new event handle into the wait set. HANDLE hWaitEvent = Push(); if( NULL == hWaitEvent ) return WAIT_FAILED; // Store the current lock count for re-acquisition. int nThisThreadsLockCount = m_nLockCount; m_nLockCount = 0; // Release the synchronization lock the appropriate number of times. // Win32 allows no error checking here. for( int i=0; i<nThisThreadsLockCount; ++i) { //::LeaveCriticalSection(&m_critsecSynchronized); m_externalMutex->Release(); } // NOTE: Conceptually, releasing the lock and entering the wait // state is done in one atomic step. Technically, that is not // true here, because we first leave the critical section and // then, in a separate line of code, call WaitForSingleObjectEx. // The reason why this code is correct is that our thread is placed // in the wait set *before* the lock is released. Therefore, if // we get preempted right here and another thread notifies us, then // that notification will *not* be missed: the wait operation below // will find the event signalled. // Wait for the event to become signalled. DWORD dwWaitResult = ::WaitForSingleObjectEx( hWaitEvent, dwMillisecondsTimeout, bAlertable ); // If the wait failed, store the last error because it will get // overwritten when acquiring the lock. DWORD dwLastError = 0; if( WAIT_FAILED == dwWaitResult ) dwLastError = ::GetLastError(); // Acquire the synchronization lock the appropriate number of times. // Win32 allows no error checking here. for( int j=0; j<nThisThreadsLockCount; ++j) { //::EnterCriticalSection(&m_critsecSynchronized); m_externalMutex->Acquire(); } // Restore lock count. m_nLockCount = nThisThreadsLockCount; // Close event handle if( ! CloseHandle(hWaitEvent) ) return WAIT_FAILED; if( WAIT_FAILED == dwWaitResult ) ::SetLastError(dwLastError); return dwWaitResult; } DWORD Wait() { DWORD dwMillisecondsTimeout = INFINITE; BOOL bAlertable = FALSE; ASSERT(LockHeldByCallingThread()); // Enter a new event handle into the wait set. HANDLE hWaitEvent = Push(); if( NULL == hWaitEvent ) return WAIT_FAILED; // Store the current lock count for re-acquisition. int nThisThreadsLockCount = m_nLockCount; m_nLockCount = 0; // Release the synchronization lock the appropriate number of times. // Win32 allows no error checking here. for( int i=0; i<nThisThreadsLockCount; ++i) { //::LeaveCriticalSection(&m_critsecSynchronized); m_externalMutex->Release(); } // NOTE: Conceptually, releasing the lock and entering the wait // state is done in one atomic step. Technically, that is not // true here, because we first leave the critical section and // then, in a separate line of code, call WaitForSingleObjectEx. // The reason why this code is correct is that our thread is placed // in the wait set *before* the lock is released. Therefore, if // we get preempted right here and another thread notifies us, then // that notification will *not* be missed: the wait operation below // will find the event signalled. // Wait for the event to become signalled. DWORD dwWaitResult = ::WaitForSingleObjectEx( hWaitEvent, dwMillisecondsTimeout, bAlertable ); // If the wait failed, store the last error because it will get // overwritten when acquiring the lock. DWORD dwLastError = 0; if( WAIT_FAILED == dwWaitResult ) dwLastError = ::GetLastError(); // Acquire the synchronization lock the appropriate number of times. // Win32 allows no error checking here. for( int j=0; j<nThisThreadsLockCount; ++j) { //::EnterCriticalSection(&m_critsecSynchronized); m_externalMutex->Acquire(); } // Restore lock count. m_nLockCount = nThisThreadsLockCount; // Close event handle if( ! CloseHandle(hWaitEvent) ) return WAIT_FAILED; if( WAIT_FAILED == dwWaitResult ) ::SetLastError(dwLastError); return dwWaitResult; } void Signal() { // Pop the first handle, if any, off the wait set. HANDLE hWaitEvent = Pop(); // If there is not thread currently waiting, that's just fine. if(NULL == hWaitEvent) return; // Signal the event. SetEvent(hWaitEvent); } void Broadcast() { // Signal all events on the deque, then clear it. Win32 allows no // error checking on entering and leaving the critical section. // ::EnterCriticalSection(&m_critsecWaitSetProtection); std::deque<HANDLE>::const_iterator it_run = m_deqWaitSet.begin(); std::deque<HANDLE>::const_iterator it_end = m_deqWaitSet.end(); for( ; it_run < it_end; ++it_run ) { if( ! SetEvent(*it_run) ) return; } m_deqWaitSet.clear(); ::LeaveCriticalSection(&m_critsecWaitSetProtection); } private: HANDLE Push() { // Create the new event. HANDLE hWaitEvent = ::CreateEvent( NULL, // no security FALSE, // auto-reset event FALSE, // initially unsignalled NULL // string name ); // if( NULL == hWaitEvent ) { return NULL; } // Push the handle on the deque. ::EnterCriticalSection(&m_critsecWaitSetProtection); m_deqWaitSet.push_back(hWaitEvent); ::LeaveCriticalSection(&m_critsecWaitSetProtection); return hWaitEvent; } HANDLE Pop() { // Pop the first handle off the deque. // ::EnterCriticalSection(&m_critsecWaitSetProtection); HANDLE hWaitEvent = NULL; if( 0 != m_deqWaitSet.size() ) { hWaitEvent = m_deqWaitSet.front(); m_deqWaitSet.pop_front(); } ::LeaveCriticalSection(&m_critsecWaitSetProtection); return hWaitEvent; } BOOL LockHeldByCallingThread() { //BOOL bTryLockResult = ::TryEnterCriticalSection(&m_critsecSynchronized); BOOL bTryLockResult = m_externalMutex->AttemptAcquire(); // If we didn't get the lock, someone else has it. // if( ! bTryLockResult ) { return FALSE; } // If we got the lock, but the lock count is zero, then nobody had it. // if( 0 == m_nLockCount ) { assert( bTryLockResult ); //::LeaveCriticalSection(&m_critsecSynchronized); m_externalMutex->Release(); return FALSE; } // Release lock once. NOTE: we still have it after this release. // Win32 allows no error checking here. assert( bTryLockResult && 0 < m_nLockCount ); //::LeaveCriticalSection(&m_critsecSynchronized); m_externalMutex->Release(); return TRUE; } std::deque<HANDLE> m_deqWaitSet; CRITICAL_SECTION m_critsecWaitSetProtection; Mutex * m_externalMutex; int m_nLockCount; }; #else class Condition { public: ARCEMU_INLINE Condition(Mutex *m) { mut=m; pthread_cond_init(&cond,NULL); } ARCEMU_INLINE ~Condition() { pthread_cond_destroy(&cond); } ARCEMU_INLINE void Signal() { pthread_cond_signal(&cond); } ARCEMU_INLINE void Broadcast() { pthread_cond_broadcast(&cond); } ARCEMU_INLINE void Wait() { pthread_cond_wait(&cond,&mut->mutex); } ARCEMU_INLINE bool Wait(time_t seconds) { timespec tv; tv.tv_nsec = 0; tv.tv_sec = seconds; if(pthread_cond_timedwait(&cond, &mut->mutex, &tv) == 0) return true; else return false; } ARCEMU_INLINE void BeginSynchronized() { mut->Acquire(); } ARCEMU_INLINE void EndSynchronized() { mut->Release(); } private: pthread_cond_t cond; Mutex *mut; }; #endif #endif
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 1 ], [ 4, 153 ], [ 155, 173 ], [ 175, 184 ], [ 186, 207 ], [ 209, 218 ], [ 220, 224 ], [ 226, 478 ], [ 480, 483 ], [ 485, 488 ], [ 490, 492 ], [ 494, 496 ], [ 498, 500 ], [ 502, 510 ], [ 512, 514 ], [ 516, 529 ] ], [ [ 2, 3 ], [ 154, 154 ], [ 174, 174 ], [ 185, 185 ], [ 208, 208 ], [ 219, 219 ], [ 225, 225 ], [ 479, 479 ], [ 484, 484 ], [ 489, 489 ], [ 493, 493 ], [ 497, 497 ], [ 501, 501 ], [ 511, 511 ], [ 515, 515 ] ] ]
21362ef5d112c1a9fb4ada44db0a4cf8f53d812a
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/newton20/engine/ai/src/AiSubsystem.cpp
e5154d7caa0f4eb56a360797d64755cd3601a044
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,780
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #include "stdinc.h" //precompiled header #include "AiSubsystem.h" #include "AiWorld.h" #include "AgentManager.h" #include "CoreMessages.h" #include "CoreSubsystem.h" #include "GameLoop.h" #include "Landmark.h" #include "LandmarkPath.h" #include "Logger.h" #include "WayPointGraphManager.h" #include "World.h" #include <xercesc/util/PlatformUtils.hpp> #include "XmlProcessor.h" #include "XmlResourceManager.h" #include "ContentModule.h" #include "DialogManager.h" using namespace Ogre; using namespace OpenSteer; using namespace XERCES_CPP_NAMESPACE; template<> rl::AiSubsystem* Singleton<rl::AiSubsystem>::ms_Singleton = 0; namespace rl { AiSubsystem::AiSubsystem(void) : mAgentManager(NULL), mWayPointGraphManager(NULL), mWorld(NULL) { LOG_MESSAGE(Logger::AI, "Init Start"); initialize(); LOG_MESSAGE(Logger::AI, "Init Ende"); } AiSubsystem::~AiSubsystem(void) { GameLoop::getSingleton().removeTask(AgentManager::getSingletonPtr()); AgentManager::getSingleton().removeAllAgents(); mWorld->removeAllObstacles(); removeAllLandmarkPaths(); removeAllLandmarks(); delete mDialogManager; delete mAgentManager; delete mWayPointGraphManager; delete mWorld; } void AiSubsystem::initialize() { mAgentManager = new AgentManager(); mWayPointGraphManager = new WayPointGraphManager(); mWorld = new AiWorld(); mDialogManager = new DialogManager(); mSceneLoadedConnection = MessagePump::getSingleton().addMessageHandler<MessageType_SceneLoaded>( boost::bind(&AiSubsystem::onAfterSceneLoaded, this)); mSceneClearingConnection = MessagePump::getSingleton().addMessageHandler<MessageType_SceneClearing>( boost::bind(&AiSubsystem::onBeforeClearScene, this)); GameLoop::getSingleton().addTask(AgentManager::getSingletonPtr(), GameLoop::TG_LOGIC); } bool AiSubsystem::onBeforeClearScene() { AgentManager::getSingleton().removeAllAgents(); mWorld->removeAllObstacles(); return true; } bool AiSubsystem::onAfterSceneLoaded() { // newton world hinzuf�gen Obstacle *newtonWorld = new NewtonWorldAsObstacle; newtonWorld->setSeenFrom(AbstractObstacle::both); mWorld->addObstacle(newtonWorld); return true; } Landmark* AiSubsystem::createLandmark(const Ogre::String& name, const Ogre::Vector3& position) { Landmark* lm = getLandmark(name); if( lm == NULL ) { lm = new Landmark(name, position); mLandmarks[name] = lm; } else { if( lm->getPosition() != position ) { std::ostringstream oss; oss << "A Landmark with the name '" << name << "' already exists at position " << lm->getPosition() << "! The position will not be changed to " << position << "!"; LOG_ERROR(Logger::AI, oss.str()); } } return lm; } Landmark* AiSubsystem::getLandmark(const Ogre::String& name) const { std::map<Ogre::String, Landmark*>::const_iterator it = mLandmarks.find(name); if (it == mLandmarks.end()) { return NULL; } return (*it).second; } LandmarkPath* AiSubsystem::createLandmarkPath(const Ogre::String& name) { LandmarkPath* path = new LandmarkPath(name); mLandmarkPaths[name] = path; return path; } LandmarkPath* AiSubsystem::getLandmarkPath(const Ogre::String& name) const { std::map<Ogre::String, LandmarkPath*>::const_iterator it = mLandmarkPaths.find(name); if (it == mLandmarkPaths.end()) { return NULL; } return (*it).second; } void AiSubsystem::removeAllLandmarkPaths() { for (std::map<Ogre::String, LandmarkPath*>::iterator it = mLandmarkPaths.begin(); it != mLandmarkPaths.end(); it++) { delete (*it).second; } mLandmarkPaths.clear(); } void AiSubsystem::removeAllLandmarks() { for (std::map<Ogre::String, Landmark*>::iterator it = mLandmarks.begin(); it != mLandmarks.end(); it++) { delete (*it).second; } mLandmarks.clear(); } }
[ "melven@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 176 ] ] ]
1dcc3d290fe12ac86706b0da0c494415daea3068
0508304aeb1d50db67a090eecb7436b13f06583d
/nemo/headers/be/interface/CheckBox.h
f918dc89870842fb2f2cfe7744a22d2637954edd
[]
no_license
BackupTheBerlios/nemo
229a7c64901162cf8359f7ddb3a7dd4d05763196
1511021681e9efd91e394191bb00313f0112c628
refs/heads/master
2016-08-03T16:33:46.947041
2004-04-28T01:51:58
2004-04-28T01:51:58
40,045,282
0
0
null
null
null
null
UTF-8
C++
false
false
4,057
h
//------------------------------------------------------------------------------ // Copyright (c) 2001-2002, OpenBeOS // // 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. // // File Name: CheckBox.h // Author: Marc Flerackers ([email protected]) // Description: BCheckBox displays an on/off control. //------------------------------------------------------------------------------ #ifndef _CHECK_BOX_H #define _CHECK_BOX_H // Standard Includes ----------------------------------------------------------- // System Includes ------------------------------------------------------------- #include <BeBuild.h> #include <Control.h> // Project Includes ------------------------------------------------------------ // Local Includes -------------------------------------------------------------- // Local Defines --------------------------------------------------------------- // Globals --------------------------------------------------------------------- // BCheckBox class ------------------------------------------------------------- class BCheckBox : public BControl { public: BCheckBox(BRect frame, const char *name, const char *label, BMessage *message, uint32 resizingMode = B_FOLLOW_LEFT | B_FOLLOW_TOP, uint32 flags = B_WILL_DRAW | B_NAVIGABLE); virtual ~BCheckBox(); /* Archiving */ BCheckBox(BMessage *archive); static BArchivable *Instantiate(BMessage *archive); virtual status_t Archive(BMessage *archive, bool deep = true) const; virtual void Draw(BRect updateRect); virtual void AttachedToWindow(); virtual void MouseDown(BPoint point); virtual void MessageReceived(BMessage *message); virtual void WindowActivated(bool active); virtual void KeyDown(const char *bytes, int32 numBytes); virtual void MouseUp(BPoint point); virtual void MouseMoved(BPoint point, uint32 transit, const BMessage *message); virtual void DetachedFromWindow(); virtual void SetValue(int32 value); virtual void GetPreferredSize(float *width, float *height); virtual void ResizeToPreferred(); virtual status_t Invoke(BMessage *message = NULL); virtual void FrameMoved(BPoint newLocation); virtual void FrameResized(float width, float height); virtual BHandler *ResolveSpecifier(BMessage *message, int32 index, BMessage *specifier, int32 what, const char *property); virtual status_t GetSupportedSuites(BMessage *message); virtual void MakeFocus(bool focused = true); virtual void AllAttached(); virtual void AllDetached(); virtual status_t Perform(perform_code d, void *arg); private: virtual void _ReservedCheckBox1(); virtual void _ReservedCheckBox2(); virtual void _ReservedCheckBox3(); BCheckBox &operator=(const BCheckBox &); bool fOutlined; uint32 _reserved[2]; }; //------------------------------------------------------------------------------ #endif // _CHECK_BOX_H /* * $Log $ * * $Id $ * */
[ "fadi_edward" ]
[ [ [ 1, 111 ] ] ]
81a94b28e56c2e6c39136542edd7c45ea0362d84
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/vector/aux_/front.hpp
fd4ab462b73a14eb244d42e8ed88daa6c01cae45
[]
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,441
hpp
#ifndef BOOST_MPL_LIST_AUX_FRONT_HPP_INCLUDED #define BOOST_MPL_LIST_AUX_FRONT_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-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/vector/aux_/front.hpp,v $ // $Date: 2006/04/17 23:49:48 $ // $Revision: 1.1 $ #include <boost/mpl/front_fwd.hpp> #include <boost/mpl/vector/aux_/at.hpp> #include <boost/mpl/vector/aux_/tag.hpp> #include <boost/mpl/aux_/nttp_decl.hpp> #include <boost/mpl/aux_/config/typeof.hpp> #include <boost/mpl/aux_/config/ctps.hpp> namespace boost { namespace mpl { #if defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES) template<> struct front_impl< aux::vector_tag > { template< typename Vector > struct apply : v_at<Vector,0> { }; }; #else #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) template< BOOST_MPL_AUX_NTTP_DECL(long, n_) > struct front_impl< aux::vector_tag<n_> > { template< typename Vector > struct apply { typedef typename Vector::item0 type; }; }; #endif // BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION #endif // BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES }} #endif // BOOST_MPL_LIST_AUX_FRONT_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 56 ] ] ]
5ab9454b5c0ce785e2b6c9f54d006290b9fda931
d80fdd26f1829d6d52bdbe4797f24e4cf7c5cf47
/Documentation/Fact.h
13725808f95f8e6c18399abc8986e83ca19985d1
[]
no_license
donaldhayes/dredging-analysis
b3f3e649d226b744c89a292e85fd94c444fe18b0
e436acebba4d773092e2a77e1bb9e7e9acdf007a
refs/heads/master
2016-09-11T10:39:48.092747
2010-09-16T19:52:16
2010-09-16T19:52:16
32,275,912
0
0
null
null
null
null
UTF-8
C++
false
false
840
h
/** * @file Fact.h * @author V.Mahesh Babu <[email protected]> * @brief Factorial header file. * Factorial has the necessary declartions to compute the factorial of a number. * * * @date 9/9/2010 * ingroup Headers */ class Factorial { public: /// Saving the job of a compiler by providing default constructor myself. Factorial() {} ; /** @brief Taking user input. Function takes an arguement to which the factorial needs to be found out. @param aNumber Arguement set to a class variable. @return Returns nothing. */ void setNumber( int aNumber ) ; /** @brief Gives result. Makes necessary calculations on the input. Gets the factorial of the number. @return Returns the result. */ int getResult() ; private: int mInputNumber ; };
[ "maheshbabu.vattigunta@c2a4d909-3516-c47f-7d8b-1112ed2e5277" ]
[ [ [ 1, 42 ] ] ]
2274a9fbd8581b49ef4013403a4bc3ad43dcf5bc
035288d85c21cb6494d5f03c1fafb58a31810988
/CS6620 Symmetry/pmvs_base/numeric/mat3.h
291c21b22485a52e8bbb92f447de24e2393e875b
[]
no_license
AySz88/cs6620-symmetry
b0a658186a8876da6de51c5e28a29059fd596f05
f189c56b45973cc7d8cf3e525b00787c86cab094
refs/heads/master
2016-09-10T02:12:57.637244
2009-12-17T23:09:44
2009-12-17T23:09:44
40,057,637
0
0
null
null
null
null
UTF-8
C++
false
false
8,069
h
#ifndef NUMERIC_MAT3_H #define NUMERIC_MAT3_H #include "vec3.h" template <class T> class TMat3 { private: TVec3<T> m_row[3]; public: // Standard constructors // TMat3() { *this = 0.0; } TMat3(const TVec3<T>& r0,const TVec3<T>& r1,const TVec3<T>& r2) { m_row[0]=r0; m_row[1]=r1; m_row[2]=r2; } TMat3(const TMat3& m) { *this = m; } // Descriptive interface // typedef T value_type; typedef TVec3<T> vector_type; typedef TMat3 inverse_type; static int dim() { return 3; } // Access methods // T& operator()(int i, int j) { return m_row[i][j]; } T operator()(int i, int j) const { return m_row[i][j]; } TVec3<T>& operator[](int i) { return m_row[i]; } const TVec3<T>& operator[](int i) const { return m_row[i]; } inline TVec3<T> col(int i) const {return TVec3<T>(m_row[0][i],m_row[1][i],m_row[2][i]);} operator T*() { return m_row[0]; } operator const T*() { return m_row[0]; } operator const T*() const { return m_row[0]; } // Assignment methods // inline TMat3& operator=(const TMat3& m); inline TMat3& operator=(T s); inline TMat3& operator+=(const TMat3& m); inline TMat3& operator-=(const TMat3& m); inline TMat3& operator*=(T s); inline TMat3& operator/=(T s); inline bool operator==(const TMat3& m) const; inline bool operator!=(const TMat3& m) const; // Construction of standard matrices // static TMat3 I(); static TMat3 outer_product(const TVec3<T>& u, const TVec3<T>& v); static TMat3 outer_product(const TVec3<T>& v); TMat3 &diag(T d); TMat3 &ident() { return diag(1.0); } }; //////////////////////////////////////////////////////////////////////// // // Methods definitions // template <class T> inline TMat3<T>& TMat3<T>::operator=(const TMat3<T>& m) { m_row[0] = m[0]; m_row[1] = m[1]; m_row[2] = m[2]; return *this; }; template <class T> inline TMat3<T>& TMat3<T>::operator=(T s) { m_row[0]=s; m_row[1]=s; m_row[2]=s; return *this; }; template <class T> inline TMat3<T>& TMat3<T>::operator+=(const TMat3<T>& m) { m_row[0] += m[0]; m_row[1] += m[1]; m_row[2] += m[2]; return *this; }; template <class T> inline TMat3<T>& TMat3<T>::operator-=(const TMat3<T>& m) { m_row[0] -= m[0]; m_row[1] -= m[1]; m_row[2] -= m[2]; return *this; }; template <class T> inline TMat3<T>& TMat3<T>::operator*=(T s) { m_row[0] *= s; m_row[1] *= s; m_row[2] *= s; return *this; }; template <class T> inline TMat3<T>& TMat3<T>::operator/=(T s) { m_row[0] /= s; m_row[1] /= s; m_row[2] /= s; return *this; }; template <class T> inline bool TMat3<T>::operator==(const TMat3<T>& m) const { if (m_row[0] == m.m_row[0] && m_row[1] == m.m_row[1] && m_row[2] == m.m_row[2]) return true; else return false; }; template <class T> inline bool TMat3<T>::operator!=(const TMat3<T>& m) const { return !(*this == m); }; //////////////////////////////////////////////////////////////////////// // // Operator definitions // template <class T> inline TMat3<T> operator+(const TMat3<T>& n, const TMat3<T>& m) { return TMat3<T>(n[0]+m[0], n[1]+m[1], n[2]+m[2]); }; template <class T> inline TMat3<T> operator-(const TMat3<T>& n, const TMat3<T>& m) { return TMat3<T>(n[0]-m[0], n[1]-m[1], n[2]-m[2]); }; template <class T> inline TMat3<T> operator-(const TMat3<T>& m) { return TMat3<T>(-m[0], -m[1], -m[2]); }; template <class T> inline TMat3<T> operator*(T s, const TMat3<T>& m) { return TMat3<T>(m[0]*s, m[1]*s, m[2]*s); }; template <class T> inline TMat3<T> operator*(const TMat3<T>& m, T s) { return s*m; }; template <class T> inline TMat3<T> operator/(const TMat3<T>& m, T s) { return TMat3<T>(m[0]/s, m[1]/s, m[2]/s); }; template <class T> inline TVec3<T> operator*(const TMat3<T>& m, const TVec3<T>& v) { return TVec3<T>(m[0]*v, m[1]*v, m[2]*v); }; template <class T> inline std::ostream &operator<<(std::ostream &out, const TMat3<T>& M) { return out << M[0] << std::endl << M[1] << std::endl << M[2]; }; template <class T> inline std::istream &operator>>(std::istream &in, TMat3<T>& M) { return in >> M[0] >> M[1] >> M[2]; }; //////////////////////////////////////////////////////////////////////// // // Misc. function definitions // template <class T> TMat3<T> TMat3<T>::I() { return TMat3<T>(TVec3<T>(1,0,0), TVec3<T>(0,1,0), TVec3<T>(0,0,1)); }; template <class T> TMat3<T> &TMat3<T>::diag(T d) { *this = 0.0; m_row[0][0] = m_row[1][1] = m_row[2][2] = d; return *this; }; template <class T> TMat3<T> diag(const TVec3<T>& v) { return TMat3<T>(TVec3<T>(v[0],0,0), TVec3<T>(0,v[1],0), TVec3<T>(0,0,v[2])); }; template <class T> TMat3<T> TMat3<T>::outer_product(const TVec3<T>& v) { TMat3<T> A; T x=v[0], y=v[1], z=v[2]; A(0,0) = x*x; A(0,1) = x*y; A(0,2) = x*z; A(1,0)=A(0,1); A(1,1) = y*y; A(1,2) = y*z; A(2,0)=A(0,2); A(2,1)=A(1,2); A(2,2) = z*z; return A; }; template <class T> TMat3<T> TMat3<T>::outer_product(const TVec3<T>& u, const TVec3<T>& v) { TMat3<T> A; for(int i=0; i<3; i++) for(int j=0; j<3; j++) A(i, j) = u[i]*v[j]; return A; }; template <class T> TMat3<T> operator*(const TMat3<T>& n, const TMat3<T>& m) { TMat3<T> A; for(int i=0;i<3;i++) for(int j=0;j<3;j++) A(i,j) = n[i]*m.col(j); return A; }; template <class T> TMat3<T> adjoint(const TMat3<T>& m) { return TMat3<T>(m[1]^m[2], m[2]^m[0], m[0]^m[1]); }; template <class T> T invert(TMat3<T>& inv, const TMat3<T>& m) { TMat3<T> A = adjoint(m); T d = A[0] * m[0]; if( d==0.0 ) return 0.0; inv = transpose(A) / d; return d; }; template <class T> inline T det(const TMat3<T>& m) { return m[0] * (m[1] ^ m[2]); }; template <class T> inline T trace(const TMat3<T>& m) { return m(0,0) + m(1,1) + m(2,2); }; template <class T> inline TMat3<T> transpose(const TMat3<T>& m) { return TMat3<T>(m.col(0), m.col(1), m.col(2)); }; template <class T> inline TMat3<T> row_extend(const TVec3<T>& v) { return TMat3<T>(v, v, v); }; /* template <class T> inline TMat3<T> rodrigues(TVec3<T> axis, const T theta) { TMat3<T> matrix; const T cost = cos(theta); const T sint = sin(theta); const T cost2 = 1 - cost; const T& wx = axis[0]; const T& wy = axis[1]; const T& wz = axis[2]; matrix[0][0] = cost + wx * wx * cost2; matrix[0][1] = wx * wy * cost2 - wz * sint; matrix[0][2] = wy * sint + wx * wz * cost2; matrix[1][0] = wz * sint + wx * wy * cost2; matrix[1][1] = cost + wy * wy * cost2; matrix[1][2] = -wx * sint + wy * wz * cost2; matrix[2][0] = -wy * sint + wx * wz * cost2; matrix[2][1] = wx * sint + wy * wz * cost2; matrix[2][2] = cost + wz * wz * cost2; return matrix; }; */ template <class T> inline TMat3<T> rodrigues(const TVec3<T>& axis) { const T theta = norm(axis); if (theta == 0) return TMat3<T>::I(); TMat3<T> wx(TVec3<T>(0, -axis[2], axis[1]), TVec3<T>(axis[2], 0, -axis[0]), TVec3<T>(-axis[1], axis[0], 0)); const T a = sin(theta) / theta; const T b = (1 - cos(theta)) / (theta * theta); return TMat3<T>::I() + wx * a + (wx * wx) * b; }; template <class T> inline TVec3<T> irodrigues(const TMat3<T>& rot) { double theta = (trace(rot) - 1) / 2; if (1.0 < theta) theta = 1.0; else if (theta < -1.0) theta = -1.0; theta = acos(theta); const double sint = sin(theta); const double denom = 2 * sint; if (denom == 0.0) return TVec3<T>(); TVec3<T> vec(rot[2][1] - rot[1][2], rot[0][2] - rot[2][0], rot[1][0] - rot[0][1]); return theta / denom * vec; /* vec = theta / denom * vec; const T len = norm(vec); const int inum = (int)floor(len / (2 * M_PI)); */ }; typedef TMat3<double> Mat3; typedef TMat3<float> Mat3f; #endif // MAT3_H
[ [ [ 1, 306 ] ] ]
c8566891b178fc72aea11896f1d01787ee85d20c
21da454a8f032d6ad63ca9460656c1e04440310e
/src/net/worldscale/pimap/client/wscPcWorkingThread.cpp
36827f83eb75ec217b20c8302a127eea3cfd7898
[]
no_license
merezhang/wcpp
d9879ffb103513a6b58560102ec565b9dc5855dd
e22eb48ea2dd9eda5cd437960dd95074774b70b0
refs/heads/master
2021-01-10T06:29:42.908096
2009-08-31T09:20:31
2009-08-31T09:20:31
46,339,619
0
0
null
null
null
null
UTF-8
C++
false
false
2,475
cpp
#include "wscPcWorkingThread.h" #include "wsiPcWorkingContext.h" #include <wcpp/net/wscDatagramSocket.h> #include <wcpp/net/wscInetAddress.h> #include <wcpp/net/wscInetSocketAddress.h> #include "wscPcReceiveThread.h" #include "wscPcTransmitter.h" #include "wscPcEventDispatcher.h" #include "wscPcExchangeBuffer.h" wscPcWorkingThread::wscPcWorkingThread(wsiPcWorkingContext * wc) { m_WorkingContext.Set( wc ); } wscPcWorkingThread::~wscPcWorkingThread(void) { } ws_result wscPcWorkingThread::Run(void) { // get working context ws_ptr< wsiPcWorkingContext > wkContext; m_WorkingContext.Get( &wkContext ); if (!wkContext) return WS_RLT_ILLEGAL_STATE; ws_result rlt(0); // create socket // get address of localhost ws_ptr<wsiInetSocketAddress> sockAddr; ws_ptr<wsiInetAddress> localhost; rlt = wscInetAddress::GetLocalHost( &localhost ); if (rlt != WS_RLT_SUCCESS) return rlt; // create datagram socket ws_ptr<wsiDatagramSocket> sock; rlt = NewObj<wscDatagramSocket>(&sock); if (rlt != WS_RLT_SUCCESS) return rlt; // bind to a port of localhost for (ws_int i=1000 ; i>0 ; i--) { sockAddr.Release(); rlt = NewObj< wscInetSocketAddress >( &sockAddr , localhost , 20000+i ); if (rlt == WS_RLT_SUCCESS) { rlt = sock->Bind( sockAddr ); if (rlt == WS_RLT_SUCCESS) i = 0; } } if (rlt!=WS_RLT_SUCCESS) return rlt; // create exchange buffer ws_ptr<wsiPcExchangeBuffer> exbuf; rlt = NewObj<wscPcExchangeBuffer>( &exbuf ); if (rlt != WS_RLT_SUCCESS) return rlt; // create transmitter ws_ptr<wsiPcTransmitter> trans; rlt = NewObj<wscPcTransmitter>(&trans,wkContext); if (rlt != WS_RLT_SUCCESS) return rlt; // create event dispatcher ws_ptr<wsiPcEventDispatcher> evtDisp; rlt = NewObj<wscPcEventDispatcher>( & evtDisp , wkContext ); if (rlt != WS_RLT_SUCCESS) return rlt; // create receive thread ws_ptr<wsiThread> rcvThd; rlt = NewObj<wscPcReceiveThread>( &rcvThd , wkContext ); if (rlt!=WS_RLT_SUCCESS) return rlt; wkContext->SetDatagramSocket( sock ); wkContext->SetEventDispatcher( evtDisp ); wkContext->SetExchangeBuffer( exbuf ); wkContext->SetTransmitter( trans ); // start receive thread rcvThd->Start(); // join sub thread(s) return rcvThd->Join(); }
[ "xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8" ]
[ [ [ 1, 84 ] ] ]
ed95f07febdd61473ce8e23c3defe0e8ef93119a
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Source/Geometry/WmlEllipse2.cpp
e06eb1f5e89c1d2b64d084a07adce73872208709
[]
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
2,909
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 "WmlEllipse2.h" using namespace Wml; //---------------------------------------------------------------------------- template <class Real> EllipseStandard2<Real>::EllipseStandard2 () { // no initialization for efficiency } //---------------------------------------------------------------------------- template <class Real> Real& EllipseStandard2<Real>::Extent (int i) { return m_afExtent[i]; } //---------------------------------------------------------------------------- template <class Real> const Real& EllipseStandard2<Real>::Extent (int i) const { return m_afExtent[i]; } //---------------------------------------------------------------------------- template <class Real> Real* EllipseStandard2<Real>::Extents () { return m_afExtent; } //---------------------------------------------------------------------------- template <class Real> const Real* EllipseStandard2<Real>::Extents () const { return m_afExtent; } //---------------------------------------------------------------------------- template <class Real> Ellipse2<Real>::Ellipse2 () { // no initialization for efficiency } //---------------------------------------------------------------------------- template <class Real> Vector2<Real>& Ellipse2<Real>::Center () { return m_kCenter; } //---------------------------------------------------------------------------- template <class Real> const Vector2<Real>& Ellipse2<Real>::Center () const { return m_kCenter; } //---------------------------------------------------------------------------- template <class Real> Matrix2<Real>& Ellipse2<Real>::A () { return m_kA; } //---------------------------------------------------------------------------- template <class Real> const Matrix2<Real>& Ellipse2<Real>::A () const { return m_kA; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- namespace Wml { template WML_ITEM class EllipseStandard2<float>; template WML_ITEM class EllipseStandard2<double>; template WML_ITEM class Ellipse2<float>; template WML_ITEM class Ellipse2<double>; template WML_ITEM class EllipseGeneral2<float>; template WML_ITEM class EllipseGeneral2<double>; } //----------------------------------------------------------------------------
[ [ [ 1, 88 ] ] ]
e86e9d31dacfa27482c24a4122b71234d3707e28
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/PatchClient/BetaPatchClientDlg.cpp
0b3def077f5be31b84cfbbd2daf626c26ecb15e3
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
22,899
cpp
// BetaPatchClientDlg.cpp : implementation file // #include "stdafx.h" #include "BetaPatchClient.h" #include "HttpDownload.h" #include "Picture.h" #include "BetaPatchClientDlg.h" #include "PatchManager.h" #include "..\_Common\HwOption.h" #include "DlgOption.h" extern CPatchManager g_PatchManager; CBetaPatchClientDlg *g_pDlg; ///////////////////////////////////////////////////////////////////////////// // CBetaPatchClientDlg dialog CBetaPatchClientDlg::CBetaPatchClientDlg(CWnd* pParent /*=NULL*/) : CDialog(CBetaPatchClientDlg::IDD, pParent) { m_pHttpDownload = NULL; m_nState = STATE_WAIT_PATCHLISTFILE; m_bClose = FALSE; m_pHttpDownload = new CHttpDownload( this ); m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CBetaPatchClientDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CBetaPatchClientDlg) DDX_Control(pDX, IDC_BUTTON_START, m_Button_Start); DDX_Control(pDX, IDC_BUTTON_REGISTER, m_Button_Register); DDX_Control(pDX, IDC_FILEPROGRESS, m_File_Progress); DDX_Control(pDX, IDC_TOTALPROGRESS, m_Total_Progress); DDX_Control(pDX, IDC_FILE_NUMBER, m_Static_FileNumber); DDX_Control(pDX, IDC_DOWN_SPEED, m_Static_DownSpeed); DDX_Control(pDX, IDC_CURRENT_STATE, m_Static_CurrentState); DDX_Control(pDX, IDC_MASQUERADEVERSION, m_Static_MasqueradeVersion); DDX_Control(pDX, IDC_HOME, m_Static_HomeLink); DDX_Control(pDX, IDC_OPTION, m_Button_Option); DDX_Control(pDX, IDC_EXIT, m_Button_Exit); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CBetaPatchClientDlg, CDialog) //{{AFX_MSG_MAP(CBetaPatchClientDlg) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_WM_DESTROY() ON_BN_CLICKED(IDC_EXIT, OnExit) ON_BN_CLICKED(IDC_OPTION, OnOption) ON_WM_NCHITTEST() ON_MESSAGE( WM_HTTPDOWNLOAD_THREAD_FINISHED, OnHttpDownloadThreadFinished ) ON_MESSAGE( WM_HTTPDOWNLOAD_FAIL_TO, OnHttpDownloadFail ) ON_BN_CLICKED(IDC_BUTTON_START, OnButtonStart) ON_BN_CLICKED(IDC_BUTTON_REGISTER, OnButtonRegister) ON_WM_ERASEBKGND() ON_WM_CTLCOLOR() ON_WM_CLOSE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CBetaPatchClientDlg message handlers BOOL CBetaPatchClientDlg::OnEraseBkgnd(CDC* pDC) { m_pic.Render( pDC ); return TRUE; } HBRUSH CBetaPatchClientDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if (CTLCOLOR_STATIC == nCtlColor) { HBITMAP hPic = m_pic.GetBitmap(); if( hPic ) { CRect rtStatic; CRect rtBitmap; pWnd->GetClientRect( rtStatic ); pWnd->GetWindowRect( rtBitmap ); ScreenToClient( rtBitmap ); HDC hMemdc=CreateCompatibleDC( pDC->m_hDC ); HBITMAP hOldBmp=(HBITMAP)SelectObject(hMemdc, hPic ); BitBlt( pDC->m_hDC, 0, 0, rtStatic.Width(), rtStatic.Height(), hMemdc, rtBitmap.left, rtBitmap.top, SRCCOPY ); SelectObject(hMemdc,hOldBmp); DeleteDC(hMemdc); return (HBRUSH)GetStockObject(NULL_BRUSH); } } return hbr; } BOOL CBetaPatchClientDlg::OnInitDialog() { CDialog::OnInitDialog(); #if __CURRENT_LANG == LANG_KOR #ifdef __LINK_PORTAL //무인자 일 경우 홈페이지로 연결 /* CString strCmdLine; strCmdLine.Format("%s", AfxGetApp()->m_lpCmdLine); if(strCmdLine.GetLength() == 0 || strCmdLine == "1") { ::ShellExecute(NULL, "open", LOGIN_LINK, NULL, ".", SW_SHOWNORMAL); OnExit(); return FALSE; } */ // else // AfxMessageBox( strCmdLine ); #endif //__LINK_PORTAL #endif // LANG_KOR SetWindowText("FLYFF"); SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon if( InitControls() == FALSE ) return TRUE; m_pHttpDownload->SetServer( PATCHSEVER_URL ); #if __CURRENT_LANG == LANG_FRA m_Static_CurrentState.SetText( _S(IDS_STR_FRA_SEARCHLIST) ); #else m_Static_CurrentState.SetText("Searching For Patch List"); #endif SetPatchVersionString( PATCH_VERSION ); g_PatchManager.EnqueueFILE( "\\list.txt", false, 0, NULL ); m_nState = STATE_WAIT_PATCHLISTFILE; m_pHttpDownload->BeginDownload( &g_PatchManager ); // for test // m_nState = STATE_WAIT_PATCHLISTFILE; // PostMessage( WM_HTTPDOWNLOAD_THREAD_FINISHED ); return TRUE; // return TRUE unless you set the focus to a control } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CBetaPatchClientDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { #ifdef __LANG_JAP #if 0 //JAPAN 패치 클라이언트 이미지 변경관련 삭제. CPaintDC dc(this); // device context for painting CDC MemDC; if( MemDC.CreateCompatibleDC(&dc) ) { CBitmap *pOldBitmap=(CBitmap*)MemDC.SelectObject(m_bmpchr[1]); BITMAP bm; m_bmpchr[1].GetBitmap( &bm ); dc.BitBlt(20,47+60,bm.bmWidth,bm.bmHeight,&MemDC,0,0 ,SRCPAINT); pOldBitmap=(CBitmap*)MemDC.SelectObject(&m_bmpchr[0]); m_bmpchr[0].GetBitmap( &bm ); dc.BitBlt(20,50+60,bm.bmWidth,bm.bmHeight,&MemDC,0,0,SRCAND); MemDC.SelectObject(pOldBitmap); } #endif #endif // __LANG_JAP CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CBetaPatchClientDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CBetaPatchClientDlg::OnDestroy() { if( m_pHttpDownload ) { delete m_pHttpDownload; m_pHttpDownload = NULL; } CDialog::OnDestroy(); } void CBetaPatchClientDlg::OnOption() { char szPath[MAX_PATH]; sprintf( szPath, "%s\\%s", g_PatchManager.GetCurrentLocalDirectory(), "neuz.ini" ); try { g_Option.Load( szPath ); } catch( ... ) { g_Option.Init(); g_Option.Save( szPath ); return; } CDlgOption dlg; dlg.m_bStartFullScreen = g_Option.m_bStartFullScreen; dlg.m_nResWidth = g_Option.m_nResWidth; dlg.m_nResHeight = g_Option.m_nResHeight; dlg.m_nTexQual = g_Option.m_nTextureQuality; dlg.m_nViewArea = g_Option.m_nViewArea; dlg.m_nObjectDetail = g_Option.m_nObjectDetail; dlg.m_nShadow = g_Option.m_nShadow; if( dlg.DoModal() == IDOK ) { g_Option.m_bStartFullScreen = dlg.m_bStartFullScreen; g_Option.m_nResWidth = dlg.m_nResWidth; g_Option.m_nResHeight = dlg.m_nResHeight; g_Option.m_nTextureQuality = dlg.m_nTexQual; g_Option.m_nViewArea = dlg.m_nViewArea; g_Option.m_nObjectDetail = dlg.m_nObjectDetail; g_Option.m_nShadow = dlg.m_nShadow; g_Option.Save( szPath ); } } void CBetaPatchClientDlg::OnExit() { m_bClose = TRUE; Sleep( 100 ); PostQuitMessage( 0 ); } LRESULT CBetaPatchClientDlg::OnNcHitTest( CPoint point ) { // 캡션바를 누른것 처럼 해주는 것이다. return HTCAPTION; } LRESULT CBetaPatchClientDlg::OnHttpDownloadThreadFinished( WPARAM wParam, LPARAM lParam ) { m_pHttpDownload->WaitForSafeToClose(); switch( m_nState ) { case STATE_WAIT_PATCHLISTFILE: { CWaitCursor cursor; MAKEPATCHLIST_RESULT result = g_PatchManager.MakePatchList( PATCH_VERSION ); switch( result ) { case MAKEPATCHLIST_FILE_NOTFOUND: break; case MAKEPATCHLIST_VERSION_MISMATCH: g_PatchManager.EnqueueFILE( "\\NewFlyff.exe", false, 0, NULL ); m_nState = STATE_OLD_PATCH; m_pHttpDownload->BeginDownload( &g_PatchManager ); break; case MAKEPATCHLIST_OK: if( g_PatchManager.GetListCount() == 0 ) // 패치 할 필요가 없다면 { #if __CURRENT_LANG == LANG_FRA m_Static_CurrentState.SetText( _S(IDS_STR_FRA_PATCHCOMP) ); // 패치 완료 #elif __CURRENT_LANG == LANG_POR m_Static_CurrentState.SetText( _S(IDS_STR_POR_PATCHCOMP) ); // 패치 완료 #else m_Static_CurrentState.SetText( "Patch Completed" ); // 패치 완료 #endif m_Button_Start.ShowWindow( SW_SHOW ); m_Button_Start.SetFocus(); m_File_Progress.SetPos( 100 ); m_Total_Progress.SetPos( 100 ); } else { #if __CURRENT_LANG == LANG_FRA m_Static_CurrentState.SetText( _S(IDS_STR_FRA_RUN) ); // 패치할 파일들 다운로드 시작 #else m_Static_CurrentState.SetText( "Run..." ); // 패치할 파일들 다운로드 시작 #endif m_nState = STATE_SELECTION; m_pHttpDownload->BeginDownload( &g_PatchManager ); } break; } } break; case STATE_SELECTION: m_nState = STATE_PATCH_END; #if __CURRENT_LANG == LANG_FRA m_Static_CurrentState.SetText( _S(IDS_STR_FRA_PATCHCOMP) ); // 패치 완료 #elif __CURRENT_LANG == LANG_POR m_Static_CurrentState.SetText( _S(IDS_STR_POR_PATCHCOMP) ); // 패치 완료 #else m_Static_CurrentState.SetText( "Patch Completed" ); // 패치 완료 #endif m_Button_Start.ShowWindow( SW_SHOW ); m_Button_Start.SetFocus(); m_File_Progress.SetPos( 100 ); m_Total_Progress.SetPos( 100 ); break; case STATE_OLD_PATCH: NewPatchClient(); // 패치 클라이언트가 다운로드 되었으니 updater로 업뎃하자. break; } return 0; } LRESULT CBetaPatchClientDlg::OnHttpDownloadFail( WPARAM wParam, LPARAM lParam ) { m_pHttpDownload->WaitForSafeToClose(); PostQuitMessage( 0 ); return 0; } void CBetaPatchClientDlg::OnButtonStart() { #if __CURRENT_LANG == LANG_KOR #ifdef __LINK_PORTAL //무인자 일 경우 홈페이지로 연결 /* CString strCmdLine; strCmdLine.Format("%s", AfxGetApp()->m_lpCmdLine); if(strCmdLine.GetLength() == 0 || strCmdLine == "1") { ::ShellExecute(NULL, "open", LOGIN_LINK, NULL, ".", SW_SHOWNORMAL); OnExit(); return; } */ // else // AfxMessageBox( strCmdLine ); #endif //__LINK_PORTAL #endif // LANG_KOR if( g_PatchManager.GetListCount() == 0 || m_nState == STATE_PATCH_END ) { CBetaPatchClientApp* pApp = (CBetaPatchClientApp*)AfxGetApp(); pApp->RunClient(); } } void CBetaPatchClientDlg::OnButtonRegister() { #if defined(__LANG_ENG_USA) || defined(__LANG_ENG_USATEST) ::ShellExecute(NULL, "open", "http://user.ffworld.com.cn/register.htm", NULL, ".", SW_SHOWNORMAL); #elif defined(__LANG_GER) ::ShellExecute(NULL, "open", "http://de.gpotato.eu/Account/AccReg.aspx", NULL, ".", SW_SHOWNORMAL); #elif defined(__LANG_FRA) ::ShellExecute(NULL, "open", "http://fr.gpotato.eu/Account/AccReg.aspx", NULL, ".", SW_SHOWNORMAL); #elif defined(__LANG_POR) ::ShellExecute(NULL, "open", "http://register.gpotato.com.br/index.php?m=Register&a=Registration", NULL, ".", SW_SHOWNORMAL); #endif } BOOL CBetaPatchClientDlg::InitControls() { #ifdef __LANG_RUS enum PublisherVersion { PUBLISHER_VERSION_1 = 0, PUBLISHER_VERSION_2 = 1 }; PublisherVersion ePublisherVersion = PUBLISHER_VERSION_1; CScanner scanner; if( scanner.Load( "a.txt" ) == TRUE ) { int nKeyNumber = scanner.GetNumber(); if( nKeyNumber == 1 ) ePublisherVersion = PUBLISHER_VERSION_2; else ePublisherVersion = PUBLISHER_VERSION_1; } else ePublisherVersion = PUBLISHER_VERSION_1; #endif // __LANG_RUS #ifdef __LANG_RUS DWORD dwBitmapID = ( ePublisherVersion == PUBLISHER_VERSION_1 ) ? IDC_BITMAP_MAIN : IDC_BITMAP_MAIN_2; if( m_pic.Load( dwBitmapID ) ) #else // __LANG_RUS if( m_pic.Load( IDC_BITMAP_MAIN ) ) #endif // __LANG_RUS { CSize size = m_pic.GetImageSize(); SetWindowPos( NULL, 0, 0, size.cx, size.cy, SWP_NOZORDER | SWP_NOMOVE ); HRGN hRgn = CreateRoundRectRgn( 0, 0, size.cx, size.cy, 20, 20 ); if( hRgn ) ::SetWindowRgn( m_hWnd, hRgn, FALSE ); } int nInfoGap = 0; int nWeblinkGap = 0; #if defined(__LANG_JAP) #if 0 //JAPAN 패치 클라이언트 이미지 변경관련 삭제. nInfoGap = 5; nWeblinkGap = 35; srand( (unsigned)time( NULL ) ); int nsel = rand()%4; UINT nchrarry[4] = { IDB_BITMAP_CHAR1, IDB_BITMAP_CHAR3, IDB_BITMAP_CHAR5, IDB_BITMAP_CHAR7 }; UINT nchrarryM[4] = { IDB_BITMAP_CHAR2, IDB_BITMAP_CHAR4, IDB_BITMAP_CHAR6, IDB_BITMAP_CHAR8 }; m_bmpchr[0].LoadBitmap( nchrarry[nsel] ); m_bmpchr[1].LoadBitmap( nchrarryM[nsel] ); #endif #endif // __LANG_JAP m_Button_Exit.SetBitmaps(IDB_BITMAP_CLOSE00, RGB(255, 0, 255), IDB_BITMAP_CLOSE01, RGB(255, 0, 255) ); m_Button_Exit.SetAlign(CButtonST::ST_ALIGN_OVERLAP, FALSE); m_Button_Exit.SetPressedStyle(CButtonST::BTNST_PRESSED_LEFTRIGHT, FALSE); m_Button_Exit.SetColor(CButtonST::BTNST_COLOR_FG_IN, RGB(0, 0, 0)); m_Button_Exit.SetColor(CButtonST::BTNST_COLOR_FG_OUT, RGB(0, 0, 0)); m_Button_Exit.SizeToContent(); m_Button_Exit.DrawTransparent(TRUE); m_Button_Exit.DrawBorder(FALSE, FALSE); m_Button_Exit.SetBtnCursor(IDC_CURSOR1); m_Button_Option.SetBitmaps(IDB_BITMAP_OPTION00, RGB(255, 0, 255), IDB_BITMAP_OPTION01, RGB(255, 0, 255) ); m_Button_Option.SetAlign(CButtonST::ST_ALIGN_OVERLAP, FALSE); m_Button_Option.SetPressedStyle(CButtonST::BTNST_PRESSED_LEFTRIGHT, FALSE); m_Button_Option.SetColor(CButtonST::BTNST_COLOR_FG_IN, RGB(0, 0, 0)); m_Button_Option.SetColor(CButtonST::BTNST_COLOR_FG_OUT, RGB(0, 0, 0)); m_Button_Option.SizeToContent(); m_Button_Option.DrawTransparent(TRUE); m_Button_Option.DrawBorder(FALSE, FALSE); m_Button_Option.SetBtnCursor(IDC_CURSOR1); m_Button_Start.SetBitmaps(IDB_BITMAP_START00, RGB(255, 0, 255), IDB_BITMAP_START01, RGB(255, 0, 255) ); m_Button_Start.SetAlign(CButtonST::ST_ALIGN_OVERLAP, FALSE); m_Button_Start.SetPressedStyle(CButtonST::BTNST_PRESSED_LEFTRIGHT, FALSE); m_Button_Start.SetColor(CButtonST::BTNST_COLOR_FG_IN, RGB(0, 0, 0)); m_Button_Start.SetColor(CButtonST::BTNST_COLOR_FG_OUT, RGB(0, 0, 0)); m_Button_Start.SizeToContent(); m_Button_Start.DrawTransparent(TRUE); m_Button_Start.DrawBorder(FALSE, FALSE); m_Button_Start.SetBtnCursor(IDC_CURSOR1); m_Button_Register.SetBitmaps(IDB_BITMAP_REGISTER00, RGB(255, 0, 255), IDB_BITMAP_REGISTER01, RGB(255, 0, 255) ); m_Button_Register.SetAlign(CButtonST::ST_ALIGN_OVERLAP, FALSE); m_Button_Register.SetPressedStyle(CButtonST::BTNST_PRESSED_LEFTRIGHT, FALSE); m_Button_Register.SetColor(CButtonST::BTNST_COLOR_FG_IN, RGB(0, 0, 0)); m_Button_Register.SetColor(CButtonST::BTNST_COLOR_FG_OUT, RGB(0, 0, 0)); m_Button_Register.SizeToContent(); m_Button_Register.DrawTransparent(TRUE); m_Button_Register.DrawBorder(FALSE, FALSE); m_Button_Register.SetBtnCursor(IDC_CURSOR1); #if defined(__LANG_ENG_USA) || defined(__LANG_ENG_USATEST) || defined(__LANG_GER) || defined(__LANG_FRA) || defined(__LANG_POR) m_Button_Register.ShowWindow(SW_SHOW); #else m_Button_Register.ShowWindow(SW_HIDE); #endif // static //#if defined(__LANG_THAI) //Background Image 교체로 Font Color 변경 COLORREF cr = RGB( 0,0,0 ); m_Static_CurrentState.SetTextColor( cr ); m_Static_CurrentState.SetFontBold(true); m_Static_DownSpeed.SetTextColor( cr ); m_Static_FileNumber.SetTextColor( cr ); m_Static_MasqueradeVersion.SetTextColor( cr ); m_Static_MasqueradeVersion.SetFontBold(true); //#endif /*#if (__CURRENT_LANG == LANG_ENG || __CURRENT_LANG == LANG_GER || __CURRENT_LANG == LANG_FRA )//|| __CURRENT_CNTRY == CNTRY_TWN) #if __VER == 12 COLORREF cr = RGB( 255, 255, 255 ); m_Static_CurrentState.SetTextColor( cr ); m_Static_DownSpeed.SetTextColor( cr ); m_Static_FileNumber.SetTextColor( cr ); m_Static_MasqueradeVersion.SetTextColor( cr ); #endif #endif*/ #ifdef __HANGAME0307 // 한게임 대응 버젼 TCHAR* szText = HOME_LINK; TCHAR* szURL = HOME_LINK; TCHAR* szWebURL = WEB_FIRST_PAGE; if( AfxGetApp()->m_lpCmdLine[0] != '\0' && memcmp( AfxGetApp()->m_lpCmdLine, "hangame.co.jp", 13 ) == 0 ) { szText = "http://www.hangame.co.jp"; szURL = "http://www.hangame.co.jp/game.asp?fo"; szWebURL = "http://www.flyff.jp/in_client/info/list.asp?domain=hangame.co.jp"; } #else // 일반버젼 #ifdef __LANG_RUS TCHAR* szText = ( ePublisherVersion == PUBLISHER_VERSION_1 ) ? HOME_LINK : HOME_LINK_2; TCHAR* szURL = ( ePublisherVersion == PUBLISHER_VERSION_1 ) ? HOME_LINK : HOME_LINK_2; TCHAR* szWebURL = ( ePublisherVersion == PUBLISHER_VERSION_1 ) ? WEB_FIRST_PAGE : WEB_FIRST_PAGE_2; #else // __LANG_RUS TCHAR* szText = HOME_LINK; TCHAR* szURL = HOME_LINK; TCHAR* szWebURL = WEB_FIRST_PAGE; #endif // __LANG_RUS #endif // __HANGAME0307 #if __CURRENT_LANG == LANG_KOR #ifdef __LINK_PORTAL // 한국 : 엔젤, 버디 포탈 링크 연결 TCHAR szArg1[64] = {0, }; TCHAR szArg2[64] = {0, }; _stscanf( AfxGetApp()->m_lpCmdLine, "%s %s", szArg1, szArg2 ); // AfxMessageBox( AfxGetApp()->m_lpCmdLine ); CString strCmdLine; strCmdLine.Format("%s", szArg2); int nLength = strCmdLine.GetLength(); if(nLength > 4) { CString strCmpWord = strCmdLine.Mid(nLength-4, nLength); if(strCmpWord == "__an") { szText = "http://af.gameangel.com"; szURL = "http://af.gameangel.com"; } else if(strCmpWord == "__bu") { szText = "http://flyff.buddybuddy.co.kr"; szURL = "http://flyff.buddybuddy.co.kr"; } } #endif //__LINK_PORTAL #endif // LANG_KOR // 홈페이지 링크 m_Static_HomeLink.SetWindowText( szText ); /*#if __CURRENT_CNTRY == CNTRY_HK m_Static_HomeLink.SetWindowPos( NULL, 300, 22+nWeblinkGap, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOREDRAW ); #else*/ m_Static_HomeLink.SetWindowPos( NULL, 280, 242+nWeblinkGap, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_NOREDRAW ); //#endif #if __CURRENT_LANG == LANG_THA m_Static_HomeLink.SetColours( RGB( 190, 30, 20 ), RGB( 240, 130, 180), RGB( 112, 147, 219 ) ); #elif __CURRENT_LANG == LANG_RUS m_Static_HomeLink.SetColours( RGB( 255, 255, 255 ), RGB( 255, 0, 0 ), RGB( 0, 130, 0 ) ); #elif __CURRENT_LANG == LANG_GER m_Static_HomeLink.SetColours( RGB( 193, 177, 160 ), RGB( 255, 0, 0 ), RGB( 255, 0, 0 ) ); #elif __CURRENT_LANG == LANG_ENG // ascension m_Static_HomeLink.SetColours( RGB( 255, 255, 255 ), RGB( 0, 0, 255 ), RGB( 0, 0, 255 ) ); #elif __CURRENT_LANG == LANG_FRA m_Static_HomeLink.SetColours( RGB( 193, 177, 160 ), RGB( 255, 0, 0 ), RGB( 255, 0, 0 ) ); #elif __CURRENT_LANG == LANG_POR m_Static_HomeLink.SetColours( RGB( 255, 255, 255 ), RGB( 255, 0, 0 ), RGB( 255, 0, 0 ) ); #else m_Static_HomeLink.SetColours( RGB( 0, 0, 0), RGB( 255, 0, 0), RGB( 0, 130, 0 ) ); #endif m_Static_HomeLink.SetURL( szURL ); m_Static_HomeLink.SetUnderline( CHyperLink::ulAlways ); #ifdef __LANG_JAP //JAPAN 패치 클라이언트 이미지 변경관련 삭제. m_Static_HomeLink.EnableWindow(FALSE); m_Static_HomeLink.ShowWindow(FALSE); #endif //__LANG_JAP // Progress 초기화 m_File_Progress.SetPos(0); m_Total_Progress.SetPos(0); CreateWebControl( szWebURL ); GetDlgItem( IDC_BUTTON_START )->MoveWindow( 25, 465, 100, 20 ); GetDlgItem( IDC_BUTTON_REGISTER )->MoveWindow( 145, 465, 100, 20 ); GetDlgItem( IDC_OPTION )->MoveWindow( 250, 465, 100, 20 ); GetDlgItem( IDC_EXIT )->MoveWindow( 355, 465, 100, 20 ); GetDlgItem( IDC_CURRENT_STATE)->MoveWindow( 25, 495, 170, 20 ); GetDlgItem( IDC_DOWN_SPEED)->MoveWindow( 200, 495, 100, 20 ); GetDlgItem( IDC_FILE_NUMBER)->MoveWindow( 350, 495, 100, 20 ); GetDlgItem( IDC_FILEPROGRESS )->MoveWindow( 25, 515, 430, 20 ); GetDlgItem( IDC_TOTALPROGRESS)->MoveWindow( 25, 540, 430, 20 ); GetDlgItem( IDC_MASQUERADEVERSION)->MoveWindow( 200, 570-nInfoGap, 200, 20 ); return TRUE; } void CBetaPatchClientDlg::NewPatchClient() { STARTUPINFO si; memset( &si, 0, sizeof( STARTUPINFO ) ); si.cb = sizeof( STARTUPINFO ); PROCESS_INFORMATION pi; // 패치 클라이언트 재 실행 #if __CURRENT_LANG == LANG_KOR #ifdef __LINK_PORTAL CString strUpdater; strUpdater.Format("Updater.exe myunglang %s", AfxGetApp()->m_lpCmdLine); // AfxMessageBox(strUpdater); if( FALSE == CreateProcess( NULL, strUpdater.GetBuffer(0), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ) ) #else //__LINK_PORTAL if( FALSE == CreateProcess( NULL, "Updater.exe myunglang", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ) ) #endif //__LINK_PORTAL #else //__LANG_KOR if( FALSE == CreateProcess( NULL, "Updater.exe myunglang", NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ) ) #endif //__LANG_KOR { DeleteFile( "NewFlyff.exe.gz"); DeleteFile( "NewFlyff.exe"); AfxMessageBox( "Updater.exe file not found" ); PostQuitMessage( 0 ); return; } HWND hUpdater = NULL; while( hUpdater == NULL ) { Sleep( 100 ); hUpdater = ::FindWindow( "Aeonsoft", "Updater" ); } pi.dwProcessId = ::GetCurrentProcessId(); if( IDOK == AfxMessageBox(IDS_UPDATE_PATCH) ) ::SendMessage( hUpdater, SEND_PROCESSID, ( WPARAM )pi.dwProcessId, 0 ); PostQuitMessage( 0 ); } void CBetaPatchClientDlg::SetPatchVersionString( int nVersion ) { char szBuffer[256]; sprintf( szBuffer, "령령各썹 %.1f %s", nVersion/10.0f, VERSION_NAME ); m_Static_MasqueradeVersion.SetText( szBuffer ); } void CBetaPatchClientDlg::CreateWebControl( LPCTSTR szURL ) { // AFX_IDW_PANE_FIRST is a safe but arbitrary ID #ifdef __LANG_JAP //JAPAN 패치 클라이언트 이미지 변경관련 웹 크기 조절. if (!m_wndBrowser.CreateControl(CLSID_WebBrowser, "", WS_VISIBLE | WS_CHILD, CRect(14, 14, 466, 447), this, AFX_IDW_PANE_FIRST)) #else //__LANG_JAP #if __CURRENT_LANG == LANG_KOR //공지사항 크기 확장 관련 조정. if (!m_wndBrowser.CreateControl(CLSID_WebBrowser, "", WS_VISIBLE | WS_CHILD, CRect(26, 190, 452, 447), this, AFX_IDW_PANE_FIRST)) #else //LANG_KOR if (!m_wndBrowser.CreateControl(CLSID_WebBrowser, "", WS_VISIBLE | WS_CHILD, CRect(26, 263, 452, 447), this, AFX_IDW_PANE_FIRST)) #endif //LANG_KOR #endif //__LANG_JAP { return; } IWebBrowser2* pBrowser; LPUNKNOWN lpUnk = m_wndBrowser.GetControlUnknown(); HRESULT hr = lpUnk->QueryInterface(IID_IWebBrowser2, (void**) &pBrowser); if (SUCCEEDED(hr)) { CString strURL( szURL ); BSTR bstrURL = strURL.AllocSysString(); COleSafeArray vPostData; LPCTSTR lpszTargetFrameName = NULL; LPCTSTR lpszHeaders = NULL; pBrowser->Navigate(bstrURL, COleVariant((long) 0, VT_I4), COleVariant(lpszTargetFrameName, VT_BSTR), vPostData, COleVariant(lpszHeaders, VT_BSTR)); } }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 707 ] ] ]
39acac8876c58c8417ed1cd27d852dbee7be1b57
12ea67a9bd20cbeed3ed839e036187e3d5437504
/winxgui/Tools/Dev/mk/mk.cpp
9e05bae9993e41bb66a7236fcd8c9b7d783b53cd
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
GB18030
C++
false
false
3,386
cpp
// ------------------------------------------------------------------------- // 文件名 : mk.cpp // 创建者 : 许式伟 // 创建时间 : 2002-1-24 16:38:34 // 功能描述 : // // ------------------------------------------------------------------------- #define _ENABLE_TRACE #include "stdafx.h" #undef __Linked_KSCommon #include "ksx_common.h" #include "ks_dir.h" #include "ks_fileutils.h" #include <stdlib.h> // ------------------------------------------------------------------------- enum KEnumSwitchs { switchClean = 0x0001, switchRelease = 0x0002, switchListCfg = 0x0004, switchForceLink = 0x0008, }; // -c clean // -r release // -l listcfg // -f force to link TCHAR g_sws[] = _T("crlfh?"); // ------------------------------------------------------------------------- const TCHAR g_szExtMak[] = _T(".temp.mak"); const TCHAR g_szExtPrj[] = _T(".prj"); int main(int argc, char* argv[]) { static TCHAR command[2048]; static TCHAR szMakeFile[_MAX_PATH]; static TCHAR szPrjFile[_MAX_PATH]; static TCHAR szCurDir[_MAX_PATH]; static TCHAR szProjPath[_MAX_PATH]; static TCHAR szProjName[_MAX_FNAME]; SWITCHS sw; LPCTSTR szCfg; LPTSTR pszMakeFileName; ksGetCwd(szCurDir, _MAX_PATH); TRACE("CurDir = %s\n", szCurDir); // 1). analyze switchs argc = AnalyzeSwitch(++argv, argc-1, &sw, g_sws); if (sw & switchUnknown) { goto lzPrompt; } // 2). get prjfile specified if (argc < 1) { if ( GenDefaultFile(szPrjFile, szCurDir, g_szExtPrj) != S_OK || !IsFileExist2(szPrjFile) ) { lzPrompt: puts( "Function: to make a project by Prjfile\n" "Usage: mk [-c -r -f] Prjfile[.prj] Config\n" " -c to clean & build, that is, to rebuild\n" " -r set $(CFG)=Release, if Config is not specified\n" " -f force to link\n" ); return -1; } } else { _tcscpy(szPrjFile, argv[0]); } TRACE("PrjFile = %s\n", szPrjFile); // 3). get config-request: if (argc > 1) szCfg = argv[1]; else if (sw & switchListCfg) szCfg = _T("-l"); else if (sw & switchRelease) szCfg = _T("Release"); else szCfg = _T("Debug"); // 4). call MakeGen(mg) to generate makefile ForceExt(szMakeFile, szPrjFile, g_szExtMak); TRACE("MakeFile = %s\n", szMakeFile); _stprintf(command, _T("mg %s %s %s"), szPrjFile, szMakeFile, szCfg); system(command); // 5). make // 5.1) set current dir to be makefile's path! MergePath(szProjPath, szCurDir, szMakeFile); TRACE("MakeFileAbs = %s\n", szProjPath); pszMakeFileName = _tcsrchr(szProjPath, '/'); *pszMakeFileName++ = 0; TRACE("ProjPath = %s, MakeFileName = %s\n", szProjPath, pszMakeFileName); ksChDir(szProjPath); // 5.2) make it! LPCTSTR szForceLink = sw & switchForceLink ? _T(" ForceLink=1") : _T(""); LPCTSTR szBuild = sw & switchClean ? _T("clean all") : _T(""); UINT iFind = _tcschr(pszMakeFileName, '.') - pszMakeFileName; _tcsncpy(szProjName, pszMakeFileName, iFind); szProjName[iFind] = 0; _stprintf(command, _T("make -f %s %s%s PROJ=%s"), pszMakeFileName, szBuild, szForceLink, szProjName); TRACE("%s\n", command); system(command); remove(pszMakeFileName); // 5.3). restore current dir! ksChDir(szCurDir); return 0; } // -------------------------------------------------------------------------
[ "[email protected]@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 125 ] ] ]
170b16edad621e9a86bf5f14131ad1e99ef28636
997e067ab6b591e93e3968ae1852003089dca848
/src/game/server/entities/drager.hpp
259b37eb41ea24fe946323e131e6baa9b574bece
[ "LicenseRef-scancode-other-permissive", "Zlib" ]
permissive
floff/ddracemax_old
06cbe9f60e7cef66e58b40c5f586921a1c881ff3
f1356177c49a3bc20632df9a84a51bc491c37f7d
refs/heads/master
2016-09-05T11:59:55.623581
2011-01-14T04:58:25
2011-01-14T04:58:25
777,555
1
0
null
null
null
null
UTF-8
C++
false
false
482
hpp
/* copyright (c) 2007 magnus auvinen, see licence.txt for more info */ #ifndef GAME_SERVER_ENTITY_DRAGER_H #define GAME_SERVER_ENTITY_DRAGER_H #include <game/server/entity.hpp> class CHARACTER; class DRAGER : public ENTITY { float strength; int eval_tick; void move(); void drag(); CHARACTER *target; public: DRAGER(vec2 pos, float strength); virtual void reset(); virtual void tick(); virtual void snap(int snapping_client); }; #endif
[ [ [ 1, 27 ] ] ]
55e1e25f9e591507809f39703aa3936bd86d5478
a5cbc2c1c12b3df161d9028791c8180838fbf2fb
/Heimdall/heimdall/source/DumpPartPitFilePacket.h
29025c23b1742b2f331a0bb6047d0b4841fb104c
[ "MIT" ]
permissive
atinm/Heimdall
e8659fe869172baceb590bc445f383d8bcb72b82
692cda38c99834384c4f0c7687c209f432300993
refs/heads/master
2020-03-27T12:29:58.609089
2010-12-03T19:25:19
2010-12-03T19:25:19
1,136,137
2
0
null
null
null
null
UTF-8
C++
false
false
1,725
h
/* Copyright (c) 2010 Benjamin Dobell, Glass Echidna Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #ifndef DUMPPARTPITFILEPACKET_H #define DUMPPARTPITFILEPACKET_H // Heimdall #include "PitFilePacket.h" namespace Heimdall { class DumpPartPitFilePacket : public PitFilePacket { private: unsigned int partIndex; public: DumpPartPitFilePacket(unsigned int partIndex) : PitFilePacket(PitFilePacket::kRequestPart) { this->partIndex = partIndex; } unsigned int GetPartIndex(void) const { return (partIndex); } void Pack(void) { PitFilePacket::Pack(); PackInteger(PitFilePacket::kDataSize, partIndex); } }; } #endif
[ [ [ 1, 56 ] ] ]
60827e93ce64080ad24b554ce8981f4e7b05a2dc
22d9640edca14b31280fae414f188739a82733e4
/Code/VTK/include/vtk-5.2/vtkMath.h
f84cce93bdb83d714ad0a6f757cd5f3e00e6a64e
[]
no_license
tack1/Casam
ad0a98febdb566c411adfe6983fcf63442b5eed5
3914de9d34c830d4a23a785768579bea80342f41
refs/heads/master
2020-04-06T03:45:40.734355
2009-06-10T14:54:07
2009-06-10T14:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
38,328
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkMath.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. ========================================================================= Copyright 2007 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive license for use of this work by or on behalf of the U.S. Government. Redistribution and use in source and binary forms, with or without modification, are permitted provided that this Notice and any statement of authorship are reproduced on all copies. Contact: [email protected],[email protected] =========================================================================*/ // .NAME vtkMath - performs common math operations // .SECTION Description // vtkMath provides methods to perform common math operations. These // include providing constants such as Pi; conversion from degrees to // radians; vector operations such as dot and cross products and vector // norm; matrix determinant for 2x2 and 3x3 matrices; univariate polynomial // solvers; and random number generation. #ifndef __vtkMath_h #define __vtkMath_h #include "vtkObject.h" #ifndef DBL_EPSILON # define VTK_DBL_EPSILON 2.2204460492503131e-16 #else // DBL_EPSILON # define VTK_DBL_EPSILON DBL_EPSILON #endif // DBL_EPSILON class vtkDataArray; class VTK_COMMON_EXPORT vtkMath : public vtkObject { public: static vtkMath *New(); vtkTypeRevisionMacro(vtkMath,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Useful constants. static float Pi() {return 3.14159265358979f;}; static float DegreesToRadians() {return 0.017453292f;}; static float RadiansToDegrees() {return 57.2957795131f;}; // Description: // Useful constants. (double-precision version) static double DoubleDegreesToRadians() {return 0.017453292519943295;}; static double DoublePi() {return 3.1415926535897932384626;}; static double DoubleRadiansToDegrees() {return 57.29577951308232;}; // Description: // Rounds a float to the nearest integer. static int Round(float f) { return static_cast<int>(f + (f >= 0 ? 0.5 : -0.5)); } static int Round(double f) { return static_cast<int>(f + (f >= 0 ? 0.5 : -0.5)); } static int Floor(double x); // Description: // Compute N factorial, N! = N*(N-1)*(N-2)...*3*2*1. // 0! is taken to be 1. static vtkTypeInt64 Factorial( int N ); // Description: // The number of combinations of n objects from a pool of m objects (m>n). // This is commonly known as "m choose n" and sometimes denoted \f$_mC_n\f$ // or \f$\left(\begin{array}{c}m \\ n\end{array}\right)\f$. static vtkTypeInt64 Binomial( int m, int n ); // Description: // Start iterating over "m choose n" objects. // This function returns an array of n integers, each from 0 to m-1. // These integers represent the n items chosen from the set [0,m[. // // You are responsible for calling vtkMath::FreeCombination() once the iterator is no longer needed. // // Warning: this gets large very quickly, especially when n nears m/2! // (Hint: think of Pascal's triangle.) static int* BeginCombination( int m, int n ); // Description: // Given \a m, \a n, and a valid \a combination of \a n integers in // the range [0,m[, this function alters the integers into the next // combination in a sequence of all combinations of \a n items from // a pool of \a m. // // If the \a combination is the last item in the sequence on input, // then \a combination is unaltered and 0 is returned. // Otherwise, 1 is returned and \a combination is updated. static int NextCombination( int m, int n, int* combination ); // Description: // Free the "iterator" array created by vtkMath::BeginCombination. static void FreeCombination( int* combination); // Description: // Dot product of two 3-vectors (float version). static float Dot(const float x[3], const float y[3]) { return (x[0]*y[0] + x[1]*y[1] + x[2]*y[2]);}; // Description: // Dot product of two 3-vectors (double-precision version). static double Dot(const double x[3], const double y[3]) { return (x[0]*y[0] + x[1]*y[1] + x[2]*y[2]);}; // Description: // Outer product of two 3-vectors (float version). static void Outer(const float x[3], const float y[3], float A[3][3]) { for (int i=0; i < 3; i++) for (int j=0; j < 3; j++) A[i][j] = x[i]*y[j]; } // Description: // Outer product of two 3-vectors (double-precision version). static void Outer(const double x[3], const double y[3], double A[3][3]) { for (int i=0; i < 3; i++) for (int j=0; j < 3; j++) A[i][j] = x[i]*y[j]; } // Description: // Cross product of two 3-vectors. Result vector in z[3]. static void Cross(const float x[3], const float y[3], float z[3]); // Description: // Cross product of two 3-vectors. Result vector in z[3]. (double-precision // version) static void Cross(const double x[3], const double y[3], double z[3]); // Description: // Compute the norm of n-vector. static float Norm(const float* x, int n); static double Norm(const double* x, int n); // Description: // Compute the norm of 3-vector. static float Norm(const float x[3]) { return static_cast<float> (sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]));}; // Description: // Compute the norm of 3-vector (double-precision version). static double Norm(const double x[3]) { return sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);}; // Description: // Normalize (in place) a 3-vector. Returns norm of vector. static float Normalize(float x[3]); // Description: // Normalize (in place) a 3-vector. Returns norm of vector // (double-precision version). static double Normalize(double x[3]); // Description: // Given a unit vector x, find two unit vectors y and z such that // x cross y = z (i.e. the vectors are perpendicular to each other). // There is an infinite number of such vectors, specify an angle theta // to choose one set. If you want only one perpendicular vector, // specify NULL for z. static void Perpendiculars(const double x[3], double y[3], double z[3], double theta); static void Perpendiculars(const float x[3], float y[3], float z[3], double theta); // Description: // Compute distance squared between two points. static float Distance2BetweenPoints(const float x[3], const float y[3]); // Description: // Compute distance squared between two points (double precision version). static double Distance2BetweenPoints(const double x[3], const double y[3]); // Description: // Dot product of two 2-vectors. The third (z) component is ignored. static float Dot2D(const float x[3], const float y[3]) { return (x[0]*y[0] + x[1]*y[1]);}; // Description: // Dot product of two 2-vectors. The third (z) component is // ignored (double-precision version). static double Dot2D(const double x[3], const double y[3]) { return (x[0]*y[0] + x[1]*y[1]);}; // Description: // Outer product of two 2-vectors (float version). z-comp is ignored static void Outer2D(const float x[3], const float y[3], float A[3][3]) { for (int i=0; i < 2; i++) for (int j=0; j < 2; j++) A[i][j] = x[i]*y[j]; } // Description: // Outer product of two 2-vectors (float version). z-comp is ignored static void Outer2D(const double x[3], const double y[3], double A[3][3]) { for (int i=0; i < 2; i++) for (int j=0; j < 2; j++) A[i][j] = x[i]*y[j]; } // Description: // Compute the norm of a 2-vector. Ignores z-component. static float Norm2D(const float x[3]) { return static_cast<float> (sqrt(x[0]*x[0] + x[1]*x[1]));}; // Description: // Compute the norm of a 2-vector. Ignores z-component // (double-precision version). static double Norm2D(const double x[3]) { return sqrt(x[0]*x[0] + x[1]*x[1]);}; // Description: // Normalize (in place) a 2-vector. Returns norm of vector. Ignores // z-component. static float Normalize2D(float x[3]); // Description: // Normalize (in place) a 2-vector. Returns norm of vector. Ignores // z-component (double-precision version). static double Normalize2D(double x[3]); // Description: // Compute determinant of 2x2 matrix. Two columns of matrix are input. static float Determinant2x2(const float c1[2], const float c2[2]) { return (c1[0]*c2[1] - c2[0]*c1[1]);}; // Description: // Calculate the determinant of a 2x2 matrix: | a b | | c d | static double Determinant2x2(double a, double b, double c, double d) { return (a * d - b * c);}; static double Determinant2x2(const double c1[2], const double c2[2]) { return (c1[0]*c2[1] - c2[0]*c1[1]);}; // Description: // LU Factorization of a 3x3 matrix. The diagonal elements are the // multiplicative inverse of those in the standard LU factorization. static void LUFactor3x3(float A[3][3], int index[3]); static void LUFactor3x3(double A[3][3], int index[3]); // Description: // LU back substitution for a 3x3 matrix. The diagonal elements are the // multiplicative inverse of those in the standard LU factorization. static void LUSolve3x3(const float A[3][3], const int index[3], float x[3]); static void LUSolve3x3(const double A[3][3], const int index[3], double x[3]); // Description: // Solve Ay = x for y and place the result in y. The matrix A is // destroyed in the process. static void LinearSolve3x3(const float A[3][3], const float x[3], float y[3]); static void LinearSolve3x3(const double A[3][3], const double x[3], double y[3]); // Description: // Multiply a vector by a 3x3 matrix. The result is placed in out. static void Multiply3x3(const float A[3][3], const float in[3], float out[3]); static void Multiply3x3(const double A[3][3], const double in[3], double out[3]); // Description: // Multiply one 3x3 matrix by another according to C = AB. static void Multiply3x3(const float A[3][3], const float B[3][3], float C[3][3]); static void Multiply3x3(const double A[3][3], const double B[3][3], double C[3][3]); // Description: // General matrix multiplication. You must allocate output storage. // colA == rowB // and matrix C is rowA x colB static void MultiplyMatrix(const double **A, const double **B, unsigned int rowA, unsigned int colA, unsigned int rowB, unsigned int colB, double **C); // Description: // Transpose a 3x3 matrix. static void Transpose3x3(const float A[3][3], float AT[3][3]); static void Transpose3x3(const double A[3][3], double AT[3][3]); // Description: // Invert a 3x3 matrix. static void Invert3x3(const float A[3][3], float AI[3][3]); static void Invert3x3(const double A[3][3], double AI[3][3]); // Description: // Set A to the identity matrix. static void Identity3x3(float A[3][3]); static void Identity3x3(double A[3][3]); // Description: // Return the determinant of a 3x3 matrix. static double Determinant3x3(float A[3][3]); static double Determinant3x3(double A[3][3]); // Description: // Compute determinant of 3x3 matrix. Three columns of matrix are input. static float Determinant3x3(const float c1[3], const float c2[3], const float c3[3]); // Description: // Compute determinant of 3x3 matrix. Three columns of matrix are input. static double Determinant3x3(const double c1[3], const double c2[3], const double c3[3]); // Description: // Calculate the determinant of a 3x3 matrix in the form: // | a1, b1, c1 | // | a2, b2, c2 | // | a3, b3, c3 | static double Determinant3x3(double a1, double a2, double a3, double b1, double b2, double b3, double c1, double c2, double c3); // Description: // Convert a quaternion to a 3x3 rotation matrix. The quaternion // does not have to be normalized beforehand. static void QuaternionToMatrix3x3(const float quat[4], float A[3][3]); static void QuaternionToMatrix3x3(const double quat[4], double A[3][3]); // Description: // Convert a 3x3 matrix into a quaternion. This will provide the // best possible answer even if the matrix is not a pure rotation matrix. // The method used is that of B.K.P. Horn. static void Matrix3x3ToQuaternion(const float A[3][3], float quat[4]); static void Matrix3x3ToQuaternion(const double A[3][3], double quat[4]); // Description: // Orthogonalize a 3x3 matrix and put the result in B. If matrix A // has a negative determinant, then B will be a rotation plus a flip // i.e. it will have a determinant of -1. static void Orthogonalize3x3(const float A[3][3], float B[3][3]); static void Orthogonalize3x3(const double A[3][3], double B[3][3]); // Description: // Diagonalize a symmetric 3x3 matrix and return the eigenvalues in // w and the eigenvectors in the columns of V. The matrix V will // have a positive determinant, and the three eigenvectors will be // aligned as closely as possible with the x, y, and z axes. static void Diagonalize3x3(const float A[3][3], float w[3], float V[3][3]); static void Diagonalize3x3(const double A[3][3],double w[3],double V[3][3]); // Description: // Perform singular value decomposition on a 3x3 matrix. This is not // done using a conventional SVD algorithm, instead it is done using // Orthogonalize3x3 and Diagonalize3x3. Both output matrices U and VT // will have positive determinants, and the w values will be arranged // such that the three rows of VT are aligned as closely as possible // with the x, y, and z axes respectively. If the determinant of A is // negative, then the three w values will be negative. static void SingularValueDecomposition3x3(const float A[3][3], float U[3][3], float w[3], float VT[3][3]); static void SingularValueDecomposition3x3(const double A[3][3], double U[3][3], double w[3], double VT[3][3]); // Description: // Solve linear equations Ax = b using Crout's method. Input is square // matrix A and load vector x. Solution x is written over load vector. The // dimension of the matrix is specified in size. If error is found, method // returns a 0. static int SolveLinearSystem(double **A, double *x, int size); // Description: // Invert input square matrix A into matrix AI. // Note that A is modified during // the inversion. The size variable is the dimension of the matrix. Returns 0 // if inverse not computed. static int InvertMatrix(double **A, double **AI, int size); // Description: // Thread safe version of InvertMatrix method. // Working memory arrays tmp1SIze and tmp2Size // of length size must be passed in. static int InvertMatrix(double **A, double **AI, int size, int *tmp1Size, double *tmp2Size); // Description: // Factor linear equations Ax = b using LU decomposition A = LU where L is // lower triangular matrix and U is upper triangular matrix. Input is // square matrix A, integer array of pivot indices index[0->n-1], and size // of square matrix n. Output factorization LU is in matrix A. If error is // found, method returns 0. static int LUFactorLinearSystem(double **A, int *index, int size); // Description: // Thread safe version of LUFactorLinearSystem method. // Working memory array tmpSize of length size // must be passed in. static int LUFactorLinearSystem(double **A, int *index, int size, double *tmpSize); // Description: // Solve linear equations Ax = b using LU decomposition A = LU where L is // lower triangular matrix and U is upper triangular matrix. Input is // factored matrix A=LU, integer array of pivot indices index[0->n-1], // load vector x[0->n-1], and size of square matrix n. Note that A=LU and // index[] are generated from method LUFactorLinearSystem). Also, solution // vector is written directly over input load vector. static void LUSolveLinearSystem(double **A, int *index, double *x, int size); // Description: // Estimate the condition number of a LU factored matrix. Used to judge the // accuracy of the solution. The matrix A must have been previously factored // using the method LUFactorLinearSystem. The condition number is the ratio // of the infinity matrix norm (i.e., maximum value of matrix component) // divided by the minimum diagonal value. (This works for triangular matrices // only: see Conte and de Boor, Elementary Numerical Analysis.) static double EstimateMatrixCondition(double **A, int size); // Description: // Initialize seed value. NOTE: Random() has the bad property that // the first random number returned after RandomSeed() is called // is proportional to the seed value! To help solve this, call // RandomSeed() a few times inside seed. This doesn't ruin the // repeatability of Random(). static void RandomSeed(long s); // Description: // Return the current seed used by the random number generator. static long GetSeed(); // Description: // Generate random numbers between 0.0 and 1.0. // This is used to provide portability across different systems. static double Random(); // Description: // Generate random number between (min,max). static double Random(double min, double max); // Description: // Jacobi iteration for the solution of eigenvectors/eigenvalues of a 3x3 // real symmetric matrix. Square 3x3 matrix a; output eigenvalues in w; // and output eigenvectors in v. Resulting eigenvalues/vectors are sorted // in decreasing order; eigenvectors are normalized. static int Jacobi(float **a, float *w, float **v); static int Jacobi(double **a, double *w, double **v); // Description: // JacobiN iteration for the solution of eigenvectors/eigenvalues of a nxn // real symmetric matrix. Square nxn matrix a; size of matrix in n; output // eigenvalues in w; and output eigenvectors in v. Resulting // eigenvalues/vectors are sorted in decreasing order; eigenvectors are // normalized. w and v need to be allocated previously static int JacobiN(float **a, int n, float *w, float **v); static int JacobiN(double **a, int n, double *w, double **v); // Description: // Solves a cubic equation c0*t^3 + c1*t^2 + c2*t + c3 = 0 when c0, c1, c2, // and c3 are REAL. Solution is motivated by Numerical Recipes In C 2nd // Ed. Return array contains number of (real) roots (counting multiple // roots as one) followed by roots themselves. The value in roots[4] is a // integer giving further information about the roots (see return codes for // int SolveCubic()). static double* SolveCubic(double c0, double c1, double c2, double c3); // Description: // Solves a quadratic equation c1*t^2 + c2*t + c3 = 0 when c1, c2, and c3 // are REAL. Solution is motivated by Numerical Recipes In C 2nd Ed. // Return array contains number of (real) roots (counting multiple roots as // one) followed by roots themselves. Note that roots[3] contains a return // code further describing solution - see documentation for SolveCubic() // for meaning of return codes. static double* SolveQuadratic(double c0, double c1, double c2); // Description: // Solves a linear equation c2*t + c3 = 0 when c2 and c3 are REAL. // Solution is motivated by Numerical Recipes In C 2nd Ed. // Return array contains number of roots followed by roots themselves. static double* SolveLinear(double c0, double c1); // Description: // Solves a cubic equation when c0, c1, c2, And c3 Are REAL. Solution // is motivated by Numerical Recipes In C 2nd Ed. Roots and number of // real roots are stored in user provided variables r1, r2, r3, and // num_roots. Note that the function can return the following integer // values describing the roots: (0)-no solution; (-1)-infinite number // of solutions; (1)-one distinct real root of multiplicity 3 (stored // in r1); (2)-two distinct real roots, one of multiplicity 2 (stored // in r1 & r2); (3)-three distinct real roots; (-2)-quadratic equation // with complex conjugate solution (real part of root returned in r1, // imaginary in r2); (-3)-one real root and a complex conjugate pair // (real root in r1 and real part of pair in r2 and imaginary in r3). static int SolveCubic(double c0, double c1, double c2, double c3, double *r1, double *r2, double *r3, int *num_roots); // Description: // Solves a quadratic equation c1*t^2 + c2*t + c3 = 0 when // c1, c2, and c3 are REAL. // Solution is motivated by Numerical Recipes In C 2nd Ed. // Roots and number of roots are stored in user provided variables // r1, r2, num_roots static int SolveQuadratic(double c0, double c1, double c2, double *r1, double *r2, int *num_roots); // Description: // Algebraically extracts REAL roots of the quadratic polynomial with // REAL coefficients c[0] X^2 + c[1] X + c[2] // and stores them (when they exist) and their respective multiplicities // in the \a r and \a m arrays. // Returns either the number of roots, or -1 if ininite number of roots. static int SolveQuadratic( double* c, double* r, int* m ); // Description: // Solves a linear equation c2*t + c3 = 0 when c2 and c3 are REAL. // Solution is motivated by Numerical Recipes In C 2nd Ed. // Root and number of (real) roots are stored in user provided variables // r2 and num_roots. static int SolveLinear(double c0, double c1, double *r1, int *num_roots); // Description: // Solves for the least squares best fit matrix for the homogeneous equation X'M' = 0'. // Uses the method described on pages 40-41 of Computer Vision by // Forsyth and Ponce, which is that the solution is the eigenvector // associated with the minimum eigenvalue of T(X)X, where T(X) is the // transpose of X. // The inputs and output are transposed matrices. // Dimensions: X' is numberOfSamples by xOrder, // M' dimension is xOrder by yOrder. // M' should be pre-allocated. All matrices are row major. The resultant // matrix M' should be pre-multiplied to X' to get 0', or transposed and // then post multiplied to X to get 0 static int SolveHomogeneousLeastSquares(int numberOfSamples, double **xt, int xOrder, double **mt); // Description: // Solves for the least squares best fit matrix for the equation X'M' = Y'. // Uses pseudoinverse to get the ordinary least squares. // The inputs and output are transposed matrices. // Dimensions: X' is numberOfSamples by xOrder, // Y' is numberOfSamples by yOrder, // M' dimension is xOrder by yOrder. // M' should be pre-allocated. All matrices are row major. The resultant // matrix M' should be pre-multiplied to X' to get Y', or transposed and // then post multiplied to X to get Y // By default, this method checks for the homogeneous condition where Y==0, and // if so, invokes SolveHomogeneousLeastSquares. For better performance when // the system is known not to be homogeneous, invoke with checkHomogeneous=0. static int SolveLeastSquares(int numberOfSamples, double **xt, int xOrder, double **yt, int yOrder, double **mt, int checkHomogeneous=1); // Description: // Convert color in RGB format (Red, Green, Blue) to HSV format // (Hue, Saturation, Value). The input color is not modified. static void RGBToHSV(const float rgb[3], float hsv[3]) { RGBToHSV(rgb[0], rgb[1], rgb[2], hsv, hsv+1, hsv+2); } static void RGBToHSV(float r, float g, float b, float *h, float *s, float *v); static double* RGBToHSV(const double rgb[3]); static double* RGBToHSV(double r, double g, double b); static void RGBToHSV(const double rgb[3], double hsv[3]) { RGBToHSV(rgb[0], rgb[1], rgb[2], hsv, hsv+1, hsv+2); } static void RGBToHSV(double r, double g, double b, double *h, double *s, double *v); // Description: // Convert color in HSV format (Hue, Saturation, Value) to RGB // format (Red, Green, Blue). The input color is not modified. static void HSVToRGB(const float hsv[3], float rgb[3]) { HSVToRGB(hsv[0], hsv[1], hsv[2], rgb, rgb+1, rgb+2); } static void HSVToRGB(float h, float s, float v, float *r, float *g, float *b); static double* HSVToRGB(const double hsv[3]); static double* HSVToRGB(double h, double s, double v); static void HSVToRGB(const double hsv[3], double rgb[3]) { HSVToRGB(hsv[0], hsv[1], hsv[2], rgb, rgb+1, rgb+2); } static void HSVToRGB(double h, double s, double v, double *r, double *g, double *b); // Description: // Convert color from the CIE-L*ab system to CIE XYZ. static void LabToXYZ(const double lab[3], double xyz[3]) { LabToXYZ(lab[0], lab[1], lab[2], xyz+0, xyz+1, xyz+2); } static void LabToXYZ(double L, double a, double b, double *x, double *y, double *z); static double *LabToXYZ(const double lab[3]); // Description: // Convert Color from the CIE XYZ system to CIE-L*ab. static void XYZToLab(const double xyz[3], double lab[3]) { XYZToLab(xyz[0], xyz[1], xyz[2], lab+0, lab+1, lab+2); } static void XYZToLab(double x, double y, double z, double *L, double *a, double *b); static double *XYZToLab(const double xyz[3]); // Description: // Convert color from the CIE XYZ system to RGB. static void XYZToRGB(const double xyz[3], double rgb[3]) { XYZToRGB(xyz[0], xyz[1], xyz[2], rgb+0, rgb+1, rgb+2); } static void XYZToRGB(double x, double y, double z, double *r, double *g, double *b); static double *XYZToRGB(const double xyz[3]); // Description: // Convert color from the RGB system to CIE XYZ. static void RGBToXYZ(const double rgb[3], double xyz[3]) { RGBToXYZ(rgb[0], rgb[1], rgb[2], xyz+0, xyz+1, xyz+2); } static void RGBToXYZ(double r, double g, double b, double *x, double *y, double *z); static double *RGBToXYZ(const double rgb[3]); // Description: // Convert color from the RGB system to CIE-L*ab. static void RGBToLab(const double rgb[3], double lab[3]) { RGBToLab(rgb[0], rgb[1], rgb[2], lab+0, lab+1, lab+2); } static void RGBToLab(double red, double green, double blue, double *L, double *a, double *b); static double *RGBToLab(const double rgb[3]); // Description: // Convert color from the CIE-L*ab system to RGB. static void LabToRGB(const double lab[3], double rgb[3]) { LabToRGB(lab[0], lab[1], lab[2], rgb+0, rgb+1, rgb+2); } static void LabToRGB(double L, double a, double b, double *red, double *green, double *blue); static double *LabToRGB(const double lab[3]); // Description: // Set the bounds to an uninitialized state static void UninitializeBounds(double bounds[6]){ bounds[0] = 1.0; bounds[1] = -1.0; bounds[2] = 1.0; bounds[3] = -1.0; bounds[4] = 1.0; bounds[5] = -1.0; } // Description: // Are the bounds initialized? static int AreBoundsInitialized(double bounds[6]){ if (bounds[1]-bounds[0]<0.0) { return 0; } return 1; } // Description: // Clamp some values against a range // The method without 'clamped_values' will perform in-place clamping. static void ClampValue(double *value, const double range[2]); static void ClampValue(double value, const double range[2], double *clamped_value); static void ClampValues( double *values, int nb_values, const double range[2]); static void ClampValues( const double *values, int nb_values, const double range[2], double *clamped_values); // Description: // Return the scalar type that is most likely to have enough precision // to store a given range of data once it has been scaled and shifted // (i.e. [range_min * scale + shift, range_max * scale + shift]. // If any one of the parameters is not an integer number (decimal part != 0), // the search will default to float types only (float or double) // Return -1 on error or no scalar type found. static int GetScalarTypeFittingRange( double range_min, double range_max, double scale = 1.0, double shift = 0.0); // Description: // Get a vtkDataArray's scalar range for a given component. // If the vtkDataArray's data type is unsigned char (VTK_UNSIGNED_CHAR) // the range is adjusted to the whole data type range [0, 255.0]. // Same goes for unsigned short (VTK_UNSIGNED_SHORT) but the upper bound // is also adjusted down to 4095.0 if was between ]255, 4095.0]. // Return 1 on success, 0 otherwise. static int GetAdjustedScalarRange( vtkDataArray *array, int comp, double range[2]); // Description: // Return true if first 3D extent is within second 3D extent // Extent is x-min, x-max, y-min, y-max, z-min, z-max static int ExtentIsWithinOtherExtent(int extent1[6], int extent2[6]); // Description: // Return true if first 3D bounds is within the second 3D bounds // Bounds is x-min, x-max, y-min, y-max, z-min, z-max // Delta is the error margin along each axis (usually a small number) static int BoundsIsWithinOtherBounds(double bounds1[6], double bounds2[6], double delta[3]); // Description: // Return true if point is within the given 3D bounds // Bounds is x-min, x-max, y-min, y-max, z-min, z-max // Delta is the error margin along each axis (usually a small number) static int PointIsWithinBounds(double point[3], double bounds[6], double delta[3]); // Description: // Special IEEE-754 numbers used to represent positive and negative infinity and Not-A-Number (Nan). static double Inf(); static double NegInf(); static double Nan(); protected: vtkMath() {}; ~vtkMath() {}; static long Seed; private: vtkMath(const vtkMath&); // Not implemented. void operator=(const vtkMath&); // Not implemented. }; //---------------------------------------------------------------------------- inline vtkTypeInt64 vtkMath::Factorial( int N ) { vtkTypeInt64 r = 1; while ( N > 1 ) { r *= N--; } return r; } //---------------------------------------------------------------------------- inline int vtkMath::Floor(double x) { #if defined i386 || defined _M_IX86 union { int i[2]; double d; } u; // use 52-bit precision of IEEE double to round (x - 0.25) to // the nearest multiple of 0.5, according to prevailing rounding // mode which is IEEE round-to-nearest,even u.d = (x - 0.25) + 3377699720527872.0; // (2**51)*1.5 // extract mantissa, use shift to divide by 2 and hence get rid // of the bit that gets messed up because the FPU uses // round-to-nearest,even mode instead of round-to-nearest,+infinity return u.i[0] >> 1; #else return static_cast<int>(floor(x)); #endif } //---------------------------------------------------------------------------- inline float vtkMath::Normalize(float x[3]) { float den; if ( (den = vtkMath::Norm(x)) != 0.0 ) { for (int i=0; i < 3; i++) { x[i] /= den; } } return den; } //---------------------------------------------------------------------------- inline double vtkMath::Normalize(double x[3]) { double den; if ( (den = vtkMath::Norm(x)) != 0.0 ) { for (int i=0; i < 3; i++) { x[i] /= den; } } return den; } //---------------------------------------------------------------------------- inline float vtkMath::Normalize2D(float x[3]) { float den; if ( (den = vtkMath::Norm2D(x)) != 0.0 ) { for (int i=0; i < 2; i++) { x[i] /= den; } } return den; } //---------------------------------------------------------------------------- inline double vtkMath::Normalize2D(double x[3]) { double den; if ( (den = vtkMath::Norm2D(x)) != 0.0 ) { for (int i=0; i < 2; i++) { x[i] /= den; } } return den; } //---------------------------------------------------------------------------- inline float vtkMath::Determinant3x3(const float c1[3], const float c2[3], const float c3[3]) { return c1[0]*c2[1]*c3[2] + c2[0]*c3[1]*c1[2] + c3[0]*c1[1]*c2[2] - c1[0]*c3[1]*c2[2] - c2[0]*c1[1]*c3[2] - c3[0]*c2[1]*c1[2]; } //---------------------------------------------------------------------------- inline double vtkMath::Determinant3x3(const double c1[3], const double c2[3], const double c3[3]) { return c1[0]*c2[1]*c3[2] + c2[0]*c3[1]*c1[2] + c3[0]*c1[1]*c2[2] - c1[0]*c3[1]*c2[2] - c2[0]*c1[1]*c3[2] - c3[0]*c2[1]*c1[2]; } //---------------------------------------------------------------------------- inline double vtkMath::Determinant3x3(double a1, double a2, double a3, double b1, double b2, double b3, double c1, double c2, double c3) { return ( a1 * vtkMath::Determinant2x2( b2, b3, c2, c3 ) - b1 * vtkMath::Determinant2x2( a2, a3, c2, c3 ) + c1 * vtkMath::Determinant2x2( a2, a3, b2, b3 ) ); } //---------------------------------------------------------------------------- inline float vtkMath::Distance2BetweenPoints(const float x[3], const float y[3]) { return ((x[0]-y[0])*(x[0]-y[0]) + (x[1]-y[1])*(x[1]-y[1]) + (x[2]-y[2])*(x[2]-y[2])); } //---------------------------------------------------------------------------- inline double vtkMath::Distance2BetweenPoints(const double x[3], const double y[3]) { return ((x[0]-y[0])*(x[0]-y[0]) + (x[1]-y[1])*(x[1]-y[1]) + (x[2]-y[2])*(x[2]-y[2])); } //---------------------------------------------------------------------------- inline double vtkMath::Random(double min, double max) { return (min + vtkMath::Random()*(max-min)); } //---------------------------------------------------------------------------- // Cross product of two 3-vectors. Result vector in z[3]. inline void vtkMath::Cross(const float x[3], const float y[3], float z[3]) { float Zx = x[1]*y[2] - x[2]*y[1]; float Zy = x[2]*y[0] - x[0]*y[2]; float Zz = x[0]*y[1] - x[1]*y[0]; z[0] = Zx; z[1] = Zy; z[2] = Zz; } //---------------------------------------------------------------------------- // Cross product of two 3-vectors. Result vector in z[3]. inline void vtkMath::Cross(const double x[3], const double y[3], double z[3]) { double Zx = x[1]*y[2] - x[2]*y[1]; double Zy = x[2]*y[0] - x[0]*y[2]; double Zz = x[0]*y[1] - x[1]*y[0]; z[0] = Zx; z[1] = Zy; z[2] = Zz; } //BTX //---------------------------------------------------------------------------- template<class T> inline double vtkDeterminant3x3(T A[3][3]) { return A[0][0]*A[1][1]*A[2][2] + A[1][0]*A[2][1]*A[0][2] + A[2][0]*A[0][1]*A[1][2] - A[0][0]*A[2][1]*A[1][2] - A[1][0]*A[0][1]*A[2][2] - A[2][0]*A[1][1]*A[0][2]; } //ETX //---------------------------------------------------------------------------- inline double vtkMath::Determinant3x3(float A[3][3]) { return vtkDeterminant3x3(A); } //---------------------------------------------------------------------------- inline double vtkMath::Determinant3x3(double A[3][3]) { return vtkDeterminant3x3(A); } //---------------------------------------------------------------------------- inline void vtkMath::ClampValue(double *value, const double range[2]) { if (value && range) { if (*value < range[0]) { *value = range[0]; } else if (*value > range[1]) { *value = range[1]; } } } //---------------------------------------------------------------------------- inline void vtkMath::ClampValue( double value, const double range[2], double *clamped_value) { if (range && clamped_value) { if (value < range[0]) { *clamped_value = range[0]; } else if (value > range[1]) { *clamped_value = range[1]; } else { *clamped_value = value; } } } #endif
[ "nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f" ]
[ [ [ 1, 942 ] ] ]
6945b800351cd74386d7a1675a1cdd860a16f1ab
51726d092ac990a55a819afb61794e7c2721308a
/tags/release_2.0.0/plugin/Sources/CValuePairArray.h
e05c5dc62ca99164c3545445824b2e66d7f927ba
[]
no_license
BackupTheBerlios/mrs-svn
3be8368d68e83437aa6cfa784aac9d3d06ded557
56d3893ad9ea72143bc26bb7a8ee94c2d1159176
refs/heads/master
2016-09-05T20:12:06.966301
2008-06-18T19:57:40
2008-06-18T19:57:40
40,749,226
0
0
null
null
null
null
UTF-8
C++
false
false
15,564
h
/* $Id$ Copyright hekkelman Created Thursday February 09 2006 09:36:27 */ #ifndef CVALUEPAIRARRAY_H #define CVALUEPAIRARRAY_H #if P_DEBUG #include <iostream> #endif #if P_GNU #include "CBitStream.h" #else class COBitStream; class CIBitStream; #endif #include "HError.h" #include <boost/type_traits/is_integral.hpp> // Rationale: // // We want to concentrate the code for writing golomb code compressed arrays // into one single area. We also support both the simple compressed document // id vectors as well as attributed document id vectors (containing e.g. document // id and weight). // For simplicity attributes are consided to be uint8 values in the range // 0 < v <= kMaxWeight // For attributed vectors we sort the vectors on attribute value first, and // on document ID next. This allows us to store the document ID's with the // same attribute values as a regular compressed array. The attribute value // is stored before these arrays as differences from the previous attribute // value. // // The original version of MRS used Golomb code compression solely. However, // a recent article by Vo Ngoc Anh and Alistair Moffat called 'Index compression // using Fixed Binary Codewords' showed that big improvements can be attained // using another compressions algorithm. The gain in decompression speed is // about 20% however, surprisingly the gain in compression ratio in the typical // bioinformatics databank results in MRS files that are typically 10 to 20% // smaller. enum CArrayCompressionKind { kAC_GolombCode = FOUR_CHAR_INLINE('golo'), kAC_SelectorCode = FOUR_CHAR_INLINE('sel1') }; namespace CValuePairCompression { template<typename V, typename W> struct WeightGreater { bool operator()(const std::pair<V,W>& inA, const std::pair<V,W>& inB) const { return inA.second > inB.second or (inA.second == inB.second and inA.first < inB.first); } }; struct CSelector { int databits; int span; }; const CSelector kSelectors[16] = { { 0, 1 }, { -3, 1 }, { -2, 1 }, { -2, 1 }, { -1, 1 }, { -1, 2 }, { -1, 4 }, { 0, 1 }, { 0, 2 }, { 0, 4 }, { 1, 1 }, { 1, 2 }, { 1, 4 }, { 2, 1 }, { 2, 2 }, { 3, 1 } }; inline uint32 Select(uint32 inBitsNeeded[], uint32 inCount, int32 inWidth, int32 inMaxWidth, const CSelector inSelectors[]) { uint32 result = 0; int32 c = inBitsNeeded[0] - inMaxWidth; for (uint32 i = 1; i < 16; ++i) { if (inSelectors[i].span > inCount) continue; int32 w = inWidth + inSelectors[i].databits; if (w > inMaxWidth or w < 0) continue; bool fits = true; int32 waste = 0; switch (inSelectors[i].span) { case 4: fits = fits and inBitsNeeded[3] <= w; waste += w - inBitsNeeded[3]; case 3: fits = fits and inBitsNeeded[2] <= w; waste += w - inBitsNeeded[2]; case 2: fits = fits and inBitsNeeded[1] <= w; waste += w - inBitsNeeded[1]; case 1: fits = fits and inBitsNeeded[0] <= w; waste += w - inBitsNeeded[0]; } if (fits == false) continue; int32 n = (inSelectors[i].span - 1) * 4 - waste; if (n > c) { result = i; c = n; } } return result; } template<class T> inline void Shift(T& ioIterator, int64& ioLast, uint32& outDelta, uint32& outWidth) { int64 next = *ioIterator++; assert(next > ioLast); outDelta = next - ioLast - 1; ioLast = next; uint32 v = outDelta; outWidth = 0; while (v > 0) { v >>= 1; ++outWidth; } } template<typename T> void CompressSimpleArraySelector(COBitStream& inBits, std::vector<T>& inArray, int64 inMax) { uint32 cnt = inArray.size(); WriteGamma(inBits, cnt); //std::cout << "Writing array with " << cnt << " elements:" << std::endl; //for (uint32 i = 0; i < cnt; ++i) // std::cout << ' ' << inArray[i]; //std::cout << std::endl; int32 maxWidth = 0; int64 v = inMax; while (v > 0) { v >>= 1; ++maxWidth; } int32 width = maxWidth; int64 last = -1; uint32 bn[4]; uint32 dv[4]; uint32 bc = 0; typename std::vector<T>::iterator a = inArray.begin(); typename std::vector<T>::iterator e = inArray.end(); while (a != e or bc > 0) { //if (bc > 0) //{ //std::cout << "array now contains:" << std::endl; // //for (uint32 i = 0; i < bc; ++i) //std::cout << " dv: " << dv[i] << ", bn: " << bn[i] << std::endl; //} // while (bc < 4 and a != e) { Shift(a, last, dv[bc], bn[bc]); //std::cout << "shifted " << bc << ", dv: " << dv[bc] << ", bn: " << bn[bc] << std::endl; ++bc; } uint32 s = Select(bn, bc, width, maxWidth, kSelectors); if (s == 0) width = maxWidth; else width += kSelectors[s].databits; uint32 n = kSelectors[s].span; WriteBinary(inBits, s, 4); //std::cout << "Selector " << s << " width: " << width << " values:"; if (width > 0) { for (uint32 i = 0; i < n; ++i) { //std::cout << ' ' << dv[i]; WriteBinary(inBits, dv[i], width); } } //std::cout << std::endl; bc -= n; if (bc > 0) { for (uint32 i = 0; i < (4 - n); ++i) { bn[i] = bn[i + n]; dv[i] = dv[i + n]; } } } } template<typename T> void CompressSimpleArrayGolomb(COBitStream& inBits, std::vector<T>& inArray, int64 inMax) { uint32 cnt = inArray.size(); int32 b = CalculateB(inMax, cnt); int32 n = 0, g = 1; while (g < b) { ++n; g <<= 1; } g -= b; WriteGamma(inBits, cnt); int64 lv = -1; // we store delta's and our arrays can start at zero... typedef typename std::vector<T>::iterator iterator; for (iterator i = inArray.begin(); i != inArray.end(); ++i) { // write the value int32 d = static_cast<int32>(*i - lv); assert(d > 0); int32 q = (d - 1) / b; int32 r = d - q * b - 1; while (q-- > 0) inBits << 1; inBits << 0; if (b > 1) { if (r < g) { for (int t = 1 << (n - 2); t != 0; t >>= 1) inBits << ((r & t) != 0); } else { r += g; for (int t = 1 << (n - 1); t != 0; t >>= 1) inBits << ((r & t) != 0); } } lv = *i; } } template<typename T> struct ValuePairTraitsPOD { typedef std::vector<T> vector_type; typedef typename vector_type::iterator iterator; typedef typename vector_type::const_iterator const_iterator; typedef T value_type; typedef void rank_type; static void CompressArray(COBitStream& inBits, std::vector<T>& inArray, int64 inMax, uint32 inKind); }; template<typename T> void ValuePairTraitsPOD<T>::CompressArray(COBitStream& inBits, std::vector<T>& inArray, int64 inMax, uint32 inKind) { switch (inKind) { case kAC_GolombCode: CompressSimpleArrayGolomb(inBits, inArray, inMax); break; case kAC_SelectorCode: CompressSimpleArraySelector(inBits, inArray, inMax); break; default: THROW(("Unsupported array compression algorithm: %4.4s", &inKind)); } } template<typename T> struct ValuePairTraitsPair { typedef std::vector<T> vector_type; typedef typename vector_type::iterator iterator; typedef typename vector_type::const_iterator const_iterator; typedef typename T::first_type value_type; typedef typename T::second_type rank_type; static void CompressArray(COBitStream& inBits, std::vector<T>& inArray, int64 inMax, uint32 inKind); }; template<typename T> void ValuePairTraitsPair<T>::CompressArray(COBitStream& inBits, std::vector<T>& inArray, int64 inMax, uint32 inKind) { WriteGamma(inBits, inArray.size()); sort(inArray.begin(), inArray.end(), WeightGreater<value_type,rank_type>()); std::vector<value_type> values; values.reserve(inArray.size()); const_iterator v = inArray.begin(); uint32 lastWeight = inArray.front().second; WriteGamma(inBits, lastWeight); while (v != inArray.end()) { uint32 w = v->second; while (v != inArray.end() and v->second == w) { values.push_back(v->first); ++v; } if (values.size()) { uint8 d = lastWeight - w; if (d > 0) // skip the first since it has been written already WriteGamma(inBits, d); switch (inKind) { case kAC_GolombCode: CompressSimpleArrayGolomb(inBits, values, inMax); break; case kAC_SelectorCode: CompressSimpleArraySelector(inBits, values, inMax); break; default: THROW(("Unsupported array compression algorithm: %4.4s", &inKind)); } values.clear(); lastWeight = w; } } } // an iterator type for compressed value/rank pairs template<typename T, uint32 K> class IteratorBase { }; template<typename T> class IteratorBase<T, kAC_GolombCode> { public: IteratorBase(CIBitStream& inData, int64 inMax) : fBits(&inData) , fCount(0) , fRead(0) , fValue(-1) , fMax(inMax) { Reset(); } virtual ~IteratorBase() {} virtual bool Next() { bool done = false; if (fRead < fCount) { int32 q = 0; int32 r = 0; if (fBits->next_bit()) { q = 1; while (fBits->next_bit()) ++q; } if (b > 1) { for (int e = 0; e < n - 1; ++e) r = (r << 1) | fBits->next_bit(); if (r >= g) { r = (r << 1) | fBits->next_bit(); r -= g; } } int32 d = r + q * b + 1; fValue += d; ++fRead; done = true; } return done; } T Value() const { return static_cast<T>(fValue); } virtual uint32 Weight() const { return 1; } virtual uint32 Count() const { return fCount; } virtual uint32 Read() const { return fRead; } protected: IteratorBase(CIBitStream& inData, int64 inMax, bool) : fBits(&inData) , fCount(0) , fRead(0) , fValue(-1) , fMax(inMax) { } IteratorBase(const IteratorBase& inOther); IteratorBase& operator=(const IteratorBase& inOther); void Reset() { fValue = -1; fCount = ReadGamma(*fBits); fRead = 0; b = CalculateB(fMax, fCount); n = 0; g = 1; while (g < b) { ++n; g <<= 1; } g -= b; } CIBitStream* fBits; uint32 fCount; uint32 fRead; int32 b, n, g; int64 fValue; int64 fMax; }; template<typename T> class IteratorBase<T, kAC_SelectorCode> { public: IteratorBase(CIBitStream& inData, int64 inMax) : fBits(&inData) , fRead(0) , fValue(-1) , fMax(inMax) { int64 v = fMax; fMaxWidth = 0; while (v > 0) { v >>= 1; ++fMaxWidth; } Reset(); } virtual ~IteratorBase() {} virtual bool Next() { bool done = false; if (fRead < fCount) { if (fSpan == 0) { uint32 selector = ReadBinary<uint32>(*fBits, 4); fSpan = kSelectors[selector].span; if (selector == 0) fWidth = fMaxWidth; else fWidth += kSelectors[selector].databits; //std::cout << "Read selector " << selector << ", width now " << fWidth << " and span " << fSpan << std::endl; } if (fWidth > 0) fValue += ReadBinary<int64>(*fBits, fWidth); fValue += 1; //std::cout << "Value " << fValue << std::endl; --fSpan; ++fRead; done = true; } return done; } T Value() const { return static_cast<T>(fValue); } virtual uint32 Weight() const { return 1; } virtual uint32 Count() const { return fCount; } virtual uint32 Read() const { return fRead; } protected: IteratorBase(CIBitStream& inData, int64 inMax, bool) : fBits(&inData) , fRead(0) , fValue(-1) , fMax(inMax) { int64 v = fMax; fMaxWidth = 0; while (v > 0) { v >>= 1; ++fMaxWidth; } } IteratorBase(const IteratorBase& inOther); IteratorBase& operator=(const IteratorBase& inOther); void Reset() { fValue = -1; fCount = ReadGamma(*fBits); fRead = 0; fSpan = 0; fWidth = fMaxWidth; } CIBitStream* fBits; uint32 fCount; uint32 fRead; int32 fWidth; int32 fMaxWidth; int64 fSpan; int64 fValue; int64 fMax; }; template<typename T, uint32 K> class VRIterator : public IteratorBase<typename ValuePairTraitsPair<T>::value_type, K> { typedef IteratorBase<typename ValuePairTraitsPair<T>::value_type, K> base_type; typedef ValuePairTraitsPair<T> traits; typedef typename traits::value_type value_type; typedef typename traits::rank_type rank_type; public: VRIterator(CIBitStream& inData, int64 inMax) : base_type(inData, inMax, false) { fTotalCount = ReadGamma(inData); fWeight = ReadGamma(inData); fTotalRead = 0; this->Reset(); } virtual bool Next(); virtual uint32 Weight() const { return fWeight; } virtual uint32 Read() const { return fTotalRead; } virtual uint32 Count() const { return fTotalCount; } private: // VRIterator(const VRIterator& inOther); //VRIterator& operator=(const VRIterator& inOther); void Restart(); uint32 fTotalCount; uint32 fTotalRead; uint32 fWeight; }; template<typename T, uint32 K> void VRIterator<T, K>::Restart() { fWeight -= ReadGamma(*this->fBits); // assert(fWeight <= kMaxWeight); assert(fWeight > 0); if (fWeight > 0) this->Reset(); else this->fCount = 0; assert(this->fCount <= fTotalCount - fTotalRead); } template<typename T, uint32 K> bool VRIterator<T, K>::Next() { bool done = false; while (not done and fWeight > 0 and fTotalRead < fTotalCount) { if (base_type::Next()) { ++fTotalRead; done = true; } else Restart(); } return done; } template<typename T, uint32 K, bool> struct ValuePairTraitsTypeFactoryBase { typedef ValuePairTraitsPOD<T> type; typedef IteratorBase<T,K> iterator; }; template<typename T, uint32 K> struct ValuePairTraitsTypeFactoryBase<T, K, false> { typedef ValuePairTraitsPair<T> type; typedef VRIterator<T,K> iterator; }; template<typename T, uint32 K> struct ValuePairTraitsTypeFactory : public ValuePairTraitsTypeFactoryBase<T, K, boost::is_integral<T>::value> { }; } template<typename T> void CompressArray(COBitStream& inBits, T& inArray, int64 inMax, uint32 inKind) { using namespace CValuePairCompression; typedef typename T::value_type vector_value_type; switch (inKind) { case kAC_GolombCode: { typedef typename ValuePairTraitsTypeFactory<vector_value_type,kAC_GolombCode>::type traits; traits::CompressArray(inBits, inArray, inMax, inKind); break; } case kAC_SelectorCode: { typedef typename ValuePairTraitsTypeFactory<vector_value_type,kAC_SelectorCode>::type traits; traits::CompressArray(inBits, inArray, inMax, inKind); break; } } } #endif // CVALUEPAIRARRAY_H
[ "hekkel@56de0a5b-be05-0410-9d44-921623777a7a" ]
[ [ [ 1, 705 ] ] ]
8102fe532168fdbfd59fb3d75f72f76ca6f146db
b3840f19a2fc41a5634420219ec3d8ddfc9c1dcc
/UI Source code/ArduEye_UI/ArduEye_UI.h
2a0b8d9cc93a636a3fa8ebf08d2d7025cf2f6c72
[]
no_license
centeye/ArduEye-Serial-UI
bf8cd6fb8dc06c68331e09ad91405b7839da5d26
c0232c05dc959b77d454306f101cc644a7044761
refs/heads/master
2021-01-01T05:53:06.524780
2011-10-26T01:07:05
2011-10-26T01:07:05
2,240,247
1
1
null
null
null
null
UTF-8
C++
false
false
5,114
h
/* ArduEye_UI.h - Event processing functions for the ArduEye UI Centeye, Inc Created by Alison Leonard. August, 2011 =============================================================================== Copyright (c) 2011, Centeye, Inc. 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 Centeye, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CENTEYE, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =============================================================================== */ #ifndef ARDUEYE_UI_H #define ARDUEYE_UI_H #include <QWidget> #include "commwrapper.h" #include "Datasets.h" #include <QElapsedTimer> #include <QFile> // text display locations #define TEXT_XLOC 10 #define TEXT_YLOC 20 // min max functions template <class T> const T& max ( const T& a, const T& b ) { return (b<a)?a:b; } template <class T> const T& min ( const T& a, const T& b ) { return (b<a)?a:b; } namespace Ui { class ArduEyeUI; } class ArduEyeUI : public QWidget { Q_OBJECT public: // constructor / destructor explicit ArduEyeUI(QWidget *parent = 0); ~ArduEyeUI(); private slots: //Serial device found void onDeviceDiscovered(const QextPortInfo &newport); //Serial device removed void onDeviceRemoved(const QextPortInfo &newport); // connect to serial device button void on_ConnectButton_clicked(); // serial data is available (via qextserial library) void onDataAvailable(); // command entered void on_CmdEdit_returnPressed(); // start file record void on_FileRecordButton_clicked(); // check if Cmd Ack has been received (slot driven by a timer) void CheckCmdReceived(); // command entered void on_enterButton_clicked(); private: // self Ui::ArduEyeUI *ui; // wrapper for qextserial library CommWrapper *comm; // list of commands (filled via parameters txt file) QStringList CmdList; // List of Command IDs (CmdList and CmdIndex together are the key for parsing text entered in the UI) QByteArray CmdIndex; // Main image display array QPixmap ImagePixMap; // Datasets structure, keeps dataset arrays and settings DataSets *DS; // number of possible datasets (defined by parameters txt file) int NumDataSets; // Buffer for reading in serial bytes char * DataBuffer; // flags for parsing incoming serial bytes int DataBufferSize, StartIdx, BufEndIdx, DataIdx; // flag for recording data bool FileRecordOn; // flag for parsing incoming serial bytes bool ESCReceived; // file for recording data QFile FileSave; // flag that cmd was received by Arduino bool CmdReceived; //FUNCTIONS //parse serial packets (process incoming data and commands) void ParsePacket(int Start, int End); // load parameters txt file and parse void LoadTextFile(); // parse commands in Cmd Text Line and send to ArduEye void Parse(QString inText); // init datasets using parameters txt file void InitDataSets(); // find index of dataset in the Datasets structure int GetActiveDataSet(int inDSID); // record active datsets to open file void RecordtoFile(); //PRINT FUNCTIONS void PrintImage(uchar * data, int rows, int cols); void PrintVectors(char *dataR, char * dataC, int rows, int cols, QPixmap * PM); void PrintOFYBoxes(char *data, int rows, int cols); void PrintOFXBoxes(char *data, int rows, int cols); void PrintText(char * data, int xloc, int yloc, QPixmap * PM); void PrintPoints(char *data, int NumPoints, QPixmap * PM); // print functions manager, called after End of Frame flag received void paintManager(); }; #endif // ArduEyeUI_H
[ [ [ 1, 141 ] ] ]
3cebfb638601b6a285ebeea9a6808fd49fa67a03
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/asio/example/chat/posix_chat_client.cpp
f284de6148cc8906160fd57248f0d701ad170c31
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,565
cpp
// // posix_chat_client.cpp // ~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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) // #include <cstdlib> #include <cstring> #include <iostream> #include <boost/array.hpp> #include <boost/bind.hpp> #include <boost/asio.hpp> #include "chat_message.hpp" #if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) using boost::asio::ip::tcp; namespace posix = boost::asio::posix; class posix_chat_client { public: posix_chat_client(boost::asio::io_service& io_service, tcp::resolver::iterator endpoint_iterator) : socket_(io_service), input_(io_service, ::dup(STDIN_FILENO)), output_(io_service, ::dup(STDOUT_FILENO)), input_buffer_(chat_message::max_body_length) { // Try connecting to the first endpoint. tcp::endpoint endpoint = *endpoint_iterator; socket_.async_connect(endpoint, boost::bind(&posix_chat_client::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator)); } private: void handle_connect(const boost::system::error_code& error, tcp::resolver::iterator endpoint_iterator) { if (!error) { // Read the fixed-length header of the next message from the server. boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.data(), chat_message::header_length), boost::bind(&posix_chat_client::handle_read_header, this, boost::asio::placeholders::error)); // Read a line of input entered by the user. boost::asio::async_read_until(input_, input_buffer_, '\n', boost::bind(&posix_chat_client::handle_read_input, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else if (endpoint_iterator != tcp::resolver::iterator()) { // That endpoint didn't work, try the next one. socket_.close(); tcp::endpoint endpoint = *endpoint_iterator; socket_.async_connect(endpoint, boost::bind(&posix_chat_client::handle_connect, this, boost::asio::placeholders::error, ++endpoint_iterator)); } } void handle_read_header(const boost::system::error_code& error) { if (!error && read_msg_.decode_header()) { // Read the variable-length body of the message from the server. boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.body(), read_msg_.body_length()), boost::bind(&posix_chat_client::handle_read_body, this, boost::asio::placeholders::error)); } else { close(); } } void handle_read_body(const boost::system::error_code& error) { if (!error) { // Write out the message we just received, terminated by a newline. static char eol[] = { '\n' }; boost::array<boost::asio::const_buffer, 2> buffers = {{ boost::asio::buffer(read_msg_.body(), read_msg_.body_length()), boost::asio::buffer(eol) }}; boost::asio::async_write(output_, buffers, boost::bind(&posix_chat_client::handle_write_output, this, boost::asio::placeholders::error)); } else { close(); } } void handle_write_output(const boost::system::error_code& error) { if (!error) { // Read the fixed-length header of the next message from the server. boost::asio::async_read(socket_, boost::asio::buffer(read_msg_.data(), chat_message::header_length), boost::bind(&posix_chat_client::handle_read_header, this, boost::asio::placeholders::error)); } else { close(); } } void handle_read_input(const boost::system::error_code& error, std::size_t length) { if (!error) { // Write the message (minus the newline) to the server. write_msg_.body_length(length - 1); input_buffer_.sgetn(write_msg_.body(), length - 1); input_buffer_.consume(1); // Remove newline from input. write_msg_.encode_header(); boost::asio::async_write(socket_, boost::asio::buffer(write_msg_.data(), write_msg_.length()), boost::bind(&posix_chat_client::handle_write, this, boost::asio::placeholders::error)); } else if (error == boost::asio::error::not_found) { // Didn't get a newline. Send whatever we have. write_msg_.body_length(input_buffer_.size()); input_buffer_.sgetn(write_msg_.body(), input_buffer_.size()); write_msg_.encode_header(); boost::asio::async_write(socket_, boost::asio::buffer(write_msg_.data(), write_msg_.length()), boost::bind(&posix_chat_client::handle_write, this, boost::asio::placeholders::error)); } else { close(); } } void handle_write(const boost::system::error_code& error) { if (!error) { // Read a line of input entered by the user. boost::asio::async_read_until(input_, input_buffer_, '\n', boost::bind(&posix_chat_client::handle_read_input, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } else { close(); } } void close() { // Cancel all outstanding asynchronous operations. socket_.close(); input_.close(); output_.close(); } private: tcp::socket socket_; posix::stream_descriptor input_; posix::stream_descriptor output_; chat_message read_msg_; chat_message write_msg_; boost::asio::streambuf input_buffer_; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: posix_chat_client <host> <port>\n"; return 1; } boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(argv[1], argv[2]); tcp::resolver::iterator iterator = resolver.resolve(query); posix_chat_client c(io_service, iterator); io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } #else // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
[ "metrix@Blended.(none)" ]
[ [ [ 1, 217 ] ] ]
6e67975d1a038dfdaafc5b5453ff3863a99d17b2
44e10950b3bf454080553a5da36bf263e6a62f8f
/depends/include/Totem/PropertyList.h
126ae47687b0315a6d0fb7a86565435d2034943b
[]
no_license
ptrefall/ste6246tradingagent
a515d88683bf5f55f862c0b3e539ad6144a260bb
89c8e5667aec4c74aef3ffe47f19eb4a1b17b318
refs/heads/master
2020-05-18T03:50:47.216489
2011-12-20T19:02:32
2011-12-20T19:02:32
32,448,454
1
0
null
null
null
null
ISO-8859-15
C++
false
false
15,293
h
#pragma once /** * @file * @class Totem::PropertyListData * * @author Pål Trefall * @author Kenneth Gangstø * * @version 2.0 * * @brief Property List Data implementation class * * @section LICENSE * 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. * * Note: Some of the libraries Totem EDK may link to may have additional * requirements or restrictions. * * @section DESCRIPTION * PropertyListData * */ #include <Totem/IPropertyList.h> #include <Totem/IPropertySerializer.h> namespace Totem { template<class T> class PropertyListData HAS_SIGNALSLOTS_INHERITANCE_TYPE { public: /** * Destructor */ ~PropertyListData() {} /// Actual list data of the property list. typename T_Vector<T>::Type value; /// Name of the property list. T_String name; /// Is the property read-only? bool readOnly; /// Signal that's emitted when a value in the property list change, returning the index that was changed, plus the old and new value. typename T_Signal_v3<const U32&, const T&, const T&>::Type valueChanged; /// Signal that's emitted when a value is added to the property list, passing the new value with the signal along with the index. typename T_Signal_v2<const U32&, const T&>::Type valueAdded; /// Signal that's emitted when a value is erased from the property list, passing the erased value with the signal along with the index. typename T_Signal_v2<const U32&, const T&>::Type valueErased; /// Signal that's emitted when the values of the property list is cleared. typename T_Signal_v0<>::Type valuesCleared; /// Signal that's emitted when the size of the property list is resized to a given value typename T_Signal_v1<const U32&>::Type listResized; }; /** * @file * @class Totem::PropertyListIndexValue * * @author Pål Trefall * @author Kenneth Gangstø * * @version 2.0 * * @brief Property List Index Value, returned by list to allow changing an index in the list safely. * * @section LICENSE * 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. * * Note: Some of the libraries Totem EDK may link to may have additional * requirements or restrictions. * * @section DESCRIPTION * PropertyListIndexValue * */ template<class T> class PropertyListIndexValue { public: /** * Constructor */ PropertyListIndexValue(typename T_SharedPtr< PropertyListData<T> >::Type data, const U32 &index) : data(data), index(index) { } /** * Destructor */ ~PropertyListIndexValue() {} /** * Returns the real value of the PropertyListValue * * @return Returns the real value of the PropertyListValue. */ const T &get() const { return data->value[index]; } /// Set's property list value's data to rhs' shared pointer data. void set(const T& rhs); /// Set's property list value's data to rhs' shared pointer data. void operator= (const T& rhs); /// Provide an assignment operator to leviate level W4 warning PropertyListIndexValue<T> &operator= (const PropertyListIndexValue<T> &rhs); /// Instead of propertyListValue.get() this operator exist for convenience. operator const T &() const { return get(); } private: /// PropertyListData of the Property list is stored inside a shared pointer. typename T_SharedPtr< PropertyListData<T> >::Type data; /// The index in the Property list's data value that this PropertyListIndexValueBool represent. const U32 &index; }; template<class T> inline void PropertyListIndexValue<T>::set(const T &rhs) { T oldValue = data->value[index]; data->value[index] = rhs; data->valueChanged.invoke(index, oldValue, data->value[index]); } template<class T> inline void PropertyListIndexValue<T>::operator =(const T &rhs) { set(rhs); } template<class T> inline PropertyListIndexValue<T> &PropertyListIndexValue<T>::operator= (const PropertyListIndexValue<T> &rhs) { if(this == &rhs) return *this; throw T_Exception("Assignment operation between property list index values are not supported!"); } /** * @file * @class Totem::PropertyList * * @author Pål Trefall * @author Kenneth Gangstø * * @version 2.0 * * @brief Property List implementation class * * @section LICENSE * 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. * * Note: Some of the libraries Totem EDK may link to may have additional * requirements or restrictions. * * @section DESCRIPTION * PropertyList * RTTI implementation was originally contributed by 'zerotri'. * */ template<class T> class PropertyList : public IPropertyList { public: /** * Default Constructor, results in a PropertyList with no data! */ PropertyList() { type = getType<T>(); } /** * Copy Constructor */ PropertyList(const PropertyList& copy) : data(copy.data) { type = getType<T>(); } /** * Constructor * * @param name Name of the property list. * @param readOnly Should the property list be read only? (Defaults to false). */ PropertyList(const T_String &name, bool readOnly = false) : data(new PropertyListData<T>()) { data->name = name; data->readOnly = readOnly; type = getType<T>(); } /** * Destructor */ virtual ~PropertyList() {} /** * Push back a value to the property list. Handles pushing onto the actual PropertyData.value, * plus invoke the valueAdded signal. This also enforces the readOnly flag, which * can only be bypassed by passing in forced = true. * * @param value The new value to add to the property list. * @param forced If this property list is read-only, setting this parameter to true will bypass the read-only rule. * @param duplicationGuard Whether the PropertyList should make an effort to guard against duplicate entires, defaults to false. */ void push_back(const T& value, bool forced = false, bool duplicationGuard = false) { if(data->readOnly && !forced) throw T_Exception(("PropertyList " + data->name + " is read-only!").c_str()); if(duplicationGuard) { for(U32 i = 0; i < data->value.size(); i++) { if(data->value[i] == value) return; } } data->value.push_back(value); data->valueAdded.invoke((U32)data->value.size()-1, value); } /** * Erase a value from the property list. Handles erasing from the actual PropertyData.value, * plus invoke the valueErased signal. This also enforces the readOnly flag, which * can only be bypassed by passing in forced = true. * * @param index The index to erase from the property list. * @param forced If this property list is read-only, setting this parameter to true will bypass the read-only rule. */ void erase(const U32 &index, bool forced = false) { if(data->readOnly && !forced) throw T_Exception(("PropertyList " + data->name + " is read-only!").c_str()); if(index >= data->value.size()) return; T value = data->value[index]; data->value.erase(data->value.begin()+index); data->valueErased.invoke(index, value); } /** * Clear all values from the property list. Handles clearing all values from the actual PropertyData.value, * plus invoke the valuesCleared signal. This also enforces the readOnly flag, which * can only be bypassed by passing in forced = true. * * @param forced If this property list is read-only, setting this parameter to true will bypass the read-only rule. */ void clear(bool forced = false) { if(data->readOnly && !forced) throw T_Exception(("PropertyList " + data->name + " is read-only!").c_str()); data->value.clear(); data->valuesCleared.invoke(); } /** * Get the number of values in the property list. * * @return Returns the number of values in the property list. */ U32 size() const { return (U32)data->value.size(); } /** * Check if the property list is empty. * * @return Returns true if list is empty, false if it has values. */ bool empty() const { return data->value.empty(); } /** * Resize the size of the list. * * @param size Sets the size of the list. */ void resize(const U32 &size) { data->value.resize(size); data->listResized.invoke(size); } /** * Resize the size of the list. * * @param size Sets the size of the list. * @param value Fills list with this initial value */ void resize(const U32 &size, const T &value) { data->value.resize(size, value); data->listResized.invoke(size); } /** * Get the value of list at given index. * * @param index Index in the list for which value is returned */ PropertyListIndexValue<T> at(const U32 &index) { if(index >= data->value.size()) throw T_Exception(("Index was out of bounds for property list " + data->name).c_str()); return PropertyListIndexValue<T>(this->data, index); } /** * Returns the real list data of the PropertyListData value * * @return Returns the real list data of the PropertyListData value. */ const typename T_Vector<T>::Type &get() const { return data->value; } /** * Get the interface of this property list. * * @return Returns the property list interface of this property list. */ IPropertyList *getInterface() { return static_cast<IPropertyList*>(this); } /** * Get the name of this property list. * * @return Returns the name of this property list. */ virtual const T_String &getName() const { return data->name; } /** * Check whether the PropertyListData is valid. * * @return Returns true if data does not exist, false if it does. */ virtual bool isNull() const { return data == NULL_PTR; } /** * Call this function to serialize the value of the property list into a string. * @param serializer The serializer to use for serialization. * @return Returns the serialized string value of this property list. */ virtual T_String toString(IPropertySerializer &serializer) { return serializer.toString(this); } /** * Call this function to deserialize a value from the string. * @param serialized_propertyList The serialized string to deserialize. * @param serializer The serializer to use for deserialization. */ virtual void fromString(const T_String &serialized_propertyList, IPropertySerializer &serializer) { serializer.fromString(this, serialized_propertyList); } /** * Function that gives the outside access to the PropertyListData's * valueChanged signal. It's through this function call we can * register slots to the valueChanged signal. * * @return Returns the valueChanged signal of this property list's PropertyListData. */ typename T_Signal_v3<const U32&, const T&, const T&>::Type &valueChanged() { return data->valueChanged; } /** * Function that gives the outside access to the PropertyListData's * valueAdded signal. It's through this function call we can * register slots to the valueAdded signal. * * @return Returns the valueAdded signal of this property list's PropertyListData. */ typename T_Signal_v2<const U32&, const T&>::Type &valueAdded() { return data->valueAdded; } /** * Function that gives the outside access to the PropertyListData's * valueErased signal. It's through this function call we can * register slots to the valueErased signal. * * @return Returns the valueErased signal of this property list's PropertyListData. */ typename T_Signal_v2<const U32&, const T&>::Type &valueErased() { return data->valueErased; } /** * Function that gives the outside access to the PropertyListData's * valuesCleared signal. It's through this function call we can * register slots to the valuesCleared signal. * * @return Returns the valueCleared signal of this property list's PropertyListData. */ typename T_Signal_v0<>::Type &valuesCleared() { return data->valuesCleared; } /// Set's property list's data to rhs' shared pointer data. PropertyList<T> operator= (const PropertyList<T>& rhs); /// Get the value of list at given index. PropertyListIndexValue<T> operator[] (const U32& index); /// Instead of propertyList.get() this operator exist for convenience. operator const typename T_Vector<T>::Type &() const { return data->value; } private: /// PropertyListData of the Property list is stored inside a shared pointer. typename T_SharedPtr< PropertyListData<T> >::Type data; }; template<class T> inline PropertyList<T> PropertyList<T>::operator =(const PropertyList<T> &rhs) { data = rhs.data; return *this; } template<class T> inline PropertyListIndexValue<T> PropertyList<T>::operator [](const U32 &index) { return at(index); } } //namespace Totem
[ "[email protected]@92bc644c-bee7-7203-82ab-e16328aa9dbe" ]
[ [ [ 1, 472 ] ] ]
577c1e7009451e2619a24fe12a34a19032114d7f
9e79b20463b122df1d83a1e394f54689a949fb4e
/examples/RS485TXTest/HardwareSerialRS485.cpp
bdd727a95b92fb0e324fbdc229619c158be734f4
[]
no_license
michaelvandam/mojoduino
4870c522b7be77a33cb19d1a6448dbee9ca9c148
57233cadde626b5b9a7accf941d78470ebe17000
refs/heads/master
2021-01-02T22:51:23.392713
2010-10-23T01:45:30
2010-10-23T01:45:30
32,952,233
0
0
null
null
null
null
UTF-8
C++
false
false
2,182
cpp
#include <stdio.h> #include <string.h> #include <inttypes.h> #include "wiring.h" #include "wiring_private.h" #include "HardwareSerial.h" #include "HardwareSerialRS485.h" HardwareSerialRS485::HardwareSerialRS485(ring_buffer *rx_buffer, volatile uint8_t *ubrrh, volatile uint8_t *ubrrl, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *udr, uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udre, uint8_t u2x, uint8_t txc): HardwareSerial(rx_buffer, ubrrh, ubrrl, ucsra, ucsrb, udr, rxen, txen, rxcie,udre,u2x) { _txc = txc; } void HardwareSerialRS485::write(const char *str) { digitalWrite(_pin,HIGH); while (*str) write(*str++); //while (( *_ucsra & (1<<_udre))==0 ); while(!(*_ucsra & (1 << _txc))); //delayMicroseconds(5000); digitalWrite(_pin,LOW); } //default implementation: may be overridden void HardwareSerialRS485::write(const uint8_t *buffer, size_t size) { digitalWrite(_pin,HIGH); while (size--) write(*buffer++); while ((*_ucsra & (1 << _txc)) == 0) {}; digitalWrite(_pin,LOW); } void HardwareSerialRS485::setControlPin(int pin) { _pin = pin; pinMode(_pin,OUTPUT); digitalWrite(_pin,LOW); } void HardwareSerialRS485::begin(long baud, int pin) { HardwareSerial::begin(baud); _pin = pin; pinMode(_pin,OUTPUT); digitalWrite(_pin,LOW); } // Preinstantiate Objects ////////////////////////////////////////////////////// #if defined(__AVR_ATmega8__) HardwareSerialRS485 SerialRS485(&rx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRE, U2X,TXC); #else HardwareSerialRS485 SerialRS485(&rx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRE0, U2X0, TXC0); #endif #if defined(__AVR_ATmega1280__) HardwareSerialRS485 Serial1RS485(&rx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRE1, U2X1, TXC1); HardwareSerialRS485 Serial2RS485(&rx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRE2, U2X2, TXC2); HardwareSerialRS485 Serial3RS485(&rx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRE3, U2X3, TXC3); #endif
[ "henry.herman@2cfd8b6e-c46e-11de-b12b-e93134c88cf6" ]
[ [ [ 1, 77 ] ] ]
7d8d65e2d2799b7fdb07ace982abd915554929d6
105cc69f4207a288be06fd7af7633787c3f3efb5
/HovercraftUniverse/HovercraftUniverse/CheckpointEvent.h
7512b837e870eec65043ed0c753df8508e0394a6
[]
no_license
allenjacksonmaxplayio/uhasseltaacgua
330a6f2751e1d6675d1cf484ea2db0a923c9cdd0
ad54e9aa3ad841b8fc30682bd281c790a997478d
refs/heads/master
2020-12-24T21:21:28.075897
2010-06-09T18:05:23
2010-06-09T18:05:23
56,725,792
0
0
null
null
null
null
UTF-8
C++
false
false
1,755
h
#ifndef CHECKPOINTEVENT_H #define CHECKPOINTEVENT_H #include "GameEvent.h" namespace HovUni { /** * Event that indicates that a player has reached a checkpoint at a certain timestamp * * @author Olivier Berghmans */ class CheckpointEvent: public GameEvent { private: /** The ID of the user */ unsigned int mUser; /** The ID of the checkpoint */ unsigned int mCheckpoint; /** The timestamp at the checkpoint */ long mTimestamp; public: /** * Constructor * * @param user the ID of the user * @param checkpoint the ID of the checkpoint * @param time the timestamp at the checkpiont */ CheckpointEvent(unsigned int user, unsigned int checkpoint, long time); /** * Default constructor for event construction */ CheckpointEvent(); /** * Destructor */ ~CheckpointEvent(); /** * Get the ID of the user * * @return the ID */ unsigned int getUser() const { return mUser; } /** * Get the ID of the checkpoint * * @return the ID */ unsigned int getCheckpoint() const { return mCheckpoint; } /** * Get the timestamp at the checkpoint * * @return the timestamp */ long getTimestamp() const { return mTimestamp; } //Network functionality /** * Write the event to a bitstream * * @param stream the stream to write to */ void write(ZCom_BitStream* stream) const; /** * Read the event from a bitstream * * @param stream the stream to read from */ void read(ZCom_BitStream* stream); /** * Parse the event from a stream * * @param stream the stream to parse from * @param the event */ static CheckpointEvent* parse(ZCom_BitStream* stream); }; } #endif
[ "berghmans.olivier@2d55a33c-0a8f-11df-aac0-2d4c26e34a4c" ]
[ [ [ 1, 98 ] ] ]
d8e79c2fe1d769fbaea64d1423bad3590702504f
faaac39c2cc373003406ab2ac4f5363de07a6aae
/ zenithprime/src/math/Vector2.cpp
209e6e63b8c8c1129b6c4b3f855b640aeac62dd5
[]
no_license
mgq812/zenithprime
595625f2ec86879eb5d0df4613ba41a10e3158c0
3c8ff4a46fb8837e13773e45f23974943a467a6f
refs/heads/master
2021-01-20T06:57:05.754430
2011-02-05T17:20:19
2011-02-05T17:20:19
32,297,284
0
0
null
null
null
null
UTF-8
C++
false
false
87
cpp
#include "Vector2.h" Vector2::Vector2(void) { } Vector2::~Vector2(void) { }
[ "mhsmith01@2c223db4-e1a0-a0c7-f360-d8b483a75394" ]
[ [ [ 1, 9 ] ] ]
c0da3e6b6d26cd90cefe9f45d2ec3daf7e789fe0
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Animation/Animation/Ik/FootPlacement/hkaFootPlacementIkSolver.h
bc01012552b88a3f3fbc6cebd12329e1357f8ce2
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
13,930
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef INC_HKA_FOOTPLACEMENT_H #define INC_HKA_FOOTPLACEMENT_H class hkaSkeleton; class hkaPose; /// This interface class defines a single method, castRay(), and it's used by the hkaFootPlacementIkSolver object to cast rays /// into the application's world. If you are using Havok Physics, you can use the optimized ray cast functionality provided there, /// including the ability to filter objects, etc.. or otherwise you can wrap your custom ray casting functionality with this interface. class hkaRaycastInterface { public: virtual ~hkaRaycastInterface() { } /// Abstract method, should be implemented by the user in a derived class. Given two points, "from" and "to", specified in /// world space, it should return whether a ray between those two points intersects the scene or not. If it does (if it returns true), /// the hitFractionOut parameter should return a value between (0..1) to specify the point of intersection with the ray (where 0 is the /// start ("from") of the ray and 1 the end ("to") of the ray). Also in that case the parameter normalWSOut should return the normal of /// the surface intersected, in world space. virtual hkBool castRay ( const hkVector4& fromWS, const hkVector4& toWS, hkReal& hitFractionOut, hkVector4& normalWSOut ); /// This interface is used instead of the above if hkaFootPlacementIkSolver::Input::m_useCollisionFilterInfo is true. /// This interface provides a collision filter word that your implementation can use to filter collisions. virtual hkBool castRay ( const hkVector4& fromWS, const hkVector4& toWS, hkUint32 collisionFilterInfo, hkReal& hitFractionOut, hkVector4& normalWSOut ); }; /// The Foot Placement solver tracks changes on the height of the ground. It then modifies the extension of a leg according to the /// original (desired) distance to the ground. It also modifies the orientation of the foot over time /// according to the original (desired) orientation of the foot and the slope of the ground. This original (desired) height and orientation are taken /// from m_originalAnkleTransformMS, part of the Input structure. It also locks and unlocks the feet based on m_footPlantedAnkleHeightInMS. /// This solver, in contrast with the other ik solvers, operates in a stateful manner, i.e., it keeps state between calls, and therefore must be instantiated for /// each leg/lower limb to be solved over time. Because of that, instead of a static solve() method, there is a non-static doFootPlacement() method. /// The solver operates with different sets of data. Setup data is passed on construction, and it contains information about the skeleton, joint/bone /// indices, axis and limits. Alongside a pose, an hkaFootPlacementIkSolver::Input struct is passed on every call to doFootPlacement(), and contains information about /// gains and current location of the model in world, as well as an interface to raycast functionality. An hkaFootPlacementIkSolver::Output struct is /// returned, containing information regarding the amount of fix-up done by the solver in the vertical direction, which can be used by the application /// to update the location of the model (i.e., update the pelvis). class hkaFootPlacementIkSolver : public hkReferencedObject { public: HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_RUNTIME ); /// This struct is passed on construction of an hkaFootPlacementIkSolver, and contains information about /// the structure of the character as well as axis and limits for the joints. struct Setup { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_RUNTIME, hkaFootPlacementIkSolver::Setup ); /* ** Information about the skeleton */ /// Skeleton of the character to which we are applying foot placement const hkaSkeleton* m_skeleton; /// Index of the joint representing the hip (== bone representing the thigh) hkInt16 m_hipIndex; /// Index of the joint representing the knee (== bone representing the calf) hkInt16 m_kneeIndex; /// Index of the joint representing the ankle (== bone representing the foot) hkInt16 m_ankleIndex; /// Axis of rotation of the knee, in local space of the knee hkVector4 m_kneeAxisLS; /// The end of the foot, in the local space of the ankle/foot. If this is 0,0,0 (default), the /// length of the foot won't be considered (only one raycast will be used) hkVector4 m_footEndLS; /* ** Information about the world and model spaces */ /// The UP direction in the world (from ground to sky), in world space hkVector4 m_worldUpDirectionWS; /// The UP direction in the model (from feet to head), in model space hkVector4 m_modelUpDirectionMS; /// The height of the ground where the model was created/animated, in model space. For example, if the root bone of the skeleton /// is the pelvis, then this is the distance pelvis-ground (a negative value). If the root bone of the skeleton is located at the ground, this is 0. hkReal m_originalGroundHeightMS; /* ** Foot planted / raised heights */ /// The height of the ankle below which the foot is considered planted. Used to calculate gains. hkReal m_footPlantedAnkleHeightMS; /// The height of the ankle above which the foot is considered fully raised. Used to calculate gains. hkReal m_footRaisedAnkleHeightMS; /* ** Foot Placement limits (used to clamp the IK results) */ /// Maximum height the ankle can reach (in model space) hkReal m_maxAnkleHeightMS; /// Minimum height the ankle can reach (in model space) hkReal m_minAnkleHeightMS; /// Limit the knee angle (to avoid knee popping artifacts). Default is -1 (180 deg). hkReal m_cosineMaxKneeAngle; /// Limit the hinge angle (to avoid knee artifacts). Default is 1 (0 deg). hkReal m_cosineMinKneeAngle; /* ** Some other internal tweaking values */ /// When ray casting from the foot towards the ground, the (positive) distance, from the foot and in the up direction, where the ray starts. Default is 0.5(m), you may /// want to change this according to the scale of your character hkReal m_raycastDistanceUp; /// When ray casting from the foot towards the ground, the (positive) distance, from the foot and in the down direction, where the ray ends. Default is 0.8(m), you may /// want to change this according to the scale of your character hkReal m_raycastDistanceDown; /// If true, the foot/ankle will be locked and unlocked. bool m_useFootLocking; /// Constructor, sets defaults (mostly to invalid values to enforce proper setup) Setup(); }; /// This structure, passed to each call to doFootPlacement(), alongside the pose, contains information about the /// location of the model in world, the original/desired position(height) and orientation of the foot, and /// an interface to raycast functionality. struct Input { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_RUNTIME, hkaFootPlacementIkSolver::Input ); /// The original position and orientation of the ankle (the one we base the foot placement on) hkQsTransform m_originalAnkleTransformMS; /// The transform that converts from model to world hkQsTransform m_worldFromModel; /// If false, foot placement will be eased out/kept off, otherwise it will be eased in/kept on bool m_footPlacementOn; /// An interface to ray cast functionality. The implementation should only hit objects that the user wants to /// do foot placement on. For example, it may ignore debris objects if the foot is not supposed to land on top of them. hkaRaycastInterface* m_raycastInterface; /* ** GAINS */ /// Gain used when transitioning from foot placement on and off. Default value is 0.2f. hkReal m_onOffGain; /// Gain used when the ground height is increasing (going up). Default value is 1.0f. hkReal m_groundAscendingGain; /// Gain used when the ground height is decreasing (going down). Default value is 1.0f. hkReal m_groundDescendingGain; /// Gain used when the foot is fully planted (as defined in Setup::m_footPlantedAnkleHeightMS). /// Depending on the height of the ankle, a value is interpolated between m_footPlantedGain /// and m_footRaisedGain and then multiplied by the ascending/descending gain to give /// the final gain used. Default (and most common) value is 1.0f. hkReal m_footPlantedGain; /// Gain used when the foot is fully raise (as defined in Setup::m_footRaisedAnkleHeightMS). /// Depending on the height of the ankle, a value is interpolated between m_footPlantedGain /// and m_footRaisedGain and then multiplied by the ascending/descending gain to give /// the final gain used. Default value is 1.0f. hkReal m_footRaisedGain; /// Gain used when the foot becomes unlocked. When the foot goes from being locked to unlocked, /// there can be a gap between the previously locked foot position and the desired position. /// This gain is used to smoothly transition to the new foot position. This gain only affects /// the horizontal component of the position, since the other gains take care of vertical /// smoothing. Default value is 1.0f. hkReal m_footUnlockGain; /// If m_useCollisionFilterInfo is true, this member is passed into hkaRaycastInterface::castRay() when performing /// raycasts. You can use this if you want to use the same raycast interface for handling cases with /// different collision properties. hkUint32 m_collisionFilterInfo; /// Whether or not to pass m_collisionFilterInfo into hkaRaycastInterface::castRay(). bool m_useCollisionFilterInfo; /// Constructor. It sets some defaults. Input(); }; /// This structure is filled by the foot placement solver, and contains information that can be used by the /// application logic struct Output { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_ANIM_RUNTIME, hkaFootPlacementIkSolver::Output ); /// A measure of how much displacement was required for the leg to reach its final location. It can /// be used to update the pelvis of the character hkReal m_verticalError; /// True if the foot placement detected ground under the foot bool m_hitSomething; }; /// Constructor. You need an instance of hkaFootPlacementIkSolver for each leg to be solved. The Setup structure contains /// information about the character setup. hkaFootPlacementIkSolver(const Setup& setup); /// Call this method to perform the foot placement (usually every frame). It modifies the pose so the leg is placed at /// a reasonable location given the input and the environment. void doFootPlacement (const Input& input, Output& output, hkaPose& poseInOut); /// This is the same setup data passed on construction. It has been made public should you need to change any /// of the setup values on the fly, although this is uncommon. Setup m_setup; private: /* ** Internal State Data */ // Current weight for the foot placement hkReal m_currentWeight; // Previous ground height, in world space hkReal m_previousGroundHeightWS; // Previous ground normal, in world space hkVector4 m_previousGroundNormalWS; // Previous vertical displacement applied to the foot hkReal m_previousVerticalDisplacement; // Whether the foot is currently locked to the ground or not hkBool m_isFootLocked; // The locked foot/ankle position. hkVector4 m_lockedFootPositionInWS; // The locked position of the end/toes of the foot. hkVector4 m_lockedFootEndPositionInWS; // When unlocking the foot the locked foot position and the new position could be different. The horizontal // component of this difference is stored in m_footUnlokcingOffset when the foot becomes unlocked. This is used // to do blend smoothly from the locked position back to the position dictated by the animation. hkVector4 m_footUnlockingOffset; // Uses two rays to cast the foot into the ground bool castFoot( const Input& input, const hkVector4& footWS, const hkVector4& footEndWS, hkVector4& projectedFootWSOut, hkVector4& groundNormalWSOut ) const; // Cast a ray using the information in the Input. bool castRay( const Input& input, const hkVector4& fromWS, const hkVector4& toWS, hkReal& hitFractionOut, hkVector4& normalWSOut ) const; }; #endif //INC_HKA_FOOTPLACEMENT_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 289 ] ] ]
870a0977c2cace01526582f769794266a985cc2f
1a558ab3eacfc15e68c58744a45ddaa762d81073
/CDReaderCP.h
f6ad8d063a91a992a537951ebd15cc0c0c40e49c
[]
no_license
markessien/discreader
2c1d3c6aaaa42dc233c00a5275464cbd6a37b93c
bd888923c134baf86586cc963845b4657078c653
refs/heads/master
2020-06-08T16:58:08.178715
2010-10-23T12:33:49
2010-10-23T12:33:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,553
h
#ifndef _CDREADERCP_H_ #define _CDREADERCP_H_ template <class T> class CProxy_ICDReaderObjEvents : public IConnectionPointImpl<T, &DIID__ICDReaderObjEvents, CComDynamicUnkArray> { //Warning this class may be recreated by the wizard. public: HRESULT Fire_CDDriveListed(BSTR Name) { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; CComVariant* pvars = new CComVariant[1]; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); pvars[0] = Name; DISPPARAMS disp = { pvars, NULL, 1, 0 }; pDispatch->Invoke(0x1, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } delete[] pvars; return varResult.scode; } HRESULT Fire_TrackListed(BSTR Name, DOUBLE Length) { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; CComVariant* pvars = new CComVariant[2]; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); pvars[1] = Name; pvars[0] = Length; DISPPARAMS disp = { pvars, NULL, 2, 0 }; pDispatch->Invoke(0x2, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } delete[] pvars; return varResult.scode; } HRESULT Fire_CDDBQueryStatusUpdate(BSTR Status) { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; CComVariant* pvars = new CComVariant[1]; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); pvars[0] = Status; DISPPARAMS disp = { pvars, NULL, 1, 0 }; pDispatch->Invoke(0x3, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } delete[] pvars; return varResult.scode; } HRESULT Fire_CDDBCDInfoRetrieved(BSTR Artist, BSTR Title, LONG Genre) { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; CComVariant* pvars = new CComVariant[3]; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); pvars[2] = Artist; pvars[1] = Title; pvars[0] = Genre; DISPPARAMS disp = { pvars, NULL, 3, 0 }; pDispatch->Invoke(0x4, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } delete[] pvars; return varResult.scode; } HRESULT Fire_TrackNameUpdate(LONG Index, BSTR NewName) { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; CComVariant* pvars = new CComVariant[2]; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); pvars[1] = Index; pvars[0] = NewName; DISPPARAMS disp = { pvars, NULL, 2, 0 }; pDispatch->Invoke(0x5, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } delete[] pvars; return varResult.scode; } HRESULT Fire_CDInserted(BSTR DriveLetter) { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; CComVariant* pvars = new CComVariant[1]; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); pvars[0] = DriveLetter; DISPPARAMS disp = { pvars, NULL, 1, 0 }; pDispatch->Invoke(0x6, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } delete[] pvars; return varResult.scode; } HRESULT Fire_CDRemoved(BSTR DriveLetter) { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; CComVariant* pvars = new CComVariant[1]; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); pvars[0] = DriveLetter; DISPPARAMS disp = { pvars, NULL, 1, 0 }; pDispatch->Invoke(0x7, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } delete[] pvars; return varResult.scode; } HRESULT Fire_CDDBServerListed(BSTR Server, BSTR CGI, LONG Port) { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; CComVariant* pvars = new CComVariant[3]; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); pvars[2] = Server; pvars[1] = CGI; pvars[0] = Port; DISPPARAMS disp = { pvars, NULL, 3, 0 }; pDispatch->Invoke(0x8, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } delete[] pvars; return varResult.scode; } HRESULT Fire_CDDBMultipleMatches() { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); DISPPARAMS disp = { NULL, NULL, 0, 0 }; pDispatch->Invoke(0x9, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } return varResult.scode; } HRESULT Fire_CDDBMultipleMatchItem(BSTR Name) { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; CComVariant* pvars = new CComVariant[1]; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); pvars[0] = Name; DISPPARAMS disp = { pvars, NULL, 1, 0 }; pDispatch->Invoke(0xa, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } delete[] pvars; return varResult.scode; } HRESULT Fire_CDDBMultipleMatchNotifyComplete() { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); DISPPARAMS disp = { NULL, NULL, 0, 0 }; pDispatch->Invoke(0xb, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } return varResult.scode; } HRESULT Fire_TrackExtractionComplete(LONG Index) { CComVariant varResult; T* pT = static_cast<T*>(this); int nConnectionIndex; CComVariant* pvars = new CComVariant[1]; int nConnections = m_vec.GetSize(); for (nConnectionIndex = 0; nConnectionIndex < nConnections; nConnectionIndex++) { pT->Lock(); CComPtr<IUnknown> sp = m_vec.GetAt(nConnectionIndex); pT->Unlock(); IDispatch* pDispatch = reinterpret_cast<IDispatch*>(sp.p); if (pDispatch != NULL) { VariantClear(&varResult); pvars[0] = Index; DISPPARAMS disp = { pvars, NULL, 1, 0 }; pDispatch->Invoke(0xc, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &disp, &varResult, NULL, NULL); } } delete[] pvars; return varResult.scode; } }; #endif
[ [ [ 1, 331 ] ] ]
ebce4878864dfd3fa906a51e45fcb060e1c80fc1
3de9e77565881674bf6b785326e85ab6e702715f
/src/math/Matrix.hpp
41b2a025792f09d53b83e8945ebf40f1a0eaade2
[]
no_license
adbrown85/gloop-old
1b7f6deccf16eb4326603a7558660d8875b0b745
8857b528c97cfc1fd57c02f055b94cbde6781aa1
refs/heads/master
2021-01-19T18:07:39.112088
2011-02-27T07:17:14
2011-02-27T07:17:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,468
hpp
/* * Matrix.hpp * * Author * Andrew Brown <[email protected]> */ #ifndef GLOOP_MATRIX_HPP #define GLOOP_MATRIX_HPP #include "gloop_common.h" #include <cmath> #include <iomanip> #include "Vec4.hpp" using namespace std; /** @brief Four-by-four matrix with multiplication and inversion. * @ingroup system */ class Matrix { public: Matrix(); Matrix(float a0, float a1, float a2, float a3, float b0, float b1, float b2, float b3, float c0, float c1, float c2, float c3, float d0, float d1, float d2, float d3); float getDeterminant() const; int getColumns() const; Matrix getInverse() const; int getRows() const; int getSize() const; Matrix getTranspose() const; float& operator()(int i, int j); float operator()(int i, int j) const; friend Matrix operator*(const Matrix &A, const Matrix &B); friend Vec4 operator*(const Matrix &A, const Vec4 &B); void print(); void set(float array[16]); void toArray(float *array); protected: Matrix getSubmatrix(int i, int j) const; float det(int n) const; private: Matrix(int size); float arr[4][4]; int size; }; /** Calculate the determinant of the entire matrix. */ inline float Matrix::getDeterminant() const {return det(size);} /** @return the number of columns */ inline int Matrix::getColumns() const {return size;} /** @return the number of rows. */ inline int Matrix::getRows() const {return size;} #endif
[ [ [ 1, 2 ], [ 4, 4 ], [ 6, 6 ], [ 10, 11 ], [ 14, 15 ], [ 18, 19 ], [ 46, 47 ], [ 60, 60 ] ], [ [ 3, 3 ], [ 5, 5 ], [ 13, 13 ], [ 50, 50 ], [ 53, 53 ], [ 56, 59 ] ], [ [ 7, 9 ], [ 12, 12 ], [ 16, 17 ], [ 20, 45 ], [ 48, 49 ], [ 51, 52 ], [ 54, 55 ] ] ]
bfe49d8eec7e578d7da51e9c2eddbcd2bdd6aadf
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/vis/properties/vis_property_stack_base.cpp
515374d33ba2926421115f9e65f213bfd77916d8
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,774
cpp
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) ** ** and SWARMS (www.swarms.de) ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the GNU General Public License, version 2. ** ************************************************************************/ #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_VIS #include "apps/vis/properties/vis_property_stack_base.h" #include "apps/vis/properties/vis_property_stack.h" #include <sstream> namespace vis { PropertyStackBase:: PropertyStackBase() {} // ---------------------------------------------------------------------- PropertyStackBase:: ~PropertyStackBase() {} // ---------------------------------------------------------------------- std::string PropertyStackBase:: error_no_property( double t ) throw() { std::ostringstream oss; oss << "no property is active at time " << t; return oss.str(); } PropertyStack<int> TEST_REMOVE; } #endif /*----------------------------------------------------------------------- * Source $Source: /cvs/shawn/shawn/tubsapps/vis/properties/vis_property_stack_base.cpp,v $ * Version $Revision: 1.1 $ * Date $Date: 2006/01/29 21:02:01 $ *----------------------------------------------------------------------- * $Log: vis_property_stack_base.cpp,v $ * Revision 1.1 2006/01/29 21:02:01 ali * began vis * *-----------------------------------------------------------------------*/
[ [ [ 1, 51 ] ] ]
7f5796001af0ecfcd485ea4c5c22ccfec3185a85
4497c10f3b01b7ff259f3eb45d0c094c81337db6
/Retargeting/Shifmap/Version01/HierarchyFHShiftMap.h
c95d497f55bfb9ee7444ae4c723b76944880adf3
[]
no_license
liuguoyou/retarget-toolkit
ebda70ad13ab03a003b52bddce0313f0feb4b0d6
d2d94653b66ea3d4fa4861e1bd8313b93cf4877a
refs/heads/master
2020-12-28T21:39:38.350998
2010-12-23T16:16:59
2010-12-23T16:16:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,269
h
#pragma once #include "FillHoleShiftMap.h" #include "HierarchyFHEnergyFunction.h" #include "MaskShift.h" #include "highgui.h" class HierarchyFHShiftMap : public FillHoleShiftMap { public: HierarchyFHShiftMap(void); ~HierarchyFHShiftMap(void); // better version of ComputeFastShiftMap // mask is of the same size with input & maskData will be auto-generated virtual void ComputeFastShiftMap2(IplImage* input, IplImage* saliency, IplImage* mask, CvPoint shift, CvSize outputSize); virtual void ComputeFastShiftMap(IplImage* input, IplImage* saliency); IplImage* GetRetargetedImage(int level); int GetLevelCount(); protected: vector<IplImage*>* _maskList; vector<IplImage*>* _maskDataList; vector<IplImage*>* _inputList; vector<IplImage*>* _saliencyList; vector<CvMat*>* _labelMapList; vector<vector<CvPoint*>*>* _pointMappingList; public: virtual void ComputeShiftMapGuess(IplImage* input, IplImage* saliency, CvMat* guess, CvSize output, CvSize shiftSize); vector<CvPoint*>* InterpolatePointMapping(vector<CvPoint*>* pointMapping); // interpolate the shift map from down 1 level void InterpolateShiftMapping(CvMat* lowerMap, CvMat* higherMap); // new version interpolate the shift map from down 1 level void InterpolateShiftMapping(CvMat* lowerMap, CvMat* higherMap, IplImage* lowerMask, IplImage* higherMask); // downsampling an image, if size = 0, no blurring is done void DownSampling(IplImage* source, IplImage* dst, int size); // downsampling until the widht < limitedSize void DownSamplingImage(IplImage* input, vector<IplImage*>* list, int limitedSize, int blurSize); void DownSamplingMask(IplImage* higherMask, IplImage* lowerMask); void DownSamplingMask(IplImage* mask, vector<IplImage*>* list, int limitedSize); void DownSamplingInput(IplImage* input, IplImage* saliency, IplImage* mask, IplImage* maskData); // better version of down sampling input // mask is the same size as input & maskData will be auto-generated void DownSamplingInput(IplImage* input, IplImage* saliency, IplImage* mask, CvSize outputSize, CvPoint shift); CvMat* CalculateLabelMapGuess(CvMat* intialGuess, vector<CvPoint*>* pointMapping, GCoptimizationGeneralGraph* gc); void ClearGC(); };
[ "kidphys@aeedd7dc-6096-11de-8dc1-e798e446b60a" ]
[ [ [ 1, 51 ] ] ]
3b63eff1220be6d6ae0f9a94a4efbef3fb2bdb9d
89147ec4f5c9a5cf4ad59c83517da2179a2f040e
/bottom2/io.cpp
612f063d64919dcc7f5e817607f190bcd47e8b68
[]
no_license
swarnaprakash/my-acm-problemset
3f977867a6637a28b486021634e30efabe30ef52
e07654590c2691839b01291e5237082971b8cc85
refs/heads/master
2016-09-05T10:39:59.726651
2011-09-04T15:01:01
2011-09-04T15:01:01
2,323,366
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
#include<iostream> #include<cstdlib> using namespace std; main() { int i,j; for(i=0;i<1<<4;++i) { cout<<"4"<<endl; for(j=0;j<4;++j) { cout<<"A"<<" "; if(i&(1<<j)) cout<<"+"<<endl; else cout<<"-"<<endl; } } for(i=0;i<10;++i) { cout<<"100"<<endl; for(j=0;j<100;++j) { cout<<(char)(rand()%10+'a')<<" "; if(j%2) cout<<"+"<<endl; else cout<<"-"<<endl; } } return 0; }
[ [ [ 1, 40 ] ] ]
e755ee0b3cc09aa55795dee77e9e4db71e3a1834
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/BaseMenu.cpp
507e8d2f1bc61bfa9067912b6a3e242caefa86ae
[]
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
9,323
cpp
// ----------------------------------------------------------------------- // // // MODULE : BaseMenu.cpp // // PURPOSE : Base class for in-game menus // // (c) 2001 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "BaseMenu.h" #include "InterfaceMgr.h" ///////////////////////////////////////////////////////////////////////////// // SubMenu members ///////////////////////////////////////////////////////////////////////////// CSubMenu::CSubMenu() { m_hFrame = NULL; m_hFrameTip = NULL; } LTBOOL CSubMenu::Init(HTEXTURE hFrame,HTEXTURE hFrameTip, LTIntPt size) { m_hFrame = hFrame; m_hFrameTip = hFrameTip; if (!Create(NULL,size.x,size.y)) return LTFALSE; SetupQuadUVs(m_Poly[0], hFrame, 0.0f, 0.0f, 1.0f, 1.0f); SetupQuadUVs(m_Poly[1], hFrameTip, 0.0f, 0.0f, 1.0f, 1.0f); RotateQuadUVs(m_Poly[1], 1); g_pDrawPrim->SetRGBA(&m_Poly[0],argbWhite); g_pDrawPrim->SetRGBA(&m_Poly[1],argbWhite); return LTTRUE; } LTBOOL CSubMenu::HandleKeyUp (int vkey ) { if (vkey == VK_ESCAPE) { g_pInterfaceMgr->GetMenuMgr()->HideSubMenu(true); return LTTRUE; } return LTFALSE; } // Render the control void CSubMenu::Render ( ) { if (!IsVisible()) return; g_pDrawPrim->SetTransformType(DRAWPRIM_TRANSFORM_SCREEN); g_pDrawPrim->SetZBufferMode(DRAWPRIM_NOZ); g_pDrawPrim->SetClipMode(DRAWPRIM_NOCLIP); g_pDrawPrim->SetFillMode(DRAWPRIM_FILL); g_pDrawPrim->SetColorOp(DRAWPRIM_MODULATE); g_pDrawPrim->SetAlphaTestMode(DRAWPRIM_NOALPHATEST); g_pDrawPrim->SetAlphaBlendMode(DRAWPRIM_BLEND_MOD_SRCALPHA); g_pDrawPrim->SetTexture(m_hFrame); g_pDrawPrim->DrawPrim(&m_Poly[0]); g_pDrawPrim->SetTexture(m_hFrameTip); g_pDrawPrim->DrawPrim(&m_Poly[1]); CLTGUIWindow::Render(); } void CSubMenu::SetBasePos ( LTIntPt pos ) { CLTGUIWindow::SetBasePos(pos); UpdateFrame(); } void CSubMenu::SetScale(float fScale) { CLTGUIWindow::SetScale(fScale); UpdateFrame(); } void CSubMenu::UpdateFrame() { float fx = (float)m_pos.x; float fy = (float)m_pos.y; float fw = (float)m_nWidth * m_fScale * 0.75f; float fh = (float)m_nHeight * m_fScale; g_pDrawPrim->SetXYWH(&m_Poly[0],fx,fy,fw,fh); g_pDrawPrim->SetXYWH(&m_Poly[1],fx+fw,fy,(fh/2.0f),fh); } ///////////////////////////////////////////////////////////////////////////// // BaseMenu members ///////////////////////////////////////////////////////////////////////////// //static members LTIntPt CBaseMenu::s_Size; uint16 CBaseMenu::s_Pos; HTEXTURE CBaseMenu::s_Frame = LTNULL; HTEXTURE CBaseMenu::s_FrameTip = LTNULL; HTEXTURE CBaseMenu::s_Up = LTNULL; HTEXTURE CBaseMenu::s_UpH = LTNULL; HTEXTURE CBaseMenu::s_Down = LTNULL; HTEXTURE CBaseMenu::s_DownH = LTNULL; CBaseMenu::CBaseMenu() { m_MenuID = MENU_ID_NONE; m_SelectedColor = argbWhite; m_NonSelectedColor = argbBlack; m_DisabledColor = argbGray; m_FontSize = 12; m_FontFace = 0; m_TitleFontSize = 0; m_TitleFontFace = 16; } CBaseMenu::~CBaseMenu() { Term(); } LTBOOL CBaseMenu::Init() { if (!s_Frame) { char szTmp[128] = ""; g_pLayoutMgr->GetMenuFrame(szTmp,sizeof(szTmp)); s_Frame = g_pInterfaceResMgr->GetTexture(szTmp); g_pLayoutMgr->GetMenuFrameTip(szTmp,sizeof(szTmp)); s_FrameTip = g_pInterfaceResMgr->GetTexture(szTmp); s_Size = g_pLayoutMgr->GetMenuSize(); s_Pos = g_pLayoutMgr->GetMenuPosition(); g_pLayoutMgr->GetMenuUpArrow(szTmp,sizeof(szTmp)); s_Up = g_pInterfaceResMgr->GetTexture(szTmp); g_pLayoutMgr->GetMenuUpArrowHighlight(szTmp,sizeof(szTmp)); s_UpH = g_pInterfaceResMgr->GetTexture(szTmp); g_pLayoutMgr->GetMenuDownArrow(szTmp,sizeof(szTmp)); s_Down = g_pInterfaceResMgr->GetTexture(szTmp); g_pLayoutMgr->GetMenuDownArrowHighlight(szTmp,sizeof(szTmp)); s_DownH = g_pInterfaceResMgr->GetTexture(szTmp); } m_FontFace = g_pLayoutMgr->GetMenuFontFace(m_MenuID); m_FontSize = g_pLayoutMgr->GetMenuFontSize(m_MenuID); m_TitleFontFace = g_pLayoutMgr->GetMenuTitleFontFace(m_MenuID); m_TitleFontSize = g_pLayoutMgr->GetMenuTitleFontSize(m_MenuID); m_Indent = g_pLayoutMgr->GetMenuIndent(m_MenuID); m_SelectedColor = g_pLayoutMgr->GetMenuSelectedColor(m_MenuID); m_NonSelectedColor = g_pLayoutMgr->GetMenuNonSelectedColor(m_MenuID); m_DisabledColor = g_pLayoutMgr->GetMenuDisabledColor(m_MenuID); if (!Create(NULL,s_Size.x,s_Size.y)) return LTFALSE; SetupQuadUVs(m_Poly[0], s_Frame, 0.0f,0.0f,1.0f,1.0f); SetupQuadUVs(m_Poly[1], s_FrameTip, 0.0f,0.0f,1.0f,1.0f); g_pDrawPrim->SetRGBA(&m_Poly[0],argbWhite); g_pDrawPrim->SetRGBA(&m_Poly[1],argbWhite); LTIntPt pos = m_Indent; CUIFont* pFont = g_pInterfaceResMgr->GetFont(m_TitleFontFace); if (!pFont) return LTFALSE; if (!m_Title.Create("X", LTNULL, LTNULL, pFont, m_TitleFontSize, this)) { return LTFALSE; } m_Title.SetColors(m_NonSelectedColor,m_NonSelectedColor,m_NonSelectedColor); m_Title.Enable(LTFALSE); pos.x = m_Indent.x + 24; CLTGUIWindow::AddControl(&m_Title,pos); m_Title.SetScale(1.0f); pos.x = m_Indent.x; pos.y += (m_Title.GetHeight() + 4); m_Title.SetScale(g_pInterfaceResMgr->GetXRatio()); m_List.Create(s_Size.y - pos.y); uint16 nOffset = (s_Size.x-m_Indent.x*2)-16; m_List.UseArrows(nOffset ,1.0f,s_Up,s_UpH,s_Down,s_DownH); CLTGUIWindow::AddControl(&m_List,pos); m_Resume.Create(LoadTempString(IDS_RESUME),MC_CLOSE,NULL,pFont,m_TitleFontSize,this); pos.x = s_Size.x - m_Indent.x - m_Resume.GetWidth(); pos.y = 12; CLTGUIWindow::AddControl(&m_Resume,pos); pos.x = s_Pos; pos.y = 0; SetBasePos(pos); return LTTRUE; } void CBaseMenu::Term() { CLTGUIWindow::RemoveControl(&m_Title,LTFALSE); m_Title.Destroy(); CLTGUIWindow::RemoveControl(&m_List,LTFALSE); m_List.Destroy(); CLTGUIWindow::RemoveControl(&m_Resume,LTFALSE); m_Resume.Destroy(); Destroy(); } // This is called when the screen gets or loses focus void CBaseMenu::OnFocus(LTBOOL bFocus) { ClearSelection(); m_List.ClearSelection(); if (bFocus) { if (m_fScale != g_pInterfaceResMgr->GetXRatio()) { SetScale(g_pInterfaceResMgr->GetXRatio()); } SetSize(s_Size.x,s_Size.y); SetSelection(GetIndex(&m_List)); } } LTBOOL CBaseMenu::OnUp() { return CLTGUIWindow::OnUp(); } LTBOOL CBaseMenu::OnDown() { return CLTGUIWindow::OnDown(); } LTBOOL CBaseMenu::OnMouseMove(int x, int y) { uint16 listSelect = m_List.GetSelectedIndex( ); LTBOOL bHandled = CLTGUIWindow::OnMouseMove(x,y); if (bHandled || listSelect != m_List.GetSelectedIndex( )) { g_pInterfaceMgr->RequestInterfaceSound(IS_CHANGE); return LTTRUE; } return LTFALSE; } void CBaseMenu::SetTitle (int stringID) { m_Title.SetString(LoadTempString(stringID)); } uint16 CBaseMenu::AddControl (int stringID, uint32 commandID, LTBOOL bStatic) { return AddControl(LoadTempString(stringID),commandID,bStatic); } uint16 CBaseMenu::AddControl (char *pString, uint32 commandID, LTBOOL bStatic) { CUIFont* pFont = g_pInterfaceResMgr->GetFont(m_FontFace); if (!pFont) return -1; CLTGUITextCtrl* pCtrl=debug_new(CLTGUITextCtrl); if (!pCtrl->Create(pString, commandID, LTNULL, pFont, m_FontSize, this)) { debug_delete(pCtrl); return -1; } pCtrl->SetBasePos(m_nextPos); if (bStatic) { pCtrl->SetColors(m_NonSelectedColor,m_NonSelectedColor,m_NonSelectedColor); pCtrl->Enable(LTFALSE); } else pCtrl->SetColors(m_SelectedColor,m_NonSelectedColor,m_DisabledColor); pCtrl->SetScale(g_pInterfaceResMgr->GetXRatio()); return m_List.AddControl(pCtrl); } uint32 CBaseMenu::OnCommand(uint32 nCommand, uint32 nParam1, uint32 nParam2) { switch (nCommand) { case MC_CLOSE: g_pInterfaceMgr->GetMenuMgr()->SlideOut(); break; case MC_LEFT: g_pInterfaceMgr->GetMenuMgr()->PreviousMenu(); break; case MC_RIGHT: g_pInterfaceMgr->GetMenuMgr()->NextMenu(); break; default: return 0; } return 1; } // Render the control void CBaseMenu::Render ( ) { if (!IsVisible()) return; g_pDrawPrim->SetTransformType(DRAWPRIM_TRANSFORM_SCREEN); g_pDrawPrim->SetZBufferMode(DRAWPRIM_NOZ); g_pDrawPrim->SetClipMode(DRAWPRIM_NOCLIP); g_pDrawPrim->SetFillMode(DRAWPRIM_FILL); g_pDrawPrim->SetColorOp(DRAWPRIM_MODULATE); g_pDrawPrim->SetAlphaTestMode(DRAWPRIM_NOALPHATEST); g_pDrawPrim->SetAlphaBlendMode(DRAWPRIM_BLEND_MOD_SRCALPHA); g_pDrawPrim->SetTexture(s_Frame); g_pDrawPrim->DrawPrim(&m_Poly[0]); g_pDrawPrim->SetTexture(s_FrameTip); g_pDrawPrim->DrawPrim(&m_Poly[1]); CLTGUIWindow::Render(); } void CBaseMenu::SetBasePos ( LTIntPt pos ) { CLTGUIWindow::SetBasePos(pos); UpdateFrame(); } void CBaseMenu::SetScale(float fScale) { CLTGUIWindow::SetScale(fScale); UpdateFrame(); } void CBaseMenu::UpdateFrame() { float fx = (float)m_pos.x; float fy = (float)m_pos.y; float fw = (float)m_nWidth * m_fScale; float fh = (float)m_nHeight * m_fScale * 0.75f; g_pDrawPrim->SetXYWH(&m_Poly[0],fx,fy,fw,fh); g_pDrawPrim->SetXYWH(&m_Poly[1],fx,fy+fh,fw,(fw/2.0f)); }
[ [ [ 1, 390 ] ] ]
1cd47f1755c2822ac6088930e92735b94d3d692b
d9d498167237f41a9cf47f4ec2d444a49da4b23b
/zhangxin/example/RemindDlg.cpp
e5e4677681a8b400cfc8a2912796e8d84626b418
[]
no_license
wangluyi1982/piggypic
d81cf15a6b58bbb5a9cde3d124333348419c9663
d173e3acc6c3e57267733fb7b80b1b07cb21fa01
refs/heads/master
2021-01-10T20:13:42.615324
2010-03-17T13:44:49
2010-03-17T13:44:49
32,907,995
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,030
cpp
// RemindDlg.cpp : インプリメンテーション ファイル // #include "stdafx.h" #include "NECTestPattern.h" #include "RemindDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CRemindDlg ダイアログ CRemindDlg::CRemindDlg(CWnd* pParent /*=NULL*/) : CDialog(CRemindDlg::IDD, pParent) { //{{AFX_DATA_INIT(CRemindDlg) m_Check = FALSE; //}}AFX_DATA_INIT } void CRemindDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CRemindDlg) DDX_Check(pDX, IDC_CHECK_SHOW, m_Check); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CRemindDlg, CDialog) //{{AFX_MSG_MAP(CRemindDlg) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CRemindDlg メッセージ ハンドラ void CRemindDlg::OnOK() { } void CRemindDlg::OnCancel() { }
[ "zhangxin.sanjin@fa8d6de2-2387-11df-88d9-3f628f631586" ]
[ [ [ 1, 52 ] ] ]
1ca1dab2ea3a2ead3c0e664f5d8c8175dd4470e1
55196303f36aa20da255031a8f115b6af83e7d11
/private/external/gameswf/gameswf/gameswf_disasm.cpp
1bf257420142a78092a02a3ff261b32751e5dd2d
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
26,163
cpp
// gameswf_disasm.cpp -- Thatcher Ulrich <[email protected]> 2003 // This source code has been donated to the Public Domain. Do // whatever you want with it. // // Disassembler // #include "gameswf/gameswf_disasm.h" #include "gameswf/gameswf_log.h" #include <stdarg.h> namespace gameswf { #define COMPILE_DISASM 1 #ifndef COMPILE_DISASM void log_disasm(const unsigned char* instruction_data) // No disassembler in this version... { log_msg("<no disasm>\n"); } #else // COMPILE_DISASM // // Action Script 3.0 // enum arg_format_avm2 { ARG_END=0, ARG_MULTINAME, ARG_NAMESPACE, ARG_BYTE, ARG_SHORT, ARG_INT, ARG_UINT, ARG_DOUBLE, ARG_STRING, ARG_COUNT, ARG_CLASSINFO, ARG_FUNCTION, ARG_EXCEPTION, ARG_REGISTER, ARG_SLOTINDEX, ARG_OFFSET, ARG_OFFSETLIST, }; int read_vu30( int& result, const uint8 *args ) { result = args[0]; if ((result & 0x00000080) == 0) { return 1; } result = (result & 0x0000007F) | args[1] << 7; if ((result & 0x00004000) == 0) { return 2; } result = (result & 0x00003FFF) | args[2] << 14; if ((result & 0x00200000) == 0) { return 3; } result = (result & 0x001FFFFF) | args[3] << 21; if ((result & 0x10000000) == 0) { return 4; } result = (result & 0x0FFFFFFF) | args[4] << 28; return 5; } struct inst_info_avm2 { const char* m_instruction; array<arg_format_avm2> m_arg_formats; inst_info_avm2(const char* opname) : m_instruction(opname) { } inst_info_avm2(const char* opname, const arg_format_avm2 arg_format_0, ...) : m_instruction(opname) { va_list arg; m_arg_formats.push_back( arg_format_0 ); va_start( arg, arg_format_0 ); arg_format_avm2 current_format; while( ( current_format = va_arg( arg, arg_format_avm2) ) != ARG_END ) { m_arg_formats.push_back( current_format ); } } int process(const abc_def* def, const uint8 *args) { int byte_count = 1; for( int i=0; i<m_arg_formats.size();++i) { int value; switch( m_arg_formats[i] ) { case ARG_MULTINAME: byte_count += read_vu30(value, &args[byte_count]); if( value >= def->m_multiname.size() ) { log_msg( "\t\tmultiname: runtime %i\n", value); } else { log_msg( "\t\tmultiname: %s\n", def->m_string[def->m_multiname[value].m_name].c_str()); } break; case ARG_NAMESPACE: byte_count += read_vu30(value, &args[byte_count]); log_msg( "\t\tnamespace: %s\n", def->m_string[ def->m_namespace[value].m_name ].c_str()); break; case ARG_BYTE: value = args[byte_count]; log_msg("\t\tvalue: %i\n", value); byte_count++; break; case ARG_SHORT: byte_count += read_vu30(value, &args[byte_count]); log_msg("\t\tvalue: %i\n", value); break; case ARG_INT: byte_count += read_vu30(value, &args[byte_count]); log_msg("\t\tvalue: %i\n", def->m_integer[value]); break; case ARG_UINT: byte_count += read_vu30(value, &args[byte_count]); log_msg("\t\tvalue: %ui\n", def->m_uinteger[value]); break; case ARG_DOUBLE: byte_count += read_vu30(value, &args[byte_count]); log_msg("\t\tvalue: %d\n", def->m_double[value]); break; case ARG_STRING: byte_count += read_vu30(value, &args[byte_count]); log_msg( "\t\tstring: %s\n", def->m_string[value].c_str()); break; case ARG_COUNT: byte_count += read_vu30(value, &args[byte_count]); log_msg( "\t\tcount: %i\n", value); break; case ARG_CLASSINFO: byte_count += read_vu30(value, &args[byte_count]); log_msg( "\t\tclass: %i\n", value); break; case ARG_FUNCTION: byte_count += read_vu30( value, &args[byte_count] ); //TODO: print signature log_msg( "\t\tfunction: %s\n", def->m_string[def->m_method[value]->m_name].c_str()); break; case ARG_EXCEPTION: byte_count += read_vu30( value, &args[byte_count] ); //TODO: print exception info log_msg( "\t\texception: %i\n", value); break; case ARG_REGISTER: byte_count += read_vu30( value, &args[byte_count] ); log_msg( "\t\tregister: %i\n", value); break; case ARG_SLOTINDEX: byte_count += read_vu30( value, &args[byte_count] ); log_msg( "\t\tslot index: %i\n", value); break; case ARG_OFFSET: value = args[byte_count] | args[byte_count+1]<<8 | args[byte_count+2]<<16; byte_count += 3; log_msg( "\t\toffset: %i\n", value); break; case ARG_OFFSETLIST: value = args[byte_count] | args[byte_count+1]<<8 | (*(int8*)&args[byte_count+2])<<16; //sign extend the high byte log_msg( "\t\tdefault offset: %i\n", value); byte_count += 3; int offset_count; byte_count += read_vu30( offset_count, &args[byte_count] ); for(int i=0;i<offset_count+1;i++) { value = args[byte_count] | args[byte_count+1]<<8 | (*(int8*)&args[byte_count+2])<<16; log_msg("\t\toffset %i: %i\n", i, value); byte_count +=3; } break; } } return byte_count; } bool has_argument() const { return m_arg_formats.size() != 0;} }; static hash<int, inst_info_avm2> s_instr; // it's called on exit from player void clear_disasm() { s_instr.clear(); } void log_disasm_avm2(const membuf& data, const abc_def* def) // Disassemble one instruction to the log, AVM2 { if (s_instr.size() == 0) { s_instr.add(0x03, inst_info_avm2("throw")); s_instr.add(0x04, inst_info_avm2("getsuper", ARG_MULTINAME, ARG_END )); s_instr.add(0x05, inst_info_avm2("setsuper" )); s_instr.add(0x06, inst_info_avm2("dxns")); s_instr.add(0x07, inst_info_avm2("dxnslate")); s_instr.add(0x08, inst_info_avm2("kill", ARG_REGISTER, ARG_END)); s_instr.add(0x09, inst_info_avm2("label")); // no inst for 0x0A, 0x0B s_instr.add(0x0C, inst_info_avm2("ifnlt", ARG_OFFSET, ARG_END)); s_instr.add(0x0D, inst_info_avm2("ifnle", ARG_OFFSET, ARG_END)); s_instr.add(0x0E, inst_info_avm2("ifngt", ARG_OFFSET, ARG_END)); s_instr.add(0x0F, inst_info_avm2("ifnge", ARG_OFFSET, ARG_END)); s_instr.add(0x10, inst_info_avm2("jump", ARG_OFFSET, ARG_END)); s_instr.add(0x11, inst_info_avm2("iftrue", ARG_OFFSET, ARG_END)); s_instr.add(0x12, inst_info_avm2("iffalse", ARG_OFFSET, ARG_END)); s_instr.add(0x13, inst_info_avm2("ifeq", ARG_OFFSET, ARG_END)); s_instr.add(0x14, inst_info_avm2("ifne", ARG_OFFSET, ARG_END)); s_instr.add(0x15, inst_info_avm2("iflt", ARG_OFFSET, ARG_END)); s_instr.add(0x16, inst_info_avm2("ifle", ARG_OFFSET, ARG_END)); s_instr.add(0x17, inst_info_avm2("ifgt", ARG_OFFSET, ARG_END)); s_instr.add(0x18, inst_info_avm2("ifge", ARG_OFFSET, ARG_END)); s_instr.add(0x19, inst_info_avm2("ifstricteq", ARG_OFFSET, ARG_END)); s_instr.add(0x1A, inst_info_avm2("ifstrictne", ARG_OFFSET, ARG_END)); s_instr.add(0x1B, inst_info_avm2("lookupswitch", ARG_OFFSETLIST, ARG_END)); s_instr.add(0x1C, inst_info_avm2("pushwith")); s_instr.add(0x1D, inst_info_avm2("popscope")); s_instr.add(0x1E, inst_info_avm2("nextname")); s_instr.add(0x1F, inst_info_avm2("hasnext")); s_instr.add(0x20, inst_info_avm2("pushnull")); s_instr.add(0x21, inst_info_avm2("pushundefined")); // no inst for 0x22 s_instr.add(0x23, inst_info_avm2("nextvalue")); s_instr.add(0x24, inst_info_avm2("pushbyte", ARG_BYTE, ARG_END)); s_instr.add(0x25, inst_info_avm2("pushshort", ARG_SHORT, ARG_END)); s_instr.add(0x26, inst_info_avm2("pushtrue")); s_instr.add(0x27, inst_info_avm2("pushfalse")); s_instr.add(0x28, inst_info_avm2("pushnan")); s_instr.add(0x29, inst_info_avm2("pop")); s_instr.add(0x2A, inst_info_avm2("dup")); s_instr.add(0x2B, inst_info_avm2("swap")); s_instr.add(0x2C, inst_info_avm2("pushstring", ARG_STRING, ARG_END)); s_instr.add(0x2D, inst_info_avm2("pushint", ARG_INT, ARG_END)); s_instr.add(0x2E, inst_info_avm2("pushuint", ARG_UINT, ARG_END)); s_instr.add(0x2F, inst_info_avm2("pushdouble", ARG_DOUBLE, ARG_END)); s_instr.add(0x30, inst_info_avm2("pushscope")); s_instr.add(0x31, inst_info_avm2("pushnamespace", ARG_NAMESPACE, ARG_END)); s_instr.add(0x32, inst_info_avm2("hasnext2", ARG_REGISTER, ARG_REGISTER, ARG_END)); // no inst for 0x33 -> 0X3F s_instr.add(0x40, inst_info_avm2("newfunction", ARG_FUNCTION, ARG_END)); s_instr.add(0x41, inst_info_avm2("call", ARG_COUNT, ARG_END)); s_instr.add(0x42, inst_info_avm2("construct", ARG_COUNT, ARG_END)); s_instr.add(0x43, inst_info_avm2("callmethod", ARG_SHORT, ARG_COUNT, ARG_END)); s_instr.add(0x44, inst_info_avm2("callstatic", ARG_FUNCTION, ARG_COUNT, ARG_END)); s_instr.add(0x45, inst_info_avm2("callsuper", ARG_MULTINAME, ARG_COUNT, ARG_END)); s_instr.add(0x46, inst_info_avm2("callproperty", ARG_MULTINAME, ARG_COUNT, ARG_END)); s_instr.add(0x47, inst_info_avm2("returnvoid")); s_instr.add(0x48, inst_info_avm2("returnvalue")); s_instr.add(0x49, inst_info_avm2("constructsuper", ARG_COUNT, ARG_END)); s_instr.add(0x4A, inst_info_avm2("constructprop", ARG_MULTINAME, ARG_COUNT, ARG_END)); // no inst for 0x4B s_instr.add(0x4C, inst_info_avm2("callproplex", ARG_MULTINAME, ARG_COUNT, ARG_END)); // no inst for 0x4E s_instr.add(0x4E, inst_info_avm2("callsupervoid", ARG_MULTINAME, ARG_COUNT, ARG_END)); s_instr.add(0x4F, inst_info_avm2("callpropvoid", ARG_MULTINAME, ARG_COUNT, ARG_END)); // no inst for 0x50 -> 0x54 s_instr.add(0x55, inst_info_avm2("newobject", ARG_COUNT, ARG_END)); s_instr.add(0x56, inst_info_avm2("newarray", ARG_COUNT, ARG_END)); s_instr.add(0x57, inst_info_avm2("newactivation")); s_instr.add(0x58, inst_info_avm2("newclass", ARG_CLASSINFO, ARG_END)); s_instr.add(0x59, inst_info_avm2("getdescendants", ARG_MULTINAME, ARG_END)); s_instr.add(0x5A, inst_info_avm2("newcatch", ARG_EXCEPTION, ARG_END)); // no inst for 0x5B -> 0x5C s_instr.add(0x5D, inst_info_avm2("findpropstrict", ARG_MULTINAME, ARG_END)); s_instr.add(0x5E, inst_info_avm2("findproperty", ARG_MULTINAME, ARG_END)); // no inst for 0x5F s_instr.add(0x60, inst_info_avm2("getlex", ARG_MULTINAME, ARG_END)); s_instr.add(0x61, inst_info_avm2("setproperty", ARG_MULTINAME, ARG_END)); s_instr.add(0x62, inst_info_avm2("getlocal", ARG_REGISTER, ARG_END)); s_instr.add(0x63, inst_info_avm2("setlocal", ARG_REGISTER, ARG_END)); s_instr.add(0x64, inst_info_avm2("getglobalscope")); s_instr.add(0x65, inst_info_avm2("getscopeobject", ARG_BYTE, ARG_END)); s_instr.add(0x66, inst_info_avm2("getproperty", ARG_MULTINAME, ARG_END)); // no inst for 0x67 s_instr.add(0x68, inst_info_avm2("initproperty", ARG_MULTINAME, ARG_END)); // no inst for 0x69 s_instr.add(0x6A, inst_info_avm2("deleteproperty", ARG_MULTINAME, ARG_END)); // no inst for 0x6B s_instr.add(0x6C, inst_info_avm2("getslot", ARG_SLOTINDEX, ARG_END)); s_instr.add(0x6D, inst_info_avm2("setslot", ARG_SLOTINDEX, ARG_END)); s_instr.add(0x6E, inst_info_avm2("getglobalslot", ARG_SLOTINDEX, ARG_END)); s_instr.add(0x6F, inst_info_avm2("setglobalslot", ARG_SLOTINDEX, ARG_END)); s_instr.add(0x70, inst_info_avm2("convert_s")); s_instr.add(0x71, inst_info_avm2("esc_xelem")); s_instr.add(0x72, inst_info_avm2("esc_xattr")); s_instr.add(0x73, inst_info_avm2("convert_i")); s_instr.add(0x74, inst_info_avm2("convert_u")); s_instr.add(0x75, inst_info_avm2("convert_d")); s_instr.add(0x76, inst_info_avm2("convert_b")); s_instr.add(0x77, inst_info_avm2("convert_o")); s_instr.add(0x78, inst_info_avm2("checkfilter")); // no inst for 0x79 - 0x7F s_instr.add(0x80, inst_info_avm2("coerce", ARG_MULTINAME, ARG_END)); // no inst for 0x81 s_instr.add(0x82, inst_info_avm2("coerce_a")); // no inst for 0x83, 0x84 s_instr.add(0x85, inst_info_avm2("coerce_s")); s_instr.add(0x86, inst_info_avm2("astype", ARG_MULTINAME, ARG_END)); s_instr.add(0x87, inst_info_avm2("astypelate", ARG_MULTINAME, ARG_END)); // no inst for 0x88->0x8F s_instr.add(0x90, inst_info_avm2("negate")); s_instr.add(0x91, inst_info_avm2("increment")); s_instr.add(0x92, inst_info_avm2("inclocal", ARG_REGISTER, ARG_END)); s_instr.add(0x93, inst_info_avm2("decrement")); s_instr.add(0x94, inst_info_avm2("declocal", ARG_REGISTER, ARG_END)); s_instr.add(0x95, inst_info_avm2("typeof")); s_instr.add(0x96, inst_info_avm2("not")); s_instr.add(0x97, inst_info_avm2("bitnot")); // no inst for 0x99->0x0x9F s_instr.add(0xA0, inst_info_avm2("add")); s_instr.add(0xA1, inst_info_avm2("subtract")); s_instr.add(0xA2, inst_info_avm2("multiply")); s_instr.add(0xA3, inst_info_avm2("divide")); s_instr.add(0xA4, inst_info_avm2("modulo")); s_instr.add(0xA5, inst_info_avm2("lshift")); s_instr.add(0xA6, inst_info_avm2("rshift")); s_instr.add(0xA7, inst_info_avm2("urshift")); s_instr.add(0xA8, inst_info_avm2("bitand")); s_instr.add(0xA9, inst_info_avm2("bitor")); s_instr.add(0xAA, inst_info_avm2("bitxor")); s_instr.add(0xAB, inst_info_avm2("equals")); s_instr.add(0xAC, inst_info_avm2("strictequals")); s_instr.add(0xAD, inst_info_avm2("lessthan")); s_instr.add(0xAE, inst_info_avm2("lessequals")); s_instr.add(0xAF, inst_info_avm2("greaterequals")); // no inst for 0xB0 s_instr.add(0xB1, inst_info_avm2("instanceof")); s_instr.add(0xB2, inst_info_avm2("istype", ARG_MULTINAME, ARG_END)); s_instr.add(0xB3, inst_info_avm2("istypelate")); s_instr.add(0xB4, inst_info_avm2("in")); // no inst for 0xB5 s_instr.add(0xC0, inst_info_avm2("increment_i")); s_instr.add(0xC1, inst_info_avm2("decrement_i")); s_instr.add(0xC2, inst_info_avm2("inclocal_i", ARG_REGISTER, ARG_END)); s_instr.add(0xC3, inst_info_avm2("declocal_i", ARG_REGISTER, ARG_END)); s_instr.add(0xC4, inst_info_avm2("negate_i")); s_instr.add(0xC5, inst_info_avm2("add_i")); s_instr.add(0xC6, inst_info_avm2("subtract_i")); s_instr.add(0xC7, inst_info_avm2("multiply_i")); // no inst for 0xC8 - > 0xCF s_instr.add(0xD0, inst_info_avm2("getlocal_0")); s_instr.add(0xD1, inst_info_avm2("getlocal_1")); s_instr.add(0xD2, inst_info_avm2("getlocal_2")); s_instr.add(0xD3, inst_info_avm2("getlocal_3")); s_instr.add(0xD4, inst_info_avm2("setlocal_0")); s_instr.add(0xD5, inst_info_avm2("setlocal_1")); s_instr.add(0xD6, inst_info_avm2("setlocal_2")); s_instr.add(0xD7, inst_info_avm2("setlocal_3")); // no inst for 0xD8 - > 0xEE s_instr.add(0xEF, inst_info_avm2("debug", ARG_BYTE, ARG_STRING, ARG_BYTE, ARG_SHORT)); s_instr.add(0xF0, inst_info_avm2("debugline", ARG_SHORT, ARG_END)); s_instr.add(0xF1, inst_info_avm2("debugfile", ARG_STRING, ARG_END)); } assert(data.size() > 0); int ip = 0; do { int opcode = data[ip]; inst_info_avm2 ii(0); if (s_instr.get(opcode, &ii)) { printf(": %s\n", ii.m_instruction); if( ii.has_argument() ) { ip += ii.process( def, &data[ip] ); } else { ip++; } } else { log_msg(": unknown opcode 0x%02X\n", opcode); ip++; } } while (ip < data.size()); } // // Action Script 2.0 // enum arg_format { ARG_NONE = 0, ARG_STR, ARG_HEX, // default hex dump, in case the format is unknown or unsupported ARG_U8, ARG_U16, ARG_S16, ARG_PUSH_DATA, ARG_DECL_DICT, ARG_FUNCTION2 }; struct inst_info { int m_action_id; const char* m_instruction; arg_format m_arg_format; }; void log_disasm(const unsigned char* instruction_data) // Disassemble one instruction to the log. { static inst_info s_instruction_table[] = { { 0x04, "next_frame", ARG_NONE }, { 0x05, "prev_frame", ARG_NONE }, { 0x06, "play", ARG_NONE }, { 0x07, "stop", ARG_NONE }, { 0x08, "toggle_qlty", ARG_NONE }, { 0x09, "stop_sounds", ARG_NONE }, { 0x0A, "add", ARG_NONE }, { 0x0B, "sub", ARG_NONE }, { 0x0C, "mul", ARG_NONE }, { 0x0D, "div", ARG_NONE }, { 0x0E, "equ", ARG_NONE }, { 0x0F, "lt", ARG_NONE }, { 0x10, "and", ARG_NONE }, { 0x11, "or", ARG_NONE }, { 0x12, "not", ARG_NONE }, { 0x13, "str_eq", ARG_NONE }, { 0x14, "str_len", ARG_NONE }, { 0x15, "substr", ARG_NONE }, { 0x17, "pop", ARG_NONE }, { 0x18, "floor", ARG_NONE }, { 0x1C, "get_var", ARG_NONE }, { 0x1D, "set_var", ARG_NONE }, { 0x20, "set_target_exp", ARG_NONE }, { 0x21, "str_cat", ARG_NONE }, { 0x22, "get_prop", ARG_NONE }, { 0x23, "set_prop", ARG_NONE }, { 0x24, "dup_sprite", ARG_NONE }, { 0x25, "rem_sprite", ARG_NONE }, { 0x26, "trace", ARG_NONE }, { 0x27, "start_drag", ARG_NONE }, { 0x28, "stop_drag", ARG_NONE }, { 0x29, "str_lt", ARG_NONE }, { 0x2B, "cast_object", ARG_NONE }, { 0x30, "random", ARG_NONE }, { 0x31, "mb_length", ARG_NONE }, { 0x32, "ord", ARG_NONE }, { 0x33, "chr", ARG_NONE }, { 0x34, "get_timer", ARG_NONE }, { 0x35, "substr_mb", ARG_NONE }, { 0x36, "ord_mb", ARG_NONE }, { 0x37, "chr_mb", ARG_NONE }, { 0x3A, "delete", ARG_NONE }, { 0x3B, "delete_all", ARG_NONE }, { 0x3C, "set_local", ARG_NONE }, { 0x3D, "call_func", ARG_NONE }, { 0x3E, "return", ARG_NONE }, { 0x3F, "mod", ARG_NONE }, { 0x40, "new", ARG_NONE }, { 0x41, "decl_local", ARG_NONE }, { 0x42, "decl_array", ARG_NONE }, { 0x43, "decl_obj", ARG_NONE }, { 0x44, "type_of", ARG_NONE }, { 0x45, "get_target", ARG_NONE }, { 0x46, "enumerate", ARG_NONE }, { 0x47, "add_t", ARG_NONE }, { 0x48, "lt_t", ARG_NONE }, { 0x49, "eq_t", ARG_NONE }, { 0x4A, "number", ARG_NONE }, { 0x4B, "string", ARG_NONE }, { 0x4C, "dup", ARG_NONE }, { 0x4D, "swap", ARG_NONE }, { 0x4E, "get_member", ARG_NONE }, { 0x4F, "set_member", ARG_NONE }, { 0x50, "inc", ARG_NONE }, { 0x51, "dec", ARG_NONE }, { 0x52, "call_method", ARG_NONE }, { 0x53, "new_method", ARG_NONE }, { 0x54, "is_inst_of", ARG_NONE }, { 0x55, "enum_object", ARG_NONE }, { 0x60, "bit_and", ARG_NONE }, { 0x61, "bit_or", ARG_NONE }, { 0x62, "bit_xor", ARG_NONE }, { 0x63, "shl", ARG_NONE }, { 0x64, "asr", ARG_NONE }, { 0x65, "lsr", ARG_NONE }, { 0x66, "eq_strict", ARG_NONE }, { 0x67, "gt_t", ARG_NONE }, { 0x68, "gt_str", ARG_NONE }, { 0x69, "extends", ARG_NONE }, { 0x81, "goto_frame", ARG_U16 }, { 0x83, "get_url", ARG_STR }, { 0x87, "store_register", ARG_U8 }, { 0x88, "decl_dict", ARG_DECL_DICT }, { 0x8A, "wait_for_frame", ARG_HEX }, { 0x8B, "set_target", ARG_STR }, { 0x8C, "goto_frame_lbl", ARG_STR }, { 0x8D, "wait_for_fr_exp", ARG_HEX }, { 0x8E, "function2", ARG_FUNCTION2 }, { 0x94, "with", ARG_U16 }, { 0x96, "push_data", ARG_PUSH_DATA }, { 0x99, "goto", ARG_S16 }, { 0x9A, "get_url2", ARG_HEX }, // { 0x8E, "function2", ARG_HEX }, { 0x9B, "func", ARG_HEX }, { 0x9D, "branch_if_true", ARG_S16 }, { 0x9E, "call_frame", ARG_HEX }, { 0x9F, "goto_frame_exp", ARG_HEX }, { 0x00, "<end>", ARG_NONE } }; int action_id = instruction_data[0]; inst_info* info = NULL; for (int i = 0; ; i++) { if (s_instruction_table[i].m_action_id == action_id) { info = &s_instruction_table[i]; } if (s_instruction_table[i].m_action_id == 0) { // Stop at the end of the table and give up. break; } } arg_format fmt = ARG_HEX; // Show instruction. if (info == NULL) { log_msg("<unknown>[0x%02X]", action_id); } else { log_msg("%-15s", info->m_instruction); fmt = info->m_arg_format; } // Show instruction argument(s). if (action_id & 0x80) { assert(fmt != ARG_NONE); int length = instruction_data[1] | (instruction_data[2] << 8); // log_msg(" [%d]", length); if (fmt == ARG_HEX) { for (int i = 0; i < length; i++) { log_msg(" 0x%02X", instruction_data[3 + i]); } log_msg("\n"); } else if (fmt == ARG_STR) { log_msg(" \""); for (int i = 0; i < length; i++) { log_msg("%c", instruction_data[3 + i]); } log_msg("\"\n"); } else if (fmt == ARG_U8) { int val = instruction_data[3]; log_msg(" %d\n", val); } else if (fmt == ARG_U16) { int val = instruction_data[3] | (instruction_data[4] << 8); log_msg(" %d\n", val); } else if (fmt == ARG_S16) { int val = instruction_data[3] | (instruction_data[4] << 8); if (val & 0x8000) val |= ~0x7FFF; // sign-extend log_msg(" %d\n", val); } else if (fmt == ARG_PUSH_DATA) { log_msg("\n"); int i = 0; while (i < length) { int type = instruction_data[3 + i]; i++; log_msg("\t\t"); // indent if (type == 0) { // string log_msg("\""); while (instruction_data[3 + i]) { log_msg("%c", instruction_data[3 + i]); i++; } i++; log_msg("\"\n"); } else if (type == 1) { // float (little-endian) union { float f; Uint32 i; } u; compiler_assert(sizeof(u) == sizeof(u.i)); memcpy(&u.i, instruction_data + 3 + i, 4); u.i = swap_le32(u.i); i += 4; log_msg("(float) %f\n", u.f); } else if (type == 2) { log_msg("NULL\n"); } else if (type == 3) { log_msg("undef\n"); } else if (type == 4) { // contents of register int reg = instruction_data[3 + i]; i++; log_msg("reg[%d]\n", reg); } else if (type == 5) { int bool_val = instruction_data[3 + i]; i++; log_msg("bool(%d)\n", bool_val); } else if (type == 6) { // double // wacky format: 45670123 union { double d; Uint64 i; struct { Uint32 lo; Uint32 hi; } sub; } u; compiler_assert(sizeof(u) == sizeof(u.i)); memcpy(&u.sub.hi, instruction_data + 3 + i, 4); memcpy(&u.sub.lo, instruction_data + 3 + i + 4, 4); u.i = swap_le64(u.i); i += 8; log_msg("(double) %f\n", u.d); } else if (type == 7) { // int32 Sint32 val = instruction_data[3 + i] | (instruction_data[3 + i + 1] << 8) | (instruction_data[3 + i + 2] << 16) | (instruction_data[3 + i + 3] << 24); i += 4; log_msg("(int) %d\n", val); } else if (type == 8) { int id = instruction_data[3 + i]; i++; log_msg("dict_lookup[%d]\n", id); } else if (type == 9) { int id = instruction_data[3 + i] | (instruction_data[3 + i + 1] << 8); i += 2; log_msg("dict_lookup_lg[%d]\n", id); } } } else if (fmt == ARG_DECL_DICT) { int i = 0; int count = instruction_data[3 + i] | (instruction_data[3 + i + 1] << 8); i += 2; log_msg(" [%d]\n", count); // Print strings. for (int ct = 0; ct < count; ct++) { log_msg("\t\t"); // indent log_msg("\""); while (instruction_data[3 + i]) { // safety check. if (i >= length) { log_msg("<disasm error -- length exceeded>\n"); break; } log_msg("%c", instruction_data[3 + i]); i++; } log_msg("\"\n"); i++; } } else if (fmt == ARG_FUNCTION2) { // Signature info for a function2 opcode. int i = 0; const char* function_name = (const char*) &instruction_data[3 + i]; i += (int) strlen(function_name) + 1; int arg_count = instruction_data[3 + i] | (instruction_data[3 + i + 1] << 8); i += 2; int reg_count = instruction_data[3 + i]; i++; log_msg("\n\t\tname = '%s', arg_count = %d, reg_count = %d\n", function_name, arg_count, reg_count); uint16 flags = (instruction_data[3 + i]) | (instruction_data[3 + i + 1] << 8); i += 2; // @@ What is the difference between "super" and "_parent"? bool preload_global = (flags & 0x100) != 0; bool preload_parent = (flags & 0x80) != 0; bool preload_root = (flags & 0x40) != 0; bool suppress_super = (flags & 0x20) != 0; bool preload_super = (flags & 0x10) != 0; bool suppress_args = (flags & 0x08) != 0; bool preload_args = (flags & 0x04) != 0; bool suppress_this = (flags & 0x02) != 0; bool preload_this = (flags & 0x01) != 0; log_msg("\t\t pg = %d\n" "\t\t pp = %d\n" "\t\t pr = %d\n" "\t\tss = %d, ps = %d\n" "\t\tsa = %d, pa = %d\n" "\t\tst = %d, pt = %d\n", int(preload_global), int(preload_parent), int(preload_root), int(suppress_super), int(preload_super), int(suppress_args), int(preload_args), int(suppress_this), int(preload_this)); for (int argi = 0; argi < arg_count; argi++) { int arg_register = instruction_data[3 + i]; i++; const char* arg_name = (const char*) &instruction_data[3 + i]; i += (int) strlen(arg_name) + 1; log_msg("\t\targ[%d] - reg[%d] - '%s'\n", argi, arg_register, arg_name); } int function_length = instruction_data[3 + i] | (instruction_data[3 + i + 1] << 8); i += 2; log_msg("\t\tfunction length = %d\n", function_length); } } else { log_msg("\n"); } } #endif // COMPILE_DISASM }; // Local Variables: // mode: C++ // c-basic-offset: 8 // tab-width: 8 // indent-tabs-mode: t // End:
[ "viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587" ]
[ [ [ 1, 852 ] ] ]
183d50c65cb172a9499693988c2de16634bedcc4
57f014e835e566614a551f70f2da15145c7683ab
/src/contour/contourtracer.h
51a55bfcb4f07b84cd48cd11480536a6bf48d63c
[]
no_license
vcer007/contour
d5c3a1bbd7f5c948fbda9d9bbc7d40333640568d
6917e4b4f24882df2111ca4af5634645cb2700eb
refs/heads/master
2020-05-30T05:35:15.107140
2011-05-23T12:59:00
2011-05-23T12:59:00
null
0
0
null
null
null
null
GB18030
C++
false
false
3,882
h
#ifndef CONTOURTRACER_H #define CONTOURTRACER_H #include "contourstruct.h" #include "../matrix/matrix.h" #include <cmath> #include <QDebug> class ContourTracer { public: ContourTracer(); ~ContourTracer(); void setGridDataInfo(CGridDataInfo& dataInfo); void setInput(Matrix& ppGridData); void setOutput(CCurveList* pCurveList); bool executeTracing(float value); private: struct IsoPoint { int i; int j; bool bHorV; float x; float y; IsoPoint(){ memset(this,0,sizeof(IsoPoint));} }previousPoint,currentPoint,nextPoint,startPoint; float **xSide; float **ySide; private: CCurve::Type getCurveType(const IsoPoint &start,const IsoPoint &end); bool isHavingPoint(float r); void allocateMemory(); void freeMemory(); void interpolateTracingValue(); //扫描并计算纵、横边上等值点的情况 void tracingNextPoint(); //追踪下一个等值点 void fromBottom2TopTracing(); void fromLeft2RightTracing(); void fromTop2BottomTracing(); void fromRight2LeftTracing(); void handlingAfterNextPointFounded(int i, int j, bool bHorizon); //当下一个等值点找到后做相应的处理 void calcAndSaveOnePointCoord(int i, int j, bool bHorizon,float &x, float &y);//计算一个等值点的坐标并保存 void tracingOneNonClosedContour(CCurve::SType type); void tracingNonClosedContour(); void tracingOneClosedContour(int i, int j); void tracingClosedContour(); private: //输入数据 CGridDataInfo m_gridDataInfo; //网格数据信息 Matrix m_ppGridData; //网格数据 float m_valueTracing; //当前要追踪的值 float deltX; float deltY; float dx; float dy; bool needAllocate; //输出数据的存放位置(需由外部在执行追踪前设定) CCurveList* m_pCurveList; //存储追踪出来的等值线链的坐标 //保存输出数据时的帮助变量 CCurve* m_currentCurveLine; //指向当前的等值线曲线 private: ContourTracer(const ContourTracer& rhs); //not implimented ContourTracer& operator=(const ContourTracer& rhs);//not implimented }; inline void ContourTracer::setInput(Matrix& ppGridData) { m_ppGridData = ppGridData; } inline void ContourTracer::setOutput(CCurveList* pCurveList) {//指定输出位置 assert( pCurveList != NULL ); m_pCurveList = pCurveList; } inline void ContourTracer::setGridDataInfo(CGridDataInfo& dataInfo) { m_gridDataInfo = dataInfo; deltX = (m_gridDataInfo.xMax - m_gridDataInfo.xMin) / ( m_gridDataInfo.cols - 1 ); deltY = (m_gridDataInfo.yMax - m_gridDataInfo.yMin) / ( m_gridDataInfo.rows - 1 ); dx = m_gridDataInfo.xMax-m_gridDataInfo.xMin; dy = m_gridDataInfo.yMax-m_gridDataInfo.yMin; //1.为xSide和ySide分配内存空间 freeMemory(); } inline bool ContourTracer::isHavingPoint(float r) { //边上是否有等值点存在 if( r == -2.0f ) { return FALSE; } else { /*r属于[0,1] (闭区间)*/ if( r>1 || r<0) return FALSE; else return TRUE; } } inline CCurve::Type ContourTracer::getCurveType(const IsoPoint &start,const IsoPoint &end) { float row = end.x - start.x; float col = end.y - start.y; if((row != 0 && fabs(col) == dy) || (col != 0 && fabs(row) == dx)) return CCurve::C; else if( ( row == 0 && (start.x == m_gridDataInfo.xMin || start.x == m_gridDataInfo.xMax ) && col !=0) || ( col == 0 && (start.y ==m_gridDataInfo.yMin || start.y == m_gridDataInfo.yMax ) && row !=0)) return CCurve::A; else if( (row != 0 && row != dx) && (col != 0 && col != dy)) return CCurve::B; } #endif
[ [ [ 1, 145 ] ] ]
61cc581b443d7773f0422635c6aa721c96b216e9
a36fcac2b8224325125203475fedea5e8ee8af7d
/KnihaJazd/KnihaJazdDlg.h
b8f2f707f61dfd73f88169573b6360a6272e6b43
[]
no_license
mareqq/knihajazd
e000a04dbed8417e32f8a1ba3dce59e35892e3bb
e99958dd9bed7cfda6b7e8c50c86ea798c4e754e
refs/heads/master
2021-01-19T08:25:50.761893
2008-05-26T09:11:56
2008-05-26T09:11:56
32,898,594
0
0
null
null
null
null
UTF-8
C++
false
false
1,510
h
#pragma once #include "afxcmn.h" #include "afxwin.h" class CKnihaJazdDlg : public CDialog { public: CMenu m_Menu; // Menu CListCtrl m_ZoznamAut; // Control so zoznamom aut CString m_Firma; // Text s nadpisom firmy CStatic m_FirmaCtrl; // Control s nadpisom firmy CKnihaJazdDlg(CWnd* pParent = NULL); enum { IDD = IDD_KNIHAJAZDDLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); protected: virtual BOOL OnInitDialog(); virtual void OnOK(); virtual void OnCancel(); void AktualizujOkno(); void NacitanieAut(); // Firma afx_msg void OnFirmaOtvor(); afx_msg void OnFirmaZmaz(); afx_msg void OnFirmaNova(); afx_msg void OnFirmaVlastnosti(); afx_msg void OnFirmaKoniec(); afx_msg void OnUpdateFirmaVlastnosti(CCmdUI *pCmdUI); afx_msg void OnUpdateFirmaZmaz(CCmdUI *pCmdUI); // Auto afx_msg void OnAutoOtvor(); afx_msg void OnAutoZmaz(); afx_msg void OnAutoNove(); afx_msg void OnAutoVlastnosti(); afx_msg void OnUpdateAutoVlastnosti(CCmdUI *pCmdUI); afx_msg void OnUpdateAutoZmaz(CCmdUI *pCmdUI); afx_msg void OnLvnItemActivateListAuta(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnUpdateAutoOtvor(CCmdUI *pCmdUI); afx_msg void OnUpdateAutoNove(CCmdUI *pCmdUI); DECLARE_MESSAGE_MAP() void AktualizujPopisFirmy(); protected: long m_IdFirmy; // ID firmy, s ktorou pracujeme CFont m_FontFirma; // Font nadpisu firmy; double m_KmSadzba; };
[ "mareqq@d4c424c1-354d-0410-9d05-3f146b4bb521", "[email protected]@d4c424c1-354d-0410-9d05-3f146b4bb521" ]
[ [ [ 1, 26 ], [ 31, 37 ], [ 48, 52 ], [ 54, 54 ], [ 56, 56 ] ], [ [ 27, 30 ], [ 38, 47 ], [ 53, 53 ], [ 55, 55 ] ] ]
2abcc9aa2948024da847bf28788b3bea73abc838
37fbb8651f55215e84700dab5f5bdb06a0dd886e
/main.cpp
8922fded1b2b051a33002c0873b35f56e434c90e
[]
no_license
lowrey/unification-game
c7076efd6fd244c45a5092c11941861df61aae7b
9c5e523f00fa4cdf2abc2f19f9841c8265372312
refs/heads/master
2020-04-06T06:40:43.945480
2010-07-09T00:29:37
2010-07-09T00:29:37
32,325,885
0
0
null
null
null
null
UTF-8
C++
false
false
8,771
cpp
/* Title:Unification Card Game * Author: Bret Lowrey * Date: 07/08/2010 * * some code based on the open source card engine Drac * found at http://drac-cardlib.sourceforge.net/ */ #include <stdio.h> #include <stdlib.h> #include <iostream> #include "includes/CGame.h" #include "font.h" #define CARD_COMMON_PILE 0 #define CARD_PLAYER_DECK 1 #define CARD_PLAYER_DISCARD 2 #define CARD_TRASH 3 #define CARD_PLAYER_HAND 4 SDL_Surface *screen; //SDLFont *font1; // 2 fonts //SDLFont *font2; CGame Unification; const unsigned int SCREEN_WIDTH = 1024; const unsigned int SCREEN_HEIGHT = 768; void Initialize() // must be called only once { //do some initialization and create the regions in here SDL_WM_SetCaption("Unification", NULL); // Set the window title //font1 = initFont("font/data/font1"); //font2 = initFont("font/data/font2"); InitDeck(screen); Unification.Initialize(screen); //index 0, Player's Deck Unification.CreateRegion(CARD_PLAYER_DECK, CRD_VISIBLE | CRD_3D, 0, 0, CRD_ATTACK_SYMBOL, SCREEN_WIDTH - CARD_WIDTH - 35, SCREEN_HEIGHT - CARD_HEIGHT - 20, 2, 2); //index 1, Player's Discard Unification.CreateRegion(CARD_PLAYER_DISCARD, CRD_VISIBLE|CRD_FACEUP|CRD_DODRAG|CRD_DODROP |CRD_3D,CRD_DOALL,CRD_DRAGTOP, CRD_ATTACK_SYMBOL, SCREEN_WIDTH - CARD_WIDTH - 35, SCREEN_HEIGHT - CARD_HEIGHT * 2 - 20 * 2, 0, 0); //index 2-6. Player's hand for (int i =0 ; i <= 4; i++) Unification.CreateRegion(CARD_PLAYER_HAND, CRD_VISIBLE|CRD_FACEUP|CRD_DODRAG|CRD_3D, CRD_DOALL,CRD_DRAGTOP, CRD_ATTACK_SYMBOL, ((CARD_WIDTH + 20) * i + 35), (SCREEN_HEIGHT - CARD_HEIGHT - (20) ) , 0, 0); //index 7-11, Common piles, row 1 for (int i =0 ; i <= 4; i++) Unification.CreateRegion(CARD_COMMON_PILE, CRD_VISIBLE|CRD_FACEUP|CRD_DODRAG|CRD_DODROP|CRD_3D, CRD_DOALL,CRD_DRAGTOP, CRD_ATTACK_SYMBOL, ((CARD_WIDTH + 20) * i + 35), (SCREEN_HEIGHT - CARD_HEIGHT * 2 - (60 * 2) ) , 0, 0); //index 12-16, Common piles, row 2 for (int i =0 ; i <= 4; i++) Unification.CreateRegion(CARD_COMMON_PILE, CRD_VISIBLE|CRD_FACEUP|CRD_DODRAG|CRD_DODROP|CRD_3D, CRD_DOALL,CRD_DRAGTOP, CRD_ATTACK_SYMBOL, ((CARD_WIDTH + 20) * i + 35), (SCREEN_HEIGHT - CARD_HEIGHT * 3 - (140) ) , 0, 0); /* //index 1-7 for (int i = 1; i <= 7; i++) Unification.CreateRegion(CARD_COMMON_PILE, CRD_VISIBLE | CRD_DODRAG | CRD_DODROP, CRD_DOALL, CRD_DRAGFACEUP, CRD_ATTACK_SYMBOL, (CARDWIDTH * (i - 1)) + (i * 35), CARDHEIGHT + 40, 0, 16); //index 8 Unification.CreateRegion(CARD_PLAYER_DISCARD, CRD_VISIBLE | CRD_FACEUP | CRD_DODRAG | CRD_3D, CRD_DOALL, CRD_DRAGTOP, CRD_ATTACK_SYMBOL, CARDWIDTH + 65, 10, 0, 0); Unification.CreateRegion(CARD_TRASH, CRD_VISIBLE | CRD_FACEUP | CRD_DODRAG | CRD_3D, CRD_DOALL, CRD_DRAGTOP, CRD_ATTACK_SYMBOL, CARDWIDTH + 65, 10, 0, 0); //index 9-12 for (int i = 4; i <= 7; i++) Unification.CreateRegion(CARD_PLAYER_HAND, CRD_VISIBLE | CRD_3D | CRD_DODRAG | CRD_DODROP, CRD_DOSINGLE , CRD_DRAGTOP, CRD_ATTACK_SYMBOL, (CARDWIDTH * (i - 1)) + (i * 35), 10, 0, 0); Unification.CreateRegion(CARD_PLAYER_DISCARD, CRD_VISIBLE | CRD_FACEUP | CRD_DODRAG | CRD_3D, CRD_DOALL, CRD_DRAGTOP, CRD_ATTACK_SYMBOL, CARDWIDTH + 65, 10, 0, 0); */ } void NewGame() { //Reset pile symbol Unification[0].SetSymbol(CRD_ATTACK_SYMBOL); //Empty the card regions from the previous game Unification.EmptyStacks(); //create then shuffle the deck Unification[0].NewSetOfCards(); Unification[0].NewDeck(); //Unification[0].Shuffle(); //add one of each card to the common piles for (unsigned int i =7 ; i <= 16; i++) Unification[i].NewPile(i-7); //for (int i = 2; i <= 6; i++) //Unification[i].Push(Unification[0].Pop(1)); //deal /*for (int i = 1; i <= 7; i++) Unification[i].Push(Unification[0].Pop(i)); //initialize all card coordinates Unification.InitAllCoords(); //set initial faced up cards in foundations for (int i = 1; i <= 7; i++) Unification[i].SetCardFaceUp(true, Unification[i].Size() - 1);*/ Unification.InitAllCoords(); } void HandleKeyDownEvent(SDL_Event &event) { if (event.key.keysym.sym == SDLK_n) { NewGame(); Unification.DrawStaticScene(); } if (event.key.keysym.sym == SDLK_a) { AnimateCards(); }; // Test animation if (event.key.keysym.sym == SDLK_r) { Unification.DrawStaticScene(); }; // Refresh } bool startdrag = false; void ShuffleDiscardIntoDeck(CCardStack *& cs) { *cs = Unification[1].Pop(Unification[1].Size()); cs->SetCardsFaceUp(false); Unification.InitDrag(cs, -1, -1); Unification.DoDrop(&Unification[0]); Unification[0].Shuffle(); Unification[0].InitCardCoords(); } void HandleMouseDownEvent(SDL_Event &event) { CCardRegion *srcReg; if (event.button.button == SDL_BUTTON_LEFT) { srcReg = Unification.OnMouseDown(event.button.x, event.button.y); if (srcReg == NULL) return; if(srcReg->Id == CARD_PLAYER_DECK) { CCardStack *cs = new CCardStack; //discard player's hand for (int i = 2; i <= 6; i++) { if(!Unification[i].IsEmpty()) { *cs = Unification[i].Pop(1); Unification.InitDrag(cs, -1, -1); Unification.DoDrop(&Unification[1]); } } if(srcReg->IsEmpty() && !Unification[1].IsEmpty()) //Bring back the cards { ShuffleDiscardIntoDeck(cs); } else if(!srcReg->IsEmpty()) { //draw new cards for the hand for (int i = 2; i <= 6; i++) { //if there are not enough left, shuffle discard back into deck if(Unification[0].IsEmpty()) { ShuffleDiscardIntoDeck(cs); } *cs = Unification[0].Pop(1); cs->SetCardsFaceUp(true); Unification.InitDrag(cs, -1, -1); Unification.DoDrop(&Unification[i]); } } } else if ( Unification.InitDrag(event.button.x, event.button.y)) { startdrag = true; SDL_WM_GrabInput(SDL_GRAB_ON); } //std::cout << "Here" << '\n'; } //substitute right-click for double-click event /*if (event.button.button == SDL_BUTTON_RIGHT) { srcReg = Unification.OnMouseDown(event.button.x, event.button.y); if (srcReg == NULL) return; CCardRegion *cr; CCard card = srcReg->GetCard(srcReg->Size() - 1); //clicked on the top of the foundations if (((srcReg->Id == CARD_PLAYER_HAND) || (srcReg->Id == CARD_COMMON_PILE)) && card.FaceUp() && srcReg->PtOnTop(event.button.x, event.button.y)) { if ((cr = Unification.FindDropRegion(CARD_PLAYER_HAND, card))) { CCardStack *cs = new CCardStack; *cs = srcReg->Pop(1); Unification.InitDrag(cs, -1, -1); Unification.DoDrop(cr); } } }*/ } void HandleMouseMoveEvent(SDL_Event &event) { if (event.motion.state == SDL_BUTTON(1) && startdrag) Unification.DoDrag(event.motion.x, event.motion.y); } void HandleMouseUpEvent(SDL_Event &event) { if (startdrag) { startdrag = false; Unification.DoDrop(); SDL_WM_GrabInput(SDL_GRAB_OFF); } if (Unification[0].IsEmpty() && Unification[1].IsEmpty()) { Unification[0].SetSymbol(1); Unification.DrawStaticScene(); } //victory /* if ((Unification[9].Size() == 13) && (Unification[10].Size() == 13) && (Unification[11].Size() == 13) && (Unification[12].Size() == 13)) { AnimateCards(); NewGame(); Unification.DrawStaticScene(); }*/ } int main(int argc, char *argv[]) { if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO) < 0) { printf("Unable to initialize SDL: %s\n", SDL_GetError()); exit(1); } atexit(SDL_Quit); //screen = SDL_SetVideoMode(800, 600, 32, SDL_SWSURFACE | SDL_HWPALETTE // | SDL_RESIZABLE); //screen = SDL_SetVideoMode(800, 600, 32, SDL_SWSURFACE | SDL_HWPALETTE // | SDL_FULLSCREEN); screen=SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE|SDL_HWPALETTE); if (screen == NULL) { printf("Unable to set 0x0 video: %s\n", SDL_GetError()); exit(1); } Initialize(); NewGame(); Unification.DrawStaticScene(); SDL_Event event; int done = 0; while (done == 0) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: return 0; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE) { done = 1; } HandleKeyDownEvent(event); break; case SDL_MOUSEBUTTONDOWN: HandleMouseDownEvent(event); break; case SDL_MOUSEMOTION: HandleMouseMoveEvent(event); break; case SDL_MOUSEBUTTONUP: HandleMouseUpEvent(event); break; } } } // perform cleaning up in here //freeFont(font1); //freeFont(font2); return 0; }
[ "scrabbleship@459df7c9-7389-46ba-4592-dcd1b89bbbbf" ]
[ [ [ 1, 307 ] ] ]
3e212b6a944bd49c5880bbbb473503db98b8a1fd
49b6646167284329aa8644c8cf01abc3d92338bd
/SEP2_M6/HAL/Lampen.h
60a77f4b5388c60b5a9bfddfde02bebb044616a4
[]
no_license
StiggyB/javacodecollection
9d017b87b68f8d46e09dcf64650bd7034c442533
bdce3ddb7a56265b4df2202d24bf86a06ecfee2e
refs/heads/master
2020-08-08T22:45:47.779049
2011-10-24T12:10:08
2011-10-24T12:10:08
32,143,796
0
0
null
null
null
null
UTF-8
C++
false
false
5,076
h
#ifndef LAMPEN_H_ #define LAMPEN_H_ #include <unistd.h> #include "../HAL/HALCore.h" #include "../Thread/HAWThread.h" #include "../Controller/Communication.h" /** * Light Control * * SE2 (+ SY and PL) Project SoSe 2011 * * Authors: Rico Flaegel, * Tell Mueller-Pettenpohl, * Torsten Krane, * Jan Quenzel * * Provides some possibilities to activate the lights. * * Inherits: HAWThread, Communication */ class Lampen : public thread::HAWThread, public Singleton_T<Lampen>{ friend class Singleton_T<Lampen>; public: Lampen(); virtual ~Lampen(); /** * Flashes a specified light until stopped. * \param period an integer, half of the flash period. * \param color Color of the Light which should flash. */ void flash(int period, Color color); /** * Flashes a specified light until duration expired. * \param period an integer, half of the flash period. * \param duration an integer, specifies how long the light should flash * \param col Color of the Light which should flash. */ void flash(int period, int duration, Color col); /** * Removes a certain light. * \param col specifies the color of the light. */ void removeLight(Color col); /** * Adds a certain light. * \param col specifies the color of the light. */ void addLight(Color col); /** * Adds a certain light. * Equals void addLight(Color col); * \param col specifies the color of the light. */ void shine(Color col); protected: virtual void execute(void*); virtual void shutdown(); private: /** * Boolean to ensure the flashing of the Light. */ bool running; /** * Mutex to ensure threadsafety for lampen thread. */ Mutex mlight; /** * contains information regarding the lights */ typedef struct lights{ Color col; /** * Time to next change. */ int time; /** * Period for changing between on/off. */ int period; /** * Total duration for the light. * "-1" for unlimited time. */ int duration; /** * True if currently used, * false if unused. */ bool activ; /** * Shows the actual state of the light. * True if currently flashed, false if not. */ bool on; } Lights; /** * Array to all lights, containing information about the actual status. */ Lights array[3]; /** * Pointer to the HALCore */ HALCore *h; /** * Calculates the bits for the lights. * \returns the calculated light bits */ int calcLights(); /** * Calculates the time for the next sleep within the executing loop. * \returns an integer, the time in ms, the lampen-thread will sleep next, but maximal 1 second. */ int calcTime(); /** * Gets the next time the thread should be sleeping. * \returns the time when the next light should be changed */ int getNextTime(); /** * Calculates which of these values is the minimal. * \param a an integer, which should be compared to the other two * \param b an integer, which should be compared to the other two * \param c an integer, which should be compared to the other two * \returns an integer, the minimal value */ int getMin(int a, int b, int c); /** * Gets the active status of the Color. * \param col the Color which status you want to know * \returns a boolean, true if the Color is activ */ bool isActiv(Color col); /** * Removes a color from the to active list. * \param col the Color which will be deactivated */ void removeTime(Color col); /** * Removes all time information from all colors. */ void removeAllTime(); /** * Gets if the light color has the specified time. * \param col the light color which will be checked * \param time the time which should be checked */ bool hasTime(Color col, int time); /** * Adds the time for a specified light color with unlimited duration. * \param col the light color which will be set * \param period the period for the light, "-1" for unlimited */ void addTime(Color col, int period); /** * Adds the time for a specified light color. * \param col the light color which will be set * \param period the period for the light, "-1" for unlimited * \param duration the maximal duration of the light, "-1" for unlimited */ void addTime(Color col, int period, int duration); /** * Sets the time for a specified light color. * \param col the light color which will be set * \param period the period for the light, "-1" for unlimited * \param duration the maximal duration of the light, "-1" for unlimited * \param activity if the light is used and activated * \param status the current status for the light, false for not flashed. */ void setTime(Color col,int period,int duration, bool activity, bool status); /** * Gets the Bit to a specified color. * \param col is the Color which Bit you want to get. * \returns an integer, the bit of that color. */ int getBitToColor(Color col); }; #endif /* LAMPEN_H_ */
[ "[email protected]@72d44fe2-11f0-84eb-49d3-ba3949d4c1b1" ]
[ [ [ 1, 183 ] ] ]
b646e0a667131a471bdf962b899f82c10bc953f9
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_gui_basics/menus/juce_MenuBarComponent.cpp
ab2ac8facf03f5913c666c589d3975f456578333
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
10,177
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ BEGIN_JUCE_NAMESPACE //============================================================================== MenuBarComponent::MenuBarComponent (MenuBarModel* model_) : model (nullptr), itemUnderMouse (-1), currentPopupIndex (-1), topLevelIndexClicked (0) { setRepaintsOnMouseActivity (true); setWantsKeyboardFocus (false); setMouseClickGrabsKeyboardFocus (false); setModel (model_); } MenuBarComponent::~MenuBarComponent() { setModel (nullptr); Desktop::getInstance().removeGlobalMouseListener (this); } MenuBarModel* MenuBarComponent::getModel() const noexcept { return model; } void MenuBarComponent::setModel (MenuBarModel* const newModel) { if (model != newModel) { if (model != nullptr) model->removeListener (this); model = newModel; if (model != nullptr) model->addListener (this); repaint(); menuBarItemsChanged (nullptr); } } //============================================================================== void MenuBarComponent::paint (Graphics& g) { const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver(); getLookAndFeel().drawMenuBarBackground (g, getWidth(), getHeight(), isMouseOverBar, *this); if (model != nullptr) { for (int i = 0; i < menuNames.size(); ++i) { Graphics::ScopedSaveState ss (g); g.setOrigin (xPositions [i], 0); g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight()); getLookAndFeel().drawMenuBarItem (g, xPositions[i + 1] - xPositions[i], getHeight(), i, menuNames[i], i == itemUnderMouse, i == currentPopupIndex, isMouseOverBar, *this); } } } void MenuBarComponent::resized() { xPositions.clear(); int x = 0; xPositions.add (x); for (int i = 0; i < menuNames.size(); ++i) { x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]); xPositions.add (x); } } int MenuBarComponent::getItemAt (const Point<int>& p) { for (int i = 0; i < xPositions.size(); ++i) if (p.x >= xPositions[i] && p.x < xPositions[i + 1]) return reallyContains (p, true) ? i : -1; return -1; } void MenuBarComponent::repaintMenuItem (int index) { if (isPositiveAndBelow (index, xPositions.size())) { const int x1 = xPositions [index]; const int x2 = xPositions [index + 1]; repaint (x1 - 2, 0, x2 - x1 + 4, getHeight()); } } void MenuBarComponent::setItemUnderMouse (const int index) { if (itemUnderMouse != index) { repaintMenuItem (itemUnderMouse); itemUnderMouse = index; repaintMenuItem (itemUnderMouse); } } void MenuBarComponent::setOpenItem (int index) { if (currentPopupIndex != index) { repaintMenuItem (currentPopupIndex); currentPopupIndex = index; repaintMenuItem (currentPopupIndex); Desktop& desktop = Desktop::getInstance(); if (index >= 0) desktop.addGlobalMouseListener (this); else desktop.removeGlobalMouseListener (this); } } void MenuBarComponent::updateItemUnderMouse (const Point<int>& p) { setItemUnderMouse (getItemAt (p)); } void MenuBarComponent::showMenu (int index) { if (index != currentPopupIndex) { PopupMenu::dismissAllActiveMenus(); menuBarItemsChanged (nullptr); setOpenItem (index); setItemUnderMouse (index); if (index >= 0) { PopupMenu m (model->getMenuForIndex (itemUnderMouse, menuNames [itemUnderMouse])); if (m.lookAndFeel == nullptr) m.setLookAndFeel (&getLookAndFeel()); const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight()); m.showMenuAsync (PopupMenu::Options().withTargetComponent (this) .withTargetScreenArea (localAreaToGlobal (itemPos)) .withMinimumWidth (itemPos.getWidth()), ModalCallbackFunction::forComponent (menuBarMenuDismissedCallback, this, index)); } } } void MenuBarComponent::menuBarMenuDismissedCallback (int result, MenuBarComponent* bar, int topLevelIndex) { if (bar != nullptr) bar->menuDismissed (topLevelIndex, result); } void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId) { topLevelIndexClicked = topLevelIndex; postCommandMessage (itemId); } void MenuBarComponent::handleCommandMessage (int commandId) { const Point<int> mousePos (getMouseXYRelative()); updateItemUnderMouse (mousePos); if (currentPopupIndex == topLevelIndexClicked) setOpenItem (-1); if (commandId != 0 && model != nullptr) model->menuItemSelected (commandId, topLevelIndexClicked); } //============================================================================== void MenuBarComponent::mouseEnter (const MouseEvent& e) { if (e.eventComponent == this) updateItemUnderMouse (e.getPosition()); } void MenuBarComponent::mouseExit (const MouseEvent& e) { if (e.eventComponent == this) updateItemUnderMouse (e.getPosition()); } void MenuBarComponent::mouseDown (const MouseEvent& e) { if (currentPopupIndex < 0) { const MouseEvent e2 (e.getEventRelativeTo (this)); updateItemUnderMouse (e2.getPosition()); currentPopupIndex = -2; showMenu (itemUnderMouse); } } void MenuBarComponent::mouseDrag (const MouseEvent& e) { const MouseEvent e2 (e.getEventRelativeTo (this)); const int item = getItemAt (e2.getPosition()); if (item >= 0) showMenu (item); } void MenuBarComponent::mouseUp (const MouseEvent& e) { const MouseEvent e2 (e.getEventRelativeTo (this)); updateItemUnderMouse (e2.getPosition()); if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y)) { setOpenItem (-1); PopupMenu::dismissAllActiveMenus(); } } void MenuBarComponent::mouseMove (const MouseEvent& e) { const MouseEvent e2 (e.getEventRelativeTo (this)); if (lastMousePos != e2.getPosition()) { if (currentPopupIndex >= 0) { const int item = getItemAt (e2.getPosition()); if (item >= 0) showMenu (item); } else { updateItemUnderMouse (e2.getPosition()); } lastMousePos = e2.getPosition(); } } bool MenuBarComponent::keyPressed (const KeyPress& key) { bool used = false; const int numMenus = menuNames.size(); const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex); if (key.isKeyCode (KeyPress::leftKey)) { showMenu ((currentIndex + numMenus - 1) % numMenus); used = true; } else if (key.isKeyCode (KeyPress::rightKey)) { showMenu ((currentIndex + 1) % numMenus); used = true; } return used; } void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/) { StringArray newNames; if (model != nullptr) newNames = model->getMenuBarNames(); if (newNames != menuNames) { menuNames = newNames; repaint(); resized(); } } void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/, const ApplicationCommandTarget::InvocationInfo& info) { if (model == nullptr || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0) return; for (int i = 0; i < menuNames.size(); ++i) { const PopupMenu menu (model->getMenuForIndex (i, menuNames [i])); if (menu.containsCommandItem (info.commandID)) { setItemUnderMouse (i); startTimer (200); break; } } } void MenuBarComponent::timerCallback() { stopTimer(); updateItemUnderMouse (getMouseXYRelative()); } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 350 ] ] ]
06f045b4a5ca324628fae6716e831993cd94c75c
971b000b9e6c4bf91d28f3723923a678520f5bcf
/QTextPanel/qtextpaneldata.h
cb3c6d02b3187a349bfba0d949c10a1ed04c7fa1
[]
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
2,033
h
#ifndef QTEXTPANELDATA_H #define QTEXTPANELDATA_H #include <QtGui> #include <QDebug> #include <QApplication> #include <QtGui> #include <QtCore> #include <QHttp> #include <QAbstractSocket> #include <QFileInfo> #include <QHttp> #include <QUrl> #include <QTimer> #include "qtextpanelmime.h" #include "qtextpanelimage.h" #define _PARSE_DEBUG_FOP_ 1 class QTextPanelData { private: static QTextPanelData *_instance; QString transfile; QFontDatabase FF_db; QTranslator PPtr; QMap<int,PanelPageSize> history_page_norms; QTextPanelData(); void FormatRegister(const QString txt , QPrinter::PageSize pp); public: QPrinter *pdev; QRectF SceneViewPort; int CurrentDocWidth; QMap<QString,SPics> ImagePageList; /* image on all documents cache */ QMap<int,QString> LastCharOpen; QMap<int,QString> LastBlockOpen; QMap<QString,QByteArray> SvgList; QMap<int,QPicture> pagecache; /* cache pages images */ QMap<int,QMimeData*> mime_story; QSettings setter; int SessionID; PanelPageSize current_Page_Format; static QTextPanelData* instance(); ~QTextPanelData(); void LoadFontDir(const QString path); inline QString tra_file() const {return transfile;} void Set_Translate_File(const QString file); inline QMap<int,PanelPageSize> mpages() {return history_page_norms;} inline QStringList FontList() {return FF_db.families();} PanelPageSize FindPagePsize(const QRect paper); inline bool Lastsignature() {return true;} /* is open a miniscribus file true xsl-fo chunk unrelax false */ inline QPicture page(const int e) const {return pagecache[e];} void AppendPaper(PanelPageSize cur); inline PanelPageSize CurrentPageFormat() {return current_Page_Format;} inline void SetPageFormat(PanelPageSize e) {current_Page_Format = e;} void SaveMimeTmp(); bool canmime() {return mime_story.size() > 0 ? true : false;} }; #endif // QTEXTPANELDATA_H
[ "[email protected]@9af58faf-7e3e-0410-b956-55d145112073" ]
[ [ [ 1, 64 ] ] ]
474cd20ad3782b467f5a0e0e8b43731992f86941
ef23e388061a637f82b815d32f7af8cb60c5bb1f
/src/mame/includes/combatsc.h
1855a46051b6e4a93cc2964addbef56149913954
[]
no_license
marcellodash/psmame
76fd877a210d50d34f23e50d338e65a17deff066
09f52313bd3b06311b910ed67a0e7c70c2dd2535
refs/heads/master
2021-05-29T23:57:23.333706
2011-06-23T20:11:22
2011-06-23T20:11:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,426
h
/************************************************************************* Combat School *************************************************************************/ class combatsc_state : public driver_device { public: combatsc_state(running_machine &machine, const driver_device_config_base &config) : driver_device(machine, config) { } /* memory pointers */ UINT8 * m_videoram; UINT8 * m_scrollram; UINT8 * m_io_ram; UINT8 * m_paletteram; UINT8 * m_spriteram[2]; /* video-related */ tilemap_t *m_bg_tilemap[2]; tilemap_t *m_textlayer; UINT8 m_scrollram0[0x40]; UINT8 m_scrollram1[0x40]; int m_priority; int m_vreg; int m_bank_select; /* 0x00..0x1f */ int m_video_circuit; /* 0 or 1 */ UINT8 *m_page[2]; /* misc */ UINT8 m_pos[4]; UINT8 m_sign[4]; int m_prot[2]; int m_boost; emu_timer *m_interleave_timer; /* devices */ cpu_device *m_audiocpu; device_t *m_k007121_1; device_t *m_k007121_2; }; /*----------- defined in video/combatsc.c -----------*/ READ8_HANDLER( combatsc_video_r ); WRITE8_HANDLER( combatsc_video_w ); WRITE8_HANDLER( combatsc_pf_control_w ); READ8_HANDLER( combatsc_scrollram_r ); WRITE8_HANDLER( combatsc_scrollram_w ); PALETTE_INIT( combatsc ); PALETTE_INIT( combatscb ); VIDEO_START( combatsc ); VIDEO_START( combatscb ); SCREEN_UPDATE( combatscb ); SCREEN_UPDATE( combatsc );
[ "Mike@localhost" ]
[ [ [ 1, 61 ] ] ]
5440a7880eaabe369d5fe8013e0dfa8bcae70626
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/vis/tasks/vis_show_comradius.h
3f38ddf5637d830cbef7ad23f09a26deea48e31d
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,483
h
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) ** ** and SWARMS (www.swarms.de) ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the GNU General Public License, version 2. ** ************************************************************************/ #ifndef __VIS_SHOW_COMRADIUS_H #define __VIS_SHOW_COMRADIUS_H #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_VIS #include "apps/vis/base/vis_task.h" namespace vis { /** \brief Shows communication radius. * * */ class ShowComradiusTask : public VisualizationTask { public: ///@name Constructor/Destructor ///@{ ShowComradiusTask(); virtual ~ShowComradiusTask(); ///@} ///@name Getter ///@{ /** * The name of the task. */ virtual std::string name( void ) const throw(); /** * A short description of the task. */ virtual std::string description( void ) const throw(); ///@} /** * Runs the task. This ist the task main method. */ virtual void run( shawn::SimulationController& sc ) throw( std::runtime_error ); }; } #endif #endif
[ [ [ 1, 52 ] ] ]
b6f904f60ec33685fce0067d1412cc610baea172
975d45994f670a7f284b0dc88d3a0ebe44458a82
/logica/WarBugsLogic/LWarBugsLib/CBugMessage.h
4b0bc654f5f631a2d8be86d5acd6ecb25dbddc7d
[]
no_license
phabh/warbugs
2b616be17a54fbf46c78b576f17e702f6ddda1e6
bf1def2f8b7d4267fb7af42df104e9cdbe0378f8
refs/heads/master
2020-12-25T08:51:02.308060
2010-11-15T00:37:38
2010-11-15T00:37:38
60,636,297
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,178
h
/* Classse para serializar dados para envio e recebimento via socket Baseada na classe dreamMessage.h do livro Programming Multiplayer Games @autor Paulo */ #pragma once class CBugMessage { private: bool _overFlow; // verifica se ouve estouro de memória int _maxSize; // tamanho máximo int _size; // tamanho corrente int _readCount; // posicao de leitura char *getNewPoint(int length); public: char * _data; // vetor com os dados void init(char *d, int length); void clear(void); void write(void *d, int length); void writeByte(char c); void writeShort(short c); void writeInt(int c); void writeFloat(float c); void writeString(char *s); void beginReading(void); void beginReading(int s); char * read(int s); char readByte(void); short readShort(void); int readInt(void); float readFloat(void); char * readString(void); bool getOverFlow(void) {return _overFlow;} int getSize(void) {return _size;} void setSize(int s) {_size = s;} };
[ [ [ 1, 28 ], [ 30, 36 ], [ 38, 45 ] ], [ [ 29, 29 ], [ 37, 37 ] ] ]
be8f34e9fbee90b5ecc5837c30c1bca44e993f98
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Common/Input/OIS/InputManager.cpp
20249938426e34c2adc76c4ba686dd873a1fed74
[]
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
5,555
cpp
/*! @file @author Albert Semenov @date 09/2009 */ #include "precompiled.h" #include "InputManager.h" #if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32 #include <windows.h> #endif namespace input { #if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32 MyGUI::Char translateWin32Text(MyGUI::KeyCode kc) { static WCHAR deadKey = 0; BYTE keyState[256]; HKL layout = GetKeyboardLayout(0); if ( GetKeyboardState(keyState) == 0 ) return 0; int code = *((int*)&kc); unsigned int vk = MapVirtualKeyEx((UINT)code, 3, layout); if ( vk == 0 ) return 0; WCHAR buff[3] = { 0, 0, 0 }; int ascii = ToUnicodeEx(vk, (UINT)code, keyState, buff, 3, 0, layout); if (ascii == 1 && deadKey != '\0' ) { // A dead key is stored and we have just converted a character key // Combine the two into a single character WCHAR wcBuff[3] = { buff[0], deadKey, '\0' }; WCHAR out[3]; deadKey = '\0'; if (FoldStringW(MAP_PRECOMPOSED, (LPWSTR)wcBuff, 3, (LPWSTR)out, 3)) return out[0]; } else if (ascii == 1) { // We have a single character deadKey = '\0'; return buff[0]; } else if (ascii == 2) { // Convert a non-combining diacritical mark into a combining diacritical mark // Combining versions range from 0x300 to 0x36F; only 5 (for French) have been mapped below // http://www.fileformat.info/info/unicode/block/combining_diacritical_marks/images.htm switch (buff[0]) { case 0x5E: // Circumflex accent: ? deadKey = 0x302; break; case 0x60: // Grave accent: ? deadKey = 0x300; break; case 0xA8: // Diaeresis: ? deadKey = 0x308; break; case 0xB4: // Acute accent: ? deadKey = 0x301; break; case 0xB8: // Cedilla: ? deadKey = 0x327; break; default: deadKey = buff[0]; break; } } return 0; } #endif InputManager::InputManager() : mInputManager(0), mKeyboard(0), mMouse(0), mCursorX(0), mCursorY(0) { } InputManager::~InputManager() { } void InputManager::createInput(size_t _handle) { std::ostringstream windowHndStr; windowHndStr << _handle; OIS::ParamList pl; pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str())); pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND"))); pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE"))); mInputManager = OIS::InputManager::createInputSystem(pl); mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true )); mKeyboard->setEventCallback(this); mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true )); mMouse->setEventCallback(this); } void InputManager::destroyInput() { if (mInputManager) { if (mMouse) { mInputManager->destroyInputObject( mMouse ); mMouse = nullptr; } if (mKeyboard) { mInputManager->destroyInputObject( mKeyboard ); mKeyboard = nullptr; } OIS::InputManager::destroyInputSystem(mInputManager); mInputManager = nullptr; } } bool InputManager::mouseMoved(const OIS::MouseEvent& _arg) { mCursorX = _arg.state.X.abs; mCursorY = _arg.state.Y.abs; checkPosition(); injectMouseMove(mCursorX, mCursorY, _arg.state.Z.abs); return true; } bool InputManager::mousePressed(const OIS::MouseEvent& _arg, OIS::MouseButtonID _id) { injectMousePress(mCursorX, mCursorY, MyGUI::MouseButton::Enum(_id)); return true; } bool InputManager::mouseReleased(const OIS::MouseEvent& _arg, OIS::MouseButtonID _id) { injectMouseRelease(mCursorX, mCursorY, MyGUI::MouseButton::Enum(_id)); return true; } bool InputManager::keyPressed(const OIS::KeyEvent& _arg) { MyGUI::Char text = (MyGUI::Char)_arg.text; MyGUI::KeyCode key = MyGUI::KeyCode::Enum(_arg.key); int scan_code = key.toValue(); if (scan_code > 70 && scan_code < 84) { static MyGUI::Char nums[13] = { 55, 56, 57, 45, 52, 53, 54, 43, 49, 50, 51, 48, 46 }; text = nums[scan_code-71]; } else if (key == MyGUI::KeyCode::Divide) { text = '/'; } else { #if MYGUI_PLATFORM == MYGUI_PLATFORM_WIN32 text = translateWin32Text(key); #endif } injectKeyPress(key, text); return true; } bool InputManager::keyReleased(const OIS::KeyEvent& _arg) { injectKeyRelease(MyGUI::KeyCode::Enum(_arg.key)); return true; } void InputManager::captureInput() { if (mMouse) mMouse->capture(); mKeyboard->capture(); } void InputManager::setInputViewSize(int _width, int _height) { if (mMouse) { const OIS::MouseState& ms = mMouse->getMouseState(); ms.width = _width; ms.height = _height; checkPosition(); } } void InputManager::setMousePosition(int _x, int _y) { //const OIS::MouseState &ms = mMouse->getMouseState(); mCursorX = _x; mCursorY = _y; checkPosition(); } void InputManager::checkPosition() { const OIS::MouseState& ms = mMouse->getMouseState(); if (mCursorX < 0) mCursorX = 0; else if (mCursorX >= ms.width) { mCursorX = ms.width - 1; } if (mCursorY < 0) mCursorY = 0; else if (mCursorY >= ms.height) mCursorY = ms.height - 1; } void InputManager::updateCursorPosition() { const OIS::MouseState& ms = mMouse->getMouseState(); injectMouseMove(mCursorX, mCursorY, ms.Z.abs); } } // namespace input
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 241 ] ] ]
dcd81d011c4b74788f7e87a94dff678f738b51cc
d37a1d5e50105d82427e8bf3642ba6f3e56e06b8
/DVR/HaohanITPlayer/public/Common/SysUtils/SonicStatus.cpp
a97a60381de2cb22f1bdc9d859837b34f97fcf1b
[]
no_license
080278/dvrmd-filter
176f4406dbb437fb5e67159b6cdce8c0f48fe0ca
b9461f3bf4a07b4c16e337e9c1d5683193498227
refs/heads/master
2016-09-10T21:14:44.669128
2011-10-17T09:18:09
2011-10-17T09:18:09
32,274,136
0
0
null
null
null
null
UTF-8
C++
false
false
3,218
cpp
//----------------------------------------------------------------------------- // SonicStatus.cpp // Copyright (c) 2001 - 2004, Haohanit. All rights reserved. //----------------------------------------------------------------------------- //SR FS: Reviewed [JAW 20040912] //SR FS: Reviewed [wwt 20040914] #include "SonicStatus.h" #include "SonicException.h" #include "SonicThread.h" #include "time_utils.h" #include "UnicodeUtilities.h" #include "CDebugLogFile.h" #include "DVDErrors.h" SonicStatus::SonicStatus() : m_message(), m_position(0), m_duration(0), m_displayCounter(true), m_cancelDisabled(false), m_isCancelling(false) { } SonicStatus::~SonicStatus() { } bool SonicStatus::GetDisplayCounter() const { return m_displayCounter; } UInt64 SonicStatus::GetDuration() const { return m_duration; } const SonicMessage & SonicStatus::GetMessage() const { return m_message; } UInt64 SonicStatus::GetPosition() const { return m_position; } bool SonicStatus::IsCancelDisabled() { return m_cancelDisabled; } void SonicStatus::IsCancelDisabled(bool isDisabled) { m_cancelDisabled = isDisabled; } bool SonicStatus::IsCancelling() { return m_isCancelling; } void SonicStatus::IsCancelling(bool isCancel) { m_isCancelling = isCancel; } void SonicStatus::Reset() { m_message = SonicMessage(); m_position = 0; m_duration = 0; m_displayCounter = true; m_cancelDisabled = false; m_isCancelling = false; Update(); } void SonicStatus::Rundown(UInt64 milliseconds) { if (m_position < m_duration) if (milliseconds == 0) SetPosition(m_duration); else { UInt64 steps = // number of steps std::max( (milliseconds + 50) / 100, // ~100 milliseconds per step static_cast<UInt64>(1)); // at least one step UInt64 size = // size of step std::max( (m_duration - m_position) / steps, static_cast<UInt64>(1)); while (m_position < m_duration) { SetPosition(m_position + size); SonicThread::Sleep(100); } } } void SonicStatus::SetDisplayCounter(bool displayCounter) { m_displayCounter = displayCounter; } void SonicStatus::SetDuration(UInt64 duration) { m_position = 0; if (m_duration != duration) { m_duration = duration; Update(); } } void SonicStatus::SetMessage(const SonicText & text) { if (m_message.GetNumber() != text.GetNumber()) { m_message = text; Update(); #ifdef _DEBUG CDebugLogFile::Log(unicode::to_string(m_message.GetText()).c_str()); #endif } } void SonicStatus::SetPosition(UInt64 position) { position = std::min(position, m_duration); if (m_position != position) { m_position = position; Update(); } } void SonicStatus::ThrowIfCancelling() { if (m_isCancelling) throw SonicException(DVDError::userCancel); } void SonicStatus::Update() { try { UpdateNotify(); } catch (std::exception & x) { if (SonicException(&x).GetNumber() == DVDError::userCancel.GetNumber()) if (!IsCancelDisabled()) m_isCancelling = true; else return; throw; } } void SonicStatus::UpdateNotify() { }
[ "[email protected]@27769579-7047-b306-4d6f-d36f87483bb3" ]
[ [ [ 1, 170 ] ] ]
62509cd5c28343e8a8bc59b48de045a83f648a36
1bedffb06790d8e001e78e970fc290234550ed67
/vp_lazyslash/vp_lazyslash.h
949147c07c0b68394f40e17f7a17318f5c65e414
[]
no_license
mRB0/lazyslash
e14e2a7769b466555848548aee0d1d522da8ff9e
52e06cf64cca5726b30d2f74b2c3392114f59dd9
refs/heads/master
2021-01-21T12:46:55.957672
2010-03-24T06:58:52
2010-03-24T06:58:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,115
h
// vp_lazyslash.h #pragma once using namespace System; namespace vp_lazyslash { public ref class vp_lazyslash : VotePlugin::IVotePlugin { System::Collections::ArrayList^ entries; System::Collections::ArrayList^ not_voted; public: static int leven_threshold = 4; property String^ vp_name { virtual String^ get() { return L"lazyparse"; } } property String^ vp_author { virtual String^ get() { return L"mrb"; } } property String^ vp_version { virtual String^ get() { return L"1.0"; } } property String^ voter { virtual String^ get() { return this->_voter; } } // * // vp_lazyslash(void) { this->_voter = nullptr; } virtual void set_entries(System::Collections::ArrayList^ entries) { this->entries = entries; } virtual void set_not_voted(System::Collections::ArrayList^ not_voted) { this->not_voted = not_voted; } virtual System::Collections::ArrayList^ parse_votes(System::Collections::ArrayList^ irctext) { System::Collections::ArrayList^ parsed = gcnew System::Collections::ArrayList; System::Collections::ArrayList^ votetokens = gcnew System::Collections::ArrayList; String^ voter = nullptr; for each (String^ line in irctext) { System::Text::RegularExpressions::Regex re_nick(L"[^<]*<([^>]+)>"); System::Text::RegularExpressions::Match^ m_nick = re_nick.Match(line); int start_votelook = 0; if (m_nick->Success) { voter = m_nick->Groups[1]->Value; start_votelook = m_nick->Index+m_nick->Length; } System::Text::RegularExpressions::Regex re_songs(L"[^a-zA-Z0-9_]*([0-9][0-9]?[\.:,;\-]?[<>:\"/\\\|\?\* ]*)?([^<>:\"/\\\|\?\* ]+)", System::Text::RegularExpressions::RegexOptions::IgnoreCase); System::Text::RegularExpressions::Match^ m_songs = re_songs.Match(line, start_votelook); while (m_songs->Success) { votetokens->Add(System::IO::Path::GetFileNameWithoutExtension(m_songs->Groups[2]->Value)); m_songs = m_songs->NextMatch(); } } if (votetokens->Count == 0) { throw gcnew VotePlugin::VoteParseException(L"Couldn't parse any entries"); } this->_voter = voter; // check votetokens for real entries for each (String^ vote in votetokens) { int lowestlscore = -1; String^ result = nullptr; for each (VotePlugin::Entry^ e in this->entries) { if (parsed->Contains(e->filename)) { // already-found results are not eligible to be found again! continue; } int lscore = VotePlugin::Helpers::levenshtein(System::IO::Path::GetFileNameWithoutExtension(e->filename), vote); if (lscore < this->leven_threshold && (lowestlscore == -1 || lscore < lowestlscore)) { lowestlscore = lscore; result = e->filename; } } if (result != nullptr) { parsed->Add(result); } } return VotePlugin::Helpers::votestrings_to_entries(parsed, this->entries); } protected: String^ _voter; }; }
[ [ [ 1, 126 ] ] ]
cd0f7ba407fa30bed30bc6fb82c3817f94186a9b
dae66863ac441ab98adbd2d6dc2cabece7ba90be
/examples/flexvcbridge/ASWorkSample.h
ace4540a852590766f8388d94b4a2018ca1ce72a
[]
no_license
bitcrystal/flexcppbridge
2485e360f47f8d8d124e1d7af5237f7e30dd1980
474c17cfa271a9d260be6afb2496785e69e72ead
refs/heads/master
2021-01-10T14:14:30.928229
2008-11-11T06:11:34
2008-11-11T06:11:34
48,993,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
h
/* * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Flex C++ Bridge. * * The Initial Developer of the Original Code is * Anirudh Sasikumar (http://anirudhs.chaosnet.org/). * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): * */ #pragma once #include "aswork.h" class CASWorkSample : public CASWork { protected: virtual void Worker(); public: CASWorkSample(void); virtual ~CASWorkSample(void); virtual CASWork* Clone(); };
[ "anirudhsasikumar@1c1c0844-4f48-0410-9872-0bebc774e022" ]
[ [ [ 1, 37 ] ] ]
2bc6f7e01d570a2d3ca7bba936123685ada52b97
894a47fd8927d077c42040f529fb326dd97e76e6
/DLL/PluginSystem.cpp
573e75cf62f0537e8d21526b87da2d3cdafd93e2
[]
no_license
macmillion/mafia2injector
952c899bddb62863e898c2bf44dd3b27e9e5d120
1508a838976a249cfb7a7dc674da0e9b143c1fe3
refs/heads/master
2021-01-10T07:42:19.668090
2010-09-05T04:08:58
2010-09-05T04:08:58
51,205,384
0
0
null
null
null
null
UTF-8
C++
false
false
1,393
cpp
#include "PluginSystem.h" #include <Windows.h> #include <string> #include "Common.h" #include "main.h" PluginSystem::PluginSystem() { } void PluginSystem::LoadPlugins() { WIN32_FIND_DATA data; HANDLE file = FindFirstFileEx("InjectorPlugins\\*.dll", FindExInfoStandard, &data, FindExSearchNameMatch, 0, 0); if (file == (HANDLE)0xffffffff) return; do { std::string path = "InjectorPlugins\\"; path += data.cFileName; HMODULE lib = LoadLibrary(path.c_str()); if (!lib){ log("could not load " + path); continue; } Plugin plugin; StartPlugin_t pStartPlugin = (StartPlugin_t)GetProcAddress(lib, "StartPlugin"); if (!pStartPlugin){ log("could find StartPlugin in " + path); continue; } StopPlugin_t pStopPlugin = (StopPlugin_t)GetProcAddress(lib, "StopPlugin"); if (!pStopPlugin){ log("could find StopPlugin in " + path); continue; } plugin.pStartPlugin = pStartPlugin; plugin.pStopPlugin = pStopPlugin; plugins.push_back(plugin); log("loaded " + path); } while (file && FindNextFile(file, &data)); } void PluginSystem::StartPlugins() { for (unsigned int i = 0; i < plugins.size(); ++i){ plugins[i].pStartPlugin(gLuaStateManager->GetState()); } } void PluginSystem::StopPlugins() { for (unsigned int i = 0; i < plugins.size(); ++i){ plugins[i].pStopPlugin(); } }
[ "klusark@localhost" ]
[ [ [ 1, 61 ] ] ]
d42fea251468be4d743e20dd4d146f6ab1c2a958
2b80036db6f86012afcc7bc55431355fc3234058
/src/win32cpp/GroupBox.cpp
cf98aea1ae85c702bceb2e32eecdaf047f0a717b
[ "BSD-3-Clause" ]
permissive
leezhongshan/musikcube
d1e09cf263854bb16acbde707cb6c18b09a0189f
e7ca6a5515a5f5e8e499bbdd158e5cb406fda948
refs/heads/master
2021-01-15T11:45:29.512171
2011-02-25T14:09:21
2011-02-25T14:09:21
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
4,316
cpp
////////////////////////////////////////////////////////////////////////////// // // License Agreement: // // The following are Copyright © 2007, Casey Langen // // Sources and Binaries of: win32cpp // // 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 author 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. // ////////////////////////////////////////////////////////////////////////////// #include <pch.hpp> #include <win32cpp/GroupBox.hpp> #include <win32cpp/Application.hpp> ////////////////////////////////////////////////////////////////////////////// using namespace win32cpp; ////////////////////////////////////////////////////////////////////////////// ///\brief ///Default constructor. /*ctor*/ GroupBox::GroupBox(const uichar* caption) : base() , caption(caption) { } HWND GroupBox::Create(Window* parent) { HINSTANCE hInstance = Application::Instance(); // create the window // (use WS_CLIPSIBLINGS to avoid unnecessary repainting of controls inside) DWORD style = WS_CHILD | WS_VISIBLE | BS_GROUPBOX | WS_CLIPSIBLINGS; // HWND hwnd = CreateWindowEx( NULL, // ExStyle _T("BUTTON"), // Class name this->caption.c_str(), // Window name style, // Style 0, // X 0, // Y 100, // Width 100, // Height parent->Handle(), // Parent NULL, // Menu hInstance, // Instance NULL); // lParam return hwnd; } void GroupBox::OnChildAdded(Window* newChild) { SIZE idealSize; idealSize.cx = 0; idealSize.cy = 0; // all child elements should be resized to their ideal size if(newChild->SendMessageW(BCM_GETIDEALSIZE, 0, (LPARAM)(SIZE*)&idealSize)) { newChild->Resize(idealSize.cx, idealSize.cy); } // all child elements should be WITHIN the groupbox frame, // so we need to try to position them perfectly RECT childRect = newChild->ClientRect(); newChild->MoveTo( childRect.left + GetSystemMetrics(SM_CXDLGFRAME) + GetSystemMetrics(SM_CXBORDER), childRect.top + GetSystemMetrics(SM_CYDLGFRAME) + GetSystemMetrics(SM_CYBORDER) + GetSystemMetrics(SM_CYCAPTION) ); } void GroupBox::OnEraseBackground(HDC hdc) { HBRUSH bgbrush; RECT bgrect; // repaint background (since its white due to its parent controls) bgbrush = ::CreateSolidBrush(GetSysColor(COLOR_BTNFACE)); ::SelectObject(hdc, bgbrush); ::GetClientRect(this->windowHandle, &bgrect); ::FillRect(hdc, &bgrect, bgbrush); ::DeleteObject(bgbrush); }
[ "[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 116 ] ] ]
40395678b2a2065c2955c5ee94b99778a250b653
dda0d7bb4153bcd98ad5e32e4eac22dc974b8c9d
/reporting/crashrpt/crash_handler.cpp
121ac3bcdfe7811f4231d14474b4fc9ba8b477dd
[ "BSD-3-Clause" ]
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
UTF-8
C++
false
false
46,797
cpp
/************************************************************************************* This file is a part of CrashRpt library. Copyright (c) 2003, Michael Carruth 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 author 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. ***************************************************************************************/ // File: CrashHandler.cpp // Description: Exception handling and report generation functionality. // Authors: mikecarruth, zexspectrum // Date: #include "stdafx.h" #include "crash_handler.h" #include "base/utility.h" #include "resource.h" #include <sys/stat.h> #include <psapi.h> #include "base/strconv.h" #include <rtcapi.h> #include <Shellapi.h> #ifndef _AddressOfReturnAddress // Taken from: http://msdn.microsoft.com/en-us/library/s975zw7k(VS.71).aspx #ifdef __cplusplus #define EXTERNC extern "C" #else #define EXTERNC #endif // _ReturnAddress and _AddressOfReturnAddress should be prototyped before use EXTERNC void * _AddressOfReturnAddress(void); EXTERNC void * _ReturnAddress(void); #endif extern HANDLE g_hModuleCrashRpt; CCrashHandler* CCrashHandler::m_pProcessCrashHandler = NULL; CCrashHandler::CCrashHandler() { m_bInitialized = FALSE; m_dwFlags = 0; m_MinidumpType = MiniDumpNormal; //m_bAppRestart = FALSE; send_method_ = 0; m_lpfnCallback = NULL; m_bAddScreenshot = FALSE; m_dwScreenshotFlags = 0; m_nJpegQuality = 95; m_hEvent = NULL; m_pCrashDesc = NULL; InitPrevExceptionHandlerPointers(); } CCrashHandler::~CCrashHandler() { Destroy(); } int CCrashHandler::Init( LPCTSTR lpcszAppName, LPCTSTR lpcszAppVersion, LPCTSTR lpcszCrashSenderPath, LPGETLOGFILE lpfnCallback, LPCTSTR lpcszUrl, int send_method, DWORD dwFlags, LPCTSTR lpcszPrivacyPolicyURL, LPCTSTR lpcszDebugHelpDLLPath, MINIDUMP_TYPE MiniDumpType, LPCTSTR lpcszErrorReportSaveDir, LPCTSTR lpcszRestartCmdLine, LPCTSTR lpcszLangFilePath, LPCTSTR lpcszCustomSenderIcon) { crSetErrorMsg(_T("Unspecified error.")); m_dwFlags = dwFlags; // Save minidump type m_MinidumpType = MiniDumpType; // Save user supplied callback m_lpfnCallback = lpfnCallback; // Save application name m_sAppName = lpcszAppName; // If no app name provided, use the default (EXE name) if(m_sAppName.IsEmpty()) { m_sAppName = Utility::getAppName(); } // Save app version m_sAppVersion = lpcszAppVersion; // If no app version provided, use the default (EXE product version) if(m_sAppVersion.IsEmpty()) { // Get EXE image name CString sImageName = Utility::GetModuleName(NULL); m_sAppVersion = Utility::GetProductVersion(sImageName); if(m_sAppVersion.IsEmpty()) { // If product version missing, return error. crSetErrorMsg(_T("Application version is not specified.")); return 1; } } // Get process image name m_sImageName = Utility::GetModuleName(NULL); m_sCustomSenderIcon = lpcszCustomSenderIcon; if(!m_sCustomSenderIcon.IsEmpty()) { CString sResourceFile; CString sIconIndex; int nIconIndex = 0; int nComma = m_sCustomSenderIcon.ReverseFind(','); if(nComma>=0) { sResourceFile = m_sCustomSenderIcon.Left(nComma); sIconIndex = m_sCustomSenderIcon.Mid(nComma+1); sIconIndex.TrimLeft(); sIconIndex.TrimRight(); nIconIndex = _ttoi(sIconIndex); } else { sResourceFile = m_sCustomSenderIcon; } sResourceFile.TrimRight(); if(nIconIndex==-1) { crSetErrorMsg(_T("Invalid index of custom icon (it should not equal to -1).")); return 1; } } // Save URL to send reports via HTTP if(lpcszUrl!=NULL) { m_sUrl = CString(lpcszUrl); } // Check that we store ZIP archives only when error reports are not being sent. BOOL bSendErrorReport = (dwFlags&CR_INST_DONT_SEND_REPORT)?FALSE:TRUE; BOOL bStoreZIPArchives = (dwFlags&CR_INST_STORE_ZIP_ARCHIVES)?TRUE:FALSE; if(bSendErrorReport && bStoreZIPArchives) { crSetErrorMsg(_T("The flag CR_INST_STORE_ZIP_ARCHIVES should be used with CR_INST_DONT_SEND_REPORT flag.")); return 1; } m_sRestartCmdLine = lpcszRestartCmdLine; // Save report sending priorities send_method_ = send_method; // Save privacy policy URL (if exists) if(lpcszPrivacyPolicyURL!=NULL) m_sPrivacyPolicyURL = lpcszPrivacyPolicyURL; // Get the name of CrashRpt DLL LPTSTR pszCrashRptModule = NULL; #ifndef CRASHRPT_LIB #ifdef _DEBUG pszCrashRptModule = _T("crash_reportd.dll"); #else pszCrashRptModule = _T("crash_report.dll"); #endif //_DEBUG #else //!CRASHRPT_LIB pszCrashRptModule = NULL; #endif // Save path to crash_sender.exe if(lpcszCrashSenderPath==NULL) { // By default assume that crash_sender.exe is located in the same dir as crash_report.dll m_sPathToCrashSender = Utility::GetModulePath((HMODULE)g_hModuleCrashRpt); } else { // Save user-specified path m_sPathToCrashSender = CString(lpcszCrashSenderPath); } // Get CrashSender EXE name CString sCrashSenderName; #ifdef _DEBUG sCrashSenderName = _T("crash_senderd.exe"); #else sCrashSenderName = _T("crash_sender.exe"); #endif //_DEBUG // Check that crash_sender.exe file exists if(m_sPathToCrashSender.Right(1)!='\\') m_sPathToCrashSender+="\\"; HANDLE hFile = CreateFile(m_sPathToCrashSender+sCrashSenderName, FILE_GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(hFile==INVALID_HANDLE_VALUE) { crSetErrorMsg(_T("crash_sender.exe is not found in the specified path.")); return 1; } else { CloseHandle(hFile); } // Determine where to look for language file. if(lpcszLangFilePath!=NULL) { // User has provided the custom lang file path. m_sLangFileName = lpcszLangFilePath; } else { // Look for crashrpt_lang.ini in the same folder as crash_sender.exe. m_sLangFileName = m_sPathToCrashSender + _T("crashrpt_lang.ini"); } m_sPathToCrashSender += sCrashSenderName; CString sLangFileVer = Utility::GetINIString(m_sLangFileName, _T("Settings"), _T("CrashRptVersion")); int lang_file_ver = _ttoi(sLangFileVer); if(lang_file_ver!=CRASHRPT_VER) { crSetErrorMsg(_T("Missing language file or wrong language file version.")); return 1; // Language INI file has wrong version! } if(lpcszDebugHelpDLLPath==NULL) { // By default assume that debughlp.dll is located in the same dir as crash_report.dll m_sPathToDebugHelpDll = Utility::GetModulePath((HMODULE)g_hModuleCrashRpt); } else { m_sPathToDebugHelpDll = CString(lpcszDebugHelpDLLPath); } CString sDebugHelpDLL_name = "dbghelp.dll"; if(m_sPathToDebugHelpDll.Right(1)!='\\') m_sPathToDebugHelpDll+="\\"; HANDLE hDbgHelpDll = LoadLibrary(m_sPathToDebugHelpDll+sDebugHelpDLL_name); if(!hDbgHelpDll) { //try again ... fallback to dbghelp.dll in path m_sPathToDebugHelpDll = _T(""); hDbgHelpDll = LoadLibrary(sDebugHelpDLL_name); if(!hDbgHelpDll) { crSetErrorMsg(_T("Couldn't load dbghelp.dll.")); return 1; } } m_sPathToDebugHelpDll += sDebugHelpDLL_name; if(hDbgHelpDll!=NULL) { FreeLibrary((HMODULE)hDbgHelpDll); hDbgHelpDll = NULL; } // Generate unique GUID for this crash report. if(0!=Utility::GenerateGUID(m_sCrashGUID)) { ATLASSERT(0); crSetErrorMsg(_T("Couldn't generate crash GUID.")); return 1; } // Create event that will be used to synchronize with crash_sender.exe process CString sEventName; sEventName.Format(_T("Local\\CrashRptEvent_%s"), m_sCrashGUID); m_hEvent = CreateEvent(NULL, FALSE, FALSE, sEventName); if(m_hEvent==NULL) { ATLASSERT(m_hEvent!=NULL); crSetErrorMsg(_T("Couldn't create synchronization event.")); return 1; } if(lpcszErrorReportSaveDir==NULL) { // Create %LOCAL_APPDATA%\CrashRpt\UnsavedCrashReports\AppName_AppVer folder. CString sLocalAppDataFolder; DWORD dwCSIDL = CSIDL_LOCAL_APPDATA; Utility::GetSpecialFolder(dwCSIDL, sLocalAppDataFolder); m_sUnsentCrashReportsFolder.Format(_T("%s\\CrashRpt\\UnsentCrashReports\\%s_%s"), sLocalAppDataFolder, m_sAppName, m_sAppVersion); } else { m_sUnsentCrashReportsFolder = lpcszErrorReportSaveDir; } BOOL bCreateDir = Utility::CreateFolder(m_sUnsentCrashReportsFolder); if(!bCreateDir) { ATLASSERT(0); crSetErrorMsg(_T("Couldn't create crash report directory.")); return 1; } // Set exception handlers with initial values (NULLs) InitPrevExceptionHandlerPointers(); // Set exception handlers that work on per-process basis int nSetProcessHandlers = SetProcessExceptionHandlers(dwFlags); if(nSetProcessHandlers!=0) { ATLASSERT(nSetProcessHandlers==0); crSetErrorMsg(_T("Couldn't set C++ exception handlers for current process.")); return 1; } // Set exception handlers that work on per-thread basis int nSetThreadHandlers = SetThreadExceptionHandlers(dwFlags); if(nSetThreadHandlers!=0) { ATLASSERT(nSetThreadHandlers==0); crSetErrorMsg(_T("Couldn't set C++ exception handlers for main execution thread.")); return 1; } // Associate this handler with the caller process m_pProcessCrashHandler = this; // Pack configuration info to shared memory. // It will be passed to crash_sender.exe later. m_pCrashDesc = PackCrashInfoIntoSharedMem(&m_SharedMem, FALSE); // If client wants us to send pending error reports that were queued recently, // launch the crash_sender.exe and make it to alert user and send the reports. if(dwFlags&CR_INST_SEND_QUEUED_REPORTS) { // Create temporary shared mem. CSharedMem tmpSharedMem; CRASH_DESCRIPTION* pCrashDesc = PackCrashInfoIntoSharedMem(&tmpSharedMem, TRUE); pCrashDesc->m_bSendRecentReports = TRUE; if(0!=LaunchCrashSender(tmpSharedMem.GetName(), TRUE, NULL)) { crSetErrorMsg(_T("Couldn't launch crash_sender.exe process.")); return 1; } m_pTmpCrashDesc = m_pCrashDesc; m_pTmpSharedMem = &m_SharedMem; } // Initialization OK. m_bInitialized = TRUE; crSetErrorMsg(_T("Success.")); return 0; } // Packs config info to shared mem. CRASH_DESCRIPTION* CCrashHandler::PackCrashInfoIntoSharedMem(CSharedMem* pSharedMem, BOOL bTempMem) { m_pTmpSharedMem = pSharedMem; CString sSharedMemName; if(bTempMem) sSharedMemName.Format(_T("%s-tmp"), m_sCrashGUID); else sSharedMemName = m_sCrashGUID; // Initialize shared memory. BOOL bSharedMem = pSharedMem->Init(sSharedMemName, FALSE, SHARED_MEM_MAX_SIZE); if(!bSharedMem) { ATLASSERT(0); crSetErrorMsg(_T("Couldn't initialize shared memory.")); return NULL; } // Create memory view. m_pTmpCrashDesc = (CRASH_DESCRIPTION*)pSharedMem->CreateView(0, sizeof(CRASH_DESCRIPTION)); if(m_pTmpCrashDesc==NULL) { ATLASSERT(0); crSetErrorMsg(_T("Couldn't create shared memory view.")); return NULL; } // Pack config information to shared memory memset(m_pTmpCrashDesc, 0, sizeof(CRASH_DESCRIPTION)); memcpy(m_pTmpCrashDesc->m_uchMagic, "CRD", 3); m_pTmpCrashDesc->m_wSize = sizeof(CRASH_DESCRIPTION); m_pTmpCrashDesc->m_dwTotalSize = sizeof(CRASH_DESCRIPTION); m_pTmpCrashDesc->m_dwCrashRptVer = CRASHRPT_VER; m_pTmpCrashDesc->m_dwInstallFlags = m_dwFlags; m_pTmpCrashDesc->m_MinidumpType = m_MinidumpType; m_pTmpCrashDesc->m_bAddScreenshot = m_bAddScreenshot; m_pTmpCrashDesc->m_dwScreenshotFlags = m_dwScreenshotFlags; //m_pTmpCrashDesc->m_bAppRestart = m_bAppRestart; m_pTmpCrashDesc->send_method = send_method_; m_pTmpCrashDesc->m_dwAppNameOffs = PackString(m_sAppName); m_pTmpCrashDesc->m_dwAppVersionOffs = PackString(m_sAppVersion); m_pTmpCrashDesc->m_dwCrashGUIDOffs = PackString(m_sCrashGUID); m_pTmpCrashDesc->m_dwImageNameOffs = PackString(m_sImageName); m_pTmpCrashDesc->m_dwLangFileNameOffs = PackString(m_sLangFileName); m_pTmpCrashDesc->m_dwPathToDebugHelpDllOffs = PackString(m_sPathToDebugHelpDll); m_pTmpCrashDesc->m_dwRestartCmdLineOffs = PackString(m_sRestartCmdLine); m_pTmpCrashDesc->m_dwPrivacyPolicyURLOffs = PackString(m_sPrivacyPolicyURL); m_pTmpCrashDesc->m_dwUnsentCrashReportsFolderOffs = PackString(m_sUnsentCrashReportsFolder); m_pTmpCrashDesc->m_dwCustomSenderIconOffs = PackString(m_sCustomSenderIcon); m_pTmpCrashDesc->m_dwUrlOffs = PackString(m_sUrl); return m_pTmpCrashDesc; } DWORD CCrashHandler::PackString(CString str) { DWORD dwTotalSize = m_pTmpCrashDesc->m_dwTotalSize; int nStrLen = str.GetLength()*sizeof(TCHAR); WORD wLength = (WORD)(sizeof(STRING_DESC)+nStrLen); LPBYTE pView = m_pTmpSharedMem->CreateView(dwTotalSize, wLength); STRING_DESC* pStrDesc = (STRING_DESC*)pView; memcpy(pStrDesc->m_uchMagic, "STR", 3); pStrDesc->m_wSize = wLength; memcpy(pView+sizeof(STRING_DESC), str.GetBuffer(0), nStrLen); m_pTmpCrashDesc->m_dwTotalSize += wLength; m_pTmpSharedMem->DestroyView(pView); return dwTotalSize; } DWORD CCrashHandler::PackFileItem(FileItem& fi) { DWORD dwTotalSize = m_pTmpCrashDesc->m_dwTotalSize; WORD wLength = sizeof(FILE_ITEM); m_pTmpCrashDesc->m_dwTotalSize += wLength; m_pTmpCrashDesc->m_uFileItems++; LPBYTE pView = m_pTmpSharedMem->CreateView(dwTotalSize, wLength); FILE_ITEM* pFileItem = (FILE_ITEM*)pView; memcpy(pFileItem->m_uchMagic, "FIL", 3); pFileItem->m_dwSrcFilePathOffs = PackString(fi.m_sSrcFilePath); pFileItem->m_dwDstFileNameOffs = PackString(fi.m_sDstFileName); pFileItem->m_dwDescriptionOffs = PackString(fi.m_sDescription); pFileItem->m_bMakeCopy = fi.m_bMakeCopy; pFileItem->m_wSize = (WORD)(m_pTmpCrashDesc->m_dwTotalSize-dwTotalSize); m_pTmpSharedMem->DestroyView(pView); return dwTotalSize; } DWORD CCrashHandler::PackProperty(CString sName, CString sValue) { DWORD dwTotalSize = m_pTmpCrashDesc->m_dwTotalSize; WORD wLength = sizeof(CUSTOM_PROP); m_pTmpCrashDesc->m_dwTotalSize += wLength; m_pTmpCrashDesc->m_uCustomProps++; LPBYTE pView = m_pTmpSharedMem->CreateView(dwTotalSize, wLength); CUSTOM_PROP* pProp = (CUSTOM_PROP*)pView; memcpy(pProp->m_uchMagic, "CPR", 3); pProp->m_dwNameOffs = PackString(sName); pProp->m_dwValueOffs = PackString(sValue); pProp->m_wSize = (WORD)(m_pTmpCrashDesc->m_dwTotalSize-dwTotalSize); m_pTmpSharedMem->DestroyView(pView); return dwTotalSize; } DWORD CCrashHandler::PackRegKey(CString sKeyName, CString sDstFileName) { DWORD dwTotalSize = m_pTmpCrashDesc->m_dwTotalSize; WORD wLength = sizeof(REG_KEY); m_pTmpCrashDesc->m_dwTotalSize += wLength; m_pTmpCrashDesc->m_uRegKeyEntries++; LPBYTE pView = m_pTmpSharedMem->CreateView(dwTotalSize, wLength); REG_KEY* pKey = (REG_KEY*)pView; memcpy(pKey->m_uchMagic, "REG", 3); pKey->m_dwRegKeyNameOffs = PackString(sKeyName); pKey->m_dwDstFileNameOffs = PackString(sDstFileName); pKey->m_wSize = (WORD)(m_pTmpCrashDesc->m_dwTotalSize-dwTotalSize); m_pTmpSharedMem->DestroyView(pView); return dwTotalSize; } BOOL CCrashHandler::IsInitialized() { return m_bInitialized; } int CCrashHandler::Destroy() { crSetErrorMsg(_T("Unspecified error.")); if(!m_bInitialized) { crSetErrorMsg(_T("Can't destroy not initialized crash handler.")); return 1; } // Reset exception callback if (m_oldSehHandler) SetUnhandledExceptionFilter(m_oldSehHandler); m_oldSehHandler = NULL; // All installed per-thread C++ exception handlers should be uninstalled // using crUninstallFromCurrentThread() before calling Destroy() { CAutoLock lock(&m_csThreadExceptionHandlers); ATLASSERT(m_ThreadExceptionHandlers.size()==0); } m_pProcessCrashHandler = NULL; // OK. m_bInitialized = FALSE; crSetErrorMsg(_T("Success.")); return 0; } // Sets internal pointers to previously used exception handlers to NULL void CCrashHandler::InitPrevExceptionHandlerPointers() { m_oldSehHandler = NULL; #if _MSC_VER>=1300 m_prevPurec = NULL; m_prevNewHandler = NULL; #endif #if _MSC_VER>=1300 && _MSC_VER<1400 m_prevSec = NULL; #endif #if _MSC_VER>=1400 m_prevInvpar = NULL; #endif m_prevSigABRT = NULL; m_prevSigINT = NULL; m_prevSigTERM = NULL; } CCrashHandler* CCrashHandler::GetCurrentProcessCrashHandler() { return m_pProcessCrashHandler; } void CCrashHandler::ReleaseCurrentProcessCrashHandler() { if(m_pProcessCrashHandler!=NULL) { delete m_pProcessCrashHandler; m_pProcessCrashHandler = NULL; } } int CCrashHandler::SetProcessExceptionHandlers(DWORD dwFlags) { crSetErrorMsg(_T("Unspecified error.")); // If 0 is specified as dwFlags, assume all handlers should be // installed if((dwFlags&0x1FF)==0) dwFlags |= 0x1FFF; if(dwFlags&CR_INST_STRUCTURED_EXCEPTION_HANDLER) { // Install top-level SEH handler m_oldSehHandler = SetUnhandledExceptionFilter(SehHandler); } _set_error_mode(_OUT_TO_STDERR); #if _MSC_VER>=1300 if(dwFlags&CR_INST_PURE_CALL_HANDLER) { // Catch pure virtual function calls. // Because there is one _purecall_handler for the whole process, // calling this function immediately impacts all threads. The last // caller on any thread sets the handler. // http://msdn.microsoft.com/en-us/library/t296ys27.aspx m_prevPurec = _set_purecall_handler(PureCallHandler); } if(dwFlags&CR_INST_NEW_OPERATOR_ERROR_HANDLER) { // Catch new operator memory allocation exceptions _set_new_mode(1); // Force malloc() to call new handler too m_prevNewHandler = _set_new_handler(NewHandler); } #endif #if _MSC_VER>=1400 if(dwFlags&CR_INST_INVALID_PARAMETER_HANDLER) { // Catch invalid parameter exceptions. m_prevInvpar = _set_invalid_parameter_handler(InvalidParameterHandler); } #endif #if _MSC_VER>=1300 && _MSC_VER<1400 if(dwFlags&CR_INST_SECURITY_ERROR_HANDLER) { // Catch buffer overrun exceptions // The _set_security_error_handler is deprecated in VC8 C++ run time library m_prevSec = _set_security_error_handler(SecurityHandler); } #endif // Set up C++ signal handlers if(dwFlags&CR_INST_SIGABRT_HANDLER) { #if _MSC_VER>=1400 _set_abort_behavior(_CALL_REPORTFAULT, _CALL_REPORTFAULT); #endif // Catch an abnormal program termination m_prevSigABRT = signal(SIGABRT, SigabrtHandler); } if(dwFlags&CR_INST_SIGILL_HANDLER) { // Catch illegal instruction handler m_prevSigINT = signal(SIGINT, SigintHandler); } if(dwFlags&CR_INST_TERMINATE_HANDLER) { // Catch a termination request m_prevSigTERM = signal(SIGTERM, SigtermHandler); } crSetErrorMsg(_T("Success.")); return 0; } int CCrashHandler::UnSetProcessExceptionHandlers() { crSetErrorMsg(_T("Unspecified error.")); // Unset all previously set handlers #if _MSC_VER>=1300 if(m_prevPurec!=NULL) _set_purecall_handler(m_prevPurec); if(m_prevNewHandler!=NULL) _set_new_handler(m_prevNewHandler); #endif #if _MSC_VER>=1400 if(m_prevInvpar!=NULL) _set_invalid_parameter_handler(m_prevInvpar); #endif //_MSC_VER>=1400 #if _MSC_VER>=1300 && _MSC_VER<1400 if(m_prevSec!=NULL) _set_security_error_handler(m_prevSec); #endif //_MSC_VER<1400 if(m_prevSigABRT!=NULL) signal(SIGABRT, m_prevSigABRT); if(m_prevSigINT!=NULL) signal(SIGINT, m_prevSigINT); if(m_prevSigTERM!=NULL) signal(SIGTERM, m_prevSigTERM); crSetErrorMsg(_T("Success.")); return 0; } // Installs C++ exception handlers that function on per-thread basis int CCrashHandler::SetThreadExceptionHandlers(DWORD dwFlags) { crSetErrorMsg(_T("Unspecified error.")); // If 0 is specified as dwFlags, assume all available exception handlers should be // installed if((dwFlags&0x1FFF)==0) dwFlags |= 0x1FFF; DWORD dwThreadId = GetCurrentThreadId(); CAutoLock lock(&m_csThreadExceptionHandlers); std::map<DWORD, ThreadExceptionHandlers>::iterator it = m_ThreadExceptionHandlers.find(dwThreadId); if(it!=m_ThreadExceptionHandlers.end()) { // handlers are already set for the thread crSetErrorMsg(_T("Can't install handlers for current thread twice.")); return 1; // failed } ThreadExceptionHandlers handlers; if(dwFlags&CR_INST_TERMINATE_HANDLER) { // Catch terminate() calls. // In a multithreaded environment, terminate functions are maintained // separately for each thread. Each new thread needs to install its own // terminate function. Thus, each thread is in charge of its own termination handling. // http://msdn.microsoft.com/en-us/library/t6fk7h29.aspx handlers.m_prevTerm = set_terminate(TerminateHandler); } if(dwFlags&CR_INST_UNEXPECTED_HANDLER) { // Catch unexpected() calls. // In a multithreaded environment, unexpected functions are maintained // separately for each thread. Each new thread needs to install its own // unexpected function. Thus, each thread is in charge of its own unexpected handling. // http://msdn.microsoft.com/en-us/library/h46t5b69.aspx handlers.m_prevUnexp = set_unexpected(UnexpectedHandler); } if(dwFlags&CR_INST_SIGFPE_HANDLER) { // Catch a floating point error typedef void (*sigh)(int); handlers.m_prevSigFPE = signal(SIGFPE, (sigh)SigfpeHandler); } if(dwFlags&CR_INST_SIGILL_HANDLER) { // Catch an illegal instruction handlers.m_prevSigILL = signal(SIGILL, SigillHandler); } if(dwFlags&CR_INST_SIGSEGV_HANDLER) { // Catch illegal storage access errors handlers.m_prevSigSEGV = signal(SIGSEGV, SigsegvHandler); } // Insert the structure to the list of handlers m_ThreadExceptionHandlers[dwThreadId] = handlers; // OK. crSetErrorMsg(_T("Success.")); return 0; } int CCrashHandler::UnSetThreadExceptionHandlers() { crSetErrorMsg(_T("Unspecified error.")); DWORD dwThreadId = GetCurrentThreadId(); CAutoLock lock(&m_csThreadExceptionHandlers); std::map<DWORD, ThreadExceptionHandlers>::iterator it = m_ThreadExceptionHandlers.find(dwThreadId); if(it==m_ThreadExceptionHandlers.end()) { // No exception handlers were installed for the caller thread? crSetErrorMsg(_T("Crash handler wasn't previously installed for current thread.")); return 1; } ThreadExceptionHandlers* handlers = &(it->second); if(handlers->m_prevTerm!=NULL) set_terminate(handlers->m_prevTerm); if(handlers->m_prevUnexp!=NULL) set_unexpected(handlers->m_prevUnexp); if(handlers->m_prevSigFPE!=NULL) signal(SIGFPE, handlers->m_prevSigFPE); if(handlers->m_prevSigILL!=NULL) signal(SIGINT, handlers->m_prevSigILL); if(handlers->m_prevSigSEGV!=NULL) signal(SIGSEGV, handlers->m_prevSigSEGV); // Remove from the list m_ThreadExceptionHandlers.erase(it); // OK. crSetErrorMsg(_T("Success.")); return 0; } int CCrashHandler::AddFile(LPCTSTR pszFile, LPCTSTR pszDestFile, LPCTSTR pszDesc, DWORD dwFlags) { crSetErrorMsg(_T("Unspecified error.")); // make sure the file exist struct _stat st; int result = _tstat(pszFile, &st); if (result!=0 && (dwFlags&CR_AF_MISSING_FILE_OK)==0) { crSetErrorMsg(_T("Couldn't stat file. File may not exist.")); return 1; } // Add file to file list. FileItem fi; fi.m_sDescription = pszDesc; fi.m_sSrcFilePath = pszFile; fi.m_bMakeCopy = (dwFlags&CR_AF_MAKE_FILE_COPY)!=0; if(pszDestFile!=NULL) { fi.m_sDstFileName = pszDestFile; m_files[pszDestFile] = fi; } else { CString sDestFile = pszFile; int pos = -1; sDestFile.Replace('/', '\\'); pos = sDestFile.ReverseFind('\\'); if(pos!=-1) sDestFile = sDestFile.Mid(pos+1); fi.m_sDstFileName = sDestFile; m_files[sDestFile] = fi; } // Pack this file item into shared mem. PackFileItem(fi); // OK. crSetErrorMsg(_T("Success.")); return 0; } int CCrashHandler::AddProperty(CString sPropName, CString sPropValue) { crSetErrorMsg(_T("Unspecified error.")); if(sPropName.IsEmpty()) { crSetErrorMsg(_T("Invalid property name specified.")); return 1; } m_props[sPropName] = sPropValue; PackProperty(sPropName, sPropValue); // OK. crSetErrorMsg(_T("Success.")); return 0; } int CCrashHandler::AddScreenshot(DWORD dwFlags, int nJpegQuality) { crSetErrorMsg(_T("Unspecified error.")); if(nJpegQuality<0 || nJpegQuality>100) { crSetErrorMsg(_T("Invalid Jpeg quality.")); return 1; } m_bAddScreenshot = TRUE; m_dwScreenshotFlags = dwFlags; m_nJpegQuality = nJpegQuality; // Pack this info into shared memory m_pCrashDesc->m_bAddScreenshot = TRUE; m_pCrashDesc->m_dwScreenshotFlags = dwFlags; m_pCrashDesc->m_nJpegQuality = nJpegQuality; crSetErrorMsg(_T("Success.")); return 0; } static void LogWhenUnNormalExit() { FILE* fp = fopen(CR_CRASH_LOG_FILE, "ab+"); if ( fp!= NULL) { // 0 stands for fail fprintf(fp, "%d\t0\n", time(NULL)); } else { // printf("fail to open file crash.log"); MessageBoxA(NULL, "fail to open file crash.log", "error", 0); } fclose(fp); } // write to log, telling that a crash happen this time int CCrashHandler::GenerateErrorReport( PCR_EXCEPTION_INFO pExceptionInfo) { LogWhenUnNormalExit(); crSetErrorMsg(_T("Unspecified error.")); // Validate input parameters if(pExceptionInfo==NULL) { crSetErrorMsg(_T("Exception info is NULL.")); return 1; } // Get exception pointers if not provided. if(pExceptionInfo->pexcptrs==NULL) { GetExceptionPointers(pExceptionInfo->code, &pExceptionInfo->pexcptrs); } // Save current process ID, thread ID and exception pointers address to shared mem. m_pCrashDesc->m_dwProcessId = GetCurrentProcessId(); m_pCrashDesc->m_dwThreadId = GetCurrentThreadId(); m_pCrashDesc->m_pExceptionPtrs = pExceptionInfo->pexcptrs; m_pCrashDesc->m_bSendRecentReports = FALSE; m_pCrashDesc->m_nExceptionType = pExceptionInfo->exctype; if(pExceptionInfo->exctype==CR_SEH_EXCEPTION) { m_pCrashDesc->m_dwExceptionCode = pExceptionInfo->code; } else if(pExceptionInfo->exctype==CR_CPP_SIGFPE) { m_pCrashDesc->m_uFPESubcode = pExceptionInfo->fpe_subcode; } else if(pExceptionInfo->exctype==CR_CPP_INVALID_PARAMETER) { m_pCrashDesc->m_dwInvParamExprOffs = PackString(pExceptionInfo->expression); m_pCrashDesc->m_dwInvParamFunctionOffs = PackString(pExceptionInfo->function); m_pCrashDesc->m_dwInvParamFileOffs = PackString(pExceptionInfo->file); m_pCrashDesc->m_uInvParamLine = pExceptionInfo->line; } // If error report is being generated manually, disable app restart. if(pExceptionInfo->bManual) m_pCrashDesc->m_dwInstallFlags &= ~CR_INST_APP_RESTART; // Let client know about the crash via the crash callback function. if (m_lpfnCallback!=NULL && m_lpfnCallback(NULL)==FALSE) { crSetErrorMsg(_T("The operation was cancelled by client.")); return 2; } // Start the crash_sender.exe process which will take the dekstop screenshot, // copy user-specified files to the error report folder, create minidump, // notify user about crash, compress the report into ZIP archive and send // the error report. int result = LaunchCrashSender(m_sCrashGUID, TRUE, &pExceptionInfo->hSenderProcess); if(result!=0) { ATLASSERT(result==0); crSetErrorMsg(_T("Error launching crash_sender.exe")); // Failed to launch crash sender process. // Try notify user about crash using message box. CString szCaption; szCaption.Format(_T("%s has stopped working"), Utility::getAppName()); CString szMessage; szMessage.Format(_T("Error launching crash_sender.exe")); MessageBox(NULL, szMessage, szCaption, MB_OK|MB_ICONERROR); return 3; } // OK crSetErrorMsg(_T("Success.")); return 0; } int CCrashHandler::AddRegKey(LPCTSTR szRegKey, LPCTSTR szDstFileName, DWORD dwFlags) { UNREFERENCED_PARAMETER(dwFlags); crSetErrorMsg(_T("Unspecified error.")); if(szDstFileName==NULL || szRegKey==NULL) { // Invalid param crSetErrorMsg(_T("Invalid registry key or invalid destination file is specified.")); return 1; } CString sDstFileName = CString(szDstFileName); if(sDstFileName.Find(_T("\\"))>=0 || sDstFileName.Find(_T("\r"))>=0 || sDstFileName.Find(_T("\n"))>=0 || sDstFileName.Find(_T("\t"))>=0) { // Inacceptable character found. return 1; } HKEY hKey = NULL; CString sKey = szRegKey; int nSkip = 0; if(sKey.Left(19).Compare(_T("HKEY_LOCAL_MACHINE\\"))==0) { hKey = HKEY_LOCAL_MACHINE; nSkip = 18; } else if(sKey.Left(18).Compare(_T("HKEY_CURRENT_USER\\"))==0) { hKey = HKEY_CURRENT_USER; nSkip = 17; } else { crSetErrorMsg(_T("Invalid registry branch is specified.")); return 1; // Invalid key. } CString sSubKey = sKey.Mid(nSkip+1); if(sSubKey.IsEmpty()) { crSetErrorMsg(_T("Empty subkey is not allowed.")); return 2; // Empty subkey not allowed } HKEY hKeyResult = NULL; LRESULT lResult = RegOpenKeyEx(hKey, sSubKey, 0, KEY_READ, &hKeyResult); if(lResult!=ERROR_SUCCESS) { crSetErrorMsg(_T("The registry key coudn't be open.")); return 3; // Invalid key. } RegCloseKey(hKeyResult); m_RegKeys[CString(szRegKey)] = sDstFileName; PackRegKey(szRegKey, sDstFileName); // OK crSetErrorMsg(_T("Success.")); return 0; } // The following code gets exception pointers using a workaround found in CRT code. void CCrashHandler::GetExceptionPointers(DWORD dwExceptionCode, EXCEPTION_POINTERS** ppExceptionPointers) { // The following code was taken from VC++ 8.0 CRT (invarg.c: line 104) EXCEPTION_RECORD ExceptionRecord; CONTEXT ContextRecord; memset(&ContextRecord, 0, sizeof(CONTEXT)); #ifdef _X86_ __asm { mov dword ptr [ContextRecord.Eax], eax mov dword ptr [ContextRecord.Ecx], ecx mov dword ptr [ContextRecord.Edx], edx mov dword ptr [ContextRecord.Ebx], ebx mov dword ptr [ContextRecord.Esi], esi mov dword ptr [ContextRecord.Edi], edi mov word ptr [ContextRecord.SegSs], ss mov word ptr [ContextRecord.SegCs], cs mov word ptr [ContextRecord.SegDs], ds mov word ptr [ContextRecord.SegEs], es mov word ptr [ContextRecord.SegFs], fs mov word ptr [ContextRecord.SegGs], gs pushfd pop [ContextRecord.EFlags] } ContextRecord.ContextFlags = CONTEXT_CONTROL; #pragma warning(push) #pragma warning(disable:4311) ContextRecord.Eip = (ULONG)_ReturnAddress(); ContextRecord.Esp = (ULONG)_AddressOfReturnAddress(); #pragma warning(pop) ContextRecord.Ebp = *((ULONG *)_AddressOfReturnAddress()-1); #elif defined (_IA64_) || defined (_AMD64_) /* Need to fill up the Context in IA64 and AMD64. */ RtlCaptureContext(&ContextRecord); #else /* defined (_IA64_) || defined (_AMD64_) */ ZeroMemory(&ContextRecord, sizeof(ContextRecord)); #endif /* defined (_IA64_) || defined (_AMD64_) */ ZeroMemory(&ExceptionRecord, sizeof(EXCEPTION_RECORD)); ExceptionRecord.ExceptionCode = dwExceptionCode; ExceptionRecord.ExceptionAddress = _ReturnAddress(); /// EXCEPTION_RECORD* pExceptionRecord = new EXCEPTION_RECORD; memcpy(pExceptionRecord, &ExceptionRecord, sizeof(EXCEPTION_RECORD)); CONTEXT* pContextRecord = new CONTEXT; memcpy(pContextRecord, &ContextRecord, sizeof(CONTEXT)); *ppExceptionPointers = new EXCEPTION_POINTERS; (*ppExceptionPointers)->ExceptionRecord = pExceptionRecord; (*ppExceptionPointers)->ContextRecord = pContextRecord; } // Launches crash_sender.exe process int CCrashHandler::LaunchCrashSender(CString sCmdLineParams, BOOL bWait, HANDLE* phProcess) { crSetErrorMsg(_T("Success.")); /* Create CrashSender process */ STARTUPINFO si; memset(&si, 0, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); PROCESS_INFORMATION pi; memset(&pi, 0, sizeof(PROCESS_INFORMATION)); CString sCmdLine; sCmdLine.Format(_T("\"%s\" \"%s\""), sCmdLineParams, sCmdLineParams.GetBuffer(0)); BOOL bCreateProcess = CreateProcess( m_sPathToCrashSender, sCmdLine.GetBuffer(0), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); if(!bCreateProcess) { ATLASSERT(bCreateProcess); crSetErrorMsg(_T("Error creating CrashSender process.")); return 1; } if(bWait) { /* Wait until CrashSender finishes with making screenshot, copying files, creating minidump. */ WaitForSingleObject(m_hEvent, INFINITE); } // Return handle to the crash_sender.exe process. if(phProcess!=NULL) { *phProcess = pi.hProcess; } return 0; } // Acquires the crash lock. Other threads that may crash will // wait until we unlock. void CCrashHandler::CrashLock(BOOL bLock) { if(bLock) m_csCrashLock.Lock(); else m_csCrashLock.Unlock(); } // Structured exception handler LONG WINAPI CCrashHandler::SehHandler(PEXCEPTION_POINTERS pExceptionPtrs) { CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. pCrashHandler->CrashLock(TRUE); CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_SEH_EXCEPTION; ei.pexcptrs = pExceptionPtrs; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } // Unreacheable code return EXCEPTION_EXECUTE_HANDLER; } // CRT terminate() call handler void __cdecl CCrashHandler::TerminateHandler() { // Abnormal program termination (terminate() function was called) CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_TERMINATE_CALL; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } } // CRT unexpected() call handler void __cdecl CCrashHandler::UnexpectedHandler() { // Unexpected error (unexpected() function was called) CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_UNEXPECTED_CALL; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } } // CRT Pure virtual method call handler #if _MSC_VER>=1300 void __cdecl CCrashHandler::PureCallHandler() { // Pure virtual function call CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_PURE_CALL; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } } #endif // CRT buffer overrun handler. Available in CRT 7.1 only #if _MSC_VER>=1300 && _MSC_VER<1400 void __cdecl CCrashHandler::SecurityHandler(int code, void *x) { // Security error (buffer overrun). code; x; CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_SECURITY_ERROR; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } } #endif // CRT invalid parameter handler #if _MSC_VER>=1400 void __cdecl CCrashHandler::InvalidParameterHandler( const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved) { pReserved; // Invalid parameter exception CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_INVALID_PARAMETER; ei.expression = expression; ei.function = function; ei.file = file; ei.line = line; pCrashHandler->GenerateErrorReport(&ei); pCrashHandler->CrashLock(FALSE); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } } #endif // CRT new operator fault handler #if _MSC_VER>=1300 int __cdecl CCrashHandler::NewHandler(size_t) { // 'new' operator memory allocation exception CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_NEW_OPERATOR_ERROR; ei.pexcptrs = NULL; pCrashHandler->GenerateErrorReport(&ei); pCrashHandler->CrashLock(FALSE); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } // Unreacheable code return 0; } #endif //_MSC_VER>=1300 // CRT SIGABRT signal handler void CCrashHandler::SigabrtHandler(int) { // Caught SIGABRT C++ signal CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_SIGABRT; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } } // CRT SIGFPE signal handler void CCrashHandler::SigfpeHandler(int /*code*/, int subcode) { // Floating point exception (SIGFPE) CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_SIGFPE; ei.pexcptrs = (PEXCEPTION_POINTERS)_pxcptinfoptrs; ei.fpe_subcode = subcode; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } } // CRT sigill signal handler void CCrashHandler::SigillHandler(int) { // Illegal instruction (SIGILL) CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_SIGILL; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } } // CRT sigint signal handler void CCrashHandler::SigintHandler(int) { // Interruption (SIGINT) CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_SIGINT; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } } // CRT SIGSEGV signal handler void CCrashHandler::SigsegvHandler(int) { // Invalid storage access (SIGSEGV) CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_SIGSEGV; ei.pexcptrs = (PEXCEPTION_POINTERS)_pxcptinfoptrs; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } } // CRT SIGTERM signal handler void CCrashHandler::SigtermHandler(int) { // Termination request (SIGTERM) CCrashHandler* pCrashHandler = CCrashHandler::GetCurrentProcessCrashHandler(); ATLASSERT(pCrashHandler!=NULL); if(pCrashHandler!=NULL) { // Acquire lock to avoid other threads (if exist) to crash while we are // inside. We do not unlock, because process is to be terminated. pCrashHandler->CrashLock(TRUE); // Fill in the exception info CR_EXCEPTION_INFO ei; memset(&ei, 0, sizeof(CR_EXCEPTION_INFO)); ei.cb = sizeof(CR_EXCEPTION_INFO); ei.exctype = CR_CPP_SIGTERM; pCrashHandler->GenerateErrorReport(&ei); // Terminate process TerminateProcess(GetCurrentProcess(), 1); } }
[ "[email protected]@9307afbf-8b4c-5d34-949b-c69a0924eb0b" ]
[ [ [ 1, 1593 ] ] ]
15d34297306c995d1c8247358488e1ea67fdc82e
f9351a01f0e2dec478e5b60c6ec6445dcd1421ec
/itl/boost/itl/type_traits/is_interval_container.hpp
4ff5994697157101e86bee59ffe26aa28f647835
[ "BSL-1.0" ]
permissive
WolfgangSt/itl
e43ed68933f554c952ddfadefef0e466612f542c
6609324171a96565cabcf755154ed81943f07d36
refs/heads/master
2016-09-05T20:35:36.628316
2008-11-04T11:44:44
2008-11-04T11:44:44
327,076
0
1
null
null
null
null
UTF-8
C++
false
false
804
hpp
/*----------------------------------------------------------------------------+ Copyright (c) 2008-2008: Joachim Faulhaber +-----------------------------------------------------------------------------+ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENCE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +----------------------------------------------------------------------------*/ #ifndef __itl_type_traits_is_interval_container_JOFA_081004_H__ #define __itl_type_traits_is_interval_container_JOFA_081004_H__ namespace boost{ namespace itl { template <class Type> struct is_interval_container; template <class Type> struct is_interval_container{ enum {value = false}; }; }} // namespace boost itl #endif
[ "jofaber@6b8beb3d-354a-0410-8f2b-82c74c7fef9a" ]
[ [ [ 1, 21 ] ] ]
6c6dc4a2fa69242086daa6e755a2874171ae355c
6581dacb25182f7f5d7afb39975dc622914defc7
/WinsockLab/Multicastexample/multicastexamplesrc.cpp
126bf911fd403f8ace46cd0957260b2af182e714
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,328
cpp
// File: // multicastexamplesrc.cpp - this file // resolve.cpp - common name resolution routines // resolve.h - header file for common name resolution routines // Purpose: // This sample illustrates the reliable multicast protocol. The client is // simple, create a reliable multicast socket, set the receive interfaces, // and wait for a session. After the session is joined, receive data on the // accepted session. For the server, the window size and other options may // be specified on the command line. // // Command line options // multicastexamples // -fb int FEC block size // -fg int FEC group size // -fo Enable on-demand FEC // -fp int Set FEC pro-active count // -i Local interface // Sender: This specifies the send interface // Receiver: This is the listen interface - may be specified multiple times // -j int Late join percentage (sender only) // -m str Dotted decimal multicast IP addres to join // -n int Number of messages to send/receive // -p int Port number to use // -s Act as server (send data); otherwise receive data. // -t int Set multicast TTL // -wb int Set the send window size in bytes // -wr int Set the send window rate in bytes/second // -ws int Set the send window size in seconds // -z int Size of the send/recv buffer // // Link to ws2_32.lib #include <winsock2.h> #include <ws2tcpip.h> #include <wsrm.h> #include <windows.h> #include "resolve.h" #include <stdio.h> #define MCASTADDRV4 "224.0.0.255" #define MCASTPORT "25000" #define BUFSIZE 1024 #define DEFAULT_COUNT 500 #define DEFAULT_TTL 8 #define MAX_LOCAL_INTERFACES 64 BOOL bSender=FALSE, // Act as sender? bUseFec=FALSE, // Enable FEC bFecOnDemand=FALSE, // Enable FEC on demand bSetSendWindow=FALSE; // For the SOCK_RDM & IPPROTO_RM to work, you must have the // MSMQ (Microsoft Message Queuing ) installed lor! // http://support.microsoft.com/kb/256096 // int gSocketType=SOCK_DGRAM, int gSocketType=SOCK_RDM, // Reliable datagram gProtocol=IPPROTO_RM, // Reliable multicast protocol //gProtocol=IPPROTO_UDP, gCount=DEFAULT_COUNT, // Number of messages to send/receive gTtl=DEFAULT_TTL, // Multicast TTL value gBufferSize=BUFSIZE; // Buffer size for send/recv int gInterfaceCount=0; // Number of local interfaces specified char *gListenInterface[MAX_LOCAL_INTERFACES], // Set of listening interfaces *gMulticast=MCASTADDRV4, // Multicast group to join *gPort=MCASTPORT; // Port number to use // Window size paramters int gWindowRateKbitsSec=0, gWindowSizeBytes=0, gWindowSizeMSec=0; // FEC parameters int gFecBlockSize=8, gFecGroupSize=16, gFecProActive=8; // Late join option int gLateJoin=-1; // Function: usage // Description: Print usage information and exit. int usage(char *progname) { printf("Usage: %s -s -m str -p int -i str -l -n int\n", progname); printf(" -fb int FEC block size\n"); printf(" -fg int FEC group size\n"); printf(" -fo Enable on-demand FEC\n"); printf(" -fp int Set FEC pro-active count\n"); printf(" -i Local interface\n"); printf(" Sender: This specifies the send interface\n"); printf(" Receiver: This is the listen interface - may be specified multiple times\n"); printf(" -j int Late join percentage (sender only)\n"); printf(" -m str Dotted decimal multicast IP addres to join\n"); printf(" -n int Number of messages to send/receive\n"); printf(" -p int Port number to use. The default port is: %s\n", MCASTPORT); printf(" -s Act as server (send data), otherwise receive data.\n"); printf(" -t int Set multicast TTL\n"); printf(" -wb int Set the send window size in bytes\n"); printf(" -wr int Set the send window rate in bytes/second\n"); printf(" -ws int Set the send window size in seconds\n"); printf(" -z int Size of the send/recv buffer\n"); printf("\n"); return 0; } // Function: ValidateArgs // Description // Parse the command line arguments and set some global flags // depeding on the values void ValidateArgs(int argc, char **argv) { int i; for(i=1; i < argc ;i++) { if ((argv[i][0] == '-') || (argv[i][0] == '/')) { switch (tolower(argv[i][1])) { case 'f': // Use fec if (strlen(argv[i]) != 3) usage(argv[0]); bUseFec = TRUE; switch (tolower(argv[i][2])) { case 'b': // FEC block size if (i+1 >= argc) usage(argv[0]); gFecBlockSize = atol(argv[++i]); break; case 'g': // FEC group size if (i+1 >= argc) usage(argv[0]); gFecGroupSize = atol(argv[++i]); break; case 'o': // FEC on demand bFecOnDemand = TRUE; break; case 'p': // Pro active FEC count if (i+1 >= argc) usage(argv[0]); gFecProActive = atol(argv[++i]); break; default: usage(argv[0]); break; } break; case 'i': // local interface to use if (i+1 >= argc) usage(argv[0]); gListenInterface[gInterfaceCount++] = argv[++i]; break; case 'j': // Late join value if (i+1 >= argc) usage(argv[0]); gLateJoin = atol(argv[++i]); if (gLateJoin > SENDER_MAX_LATE_JOINER_PERCENTAGE) { gLateJoin = SENDER_MAX_LATE_JOINER_PERCENTAGE; printf("Exceeded maximum late join value (%d%%)!\n", gLateJoin); printf(" Setting value to maximum allowed\n"); } break; case 'm': // multicast group to join if (i+1 >= argc) usage(argv[0]); gMulticast = argv[++i]; break; case 'n': // Number of messages to send/recv if (i+1 >= argc) usage(argv[0]); gCount = atoi(argv[++i]); break; case 'p': // Port number to use if (i+1 >= argc) usage(argv[0]); gPort = argv[++i]; break; case 's': // sender bSender = TRUE; break; case 't': // Multicast ttl if (i+1 >= argc) usage(argv[0]); gTtl = atoi(argv[++i]); break; case 'w': // Send window size if ((i+1 >= argc) || (strlen(argv[i]) != 3)) usage(argv[0]); bSetSendWindow = TRUE; switch (tolower(argv[i][2])) { case 'b': // Window size in bytes gWindowSizeBytes = atol(argv[++i]); break; case 's': // Window size in seconds gWindowSizeMSec = atol(argv[++i]) * 1000; break; case 'r': // Window size in bytes/sec gWindowRateKbitsSec = (atol(argv[++i])/1000) * 8; break; default: usage(argv[0]); break; } break; case 'z': // Buffer size for send/recv if (i+1 >= argc) usage(argv[0]); gBufferSize = atol(argv[++i]); break; default: usage(argv[0]); break; } } } return; } // Function: SetSendInterface // Description: This routine sets the sending interface. This option may only be set on senders int SetSendInterface(SOCKET s, struct addrinfo *iface) { int rc; // Set the send interface rc = setsockopt( s, IPPROTO_RM, RM_SET_SEND_IF, (char *)&((SOCKADDR_IN *)iface->ai_addr)->sin_addr.s_addr, sizeof(ULONG) ); if (rc == SOCKET_ERROR) { printf("setsockopt() failed with error code %d\n", WSAGetLastError()); } else { printf("Set sending interface to: "); PrintAddress(iface->ai_addr, iface->ai_addrlen); printf("\n"); } return rc; } // Function: AddReceiveInterface // Description: // This routine adds the given interface to the receiving interfac // list. This option is valid only for receivers int AddReceiveInterface(SOCKET s, struct addrinfo *iface) { int rc; rc = setsockopt( s, IPPROTO_RM, RM_ADD_RECEIVE_IF, (char *)&((SOCKADDR_IN *)iface->ai_addr)->sin_addr.s_addr, sizeof(ULONG) ); if (rc == SOCKET_ERROR) { printf("setsockopt(): RM_ADD_RECEIVE_IF failed with error code %d\n", WSAGetLastError()); } else { printf("Adding receive interface: "); PrintAddress(iface->ai_addr, iface->ai_addrlen); printf("\n"); } return rc; } // Function: SetMulticastTtl // Description: This routine sets the multicast TTL value for the socket. int SetMulticastTtl(SOCKET s, int af, int ttl) { int rc; // Set the TTL value rc = setsockopt( s, IPPROTO_RM, RM_SET_MCAST_TTL, (char *)&ttl, sizeof(ttl) ); if (rc == SOCKET_ERROR) { fprintf(stderr, "SetMulticastTtl: setsockopt() failed with error code %d\n", WSAGetLastError()); } else { printf("Set multicast ttl to: %d\n", ttl); } return rc; } // Function: SetFecParamters // Description: // This routine sets the requested FEC parameters on a sender socket. // A client does not have to do anything special when the sender enables or disables FEC int SetFecParameters(SOCKET s, int blocksize, int groupsize, int ondemand, int proactive) { RM_FEC_INFO fec; int rc; memset(&fec, 0, sizeof(fec)); fec.FECBlockSize = (USHORT) blocksize; fec.FECProActivePackets = (USHORT) proactive; fec.FECGroupSize = (UCHAR) blocksize; fec.fFECOnDemandParityEnabled = (BOOLEAN)ondemand; rc = setsockopt(s, IPPROTO_RM, RM_USE_FEC, (char *)&fec, sizeof(fec)); if (rc == SOCKET_ERROR) { printf("Setting FEC parameters:\n"); printf(" Block size: %d\n", blocksize); printf(" Pro active: %d\n", proactive); printf(" Group size: %d\n", groupsize); printf(" On demand : %s\n", (ondemand ? "TRUE" : "FALSE")); } else { fprintf(stderr, "setsockopt(): RM_USE_FEC failed with error code %d\n", WSAGetLastError()); } return rc; } // Function: SetWindowSize // Description: // This routine sets the window size for the sending socket which includes // the byte rate, window size, and window time parameters. Before setting // the parameters a simple calculation is performed to determine whether // the values passed in make sense. If they don't an error message is // displayed but the set is attempted anyway. If the values don't jive // then the option will fail with WSAEINVAL and the default window // rate, size, and time are used instead. int SetWindowSize(SOCKET s, int windowsize, int windowtime, int windowrate) { RM_SEND_WINDOW window; int rc; memset(&window, 0, sizeof(window)); if (windowsize != ((windowrate/8) * windowtime)) { printf("Window parameters don't compute!\n"); } window.RateKbitsPerSec = windowrate; window.WindowSizeInMSecs = windowtime; window.WindowSizeInBytes = windowsize; rc = setsockopt(s, IPPROTO_RM, RM_RATE_WINDOW_SIZE, (char *)&window, sizeof(window)); if (rc == SOCKET_ERROR) { fprintf(stderr, "setsockopt(): RM_RATE_WINDOW_SIZE failed with error code %d\n", WSAGetLastError()); } else { printf("Setting window parameters:\n"); printf(" Rate (kbits/sec): %d\n", windowrate); printf(" Size (bytes) : %d\n", windowsize); printf(" Time (msec) : %d\n", windowtime); } return rc; } // Function: SetLateJoin // Description: // This option sets the latejoin value. This specifies the percentage of the // window that a receiver can NAK in the event the receiver picked up the // session in the middle of the sender's transmission. This option is set // on the sender side and is advertised to the receivers when the session is joined. int SetLateJoin(SOCKET s, int latejoin) { int rc; rc = setsockopt(s, IPPROTO_RM, RM_LATEJOIN, (char *)&latejoin, sizeof(latejoin)); if (rc == SOCKET_ERROR) { fprintf(stderr, "setsockopt(): RM_LATEJOIN failed with error code %d\n", WSAGetLastError()); } else { printf("Setting latejoin: %d\n", latejoin); } return rc; } // Function: main // Description: // Parse the command line arguments, load the Winsock library, // create a socket and join the multicast group. If set as a // sender then begin sending messages to the multicast group; // otherwise, call recvfrom() to read messages send to the group int main(int argc, char **argv) { WSADATA wsd; SOCKET s, sc; SOCKADDR_STORAGE remote; struct addrinfo *resmulti=NULL, *resif=NULL, *resbind=NULL; char *buf=NULL; int remotelen, err, rc, i=0; // If no arguments supplied, exit and shows the usage if(argc < 2) { usage(argv[0]); exit(1); } // Parse the command line ValidateArgs(argc, argv); // Load Winsock if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) { printf("WSAStartup() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("WSAStartup() is OK!\n"); // Resolve the multicast address resmulti = ResolveAddress(gMulticast, gPort, AF_INET, 0, 0); if (resmulti == NULL) { fprintf(stderr, "Unable to convert multicast address '%s': %d\n", gMulticast, WSAGetLastError()); return -1; } else printf("ResolveAddress() should be fine!\n"); // Create the socket. In Winsock 1 you don't need any special // flags to indicate multicasting. s = socket(resmulti->ai_family, gSocketType, gProtocol); if (s == INVALID_SOCKET) { printf("socket() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("socket() is working...\n"); printf("socket handle = 0x%p\n", s); // Allocate the send/receive buffer buf = (char *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, gBufferSize); if (buf == NULL) { fprintf(stderr, "HeapAlloc() failed with error code %d\n", GetLastError()); return -1; } else printf("HeapAlloc() for buffer is OK!\n"); if (bSender) { // Bind to the wildcard address resbind = ResolveAddress(NULL, gPort, AF_INET, 0, 0); if (resbind == NULL) { fprintf(stderr, "Unable to obtain bind address!\n"); return -1; } else printf("ResolveAddress() should be fine!\n"); // Bind the socket rc = bind(s, resbind->ai_addr, resbind->ai_addrlen); if (rc == SOCKET_ERROR) { fprintf(stderr, "bind() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("bind() is OK!\n"); freeaddrinfo(resbind); // If sepcified, set the send interface if (gInterfaceCount == 1) { resif = ResolveAddress(gListenInterface[0], gPort, AF_INET, 0, 0); if (resif == NULL) { return -1; } else printf("Setting the interface count...\n"); rc = SetSendInterface(s, resif); freeaddrinfo(resif); // Set the TTL to something else. The default TTL is one. rc = SetMulticastTtl(s, resmulti->ai_family, gTtl); if (rc == SOCKET_ERROR) { return -1; } else printf("Setting the TTL...\n"); } // If specified set the late joiner option if (gLateJoin != -1) { printf("Setting the late joiner...\n"); SetLateJoin(s, gLateJoin); } // If specified set the window parameters if (bSetSendWindow) { printf("Setting the window size...\n"); SetWindowSize(s, gWindowSizeBytes, gWindowSizeMSec, gWindowRateKbitsSec); } // If specified set the FEC paramters if (bUseFec == TRUE) { printf("Setting the FEC...\n"); SetFecParameters(s, gFecBlockSize, gFecGroupSize, bFecOnDemand, gFecProActive); } // Connect the socket to the multicast group the session is to be on rc = connect(s, resmulti->ai_addr, resmulti->ai_addrlen); if (rc == SOCKET_ERROR) { printf("connect() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("connect() looks fine!\n"); memset(buf, '$', gBufferSize); // Send some data for(i=0; i < gCount ; i++) { rc = send(s, buf, gBufferSize, 0); if (rc == SOCKET_ERROR) { fprintf(stderr, "send() failed with error code %d\n", WSAGetLastError()); return -1; } printf("Sent %d bytes\n", rc); } } else { // Bind the socket to the multicast address on which the session will take place rc = bind(s, resmulti->ai_addr, resmulti->ai_addrlen); if (rc == SOCKET_ERROR) { fprintf(stderr, "bind() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("bind() is pretty fine!\n"); printf("Binding to "); PrintAddress(resmulti->ai_addr, resmulti->ai_addrlen); printf("\n"); // Add each supplied interface as a receive interface if (gInterfaceCount > 0) { for(i=0; i < gInterfaceCount ;i++) { resif = ResolveAddress(gListenInterface[i], "0", AF_INET, 0, 0); if (resif == NULL) { return -1; } rc = AddReceiveInterface(s, resif); freeaddrinfo(resif); } } // Listen for sessions rc = listen(s, 1); if (rc == SOCKET_ERROR) { fprintf(stderr, "listen() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("listen() is OK!\n"); // Wait for a session to become available remotelen = sizeof(remote); sc = accept(s, (SOCKADDR *)&remote, &remotelen); if (sc == INVALID_SOCKET) { fprintf(stderr, "accept() failed with error code %d\n", WSAGetLastError()); return -1; } else printf("accept() is OK!\n"); printf("Join multicast session from: "); PrintAddress((SOCKADDR *)&remote, remotelen); printf("\n"); while (1) { // Receive data until an error or until the session is closed rc = recv(sc, buf, gBufferSize, 0); if (rc == SOCKET_ERROR) { if ((err = WSAGetLastError()) != WSAEDISCON) { fprintf(stderr, "recv() failed with error code %d\n", err); } break; } else { printf("received %d bytes\n", rc); } } // Close the session socket if(closesocket(sc) == 0) printf("closesocket(sc) is OK!\n"); else printf("closesocket(sc) failed with error code %d\n",WSAGetLastError()); } // Clean up freeaddrinfo(resmulti); if(closesocket(s) == 0) printf("closesocket(s) is OK!\n"); else printf("closesocket(s) failed with error code %d\n",WSAGetLastError()); if(WSACleanup() == 0) printf("WSACleanup() is OK!\n"); else printf("WSACleanup() failed with error code %d\n", WSAGetLastError()); return 0; }
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 650 ] ] ]
39830d84456fc3988957cf350e7381fb086c086d
ffa46b6c97ef6e0c03e034d542fa94ba02d519e5
/pages.h
26efa47231eadd4bce2a9d0b04aac4ba43629815
[]
no_license
jason-cpc/chmcreator
50467a2bc31833aef931e24be1ac68f5c06efd97
5da66666a9df47c5cf67b71bfb115b403f41b72b
refs/heads/master
2021-12-04T11:22:23.616758
2010-07-20T23:50:15
2010-07-20T23:50:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,564
h
#ifndef PAGES_H #define PAGES_H #include <QtGui> #include "chmproject.h" #include "qlocalemap.h" #include "global.h" #include "qmodifyfiledialog.h" class GeneralTab : public QWidget { Q_OBJECT public: GeneralTab(QSettings* setting=0,QWidget *parent = 0); QLineEdit *fileNameEdit; QLineEdit *targetNameEdit; QLineEdit *contentsNameEdit; QLineEdit *indexNameEdit; QLineEdit *logNameEdit; QComboBox *pathValueLabel; QLineEdit* fontBox; QComboBox* languageBox; void save(); QSettings* settings; QModifyFileDialog* modifyFileDialog; QPushButton* butn; private slots: void setFont(); void setDefaultFile(); }; class ButtonsPage : public QWidget { public: ButtonsPage(QSettings* setting,QWidget *parent = 0); void save(); }; class WindowPage : public QWidget { public: WindowPage(QSettings* setting,QWidget *parent = 0); void save(); }; class ComplierPage : public QWidget { public: ComplierPage(QSettings* setting,QWidget *parent = 0); void save(); private: QSettings* settings; QComboBox* compatibiBox; QCheckBox* dontIncludeFolder;// = new QCheckBox(tr("Don't Include Folder in Compiled File.")); QCheckBox* enhancedDecomp;// = new QCheckBox(tr("Support Enhanced Decompliation.")); QCheckBox* fullSearchSpt;// = new QCheckBox(tr("Full Text Search Support.")); QCheckBox* binaryIndex;// = new QCheckBox(tr("Create Binary Index.")); QCheckBox* binaryToc;// = new QCheckBox(tr("Create Binary TOC(Large TOC File.)")); }; //! [0] //! [1] class PositionPage : public QWidget { Q_OBJECT public: PositionPage(QSettings* setting, QWidget *parent = 0); void save(); }; //! [1] //! [2] class NavPage : public QWidget { Q_OBJECT public: NavPage(QSettings* setting,QWidget *parent = 0); void save(); }; class StylesPage : public QWidget { Q_OBJECT public: StylesPage(QSettings* setting,QWidget *parent = 0); void save(); }; class MergePage : public QWidget { Q_OBJECT QListWidget* listWidget; public: MergePage(QSettings* setting, QWidget *parent = 0); void save(); QSettings* settings; private slots: void add(); void remove(); }; /*class QPropertyDialog : public QDialog { Q_OBJECT public: QPropertyDialog(const QString &fileName, QWidget *parent = 0); void save(); private: QTabWidget *tabWidget; QDialogButtonBox *buttonBox; };*/ #endif
[ "zhurx4g@35deca34-8bc2-11de-b999-7dfecaa767bb" ]
[ [ [ 1, 121 ] ] ]
3e33b6480f3bc00bdaa22378b9f29997a7e70cfd
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/WildMagic2/Source/Physics/WmlIntersectingRectangles.cpp
a0120fdec4de39dad7ffd987550b1fd37d035e98
[]
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
9,088
cpp
// Magic Software, Inc. // http://www.magic-software.com // http://www.wild-magic.com // Copyright (c) 2003. All Rights Reserved // // The Game Physics source code is supplied under the terms of the license // agreement http://www.magic-software.com/License/GamePhysics.pdf and may not // be copied or disclosed except in accordance with the terms of that // agreement. #include "WmlIntersectingRectangles.h" using namespace Wml; #include <algorithm> using namespace std; //---------------------------------------------------------------------------- template <class Real> IntersectingRectangles<Real>::IntersectingRectangles ( vector<AxisAlignedBox2<Real> >& rkRects) : m_rkRects(rkRects) { Initialize(); } //---------------------------------------------------------------------------- template <class Real> IntersectingRectangles<Real>::~IntersectingRectangles () { } //---------------------------------------------------------------------------- template <class Real> void IntersectingRectangles<Real>::Initialize () { // get the rectangle end points int iISize = (int)m_rkRects.size(), iESize = 2*iISize; m_kXEndPoint.resize(iESize); m_kYEndPoint.resize(iESize); int i, j; for (i = 0, j = 0; i < iISize; i++) { m_kXEndPoint[j].Type = 0; m_kXEndPoint[j].Value = m_rkRects[i].GetXMin(); m_kXEndPoint[j].Index = i; m_kYEndPoint[j].Type = 0; m_kYEndPoint[j].Value = m_rkRects[i].GetYMin(); m_kYEndPoint[j].Index = i; j++; m_kXEndPoint[j].Type = 1; m_kXEndPoint[j].Value = m_rkRects[i].GetXMax(); m_kXEndPoint[j].Index = i; m_kYEndPoint[j].Type = 1; m_kYEndPoint[j].Value = m_rkRects[i].GetYMax(); m_kYEndPoint[j].Index = i; j++; } // sort the rectangle end points sort(m_kXEndPoint.begin(),m_kXEndPoint.end()); sort(m_kYEndPoint.begin(),m_kYEndPoint.end()); // create the interval-to-endpoint lookup tables m_kXLookup.resize(iESize); m_kYLookup.resize(iESize); for (j = 0; j < iESize; j++) { m_kXLookup[2*m_kXEndPoint[j].Index + m_kXEndPoint[j].Type] = j; m_kYLookup[2*m_kYEndPoint[j].Index + m_kYEndPoint[j].Type] = j; } // active set of rectangles (stored by index in array) set<int> kActive; // set of overlapping rectangles (stored by pairs of indices in array) m_kOverlap.clear(); // sweep through the end points to determine overlapping x-intervals for (i = 0; i < iESize; i++) { EndPoint& rkEnd = m_kXEndPoint[i]; int iIndex = rkEnd.Index; if ( rkEnd.Type == 0 ) // an interval 'begin' value { // In the 1D problem, the current interval overlaps with all the // active intervals. In 2D this we also need to check for // y-overlap. set<int>::iterator pkIter = kActive.begin(); for (/**/; pkIter != kActive.end(); pkIter++) { // Rectangles iAIndex and iIndex overlap in the x-dimension. // Test for overlap in the y-dimension. int iAIndex = *pkIter; const AxisAlignedBox2<Real>& rkR0 = m_rkRects[iAIndex]; const AxisAlignedBox2<Real>& rkR1 = m_rkRects[iIndex]; if ( rkR0.HasYOverlap(rkR1) ) { if ( iAIndex < iIndex ) m_kOverlap.insert(make_pair(iAIndex,iIndex)); else m_kOverlap.insert(make_pair(iIndex,iAIndex)); } } kActive.insert(iIndex); } else // an interval 'end' value { kActive.erase(iIndex); } } } //---------------------------------------------------------------------------- template <class Real> void IntersectingRectangles<Real>::SetRectangle (int i, const AxisAlignedBox2<Real>& rkRect) { assert( 0 <= i && i < (int)m_rkRects.size() ); m_rkRects[i] = rkRect; m_kXEndPoint[m_kXLookup[2*i]].Value = rkRect.GetXMin(); m_kXEndPoint[m_kXLookup[2*i+1]].Value = rkRect.GetXMax(); m_kYEndPoint[m_kYLookup[2*i]].Value = rkRect.GetYMin(); m_kYEndPoint[m_kYLookup[2*i+1]].Value = rkRect.GetYMax(); } //---------------------------------------------------------------------------- template <class Real> void IntersectingRectangles<Real>::GetRectangle (int i, AxisAlignedBox2<Real>& rkRect) const { assert( 0 <= i && i < (int)m_rkRects.size() ); rkRect = m_rkRects[i]; } //---------------------------------------------------------------------------- template <class Real> void IntersectingRectangles<Real>::InsertionSort ( vector<EndPoint>& rkEndPoint, vector<int>& rkLookup) { // Apply an insertion sort. Under the assumption that the rectangles // have not changed much since the last call, the end points are nearly // sorted. The insertion sort should be very fast in this case. int iESize = (int)rkEndPoint.size(); for (int j = 1; j < iESize; j++) { EndPoint kKey = rkEndPoint[j]; int i = j - 1; while ( i >= 0 && kKey < rkEndPoint[i] ) { EndPoint kE0 = rkEndPoint[i]; EndPoint kE1 = rkEndPoint[i+1]; // update the overlap status if ( kE0.Type == 0 ) { if ( kE1.Type == 1 ) { // The 'b' of interval E0.Index was smaller than the 'e' // of interval E1.Index, and the intervals *might have // been* overlapping. Now 'b' and 'e' are swapped, and // the intervals cannot overlap. Remove the pair from // the overlap set. The removal operation needs to find // the pair and erase it if it exists. Finding the pair // is the expensive part of the operation, so there is no // real time savings in testing for existence first, then // deleting if it does. if ( kE0.Index < kE1.Index ) m_kOverlap.erase(make_pair(kE0.Index,kE1.Index)); else m_kOverlap.erase(make_pair(kE1.Index,kE0.Index)); } } else { if ( kE1.Type == 0 ) { // The 'b' of interval E0.index was larger than the 'e' // of interval E1.index, and the intervals were not // overlapping. Now 'b' and 'e' are swapped, and the // intervals *might be* overlapping. We need to determine // if this is so and insert only if they do overlap. const AxisAlignedBox2<Real>& rkR0 = m_rkRects[kE0.Index]; const AxisAlignedBox2<Real>& rkR1 = m_rkRects[kE1.Index]; if ( rkR0.TestIntersection(rkR1) ) { if ( kE0.Index < kE1.Index ) m_kOverlap.insert(make_pair(kE0.Index,kE1.Index)); else m_kOverlap.insert(make_pair(kE1.Index,kE0.Index)); } } } // reorder the items to maintain the sorted list rkEndPoint[i] = kE1; rkEndPoint[i+1] = kE0; rkLookup[2*kE1.Index + kE1.Type] = i; rkLookup[2*kE0.Index + kE0.Type] = i+1; i--; } rkEndPoint[i+1] = kKey; rkLookup[2*kKey.Index + kKey.Type] = i+1; } } //---------------------------------------------------------------------------- template <class Real> void IntersectingRectangles<Real>::Update () { InsertionSort(m_kXEndPoint,m_kXLookup); InsertionSort(m_kYEndPoint,m_kYLookup); } //---------------------------------------------------------------------------- template <class Real> #ifdef WML_USING_VC6 // VC6 on the PC generates an error if typename is included. const set<IntersectingRectangles<Real>::RectanglePair>& #else // g++ 3.x on the Macintosh generates a warning if typename is not included. const set<typename IntersectingRectangles<Real>::RectanglePair>& #endif IntersectingRectangles<Real>::GetOverlap () const { return m_kOverlap; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- namespace Wml { template class WML_ITEM IntersectingRectangles<float>; template class WML_ITEM IntersectingRectangles<double>; } //----------------------------------------------------------------------------
[ [ [ 1, 233 ] ] ]
cf36b946684d89aa2330cebbcdc4699f7c798b1f
15732b8e4190ae526dcf99e9ffcee5171ed9bd7e
/GeneratedFiles/Release/moc_MainWindow.cpp
c06dace9eb0c62617641867ea73cbed404e3d7f1
[]
no_license
clovermwliu/whutnetsim
d95c07f77330af8cefe50a04b19a2d5cca23e0ae
924f2625898c4f00147e473a05704f7b91dac0c4
refs/heads/master
2021-01-10T13:10:00.678815
2010-04-14T08:38:01
2010-04-14T08:38:01
48,568,805
0
0
null
null
null
null
UTF-8
C++
false
false
3,486
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'gui_frame.h' ** ** Created: Wed Feb 3 16:50:57 2010 ** by: The Qt Meta Object Compiler version 59 (Qt 4.3.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../INC/gui_frame.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'gui_frame.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 59 #error "This file was generated using the moc from 4.3.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif static const uint qt_meta_data_gui_frame[] = { // content: 1, // revision 0, // classname 0, 0, // classinfo 9, 10, // methods 0, 0, // properties 0, 0, // enums/sets // signals: signature, parameters, type, tag, flags 25, 11, 10, 10, 0x05, 48, 10, 10, 10, 0x05, 60, 10, 10, 10, 0x05, // slots: signature, parameters, type, tag, flags 79, 10, 10, 10, 0x0a, 90, 10, 10, 10, 0x0a, 100, 10, 10, 10, 0x0a, 111, 10, 10, 10, 0x0a, 121, 10, 10, 10, 0x0a, 134, 10, 10, 10, 0x0a, 0 // eod }; static const char qt_meta_stringdata_gui_frame[] = { "gui_frame\0\0configureFile\0" "openConfigure(QString)\0globalfun()\0" "fileready(QString)\0openfile()\0newfile()\0" "editfile()\0testent()\0dirsetting()\0" "fileprocess(QString)\0" }; const QMetaObject gui_frame::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_gui_frame, qt_meta_data_gui_frame, 0 } }; const QMetaObject *gui_frame::metaObject() const { return &staticMetaObject; } void *gui_frame::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_gui_frame)) return static_cast<void*>(const_cast< gui_frame*>(this)); return QMainWindow::qt_metacast(_clname); } int gui_frame::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: openConfigure((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 1: globalfun(); break; case 2: fileready((*reinterpret_cast< QString(*)>(_a[1]))); break; case 3: openfile(); break; case 4: newfile(); break; case 5: editfile(); break; case 6: testent(); break; case 7: dirsetting(); break; case 8: fileprocess((*reinterpret_cast< QString(*)>(_a[1]))); break; } _id -= 9; } return _id; } // SIGNAL 0 void gui_frame::openConfigure(const QString & _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void gui_frame::globalfun() { QMetaObject::activate(this, &staticMetaObject, 1, 0); } // SIGNAL 2 void gui_frame::fileready(QString _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); }
[ "pengelmer@f37e807c-cba8-11de-937e-2741d7931076" ]
[ [ [ 1, 111 ] ] ]
b1bc2b754832624d6b4e1bdd566d79a137e222e2
1e5a2230acf1c2edfe8b9d226100438f9374e98a
/src/tabimswitch/NativeCodeLogger.cpp
57684ee6b2bdd12d092abc511a044e0bf3016ddb
[]
no_license
lifanxi/tabimswitch
258860fea291c935d3630abeb61436e20f5dcd09
f351fc4b04983e59d1ad2b91b85e396e1f4920ed
refs/heads/master
2020-05-20T10:53:41.990172
2008-10-15T11:15:41
2008-10-15T11:15:41
32,111,854
0
0
null
null
null
null
UTF-8
C++
false
false
1,749
cpp
#include "NativeCodeLogger.h" #include "LoggerImpl.h" #include <windows.h> #include <vector> #include <atlbase.h> #include <atlconv.h> #include <iomanip> using std::setw; using std::setfill; using std::hex; CNativeLoggerConfig& CNativeLoggerConfig::instance(void) { static CNativeLoggerConfig config; return config; } void CNativeLoggerConfig::setLevel(LogLevel level) { LOGGER(LOG_MUST_PRINT) << "Native log level changed to " << level << endlog; m_level = level; } CLineLogger::CLineLoggerObj::CLineLoggerObj(void) : m_logFinished(false) {} CLineLogger::CLineLogger(LogLevel level, char const* srcfile, int srcline) : m_level(level) , m_srcFile(srcfile) , m_srcLine(srcline) , m_obj(new CLineLoggerObj()) { } CLineLogger::EndLogLine_t endlog; CLineLogger::~CLineLogger(void) { if ( ! isLogFinished() ) finishLog(); } void CLineLogger::finishLog(void) const { assert ( ! isLogFinished() ); FileLogger& logger = FileLogger::getLogger(); if ( shouldPrint() ) logger.write(m_srcFile, m_srcLine, m_level, m_obj->m_message.str().c_str()); m_obj->m_logFinished = true; } CLineLogger const& operator<<(CLineLogger const& logger, wchar_t const*const wideStr) { if ( wideStr != NULL ) { try { ATL::CW2A ansiString(wideStr); logger << static_cast<char const*>(ansiString); } catch (ATL::CAtlException& e) { logger << "(UNICODE conversion failure " << reinterpret_cast<void*>(e.m_hr) << ")"; } } else { logger << "(null)"; } return logger; } CLineLogger const& operator<<(CLineLogger const& logger, std::wstring const& wideStr) { logger << wideStr.c_str(); return logger; }
[ "ftofficer.zhangc@237747d1-5336-0410-8d3f-2982d197fc3e" ]
[ [ [ 1, 82 ] ] ]
19762edb389f7e91748e391e3921e4c95a2a3280
d76a67033e3abf492ff2f22d38fb80de804c4269
/src/opengl/resources.h
1879209686ff6b4e4352dda6f4b99da3d879969a
[ "Zlib" ]
permissive
truthwzl/lov8
869a6be317b7d963600f2f88edaefdf9b5996f2d
579163941593bae481212148041e0db78270c21d
refs/heads/master
2021-01-10T01:58:59.103256
2009-12-16T16:00:09
2009-12-16T16:00:09
36,340,451
0
0
null
null
null
null
UTF-8
C++
false
false
426
h
#ifndef LOVE_RESOURCES_H #define LOVE_RESOURCES_H #include <vector> #include <love/MemoryFile.h> namespace love { extern pFile Vera_ttf; extern pFile mini_moose_png; extern pFile logo128x64_png; extern pFile logo256x128_png; extern pFile rpgfont_png; extern pFile mutant_vermin_png; extern pFile big_love_ball_png; extern pFile freechan_png; extern pFile green_ball_png; extern pFile speak_cloud_png; } #endif
[ "m4rvin2005@8b5f54a0-8722-11de-9e21-49812d2d8162" ]
[ [ [ 1, 21 ] ] ]
f995fe3a98c98d3f36576e519652e5ecbb9046ed
a6a3df5a00bf2389f723e6cb8bd69fc3c0618301
/Notify.cpp
d3a1f5203a5a38f86e72674a973ef05cf8e50a96
[]
no_license
libfetion/libfetion-gui-wince
4de482e3451faf0bba885b14b57fc01b2bb980cd
b69456b10d888ff3b7421b401887a69333c72c12
refs/heads/master
2020-04-16T08:02:28.921130
2011-03-14T14:55:39
2011-03-14T14:55:39
32,465,759
0
1
null
null
null
null
UTF-8
C++
false
false
6,058
cpp
#include "StdAfx.h" #include "Notify.h" #ifdef WIN32_PLATFORM_WFSP #include "Resourcesp.h" #else #include "Resourceppc.h" #endif #ifdef WIN32_PLATFORM_WFSP #include "vibrate.h" #endif #ifdef WIN32_PLATFORM_PSPC #include <Nled.h> #if _WIN32_WCE<0x500 extern "C" { BOOL NLedGetDeviceInfo(INT nID, PVOID pOutput); BOOL NLedSetDevice(INT nID, PVOID pOutput); } #endif SHNOTIFICATIONDATA2* pNotification; int iMsgCount; #endif static const GUID guidNotifyApp = { 0x569440f0, 0xc5b4, 0x4ac2, { 0xa9, 0xab, 0xc6, 0x16, 0xd1, 0x9c, 0x1, 0x2f } }; void CNotify::CreateAndAddNotification(HWND hwnd, CString szTitle, CString szNotify) { #ifdef WIN32_PLATFORM_PSPC if(pNotification == NULL) { iMsgCount ++; //HICON hIcon =(HICON)LoadImage(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_ICON_NOTIFY), // IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR); TCHAR szMsgTitle[128]; TCHAR szMsgBody[1024]; wsprintf(szMsgTitle, TEXT("收到来自 %s 的飞信消息"), szTitle); #ifndef NOTIF_NUM_SOFTKEYS wsprintf(szMsgBody, TEXT("<html><body><form method=\"POST\" action=>%s<p><input type=button name='cmd:%u' value='查看'>&nbsp;<input type=button name='cmd:%u' value='取消'></body></html>"), szNotify, IDM_MAIN_SHOWNEWMSG2, IDM_MAIN_DIMISS); #else wsprintf(szMsgBody, TEXT("<html><body><form method=\"POST\" action=>%s</body></html>"), szNotify); #endif pNotification =(SHNOTIFICATIONDATA2*)malloc( sizeof(SHNOTIFICATIONDATA2)); ZeroMemory(pNotification, sizeof(SHNOTIFICATIONDATA2)); pNotification->dwID = (DWORD)hwnd; pNotification->clsid = guidNotifyApp; pNotification->npPriority = SHNP_INFORM; pNotification->csDuration = 20; pNotification->hwndSink = hwnd; pNotification->pszHTML = szMsgBody; pNotification->hicon = LoadIcon(AfxGetApp()->m_hInstance, MAKEINTRESOURCE(IDI_ICON_NOTIFY)); #ifndef NOTIF_NUM_SOFTKEYS pNotification->cbStruct = sizeof(SHNOTIFICATIONDATA); #else pNotification->cbStruct = sizeof(SHNOTIFICATIONDATA2); #endif pNotification->pszTitle = szMsgTitle; pNotification->grfFlags = SHNF_ALERTONUPDATE | SHNF_DISPLAYON; pNotification->rgskn[0].pszTitle = TEXT("查看"); pNotification->rgskn[0].skc.wpCmd = IDM_MAIN_SHOWNEWMSG2; pNotification->rgskn[0].skc.grfFlags = NOTIF_SOFTKEY_FLAGS_DISMISS; pNotification->rgskn[1].pszTitle = TEXT("忽略"); pNotification->rgskn[1].skc.wpCmd = IDM_MAIN_DIMISS; pNotification->rgskn[1].skc.grfFlags = NOTIF_SOFTKEY_FLAGS_DISMISS; LRESULT ret = SHNotificationAdd(pNotification); } else { iMsgCount ++; TCHAR szMsgBody[1024]; #ifndef NOTIF_NUM_SOFTKEYS wsprintf(szMsgBody, TEXT("<html><body><form method=\"POST\" action=>收到 %d 条消息!<input type=button name='cmd:%u' value='查看'>&nbsp;<input type=button name='cmd:%u' value='取消'></body></html>"), iMsgCount, IDM_MAIN_SHOWNEWMSG2, IDM_MAIN_DIMISS); #else wsprintf(szMsgBody, TEXT("<html><body><form method=\"POST\" action=>收到 %d 条消息!</body></html>"), iMsgCount); #endif pNotification->pszTitle = TEXT("LibFetion提醒"); pNotification->pszHTML = szMsgBody; SHNotificationUpdate(SHNUM_TITLE | SHNUM_HTML, pNotification); } #endif return; } // function removed all nodes in the list // called when the programme exits void CNotify::RemoveNotification() { #ifdef WIN32_PLATFORM_PSPC if(pNotification != NULL) { SHNotificationRemove(&guidNotifyApp, pNotification->dwID); //FreeNotificationData(pNotification); free(pNotification); iMsgCount = 0; pNotification = NULL; } #endif } #define TIMER_STOPVIBRATE 30 #ifdef WIN32_PLATFORM_WFSP //SP用于停止振动 void CALLBACK StopVib( HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime ) { //停止振动 VibrateStop(); } #endif #ifdef WIN32_PLATFORM_PSPC //PPC振动函数 int m_LedNum = 0; bool m_bLedInited = false; void StartVirbate( ) { NLED_SETTINGS_INFO settings ; memset(&settings,0,sizeof(NLED_SETTINGS_INFO)); NLED_COUNT_INFO nci; if(!m_bLedInited) { if(NLedGetDeviceInfo(NLED_COUNT_INFO_ID, (PVOID) &nci)) { for(int i = 0; i < (int)nci.cLeds; i++) { NLED_SUPPORTS_INFO nsi; nsi.LedNum = i; if(NLedGetDeviceInfo(NLED_SUPPORTS_INFO_ID, (PVOID) &nsi)) { // 该条件是判断振动器是否可用的条件 if(-1 == nsi.lCycleAdjust) { m_LedNum = i; break; } } } } m_bLedInited = true; } settings.LedNum = m_LedNum; settings.OffOnBlink = 1; NLedSetDevice(NLED_SETTINGS_INFO_ID, &settings); } void StopVirbate(HWND hwnd, UINT idEvent, UINT_PTR, DWORD ) { NLED_SETTINGS_INFO settings; memset(&settings,0,sizeof(NLED_SETTINGS_INFO)); settings.LedNum= m_LedNum; settings.OffOnBlink= 0; NLedSetDevice(NLED_SETTINGS_INFO_ID, &settings); KillTimer(hwnd, TIMER_STOPVIBRATE); } #endif CNotify::CNotify(void) { } CNotify::~CNotify(void) { } // 播放指定的声音或振动 // 如果strPath不为空, 则播放声音 void CNotify::Nodify(HWND hwnd, LPCWSTR strPath, int iPeriod, BOOL bSound, BOOL bVibr, UINT Styles) { if(bVibr) { #ifdef WIN32_PLATFORM_PSPC StartVirbate(); SetTimer(hwnd, TIMER_STOPVIBRATE, iPeriod, StopVirbate); #endif #ifdef WIN32_PLATFORM_WFSP Vibrate (0, NULL, FALSE, INFINITE); SetTimer(hwnd, TIMER_STOPVIBRATE, iPeriod, StopVib); #endif } if(bSound) { PlaySound (strPath, AfxGetApp()->m_hInstance, Styles | SND_ASYNC); } } void CNotify::StartViberate(bool bVibe) { if(!bVibe) return; // TODO 开始振动 } void CNotify::StopViberate(bool bVibe) { if(!bVibe) return; // TODO 停止振动 }
[ "shikun.z@8f3339bc-7e71-11dd-a943-c76e4c82ec5c", "gladyeti@8f3339bc-7e71-11dd-a943-c76e4c82ec5c", "daviyang35@8f3339bc-7e71-11dd-a943-c76e4c82ec5c" ]
[ [ [ 1, 2 ], [ 8, 31 ], [ 33, 42 ], [ 51, 56 ], [ 62, 62 ], [ 64, 74 ], [ 80, 139 ], [ 154, 156 ], [ 158, 169 ], [ 171, 183 ], [ 185, 196 ], [ 198, 198 ], [ 200, 217 ] ], [ [ 3, 7 ], [ 32, 32 ], [ 43, 50 ], [ 57, 61 ], [ 63, 63 ], [ 75, 79 ], [ 140, 153 ], [ 157, 157 ], [ 170, 170 ], [ 184, 184 ] ], [ [ 197, 197 ], [ 199, 199 ] ] ]
80f4a6d91fdbcc3071967047e05a27e326b8d6ca
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
/matlab/mex_pyr_builder_vxl.cpp
3aeb415f97a3b2543c08911b287eaef3a217caa7
[]
no_license
chenbk85/alcordev
41154355a837ebd15db02ecaeaca6726e722892a
bdb9d0928c80315d24299000ca6d8c492808f1d5
refs/heads/master
2021-01-10T13:36:29.338077
2008-10-22T15:57:50
2008-10-22T15:57:50
44,953,286
0
1
null
null
null
null
UTF-8
C++
false
false
5,626
cpp
//MATLAB Includes #include "mex.h" //VXL Includes #include <vcl_iostream.h> #include <vimt/vimt_image_pyramid.h> #include <vimt/vimt_image_2d_of.h> #include <vimt/vimt_gaussian_pyramid_builder_2d.h> #include <vimt/vimt_dog_pyramid_builder_2d.h> #include <vil/vil_image_view.h> #include <vil/vil_convert.h> #include <vil/algo/vil_sobel_3x3.h> #include <vil/vil_convert.h> #include <vil/vil_save.h> #include <vil\algo\vil_histogram_equalise.h> #include <vil/vil_transpose.h> #include <vxl_config.h> // for vxl_byte //#include <vcl_iostream.h> //Linker #pragma comment (lib, "ws2_32.lib") #pragma comment (lib, "vsl.lib") #pragma comment (lib, "vcl.lib") #pragma comment (lib, "vil.lib") #pragma comment (lib, "vil_algo.lib") #pragma comment (lib, "vil_io.lib") #pragma comment (lib, "png.lib") #pragma comment (lib, "tiff.lib") #pragma comment (lib, "jpeg.lib") #pragma comment (lib, "vnl.lib") //#pragma comment (lib, "vsl.lib") #pragma comment (lib, "vgl.lib") #pragma comment (lib, "vimt.lib") //#pragma comment (lib, "vimt_algo.lib") //#pragma comment (lib, "vul.lib") #pragma comment (lib, "z.lib") //#pragma comment (lib, "netlib.lib") //#pragma comment (lib, "v3p_netlib.lib") //#pragma comment (lib, "vimt_algo.lib") //Local Defines #define MX_INPUT_IMAGE prhs[0] void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray *prhs[] ) { if(nrhs > 0) { if ( mxIsUint8(MX_INPUT_IMAGE) ) { vxl_byte* input_image_ptr = static_cast<vxl_byte*>(mxGetData(MX_INPUT_IMAGE)); size_t n = mxGetN(MX_INPUT_IMAGE); size_t m = mxGetM(MX_INPUT_IMAGE); //const mwSize* im_size = mxGetDimensions(MX_INPUT_IMAGE); printf("Size: M: %d N:%d\n", m, n); // vil_image_view<vxl_byte> base_image_view(input_image_ptr ,n,m // ,1,1 ,1 ,m*n); vil_image_view<vxl_byte> base_image_view2(input_image_ptr ,m,n // ,1,1 ,1 ,m*n); //I tried this one and it succeded ... but if passed as //argument to algorithms it fails. //This seems to me a logical way to build a //vil_image_view from a column major raw memory array // M rows and N columns. vil_image_view<vxl_byte> cmajor_image(input_image_ptr ,n,m // ,m,1 ,1 ,m*n); base_image_view; base_image_view2; printf("Vil images Created\n"); printf("save base_image_view\n"); vil_save(base_image_view , "base_image_view_1.pnm"); vil_save(base_image_view2 , "base_image_view_2.pnm"); printf ("Transpose_1\n"); vil_image_view<vxl_byte> transposed_view = vil_transpose(base_image_view); printf ("Transpose_2\n"); vil_image_view<vxl_byte> transposed_view2 = vil_transpose(base_image_view2); printf("Saving Transposed\n"); vil_save(transposed_view, "transposed_view_1.pnm"); vil_save(transposed_view2, "transposed_view_2.ppm"); printf("vil_histogram_equalise 1\n"); vil_histogram_equalise(transposed_view); printf("vil_histogram_equalise 2\n"); vil_histogram_equalise(transposed_view2); printf("save base_image_view hist\n"); vil_save(transposed_view , "vil_histogram_equalise_1.ppm"); printf("save base_image_view hist\n"); vil_save(transposed_view2 , "vil_histogram_equalise_2.ppm"); // printf("Vimt Pyramid\n"); vimt_image_2d_of<vxl_byte> base_image_b(transposed_view); vimt_image_pyramid image_pyr; vimt_gaussian_pyramid_builder_2d<vxl_byte> builder; printf("Build Pyramid\n"); builder.build(image_pyr, base_image_b); printf("Levels: %d\n", image_pyr.n_levels()); //save level 2 vimt_image_2d_of<float> level2; vil_image_view<vxl_byte> level_2image; level2 = static_cast<vimt_image_2d_of<float>& > (image_pyr(2)) ; vil_convert_stretch_range(level2.image(),level_2image); vil_save(level_2image,"level2.ppm"); printf("Flattening\n"); vimt_image_2d_of<vxl_byte> gauss_pyr; vimt_image_pyramid_flatten(gauss_pyr, image_pyr); //// printf("Saving\n"); vil_save(gauss_pyr.image(),"pyramid.ppm"); //DOG vimt_image_2d_of<float> image_f, flat_dog, flat_smooth; vil_convert_cast(transposed_view, image_f.image()); vimt_image_pyramid dog_pyramid,smooth_pyramid; vimt_dog_pyramid_builder_2d<float> pyr_builder; pyr_builder.build_dog(dog_pyramid,smooth_pyramid,image_f); vimt_image_pyramid_flatten(flat_dog,dog_pyramid); vimt_image_pyramid_flatten(flat_smooth,smooth_pyramid); vil_image_view<vxl_byte> out_dog; vil_convert_stretch_range(flat_dog.image(),out_dog); vil_save(out_dog, "dog_pyramid.png"); vcl_cout<<"DoG saved "<< vcl_endl; vil_image_view<vxl_byte> out_smooth; vil_convert_stretch_range(flat_smooth.image(),out_smooth); vil_save(out_smooth,"smooth_pyramid.png"); vcl_cout<< "Smooth pyramid saved" <<vcl_endl; } else { printf("Image is not Uint8\n"); } } }
[ "andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81" ]
[ [ [ 1, 179 ] ] ]
196e13924f47419e3c9dc2dd425500cd196a0d82
8ce47e73afa904a145a1104fa8eaa71e3a237907
/Robot/controller/Path.h
fe5b05deb409e034cfaeefbf248a86e969e083c6
[]
no_license
nobody/magiclegoblimps
bc4f1459773773599ec397bdd1a43b1c341ff929
d66fe634cc6727937a066118f25847fa7d71b8f6
refs/heads/master
2021-01-23T15:42:15.729310
2010-05-05T03:15:00
2010-05-05T03:15:00
39,790,220
1
0
null
null
null
null
UTF-8
C++
false
false
668
h
#ifndef PATH_H #define PATH_H #include <vector> #include "GridLoc.h" //#include "Robot.h" using namespace std; class Path { public: Path(void); void extend(GridLoc* pt); GridLoc* advPath(void); void setMetric(double newMet); void clearPath(void); vector<GridLoc*> getPath(void); GridLoc* getStart(void); GridLoc* getEnd(void); int getSize(void); double getMetric(void) const; Path* copy(void); bool contains(GridLoc& gl); void calcMetric(GridLoc curr, GridLoc dest); bool operator()(const Path* p1, const Path* p2); void print(); ~Path(void); private: vector<GridLoc*> path; double metric; }; #endif
[ "tsheerin@445d4ad4-0937-11df-b996-818f58f34e26" ]
[ [ [ 1, 40 ] ] ]
8bd9a5443aeea6b8e5dad7d8196a27492b59b950
0454def9ffc8db9884871a7bccbd7baa4322343b
/src/remoteimages/QUCoverGroup.h
f2692a02e566685e9488362c9e8957a52238dd07
[]
no_license
escaped/uman
e0187d1d78e2bb07dade7ef6ef041b6ed424a2d3
bedc1c6c4fc464be4669f03abc9bac93e7e442b0
refs/heads/master
2016-09-05T19:26:36.679240
2010-07-26T07:55:31
2010-07-26T07:55:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
997
h
#ifndef QUCOVERGROUP_H_ #define QUCOVERGROUP_H_ #include "QU.h" #include "QUSongItem.h" #include "QURemoteImageSourcePlugin.h" #include <QWidget> #include <QSize> #include "ui_QUCoverGroup.h" class QUCoverGroup: public QWidget, public Ui::QUCoverGroup { Q_OBJECT public: QUCoverGroup(QUSongItem *item, QURemoteImageCollector *collector, QWidget *parent = 0); void getCovers(); void copyCoverToSongPath(bool deleteCurrentCover = false); void setCollector(QURemoteImageCollector *collector); QUSongItem* songItem() const { return _item; } public slots: void openAmazonSearchUrl(); void showStatus(const QString &status); void showCovers(); void showFailure(); protected: QUSongFile* song() const { return _item->song(); } QURemoteImageCollector* collector() const { return _collector; } private: QUSongItem *_item; QURemoteImageCollector *_collector; QString currentFilePath() const; }; #endif /* QUCOVERGROUP_H_ */
[ [ [ 1, 43 ] ] ]
4bd2d3863e213b995ce4c797f69651b760fb6ceb
be0db8bf2276da4b71a67723bbe8fb75e689bacb
/Src/App/init.cpp
d888c01b5df8390fb58162ef1efbd36db997300d
[]
no_license
jy02140486/cellwarfare
21a8eb793b94b8472905d793f4b806041baf57bb
85f026efd03f12dd828817159b9821eff4e4aff0
refs/heads/master
2020-12-24T15:22:58.595707
2011-07-24T12:36:45
2011-07-24T12:36:45
32,970,508
0
0
null
null
null
null
UTF-8
C++
false
false
6,030
cpp
#include "app.h" #include "event.h" #include <time.h> bool T_App::init() { try { //initail window description mWinDesc.set_title("CellWarfare"); mWinDesc.set_allow_resize(true); mWinDesc.set_size(CL_Size (800, 600), false); CL_String resource("../Res/GUITheme/resources.xml"); CL_String theme("../Res/GUITheme/theme.css"); //initail resource manager mResManager.load(resource); ////initail gui theme mGUITheme.set_resources(mResManager); //initail gui mpDisplayWindow = new CL_DisplayWindow(mWinDesc); mpWinManager = new CL_GUIWindowManagerTexture(*mpDisplayWindow); mGui.set_window_manager(*mpWinManager); mGui.set_theme(mGUITheme); mGui.set_css_document(theme); mpWinManager->func_repaint().set(this, &T_App::render); //initail GUIComponet window CL_DisplayWindowDescription comWindowDesc; comWindowDesc.show_border(false); comWindowDesc.set_allow_resize(true); comWindowDesc.set_title("settings"); comWindowDesc.set_size(CL_Size(300, 570),false); comWindowDesc.set_allow_resize(true); comWindowDesc.set_layered(true); mpComWindow = new CL_Window(&mGui, comWindowDesc); mpComWindow->set_draggable(false); //initail events mInput = mpDisplayWindow->get_ic(); mKeyboard = mInput.get_keyboard(); mMouse = mInput.get_mouse(); //mJoystick = mInput.get_joystick(); mpConsole = new CL_ConsoleWindow("Console", 80, 100); entites=new EM(); entites->iniLVs(); words=new CL_Font(mpComWindow->get_gc(),"Tahoma",20); offset.x=320; offset.y=420; entites->initScrObjs(); body=new CL_Image(mpDisplayWindow->get_gc(),"../res/body.png"); stage_clear=new CL_Image(mpDisplayWindow->get_gc(),"../res/stage clear.png"); if(RandomVal::randombool()) gameover=new CL_Image(mpDisplayWindow->get_gc(),"../res/gameover2.png"); else gameover=new CL_Image(mpDisplayWindow->get_gc(),"../res/gameover.png"); all_clear=new CL_Image(mpDisplayWindow->get_gc(),"../res/allclear.png"); //init menu items mx=new CL_LineEdit(mpComWindow); mx->set_geometry(CL_Rect(40,40, CL_Size(80, 20))); my=new CL_LineEdit(mpComWindow); my->set_geometry(CL_Rect(40,80, CL_Size(80, 20))); cirfirm=new CL_PushButton(mpComWindow); cirfirm->set_text("enter"); cirfirm->set_geometry(CL_Rect(40,500, CL_Size(150, 30))); cirfirm->func_clicked().set(this,&T_App::ButtonClick); PainKiller=new CL_PushButton(mpComWindow); PainKiller->set_text("PainKiller"); PainKiller->set_geometry(CL_Rect(40,540, CL_Size(100, 20))); PainKiller->func_clicked().set(this,&T_App::takePill); CL_Point lboffset(10,10); CL_Size sspin(80,20); CL_Size slb(80,20); infoBF=new CL_Label(mpComWindow); infoBF->set_geometry(CL_Rect(10,110, CL_Size(290, 300))); infoBF->set_text("infobf"); infoBF->set_visible(false); lbcellsdeployed=new CL_Label(infoBF); lbcellsdeployed->set_geometry(CL_Rect(lboffset.x,lboffset.y+5, slb)); lbcellsdeployed->set_text("Cells deployed"); cellsdeployed=new CL_Spin(infoBF); cellsdeployed->set_geometry(CL_Rect(lboffset.x+80,lboffset.y, sspin)); cellsdeployed->set_step_size(1); cellsdeployed->set_ranges(0,100); cellsdeployed->set_value(entites->curLV->defbfs[0].ImmunityPoints); lbintruders=new CL_Label(infoBF); lbintruders->set_geometry(CL_Rect(lboffset.x,lboffset.y+35, slb)); lbintruders->set_text("Intruders"); intruders=new CL_Spin(infoBF); intruders->set_geometry(CL_Rect(lboffset.x+80,lboffset.y+30, sspin)); lbtimeleft=new CL_Label(infoBF); lbtimeleft->set_geometry(CL_Rect(lboffset.x,lboffset.y+65, slb)); lbtimeleft->set_text("Time left"); timeleft=new CL_ProgressBar(infoBF); timeleft->set_geometry(CL_Rect(lboffset.x+80,lboffset.y+65, slb)); timeleft->set_min(0); timeleft->set_max(40); timeleft->set_position(20); SendingCirfirm=new CL_PushButton(infoBF); SendingCirfirm->set_geometry(CL_Rect(lboffset.x,lboffset.y+95, slb)); SendingCirfirm->set_text("Send"); SendingCirfirm->func_clicked().set(this,&T_App::OnSendingCirfirmClick); //tatical layer TaticalBoard=new CL_Label(mpComWindow); TaticalBoard->set_geometry(CL_Rect(10,310, CL_Size(290, 200))); TaticalBoard->set_text("TaticalBoard"); TaticalBoard->set_visible(true); // TaticalBoard->set_constant_repaint(true); lbTcellsdeployed=new CL_Label(TaticalBoard); lbTcellsdeployed->set_geometry(CL_Rect(lboffset.x,lboffset.y+5, slb)); lbTcellsdeployed->set_text("Cells deployed"); lbTcellsdeployed->set_visible(true); Tcellsdeployed=new CL_Label(TaticalBoard); Tcellsdeployed->set_geometry(CL_Rect(lboffset.x+100,lboffset.y+5, slb)); Tcellsdeployed->set_text("Cells deployed"); Tcellsdeployed->set_visible(true); lbTintruders=new CL_Label(TaticalBoard); lbTintruders->set_geometry(CL_Rect(lboffset.x,lboffset.y+15, slb)); lbTintruders->set_text("Itruders"); lbTintruders->set_visible(true); Tintruders=new CL_Label(TaticalBoard); Tintruders->set_geometry(CL_Rect(lboffset.x+100,lboffset.y+15, slb)); Tintruders->set_text("Itruders"); Tintruders->set_visible(true); entites->hero->eventTimer->func_expired().set(this,&T_App::invading_LogicLayer_Failure); entites->hero->eventTimer->begin(true); //LibDebugOnConsole(); time(&Atime); } catch (CL_Exception &exception) { CL_Console::write_line("Exception:Init error", exception.get_message_and_stack_trace()); // mpConsole->display_close_message(); CL_Console::write_line(exception.get_message_and_stack_trace()); return true; } running=true; T_Event::eventInit(); T_App::eventInit(); // slotMouseDown = mMouse.sig_key_down().connect(this, // &T_App::onMouseDown); return true; } void T_App::OnSendingCirfirmClick() { if (entites->SOselected!=NULL) { entites->SOselected->datas->ImmunityPoints+=cellsdeployed->get_value(); if (entites->hero->ImmunityPoints->minusable(cellsdeployed->get_value())) { entites->hero->ImmunityPoints->minus(cellsdeployed->get_value()); } } }
[ "[email protected]@7e182df5-b8f1-272d-db4e-b61a9d634eb1" ]
[ [ [ 1, 198 ] ] ]
1b8f3a25c8c5d2964f98b77819d83d1a653fd099
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/gui/nguihorisliderboxed_main.cc
9cc715fba8a8b0bb24098504c8b93d1f9d188079
[]
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
7,355
cc
#include "precompiled/pchngui.h" //------------------------------------------------------------------------------ // nGuiHoriSliderBoxed_main.cc // (C) 2004 RadonLabs GmbH //------------------------------------------------------------------------------ #include "gui/nGuiHoriSliderBoxed.h" #include "gui/nguiserver.h" #include "gui/nguiskin.h" nNebulaClass(nGuiHoriSliderBoxed, "nguiformlayout"); //--- MetaInfo --------------------------------------------------------------- /** @scriptclass nGuiHoriSliderBoxed @cppclass nGuiHoriSliderBoxed @superclass nguiformlayout @classinfo Docs needed. */ //------------------------------------------------------------------------------ /** */ nGuiHoriSliderBoxed::nGuiHoriSliderBoxed() : labelFont("GuiSmall"), minValue(0), maxValue(10), curValue(0), knobSize(1), leftWidth(0.2f), rightWidth(0.1f) { // empty } //------------------------------------------------------------------------------ /** */ nGuiHoriSliderBoxed::~nGuiHoriSliderBoxed() { // empty } //------------------------------------------------------------------------------ /** */ void nGuiHoriSliderBoxed::OnShow() { nGuiSkin* skin = nGuiServer::Instance()->GetSkin(); n_assert(skin); nGuiFormLayout::OnShow(); kernelServer->PushCwd(this); // text entry sizes vector2 textSize = nGuiServer::Instance()->ComputeScreenSpaceBrushSize("textentry_n"); vector2 textMinSize(0.0f, textSize.y); vector2 textMaxSize(1.0f, textSize.y); // create slider widget nGuiSlider2* slider = (nGuiSlider2*) kernelServer->New("nguislider2", "Slider"); n_assert(slider); slider->SetRangeSize(float((this->maxValue - this->minValue) + this->knobSize)); slider->SetVisibleRangeStart(float(this->curValue - this->minValue)); slider->SetVisibleRangeSize(float(this->knobSize)); slider->SetHorizontal(true); this->AttachForm(slider, Top, 0.0f); this->AttachPos(slider, Left, this->leftWidth); this->AttachPos(slider, Right, 1.0f - this->rightWidth); slider->OnShow(); this->refSlider = slider; const vector2& sliderMinSize = slider->GetMinSize(); const vector2& sliderMaxSize = slider->GetMaxSize(); // create left text label nGuiTextLabel* leftLabel = (nGuiTextLabel*) kernelServer->New("nguitextlabel", "LeftLabel"); n_assert(leftLabel); leftLabel->SetText(this->leftText.Get()); leftLabel->SetFont(this->GetLabelFont()); leftLabel->SetAlignment(nGuiTextLabel::Right); leftLabel->SetColor(skin->GetLabelTextColor()); leftLabel->SetMinSize(vector2(0.0f, sliderMinSize.y)); leftLabel->SetMaxSize(vector2(1.0f, sliderMaxSize.y)); this->AttachForm(leftLabel, Top, 0.0f); this->AttachForm(leftLabel, Left, 0.0f); this->AttachPos(leftLabel, Right, this->leftWidth); leftLabel->OnShow(); this->refLeftLabel = leftLabel; // create right text entry nGuiTextEntry* textEntry = (nGuiTextEntry*) kernelServer->New("nguitextentry", "RightEntry"); n_assert(textEntry); textEntry->SetText("0"); textEntry->SetFont("GuiSmall"); textEntry->SetAlignment(nGuiTextLabel::Left); textEntry->SetColor(vector4(0.0f, 0.0f, 0.0f, 1.0f)); textEntry->SetMinSize(textMinSize); textEntry->SetMaxSize(textMaxSize); textEntry->SetDefaultBrush("textentry_n"); textEntry->SetPressedBrush("textentry_p"); textEntry->SetHighlightBrush("textentry_h"); textEntry->SetDisabledBrush("textentry_d"); textEntry->SetCursorBrush("textcursor"); textEntry->SetColor(vector4(0.85f, 0.85f, 0.85f, 1.0f)); this->AttachForm(textEntry, Top, 0.0f); this->AttachForm(textEntry, Right, 0.005f); this->AttachPos(textEntry, Left, 1.0f - this->rightWidth); textEntry->OnShow(); this->refTextEntry = textEntry; kernelServer->PopCwd(); this->SetMinSize(sliderMinSize); this->SetMaxSize(sliderMaxSize); this->UpdateLayout(this->rect); nGuiServer::Instance()->RegisterEventListener(this); } //------------------------------------------------------------------------------ /** */ void nGuiHoriSliderBoxed::SetMaxLength(int l) { this->refTextEntry->SetMaxLength(l); } //------------------------------------------------------------------------------ /** */ void nGuiHoriSliderBoxed::OnHide() { nGuiServer::Instance()->UnregisterEventListener(this); this->ClearAttachRules(); if (this->refSlider.isvalid()) { this->refSlider->Release(); n_assert(!this->refSlider.isvalid()); } if (this->refLeftLabel.isvalid()) { this->refLeftLabel->Release(); n_assert(!this->refLeftLabel.isvalid()); } if (this->refTextEntry.isvalid()) { this->refTextEntry->Release(); n_assert(!this->refTextEntry.isvalid()); } nGuiFormLayout::OnHide(); } //------------------------------------------------------------------------------ /** */ void nGuiHoriSliderBoxed::OnFrame() { if (this->refSlider.isvalid()) { this->curValue = this->minValue + int(this->refSlider->GetVisibleRangeStart()); // update left and right label formatted strings char buf[1024]; snprintf(buf, sizeof(buf), this->leftText.Get(), this->curValue); this->refLeftLabel->SetText(buf); snprintf(buf, sizeof(buf), this->rightText.Get(), this->curValue); if (! this->refTextEntry->GetActive()) { this->refTextEntry->SetText(buf); this->refTextEntry->SetInitialCursorPos(nGuiTextLabel::Right); } } nGuiFormLayout::OnFrame(); } // juanga (from Nebula2SDK_2004) // added 29sept04: replicates the event, allowing handle values WHILE dragging the slider knob void nGuiHoriSliderBoxed::OnEvent(const nGuiEvent& event) { switch(event.GetType()) { case nGuiEvent::Char: case nGuiEvent::KeyUp: { if (this->refTextEntry.isvalid() && (event.GetWidget() == this->refTextEntry)) { // update slider this->SetValue(atoi(this->refTextEntry->GetText())); // replicate event, to process some other changes if needed on derivated classes nGuiEvent event(this, nGuiEvent::SliderChanged); nGuiServer::Instance()->PutEvent(event); } } break; case nGuiEvent::SliderChanged: { if (this->refSlider.isvalid() && (event.GetWidget() == this->refSlider)) { // replicate event nGuiEvent event(this, nGuiEvent::SliderChanged); nGuiServer::Instance()->PutEvent(event); // if the user touches the slider, disable cursor on textentry, so the value will be updated //this->refTextEntry->SetActive(false); } } break; default: { if (event.GetWidget() == this->refTextEntry) { //this->SetValue(atoi(this->refTextEntry->GetText())); } } break; } }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 234 ] ] ]
b0ae2c559ec6b3bd0c1954a8053a8e7be6aec3f8
81d3ba636ee63af055c917f13f6ebcb3b7e4717e
/juce/src/audio/midi/juce_MidiBuffer.cpp
4dad307c0e88d935e7b2d17eb7b6250f243b5ee2
[]
no_license
haibocheng/video_editor
cc68a4f02fc14756c2aa9369a536c8f49fef1334
40ab4a33642f70ea1c731f59aa062d82e7120bc7
refs/heads/master
2021-01-16T17:55:47.850527
2011-03-11T00:42:55
2011-03-11T00:42:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,274
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-10 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #include "../../core/juce_StandardHeader.h" BEGIN_JUCE_NAMESPACE #include "juce_MidiBuffer.h" //============================================================================== MidiBuffer::MidiBuffer() throw() : bytesUsed (0) { } MidiBuffer::MidiBuffer (const MidiMessage& message) throw() : bytesUsed (0) { addEvent (message, 0); } MidiBuffer::MidiBuffer (const MidiBuffer& other) throw() : data (other.data), bytesUsed (other.bytesUsed) { } MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw() { bytesUsed = other.bytesUsed; data = other.data; return *this; } void MidiBuffer::swapWith (MidiBuffer& other) throw() { data.swapWith (other.data); swapVariables <int> (bytesUsed, other.bytesUsed); } MidiBuffer::~MidiBuffer() { } inline uint8* MidiBuffer::getData() const throw() { return static_cast <uint8*> (data.getData()); } inline int MidiBuffer::getEventTime (const void* const d) throw() { return *static_cast <const int*> (d); } inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw() { return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int)); } inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw() { return getEventDataSize (d) + sizeof (int) + sizeof (uint16); } void MidiBuffer::clear() throw() { bytesUsed = 0; } void MidiBuffer::clear (const int startSample, const int numSamples) { uint8* const start = findEventAfter (getData(), startSample - 1); uint8* const end = findEventAfter (start, startSample + numSamples - 1); if (end > start) { const int bytesToMove = bytesUsed - (int) (end - getData()); if (bytesToMove > 0) memmove (start, end, bytesToMove); bytesUsed -= (int) (end - start); } } void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber) { addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber); } namespace MidiBufferHelpers { int findActualEventLength (const uint8* const data, const int maxBytes) throw() { unsigned int byte = (unsigned int) *data; int size = 0; if (byte == 0xf0 || byte == 0xf7) { const uint8* d = data + 1; while (d < data + maxBytes) if (*d++ == 0xf7) break; size = (int) (d - data); } else if (byte == 0xff) { int n; const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n); size = jmin (maxBytes, n + 2 + bytesLeft); } else if (byte >= 0x80) { size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte)); } return size; } } void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber) { const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes); if (numBytes > 0) { int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16); data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7); uint8* d = findEventAfter (getData(), sampleNumber); const int bytesToMove = bytesUsed - (int) (d - getData()); if (bytesToMove > 0) memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove); *reinterpret_cast <int*> (d) = sampleNumber; d += sizeof (int); *reinterpret_cast <uint16*> (d) = (uint16) numBytes; d += sizeof (uint16); memcpy (d, newData, numBytes); bytesUsed += numBytes + sizeof (int) + sizeof (uint16); } } void MidiBuffer::addEvents (const MidiBuffer& otherBuffer, const int startSample, const int numSamples, const int sampleDeltaToAdd) { Iterator i (otherBuffer); i.setNextSamplePosition (startSample); const uint8* eventData; int eventSize, position; while (i.getNextEvent (eventData, eventSize, position) && (position < startSample + numSamples || numSamples < 0)) { addEvent (eventData, eventSize, position + sampleDeltaToAdd); } } void MidiBuffer::ensureSize (size_t minimumNumBytes) { data.ensureSize (minimumNumBytes); } bool MidiBuffer::isEmpty() const throw() { return bytesUsed == 0; } int MidiBuffer::getNumEvents() const throw() { int n = 0; const uint8* d = getData(); const uint8* const end = d + bytesUsed; while (d < end) { d += getEventTotalSize (d); ++n; } return n; } int MidiBuffer::getFirstEventTime() const throw() { return bytesUsed > 0 ? getEventTime (data.getData()) : 0; } int MidiBuffer::getLastEventTime() const throw() { if (bytesUsed == 0) return 0; const uint8* d = getData(); const uint8* const endData = d + bytesUsed; for (;;) { const uint8* const nextOne = d + getEventTotalSize (d); if (nextOne >= endData) return getEventTime (d); d = nextOne; } } uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw() { const uint8* const endData = getData() + bytesUsed; while (d < endData && getEventTime (d) <= samplePosition) d += getEventTotalSize (d); return d; } //============================================================================== MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw() : buffer (buffer_), data (buffer_.getData()) { } MidiBuffer::Iterator::~Iterator() throw() { } //============================================================================== void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw() { data = buffer.getData(); const uint8* dataEnd = data + buffer.bytesUsed; while (data < dataEnd && getEventTime (data) < samplePosition) data += getEventTotalSize (data); } bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw() { if (data >= buffer.getData() + buffer.bytesUsed) return false; samplePosition = getEventTime (data); numBytes = getEventDataSize (data); data += sizeof (int) + sizeof (uint16); midiData = data; data += numBytes; return true; } bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw() { if (data >= buffer.getData() + buffer.bytesUsed) return false; samplePosition = getEventTime (data); const int numBytes = getEventDataSize (data); data += sizeof (int) + sizeof (uint16); result = MidiMessage (data, numBytes, samplePosition); data += numBytes; return true; } END_JUCE_NAMESPACE
[ [ [ 1, 300 ] ] ]
fcbbebb87d94c4c85a18ea12cc14967a0b5881db
faacd0003e0c749daea18398b064e16363ea8340
/3rdparty/phonon/globalconfig.cpp
52339f06f35301b63da205b122b0d05cbbc0d30c
[]
no_license
yjfcool/lyxcar
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
750be6c984de694d7c60b5a515c4eb02c3e8c723
refs/heads/master
2016-09-10T10:18:56.638922
2009-09-29T06:03:19
2009-09-29T06:03:19
42,575,701
0
0
null
null
null
null
UTF-8
C++
false
false
9,781
cpp
/* This file is part of the KDE project Copyright (C) 2006-2008 Matthias Kretz <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Trolltech ASA (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "globalconfig_p.h" #include "factory_p.h" #include "objectdescription.h" #include "phonondefs_p.h" #include "platformplugin.h" #include "backendinterface.h" #include "qsettingsgroup_p.h" #include "phononnamespace_p.h" #include <QtCore/QList> #include <QtCore/QVariant> QT_BEGIN_NAMESPACE namespace Phonon { GlobalConfig::GlobalConfig() : m_config(QLatin1String("kde.org"), QLatin1String("libphonon")) { } GlobalConfig::~GlobalConfig() { } enum WhatToFilter { FilterAdvancedDevices = 1, FilterHardwareDevices = 2, FilterUnavailableDevices = 4 }; static void filter(ObjectDescriptionType type, BackendInterface *backendIface, QList<int> *list, int whatToFilter) { QMutableListIterator<int> it(*list); while (it.hasNext()) { const QHash<QByteArray, QVariant> properties = backendIface->objectDescriptionProperties(type, it.next()); QVariant var; if (whatToFilter & FilterAdvancedDevices) { var = properties.value("isAdvanced"); if (var.isValid() && var.toBool()) { it.remove(); continue; } } if (whatToFilter & FilterHardwareDevices) { var = properties.value("isHardwareDevice"); if (var.isValid() && var.toBool()) { it.remove(); continue; } } if (whatToFilter & FilterUnavailableDevices) { var = properties.value("available"); if (var.isValid() && !var.toBool()) { it.remove(); continue; } } } } static QList<int> listSortedByConfig(const QSettingsGroup &backendConfig, Phonon::Category category, QList<int> &defaultList) { if (defaultList.size() <= 1) { // nothing to sort return defaultList; } else { // make entries unique QSet<int> seen; QMutableListIterator<int> it(defaultList); while (it.hasNext()) { if (seen.contains(it.next())) { it.remove(); } else { seen.insert(it.value()); } } } QString categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(category)); if (!backendConfig.hasKey(categoryKey)) { // no list in config for the given category categoryKey = QLatin1String("Category_") + QString::number(static_cast<int>(Phonon::NoCategory)); if (!backendConfig.hasKey(categoryKey)) { // no list in config for NoCategory return defaultList; } } //Now the list from m_config QList<int> deviceList = backendConfig.value(categoryKey, QList<int>()); //if there are devices in m_config that the backend doesn't report, remove them from the list QMutableListIterator<int> i(deviceList); while (i.hasNext()) { if (0 == defaultList.removeAll(i.next())) { i.remove(); } } //if the backend reports more devices that are not in m_config append them to the list deviceList += defaultList; return deviceList; } QList<int> GlobalConfig::audioOutputDeviceListFor(Phonon::Category category, int override) const { //The devices need to be stored independently for every backend const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioOutputDevice")); // + Factory::identifier()); const QSettingsGroup generalGroup(&m_config, QLatin1String("General")); const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings) ? generalGroup.value(QLatin1String("HideAdvancedDevices"), true) : static_cast<bool>(override & HideAdvancedDevices)); QList<int> defaultList; #ifndef QT_NO_PHONON_PLATFORMPLUGIN if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) { // the platform plugin lists the audio devices for the platform // this list already is in default order (as defined by the platform plugin) defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioOutputDeviceType); if (hideAdvancedDevices) { QMutableListIterator<int> it(defaultList); while (it.hasNext()) { AudioOutputDevice objDesc = AudioOutputDevice::fromIndex(it.next()); const QVariant var = objDesc.property("isAdvanced"); if (var.isValid() && var.toBool()) { it.remove(); } } } } #endif //QT_NO_PHONON_PLATFORMPLUGIN // lookup the available devices directly from the backend (mostly for virtual devices) if (BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend())) { // this list already is in default order (as defined by the backend) QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioOutputDeviceType); if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) { filter(AudioOutputDeviceType, backendIface, &list, (hideAdvancedDevices ? FilterAdvancedDevices : 0) // the platform plugin already provided the hardware devices | (defaultList.isEmpty() ? 0 : FilterHardwareDevices) | ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0) ); } defaultList += list; } return listSortedByConfig(backendConfig, category, defaultList); } int GlobalConfig::audioOutputDeviceFor(Phonon::Category category, int override) const { QList<int> ret = audioOutputDeviceListFor(category, override); if (ret.isEmpty()) return -1; return ret.first(); } #ifndef QT_NO_PHONON_AUDIOCAPTURE QList<int> GlobalConfig::audioCaptureDeviceListFor(Phonon::Category category, int override) const { //The devices need to be stored independently for every backend const QSettingsGroup backendConfig(&m_config, QLatin1String("AudioCaptureDevice")); // + Factory::identifier()); const QSettingsGroup generalGroup(&m_config, QLatin1String("General")); const bool hideAdvancedDevices = ((override & AdvancedDevicesFromSettings) ? generalGroup.value(QLatin1String("HideAdvancedDevices"), true) : static_cast<bool>(override & HideAdvancedDevices)); QList<int> defaultList; #ifndef QT_NO_PHONON_PLATFORMPLUGIN if (PlatformPlugin *platformPlugin = Factory::platformPlugin()) { // the platform plugin lists the audio devices for the platform // this list already is in default order (as defined by the platform plugin) defaultList = platformPlugin->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType); if (hideAdvancedDevices) { QMutableListIterator<int> it(defaultList); while (it.hasNext()) { AudioCaptureDevice objDesc = AudioCaptureDevice::fromIndex(it.next()); const QVariant var = objDesc.property("isAdvanced"); if (var.isValid() && var.toBool()) { it.remove(); } } } } #endif //QT_NO_PHONON_PLATFORMPLUGIN // lookup the available devices directly from the backend (mostly for virtual devices) if (BackendInterface *backendIface = qobject_cast<BackendInterface *>(Factory::backend())) { // this list already is in default order (as defined by the backend) QList<int> list = backendIface->objectDescriptionIndexes(Phonon::AudioCaptureDeviceType); if (hideAdvancedDevices || !defaultList.isEmpty() || (override & HideUnavailableDevices)) { filter(AudioCaptureDeviceType, backendIface, &list, (hideAdvancedDevices ? FilterAdvancedDevices : 0) // the platform plugin already provided the hardware devices | (defaultList.isEmpty() ? 0 : FilterHardwareDevices) | ((override & HideUnavailableDevices) ? FilterUnavailableDevices : 0) ); } defaultList += list; } return listSortedByConfig(backendConfig, category, defaultList); } int GlobalConfig::audioCaptureDeviceFor(Phonon::Category category, int override) const { QList<int> ret = audioCaptureDeviceListFor(category, override); if (ret.isEmpty()) return -1; return ret.first(); } #endif //QT_NO_PHONON_AUDIOCAPTURE } // namespace Phonon QT_END_NAMESPACE
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
[ [ [ 1, 243 ] ] ]
a895c5eb6bec1153d70cf30ce6fc9a001a90652b
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/CommonSources/TransmitterPattern/Transmitter.h
a7656b3abfc3434e8609eb6ac9d03591993fcc53
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
2,349
h
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * This Program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2, or (at your option) // * any later version. // * // * This Program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #pragma once #define MSG_TRANSMITTER_QUIT 0 class MessageDetails { public: virtual ~MessageDetails() {} }; class Receiver { public: virtual void OnMessage(UINT msgID, LPVOID sender, MessageDetails* detail) = 0; #ifdef _DEBUG virtual LPCTSTR GetReceiverName() = 0; #endif }; class Transmitter { public: virtual ~Transmitter() {} virtual void RegisterReceiver(Receiver& receiver) = 0; virtual void UnRegisterReceiver(Receiver& receiver) = 0; //===SendMessage //Sends a message directly to the Registered Receivers //- msgID: The App-Defined Identification of the message. *value 0 is reserved //- sender: [Optional]The sender of the message. //- detail: [Optional] Details for the message. // The receiver must be able to cast the derived MessageDetain through the ID virtual void SendMessage(UINT msgID, LPVOID sender = NULL, MessageDetails* detail = NULL) = 0; //===PostMessage //Queues the message in a storage. The message is being send in the next Heartbeat. //Extra options //- bGroupSimilar. Similar msgIDs may be grouped in one. virtual void PostMessage(UINT msgID, LPVOID sender = NULL, MessageDetails* detail = NULL, BOOL bGroupSimilar = FALSE) = 0; //===HeartBeat //- Posted Messages are send when HeartBeat is called virtual void HeartBeat() = 0; };
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 68 ] ] ]
a639677a435005c6c5c7a6fbaf88e99ebf90667a
e354a51eef332858855eac4c369024a7af5ff804
/tuples.cpp
06f31e5a6aa8953b44fc013f6649d2e6bc7ef212
[]
no_license
cjus/msgCourierLite
0f9c1e05b71abf820c55f74a913555eec2267bb4
9efc1d54737ba47620a03686707b31b1eeb61586
refs/heads/master
2020-04-05T22:41:39.141740
2010-09-05T18:43:12
2010-09-05T18:43:12
887,172
1
0
null
null
null
null
UTF-8
C++
false
false
3,040
cpp
/* tuples.cpp Copyright (C) 2006 Carlos Justiniano [email protected], [email protected], [email protected] tuples.cpp 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. tuples.cpp was developed by Carlos Justiniano for use on the msgCourier project and the ChessBrain Project and is now 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 tuples.cpp; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /** @file tuples.cpp @brief Tuple handling @author Carlos Justiniano @attention Copyright (C) 2006 Carlos Justiniano, GNU GPL Licence (see source file header) */ #include "tuples.h" #include "log.h" #include "exception.h" #include "cbstrtok.h" using namespace std; cTuples::cTuples() { } cTuples::~cTuples() { try { m_tuplesMap.erase(m_tuplesMap.begin(), m_tuplesMap.end()); } catch (exception const &e) { LOGALL(e.what()); } } const char *cTuples::Query(const char *pKey) { cAutoThreadSync ThreadSync(&m_ThreadSync); const char *pRet = 0; try { map<std::string,std::string>::iterator it; it = m_tuplesMap.find(pKey); if (it == m_tuplesMap.end()) pRet = 0; else pRet = ((*it).second).c_str(); } catch (exception const &e) { LOGALL(e.what()); } return pRet; } void cTuples::AddTupleStream(const char *pstring) { STRTOKVA; char *pSep = "|"; char *pToken1, *pToken2; int octval; char *pBuf; MC_NEW(pBuf, char[strlen(pstring)+1]); strcpy(pBuf, pstring); pToken1 = STRTOK(pBuf, pSep); if (pToken1 == NULL) return; while (1) { pToken2 = STRTOK(NULL, pSep); if (pToken2 == NULL) break; AddTuple(pToken1, pToken2); pToken1 = STRTOK(NULL, pSep); if (pToken1 == NULL) break; } delete []pBuf; } void cTuples::AddTuple(const char *pKey, const char *pValue) { cAutoThreadSync ThreadSync(&m_ThreadSync); try { string sKey = pKey; string sValue = pValue; map<std::string,std::string>::iterator it; it = m_tuplesMap.find(pKey); if (it == m_tuplesMap.end()) m_tuplesMap.insert(pair<string,string>(sKey, sValue)); else (*it).second = sValue; } catch (exception const &e) { LOGALL(e.what()); } } std::string cTuples::GetTupleStream() { cAutoThreadSync ThreadSync(&m_ThreadSync); string stream = ""; map<std::string,string>::iterator it; for (it = m_tuplesMap.begin(); it != m_tuplesMap.end(); it++) { stream += it->first; stream += "|"; stream += it->second; stream += "|"; } return stream; }
[ [ [ 1, 141 ] ] ]
86e0d4bc38154562db1dc62d2a8caf914a374f4f
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Include/ZipPlugin/Storage/ZipArchive.h
3a8197f48a7145fbf44dcbe579459c4faf1146ce
[]
no_license
dzw/stellarengine
2b70ddefc2827be4f44ec6082201c955788a8a16
2a0a7db2e43c7c3519e79afa56db247f9708bc26
refs/heads/master
2016-09-01T21:12:36.888921
2008-12-12T12:40:37
2008-12-12T12:40:37
36,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
3,954
h
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## ZipArchive.h - Zip archive implementation  // // ### # # ###  // // # ### # ### Represents a zip archive from which streams can be opened  // // # ## # # ## ## to read data out of compressed files  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #ifndef NUCLEX_STORAGE_ZIPARCHIVE_H #define NUCLEX_STORAGE_ZIPARCHIVE_H #include "ZipPlugin/ZipPlugin.h" #include "Nuclex/Storage/StorageServer.h" #include "Zipex/Zipex.h" namespace Nuclex { namespace Storage { //  // //  Nuclex::Storage::ZipArchive  // //  // /// Zip data storage class /** This storage implementation accesses a .zip archive. Zip archives store multiple files in a single compressed file. NuclexZip is able to directly read from and write to these these files without requiring to extract them. */ class ZipArchive : public Archive { public: /// Constructor NUCLEXZIP_API ZipArchive(const string &sZIPFile); /// Destructor NUCLEXZIP_API virtual ~ZipArchive(); // // Storage implementation // public: /// Get child type NUCLEXZIP_API ItemType getType(const string &sName) const; /// Get storage enumerator NUCLEXZIP_API shared_ptr<ArchiveEnumerator> enumArchives() const; /// Open a storage NUCLEXZIP_API shared_ptr<Archive> openArchive(const string &sName, bool bAllowCreate = false); /// Delete an existing storage NUCLEXZIP_API void deleteArchive(const string &sName); /// Get stream enumerator NUCLEXZIP_API shared_ptr<StreamEnumerator> enumStreams() const; /// Open a stream NUCLEXZIP_API shared_ptr<Stream> openStream(const string &sName, Stream::AccessMode eMode = Stream::AM_READ); /// Delete an existing stream NUCLEXZIP_API void deleteStream(const string &sName); private: /// Zip directory struct ZipDirectory; /// Zip sub stoage class SubZipArchive; friend SubZipArchive; Zipex::ZipArchive m_ZipArchive; ///< Zipex archive std::auto_ptr<ZipDirectory> m_spDirectory; ///< Zip directory }; //  // //  Nuclex::Storage::ZipArchiveFactory  // //  // /// ZipArchive factory /** Creates ZipArchives and checks whether a given source identifier can be opened as a zip file */ class ZipArchiveFactory : public StorageServer::ArchiveFactory { public: /// Destuctor /** Destroys an instance of ZipStorageFactory */ NUCLEXZIP_API virtual ~ZipArchiveFactory() {} // // StorageFactory implementation // public: /// Check whether storage can be created on specified source NUCLEXZIP_API bool canCreateArchive(const string &sSource) const; /// Create a storage from the specified source NUCLEXZIP_API shared_ptr<Archive> createArchive(const string &sSource); }; }} // namespace Nuclex::Storage #endif // NUCLEX_STORAGE_ZIPARCHIVE_H
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 96 ] ] ]
562dfe8f0ba8b268121e0c5d97ce5daa60798370
12ea67a9bd20cbeed3ed839e036187e3d5437504
/winxgui/Test/MfcGuiApp/MfcGuiApp.cpp
d911cad6345f2cfa3feadce15f2cc34c982f6972
[]
no_license
cnsuhao/winxgui
e0025edec44b9c93e13a6c2884692da3773f9103
348bb48994f56bf55e96e040d561ec25642d0e46
refs/heads/master
2021-05-28T21:33:54.407837
2008-09-13T19:43:38
2008-09-13T19:43:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,123
cpp
// MfcGuiApp.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "MfcGuiApp.h" #include "MfcGuiAppDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMfcGuiAppApp BEGIN_MESSAGE_MAP(CMfcGuiAppApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CMfcGuiAppApp construction CMfcGuiAppApp::CMfcGuiAppApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CMfcGuiAppApp object CMfcGuiAppApp theApp; // CMfcGuiAppApp initialization BOOL CMfcGuiAppApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); CMfcGuiAppDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }
[ "xushiweizh@86f14454-5125-0410-a45d-e989635d7e98" ]
[ [ [ 1, 78 ] ] ]
edd401d32889e3862267797b16e95a837164fe51
547a31c6d098df866be58befd8642ab773b32226
/vc/DataLogger/PDFLib/except.cpp
27cc6a57375c6a083714494715dce488274d5291
[]
no_license
neirons/pythondatalogger
64634d97eaa724a04707e4837dced51bcf750146
f1cd1aea4d63407c3d4156ddccd02339dc96dcec
refs/heads/master
2020-05-17T07:48:33.707106
2010-08-08T13:37:33
2010-08-08T13:37:33
41,642,510
0
0
null
null
null
null
UTF-8
C++
false
false
2,555
cpp
/*---------------------------------------------------------------------------* | PDFlib - A library for generating PDF on the fly | +---------------------------------------------------------------------------+ | Copyright (c) 1997-2002 PDFlib GmbH and Thomas Merz. All rights reserved. | +---------------------------------------------------------------------------+ | This software is NOT in the public domain. It can be used under two | | substantially different licensing terms: | | | | The commercial license is available for a fee, and allows you to | | - ship a commercial product based on PDFlib | | - implement commercial Web services with PDFlib | | - distribute (free or commercial) software when the source code is | | not made available | | Details can be found in the file PDFlib-license.pdf. | | | | The "Aladdin Free Public License" doesn't require any license fee, | | and allows you to | | - develop and distribute PDFlib-based software for which the complete | | source code is made available | | - redistribute PDFlib non-commercially under certain conditions | | - redistribute PDFlib on digital media for a fee if the complete | | contents of the media are freely redistributable | | Details can be found in the file aladdin-license.pdf. | | | | These conditions extend to ports to other programming languages. | | PDFlib is distributed with no warranty of any kind. Commercial users, | | however, will receive warranty and support statements in writing. | *---------------------------------------------------------------------------*/ /* $Id: except.c,v 1.1.2.6 2002/01/07 18:26:29 tm Exp $ */ #include "stdafx.h" #include <string.h> #include "pdflib.h" #include "except.h" void pdf_cpp_errorhandler(PDF *p, int type, const char *msg) { pdf_err_info *ei = (pdf_err_info *) PDF_get_opaque(p); ei->type = type; strcpy(ei->msg, msg); longjmp(ei->jbuf, 1); }
[ "shixiaoping79@5c1c4db6-e7b1-408c-73c2-e61316242a6a" ]
[ [ [ 1, 45 ] ] ]
59cfee9693984396770fc2f0acd89767985b10b0
188058ec6dbe8b1a74bf584ecfa7843be560d2e5
/GodDK/io/InputStream.cxx
e9fb7b8a2f429b4ea12c964b1cf68b8ad74d9c23
[]
no_license
mason105/red5cpp
636e82c660942e2b39c4bfebc63175c8539f7df0
fcf1152cb0a31560af397f24a46b8402e854536e
refs/heads/master
2021-01-10T07:21:31.412996
2007-08-23T06:29:17
2007-08-23T06:29:17
36,223,621
0
0
null
null
null
null
UTF-8
C++
false
false
1,429
cxx
#ifdef HAVE_CONFIG_H # include "config.h" #endif #include "io/InputStream.h" #include "lang/String.h" using goddk::lang::String; #include "lang/NullPointerException.h" using goddk::lang::NullPointerException; using namespace goddk::io; jint InputStream::available() throw (IOExceptionPtr) { return 0; } void InputStream::close() throw (IOExceptionPtr) { } void InputStream::mark(jint readlimit) throw () { } bool InputStream::markSupported() throw () { return false; } jint InputStream::read(bytearray& b) throw (IOExceptionPtr) { return read(b.data(), 0, b.size()); } jint InputStream::read(byte* data, jint offset, jint length) throw (IOExceptionPtr) { if (!data) THROWEXCEPTIONPTR(NullPointerException) jint b = read(); if (b < 0) return -1; data[offset] = (byte) b; jint i = 1; try { while (i < length) { b = read(); if (b < 0) break; data[offset+i++] = (byte) b; } } catch (IOException&) { // ignore } return i; } jint InputStream::skip(jint n) throw (IOExceptionPtr) { jint remaining = n; byte skip[2048]; while (remaining > 0) { jint rc = read(skip, 0, remaining > 2048 ? 2048 : remaining); if (rc < 0) break; remaining -= rc; } return n - remaining; } void InputStream::reset() throw (IOExceptionPtr) { THROWEXCEPTIONPTR1(IOException,"reset not supported"); }
[ "soaris@46205fef-a337-0410-8429-7db05d171fc8" ]
[ [ [ 1, 87 ] ] ]
ca0c3b13465618bea0dfd72c097003afb2d6d543
dae66863ac441ab98adbd2d6dc2cabece7ba90be
/examples/flexrun/ASWorkFlexRun.h
aad3385447c35be6ad42d6653b4001fb392c9140
[]
no_license
bitcrystal/flexcppbridge
2485e360f47f8d8d124e1d7af5237f7e30dd1980
474c17cfa271a9d260be6afb2496785e69e72ead
refs/heads/master
2021-01-10T14:14:30.928229
2008-11-11T06:11:34
2008-11-11T06:11:34
48,993,836
0
0
null
null
null
null
UTF-8
C++
false
false
1,045
h
/* * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Flex C++ Bridge. * * The Initial Developer of the Original Code is * Anirudh Sasikumar (http://anirudhs.chaosnet.org/). * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): * */ #pragma once #include "aswork.h" class CASWorkFlexRun : public CASWork { protected: virtual void Worker(); public: CASWorkFlexRun(void); virtual ~CASWorkFlexRun(void); virtual CASWork* Clone(); };
[ "anirudhsasikumar@1c1c0844-4f48-0410-9872-0bebc774e022" ]
[ [ [ 1, 37 ] ] ]
a3ad1bd45d9e85a51ef053669b789a3d94bf14b0
881321ed22c5c024aa515e0f152b7f9cc7d1decd
/Pathman/Game.h
1d10837d5e44fb7d5f2a621a67270ecc7e3f0f3d
[]
no_license
titarenko/Pathman
c37f756c08a1473fc0df561f303942cde97e1d90
1c998f57b02576574c48943734fcc0e22e9a63c3
refs/heads/master
2020-05-19T08:02:44.881983
2011-04-01T20:13:39
2011-04-01T20:13:39
3,443,429
0
0
null
null
null
null
UTF-8
C++
false
false
2,126
h
#pragma once #include <irrlicht.h> #include <irrKlang.h> #include "StageInfo.h" #include "EGameEvent.h" class GameConfig; /*! Represents root object of the game. */ class Game : irr::IEventReceiver { public: /*! Initializes game using provided config. @param configFilename Path to the config file. */ Game(const char* configFilename); /*! Deallocates resources. */ ~Game(void); /*! Implementation of irr::IEventReceiver. */ virtual bool OnEvent(const irr::SEvent& event); /*! Creates Irrlicht's root object using data from provided config as well as IrrKlang's root object. */ void createDevice(const GameConfig& config); /*! Returns pointer to the Irrlicht's root object. */ irr::IrrlichtDevice* getDevice() const; /*! Returns pointer to the IrrKlang's root object. */ irrklang::ISoundEngine* getSoundEngine() const; /*! Add assets pack to the Irrlicht's filesystem. @param filename Path to folder or archive file with assets. */ void addAssets(const irr::io::path& filename); /*! Broadcast event to all stages of the game. */ void broadcastEvent(E_GAME_EVENT event); /*! Updates game. Must be called until false is returned in order to run the game. */ bool update(); /*! Converts Irrlicht's user event to the game event. (Game events are broadcasted using Irrlicht's user event system.) */ static E_GAME_EVENT ToGameEvent(const irr::SEvent& event); /*! Enables additional render: scene will be rendered twice per frame. Special events shall be broadcasted before rendering additional time and after to allow stages to perform needed changes. */ void enableAdditionalRender(bool enable); /*! Enables or disables sounds. */ void enableSound(bool enable); private: irr::IrrlichtDevice* _device; irrklang::ISoundEngine* _soundEngine; irr::core::array<irr::IEventReceiver*> _stages; irr::u32 _sleepValue; bool _additionalRender; bool _soundEnabled; bool _soundAllowed; irr::IEventReceiver* createStage(const StageInfo& stage); };
[ [ [ 1, 95 ] ] ]
1202723c50d95b34b9514acdae35b3834d33f7d7
36135d8069401456e92aea4515a9504b6afdc8f4
/seeautz/source/glutFramework/glutFramework/projekt1App.cpp
ee23a826e65315fee8495496c5956fc43ecd5a51
[]
no_license
CorwinJV/seeautz-projekt1
82d03b19d474de61ef58dea475ac4afee11570a5
bbfb4ce0d341dfba9f4d076eced229bee5c9301c
refs/heads/master
2020-03-30T23:06:45.280743
2009-05-31T23:09:15
2009-05-31T23:09:15
32,131,398
0
0
null
null
null
null
UTF-8
C++
false
false
3,267
cpp
#include "projekt1App.h" #include "States\DevLogoState.h" #include "playGame.h" #include "oglGameVars.h" // start additional state includes for testing purposes, don't NEED to be here, but are anyways //#include "States\LogicViewState.h" #include "SG400KGA1.h" #include "helpScreenState.h" #include "fontTest.h" #include "skipTutorialsPopupState.h" // end additional state includes #include <iostream> using namespace std; projekt1App::projekt1App(std::string title, int sizeX, int sizeY, int argc, char **argv) : oglApp(title, sizeX, sizeY, argc, argv) { initOpenGL(); //Load our starting state into the GameStateManager GameVars->Instance(); //string temp = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"; // text parsing system example... nuke this at will, the damn thing works perfectly though woohoo! //string temp = "This is a test of my random text parsing system, lets see what happens when i do random things to it."; //vector<string*> tempb; //GameVars->parseMeIntoRows(&tempb, temp, 10, false); //GameVars->parseMeIntoRows(&tempb, temp, 12, true); //GameVars->parseMeIntoRows(&tempb, temp, 13, false); //GameVars->parseMeIntoRows(&tempb, temp, 15, true); //GameVars->parseMeIntoRows(&tempb, temp, 16, true); //GameVars->parseMeIntoRows(&tempb, temp, 17, true); //GameVars->parseMeIntoRows(&tempb, temp, 20, true); //myStateManager.addGameState<playGame>(); //myStateManager.addGameState<LogicViewState>(); //myStateManager.addGameState<skipTutorialsPopupState>(); myStateManager.addGameState<DevLogoState>(); // main game start screen //myStateManager.addGameState<helpScreenState>(); //myStateManager.addGameState<SG400KGA1>(); // sg400 kga1 heh //myStateManager.addGameState<fontTest>(); } void projekt1App::initOpenGL() { glClearColor(0,0,0,0);//Define our background color //glMatrixMode(GL_PROJECTION); // Changes the current matrix to the projection matrix //// Sets up the projection matrix for a perspective transform //gluPerspective( 45, // viewing angle // 1.0, // aspect ratio // 10.0, // near clip // 200.0); // far clip //glMatrixMode(GL_MODELVIEW); } void projekt1App::updateScene(void) { //std::cout << "project1App - Starting Update" << std::endl; myStateManager.Update(); } void projekt1App::drawScene(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); myStateManager.Draw(); // Not sure why, bottom left of the screen is 0,0 // Top right of the screen is 800,600 //glEnable2D(); // glBegin(GL_QUADS); // glColor3f(1,0,0); // glVertex3f(100,100,0); // glColor3f(0,100,0); // glVertex3f(700,100,0); // glColor3f(0,0,1); // glVertex3f(700,500,0); // glColor3f(0,0,1); // glVertex3f(100,500,0); // glEnd(); //glDisable2D(); glFlush(); glutSwapBuffers(); } void projekt1App::processMouse(int x, int y) { myStateManager.processMouse(x, y); } void projekt1App::processMouseClick(int button, int state, int x, int y) { myStateManager.processMouseClick(button, state, x, y); } void projekt1App::keyboardInput(unsigned char c, int x, int y) { myStateManager.keyboardInput(c, x, y); }
[ "corwin.j@6d558e22-e0db-11dd-bce9-bf72c0239d3a", "[email protected]@6d558e22-e0db-11dd-bce9-bf72c0239d3a", "[email protected]@6d558e22-e0db-11dd-bce9-bf72c0239d3a" ]
[ [ [ 1, 2 ], [ 4, 4 ], [ 14, 21 ], [ 23, 23 ], [ 38, 38 ], [ 40, 40 ], [ 48, 67 ], [ 69, 74 ], [ 76, 97 ] ], [ [ 3, 3 ], [ 22, 22 ], [ 31, 31 ], [ 33, 33 ], [ 98, 113 ] ], [ [ 5, 13 ], [ 24, 30 ], [ 32, 32 ], [ 34, 37 ], [ 39, 39 ], [ 41, 47 ], [ 68, 68 ], [ 75, 75 ] ] ]
4255044631e2717e540232d72ae702939e0ef9a1
95afbe3ce494b70bb76232bae55c002532902abd
/fr/recognition/recognizer/recognizer.h
1c385d90cc0c90df0341b36982296ac17fa6742b
[]
no_license
bergmansj/sparks
fd701ddc6d863cfb774d6e4a202950e71724067e
25e040edef405f49e86c12983d41c4f54f953e40
refs/heads/master
2016-09-06T09:40:43.940984
2011-07-29T16:37:39
2011-07-29T16:37:39
2,078,013
0
0
null
null
null
null
UTF-8
C++
false
false
2,160
h
#ifndef COGNITION_RECOGNIZER_H #define COGNITION_RECOGNIZER_H // Implementation based on http://code.google.com/p/visual-control/ // License is unknown, but open-source. #include <string> namespace cv { class Mat; } namespace cognition { /*! * \brief Base class for recognizers. Provides the interface * for different kinds of recognizers. * * \todo add method to add already loaded training images (cv::Mat) * \author Christophe Hesters 29-1-2011 */ class Recognizer { public: Recognizer() :isTrained(false){} /*! * \brief Adds a training image path to the training set of known images * after you have added 2 or more images, call train to learn and * set yourself up for recognition. All images must be the same size! * * \param filename the path where to find the image (all of the same size!) * \param name the name you want to attach to the image * \return bool true if the path is added succesfully */ virtual bool addTrainingImage(const std::string &filename, const std::string &name) = 0; /*! * \brief starts the learning process on all the known images that * are added trough addTrainingImage. You can add more training images * after training, but you have to call train again. While training * you cannot use recognize()! * * \return bool true if trained and ready, false otherwise */ virtual bool train() = 0; /*! * \brief does recognition on the face, and returns the most likely match. * This face must grayscale and be exactly the same size as the training * images. * * \param face the matrix containing the face * \return string name of closest match in the set of training images */ virtual std::string recognize(cv::Mat &face) = 0; /*! * \brief gets the number of training images available * * \return size_t the number of registered training images */ virtual std::size_t numTrainingImages() = 0; bool trained() { return isTrained; } protected: bool isTrained; }; } #endif //COGNITION_RECOGNIZER_H
[ [ [ 1, 74 ] ] ]
218f5b663bbe8a76eff436d9cdcaf8678003e023
d425cf21f2066a0cce2d6e804bf3efbf6dd00c00
/Tactical/XML_EnemyItemChoice.cpp
ef2331f40fceb091d4ba797af11a1af0c38fc3f7
[]
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
15,653
cpp
#ifdef PRECOMPILEDHEADERS #include "Tactical All.h" #else #include "sgp.h" #include "overhead.h" #include "weapons.h" #include "Debug Control.h" #include "expat.h" #include "XML.h" #include "Inventory Choosing.h" #endif struct { PARSE_STAGE curElement; CHAR8 szCharData[MAX_CHAR_DATA_LENGTH+1]; ARMY_GUN_CHOICE_TYPE curArmyItemChoices; ARMY_GUN_CHOICE_TYPE * curArray; UINT32 maxArraySize; UINT32 currentDepth; UINT32 maxReadDepth; } typedef armyitemchoicesParseData; static void XMLCALL armyitemchoicesStartElementHandle(void *userData, const XML_Char *name, const XML_Char **atts) { armyitemchoicesParseData * pData = (armyitemchoicesParseData *)userData; if(pData->currentDepth <= pData->maxReadDepth) //are we reading this element? { if(strcmp(name, "ENEMYITEMCHOICESLIST") == 0 && pData->curElement == ELEMENT_NONE) { pData->curElement = ELEMENT_LIST; memset(pData->curArray,0,sizeof(ARMY_GUN_CHOICE_TYPE)*pData->maxArraySize); pData->maxReadDepth++; //we are not skipping this element } else if(strcmp(name, "ENEMYITEMCHOICES") == 0 && pData->curElement == ELEMENT_LIST) { pData->curElement = ELEMENT; memset(&pData->curArmyItemChoices,0,sizeof(ARMY_GUN_CHOICE_TYPE)); pData->maxReadDepth++; //we are not skipping this element } else if(pData->curElement == ELEMENT && (strcmp(name, "uiIndex") == 0 || strcmp(name, "ubChoices") == 0 || strcmp(name, "bItemNo1") == 0 || strcmp(name, "bItemNo2") == 0 || strcmp(name, "bItemNo3") == 0 || strcmp(name, "bItemNo4") == 0 || strcmp(name, "bItemNo5") == 0 || strcmp(name, "bItemNo6") == 0 || strcmp(name, "bItemNo7") == 0 || strcmp(name, "bItemNo8") == 0 || strcmp(name, "bItemNo9") == 0 || strcmp(name, "bItemNo10") == 0 || strcmp(name, "bItemNo11") == 0 || strcmp(name, "bItemNo12") == 0 || strcmp(name, "bItemNo13") == 0 || strcmp(name, "bItemNo14") == 0 || strcmp(name, "bItemNo15") == 0 || strcmp(name, "bItemNo16") == 0 || strcmp(name, "bItemNo17") == 0 || strcmp(name, "bItemNo18") == 0 || strcmp(name, "bItemNo19") == 0 || strcmp(name, "bItemNo20") == 0 || strcmp(name, "bItemNo21") == 0 || strcmp(name, "bItemNo22") == 0 || strcmp(name, "bItemNo23") == 0 || strcmp(name, "bItemNo24") == 0 || strcmp(name, "bItemNo25") == 0 || strcmp(name, "bItemNo26") == 0 || strcmp(name, "bItemNo27") == 0 || strcmp(name, "bItemNo28") == 0 || strcmp(name, "bItemNo29") == 0 || strcmp(name, "bItemNo30") == 0 || strcmp(name, "bItemNo31") == 0 || strcmp(name, "bItemNo32") == 0 || strcmp(name, "bItemNo33") == 0 || strcmp(name, "bItemNo34") == 0 || strcmp(name, "bItemNo35") == 0 || strcmp(name, "bItemNo36") == 0 || strcmp(name, "bItemNo37") == 0 || strcmp(name, "bItemNo38") == 0 || strcmp(name, "bItemNo39") == 0 || strcmp(name, "bItemNo40") == 0 || strcmp(name, "bItemNo41") == 0 || strcmp(name, "bItemNo42") == 0 || strcmp(name, "bItemNo43") == 0 || strcmp(name, "bItemNo44") == 0 || strcmp(name, "bItemNo45") == 0 || strcmp(name, "bItemNo46") == 0 || strcmp(name, "bItemNo47") == 0 || strcmp(name, "bItemNo48") == 0 || strcmp(name, "bItemNo49") == 0 || strcmp(name, "bItemNo50") == 0 )) { pData->curElement = ELEMENT_PROPERTY; pData->maxReadDepth++; //we are not skipping this element } pData->szCharData[0] = '\0'; } pData->currentDepth++; } static void XMLCALL armyitemchoicesCharacterDataHandle(void *userData, const XML_Char *str, int len) { armyitemchoicesParseData * pData = (armyitemchoicesParseData *)userData; if( (pData->currentDepth <= pData->maxReadDepth) && (strlen(pData->szCharData) < MAX_CHAR_DATA_LENGTH) ){ strncat(pData->szCharData,str,__min((unsigned int)len,MAX_CHAR_DATA_LENGTH-strlen(pData->szCharData))); } } static void XMLCALL armyitemchoicesEndElementHandle(void *userData, const XML_Char *name) { armyitemchoicesParseData * pData = (armyitemchoicesParseData *)userData; if(pData->currentDepth <= pData->maxReadDepth) //we're at the end of an element that we've been reading { if(strcmp(name, "ENEMYITEMCHOICESLIST") == 0) { pData->curElement = ELEMENT_NONE; } else if(strcmp(name, "ENEMYITEMCHOICES") == 0) { pData->curElement = ELEMENT_LIST; if(pData->curArmyItemChoices.uiIndex < pData->maxArraySize) { pData->curArray[pData->curArmyItemChoices.uiIndex] = pData->curArmyItemChoices; //write the armyitemchoices into the table } } else if(strcmp(name, "uiIndex") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.uiIndex = (UINT32) atol(pData->szCharData); } else if(strcmp(name, "ubChoices") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.ubChoices = (UINT8) atol(pData->szCharData); } else if(strcmp(name, "bItemNo1") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[0] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo2") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[1] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo3") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[2] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo4") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[3] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo5") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[4] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo6") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[5] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo7") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[6] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo8") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[7] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo9") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[8] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo10") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[9] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo11") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[10] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo12") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[11] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo13") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[12] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo14") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[13] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo15") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[14] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo16") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[15] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo17") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[16] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo18") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[17] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo19") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[18] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo20") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[19] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo21") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[20] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo22") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[21] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo23") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[22] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo24") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[23] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo25") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[24] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo26") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[25] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo27") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[26] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo28") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[27] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo29") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[28] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo30") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[29] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo31") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[30] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo32") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[31] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo33") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[32] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo34") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[33] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo35") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[34] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo36") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[35] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo37") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[36] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo38") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[37] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo39") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[38] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo40") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[39] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo41") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[40] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo42") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[41] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo43") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[42] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo44") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[43] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo45") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[44] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo46") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[45] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo47") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[46] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo48") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[47] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo49") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[48] = (INT16) atol(pData->szCharData); } else if(strcmp(name, "bItemNo50") == 0) { pData->curElement = ELEMENT; pData->curArmyItemChoices.bItemNo[49] = (INT16) atol(pData->szCharData); } pData->maxReadDepth--; } pData->currentDepth--; } BOOLEAN ReadInArmyItemChoicesStats(STR fileName) { HWFILE hFile; UINT32 uiBytesRead; UINT32 uiFSize; CHAR8 * lpcBuffer; XML_Parser parser = XML_ParserCreate(NULL); armyitemchoicesParseData pData; DebugMsg(TOPIC_JA2, DBG_LEVEL_3, "Loading EnemyItemChoicess.xml" ); // Open armyitemchoices file hFile = FileOpen( fileName, FILE_ACCESS_READ, FALSE ); if ( !hFile ) return( FALSE ); uiFSize = FileGetSize(hFile); lpcBuffer = (CHAR8 *) MemAlloc(uiFSize+1); //Read in block if ( !FileRead( hFile, lpcBuffer, uiFSize, &uiBytesRead ) ) { MemFree(lpcBuffer); return( FALSE ); } lpcBuffer[uiFSize] = 0; //add a null terminator FileClose( hFile ); XML_SetElementHandler(parser, armyitemchoicesStartElementHandle, armyitemchoicesEndElementHandle); XML_SetCharacterDataHandler(parser, armyitemchoicesCharacterDataHandle); memset(&pData,0,sizeof(pData)); pData.curArray = gArmyItemChoices; pData.maxArraySize = MAX_ITEM_TYPES; XML_SetUserData(parser, &pData); if(!XML_Parse(parser, lpcBuffer, uiFSize, TRUE)) { CHAR8 errorBuf[511]; sprintf(errorBuf, "XML Parser Error in EnemyItemChoicess.xml: %s at line %d", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser)); LiveMessage(errorBuf); MemFree(lpcBuffer); return FALSE; } MemFree(lpcBuffer); XML_ParserFree(parser); return( TRUE ); } BOOLEAN WriteArmyItemChoicesStats() { //DebugMsg (TOPIC_JA2,DBG_LEVEL_3,"writearmyitemchoicesstats"); HWFILE hFile; //Debug code; make sure that what we got from the file is the same as what's there // Open a new file hFile = FileOpen( "TABLEDATA\\EnemyItemChoices out.xml", FILE_ACCESS_WRITE | FILE_CREATE_ALWAYS, FALSE ); if ( !hFile ) return( FALSE ); { UINT32 cnt; FilePrintf(hFile,"<ENEMYITEMCHOICESLIST>\r\n"); for(cnt = 0;cnt < ARMY_GUN_LEVELS;cnt++) { FilePrintf(hFile,"\t<ENEMYITEMCHOICES>\r\n"); FilePrintf(hFile,"\t\t<uiIndex>%d</uiIndex>\r\n", cnt ); FilePrintf(hFile,"\t\t<ubChoices>%d</ubChoices>\r\n", gArmyItemChoices[cnt].ubChoices ); for (int i=0;i<50;i++) FilePrintf(hFile,"\t\t<bItemNo%d>%d</bItemNo%d>\r\n",i+1,gArmyItemChoices[cnt].bItemNo[i],i+1 ); FilePrintf(hFile,"\t</ENEMYITEMCHOICES>\r\n"); } FilePrintf(hFile,"</ENEMYITEMCHOICESLIST>\r\n"); } FileClose( hFile ); return( TRUE ); }
[ "jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1" ]
[ [ [ 1, 514 ] ] ]
d0493756aba8130b369edc34a1d4d45899cf5c9c
c0bd82eb640d8594f2d2b76262566288676b8395
/src/scripts/PaladinSpells.cpp
408cb073b85422306b4fc29d948fecb4a4627fae
[ "FSFUL" ]
permissive
vata/solution
4c6551b9253d8f23ad5e72f4a96fc80e55e583c9
774fca057d12a906128f9231831ae2e10a947da6
refs/heads/master
2021-01-10T02:08:50.032837
2007-11-13T22:01:17
2007-11-13T22:01:17
45,352,930
0
1
null
null
null
null
UTF-8
C++
false
false
4,237
cpp
////////////////////////////////////////////////// // Copyright (C) 2006 Burlex for WoWd Project ////////////////////////////////////////////////// // Seal of Righteousness spell script #include "StdAfx.h" /* Script Export Declarations */ extern "C" WOWD_SCRIPT_DECL bool HandleDummyAura(uint32 uSpellId, uint32 i, Aura* pAura, bool apply); extern "C" WOWD_SCRIPT_DECL void ScriptInitialize(ScriptModule *mod); // Build version info function BUILD_VERSIONINFO_DATA(SCRIPTLIB_VERSION_MAJOR, SCRIPTLIB_VERSION_MINOR); /* This is needed because windows is a piece of shit. ;) */ #ifdef WIN32 BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } #endif /* Actual Aura Code */ bool HandleDummyAura(uint32 uSpellId, uint32 i, Aura* pAura, bool apply) { if(i != 0) return false; // omfg, so god damn fucking hacky.. but i guess w/ dummy spells // you cant expect everything to be in dbc :D // well, i could parse the strings :P but bah i'll just hardcode it here, // that's the point of scripts, right? ;) uint32 applyId = 0; Unit * u_caster = pAura->GetUnitCaster(); if(u_caster == 0) return false; switch(uSpellId) { case 20154: // Rank 1: "Melee attacks cause an additional $/87;20187s3 to $/25;20187s3 Holy damage." applyId = 20187; break; case 20287: // Rank 2: $/25;20280s3 applyId = 20280; break; case 20288: // Rank 3: applyId = 20281; break; case 20289: // Rank 4 applyId = 20282; break; case 20290: // Rank 5 applyId = 20283; break; case 20291: // Rank 6 applyId = 20284; break; case 20292: // Rank 7 applyId = 20285; break; case 20293: // Rank 8 applyId = 20286; break; case 27155: // Rank 9 applyId = 27157; break; } SpellEntry * m_spellInfo = sSpellStore.LookupEntry(applyId); if(apply == true) { int32 value = 0; float randomPointsPerLevel = m_spellInfo->EffectDicePerLevel[2]; int32 basePoints = m_spellInfo->EffectBasePoints[2] + 1; int32 randomPoints = m_spellInfo->EffectDieSides[2]; if(u_caster) randomPoints += u_caster->getLevel() * (int32)randomPointsPerLevel; if(randomPoints <= 1) value = basePoints; else value = basePoints + rand() %randomPoints; //this may be dangerous but let it be /*if(m_spellInfo->SpellGroupType) { SM_FIValue(u_caster->SM_FDummy,&value,m_spellInfo->SpellGroupType); SM_PIValue(u_caster->SM_PDummy,&value,m_spellInfo->SpellGroupType); }*/ // add spell damage! uint32 max_dmg = value / 21; uint32 min_dmg = value / 27; u_caster->AddOnStrikeSpellDamage(uSpellId, min_dmg, max_dmg); // set the seal business if(u_caster->GetTypeId() == TYPEID_PLAYER) { ((Player*)u_caster)->judgespell = applyId; ((Player*)u_caster)->Seal = uSpellId; } u_caster->SetFlag(UNIT_FIELD_AURASTATE, 16); } else { u_caster->RemoveOnStrikeSpellDamage(uSpellId); // set the seal business if(u_caster->GetTypeId() == TYPEID_PLAYER) { ((Player*)u_caster)->judgespell = 0; ((Player*)u_caster)->Seal = 0; } u_caster->RemoveFlag(UNIT_FIELD_AURASTATE, 16); } return true; } void ScriptInitialize(ScriptModule *mod) { sScriptMgr.ScriptAddAuraModule(20154, mod); sScriptMgr.ScriptAddAuraModule(20287, mod); sScriptMgr.ScriptAddAuraModule(20288, mod); sScriptMgr.ScriptAddAuraModule(20289, mod); sScriptMgr.ScriptAddAuraModule(20290, mod); sScriptMgr.ScriptAddAuraModule(20291, mod); sScriptMgr.ScriptAddAuraModule(20292, mod); sScriptMgr.ScriptAddAuraModule(20293, mod); sScriptMgr.ScriptAddAuraModule(27155, mod); }
[ [ [ 1, 136 ] ] ]
1f3587b9a4ac261cfaf51d16c5d703f08f2a0b89
cf58ec40b7ea828aba01331ee3ab4c7f2195b6ca
/Nestopia/core/board/NstBoardUnlWorldHero.cpp
476754fe6f8bc336d7e12f3d9a45115e7cd7bbbf
[]
no_license
nicoya/OpenEmu
e2fd86254d45d7aa3d7ef6a757192e2f7df0da1e
dd5091414baaaddbb10b9d50000b43ee336ab52b
refs/heads/master
2021-01-16T19:51:53.556272
2011-08-06T18:52:40
2011-08-06T18:52:40
2,131,312
1
0
null
null
null
null
UTF-8
C++
false
false
4,634
cpp
//////////////////////////////////////////////////////////////////////////////////////// // // Nestopia - NES/Famicom emulator written in C++ // // Copyright (C) 2003-2008 Martin Freij // // This file is part of Nestopia. // // Nestopia 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. // // Nestopia 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 Nestopia; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //////////////////////////////////////////////////////////////////////////////////////// #include "../NstClock.hpp" #include "NstBoard.hpp" #include "NstBoardKonamiVrc4.hpp" #include "NstBoardUnlWorldHero.hpp" namespace Nes { namespace Core { namespace Boards { namespace Unlicensed { #ifdef NST_MSVC_OPTIMIZE #pragma optimize("s", on) #endif WorldHero::WorldHero(const Context& c) : Board(c), irq(*c.cpu) {} void WorldHero::SubReset(const bool hard) { if (hard) prgSwap = 0; irq.Reset( hard, hard ? false : irq.Connected() ); for (dword i=0x8000; i <= 0xFFFF; ++i) { switch (i & 0xF0C3) { case 0x8000: Map( i, &WorldHero::Poke_8000 ); break; case 0x9000: Map( i, NMT_SWAP_VH01 ); break; case 0x9002: case 0x9080: Map( i, &WorldHero::Poke_9000 ); break; case 0xA000: Map( i, PRG_SWAP_8K_1 ); break; case 0xB000: case 0xB001: case 0xB002: case 0xB003: case 0xC000: case 0xC001: case 0xC002: case 0xC003: case 0xD000: case 0xD001: case 0xD002: case 0xD003: case 0xE000: case 0xE001: case 0xE002: case 0xE003: Map( i, &WorldHero::Poke_B000 ); break; case 0xF000: Map( i, &WorldHero::Poke_F000 ); break; case 0xF001: Map( i, &WorldHero::Poke_F001 ); break; case 0xF002: Map( i, &WorldHero::Poke_F002 ); break; case 0xF003: Map( i, &WorldHero::Poke_F003 ); break; } } } void WorldHero::SubLoad(State::Loader& state,const dword baseChunk) { NST_VERIFY( baseChunk == (AsciiId<'U','W','H'>::V) ); if (baseChunk == AsciiId<'U','W','H'>::V) { while (const dword chunk = state.Begin()) { switch (chunk) { case AsciiId<'R','E','G'>::V: prgSwap = state.Read8() & 0x2; break; case AsciiId<'I','R','Q'>::V: irq.LoadState( state ); break; } state.End(); } } } void WorldHero::SubSave(State::Saver& state) const { state.Begin( AsciiId<'U','W','H'>::V ); state.Begin( AsciiId<'R','E','G'>::V ).Write8( prgSwap ).End(); irq.SaveState( state, AsciiId<'I','R','Q'>::V ); state.End(); } #ifdef NST_MSVC_OPTIMIZE #pragma optimize("", on) #endif NES_POKE_D(WorldHero,8000) { prg.SwapBank<SIZE_8K>( prgSwap << 13, data ); } NES_POKE_D(WorldHero,9000) { data &= 0x2; if (prgSwap != data) { prgSwap = data; prg.SwapBanks<SIZE_8K,0x0000> ( prg.GetBank<SIZE_8K,0x4000>(), prg.GetBank<SIZE_8K,0x0000>() ); } } NES_POKE_AD(WorldHero,B000) { ppu.Update(); const bool part = address & 0x1; address = ((address - 0xB000) >> 1 & 0x1800) | (address << 9 & 0x0400); chr.SwapBank<SIZE_1K>( address, (chr.GetBank<SIZE_1K>(address) & (part ? 0x00F : 0xFF0)) | (part ? data << 4 : data & 0xF) ); } NES_POKE_D(WorldHero,F000) { irq.WriteLatch0( data ); } NES_POKE_D(WorldHero,F001) { irq.WriteLatch1( data ); } NES_POKE_D(WorldHero,F002) { irq.Toggle( data ); } NES_POKE(WorldHero,F003) { irq.Toggle(); } void WorldHero::Sync(Event event,Input::Controllers* controllers) { if (event == EVENT_END_FRAME) irq.VSync(); Board::Sync( event, controllers ); } } } } }
[ [ [ 1, 182 ] ] ]
63236923b3334fb0100bc305e51d412648c91c43
34d807d2bc616a23486af858647301af98b6296e
/ccbot/bncsutilinterface.cpp
57e665f15ca15dbd7e9bafa87c09ec4e7f1d18f2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
Mofsy/ccbot
65cf5bb08c211cdce2001a36db8968844fce2e05
f171351c99cce4059a82a23399e7c4587f37beb5
refs/heads/master
2020-12-28T21:39:19.297873
2011-03-01T00:44:46
2011-03-01T00:44:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,431
cpp
/* Copyright [2009] [Joško Nikolić] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. HEAVILY MODIFIED PROJECT BASED ON GHOST++: http://forum.codelain.com GHOST++ CODE IS PORTED FROM THE ORIGINAL GHOST PROJECT: http://ghost.pwner.org/ */ #include "ccbot.h" #include "util.h" #include "bncsutilinterface.h" #include <bncsutil/bncsutil.h> // // CBNCSUtilInterface // CBNCSUtilInterface :: CBNCSUtilInterface( string userName, string userPassword ) { // m_nls = (void *)nls_init( userName.c_str( ), userPassword.c_str( ) ); m_NLS = new NLS( userName, userPassword ); } CBNCSUtilInterface :: ~CBNCSUtilInterface( ) { // nls_free( (nls_t *)m_nls ); delete (NLS *)m_NLS; } void CBNCSUtilInterface :: Reset( string userName, string userPassword ) { // nls_free( (nls_t *)m_nls ); // m_nls = (void *)nls_init( userName.c_str( ), userPassword.c_str( ) ); delete (NLS *)m_NLS; m_NLS = new NLS( userName, userPassword ); } bool CBNCSUtilInterface :: HELP_SID_AUTH_CHECK( string war3Path, string keyROC, string keyTFT, string valueStringFormula, string mpqFileName, BYTEARRAY clientToken, BYTEARRAY serverToken ) { // set m_EXEVersion, m_EXEVersionHash, m_EXEInfo, m_InfoROC, m_InfoTFT string FileWar3EXE = war3Path + "war3.exe"; string FileStormDLL = war3Path + "Storm.dll"; if( !UTIL_FileExists( FileStormDLL ) ) FileStormDLL = war3Path + "storm.dll"; string FileGameDLL = war3Path + "game.dll"; bool ExistsWar3EXE = UTIL_FileExists( FileWar3EXE ); bool ExistsStormDLL = UTIL_FileExists( FileStormDLL ); bool ExistsGameDLL = UTIL_FileExists( FileGameDLL ); if( ExistsWar3EXE && ExistsStormDLL && ExistsGameDLL ) { // todotodo: check getExeInfo return value to ensure 1024 bytes was enough char buf[1024]; uint32_t EXEVersion; getExeInfo( FileWar3EXE.c_str( ), (char *)&buf, 1024, (uint32_t *)&EXEVersion, BNCSUTIL_PLATFORM_X86 ); m_EXEInfo = buf; m_EXEVersion = UTIL_CreateByteArray( EXEVersion, false ); uint32_t EXEVersionHash; checkRevisionFlat( valueStringFormula.c_str( ), FileWar3EXE.c_str( ), FileStormDLL.c_str( ), FileGameDLL.c_str( ), extractMPQNumber( mpqFileName.c_str( ) ), (unsigned long *)&EXEVersionHash ); m_EXEVersionHash = UTIL_CreateByteArray( EXEVersionHash, false ); m_KeyInfoROC = CreateKeyInfo( keyROC, UTIL_ByteArrayToUInt32( clientToken, false ), UTIL_ByteArrayToUInt32( serverToken, false ) ); if( !keyTFT.empty( ) ) m_KeyInfoTFT = CreateKeyInfo( keyTFT, UTIL_ByteArrayToUInt32( clientToken, false ), UTIL_ByteArrayToUInt32( serverToken, false ) ); if( m_KeyInfoROC.size( ) == 36 && ( keyTFT.empty( ) || m_KeyInfoTFT.size( ) == 36 ) ) return true; else { if( m_KeyInfoROC.size( ) != 36 ) CONSOLE_Print( "[BNCSUI] unable to create ROC key info - invalid ROC key" ); if( !keyTFT.empty( ) && m_KeyInfoTFT.size( ) != 36 ) CONSOLE_Print( "[BNCSUI] unable to create TFT key info - invalid TFT key" ); } } return false; } bool CBNCSUtilInterface :: HELP_SID_AUTH_ACCOUNTLOGON( ) { // set m_ClientKey char buf[32]; // nls_get_A( (nls_t *)m_nls, buf ); ( (NLS *)m_NLS )->getPublicKey( buf ); m_ClientKey = UTIL_CreateByteArray( (unsigned char *)buf, 32 ); return true; } bool CBNCSUtilInterface :: HELP_SID_AUTH_ACCOUNTLOGONPROOF( BYTEARRAY salt, BYTEARRAY serverKey ) { // set m_M1 char buf[20]; // nls_get_M1( (nls_t *)m_nls, buf, string( serverKey.begin( ), serverKey.end( ) ).c_str( ), string( salt.begin( ), salt.end( ) ).c_str( ) ); ( (NLS *)m_NLS )->getClientSessionKey( buf, string( salt.begin( ), salt.end( ) ).c_str( ), string( serverKey.begin( ), serverKey.end( ) ).c_str( ) ); m_M1 = UTIL_CreateByteArray( (unsigned char *)buf, 20 ); return true; } bool CBNCSUtilInterface :: HELP_PvPGNPasswordHash( string userPassword ) { // set m_PvPGNPasswordHash char buf[20]; hashPassword( userPassword.c_str( ), buf ); m_PvPGNPasswordHash = UTIL_CreateByteArray( (unsigned char *)buf, 20 ); return true; } BYTEARRAY CBNCSUtilInterface :: CreateKeyInfo( string key, uint32_t clientToken, uint32_t serverToken ) { unsigned char Zeros[] = { 0, 0, 0, 0 }; BYTEARRAY KeyInfo; CDKeyDecoder Decoder( key.c_str( ), key.size( ) ); if( Decoder.isKeyValid( ) ) { UTIL_AppendByteArray( KeyInfo, UTIL_CreateByteArray( (uint32_t)key.size( ), false ) ); UTIL_AppendByteArray( KeyInfo, UTIL_CreateByteArray( Decoder.getProduct( ), false ) ); UTIL_AppendByteArray( KeyInfo, UTIL_CreateByteArray( Decoder.getVal1( ), false ) ); UTIL_AppendByteArray( KeyInfo, UTIL_CreateByteArray( Zeros, 4 ) ); size_t Length = Decoder.calculateHash( clientToken, serverToken ); char *buf = new char[Length]; Length = Decoder.getHash( buf ); UTIL_AppendByteArray( KeyInfo, UTIL_CreateByteArray( (unsigned char *)buf, Length ) ); delete [] buf; } return KeyInfo; }
[ [ [ 1, 152 ] ] ]
d106b144083fa07f2f0d15fbac9cb2e9a1b87d96
143ada25a90b28c2ee28d2105d4584c0f2a7480d
/include/detail/job.hpp
e182ed67b5f1a32cc3e0482e214551ac93c6e654
[]
no_license
brightman/mapreduce
a311285c13db5c4f93d4a6ec2adfb1a3ac14d271
9b93a7300f0c7ffc8896f92f83cdd4d3321aa4e7
refs/heads/master
2021-01-20T22:59:51.992563
2011-04-30T13:14:26
2011-04-30T13:14:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,446
hpp
// MapReduce library // // Copyright (C) 2009 Craig Henderson. // [email protected] // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // For more information, see http://craighenderson.co.uk/mapreduce/ // #ifndef MAPREDUCE_JOB_HPP #define MAPREDUCE_JOB_HPP namespace mapreduce { template<typename T> size_t length(T const &str); template<typename MapKey, typename MapValue> class map_task { public: typedef MapKey key_type; typedef MapValue value_type; }; template<typename ReduceKey, typename ReduceValue> class reduce_task { public: typedef ReduceKey key_type; typedef ReduceValue value_type; }; template<typename MapTask, typename ReduceTask, typename Combiner=null_combiner, typename Datasource=datasource::directory_iterator<MapTask>, typename IntermediateStore=intermediates::in_memory<MapTask, ReduceTask>, typename StoreResult=typename IntermediateStore::store_result_type> class job : private boost::noncopyable { public: typedef MapTask map_task_type; typedef ReduceTask reduce_task_type; typedef Datasource datasource_type; typedef IntermediateStore intermediate_store_type; typedef Combiner combiner_type; typedef typename intermediate_store_type::const_result_iterator const_result_iterator; typedef typename intermediate_store_type::keyvalue_t keyvalue_t; public: class map_task_runner : boost::noncopyable { public: map_task_runner(job &j) : job_(j), intermediate_store_(job_.number_of_partitions()) { } // 'value' parameter is not a reference to const to enable streams to be passed map_task_runner &operator()(typename map_task_type::key_type const &key, typename map_task_type::value_type &value) { map_task_type()(*this, key, value); // consolidating map intermediate results can save network time by // aggregating the mapped valued at mapper combiner_type::run(intermediate_store_); return *this; } bool const emit_intermediate(typename reduce_task_type::key_type const &key, typename reduce_task_type::value_type const &value) { return intermediate_store_.insert(key, value); } intermediate_store_type &intermediate_store(void) { return intermediate_store_; } private: job &job_; intermediate_store_type intermediate_store_; }; class reduce_task_runner : boost::noncopyable { public: reduce_task_runner( std::string const &output_filespec, unsigned const &partition, unsigned const num_partitions, intermediate_store_type &intermediate_store, results &result) : partition_(partition), result_(result), intermediate_store_(intermediate_store), store_result_(output_filespec, partition, num_partitions) { } void reduce(void) { intermediate_store_.reduce(partition_, *this); } void emit(typename reduce_task_type::key_type const &key, typename reduce_task_type::value_type const &value) { intermediate_store_.insert(key, value, store_result_); } template<typename It> void operator()(typename reduce_task_type::key_type const &key, It it, It ite) { ++result_.counters.reduce_keys_executed; reduce_task_type()(*this, key, it, ite); ++result_.counters.reduce_keys_completed; } private: unsigned const &partition_; results &result_; intermediate_store_type &intermediate_store_; StoreResult store_result_; }; job(datasource_type &datasource, specification const &spec) : datasource_(datasource), specification_(spec), intermediate_store_(specification_.reduce_tasks) { } const_result_iterator begin_results(void) const { return intermediate_store_.begin_results(); } const_result_iterator end_results(void) const { return intermediate_store_.end_results(); } bool const get_next_map_key(void *&key) { std::auto_ptr<typename map_task_type::key_type> next_key(new typename map_task_type::key_type); if (!datasource_.setup_key(*next_key)) return false; key = next_key.release(); return true; } template<typename SchedulePolicy> void run(results &result) { SchedulePolicy schedule; this->run(schedule, result); } template<typename SchedulePolicy> void run(SchedulePolicy &schedule, results &result) { using namespace boost::posix_time; ptime start_time(microsec_clock::universal_time()); schedule(*this, result); result.job_runtime = microsec_clock::universal_time() - start_time; } template<typename Sync> bool const run_map_task(void *key, results &result, Sync &sync) { using namespace boost::posix_time; ptime start_time(microsec_clock::universal_time()); bool success = true; try { ++result.counters.map_keys_executed; std::auto_ptr<typename map_task_type::key_type> map_key_ptr( reinterpret_cast< typename map_task_type::key_type *>(key)); typename map_task_type::key_type &map_key = *map_key_ptr; // get the data typename map_task_type::value_type value; if (!datasource_.get_data(map_key, value)) { ++result.counters.map_key_errors; return false; } map_task_runner runner(*this); runner(map_key, value); // merge the map task intermediate results into the job sync.lock(); intermediate_store_.merge_from(runner.intermediate_store()); sync.unlock(); ++result.counters.map_keys_completed; } catch (std::exception &) { ++result.counters.map_key_errors; success = false; } result.map_times.push_back(microsec_clock::universal_time() - start_time); return success; } unsigned const number_of_partitions(void) const { return specification_.reduce_tasks; } unsigned const number_of_map_tasks(void) const { return specification_.map_tasks; } bool const run_reduce_task(unsigned const partition, results &result) { bool success = true; using namespace boost::posix_time; ptime start_time(microsec_clock::universal_time()); try { reduce_task_runner runner( specification_.output_filespec, partition, number_of_partitions(), intermediate_store_, result); runner.reduce(); } catch (std::exception &e) { std::cerr << "\nError: " << e.what() << "\n"; ++result.counters.reduce_key_errors; success = false; } result.reduce_times.push_back(microsec_clock::universal_time()-start_time); return success; } private: datasource_type &datasource_; specification const &specification_; intermediate_store_type intermediate_store_; }; template<> inline size_t length(std::string const &str) { return str.length(); } } // namespace mapreduce #endif // MAPREDUCE_JOB_HPP
[ [ [ 1, 280 ] ] ]
fa59bf9088783748f4669cf329cea49eaaade1bb
c7dcd4b321428c91074d6802b8a655a40fbb283b
/ObjectDetection/ObjectDetection/loadConfigs.cpp
b162c785bc7571a23eb5c7fccdc2621f3dcbc7b6
[]
no_license
buubui/imgdetection
7c12576ef6ddc06d788183f4261bc070e13ee2fb
feeb9b5233c2a0bd35b60bf7792bd05005cc0409
refs/heads/master
2016-09-05T11:45:33.588669
2011-04-27T16:08:34
2011-04-27T16:08:34
32,272,304
0
0
null
null
null
null
UTF-8
C++
false
false
2,234
cpp
#include "stdafx.h" extern Size cellSize,blockSize,wndSize,maxWndSz; extern cv::Vec2i blockOverlap; extern cv::Vec2f regionOverlap; extern float delPart; extern int useTech; extern string weightFile; void loadConfig() { srand(time(NULL)); ifstream conffile; conffile.open ("input/config.txt"); string tmp; if (conffile.is_open()) { // while (! inputfile.eof() ) // { getline (conffile,tmp);//cell getline (conffile,tmp); cellSize.width = atoi(tmp.c_str()); getline (conffile,tmp); cellSize.height = atoi(tmp.c_str()); getline (conffile,tmp);//block getline (conffile,tmp); blockSize.width = atoi(tmp.c_str()); getline (conffile,tmp); blockSize.height = atoi(tmp.c_str()); getline (conffile,tmp);//window size getline (conffile,tmp); wndSize.width = atoi(tmp.c_str()); getline (conffile,tmp); wndSize.height = atoi(tmp.c_str()); getline (conffile,tmp);//Max Window Size getline (conffile,tmp); maxWndSz.width = atoi(tmp.c_str()); getline (conffile,tmp); maxWndSz.height = atoi(tmp.c_str()); getline (conffile,tmp);//Block overlap getline (conffile,tmp); blockOverlap[0] = atoi(tmp.c_str()); getline (conffile,tmp); blockOverlap[1] = atoi(tmp.c_str()); getline (conffile,tmp);//Del part getline (conffile,tmp); delPart = atof(tmp.c_str()); getline (conffile,tmp);//Region overlap getline (conffile,tmp); regionOverlap[0] = atof(tmp.c_str()); getline (conffile,tmp); regionOverlap[1] = atof(tmp.c_str()); getline (conffile,tmp); // use tech getline (conffile,tmp); useTech = atoi(tmp.c_str()); getline (conffile,tmp);//weight file getline (conffile,tmp); weightFile = tmp; printf("tech:%d weight:%s",useTech,weightFile.c_str()); // } } conffile.close(); } void getWeight(string filename,Mat* &weight, float& b){ ifstream fi; fi.open (filename.c_str()); string tmp; int n; if (fi.is_open()) { getline (fi,tmp); n = atoi(tmp.c_str()); weight = new Mat(n,1,DataType<float>::type); for (int i=0;i<n;i++) { getline (fi,tmp); weight->at<float>(i,0)=atof(tmp.c_str()); } getline (fi,tmp); b=atof(tmp.c_str()); } }
[ "bhlbuu@b6243d83-3e35-bad2-eac4-1d342526e9e5", "[email protected]@b6243d83-3e35-bad2-eac4-1d342526e9e5" ]
[ [ [ 1, 5 ], [ 8, 54 ], [ 62, 91 ] ], [ [ 6, 7 ], [ 55, 61 ] ] ]
8e468f2f3d77f3abb25007852ed2457ddd0dd17e
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/include/aosl/event_selection_forward.hpp
57f6575adf0a4af2a00496ab62d07e21e7545441
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
14,654
hpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // #ifndef AOSLCPP_AOSL__EVENT_SELECTION_FORWARD_HPP #define AOSLCPP_AOSL__EVENT_SELECTION_FORWARD_HPP // Begin prologue. // // // End prologue. #include <xsd/cxx/version.hxx> #if (XSD_INT_VERSION != 3030000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> #include <xsd/cxx/xml/dom/serialization-header.hxx> #include <xsd/cxx/tree/serialization.hxx> #include <xsd/cxx/tree/serialization/byte.hxx> #include <xsd/cxx/tree/serialization/unsigned-byte.hxx> #include <xsd/cxx/tree/serialization/short.hxx> #include <xsd/cxx/tree/serialization/unsigned-short.hxx> #include <xsd/cxx/tree/serialization/int.hxx> #include <xsd/cxx/tree/serialization/unsigned-int.hxx> #include <xsd/cxx/tree/serialization/long.hxx> #include <xsd/cxx/tree/serialization/unsigned-long.hxx> #include <xsd/cxx/tree/serialization/boolean.hxx> #include <xsd/cxx/tree/serialization/float.hxx> #include <xsd/cxx/tree/serialization/double.hxx> #include <xsd/cxx/tree/serialization/decimal.hxx> #include <xsd/cxx/tree/std-ostream-operators.hxx> /** * @brief C++ namespace for the %http://www.w3.org/2001/XMLSchema * schema namespace. */ namespace xml_schema { // anyType and anySimpleType. // /** * @brief C++ type corresponding to the anyType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::type Type; /** * @brief C++ type corresponding to the anySimpleType XML Schema * built-in type. */ typedef ::xsd::cxx::tree::simple_type< Type > SimpleType; /** * @brief Alias for the anyType type. */ typedef ::xsd::cxx::tree::type Container; // 8-bit // /** * @brief C++ type corresponding to the byte XML Schema * built-in type. */ typedef signed char Byte; /** * @brief C++ type corresponding to the unsignedByte XML Schema * built-in type. */ typedef unsigned char UnsignedByte; // 16-bit // /** * @brief C++ type corresponding to the short XML Schema * built-in type. */ typedef short Short; /** * @brief C++ type corresponding to the unsignedShort XML Schema * built-in type. */ typedef unsigned short UnsignedShort; // 32-bit // /** * @brief C++ type corresponding to the int XML Schema * built-in type. */ typedef int Int; /** * @brief C++ type corresponding to the unsignedInt XML Schema * built-in type. */ typedef unsigned int UnsignedInt; // 64-bit // /** * @brief C++ type corresponding to the long XML Schema * built-in type. */ typedef long long Long; /** * @brief C++ type corresponding to the unsignedLong XML Schema * built-in type. */ typedef unsigned long long UnsignedLong; // Supposed to be arbitrary-length integral types. // /** * @brief C++ type corresponding to the integer XML Schema * built-in type. */ typedef long long Integer; /** * @brief C++ type corresponding to the nonPositiveInteger XML Schema * built-in type. */ typedef long long NonPositiveInteger; /** * @brief C++ type corresponding to the nonNegativeInteger XML Schema * built-in type. */ typedef unsigned long long NonNegativeInteger; /** * @brief C++ type corresponding to the positiveInteger XML Schema * built-in type. */ typedef unsigned long long PositiveInteger; /** * @brief C++ type corresponding to the negativeInteger XML Schema * built-in type. */ typedef long long NegativeInteger; // Boolean. // /** * @brief C++ type corresponding to the boolean XML Schema * built-in type. */ typedef bool Boolean; // Floating-point types. // /** * @brief C++ type corresponding to the float XML Schema * built-in type. */ typedef float Float; /** * @brief C++ type corresponding to the double XML Schema * built-in type. */ typedef double Double; /** * @brief C++ type corresponding to the decimal XML Schema * built-in type. */ typedef double Decimal; // String types. // /** * @brief C++ type corresponding to the string XML Schema * built-in type. */ typedef ::xsd::cxx::tree::string< char, SimpleType > String; /** * @brief C++ type corresponding to the normalizedString XML Schema * built-in type. */ typedef ::xsd::cxx::tree::normalized_string< char, String > NormalizedString; /** * @brief C++ type corresponding to the token XML Schema * built-in type. */ typedef ::xsd::cxx::tree::token< char, NormalizedString > Token; /** * @brief C++ type corresponding to the Name XML Schema * built-in type. */ typedef ::xsd::cxx::tree::name< char, Token > Name; /** * @brief C++ type corresponding to the NMTOKEN XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtoken< char, Token > Nmtoken; /** * @brief C++ type corresponding to the NMTOKENS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::nmtokens< char, SimpleType, Nmtoken > Nmtokens; /** * @brief C++ type corresponding to the NCName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::ncname< char, Name > Ncname; /** * @brief C++ type corresponding to the language XML Schema * built-in type. */ typedef ::xsd::cxx::tree::language< char, Token > Language; // ID/IDREF. // /** * @brief C++ type corresponding to the ID XML Schema * built-in type. */ typedef ::xsd::cxx::tree::id< char, Ncname > Id; /** * @brief C++ type corresponding to the IDREF XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idref< char, Ncname, Type > Idref; /** * @brief C++ type corresponding to the IDREFS XML Schema * built-in type. */ typedef ::xsd::cxx::tree::idrefs< char, SimpleType, Idref > Idrefs; // URI. // /** * @brief C++ type corresponding to the anyURI XML Schema * built-in type. */ typedef ::xsd::cxx::tree::uri< char, SimpleType > Uri; // Qualified name. // /** * @brief C++ type corresponding to the QName XML Schema * built-in type. */ typedef ::xsd::cxx::tree::qname< char, SimpleType, Uri, Ncname > Qname; // Binary. // /** * @brief Binary buffer type. */ typedef ::xsd::cxx::tree::buffer< char > Buffer; /** * @brief C++ type corresponding to the base64Binary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::base64_binary< char, SimpleType > Base64Binary; /** * @brief C++ type corresponding to the hexBinary XML Schema * built-in type. */ typedef ::xsd::cxx::tree::hex_binary< char, SimpleType > HexBinary; // Date/time. // /** * @brief Time zone type. */ typedef ::xsd::cxx::tree::time_zone TimeZone; /** * @brief C++ type corresponding to the date XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date< char, SimpleType > Date; /** * @brief C++ type corresponding to the dateTime XML Schema * built-in type. */ typedef ::xsd::cxx::tree::date_time< char, SimpleType > DateTime; /** * @brief C++ type corresponding to the duration XML Schema * built-in type. */ typedef ::xsd::cxx::tree::duration< char, SimpleType > Duration; /** * @brief C++ type corresponding to the gDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gday< char, SimpleType > Gday; /** * @brief C++ type corresponding to the gMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth< char, SimpleType > Gmonth; /** * @brief C++ type corresponding to the gMonthDay XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gmonth_day< char, SimpleType > GmonthDay; /** * @brief C++ type corresponding to the gYear XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear< char, SimpleType > Gyear; /** * @brief C++ type corresponding to the gYearMonth XML Schema * built-in type. */ typedef ::xsd::cxx::tree::gyear_month< char, SimpleType > GyearMonth; /** * @brief C++ type corresponding to the time XML Schema * built-in type. */ typedef ::xsd::cxx::tree::time< char, SimpleType > Time; // Entity. // /** * @brief C++ type corresponding to the ENTITY XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entity< char, Ncname > Entity; /** * @brief C++ type corresponding to the ENTITIES XML Schema * built-in type. */ typedef ::xsd::cxx::tree::entities< char, SimpleType, Entity > Entities; // Namespace information and list stream. Used in // serialization functions. // /** * @brief Namespace serialization information. */ typedef ::xsd::cxx::xml::dom::namespace_info< char > NamespaceInfo; /** * @brief Namespace serialization information map. */ typedef ::xsd::cxx::xml::dom::namespace_infomap< char > NamespaceInfomap; /** * @brief List serialization stream. */ typedef ::xsd::cxx::tree::list_stream< char > ListStream; /** * @brief Serialization wrapper for the %double type. */ typedef ::xsd::cxx::tree::as_double< Double > AsDouble; /** * @brief Serialization wrapper for the %decimal type. */ typedef ::xsd::cxx::tree::as_decimal< Decimal > AsDecimal; /** * @brief Simple type facet. */ typedef ::xsd::cxx::tree::facet Facet; // Flags and properties. // /** * @brief Parsing and serialization flags. */ typedef ::xsd::cxx::tree::flags Flags; /** * @brief Parsing properties. */ typedef ::xsd::cxx::tree::properties< char > Properties; // Parsing/serialization diagnostics. // /** * @brief Error severity. */ typedef ::xsd::cxx::tree::severity Severity; /** * @brief Error condition. */ typedef ::xsd::cxx::tree::error< char > Error; /** * @brief List of %error conditions. */ typedef ::xsd::cxx::tree::diagnostics< char > Diagnostics; // Exceptions. // /** * @brief Root of the C++/Tree %exception hierarchy. */ typedef ::xsd::cxx::tree::exception< char > Exception; /** * @brief Exception indicating that the size argument exceeds * the capacity argument. */ typedef ::xsd::cxx::tree::bounds< char > Bounds; /** * @brief Exception indicating that a duplicate ID value * was encountered in the object model. */ typedef ::xsd::cxx::tree::duplicate_id< char > DuplicateId; /** * @brief Exception indicating a parsing failure. */ typedef ::xsd::cxx::tree::parsing< char > Parsing; /** * @brief Exception indicating that an expected element * was not encountered. */ typedef ::xsd::cxx::tree::expected_element< char > ExpectedElement; /** * @brief Exception indicating that an unexpected element * was encountered. */ typedef ::xsd::cxx::tree::unexpected_element< char > UnexpectedElement; /** * @brief Exception indicating that an expected attribute * was not encountered. */ typedef ::xsd::cxx::tree::expected_attribute< char > ExpectedAttribute; /** * @brief Exception indicating that an unexpected enumerator * was encountered. */ typedef ::xsd::cxx::tree::unexpected_enumerator< char > UnexpectedEnumerator; /** * @brief Exception indicating that the text content was * expected for an element. */ typedef ::xsd::cxx::tree::expected_text_content< char > ExpectedTextContent; /** * @brief Exception indicating that a prefix-namespace * mapping was not provided. */ typedef ::xsd::cxx::tree::no_prefix_mapping< char > NoPrefixMapping; /** * @brief Exception indicating that the type information * is not available for a type. */ typedef ::xsd::cxx::tree::no_type_info< char > NoTypeInfo; /** * @brief Exception indicating that the types are not * related by inheritance. */ typedef ::xsd::cxx::tree::not_derived< char > NotDerived; /** * @brief Exception indicating a serialization failure. */ typedef ::xsd::cxx::tree::serialization< char > Serialization; /** * @brief Error handler callback interface. */ typedef ::xsd::cxx::xml::error_handler< char > ErrorHandler; /** * @brief DOM interaction. */ namespace dom { /** * @brief Automatic pointer for DOMDocument. */ using ::xsd::cxx::xml::dom::auto_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA /** * @brief DOM user data key for back pointers to tree nodes. */ const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } #include "aosl/event_selection_base_forward.hpp" #include "aosl/object_ref_forward.hpp" // Forward declarations. // namespace aosl { class Event_selection; } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // AOSLCPP_AOSL__EVENT_SELECTION_FORWARD_HPP
[ "klaim@localhost" ]
[ [ [ 1, 612 ] ] ]
6ce815f21a19f3dd85b9398fb71abe0e8aa3676c
6581dacb25182f7f5d7afb39975dc622914defc7
/MouseHook/MouseHook/MouseHook.cpp
b57c08fd572b9a93ff3723ec873add324d48adc1
[]
no_license
dice2019/alexlabonline
caeccad28bf803afb9f30b9e3cc663bb2909cc4f
4c433839965ed0cff99dad82f0ba1757366be671
refs/heads/master
2021-01-16T19:37:24.002905
2011-09-21T15:20:16
2011-09-21T15:20:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,135
cpp
// MouseHook.cpp : Defines the entry point for the DLL application. // #include "stdafx.h" #define _COMPILING_44E531B1_14D3_11d5_A025_006067718D04 #include "MouseHook.h" #include <fstream> #pragma data_seg(".JOE") HWND hWndServer = NULL; #pragma data_seg() #pragma comment(linker, "/section:.JOE,rws") #pragma data_seg(".SHARDAT") HHOOK hKeyboard=NULL; #pragma data_seg() HINSTANCE hInst; UINT UWM_MOUSEMOVE; HHOOK hMouseHook; static LRESULT CALLBACK MsgProc(UINT nCode, WPARAM wParam, LPARAM lParam); static LRESULT CALLBACK KeyboardProc( int nCode, WPARAM wParam, LPARAM lParam); BOOL APIENTRY DllMain( HINSTANCE hInstance, DWORD Reason, LPVOID Reserved ) { switch(Reason) { /* reason */ case DLL_PROCESS_ATTACH: hInst = hInstance; UWM_MOUSEMOVE = RegisterWindowMessage(UWM_MOUSEMOVE_MSG); return TRUE; case DLL_PROCESS_DETACH: if(hWndServer != NULL) clearMyHook(hWndServer); return TRUE; } /* reason */ return TRUE; } /**************************************************************************** * setMyHook * Inputs: * HWND hWnd: Window to notify * Result: BOOL * TRUE if successful * FALSE if error * Effect: * Sets the hook ****************************************************************************/ __declspec(dllexport) BOOL setMyHook(HWND hWnd) { if(hWndServer != NULL) return FALSE; // already hooked! hMouseHook = SetWindowsHookEx(WH_GETMESSAGE, (HOOKPROC)MsgProc, hInst, 0); hKeyboard = SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardProc, hInst, 0); if(hMouseHook != NULL) { /* success */ hWndServer = hWnd; return TRUE; } /* success */ return FALSE; // failed to set hook } // setMyHook /**************************************************************************** * clearMyHook * Inputs: * HWND hWnd: Window hook * Result: BOOL * TRUE if successful * FALSE if error * Effect: * Removes the hook that has been set ****************************************************************************/ __declspec(dllexport) BOOL clearMyHook(HWND hWnd) { if(hWnd != hWndServer || hWnd == NULL) return FALSE; BOOL unhooked = UnhookWindowsHookEx(hMouseHook) && UnhookWindowsHookEx(hKeyboard); if(unhooked) hWndServer = NULL; return unhooked; } // clearMyHook /**************************************************************************** * msghook * Inputs: * int nCode: Code value * WPARAM wParam: * LPARAM lParam: * Result: LRESULT * Either 0 or the result of CallNextHookEx * Effect: * Hook processing function. If the message is a mouse-move message, * posts the coordinates to the parent window ****************************************************************************/ static LRESULT CALLBACK MsgProc(UINT nCode, WPARAM wParam, LPARAM lParam) { if(nCode < 0) { /* pass it on */ CallNextHookEx(hMouseHook, nCode, wParam, lParam); return 0; } /* pass it on */ LPMSG msg = (LPMSG)lParam; if(msg->message == WM_MOUSEMOVE || msg->message == WM_NCMOUSEMOVE) { PostMessage(hWndServer, UWM_MOUSEMOVE, 0, 0); } return CallNextHookEx(hMouseHook, nCode, wParam, lParam); } // msghook static LRESULT CALLBACK KeyboardProc( int nCode, WPARAM wParam, LPARAM lParam) { char ch; if (((DWORD)lParam & 0x40000000) &&(HC_ACTION==nCode)) { if ((wParam==VK_SPACE)||(wParam==VK_RETURN)||(wParam>=0x2f ) &&(wParam<=0x100)) { if (wParam==VK_RETURN) { ch='\n'; } else { BYTE ks[256]; GetKeyboardState(ks); WORD w; UINT scan; scan=0; ToAscii(wParam,scan,ks,&w,0); ch =char(w); } // std::ofstream fout("C:\\Key.txt",std::ios::app); // fout<<ch<<','<<std::endl; // fout.close(); } } return CallNextHookEx( hKeyboard, nCode, wParam, lParam ); }
[ "damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838" ]
[ [ [ 1, 157 ] ] ]
c7e21c79ce487e3bac74a8bd5a338c49635898f6
9df55ed98688ff13caec3061237a2a0895914577
/main.cpp
bd29e05649bceeeba97307229ac0bcc781176516
[]
no_license
tiashaun/sdl_tetris
f625ee0f06e642411f7a04b18b470aa0df61c1ca
4799cfa4b28cd21b8431f8b6a00bacfb89e794f0
refs/heads/master
2020-11-30T23:32:43.812813
2009-12-06T20:33:43
2009-12-06T20:33:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
165
cpp
#include <iostream> #include <SDL/SDL.h> #include "Game.h" int main(int argc, char* argv[]) { Game *game = new Game(); game->startGame(); return 0; }
[ [ [ 1, 10 ] ] ]
306f6e7e28b0353e88ec5e6e49cd37b5daa0f993
3ea33f3b6b61d71216d9e81993a7b6ab0898323b
/src/Network/Network.h
f0c677b807bde0fdc95a386d4f74c0a23c9a535d
[]
no_license
drivehappy/tlmp
fd1510f48ffea4020a277f28a1c4525dffb0397e
223c07c6a6b83e4242a5e8002885e23d0456f649
refs/heads/master
2021-01-10T20:45:15.629061
2011-07-07T00:43:00
2011-07-07T00:43:00
32,191,389
2
0
null
null
null
null
UTF-8
C++
false
false
932
h
#pragma once #include "Messages.h" #include "Server.h" #include "Client.h" #include "NetworkEntity.h" #include "State.h" namespace TLMP { namespace Network { class NetworkState { public: static NetworkState& getSingleton(); void SetState(State state); State GetState() const; inline bool GetSuppressed_LevelChange() { return m_bSuppressLevelChange; } inline void SetSuppressed_LevelChange(bool value) { m_bSuppressLevelChange = value; } protected: NetworkState(); NetworkState(const NetworkState&); NetworkState& operator=(const NetworkState&); ~NetworkState(); private: State m_State; bool m_bSuppressLevelChange; }; void HostGame(u16 port); void JoinGame(const char *address, u16 port); void StartReceivingMessages(); void ReceiveMessages(void *); }; };
[ "drivehappy@7af81de8-dd64-11de-95c9-073ad895b44c" ]
[ [ [ 1, 43 ] ] ]
3823170ca2526b7b1618b236d6bca0edf090a2d9
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-10-27/pcbnew/netlist.cpp
7707b586004638238f618260d1327606a22517e2
[]
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
31,012
cpp
/************************************/ /* PCBNEW: traitement des netlistes */ /************************************/ /* Fichier NETLIST.CPP */ /* Fonction de lecture de la netliste pour: - Chargement modules et nouvelles connexions - Test des modules (modules manquants ou en trop - Recalcul du chevelu Remarque importante: Lors de la lecture de la netliste pour Chargement modules et nouvelles connexions, l'identification des modules peut se faire selon 2 criteres: - la reference (U2, R5 ..): c'est le mode normal - le Time Stamp (Signature Temporelle), a utiliser apres reannotation d'un schema, donc apres modification des references sans pourtant avoir reellement modifie le schema */ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "pcbnew.h" #include "autorout.h" #include "protos.h" #define TESTONLY 1 /* ctes utilisees lors de l'appel a */ #define READMODULE 0 /* ReadNetModuleORCADPCB */ /* Structures locales */ class MODULEtoLOAD : public EDA_BaseStruct { public: wxString m_LibName; wxString m_CmpName; public: MODULEtoLOAD(const wxString & libname, const wxString & cmpname, int timestamp); ~MODULEtoLOAD(void){}; MODULEtoLOAD * Next(void) { return (MODULEtoLOAD *) Pnext; } }; /* Fonctions locales : */ static void SortListModulesToLoadByLibname(int NbModules); /* Variables locales */ static int s_NbNewModules; static MODULEtoLOAD * s_ModuleToLoad_List; FILE * source; static bool ChangeExistantModule; static bool DisplayWarning = TRUE; static int DisplayWarningCount ; /*****************************/ /* class WinEDA_NetlistFrame */ /*****************************/ enum id_netlist_functions { ID_READ_NETLIST_FILE = 1900, ID_TEST_NETLIST, ID_CLOSE_NETLIST, ID_COMPILE_RATSNEST, ID_OPEN_NELIST }; class WinEDA_NetlistFrame: public wxDialog { private: WinEDA_PcbFrame * m_Parent; wxDC * m_DC; wxRadioBox * m_Select_By_Timestamp; wxRadioBox * m_DeleteBadTracks; wxRadioBox * m_ChangeExistantModuleCtrl; wxCheckBox * m_DisplayWarningCtrl; wxTextCtrl * m_MessageWindow; public: // Constructor and destructor WinEDA_NetlistFrame(WinEDA_PcbFrame *parent, wxDC * DC, const wxPoint & pos); ~WinEDA_NetlistFrame(void) { } private: void OnQuit(wxCommandEvent& event); void ReadPcbNetlist(wxCommandEvent& event); void Set_NetlisteName(wxCommandEvent& event); bool OpenNetlistFile(wxCommandEvent& event); int BuildListeNetModules(wxCommandEvent& event, char * BufName); void ModulesControle(wxCommandEvent& event); void RecompileRatsnest(wxCommandEvent& event); int ReadListeModules(const char * RefCmp, int TimeStamp, char * NameModule); int SetPadNetName( char * Line, MODULE * Module); MODULE * ReadNetModule( char * Text, int * UseFichCmp, int TstOnly); void AddToList(const char * NameLibCmp, const char * NameCmp,int TimeStamp ); void LoadListeModules(wxDC *DC); DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(WinEDA_NetlistFrame, wxDialog) EVT_BUTTON(ID_READ_NETLIST_FILE, WinEDA_NetlistFrame::ReadPcbNetlist) EVT_BUTTON(ID_CLOSE_NETLIST, WinEDA_NetlistFrame::OnQuit) EVT_BUTTON(ID_OPEN_NELIST, WinEDA_NetlistFrame::Set_NetlisteName) EVT_BUTTON(ID_TEST_NETLIST, WinEDA_NetlistFrame::ModulesControle) EVT_BUTTON(ID_COMPILE_RATSNEST, WinEDA_NetlistFrame::RecompileRatsnest) END_EVENT_TABLE() /*************************************************************************/ void WinEDA_PcbFrame::InstallNetlistFrame( wxDC * DC, const wxPoint & pos) /*************************************************************************/ { WinEDA_NetlistFrame * frame = new WinEDA_NetlistFrame(this, DC, pos); frame->ShowModal(); frame->Destroy(); } /******************************************************************/ WinEDA_NetlistFrame::WinEDA_NetlistFrame(WinEDA_PcbFrame *parent, wxDC * DC, const wxPoint & framepos): wxDialog(parent, -1, "", framepos, wxSize(-1, -1), DIALOG_STYLE) /******************************************************************/ { wxPoint pos; wxString number; wxString title; wxButton * Button; m_Parent = parent; SetFont(*g_DialogFont); m_DC = DC; Centre(); /* Mise a jour du Nom du fichier NETLISTE correspondant */ NetNameBuffer = m_Parent->m_CurrentScreen->m_FileName; ChangeFileNameExt(NetNameBuffer, NetExtBuffer); title = _("Netlist: ") + NetNameBuffer; SetTitle(title); /* Creation des boutons de commande */ pos.x = 170; pos.y = 10; Button = new wxButton(this, ID_OPEN_NELIST, _("Select"), pos); Button->SetForegroundColour(*wxRED); pos.y += Button->GetDefaultSize().y + 10; Button = new wxButton(this, ID_READ_NETLIST_FILE, _("Read"), pos); Button->SetForegroundColour(wxColor(0,80,0) ); pos.y += Button->GetDefaultSize().y + 10; Button = new wxButton(this, ID_TEST_NETLIST, _("Module Test"), pos); Button->SetForegroundColour(wxColor(0,80,80) ); pos.y += Button->GetDefaultSize().y + 10; Button = new wxButton(this, ID_COMPILE_RATSNEST, _("Compile"), pos); Button->SetForegroundColour(wxColor(0,0,80) ); pos.y += Button->GetDefaultSize().y + 10; Button = new wxButton(this, ID_CLOSE_NETLIST, _("Close"), pos); Button->SetForegroundColour(*wxBLUE); // Options: wxString opt_select[2] = { _("Reference"), _("Timestamp") }; pos.x = 15; pos.y = 10; m_Select_By_Timestamp = new wxRadioBox( this, -1, _("Module Selection:"), pos, wxDefaultSize, 2, opt_select, 1); wxString track_select[2] = { _("Keep"), _("Delete") }; int x, y; m_Select_By_Timestamp->GetSize(&x, &y); pos.y += 5 + y; m_DeleteBadTracks = new wxRadioBox(this, -1, _("Bad Tracks Deletion:"), pos, wxDefaultSize, 2, track_select, 1); m_DeleteBadTracks->GetSize(&x, &y); pos.y += 5 + y; wxString change_module_select[2] = { _("Keep"), _("Change") }; m_ChangeExistantModuleCtrl = new wxRadioBox(this, -1, _("Exchange Module:"), pos, wxDefaultSize, 2, change_module_select, 1); m_ChangeExistantModuleCtrl->GetSize(&x, &y); pos.y += 15 + y; m_DisplayWarningCtrl = new wxCheckBox(this, -1, _("Display Warnings"), pos); m_DisplayWarningCtrl->SetValue(DisplayWarning); m_DisplayWarningCtrl->GetSize(&x, &y); pos.x = 5; pos.y += 10 + y; m_MessageWindow = new wxTextCtrl(this, -1, "", pos, wxSize(265, 120),wxTE_READONLY|wxTE_MULTILINE); m_MessageWindow->GetSize(&x, &y); pos.y += 10 + y; SetClientSize(280, pos.y); } /**********************************************************************/ void WinEDA_NetlistFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) /**********************************************************************/ { // true is to force the frame to close Close(true); } /*****************************************************************/ void WinEDA_NetlistFrame::RecompileRatsnest(wxCommandEvent& event) /*****************************************************************/ { m_Parent->Compile_Ratsnest(m_DC, TRUE); } /***************************************************************/ bool WinEDA_NetlistFrame::OpenNetlistFile(wxCommandEvent& event) /***************************************************************/ /* routine de selection et d'ouverture du fichier Netlist */ { wxString FullFileName; wxString msg; if( NetNameBuffer == "" ) /* Pas de nom specifie */ Set_NetlisteName(event); if( NetNameBuffer == "" ) return(FALSE); /* toujours Pas de nom specifie */ FullFileName = NetNameBuffer; source = fopen(FullFileName.GetData(),"rt"); if (source == 0) { msg.Printf(_("Netlist file %s not found"),FullFileName.GetData()) ; DisplayError(this, msg) ; return FALSE ; } msg.Printf("Netlist %s",FullFileName.GetData()); SetTitle(msg); return TRUE; } /**************************************************************/ void WinEDA_NetlistFrame::ReadPcbNetlist(wxCommandEvent& event) /**************************************************************/ /* mise a jour des empreintes : corrige les Net Names, les textes, les "TIME STAMP" Analyse les lignes: # EESchema Netlist Version 1.0 generee le 18/5/2005-12:30:22 ( ( 40C08647 $noname R20 4,7K {Lib=R} ( 1 VCC ) ( 2 MODB_1 ) ) ( 40C0863F $noname R18 4,7_k {Lib=R} ( 1 VCC ) ( 2 MODA_1 ) ) } #End */ { int LineNum, State, Comment; MODULE * Module = NULL; D_PAD * PtPad; char Line[256], *Text; int UseFichCmp = 1; wxString msg; ChangeExistantModule = m_ChangeExistantModuleCtrl->GetSelection() == 1 ? TRUE : FALSE; DisplayWarning = m_DisplayWarningCtrl->GetValue(); if ( DisplayWarning ) DisplayWarningCount = 8; else DisplayWarningCount = 0; if( ! OpenNetlistFile(event) ) return; msg = _("Read Netlist ") + NetNameBuffer; m_MessageWindow->AppendText(msg); m_Parent->m_CurrentScreen->SetModify(); m_Parent->m_Pcb->m_Status_Pcb = 0 ; State = 0; LineNum = 0; Comment = 0; s_NbNewModules = 0; /* Premiere lecture de la netliste: etablissement de la liste des modules a charger */ while( GetLine( source, Line, &LineNum) ) { Text = StrPurge(Line); if ( Comment ) /* Commentaires en cours */ { if( (Text = strchr(Text,'}') ) == NULL )continue; Comment = 0; } if ( *Text == '{' ) /* Commentaires */ { Comment = 1; if( (Text = strchr(Text,'}') ) == NULL ) continue; } if ( *Text == '(' ) State++; if ( *Text == ')' ) State--; if( State == 2 ) { Module = ReadNetModule(Text, & UseFichCmp, TESTONLY); continue; } if( State >= 3 ) /* la ligne de description d'un pad est ici non analysee */ { State--; } } /* Chargement des nouveaux modules */ if( s_NbNewModules ) { LoadListeModules(m_DC); // Free module list: MODULEtoLOAD * item, *next_item; for ( item = s_ModuleToLoad_List; item != NULL; item = next_item ) { next_item = item->Next(); delete item; } s_ModuleToLoad_List = NULL; } /* Relecture de la netliste, tous les modules sont ici charges */ fseek(source, 0, SEEK_SET); LineNum = 0; while( GetLine( source, Line, &LineNum) ) { Text = StrPurge(Line); if ( Comment ) /* Commentaires en cours */ { if( (Text = strchr(Text,'}') ) == NULL )continue; Comment = 0; } if ( *Text == '{' ) /* Commentaires */ { Comment = 1; if( (Text = strchr(Text,'}') ) == NULL ) continue; } if ( *Text == '(' ) State++; if ( *Text == ')' ) State--; if( State == 2 ) { Module = ReadNetModule(Text, & UseFichCmp, READMODULE ); if( Module == NULL ) { /* empreinte non trouvee dans la netliste */ continue ; } else /* Raz netnames sur pads */ { PtPad = Module->m_Pads; for( ; PtPad != NULL; PtPad = (D_PAD *)PtPad->Pnext ) { PtPad->m_Netname = ""; } } continue; } if( State >= 3 ) { if ( Module ) { SetPadNetName( Text, Module); } State--; } } fclose(source); /* Mise a jour et Cleanup du circuit imprime: */ m_Parent->Compile_Ratsnest(m_DC, TRUE); if( m_Parent->m_Pcb->m_Track ) { if( m_DeleteBadTracks->GetSelection() == 1 ) { wxBeginBusyCursor();; Netliste_Controle_piste(m_Parent, m_DC, TRUE); m_Parent->Compile_Ratsnest(m_DC, TRUE); wxEndBusyCursor();; } } Affiche_Infos_Status_Pcb(m_Parent); } /****************************************************************************/ MODULE * WinEDA_NetlistFrame::ReadNetModule(char * Text, int * UseFichCmp, int TstOnly) /****************************************************************************/ /* charge la description d'une empreinte ,netliste type PCBNEW et met a jour le module correspondant Si TstOnly == 0 si le module n'existe pas, il est charge Si TstOnly != 0 si le module n'existe pas, il est ajoute a la liste des modules a charger Text contient la premiere ligne de la description * UseFichCmp est un flag si != 0, le fichier des composants .CMP sera utilise est remis a 0 si le fichier n'existe pas Analyse les lignes type: ( 40C08647 $noname R20 4,7K {Lib=R} ( 1 VCC ) ( 2 MODB_1 ) */ { MODULE * Module; char *TextTimeStamp; char *TextNameLibMod; char *TextValeur; char *TextCmpName; int TimeStamp = -1, Error = 0; char Line[1024], NameLibCmp[256]; bool Found; strcpy(Line,Text); if( (TextTimeStamp = strtok(Line, " ()\t\n")) == NULL ) Error = 1; if( (TextNameLibMod = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; if( (TextCmpName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; if( (TextValeur = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; if( Error ) return( NULL ); sscanf(TextTimeStamp,"%X", &TimeStamp); /* Tst si composant deja charge */ Module = (MODULE*) m_Parent->m_Pcb->m_Modules; MODULE * NextModule; for( Found = FALSE; Module != NULL; Module = NextModule ) { NextModule = (MODULE*)Module->Pnext; if( m_Select_By_Timestamp->GetSelection() == 1 ) /* Reconnaissance par signature temporelle */ { if( TimeStamp == Module->m_TimeStamp) Found = TRUE; } else /* Reconnaissance par Reference */ { if( stricmp(TextCmpName,Module->m_Reference->GetText()) == 0 ) Found = TRUE; } if ( Found ) // Test si module (m_LibRef) et module specifie en netlist concordent { if( TstOnly != TESTONLY ) { strcpy(NameLibCmp, TextNameLibMod); if( *UseFichCmp ) { if( m_Select_By_Timestamp->GetSelection() == 1 ) { /* Reconnaissance par signature temporelle */ *UseFichCmp = ReadListeModules(NULL, TimeStamp, NameLibCmp); } else /* Reconnaissance par Reference */ { *UseFichCmp = ReadListeModules(TextCmpName, 0, NameLibCmp); } } if ( stricmp(Module->m_LibRef.GetData(), NameLibCmp) != 0 ) {// Module Mismatch: Current module and module specified in netlist are diff. if ( ChangeExistantModule ) { MODULE * NewModule = m_Parent->Get_Librairie_Module(this, "", NameLibCmp, TRUE); if( NewModule ) /* Nouveau module trouve : changement de module */ Module = m_Parent->Exchange_Module(this, Module, NewModule); } else { wxString msg; msg.Printf( _("Cmp %s: Mismatch! module is [%s] and netlist said [%s]\n"), TextCmpName, Module->m_LibRef.GetData(), NameLibCmp); m_MessageWindow->AppendText(msg); if ( DisplayWarningCount > 0) { DisplayError(this, msg, 2); DisplayWarningCount--; } } } } break; } } if( Module == NULL ) /* Module a charger */ { strcpy(NameLibCmp, TextNameLibMod); if( *UseFichCmp ) { if( m_Select_By_Timestamp->GetSelection() == 1) { /* Reconnaissance par signature temporelle */ *UseFichCmp = ReadListeModules(NULL, TimeStamp, NameLibCmp); } else /* Reconnaissance par Reference */ { *UseFichCmp = ReadListeModules(TextCmpName, 0, NameLibCmp); } } if( TstOnly == TESTONLY) AddToList(NameLibCmp, TextCmpName, TimeStamp); else { wxString msg; msg.Printf(_("Componant [%s] not found"), TextCmpName); m_MessageWindow->AppendText(msg+"\n"); if (DisplayWarningCount> 0) { DisplayError(this, msg, 2); DisplayWarningCount--; } } return(NULL); /* Le module n'avait pas pu etre charge */ } /* mise a jour des reperes ( nom et ref "Time Stamp") si module charge */ Module->m_Reference->m_Text = TextCmpName; Module->m_Value->m_Text = TextValeur; Module->m_TimeStamp = TimeStamp; return(Module) ; /* composant trouve */ } /********************************************************************/ int WinEDA_NetlistFrame::SetPadNetName( char * Text, MODULE * Module) /********************************************************************/ /* Met a jour le netname de 1 pastille, Netliste ORCADPCB entree : Text = ligne de netliste lue ( (pad = net) ) Module = adresse de la structure MODULE a qui appartient les pads */ { D_PAD * pad; char * TextPinName, * TextNetName; int Error = 0; bool trouve; char Line[256], Msg[80]; if( Module == NULL ) return ( 0 ); strcpy( Line, Text); if( (TextPinName = strtok(Line, " ()\t\n")) == NULL ) Error = 1; if( (TextNetName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; if(Error) return(0); /* recherche du pad */ pad = Module->m_Pads; trouve = FALSE; for( ; pad != NULL; pad = (D_PAD *)pad->Pnext ) { if( strnicmp( TextPinName, pad->m_Padname, 4) == 0 ) { /* trouve */ trouve = TRUE; if( *TextNetName != '?' ) pad->m_Netname = TextNetName; else pad->m_Netname = ""; } } if( !trouve && (DisplayWarningCount > 0) ) { sprintf(Msg,_("Module [%s]: Pad [%s] not found"), Module->m_Reference->GetText(), TextPinName); DisplayError(this, Msg, 1); DisplayWarningCount--; } return(trouve); } /*****************************************************/ MODULE * WinEDA_PcbFrame::ListAndSelectModuleName(void) /*****************************************************/ /* liste les noms des modules du PCB Retourne: un pointeur sur le module selectionne NULL si pas de selection */ { int ii, jj, nb_empr; MODULE * Module; WinEDAListBox * ListBox; const char ** ListNames = NULL; if( m_Pcb->m_Modules == NULL ) { DisplayError(this, _("No Modules") ) ; return(0); } /* Calcul du nombre des modules */ nb_empr = 0; Module = (MODULE*)m_Pcb->m_Modules; for( ;Module != NULL; Module = (MODULE*)Module->Pnext) nb_empr++; ListNames = (const char**) MyZMalloc( (nb_empr + 1) * sizeof(char*) ); Module = (MODULE*) m_Pcb->m_Modules; for( ii = 0; Module != NULL; Module = (MODULE*)Module->Pnext, ii++) { ListNames[ii] = Module->m_Reference->GetText(); } ListBox = new WinEDAListBox(this, _("Componants"), ListNames, ""); ii = ListBox->ShowModal(); ListBox->Destroy(); if( ii < 0 ) /* Pas de selection */ { Module = NULL; } else /* Recherche du module selectionne */ { Module = (MODULE*) m_Pcb->m_Modules; for( jj = 0; Module != NULL; Module = (MODULE*)Module->Pnext, jj++) { if( Module->m_Reference->GetText() == ListNames[ii] ) break; } } free(ListNames); return(Module); } /***************************************************************/ void WinEDA_NetlistFrame::ModulesControle(wxCommandEvent& event) /***************************************************************/ /* donne la liste : 1 - des empreintes doublées sur le PCB 2 - des empreintes manquantes par rapport a la netliste 3 - des empreintes supplémentaires par rapport a la netliste */ #define MAX_LEN_TXT 32 { int ii, NbModulesPcb; MODULE * Module, * pt_aux; int NbModulesNetListe ,nberr = 0 ; char *ListeNetModules, * NameNetMod; WinEDA_TextFrame * List; /* determination du nombre des modules du PCB*/ NbModulesPcb = 0; Module = (MODULE*) m_Parent->m_Pcb->m_Modules; for( ;Module != NULL; Module = (MODULE*)Module->Pnext) { NbModulesPcb++; } if( NbModulesPcb == 0 ) { DisplayError(this, _("No modules"), 10); return; } /* Construction de la liste des references des modules de la netliste */ NbModulesNetListe = BuildListeNetModules(event, NULL); if( NbModulesNetListe < 0 ) return; /* fichier non trouve */ if( NbModulesNetListe == 0 ) { DisplayError(this, _("No modules in NetList"), 10); return; } ii = NbModulesNetListe * (MAX_LEN_TXT + 1); ListeNetModules = (char*)MyZMalloc ( ii ); if( NbModulesNetListe ) BuildListeNetModules(event, ListeNetModules); List = new WinEDA_TextFrame(this, _("Check Modules")); /* recherche des doubles */ List->Append(_("Duplicates")); Module = (MODULE*) m_Parent->m_Pcb->m_Modules; for( ;Module != NULL; Module = (MODULE*)Module->Pnext) { pt_aux = (MODULE*)Module->Pnext; for( ; pt_aux != NULL; pt_aux = (MODULE*)pt_aux->Pnext) { if( strnicmp(Module->m_Reference->GetText(), pt_aux->m_Reference->GetText(),MAX_LEN_TXT) == 0 ) { List->Append(Module->m_Reference->GetText()); nberr++ ; break; } } } /* recherche des manquants par rapport a la netliste*/ List->Append(_("Lack:") ); NameNetMod = ListeNetModules; for ( ii = 0 ; ii < NbModulesNetListe ; ii++, NameNetMod += MAX_LEN_TXT+1 ) { Module = (MODULE*) m_Parent->m_Pcb->m_Modules; for( ;Module != NULL; Module = (MODULE*)Module->Pnext) { if( strnicmp(Module->m_Reference->GetText(), NameNetMod, MAX_LEN_TXT) == 0 ) { break; } } if( Module == NULL ) { List->Append(NameNetMod); nberr++ ; } } /* recherche des modules supplementaires (i.e. Non en Netliste) */ List->Append(_("Not in Netlist:") ); Module = (MODULE*) m_Parent->m_Pcb->m_Modules; for( ;Module != NULL; Module = Module->Next()) { NameNetMod = ListeNetModules; for (ii = 0; ii < NbModulesNetListe ; ii++, NameNetMod += MAX_LEN_TXT+1 ) { if( strnicmp(Module->m_Reference->GetText(), NameNetMod, MAX_LEN_TXT) == 0 ) { break ;/* Module trouve en netliste */ } } if( ii == NbModulesNetListe ) /* Module en trop */ { List->Append(Module->m_Reference->GetText()); nberr++ ; } } sprintf(cbuf, _("%d Errors"), nberr); List->ShowModal(); List->Destroy(); MyFree(ListeNetModules); } /***********************************************************************************/ int WinEDA_NetlistFrame::BuildListeNetModules(wxCommandEvent& event, char * BufName) /***********************************************************************************/ /* charge en BufName la liste des noms des modules de la netliste, ( chaque nom est en longueur fixe, sizeof(pt_texte_ref->name) + code 0 ) retourne le nombre des modules cités dans la netliste Si BufName == NULL: determination du nombre des Module uniquement */ { int textlen; int nb_modules_lus ; int State, LineNum, Comment; char Line[256], *Text, * LibModName; if( ! OpenNetlistFile(event) ) return -1; State = 0; LineNum = 0; Comment = 0; nb_modules_lus = 0; textlen = MAX_LEN_TXT; while( GetLine( source, Line, &LineNum) ) { Text = StrPurge(Line); if ( Comment ) /* Commentaires en cours */ { if( (Text = strchr(Text,'}') ) == NULL )continue; Comment = 0; } if ( *Text == '{' ) /* Commentaires */ { Comment = 1; if( (Text = strchr(Text,'}') ) == NULL ) continue; } if ( *Text == '(' ) State++; if ( *Text == ')' ) State--; if( State == 2 ) { int Error = 0; if( strtok(Line, " ()\t\n") == NULL ) Error = 1; /* TimeStamp */ if( ( LibModName = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; /* nom Lib */ /* Lecture du nom (reference) du composant: */ if( (Text = strtok(NULL, " ()\t\n")) == NULL ) Error = 1; nb_modules_lus++; if( BufName ) { strncpy( BufName, Text, textlen ); BufName[textlen] = 0; BufName += textlen+1; } continue; } if( State >= 3 ) { State--; /* Lecture 1 ligne relative au Pad */ } } fclose(source); return(nb_modules_lus); } /*****************************************************************************************/ int WinEDA_NetlistFrame::ReadListeModules(const char * RefCmp, int TimeStamp, char * NameModule) /*****************************************************************************************/ /* Lit le fichier .CMP donnant l'equivalence Modules / Composants Retourne: Si ce fichier existe: 1 et le nom module dans NameModule -1 si module non trouve en fichier sinon 0; parametres d'appel: RefCmp (NULL si selection par TimeStamp) TimeStamp (signature temporelle si elle existe, NULL sinon) pointeur sur le buffer recevant le nom du module Exemple de fichier: Cmp-Mod V01 Genere par PcbNew le 29/10/2003-13:11:6 BeginCmp TimeStamp = 322D3011; Reference = BUS1; ValeurCmp = BUSPC; IdModule = BUS_PC; EndCmp BeginCmp TimeStamp = 32307DE2; Reference = C1; ValeurCmp = 47uF; IdModule = CP6; EndCmp */ { wxString CmpFullFileName; char refcurrcmp[512], idmod[512], ia[1024]; int timestamp; char *ptcar; FILE * FichCmp; if( (RefCmp == NULL) && (TimeStamp == 0) ) return(0); CmpFullFileName = NetNameBuffer; ChangeFileNameExt(CmpFullFileName,NetCmpExtBuffer) ; FichCmp = fopen(CmpFullFileName.GetData(),"rt"); if (FichCmp == NULL) { wxString msg; msg.Printf( _("File <%s> not found, use Netlist for lib module selection"), CmpFullFileName.GetData()) ; DisplayError(this, cbuf, 20) ; return(0); } while( fgets(ia,sizeof(ia),FichCmp) != NULL ) { if( strnicmp(ia,"BeginCmp",8) != 0 ) continue; /* Ici une description de 1 composant commence */ *refcurrcmp = *idmod = 0; timestamp = -1; while( fgets(ia,sizeof(ia),FichCmp) != NULL ) { if( strnicmp(ia,"EndCmp",6) == 0 ) break; if( strnicmp(ia,"Reference =",11) == 0 ) { ptcar = ia+11; ptcar = strtok(ptcar," =;\t\n"); if( ptcar ) strcpy(refcurrcmp,ptcar); continue; } if( strnicmp(ia,"IdModule =",11) == 0 ) { ptcar = ia+11; ptcar = strtok(ptcar," =;\t\n"); if( ptcar ) strcpy(idmod,ptcar); continue; } if( strnicmp(ia,"TimeStamp =",11) == 0 ) { ptcar = ia+11; ptcar = strtok(ptcar," =;\t\n"); if( ptcar ) sscanf(ptcar, "%X", &timestamp); } }/* Fin lecture 1 descr composant */ /* Test du Composant lu en fichier: est-il le bon */ if( RefCmp ) { if( stricmp(RefCmp, refcurrcmp) == 0 ) { fclose(FichCmp); strcpy(NameModule, idmod); return(1); } } else if( TimeStamp != -1 ) { if( TimeStamp == timestamp ) { fclose(FichCmp); strcpy(NameModule, idmod); return(1); } } } fclose(FichCmp); return(-1); } /***************************************************************/ void WinEDA_NetlistFrame::Set_NetlisteName(wxCommandEvent& event) /***************************************************************/ /* Selection un nouveau nom de netliste Affiche la liste des fichiers netlistes pour selection sur liste */ { wxString fullfilename, mask("*"); mask += NetExtBuffer; fullfilename = EDA_FileSelector( _("Netlist Selection:"), "", /* Chemin par defaut */ NetNameBuffer, /* nom fichier par defaut */ NetExtBuffer, /* extension par defaut */ mask, /* Masque d'affichage */ this, 0, TRUE ); if ( fullfilename == "" ) return; NetNameBuffer = fullfilename; SetTitle(fullfilename); } /***********************************************************************************/ void WinEDA_NetlistFrame::AddToList(const char * NameLibCmp, const char * CmpName,int TimeStamp ) /************************************************************************************/ /* Fontion copiant en memoire de travail les caracteristiques des nouveaux modules */ { MODULEtoLOAD * NewMod; NewMod = new MODULEtoLOAD(NameLibCmp, CmpName, TimeStamp); NewMod->Pnext = s_ModuleToLoad_List; s_ModuleToLoad_List = NewMod; s_NbNewModules++; } /***************************************************************/ void WinEDA_NetlistFrame::LoadListeModules(wxDC * DC) /***************************************************************/ /* Routine de chargement des nouveaux modules en une seule lecture des librairies Si un module vient d'etre charge il est duplique, ce qui evite une lecture inutile de la librairie */ { MODULEtoLOAD * ref, *cmp; int ii; MODULE * Module = NULL; wxPoint OldPos = m_Parent->m_CurrentScreen->m_Curseur; if( s_NbNewModules == 0 ) return; SortListModulesToLoadByLibname(s_NbNewModules); ref = cmp = s_ModuleToLoad_List; // Calcul de la coordonnée de placement des modules: if ( m_Parent->SetBoardBoundaryBoxFromEdgesOnly() ) { m_Parent->m_CurrentScreen->m_Curseur.x = m_Parent->m_Pcb->m_BoundaryBox.GetRight() + 5000; m_Parent->m_CurrentScreen->m_Curseur.y = m_Parent->m_Pcb->m_BoundaryBox.GetBottom() + 10000; } else { m_Parent->m_CurrentScreen->m_Curseur = wxPoint(0,0); } for( ii = 0; ii < s_NbNewModules; ii++, cmp = cmp->Next() ) { if( (ii == 0) || ( ref->m_LibName != cmp->m_LibName) ) { /* Nouveau Module a charger */ Module = m_Parent->Get_Librairie_Module(this, "", cmp->m_LibName, TRUE ); ref = cmp; if ( Module == NULL ) continue; m_Parent->Place_Module(Module, DC); /* mise a jour des reperes ( nom et ref "Time Stamp") si module charge */ Module->m_Reference->m_Text = cmp->m_CmpName; Module->m_TimeStamp = cmp->m_TimeStamp; } else { /* module deja charge, on peut le dupliquer */ MODULE * newmodule; if ( Module == NULL ) continue; /* module non existant en libr */ newmodule = new MODULE(m_Parent->m_Pcb); newmodule->Copy(Module); newmodule->AddToChain(Module); Module = newmodule; Module->m_Reference->m_Text = cmp->m_CmpName; Module->m_TimeStamp = cmp->m_TimeStamp; } } m_Parent->m_CurrentScreen->m_Curseur = OldPos; } /* Routine utilisee par qsort pour le tri des modules a charger */ static int SortByLibName( MODULEtoLOAD ** ref, MODULEtoLOAD ** cmp ) { return (strcmp( (*ref)->m_LibName.GetData(), (*cmp)->m_LibName.GetData() ) ); } /*************************************************/ void SortListModulesToLoadByLibname(int NbModules) /**************************************************/ /* Rearrage la liste des modules List par ordre alphabetique des noms lib des modules */ { MODULEtoLOAD ** base_list, * item; int ii; base_list = (MODULEtoLOAD **) MyMalloc( NbModules * sizeof(MODULEtoLOAD *) ); for ( ii = 0, item = s_ModuleToLoad_List; ii < NbModules; ii++ ) { base_list[ii] = item; item = item->Next(); } qsort( base_list, NbModules, sizeof(MODULEtoLOAD*), (int(*)(const void *, const void *) )SortByLibName); // Reconstruction du chainage: s_ModuleToLoad_List = *base_list; for ( ii = 0; ii < NbModules-1; ii++ ) { item = base_list[ii]; item->Pnext = base_list[ii + 1]; } // Dernier item: Pnext = NULL: item = base_list[ii]; item->Pnext = NULL; free(base_list); } /*****************************************************************************/ MODULEtoLOAD::MODULEtoLOAD(const wxString & libname, const wxString & cmpname, int timestamp) : EDA_BaseStruct(TYPE_NOT_INIT) /*****************************************************************************/ { m_LibName = libname; m_CmpName = cmpname; m_TimeStamp = timestamp; }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 1103 ] ] ]
a59360fcf81c53b3316b720901fda7ee24465ddb
6be1c51c980e8906406762fe3c7b59ca6c09faaf
/SimpleKBot/KBotDrive.cpp
a086b75458bb2ac738955e38cad84771b0f2bb35
[]
no_license
woodk/SimpleKBot
4aed0122fa8a8e4b49bff3a966c31af85a6cd87f
4433bd1ca71c3b39460032279dea4c089aa1eb04
refs/heads/master
2021-01-01T18:07:55.574893
2011-01-07T19:37:40
2011-01-07T19:37:40
1,035,746
0
0
null
null
null
null
UTF-8
C++
false
false
6,724
cpp
/*----------------------------------------------------------------------------*/ /* Copyright (c) KBotics 2010. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. */ /*----------------------------------------------------------------------------*/ #include "KBotDrive.h" #include "GenericHID.h" KBotDrive::KBotDrive(UINT32 leftMotorChannel, UINT32 rightMotorChannel) : RobotDrive(leftMotorChannel, rightMotorChannel){;} KBotDrive::KBotDrive(UINT32 frontLeftMotorChannel, UINT32 rearLeftMotorChannel, UINT32 frontRightMotorChannel, UINT32 rearRightMotorChannel) : RobotDrive(frontLeftMotorChannel, rearLeftMotorChannel, frontRightMotorChannel, rearRightMotorChannel){;} KBotDrive::KBotDrive(SpeedController *leftMotor, SpeedController *rightMotor) : RobotDrive(leftMotor, rightMotor){;} KBotDrive::KBotDrive(SpeedController &leftMotor, SpeedController &rightMotor) : RobotDrive(leftMotor, rightMotor){;} KBotDrive::KBotDrive(SpeedController *frontLeftMotor, SpeedController *rearLeftMotor, SpeedController *frontRightMotor, SpeedController *rearRightMotor) : RobotDrive(frontLeftMotor, rearLeftMotor, frontRightMotor, rearRightMotor){;} KBotDrive::KBotDrive(SpeedController &frontLeftMotor, SpeedController &rearLeftMotor, SpeedController &frontRightMotor, SpeedController &rearRightMotor) : RobotDrive(frontLeftMotor, rearLeftMotor, frontRightMotor, rearRightMotor){;} /** * Arcade drive implements single stick driving. * Given a single Joystick, the class assumes the Y axis for the move value and the X axis * for the rotate value. * (Should add more information here regarding the way that arcade drive works.) * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected * for forwards/backwards and the X-axis will be selected for rotation rate. * @param squaredInputs If true, the sensitivity will be increased for small values */ void KBotDrive::ArcadeDrive(GenericHID *stick, bool squaredInputs) { // simply call the full-featured ArcadeDrive with the appropriate values ArcadeDrive(stick->GetY(), stick->GetX(), stick->GetTrigger()); } /** * Arcade drive implements single stick driving. * Given a single Joystick, the class assumes the Y axis for the move value and the X axis * for the rotate value. * (Should add more information here regarding the way that arcade drive works.) * @param stick The joystick to use for Arcade single-stick driving. The Y-axis will be selected * for forwards/backwards and the X-axis will be selected for rotation rate. * @param squaredInputs If true, the sensitivity will be increased for small values */ void KBotDrive::ArcadeDrive(GenericHID &stick, bool squaredInputs) { // simply call the full-featured ArcadeDrive with the appropriate values ArcadeDrive(stick.GetY(), stick.GetX(), stick.GetTrigger()); } /** * Arcade drive implements single stick driving. * Given two joystick instances and two axis, compute the values to send to either two * or four motors. * @param moveStick The Joystick object that represents the forward/backward direction * @param moveAxis The axis on the moveStick object to use for fowards/backwards (typically Y_AXIS) * @param rotateStick The Joystick object that represents the rotation value * @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically X_AXIS) * @param squaredInputs Setting this parameter to true increases the sensitivity at lower speeds */ void KBotDrive::ArcadeDrive(GenericHID* moveStick, UINT32 moveAxis, GenericHID* rotateStick, UINT32 rotateAxis, bool squaredInputs) { float moveValue = moveStick->GetRawAxis(moveAxis); float rotateValue = rotateStick->GetRawAxis(rotateAxis); ArcadeDrive(moveValue, rotateValue, squaredInputs); } /** * Arcade drive implements single stick driving. * Given two joystick instances and two axis, compute the values to send to either two * or four motors. * @param moveStick The Joystick object that represents the forward/backward direction * @param moveAxis The axis on the moveStick object to use for fowards/backwards (typically Y_AXIS) * @param rotateStick The Joystick object that represents the rotation value * @param rotateAxis The axis on the rotation object to use for the rotate right/left (typically X_AXIS) * @param squaredInputs Setting this parameter to true increases the sensitivity at lower speeds */ void KBotDrive::ArcadeDrive(GenericHID &moveStick, UINT32 moveAxis, GenericHID &rotateStick, UINT32 rotateAxis, bool squaredInputs) { float moveValue = moveStick.GetRawAxis(moveAxis); float rotateValue = rotateStick.GetRawAxis(rotateAxis); ArcadeDrive(moveValue, rotateValue, squaredInputs); } /** * Arcade drive implements single stick driving. * This function lets you directly provide joystick values from any source. * @param moveValue The value to use for fowards/backwards * @param rotateValue The value to use for the rotate right/left * @param squaredInputs If set, increases the sensitivity at low speeds */ void KBotDrive::ArcadeDrive(float moveValue, float rotateValue, bool squaredInputs) { // local variables to hold the computed PWM values for the motors float leftMotorSpeed; float rightMotorSpeed; moveValue = Limit(moveValue); rotateValue = Limit(rotateValue); if (squaredInputs) { // square the inputs (while preserving the sign) to increase fine control while permitting full power if (moveValue >= 0.0) { moveValue = (moveValue * moveValue); } else { moveValue = -(moveValue * moveValue); } if (rotateValue >= 0.0) { rotateValue = (rotateValue * rotateValue); } else { rotateValue = -(rotateValue * rotateValue); } } leftMotorSpeed = moveValue - rotateValue; rightMotorSpeed = moveValue + rotateValue; // Modify reverse so that back-left goes back-left and back-right goes back-right if (moveValue<0) { // Joystick backwards (NOTE: < not > for new robot) leftMotorSpeed += 2*moveValue*rotateValue; rightMotorSpeed -= 2*moveValue*rotateValue; } if (leftMotorSpeed>0.95) leftMotorSpeed=1.0; if (leftMotorSpeed<-0.95) leftMotorSpeed=-1.0; if (rightMotorSpeed>0.95) rightMotorSpeed=1.0; if (rightMotorSpeed<-0.95) rightMotorSpeed=-1.0; SetLeftRightMotorOutputs(leftMotorSpeed, rightMotorSpeed); m_fLeftSpeed = leftMotorSpeed; m_fRightSpeed = rightMotorSpeed; }
[ [ [ 1, 149 ] ] ]
a18abd538c27de8be9e52c154b86670921f7ff2e
a84b013cd995870071589cefe0ab060ff3105f35
/webdriver/branches/chrome/chrome/src/cpp/include/breakpad/src/client/windows/handler/exception_handler.h
c3d94e2227b6432949bd2097a7f3d26f817bdf3e
[ "Apache-2.0" ]
permissive
vdt/selenium
137bcad58b7184690b8785859d77da0cd9f745a0
30e5e122b068aadf31bcd010d00a58afd8075217
refs/heads/master
2020-12-27T21:35:06.461381
2009-08-18T15:56:32
2009-08-18T15:56:32
13,650,409
1
0
null
null
null
null
UTF-8
C++
false
false
19,036
h
// Copyright (c) 2006, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ExceptionHandler can write a minidump file when an exception occurs, // or when WriteMinidump() is called explicitly by your program. // // To have the exception handler write minidumps when an uncaught exception // (crash) occurs, you should create an instance early in the execution // of your program, and keep it around for the entire time you want to // have crash handling active (typically, until shutdown). // // If you want to write minidumps without installing the exception handler, // you can create an ExceptionHandler with install_handler set to false, // then call WriteMinidump. You can also use this technique if you want to // use different minidump callbacks for different call sites. // // In either case, a callback function is called when a minidump is written, // which receives the unqiue id of the minidump. The caller can use this // id to collect and write additional application state, and to launch an // external crash-reporting application. // // It is important that creation and destruction of ExceptionHandler objects // be nested cleanly, when using install_handler = true. // Avoid the following pattern: // ExceptionHandler *e = new ExceptionHandler(...); // ExceptionHandler *f = new ExceptionHandler(...); // delete e; // This will put the exception filter stack into an inconsistent state. #ifndef CLIENT_WINDOWS_HANDLER_EXCEPTION_HANDLER_H__ #define CLIENT_WINDOWS_HANDLER_EXCEPTION_HANDLER_H__ #include <stdlib.h> #include <Windows.h> #include <DbgHelp.h> #include <rpc.h> #pragma warning( push ) // Disable exception handler warnings. #pragma warning( disable : 4530 ) #include <string> #include <vector> #include "client/windows/common/ipc_protocol.h" #include "client/windows/crash_generation/crash_generation_client.h" #include "google_breakpad/common/minidump_format.h" #include "processor/scoped_ptr.h" namespace google_breakpad { using std::vector; using std::wstring; class ExceptionHandler { public: // A callback function to run before Breakpad performs any substantial // processing of an exception. A FilterCallback is called before writing // a minidump. context is the parameter supplied by the user as // callback_context when the handler was created. exinfo points to the // exception record, if any; assertion points to assertion information, // if any. // // If a FilterCallback returns true, Breakpad will continue processing, // attempting to write a minidump. If a FilterCallback returns false, Breakpad // will immediately report the exception as unhandled without writing a // minidump, allowing another handler the opportunity to handle it. typedef bool (*FilterCallback)(void* context, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion); // A callback function to run after the minidump has been written. // minidump_id is a unique id for the dump, so the minidump // file is <dump_path>\<minidump_id>.dmp. context is the parameter supplied // by the user as callback_context when the handler was created. exinfo // points to the exception record, or NULL if no exception occurred. // succeeded indicates whether a minidump file was successfully written. // assertion points to information about an assertion if the handler was // invoked by an assertion. // // If an exception occurred and the callback returns true, Breakpad will treat // the exception as fully-handled, suppressing any other handlers from being // notified of the exception. If the callback returns false, Breakpad will // treat the exception as unhandled, and allow another handler to handle it. // If there are no other handlers, Breakpad will report the exception to the // system as unhandled, allowing a debugger or native crash dialog the // opportunity to handle the exception. Most callback implementations // should normally return the value of |succeeded|, or when they wish to // not report an exception of handled, false. Callbacks will rarely want to // return true directly (unless |succeeded| is true). // // For out-of-process dump generation, dump path and minidump ID will always // be NULL. In case of out-of-process dump generation, the dump path and // minidump id are controlled by the server process and are not communicated // back to the crashing process. typedef bool (*MinidumpCallback)(const wchar_t* dump_path, const wchar_t* minidump_id, void* context, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion, bool succeeded); // HandlerType specifies which types of handlers should be installed, if // any. Use HANDLER_NONE for an ExceptionHandler that remains idle, // without catching any failures on its own. This type of handler may // still be triggered by calling WriteMinidump. Otherwise, use a // combination of the other HANDLER_ values, or HANDLER_ALL to install // all handlers. enum HandlerType { HANDLER_NONE = 0, HANDLER_EXCEPTION = 1 << 0, // SetUnhandledExceptionFilter HANDLER_INVALID_PARAMETER = 1 << 1, // _set_invalid_parameter_handler HANDLER_PURECALL = 1 << 2, // _set_purecall_handler HANDLER_ALL = HANDLER_EXCEPTION | HANDLER_INVALID_PARAMETER | HANDLER_PURECALL }; // Creates a new ExceptionHandler instance to handle writing minidumps. // Before writing a minidump, the optional filter callback will be called. // Its return value determines whether or not Breakpad should write a // minidump. Minidump files will be written to dump_path, and the optional // callback is called after writing the dump file, as described above. // handler_types specifies the types of handlers that should be installed. ExceptionHandler(const wstring& dump_path, FilterCallback filter, MinidumpCallback callback, void* callback_context, int handler_types); // Creates a new ExcetpionHandler instance that can attempt to perform // out-of-process dump generation if pipe_name is not NULL. If pipe_name is // NULL, or if out-of-process dump generation registration step fails, // in-process dump generation will be used. This also allows specifying // the dump type to generate. ExceptionHandler(const wstring& dump_path, FilterCallback filter, MinidumpCallback callback, void* callback_context, int handler_types, MINIDUMP_TYPE dump_type, const wchar_t* pipe_name, const CustomClientInfo* custom_info); ~ExceptionHandler(); // Get and set the minidump path. wstring dump_path() const { return dump_path_; } void set_dump_path(const wstring &dump_path) { dump_path_ = dump_path; dump_path_c_ = dump_path_.c_str(); UpdateNextID(); // Necessary to put dump_path_ in next_minidump_path_. } // Writes a minidump immediately. This can be used to capture the // execution state independently of a crash. Returns true on success. bool WriteMinidump(); // Writes a minidump immediately, with the user-supplied exception // information. bool WriteMinidumpForException(EXCEPTION_POINTERS* exinfo); // Convenience form of WriteMinidump which does not require an // ExceptionHandler instance. static bool WriteMinidump(const wstring &dump_path, MinidumpCallback callback, void* callback_context); // Get the thread ID of the thread requesting the dump (either the exception // thread or any other thread that called WriteMinidump directly). This // may be useful if you want to include additional thread state in your // dumps. DWORD get_requesting_thread_id() const { return requesting_thread_id_; } // Controls behavior of EXCEPTION_BREAKPOINT and EXCEPTION_SINGLE_STEP. bool get_handle_debug_exceptions() const { return handle_debug_exceptions_; } void set_handle_debug_exceptions(bool handle_debug_exceptions) { handle_debug_exceptions_ = handle_debug_exceptions; } // Returns whether out-of-process dump generation is used or not. bool IsOutOfProcess() const { return crash_generation_client_.get() != NULL; } private: friend class AutoExceptionHandler; // Initializes the instance with given values. void Initialize(const wstring& dump_path, FilterCallback filter, MinidumpCallback callback, void* callback_context, int handler_types, MINIDUMP_TYPE dump_type, const wchar_t* pipe_name, const CustomClientInfo* custom_info); // Function pointer type for MiniDumpWriteDump, which is looked up // dynamically. typedef BOOL (WINAPI *MiniDumpWriteDump_type)( HANDLE hProcess, DWORD dwPid, HANDLE hFile, MINIDUMP_TYPE DumpType, CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam); // Function pointer type for UuidCreate, which is looked up dynamically. typedef RPC_STATUS (RPC_ENTRY *UuidCreate_type)(UUID* Uuid); // Runs the main loop for the exception handler thread. static DWORD WINAPI ExceptionHandlerThreadMain(void* lpParameter); // Called on the exception thread when an unhandled exception occurs. // Signals the exception handler thread to handle the exception. static LONG WINAPI HandleException(EXCEPTION_POINTERS* exinfo); #if _MSC_VER >= 1400 // MSVC 2005/8 // This function will be called by some CRT functions when they detect // that they were passed an invalid parameter. Note that in _DEBUG builds, // the CRT may display an assertion dialog before calling this function, // and the function will not be called unless the assertion dialog is // dismissed by clicking "Ignore." static void HandleInvalidParameter(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t reserved); #endif // _MSC_VER >= 1400 // This function will be called by the CRT when a pure virtual // function is called. static void HandlePureVirtualCall(); // This is called on the exception thread or on another thread that // the user wishes to produce a dump from. It calls // WriteMinidumpWithException on the handler thread, avoiding stack // overflows and inconsistent dumps due to writing the dump from // the exception thread. If the dump is requested as a result of an // exception, exinfo contains exception information, otherwise, it // is NULL. If the dump is requested as a result of an assertion // (such as an invalid parameter being passed to a CRT function), // assertion contains data about the assertion, otherwise, it is NULL. bool WriteMinidumpOnHandlerThread(EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion); // This function does the actual writing of a minidump. It is called // on the handler thread. requesting_thread_id is the ID of the thread // that requested the dump. If the dump is requested as a result of // an exception, exinfo contains exception information, otherwise, // it is NULL. bool WriteMinidumpWithException(DWORD requesting_thread_id, EXCEPTION_POINTERS* exinfo, MDRawAssertionInfo* assertion); // Generates a new ID and stores it in next_minidump_id_, and stores the // path of the next minidump to be written in next_minidump_path_. void UpdateNextID(); FilterCallback filter_; MinidumpCallback callback_; void* callback_context_; scoped_ptr<CrashGenerationClient> crash_generation_client_; // The directory in which a minidump will be written, set by the dump_path // argument to the constructor, or set_dump_path. wstring dump_path_; // The basename of the next minidump to be written, without the extension. wstring next_minidump_id_; // The full pathname of the next minidump to be written, including the file // extension. wstring next_minidump_path_; // Pointers to C-string representations of the above. These are set when // the above wstring versions are set in order to avoid calling c_str during // an exception, as c_str may attempt to allocate heap memory. These // pointers are not owned by the ExceptionHandler object, but their lifetimes // should be equivalent to the lifetimes of the associated wstring, provided // that the wstrings are not altered. const wchar_t* dump_path_c_; const wchar_t* next_minidump_id_c_; const wchar_t* next_minidump_path_c_; HMODULE dbghelp_module_; MiniDumpWriteDump_type minidump_write_dump_; MINIDUMP_TYPE dump_type_; HMODULE rpcrt4_module_; UuidCreate_type uuid_create_; // Tracks the handler types that were installed according to the // handler_types constructor argument. int handler_types_; // When installed_handler_ is true, previous_filter_ is the unhandled // exception filter that was set prior to installing ExceptionHandler as // the unhandled exception filter and pointing it to |this|. NULL indicates // that there is no previous unhandled exception filter. LPTOP_LEVEL_EXCEPTION_FILTER previous_filter_; #if _MSC_VER >= 1400 // MSVC 2005/8 // Beginning in VC 8, the CRT provides an invalid parameter handler that will // be called when some CRT functions are passed invalid parameters. In // earlier CRTs, the same conditions would cause unexpected behavior or // crashes. _invalid_parameter_handler previous_iph_; #endif // _MSC_VER >= 1400 // The CRT allows you to override the default handler for pure // virtual function calls. _purecall_handler previous_pch_; // The exception handler thread. HANDLE handler_thread_; // The critical section enforcing the requirement that only one exception be // handled by a handler at a time. CRITICAL_SECTION handler_critical_section_; // Semaphores used to move exception handling between the exception thread // and the handler thread. handler_start_semaphore_ is signalled by the // exception thread to wake up the handler thread when an exception occurs. // handler_finish_semaphore_ is signalled by the handler thread to wake up // the exception thread when handling is complete. HANDLE handler_start_semaphore_; HANDLE handler_finish_semaphore_; // The next 2 fields contain data passed from the requesting thread to // the handler thread. // The thread ID of the thread requesting the dump (either the exception // thread or any other thread that called WriteMinidump directly). DWORD requesting_thread_id_; // The exception info passed to the exception handler on the exception // thread, if an exception occurred. NULL for user-requested dumps. EXCEPTION_POINTERS* exception_info_; // If the handler is invoked due to an assertion, this will contain a // pointer to the assertion information. It is NULL at other times. MDRawAssertionInfo* assertion_; // The return value of the handler, passed from the handler thread back to // the requesting thread. bool handler_return_value_; // If true, the handler will intercept EXCEPTION_BREAKPOINT and // EXCEPTION_SINGLE_STEP exceptions. Leave this false (the default) // to not interfere with debuggers. bool handle_debug_exceptions_; // A stack of ExceptionHandler objects that have installed unhandled // exception filters. This vector is used by HandleException to determine // which ExceptionHandler object to route an exception to. When an // ExceptionHandler is created with install_handler true, it will append // itself to this list. static vector<ExceptionHandler*>* handler_stack_; // The index of the ExceptionHandler in handler_stack_ that will handle the // next exception. Note that 0 means the last entry in handler_stack_, 1 // means the next-to-last entry, and so on. This is used by HandleException // to support multiple stacked Breakpad handlers. static LONG handler_stack_index_; // handler_stack_critical_section_ guards operations on handler_stack_ and // handler_stack_index_. static CRITICAL_SECTION handler_stack_critical_section_; // True when handler_stack_critical_section_ has been initialized. static bool handler_stack_critical_section_initialized_; // disallow copy ctor and operator= explicit ExceptionHandler(const ExceptionHandler &); void operator=(const ExceptionHandler &); }; } // namespace google_breakpad #pragma warning( pop ) #endif // CLIENT_WINDOWS_HANDLER_EXCEPTION_HANDLER_H__
[ "noel.gordon@07704840-8298-11de-bf8c-fd130f914ac9" ]
[ [ [ 1, 408 ] ] ]
e9fabf836bd1fa00753a3e18495f0a42db65a551
188058ec6dbe8b1a74bf584ecfa7843be560d2e5
/FLVGServer/ControlFrameWnd.cpp
302e14aca4d7dbd91d0b851018d7ff861638c323
[]
no_license
mason105/red5cpp
636e82c660942e2b39c4bfebc63175c8539f7df0
fcf1152cb0a31560af397f24a46b8402e854536e
refs/heads/master
2021-01-10T07:21:31.412996
2007-08-23T06:29:17
2007-08-23T06:29:17
36,223,621
0
0
null
null
null
null
UTF-8
C++
false
false
803
cpp
// ControlFrameWnd.cpp : implementation file // #include "stdafx.h" #include "XDigitalLifeServerApp.h" #include "ControlFrameWnd.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CControlFrameWnd IMPLEMENT_DYNCREATE(CControlFrameWnd, CFrameWnd) CControlFrameWnd::CControlFrameWnd() { } CControlFrameWnd::~CControlFrameWnd() { } BEGIN_MESSAGE_MAP(CControlFrameWnd, CFrameWnd) //{{AFX_MSG_MAP(CControlFrameWnd) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CControlFrameWnd message handlers
[ "soaris@46205fef-a337-0410-8429-7db05d171fc8" ]
[ [ [ 1, 35 ] ] ]
cb5d4ae5bb50b73a1c38e17350052a6b679dd042
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/dom/impl/DOMProcessingInstructionImpl.hpp
f12e36f8abaf181c33aed5444bd6e03aec696802
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
3,035
hpp
#ifndef DOMProcessingInstructionImpl_HEADER_GUARD_ #define DOMProcessingInstructionImpl_HEADER_GUARD_ /* * Copyright 2001-2002,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: DOMProcessingInstructionImpl.hpp 176026 2004-09-08 13:57:07Z peiyongz $ */ // // This file is part of the internal implementation of the C++ XML DOM. // It should NOT be included or used directly by application programs. // // Applications should include the file <xercesc/dom/DOM.hpp> for the entire // DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class // name is substituded for the *. // #include <xercesc/util/XercesDefs.hpp> #include <xercesc/dom/DOMProcessingInstruction.hpp> #include "DOMCharacterDataImpl.hpp" #include "DOMNodeImpl.hpp" #include "DOMChildNode.hpp" XERCES_CPP_NAMESPACE_BEGIN class DocumentImpl; class CDOM_EXPORT DOMProcessingInstructionImpl: public DOMProcessingInstruction { private: DOMNodeImpl fNode; DOMChildNode fChild; // use fCharacterData to store its data so that those character utitlites can be used DOMCharacterDataImpl fCharacterData; XMLCh *fTarget; const XMLCh *fBaseURI; public: DOMProcessingInstructionImpl(DOMDocument *ownerDoc, const XMLCh * target, const XMLCh *data); DOMProcessingInstructionImpl(const DOMProcessingInstructionImpl &other, bool deep=false); virtual ~DOMProcessingInstructionImpl(); // Declare all of the functions from DOMNode. DOMNODE_FUNCTIONS; virtual const XMLCh *getData() const; virtual const XMLCh *getTarget() const; virtual void setData(const XMLCh *arg); // NON-DOM: set base uri virtual void setBaseURI(const XMLCh* baseURI); // Non standard extension for the range to work void deleteData(XMLSize_t offset, XMLSize_t count); const XMLCh* substringData(XMLSize_t offset, XMLSize_t count) const; DOMProcessingInstruction* splitText(XMLSize_t offset); private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- DOMProcessingInstructionImpl & operator = (const DOMProcessingInstructionImpl &); }; XERCES_CPP_NAMESPACE_END #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 88 ] ] ]
e640252cbe72e57d898dbfa08d22087d7b03eb62
61c263eb77eb64cf8ab42d2262fc553ac51a6399
/src/Command.cpp
159a8add0c9b9be9607029b56d9a413ea0dd41b2
[]
no_license
ycaihua/fingermania
20760830f6fe7c48aa2332b67f455eef8f9246a3
daaa470caf02169ea6533669aa511bf59f896805
refs/heads/master
2021-01-20T09:36:38.221802
2011-01-23T12:31:19
2011-01-23T12:31:19
40,102,565
1
0
null
null
null
null
UTF-8
C++
false
false
2,118
cpp
#include "global.h" #include "Command.h" #include "RageUtil.h" #include "RageLog.h" #include "arch/Dialog/Dialog.h" #include "Foreach.h" RString Command::GetName() const { if (m_vsArgs.empty()) return RString(); RString s = m_vArgs[0]; Trim(s); return s; } Command::Arg Command::GetArg(unsigned index) const { Arg a; if (index < m_vsArgs.size()) a.s = m_vsArgs[index]; return a; } void Command::Load(const RString& sCommand) { m_vsArgs.clear(); split(sCommand, ",", m_vsArgs, false); } RString Command::GetOriginalCommandString() const { return join(",", m_vsArgs); } static void SplitWithQuotes(const RString sSource, const char Delimitor, vector<RString>& asOut, const bool bIgnoreEmpty) { if (sSource.empty()) return; size_t startpos = 0; do { size_t pos = startpos; while (pos < sSource.size()) { if (sSource[pos] == Delimitor) break; if (sSource[pos] == '"' || sSource[pos] == '\'') { pos = sSource.find(sSource[pos], pos + 1); if (pos == string::npos) pos = sSource.size(); else ++pos; } else ++pos; } if (pos - startpos > 0 || !bIgnoreEmpty) { if (startpos == 0 && pos - startpos == sSource.size()) asOut.push_back(sSource); else { const RString AddCString = sSource.substr( startpos, pos-startpos ); asOut.push_back( AddCString ); } } startpos = pos + 1; } while (startpos <= sSource.size()); } RString Commands::GetOriginalCommandString() const { RString s; FOREACH_CONST(Command, v, c) s += c->GetOriginalCommandString(); return s; } void ParseCommands(const RString& sCommands, Commands& vCommandOut) { vector<RString> vsCommands; SplitWithQuotes(sCommands, ";", vsCommands, true); vCommandsOut.resize(vsCommands.size()); for (unsigned i = 0; i < vsCommands.size(); i++) { Command& cmd = vCommandOut.v[i]; cmd.Load(vsCommands[i]); } } Commands ParseCommands(const RString& sCommands) { Commands vCommands; ParseCommands(sCommands, vCommands); return vCommands; }
[ [ [ 1, 105 ] ] ]
ae33782e1ed46f3e054a2e8462295f9673932769
d38dd2b4c110cdc21724977a5e7546e32fee80a4
/profile/Sigma.h
0ed2b5889651d91b7f76d89b13c481254bfa152e
[]
no_license
arm2arm/mstgraph
ae306f17e216dc5be06f79263a776f7cb9451f92
b9b8c1af1a56fbfabc9f7ecc34dcb7af23e4fd4e
refs/heads/master
2020-12-24T19:46:21.823308
2010-06-25T13:58:42
2010-06-25T13:58:42
56,456,768
0
0
null
null
null
null
UTF-8
C++
false
false
9,587
h
#ifndef _MYSIGMA_ #define _MYSIGMA_ ////////////// This class does velosity disperson profile. //usage: // CSigma<double> GetSigma(data.x, data.y, data.z, data.vx, data.vy, data.vz); // #include <vector> // for vector #include <algorithm> // for adjacent_find, find #include <functional> // for bind1st, equal_to #include <iostream> // for cout, endl #include <fstream> // for file IO #include <stdlib.h> #include <cmath> // for sqrt #include <cstring> // for string #include <string> // for string #include <bitset> //bitsets #include <valarray> //vallaray #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> //#include "utils.h" using std::vector; using std::valarray; using std::cout; using std::cerr; using std::endl; using std::string; /////////////// UTILS for some mnipulation struct TWhereIs{ vector<int> idx; vector<bool> hash; TWhereIs(vector<bool> bv){ hash=bv; }; TWhereIs(){}; vector<int> get(){return idx;}; void update(){ idx.clear(); for(size_t i=0;i<hash.size();i++) if(hash[i]) idx.push_back(i); }; void reset(){hash.clear();idx.clear();}; void push(vector<bool> bv){ if(hash.size()==0){ hash=bv; }else{ if(bv.size() != hash.size()) cerr<<"# Error in TWhereIs the vectors are not equal."<<endl; typedef vector<bool> BV; BV::iterator ibhash=hash.begin(), iehash=hash.end(); for(int i=0;iehash!=ibhash;ibhash++){ (*ibhash) = (*ibhash) && bv[i++]; } } update(); }; inline size_t size(){ return (int)std::count(hash.begin(), hash.end(), true); }; }; template <class Tg> valarray<Tg> get(vector<int> &ib,vector<Tg> &v) { valarray<Tg> tmp(ib.size()); for(size_t i=0;i<ib.size();i++) { tmp[i]= v[ib[i]]; } return tmp; }; void mma(vector<double> &data, std::string msg="Stat ") { std::cout<<msg+string(" min=")<<(*std::min_element(data.begin(), data.end())) <<endl; std::cout<<msg+string(" max=") << *std::max_element(data.begin(), data.end())<<endl; }; //////////////////////////////////////////// template <class T> class CSigma{ public: vector< vector<double> > sigma; vector<double> rr, rrslw; string m_fname; void save(vector<double> &rr_, vector< vector<double> > &sig, string fname) { std::ofstream stream(fname.c_str()); if(stream.is_open()) { stream<<"# Rad \t"; for(size_t ity=0;ity<types.size();ity++) stream<<"sigma_T"<<types[ity]<<"\t"; stream<<endl; for(size_t i=0;i<rr_.size();i++) { stream<<rr_[i]<<"\t"; for(size_t ity=0;ity<types.size();ity++) stream<<sig[ity][i]<<"\t"; stream<<endl; } } } struct CData { inline size_t size(){return x.size();}; inline T R(size_t i) { if(i<x.size()) return sqrt(x[i]*x[i]+y[i]*y[i]+z[i]*z[i]); return 0; } inline void reserve(size_t np){ m_np=np; x.resize(np); y.resize(np); z.resize(np); vx.resize(np); vy.resize(np); vz.resize(np); type.resize(np); }; void insert(int type_,float *pX, float *pV) { // if(abs(pX[2])<3.0 && abs(pV[2])<400.0 ) { x.push_back(pX[0]); y.push_back(pX[1]); z.push_back(pX[2]); vx.push_back(pV[0]); vy.push_back(pV[1]); vz.push_back(pV[2]); type.push_back(type_); } } void insert(int type_,T x_, T y_,T z_, T vx_, T vy_, T vz_) { x.push_back(x_); y.push_back(y_); z.push_back(z_); vx.push_back(vx_); vy.push_back(vy_); vz.push_back(vz_); type.push_back(type_); } valarray<double> GetDistXY() { valarray<double> dist(this->size()); for(size_t i=0;i<this->size();i++) { dist[i]=sqrt(x[i]*x[i]+y[i]*y[i]); } return dist; } size_t m_np; vector<T> x,y,z,vx, vy, vz; vector<int> type; void SubstractMean(vector<T> &x) { MeanValue mv = for_each (x.begin(), x.end(), // range MeanValue()); // operation std::transform(x.begin(), x.end(), x.begin(), std::bind2nd(std::plus<T>(), -mv.value())); }; void PutInCom(void) { SubstractMean(x);SubstractMean(y);SubstractMean(z); SubstractMean(vx);SubstractMean(vy);SubstractMean(vz); }; }data; enum eTYPE{T0,T1,T2,T3,T4,T5,numtypes}; std::bitset<numtypes> userTypes; vector<int> types; void GetTypes(std::string &strType){ string names[]={"T0","T1","T2","T3","T4","T5"}; std::string::iterator its=strType.begin(); while( its!=strType.end() ) { char ch=*its; int val=atoi(&ch); if(val > -1 && val<numtypes+1) { userTypes.set(val); types.push_back(val); } cout<<*its<<endl; its++; } }; CSigma(std::string strType,int *pType, float *pX, float *pV,size_t np) { m_fname="sigma.txt"; GetTypes(strType); if (userTypes.any()) { for(size_t i=0;i<np;i++) { if (userTypes[(eTYPE)pType[i]]) { data.insert(pType[i],&pX[i*3],&pV[i*3]); } } cout<<"# Prepare for sigma over the "<<data.size()<<" particles"<<endl; } }; ~CSigma(){ save(rr,sigma, m_fname); save(rrslw, sigmaSlitX, m_fname+".slitX"); save(rrslw, sigmaSlitY, m_fname+".slitY"); } vector<double> Jv; vector<double> GetJv(void) { Jv.resize(3); size_t np=0; for(size_t i =0; i<data.vz.size();i++) { if(data.type[i]==4 && data.R(i)<40.0) { Jv[0] += (data.y[i]*data.vz[i]-data.z[i]*data.vy[i]); Jv[1] += (data.z[i]*data.vx[i]-data.x[i]*data.vz[i]); Jv[2] += (data.x[i]*data.vy[i]-data.y[i]*data.vx[i]); np++; } } Jv[0]/=static_cast<double>(np); Jv[1]/=static_cast<double>(np); Jv[2]/=static_cast<double>(np); return Jv; } void GetSigma(size_t Nbins=150, double Rc=4.0){ int typeCount=userTypes.count(); if(!typeCount)return; cout<<"# Sigma in the X and Y slits..."; cout.flush(); GetSigmaInSlit(Nbins, Rc); cout<<"..done"<<endl; cout<<"# Sigma within circular rings .."; cout.flush(); valarray<double> dist(0.0,data.size()); for(size_t i=0;i<data.size();i++) { dist[i]=sqrt(data.x[i]*data.x[i]+data.y[i]*data.y[i]); } double dr=0.1; Nbins=(size_t)(Rc/dr); double r; sigma.resize(6); for(size_t i=0;i<6;i++) sigma[i].resize(Nbins); rr.resize(Nbins); valarray<double> vz(&data.vz[0], data.vz.size()); //valarray<double> z(&data.z[0], data.z.size()); valarray<int> type(&data.type[0], data.type.size()); double mvel=vz.sum()/(double)vz.size(); for(size_t i=0l;i<Nbins;i++) { r=dr*i; rr[i]=r; //cout<<i<<") "<<r<<" "; for(size_t itype=0;itype<types.size();itype++) { valarray<bool> ids = (dist < r+dr) && (dist > r) && (type==types[itype]); if(ids.max()) { valarray<double> d=vz[ids]; d-=mvel; d=pow(d,2.0); sigma[itype][i]= sqrt(d.sum()/(double)d.size()); } //cout<<sigma[itype][i]<<"\t"; } //cout<<endl; } cout<<"..done"<<endl; for(size_t i=0;i<6;i++) smooth(sigma[i]); }; /////////////////////////////// vector<vector<double> > sigmaSlitX, sigmaSlitY; void GetSigmaInSlit(size_t Nbins=150, double Rc=4.0, double slw=0.5, double dr=0.1){ CData slitdataX, slitdataY; //std::ofstream stream("test.txt"),streamy("test2.txt"); //if(stream.is_open()) for(size_t i=0;i<data.size();i++) { if(abs(data.y[i])<slw && abs(data.x[i])<Rc) { slitdataX.insert(data.type[i], data.x[i], data.y[i], data.z[i], data.vx[i], data.vy[i], data.vz[i] ); // stream<<data.x[i]<<" "<<data.y[i]<<endl; } if(abs(data.x[i])<slw && abs(data.y[i])<Rc) {slitdataY.insert(data.type[i], data.x[i], data.y[i], data.z[i], data.vx[i], data.vy[i], data.vz[i] ); //streamy<<data.x[i]<<" "<<data.y[i]<<endl; } } //stream.close();streamy.close(); dr=(2.0*Rc)/static_cast<double>(Nbins); cout<<"Nbins="<<Nbins<<endl; double r; sigmaSlitX.resize(6); sigmaSlitY.resize(6); for(size_t i=0;i<6;i++) { sigmaSlitX[i].resize(Nbins); sigmaSlitY[i].resize(Nbins); } rrslw.resize(Nbins); valarray<double> slitXvz(&slitdataX.vz[0], slitdataX.vz.size()); valarray<int> typeX(&slitdataX.type[0], slitdataX.type.size()); valarray<double> slitYvz(&slitdataY.vz[0], slitdataY.vz.size()); valarray<int> typeY(&slitdataY.type[0], slitdataY.type.size()); double mvelX=slitXvz.sum()/static_cast<double>(slitXvz.size()); double mvelY=slitYvz.sum()/static_cast<double>(slitYvz.size()); valarray<double> slwX(&slitdataX.x[0], slitdataX.x.size()); valarray<double> slwY(&slitdataY.y[0], slitdataY.y.size()); for(size_t i=0l;i<Nbins;i++) { r=dr*i-Rc; rrslw[i]=r; if(false)cout<<i<<" "<<r<<endl; for(size_t itype=0;itype<types.size();itype++) { valarray<bool> idsX = (slwX < r+dr) && (slwX > r) && (typeX==types[itype]); valarray<bool> idsY = (slwY < r+dr) && (slwY > r) && (typeY==types[itype]); if(idsX.max()) sigmaSlitX[itype][i]=check_and_get(idsX, mvelX,slitXvz); if(idsY.max()) sigmaSlitY[itype][i]=check_and_get(idsY, mvelY,slitYvz); } } for(size_t i=0;i<6;i++) { smooth(sigmaSlitX[i]); smooth(sigmaSlitY[i]); } //save(rrslw, sigmaSlitX, m_fname+".slitX"); //save(rrslw, sigmaSlitY, m_fname+".slitY"); }; /////////////////////////////// double check_and_get(valarray<bool> &ids_, double mvel/*meanvalue of the velociti in the whole region*/, valarray<double> &vz_) { double sig=0.0; if(ids_.max()) { valarray<double> d=vz_[ids_]; d-=mvel; d=pow(d,2.0); sig = sqrt(d.sum()/(double)d.size()); } return sig; } }; #endif
[ "arm2arm@06a51f3c-712f-11de-a0a7-fb2681086dbc" ]
[ [ [ 1, 391 ] ] ]